Algorithm Search⌘K

Algorithmcore

Baraff-Witkin implicit cloth

Also called large steps in cloth simulation.

Simulate triangle cloth with one linearized implicit Euler step per time step, solved by a conjugate gradient method that filters constraints, with energies built from triangle conditions.

Time
Θ(n + t + e) assembly · iterationΘ(k (n + t + e)) step
Space
Θ(n + t + e) matrix
Where
e = the number of interior edges; k = the number of conjugate gradient iterations in a step; n = the number of particles; t = the number of triangles
Properties
constraints exactdeterministicnot exactimplicit
Origin
David Baraff, Andrew Witkin, 1998

Baraff and Witkin (1998) made cloth simulation fast by taking large steps. Cloth resists stretch much more than it resists bending, so the equations of motion are stiff, and an explicit integrator needs many tiny steps per frame. Their simulator takes one step of backward Euler, linearized at the start of the step, so each step is one sparse linear solve. The forces come from simple conditions on each triangle and edge: stretch, shear and bend. The linear system is solved by a conjugate gradient method that also keeps particle constraints exactly, for example a particle that is pinned or that slides on a floor.

In plain words

Cloth is easy to bend and very hard to stretch. If you simulate it by small pushes forward in time, the hard-to-stretch part forces you to take thousands of tiny steps every second, or the cloth explodes.

Baraff and Witkin instead ask, at each step: "what velocities at the end of the step are consistent with the forces at the end of the step?" They answer an approximate form of this question with one large but sparse system of equations, so the step can be as long as a frame of animation.

The forces come from three simple measurements on the cloth: how much each triangle is stretched, how much it is sheared, and how much two neighbouring triangles are folded. A particle that is held, or that rests on a surface, is handled inside the solver so that it stays exactly where it must.

The problem

Given a triangle mesh with rest coordinates (u,v)(u, v) for each vertex, positions x0\mathbf x_0, velocities v0\mathbf v_0, masses MM, external forces and a step hh, find v1\mathbf v_1 and x1\mathbf x_1 of one backward Euler step,

v1=v0+hM−1f(x1,v1),x1=x0+hv1,\mathbf v_1 = \mathbf v_0 + h M^{-1} \mathbf f(\mathbf x_1, \mathbf v_1), \qquad \mathbf x_1 = \mathbf x_0 + h \mathbf v_1,

with some particles constrained: the change Δvi=v1−v0\Delta \mathbf v_i = \mathbf v_1 - \mathbf v_0 of particle ii has a given value zi\mathbf z_i in zero, one, two or three directions. This is one way to solve cloth simulation.

The algorithm

Masses (Section 2.2). Each triangle gives one third of its mass to each of its vertices.

Conditions and forces (Section 4). A condition C(x)C(\mathbf x), zero at rest, with stiffness kk has the energy k2C2\frac k2 C^2, the force fi=−k C ∂C/∂xi\mathbf f_i = -k\, C\, \partial C/\partial \mathbf x_i (equation (7)) and the Jacobian Kij=−k(∂C∂xi∂C∂xj ⁣⊤+∂2C∂xi∂xjC)K_{ij} = -k(\frac{\partial C}{\partial \mathbf x_i}\frac{\partial C}{\partial \mathbf x_j}^{\!\top} + \frac{\partial^2 C}{\partial \mathbf x_i \partial \mathbf x_j} C) (equation (8)). For a triangle, the map from (u,v)(u, v) to the world has the derivatives (wu wv)=(Δx1 Δx2)(Δu1Δu2Δv1Δv2)−1(\mathbf w_u\ \mathbf w_v) = (\Delta \mathbf x_1\ \Delta \mathbf x_2)\begin{pmatrix} \Delta u_1 & \Delta u_2 \\ \Delta v_1 & \Delta v_2 \end{pmatrix}^{-1} (equation (9)), which are linear in the three vertex positions. With aa the rest area of the triangle:

  • stretch, C=a (∣wu∣−bu, ∣wv∣−bv)C = a\,(|\mathbf w_u| - b_u,\ |\mathbf w_v| - b_v), two conditions, with bu=bv=1b_u = b_v = 1 for no stretch at rest (equation (10));
  • shear, C=a wu⋅wvC = a\, \mathbf w_u \cdot \mathbf w_v;
  • bend, C=θC = \theta, the angle between the normals of the two triangles at an interior edge.

Damping (Section 4.5). Each condition also has a damping force di=−kd C˙ ∂C/∂xi\mathbf d_i = -k_d\, \dot C\, \partial C/\partial \mathbf x_i (equation (11)), with C˙\dot C the rate of change of CC.

The step (Sections 3 and 5). Linearize the forces at the start of the step. Then backward Euler becomes one linear system A Δv=bA\, \Delta \mathbf v = \mathbf b (equations (15) and (16)), which is solved by modified-pcg. The filter SiS_i of a particle removes the constrained directions: Si=IS_i = I for a free particle, I−pp⊤I - \mathbf p \mathbf p^\top for a particle that cannot move along p\mathbf p, I−pp⊤−qq⊤I - \mathbf p \mathbf p^\top - \mathbf q \mathbf q^\top for two such directions, and 00 for a pinned particle (equation (13)). filter(a)\text{filter}(\mathbf a) applies SiS_i to each block ai\mathbf a_i. QQ is the diagonal matrix with the entries 1/Aii1/A_{ii}.

  1. BARAFF-WITKIN-STEP(x0, v0, h, {(S_i, z_i)})
  2. 1f, df/dx, df/dv <- sums over the stretch, shear and bend conditions, with damping
  3. 2A <- M - h df/dv - h^2 df/dx ; b <- h (f + f_ext + h (df/dx) v0)
  4. 3dv <- z ▷ constrained parts are right from the start
  5. 4delta0 <- filter(b)^T Q filter(b) ; r <- filter(b - A dv)
  6. 5c <- filter(Q r) ; delta_new <- r^T c
  7. 6while delta_new > eps^2 delta0:
  8. 7q <- filter(A c) ; alpha <- delta_new / (c^T q)
  9. 8dv <- dv + alpha c ; r <- r - alpha q
  10. 9s <- Q r ; delta_old <- delta_new ; delta_new <- r^T s
  11. 10c <- filter(s + (delta_new / delta_old) c)
  12. 11v1 <- v0 + dv ; x1 <- x0 + h v1

Lines L3 to L10 are the procedure modified-pcg of Section 5.3. Without constraints it is the standard preconditioned conjugate gradient method. The filter keeps every search direction c\mathbf c in the free directions, so the constrained components of Δv\Delta \mathbf v stay equal to z\mathbf z at every iteration.

Damping Jacobian (Section 4.5). ∂d/∂x\partial \mathbf d / \partial \mathbf x has a term ∂C∂xi∂C˙∂xj ⁣⊤\frac{\partial C}{\partial \mathbf x_i} \frac{\partial \dot C}{\partial \mathbf x_j}^{\!\top} that is not symmetric. The paper drops it so that AA stays symmetric; the code does the same. The paper says that dropping all of equation (12) causes serious problems.

Choices of this code. The bend Jacobian keeps only −k ∂θ∂xi∂θ∂xj ⁣⊤-k\,\frac{\partial \theta}{\partial \mathbf x_i}\frac{\partial \theta}{\partial \mathbf x_j}^{\!\top}. That is exact where θ=0\theta = 0 and keeps the bend part of AA positive semidefinite. The bend force itself is exact, with the angle gradient of Bridson, Marino and Fedkiw. The paper writes Pii=1/AiiP_{ii} = 1/A_{ii} and then uses PP in δ0\delta_0 but P−1P^{-1} in P−1rP^{-1}\mathbf r, which read literally puts the two in different norms. The code uses the one diagonal matrix QQ in all three places, which is the standard diagonal preconditioner. The code has no collisions, and the caller gives the constraints.

Example

A particle on a floor, by hand. One particle of 11 kg rests on a floor with the normal p=(0,1,0)\mathbf p = (0, 1, 0), so S=I−pp⊤S = I - \mathbf p \mathbf p^\top and z=0z = 0. It feels gravity and a side force of 55 N, and h=0.01h = 0.01 s. With no elastic forces, A=M=IA = M = I and b=hf=(0.05,−0.0981,0)\mathbf b = h \mathbf f = (0.05, -0.0981, 0). Line L4 gives r=filter(b)=(0.05,0,0)\mathbf r = \text{filter}(\mathbf b) = (0.05, 0, 0), line L5 gives c=(0.05,0,0)\mathbf c = (0.05, 0, 0) and δnew=0.0025\delta_{\text{new}} = 0.0025. One iteration gives α=1\alpha = 1, Δv=(0.05,0,0)\Delta \mathbf v = (0.05, 0, 0) and r=0\mathbf r = 0, so the loop stops. The particle slides sideways and does not sink. The residual AΔv−b=(0,0.0981,0)A\Delta \mathbf v - \mathbf b = (0, 0.0981, 0) is hh times the force that the floor must supply, 9.819.81 N upward. Section 5.3 of the paper uses this residual to find contact forces.

A stiff hanging sheet, measured. A 5 by 5 sheet with spacing 0.10.1 m (32 triangles, 40 interior edges), density 0.40.4 kg/m², stretch stiffness 10610^6, shear stiffness 10510^5 and bend stiffness 10−410^{-4}, no damping, hangs from two pinned corners with h=1/30h = 1/30 s and ε=10−6\varepsilon = 10^{-6}. The solve has 69 unknowns.

step 1 2 5 10 20
modified-pcg iterations 42 43 39 42 43
largest speed (m/s) 0.009 4.2e-4 3.7e-6 4.6e-10 4.1e-15

The sheet comes to rest in about ten steps although there is no damping force: this is the numerical damping of backward Euler, so the step is stable, and stable is not accurate. Explicit Euler with the same forces and step gives the elastic energies 0.330.33, 3.13.1 and 1.4×1091.4 \times 10^9 J after steps 2, 3 and 4.

Timings, measured by the authors. Baraff and Witkin (Section 8) report 0.230.23, 0.460.46, 2.232.23 and 10.310.3 seconds per frame for cloths of 500, 899, 2,602 and 7,359 particles on an SGI Octane R10000 at 195 MHz, slightly better than O(n1.5)O(n^{1.5}). They also report 50 to 100 iterations for a 6,000 node cloth (Section 1.1) and usually two to three steps per frame at 30 Hz.

Correctness

The claims are proved in proofs/correctness.md.

  1. Forces (proved). Each condition force is minus the gradient of k2C2\frac k2 C^2, and KK is symmetric. The stretch and shear Jacobians of the code are exact; the bend Jacobian is exact where θ=0\theta = 0.
  2. Rest and rigid motion (proved). All internal forces are zero at rest and after a rigid motion, and they sum to zero.
  3. modified-pcg (proved). If AA is symmetric positive definite, modified-pcg is the standard preconditioned conjugate gradient method on the free directions. The constrained components equal z\mathbf z after any number of iterations, and in exact arithmetic it reaches the solution of equation (14) in at most as many iterations as free directions.
  4. Momentum (proved). Without constraints, the change of linear momentum differs from h∑fexth \sum \mathbf f_{\text{ext}} by the sum of the residual blocks, so an exact solve keeps momentum exactly.
  5. Positive definiteness (model). The paper calls AA positive definite. That is true near rest, but compressed or sheared triangles add terms of either sign, so it is an assumption, not a theorem.
  6. Large steps (measured). The step is one Newton iteration of backward Euler. For nonlinear cloth this page claims no stability theorem; the bounded run above and in the tests is a measurement.

The tests check the bend gradient and the forces against central differences, zero force at rest and after a rotation, the stretch and shear Jacobians and their symmetry, the bend Jacobian at θ=0\theta = 0, both damping Jacobians, the dissipation of damping, modified-pcg against a dense solve with and without constraints, the constrained components after 0, 1, 2 and 5 iterations, the momentum to 10−1010^{-10} relative, and the stiff sheet against explicit Euler.

Proof: The condition forces are exact gradients, modified-pcg is preconditioned CG on the free directions, and the step keeps momentum up to the residualfull

We use the notation of the page. The state has nn particles in 3D. A condition C(x)C(\mathbf x) with stiffness kk has the energy EC=k2C2E_C = \frac k2 C^2 (Baraff and Witkin 1998, Section 4.1). x\mathbf x, v\mathbf v and the other state vectors have 3n3n entries, in blocks of 3 per particle.

Forces and Jacobians

Lemma 1 (equations (7) and (8)). fi=−∂EC/∂xi=−k C ∂C/∂xi\mathbf f_i = -\partial E_C / \partial \mathbf x_i = -k\, C\, \partial C/\partial \mathbf x_i, and Kij=∂fi/∂xj=−k(∂C∂xi∂C∂xj ⁣⊤+∂2C∂xi∂xjC)K_{ij} = \partial \mathbf f_i / \partial \mathbf x_j = -k \big( \frac{\partial C}{\partial \mathbf x_i} \frac{\partial C}{\partial \mathbf x_j}^{\!\top} + \frac{\partial^2 C}{\partial \mathbf x_i \partial \mathbf x_j} C \big). The matrix KK is symmetric.

Proof. The chain rule for k2C2\frac k2 C^2 gives the force, and the product rule gives KK. Both terms of KijK_{ij} change into those of Kji⊤K_{ji}^\top when ii and jj change places, because second derivatives commute. □\square

The stretch condition. For a triangle with vertices x0,x1,x2\mathbf x_0, \mathbf x_1, \mathbf x_2 and rest coordinates (ui,vi)(u_i, v_i), equation (9) of the paper is (wu wv)=(Δx1 Δx2)D−1(\mathbf w_u\ \mathbf w_v) = (\Delta \mathbf x_1\ \Delta \mathbf x_2) D^{-1} with D=(Δu1Δu2Δv1Δv2)D = \begin{pmatrix} \Delta u_1 & \Delta u_2 \\ \Delta v_1 & \Delta v_2 \end{pmatrix}. With det⁡D=Δu1Δv2−Δu2Δv1\det D = \Delta u_1 \Delta v_2 - \Delta u_2 \Delta v_1, this is wu=∑iciuxi\mathbf w_u = \sum_i c^u_i \mathbf x_i and wv=∑icivxi\mathbf w_v = \sum_i c^v_i \mathbf x_i, with c1u=Δv2/det⁡Dc^u_1 = \Delta v_2/\det D, c2u=−Δv1/det⁡Dc^u_2 = -\Delta v_1/\det D, c1v=−Δu2/det⁡Dc^v_1 = -\Delta u_2/\det D, c2v=Δu1/det⁡Dc^v_2 = \Delta u_1/\det D and c0=−c1−c2c_0 = -c_1 - c_2 for both. The coefficients do not depend on x\mathbf x, so ∂wu/∂xi=ciuI\partial \mathbf w_u / \partial \mathbf x_i = c^u_i I. For Cu=a(∣wu∣−bu)C_u = a(|\mathbf w_u| - b_u), with w^=wu/∣wu∣\hat{\mathbf w} = \mathbf w_u / |\mathbf w_u|,

∂Cu∂xi=a ciu w^,∂2Cu∂xi∂xj=a ciucju∣wu∣(I−w^w^⊤),\frac{\partial C_u}{\partial \mathbf x_i} = a\, c^u_i\, \hat{\mathbf w}, \qquad \frac{\partial^2 C_u}{\partial \mathbf x_i \partial \mathbf x_j} = \frac{a\, c^u_i c^u_j}{|\mathbf w_u|} \big(I - \hat{\mathbf w} \hat{\mathbf w}^\top\big),

because the derivative of w↦w/∣w∣\mathbf w \mapsto \mathbf w/|\mathbf w| is (I−w^w^⊤)/∣w∣(I - \hat{\mathbf w}\hat{\mathbf w}^\top)/|\mathbf w|. The same holds for CvC_v with cvc^v.

The shear condition. For C=a wu⋅wvC = a\, \mathbf w_u \cdot \mathbf w_v (Section 4.3), ∂C/∂xi=a(ciuwv+civwu)\partial C / \partial \mathbf x_i = a (c^u_i \mathbf w_v + c^v_i \mathbf w_u) and ∂2C/∂xi∂xj=a(ciucjv+civcju)I\partial^2 C / \partial \mathbf x_i \partial \mathbf x_j = a (c^u_i c^v_j + c^v_i c^u_j) I.

The bend condition. C=θC = \theta, the signed angle of the code. Its gradient is the formula of Bridson, Marino and Fedkiw; this note does not prove it, and the tests check it against central differences at ten random configurations. The code uses only the term −k∂C∂xi∂C∂xj ⁣⊤-k \frac{\partial C}{\partial \mathbf x_i}\frac{\partial C}{\partial \mathbf x_j}^{\!\top} of the bend Jacobian. The dropped term has the factor C=θC = \theta, so it is zero at every configuration with θ=0\theta = 0, and the Jacobian is exact there.

Lemma 2 (invariance). Every condition of the page has ∑i∂C/∂xi=0\sum_i \partial C/\partial \mathbf x_i = 0 and ∑i∂2C/∂xi∂xj=0\sum_i \partial^2 C / \partial \mathbf x_i \partial \mathbf x_j = 0 for each jj. Hence the internal forces sum to zero and every block column of KK and of the damping Jacobians sums to zero. Every condition is zero at the rest state (xi=(ui,−vi,0)\mathbf x_i = (u_i, -v_i, 0), bu=bv=1b_u = b_v = 1) and keeps its value under a rigid motion, so all internal forces are zero there.

Proof. A translation of all particles by t\mathbf t does not change wu\mathbf w_u, wv\mathbf w_v (the coefficients sum to zero) or θ\theta. So C(x+1⊗t)=C(x)C(\mathbf x + \mathbf 1 \otimes \mathbf t) = C(\mathbf x) for all t\mathbf t, and the derivative in t\mathbf t is ∑i∂C/∂xi=0\sum_i \partial C / \partial \mathbf x_i = 0. Differentiating this identity in xj\mathbf x_j gives the second claim. A rotation RR maps wu,wv\mathbf w_u, \mathbf w_v to Rwu,RwvR\mathbf w_u, R \mathbf w_v and keeps lengths, dot products and the angle between normals. At rest, wu=(1,0,0)\mathbf w_u = (1, 0, 0) and wv=(0,−1,0)\mathbf w_v = (0, -1, 0), so the stretch and shear conditions are zero, and the sheet is flat, so θ=0\theta = 0. Each force is a multiple of CC or of C˙\dot C, and C˙=0\dot C = 0 when v=0\mathbf v = 0. □\square

Damping

Lemma 3. For di=−kd C˙ ∂C/∂xi\mathbf d_i = -k_d\, \dot C\, \partial C / \partial \mathbf x_i with C˙=∑j∂C∂xj⋅vj\dot C = \sum_j \frac{\partial C}{\partial \mathbf x_j} \cdot \mathbf v_j (equation (11)): (a) ∂di/∂vj=−kd∂C∂xi∂C∂xj ⁣⊤\partial \mathbf d_i / \partial \mathbf v_j = -k_d \frac{\partial C}{\partial \mathbf x_i} \frac{\partial C}{\partial \mathbf x_j}^{\!\top}, which is symmetric; (b) ∂di/∂xj=−kd(∂C∂xi∂C˙∂xj ⁣⊤+∂2C∂xi∂xjC˙)\partial \mathbf d_i / \partial \mathbf x_j = -k_d \big( \frac{\partial C}{\partial \mathbf x_i} \frac{\partial \dot C}{\partial \mathbf x_j}^{\!\top} + \frac{\partial^2 C}{\partial \mathbf x_i \partial \mathbf x_j} \dot C \big) (equation (12)), and the code keeps only the second term, as the paper does; (c) ∑idi⋅vi=−kdC˙2≤0\sum_i \mathbf d_i \cdot \mathbf v_i = -k_d \dot C^2 \le 0.

Proof. C˙\dot C is linear in v\mathbf v with the gradient ∂C/∂xj\partial C / \partial \mathbf x_j, which gives (a). The product rule gives (b). For (c), ∑idi⋅vi=−kdC˙∑i∂C∂xi⋅vi=−kdC˙2\sum_i \mathbf d_i \cdot \mathbf v_i = -k_d \dot C \sum_i \frac{\partial C}{\partial \mathbf x_i} \cdot \mathbf v_i = -k_d \dot C^2. □\square

The term that the code drops makes ∂d/∂x\partial \mathbf d / \partial \mathbf x asymmetric. Without it the matrix AA below is symmetric. The paper calls the omission "not physically justifiable" and reports no ill effects; this is a model choice, not a theorem. The test checks that the code's ∂d/∂x\partial \mathbf d / \partial \mathbf x plus the dropped term equals central differences of d\mathbf d.

The linear system

Linearize f(x0+Δx,v0+Δv)\mathbf f(\mathbf x_0 + \Delta \mathbf x, \mathbf v_0 + \Delta \mathbf v) at (x0,v0)(\mathbf x_0, \mathbf v_0) and put Δx=h(v0+Δv)\Delta \mathbf x = h(\mathbf v_0 + \Delta \mathbf v) into backward Euler MΔv=hf(x1,v1)M \Delta \mathbf v = h \mathbf f(\mathbf x_1, \mathbf v_1). This gives equation (15):

A Δv=b,A=M−h∂f∂v−h2∂f∂x,b=h(f0+h∂f∂xv0).A\, \Delta \mathbf v = \mathbf b, \qquad A = M - h \frac{\partial \mathbf f}{\partial \mathbf v} - h^2 \frac{\partial \mathbf f}{\partial \mathbf x}, \qquad \mathbf b = h\Big(\mathbf f_0 + h \frac{\partial \mathbf f}{\partial \mathbf x} \mathbf v_0\Big).

By Lemmas 1 and 3, AA is symmetric. The paper calls AA positive definite. That holds when −∂f/∂x-\partial \mathbf f / \partial \mathbf x is positive semidefinite, for example near the rest state, but a compressed stretch condition or a sheared triangle adds terms −k ∂2C C-k\, \partial^2 C\, C of either sign, and a large hh can then make AA indefinite. This note assumes that AA is positive definite, as the paper does (model assumption).

modified-pcg

Let SiS_i be the filter of particle ii (equation (13)): II, I−pp⊤I - \mathbf p \mathbf p^\top, I−pp⊤−qq⊤I - \mathbf p \mathbf p^\top - \mathbf q \mathbf q^\top with orthonormal p,q\mathbf p, \mathbf q, or 00. Each SiS_i is an orthogonal projection. Let WW be the block diagonal matrix of the SiS_i, so filter(a)=Wa\text{filter}(\mathbf a) = W \mathbf a. Choose a matrix BB with orthonormal columns that span the range of WW; then W=BB⊤W = B B^\top and B⊤B=IB^\top B = I. The value ziz_i lies in the range of I−SiI - S_i, so Wz=0W \mathbf z = 0.

The code applies one diagonal matrix QQ, with Qii=1/AiiQ_{ii} = 1/A_{ii} for each of the 3n3n components, wherever the paper writes PP or P−1P^{-1}. The paper defines Pii=1/AiiP_{ii} = 1/A_{ii}, uses PP in δ0\delta_0 and P−1P^{-1} in the products P−1rP^{-1}\mathbf r; read literally, δ0\delta_0 and δnew\delta_{\text{new}} would then be in different norms. Using QQ in all three places is the standard preconditioned conjugate gradient method with the preconditioner diag(A)\text{diag}(A). The value δ0\delta_0 only sets the scale of the stopping test, so this choice does not change the iterates.

Theorem 4. Let A^=B⊤AB\hat A = B^\top A B, b^=B⊤(b−Az)\hat{\mathbf b} = B^\top (\mathbf b - A \mathbf z) and Q^=B⊤QB\hat Q = B^\top Q B. If AA is symmetric positive definite, then A^\hat A and Q^\hat Q are symmetric positive definite, and the iterates of modified-pcg are Δvk=z+Bαk\Delta \mathbf v_k = \mathbf z + B \boldsymbol\alpha_k, rk=Bρk\mathbf r_k = B \boldsymbol\rho_k and ck=Bγk\mathbf c_k = B \boldsymbol\gamma_k, where αk\boldsymbol\alpha_k, ρk\boldsymbol\rho_k and γk\boldsymbol\gamma_k are the iterates of the standard preconditioned conjugate gradient method for A^α=b^\hat A \boldsymbol\alpha = \hat{\mathbf b} with the preconditioner Q^\hat Q, started at α0=0\boldsymbol\alpha_0 = 0. The scalars δ\delta and α\alpha of the two methods are equal.

Proof. A^\hat A is symmetric, and for α≠0\boldsymbol\alpha \ne 0, Bα≠0B \boldsymbol\alpha \ne 0, so α⊤A^α=(Bα)⊤A(Bα)>0\boldsymbol\alpha^\top \hat A \boldsymbol\alpha = (B\boldsymbol\alpha)^\top A (B\boldsymbol\alpha) > 0. The same argument works for Q^\hat Q, since QQ is diagonal with positive entries (Aii>0A_{ii} > 0 for a positive definite AA). Induction on kk. At the start (lines L3 to L5), Δv0=z\Delta \mathbf v_0 = \mathbf z, r0=W(b−Az)=Bb^\mathbf r_0 = W(\mathbf b - A \mathbf z) = B \hat{\mathbf b}, so ρ0=b^−A^⋅0\boldsymbol\rho_0 = \hat{\mathbf b} - \hat A \cdot 0. Then c0=WQr0=B(B⊤QB)ρ0=BQ^ρ0\mathbf c_0 = W Q \mathbf r_0 = B (B^\top Q B) \boldsymbol\rho_0 = B \hat Q \boldsymbol\rho_0, and δnew=r0⊤c0=ρ0⊤Q^ρ0\delta_{\text{new}} = \mathbf r_0^\top \mathbf c_0 = \boldsymbol\rho_0^\top \hat Q \boldsymbol\rho_0, using B⊤B=IB^\top B = I. At an iteration (lines L7 to L10), q=WAc=B(B⊤AB)γ=BA^γ\mathbf q = W A \mathbf c = B (B^\top A B) \boldsymbol\gamma = B \hat A \boldsymbol\gamma, and c⊤q=γ⊤A^γ\mathbf c^\top \mathbf q = \boldsymbol\gamma^\top \hat A \boldsymbol\gamma, so α\alpha is the same. The updates of Δv\Delta \mathbf v and r\mathbf r are the images under BB of the updates of α\boldsymbol\alpha and ρ\boldsymbol\rho. The vector s=Qr\mathbf s = Q \mathbf r is not filtered, but it enters only through r⊤s=ρ⊤Q^ρ\mathbf r^\top \mathbf s = \boldsymbol\rho^\top \hat Q \boldsymbol\rho and through c=W(s+βc)=B(Q^ρ+βγ)\mathbf c = W(\mathbf s + \beta \mathbf c) = B(\hat Q \boldsymbol\rho + \beta \boldsymbol\gamma). These are the formulas of the standard method. □\square

Corollary 5. (a) After any number of iterations, (I−Si)Δvi=zi(I - S_i) \Delta \mathbf v_i = \mathbf z_i for every constrained particle. (b) In exact arithmetic, the method stops after at most dim⁡(range W)\dim(\text{range } W) iterations with the unique solution of W(AΔv−b)=0W(A \Delta \mathbf v - \mathbf b) = 0 with (I−W)Δv=z(I - W)\Delta \mathbf v = \mathbf z, which is equation (14) of the paper. (c) Without constraints this is the standard preconditioned conjugate gradient method for AΔv=bA \Delta \mathbf v = \mathbf b.

Proof. (a) (I−W)(z+Bα)=z(I - W)(\mathbf z + B\boldsymbol\alpha) = \mathbf z, because Wz=0W\mathbf z = 0 and WB=BW B = B. (b) The standard method on an SPD system of dimension mm reaches the exact solution in at most mm steps, and A^α=b^\hat A \boldsymbol\alpha = \hat{\mathbf b} is B⊤(AΔv−b)=0B^\top (A\Delta \mathbf v - \mathbf b) = 0, which is W(AΔv−b)=0W(A \Delta \mathbf v - \mathbf b) = 0. (c) Take W=IW = I, B=IB = I and z=0\mathbf z = 0. □\square

The tests check (a) after 0, 1, 2 and 5 iterations, and the final Δv\Delta \mathbf v against a dense solve of the reduced system A^α=b^\hat A \boldsymbol\alpha = \hat{\mathbf b}, with two pinned particles and two particles on planes.

Momentum

Theorem 6. With no constraints, ∑imiΔvi−h∑ifext,i=∑i(AΔv−b)i\sum_i m_i \Delta \mathbf v_i - h \sum_i \mathbf f_{\text{ext}, i} = \sum_i (A \Delta \mathbf v - \mathbf b)_i, the sum of the blocks of the residual. So the exact solve changes the linear momentum by h∑fexth \sum \mathbf f_{\text{ext}} exactly, and an inexact solve is off by the sum of its residual blocks.

Proof. By Lemma 2, every block column of ∂f/∂x\partial \mathbf f / \partial \mathbf x and ∂f/∂v\partial \mathbf f / \partial \mathbf v sums to zero, so ∑i(AΔv)i=∑imiΔvi\sum_i (A \Delta \mathbf v)_i = \sum_i m_i \Delta \mathbf v_i. Also by Lemma 2, ∑i(f0)i=∑ifext,i\sum_i (\mathbf f_0)_i = \sum_i \mathbf f_{\text{ext}, i} and ∑i(∂f∂xv0)i=0\sum_i \big(\frac{\partial \mathbf f}{\partial \mathbf x} \mathbf v_0\big)_i = 0, so ∑ibi=h∑ifext,i\sum_i \mathbf b_i = h \sum_i \mathbf f_{\text{ext}, i}. Subtract. □\square

The test runs five steps with the tolerance ε=10−14\varepsilon = 10^{-14} and checks the momentum to 10−1010^{-10} relative.

Stable is not accurate

For a linear force f=−Kx\mathbf f = -K\mathbf x, the linearization is exact, and one step is backward Euler. For one mass on one spring, the energy is then multiplied by 1/(1+ω2h2)1/(1 + \omega^2 h^2) at each step (the same computation as in the proof of the fast mass-spring page). So the step damps stiff motion strongly. For the nonlinear conditions of cloth, the page claims no stability theorem: the step is one Newton iteration of backward Euler, and the bounded run at a large step is a measurement.

Complexity

Each condition touches 3 or 4 particles, so assembling the forces and AA costs Θ(n+t+e)\Theta(n + t + e), and AA has Θ(n+t+e)\Theta(n + t + e) nonzero 3×33 \times 3 blocks. One iteration of modified-pcg is one product with AA, a few vector operations and the filter, so it costs Θ(n+t+e)\Theta(n + t + e). A step with kk iterations costs Θ(k(n+t+e))\Theta(k (n + t + e)). For a mesh, tt and ee are Θ(n)\Theta(n). The number kk depends on the conditioning of AA; Baraff and Witkin measured a total cost close to O(n1.5)O(n^{1.5}) per frame, which they relate to the usual behaviour of the conjugate gradient method on such systems.

Properties

  • Large steps. In practice the step can be close to a frame long, because stiff stretch does not limit hh as it does for explicit methods (measured, not proved for the nonlinear case).
  • Exact constraints. A pinned or sliding particle has its constrained velocity change exactly, whatever the number of iterations (proved).
  • Damped. Backward Euler removes energy from fast motion, so large steps look calm. This is numerical damping, not a material property.
  • Not exact. One linearized step is not the solution of the nonlinear backward Euler equations, and the conjugate gradient method stops at a tolerance.
  • Anisotropic material. The stretch condition measures warp and weft separately through bub_u and bvb_v, so the cloth can be stiffer in one direction.

Variants and improvements

  • Adaptive step size (Section 7). The simulator rejects a step when the stretch changes too much and retries with a smaller step.
  • Collisions (Section 6). Cloth-solid contact becomes a constraint in the filter, with z\mathbf z chosen to push the particle out. Cloth-cloth contact uses stiff damped springs.
  • Other energies. Later work replaces the conditions by finite elements, such as corotational FEM or the St. Venant-Kirchhoff model, and the bend condition by discrete shells or the quadratic bending model.
  • Full Newton. Several Newton iterations with a line search solve the nonlinear step, as in optimization time integration.
  • Constant matrix. Fast mass-spring and projective dynamics change the splitting so that the matrix stays the same over all steps.
  • Robust collisions. Robust cloth collision handles cloth-cloth contact after each step, without stiff springs in the solve.

When to use it

Use it for cloth and other thin sheets where stretch is much stiffer than bending and steps of a frame or so are wanted: film and offline animation, and interactive tools with a few thousand particles.

Do not use it when you need accurate dynamics of fast motion with large steps, because backward Euler damps it. If the matrix can become indefinite, as under strong compression, use a Newton method with a definiteness fix. For real-time use with fixed topology, a constant-matrix method such as fast mass-spring can be cheaper.

Pitfalls

  • Indefinite A. Compression of stretch conditions and shear add terms of either sign to AA. With a large step the conjugate gradient method can fail. A common fix is to drop or clamp these terms.
  • Stopping test. δ0\delta_0 comes from filter(b)\text{filter}(\mathbf b). If it is zero, the loop does not run, which is right only when the free part of b\mathbf b is zero.
  • Constraint values. Each zi\mathbf z_i must lie in the constrained directions, the range of I−SiI - S_i. A component in the free directions is changed by the iterations.
  • Dropping too much. Dropping the whole damping Jacobian ∂d/∂x\partial \mathbf d/\partial \mathbf x is not the same as dropping its asymmetric term; the paper reports serious problems with it.
  • Area scaling. The stretch and shear conditions are multiplied by the rest area aa, so the energy scales with a2a^2, and stiffness values do not carry over between meshes of different resolution.

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
baraff_witkin_cloth.py 292 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/baraff-witkin-cloth/. The authors are listed in prov/7F3XVP.jsonl.

"""Large steps in cloth simulation (Baraff and Witkin 1998), in 3D.

The cloth is a triangle mesh with rest coordinates (u, v) for each vertex.
Each triangle has a stretch condition C = a (|w_u| - b_u, |w_v| - b_v) and a
shear condition C = a w_u . w_v, where (w_u w_v) = (dx1 dx2) [[du1, du2], [dv1, dv2]]^-1
and a is the rest area. Each interior edge has a bend condition C = theta, the
signed angle between the normals of its two triangles. A condition with
stiffness k has the energy k/2 C^2, the force f_i = -k dC/dx_i C and the
force Jacobian K_ij = -k (dC/dx_i dC/dx_j^T + d2C/dx_i dx_j C)
(equations (7) and (8) of the paper). The damping force is
d_i = -k_d dC/dx_i Cdot (equation (11)).

One step solves the linearized backward Euler system
(M - h df/dv - h^2 df/dx) dv = h (f0 + h df/dx v0) (equation (15)) with the
modified preconditioned conjugate gradient method of Section 5.3, which keeps
the constrained velocity components of each particle at the values z_i.

Simplifications of this code, not of the paper:
- The bend Jacobian keeps only the term -k dC/dx_i dC/dx_j^T (Gauss-Newton).
  It is exact where theta = 0. The bend force itself is exact.
- No collisions. Constraints are given by the caller as {i: (S_i, z_i)}.
"""

import math

from anim import add, cross, dot, norm, scale, sub

GRAVITY = (0.0, -9.81, 0.0)
IDENTITY = ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))
ZERO3 = ((0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0))


# ---------------------------------------------------------------- 3 by 3 blocks


def outer(a, b, s=1.0):
    return [[s * a[r] * b[c] for c in range(3)] for r in range(3)]


def block_vec(m, x):
    return (m[0][0] * x[0] + m[0][1] * x[1] + m[0][2] * x[2],
            m[1][0] * x[0] + m[1][1] * x[1] + m[1][2] * x[2],
            m[2][0] * x[0] + m[2][1] * x[1] + m[2][2] * x[2])


def add_block(mat, i, j, blk, s=1.0):
    """mat[i][j] += s blk for a sparse block matrix stored as {i: {j: 3 by 3}}."""
    row = mat.setdefault(i, {})
    cur = row.get(j)
    if cur is None:
        cur = [[0.0] * 3 for _ in range(3)]
        row[j] = cur
    for r in range(3):
        for c in range(3):
            cur[r][c] += s * blk[r][c]


def sparse_matvec(mat, x):
    out = []
    for i in range(len(x)):
        s0 = s1 = s2 = 0.0
        for j, m in mat.get(i, {}).items():
            xj = x[j]
            s0 += m[0][0] * xj[0] + m[0][1] * xj[1] + m[0][2] * xj[2]
            s1 += m[1][0] * xj[0] + m[1][1] * xj[1] + m[1][2] * xj[2]
            s2 += m[2][0] * xj[0] + m[2][1] * xj[1] + m[2][2] * xj[2]
        out.append((s0, s1, s2))
    return out


def vdot(a, b):
    """Dot product of two lists of 3-vectors."""
    return sum(p[0] * q[0] + p[1] * q[1] + p[2] * q[2] for p, q in zip(a, b))


# ---------------------------------------------------------------- the cloth


class Cloth:
    def __init__(self, uv, triangles, density=1.0, k_stretch=1.0, k_shear=1.0, k_bend=0.0,
                 kd_stretch=0.0, kd_shear=0.0, kd_bend=0.0, b_u=1.0, b_v=1.0, gravity=GRAVITY):
        self.n = len(uv)
        self.triangles = [tuple(t) for t in triangles]
        self.k_stretch, self.k_shear, self.k_bend = k_stretch, k_shear, k_bend
        self.kd_stretch, self.kd_shear, self.kd_bend = kd_stretch, kd_shear, kd_bend
        self.b_u, self.b_v = b_u, b_v
        self.rest = []  # per triangle: (area, cu, cv) with w_u = sum cu_i x_i and w_v = sum cv_i x_i
        self.mass = [0.0] * self.n
        for t in self.triangles:
            p0, p1, p2 = (uv[i] for i in t)
            du1, dv1 = p1[0] - p0[0], p1[1] - p0[1]
            du2, dv2 = p2[0] - p0[0], p2[1] - p0[1]
            det = du1 * dv2 - du2 * dv1
            if det == 0.0:
                raise ValueError("degenerate triangle in (u, v)")
            cu1, cu2 = dv2 / det, -dv1 / det
            cv1, cv2 = -du2 / det, du1 / det
            area = 0.5 * abs(det)
            self.rest.append((area, (-cu1 - cu2, cu1, cu2), (-cv1 - cv2, cv1, cv2)))
            for i in t:
                self.mass[i] += density * area / 3.0  # one third of each incident triangle
        self.f_ext = [scale(gravity, m) for m in self.mass]
        # bend edges (x1, x2, x3, x4): x3 -> x4 is the shared edge as it runs in the first
        # triangle, x1 is opposite in that triangle and x2 is opposite in the other one
        first = {}
        self.edges = []
        for t in self.triangles:
            for e in range(3):
                a, b, c = t[e], t[(e + 1) % 3], t[(e + 2) % 3]
                if (b, a) in first:
                    self.edges.append((first.pop((b, a)), c, b, a))
                else:
                    first[(a, b)] = c

    # ------------------------------------------------------------ conditions

    def conditions(self, x):
        """Return (indices, C, gradients, s, B, k, k_d) for every scalar condition.

        The second derivative of C is d2C/dx_i dx_j = s[i][j] B, or s is None if
        the code does not use it.
        """
        out = []
        for t, (area, cu, cv) in zip(self.triangles, self.rest):
            xs = [x[i] for i in t]
            wu = add(add(scale(xs[0], cu[0]), scale(xs[1], cu[1])), scale(xs[2], cu[2]))
            wv = add(add(scale(xs[0], cv[0]), scale(xs[1], cv[1])), scale(xs[2], cv[2]))
            for w, coef, b in ((wu, cu, self.b_u), (wv, cv, self.b_v)):
                length = norm(w)
                wh = scale(w, 1.0 / length)
                grads = [scale(wh, area * coef[i]) for i in range(3)]
                s = [[area * coef[i] * coef[j] / length for j in range(3)] for i in range(3)]
                proj = [[(1.0 if r == c else 0.0) - wh[r] * wh[c] for c in range(3)] for r in range(3)]
                out.append((t, area * (length - b), grads, s, proj, self.k_stretch, self.kd_stretch))
            grads = [add(scale(wv, area * cu[i]), scale(wu, area * cv[i])) for i in range(3)]
            s = [[area * (cu[i] * cv[j] + cv[i] * cu[j]) for j in range(3)] for i in range(3)]
            out.append((t, area * dot(wu, wv), grads, s, IDENTITY, self.k_shear, self.kd_shear))
        if self.k_bend != 0.0 or self.kd_bend != 0.0:
            for e in self.edges:
                theta, grads = bend_angle(*(x[i] for i in e))
                out.append((e, theta, grads, None, None, self.k_bend, self.kd_bend))
        return out

    def energy(self, x):
        return sum(0.5 * k * c * c for _, c, _, _, _, k, _ in self.conditions(x))

    def forces(self, x, v):
        """Return (f, K, D): internal forces (elastic and damping), df/dx and df/dv as block matrices."""
        f = [[0.0, 0.0, 0.0] for _ in range(self.n)]
        kmat, dmat = {}, {}
        for idx, c, grads, s, base, k, kd in self.conditions(x):
            cdot = sum(dot(g, v[i]) for g, i in zip(grads, idx))
            for a, i in enumerate(idx):
                fi = f[i]
                coef = -k * c - kd * cdot  # equations (7) and (11)
                for r in range(3):
                    fi[r] += coef * grads[a][r]
                for b, j in enumerate(idx):
                    gg = outer(grads[a], grads[b])
                    add_block(kmat, i, j, gg, -k)  # equation (8), first term
                    if s is not None:
                        # equation (8), second term, and equation (12) without its asymmetric term
                        add_block(kmat, i, j, base, -(k * c + kd * cdot) * s[a][b])
                    if kd != 0.0:
                        add_block(dmat, i, j, gg, -kd)  # dd/dv
        return [tuple(fi) for fi in f], kmat, dmat

    # ------------------------------------------------------------ one step

    def system(self, x, v, h):
        """Return the block matrix A = M - h df/dv - h^2 df/dx and b = h (f0 + h df/dx v0)."""
        f, kmat, dmat = self.forces(x, v)  # @line L1
        amat = {}
        for i in range(self.n):
            add_block(amat, i, i, IDENTITY, self.mass[i])
        for src, w in ((kmat, -h * h), (dmat, -h)):
            for i, row in src.items():
                for j, blk in row.items():
                    add_block(amat, i, j, blk, w)
        kv = sparse_matvec(kmat, v)
        b = [scale(add(add(f[i], self.f_ext[i]), scale(kv[i], h)), h) for i in range(self.n)]  # @line L2
        return amat, b

    def step(self, x, v, h, constraints=None, eps=1e-8, max_iter=2000):
        """One step. Return (x, v, iterations of modified-pcg)."""
        amat, b = self.system(x, v, h)
        dv, iters = modified_pcg(amat, b, constraints or {}, eps, max_iter)
        new_v = [add(v[i], dv[i]) for i in range(self.n)]
        new_x = [add(x[i], scale(new_v[i], h)) for i in range(self.n)]  # @line L11
        return new_x, new_v, iters


def bend_angle(x1, x2, x3, x4):
    """Signed angle theta between the triangles (x3, x4, x1) and (x4, x3, x2), and d theta/dx.

    theta = atan2((n2 x n1) . e, n1 . n2) with the unit edge e from x3 to x4 and
    n1 = (x1 - x3) x (x1 - x4), n2 = (x2 - x4) x (x2 - x3). The gradient is the
    formula of Bridson, Marino and Fedkiw (2003). The tests check it against
    central differences of theta.
    """
    e = sub(x4, x3)
    n1 = cross(sub(x1, x3), sub(x1, x4))
    n2 = cross(sub(x2, x4), sub(x2, x3))
    le = norm(e)
    q1, q2 = dot(n1, n1), dot(n2, n2)
    theta = math.atan2(dot(cross(n2, n1), e) / le, dot(n1, n2))
    a1, a2 = scale(n1, 1.0 / q1), scale(n2, 1.0 / q2)
    u1 = scale(a1, le)
    u2 = scale(a2, le)
    u3 = add(scale(a1, dot(sub(x1, x4), e) / le), scale(a2, dot(sub(x2, x4), e) / le))
    u4 = scale(add(scale(a1, dot(sub(x1, x3), e) / le), scale(a2, dot(sub(x2, x3), e) / le)), -1.0)
    return theta, [u1, u2, u3, u4]


# ---------------------------------------------------------------- modified-pcg


def modified_pcg(amat, b, constraints, eps=1e-8, max_iter=2000):
    """Solve A dv = b with the components of particle i in the range of I - S_i fixed at z_i.

    constraints maps a particle i to (S_i, z_i), with S_i one of the filters of
    equation (13) and z_i in the range of I - S_i. The preconditioner is the
    diagonal of A, so applying P^-1 divides each component by A_ii.
    Return (dv, iterations).
    """
    n = len(b)

    def filt(a):
        return [block_vec(constraints[i][0], a[i]) if i in constraints else a[i] for i in range(n)]

    inv_diag = [tuple(1.0 / amat[i][i][r][r] for r in range(3)) for i in range(n)]

    def precond(a):
        return [(p[0] * q[0], p[1] * q[1], p[2] * q[2]) for p, q in zip(inv_diag, a)]

    dv = [tuple(constraints[i][1]) if i in constraints else (0.0, 0.0, 0.0) for i in range(n)]  # @line L3
    fb = filt(b)
    delta0 = vdot(fb, precond(fb))
    av = sparse_matvec(amat, dv)
    r = filt([sub(b[i], av[i]) for i in range(n)])  # @line L4
    c = filt(precond(r))
    delta_new = vdot(r, c)  # @line L5
    iters = 0
    while delta_new > eps * eps * delta0 and iters < max_iter:  # @line L6
        q = filt(sparse_matvec(amat, c))
        alpha = delta_new / vdot(c, q)  # @line L7
        dv = [add(dv[i], scale(c[i], alpha)) for i in range(n)]
        r = [sub(r[i], scale(q[i], alpha)) for i in range(n)]  # @line L8
        s = precond(r)
        delta_old, delta_new = delta_new, vdot(r, s)  # @line L9
        beta = delta_new / delta_old
        c = filt([add(s[i], scale(c[i], beta)) for i in range(n)])  # @line L10
        iters += 1
    return dv, iters


def constraint_force(amat, b, dv):
    """e = A dv - b. For a constrained particle, e_i is the force that kept the constraint (Section 5.3)."""
    av = sparse_matvec(amat, dv)
    return [sub(av[i], b[i]) for i in range(len(b))]


# ---------------------------------------------------------------- filters and meshes


def pin(z=(0.0, 0.0, 0.0)):
    """A filter that fixes all three components of dv at z."""
    return (ZERO3, tuple(z))


def plane(p, z_along):
    """A filter that fixes the dv component along the unit vector p at z_along."""
    s = [[(1.0 if r == c else 0.0) - p[r] * p[c] for c in range(3)] for r in range(3)]
    return (s, scale(p, z_along))


def grid(nx, ny, spacing):
    """A grid cloth in the plane z = 0. Return (uv, triangles, x) with x = (u, -v, 0)."""
    def idx(i, j):
        return j * nx + i

    uv = [(i * spacing, j * spacing) for j in range(ny) for i in range(nx)]
    tris = []
    for j in range(ny - 1):
        for i in range(nx - 1):
            tris.append((idx(i, j), idx(i + 1, j), idx(i + 1, j + 1)))
            tris.append((idx(i, j), idx(i + 1, j + 1), idx(i, j + 1)))
    x = [(u, -w, 0.0) for u, w in uv]
    return uv, tris, x
test_baraff_witkin_cloth.py 236 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/baraff-witkin-cloth/. The authors are listed in prov/7F3XVP.jsonl.

"""Tests of Baraff-Witkin cloth against central differences, a dense solve and exact identities."""

import math
import random

from anim import num_grad, q_from_axis_angle, q_rotate, solve
import baraff_witkin_cloth as bw


def flat(xs):
    return [c for p in xs for c in p]


def unflat(f):
    return [tuple(f[3 * i:3 * i + 3]) for i in range(len(f) // 3)]


def jiggle(rng, x, a):
    return [tuple(c + rng.uniform(-a, a) for c in p) for p in x]


def dense(mat, n):
    out = [[0.0] * (3 * n) for _ in range(3 * n)]
    for i, row in mat.items():
        for j, blk in row.items():
            for r in range(3):
                for c in range(3):
                    out[3 * i + r][3 * j + c] = blk[r][c]
    return out


def numeric_jacobian(fun, x):
    """Central differences of a list-of-3-vectors function, as a dense 3n by 3n matrix."""
    n = len(x)
    flat_x = flat(x)
    cols = []
    for k in range(3 * n):
        def comp(t, k=k):
            y = list(flat_x)
            y[k] += t
            return flat(fun(unflat(y)))
        p, m = comp(1e-6), comp(-1e-6)
        cols.append([(a - b) / 2e-6 for a, b in zip(p, m)])
    return [list(row) for row in zip(*cols)]


def test_bend_gradient_against_num_grad():
    rng = random.Random(1)
    for _ in range(10):
        pts = [tuple(rng.uniform(-1, 1) for _ in range(3)) for _ in range(4)]
        _, g = bw.bend_angle(*pts)
        ng = num_grad(lambda f: bw.bend_angle(*unflat(f))[0], flat(pts))
        assert max(abs(a - b) for a, b in zip(flat(g), ng)) <= 1e-6 * max(abs(c) for c in ng)


def test_forces_against_num_grad_rest_and_rotation():
    rng = random.Random(2)
    uv, tris, x = bw.grid(4, 4, 0.1)
    cl = bw.Cloth(uv, tris, density=0.5, k_stretch=100.0, k_shear=10.0, k_bend=0.01)
    y = jiggle(rng, x, 0.02)
    f, _, _ = cl.forces(y, [(0.0, 0.0, 0.0)] * len(y))
    ng = num_grad(lambda fl: cl.energy(unflat(fl)), flat(y))
    assert max(abs(a + b) for a, b in zip(flat(f), ng)) <= 1e-6 * max(abs(c) for c in ng)
    # zero force at rest and after a rigid motion
    q = q_from_axis_angle((0.3, -1.0, 0.5), 0.9)
    for z in (x, [tuple(c + d for c, d in zip(q_rotate(q, p), (0.2, -0.4, 1.0))) for p in x]):
        f, _, _ = cl.forces(z, [(0.0, 0.0, 0.0)] * len(z))
        assert max(abs(c) for fi in f for c in fi) < 1e-10


def test_stretch_and_shear_jacobian_against_central_differences():
    rng = random.Random(3)
    uv, tris, x = bw.grid(3, 3, 0.1)
    cl = bw.Cloth(uv, tris, k_stretch=200.0, k_shear=30.0)
    y = jiggle(rng, x, 0.03)
    zero = [(0.0, 0.0, 0.0)] * len(y)
    _, kmat, _ = cl.forces(y, zero)
    got = dense(kmat, len(y))
    want = numeric_jacobian(lambda z: cl.forces(z, zero)[0], y)
    scale = max(abs(c) for row in want for c in row)
    for i in range(len(got)):
        for j in range(len(got)):
            assert abs(got[i][j] - want[i][j]) <= 1e-6 * scale
            assert got[i][j] == got[j][i] or abs(got[i][j] - got[j][i]) <= 1e-12 * scale


def test_bend_jacobian_is_exact_where_theta_is_zero():
    """The code keeps only -k dC dC^T of the bend Jacobian, which is exact at theta = 0."""
    rng = random.Random(4)
    uv, tris, x = bw.grid(3, 3, 0.1)
    cl = bw.Cloth(uv, tris, k_stretch=0.0, k_shear=0.0, k_bend=0.5)
    # a stretched flat sheet: every theta is zero
    y = [(1.3 * p[0] + rng.uniform(-0.01, 0.01), 0.8 * p[1] + rng.uniform(-0.01, 0.01), 0.0) for p in x]
    zero = [(0.0, 0.0, 0.0)] * len(y)
    got = dense(cl.forces(y, zero)[1], len(y))
    want = numeric_jacobian(lambda z: cl.forces(z, zero)[0], y)
    scale = max(abs(c) for row in want for c in row)
    assert max(abs(a - b) for ra, rb in zip(got, want) for a, b in zip(ra, rb)) <= 1e-6 * scale


def test_damping_velocity_jacobian_and_dissipation():
    rng = random.Random(5)
    uv, tris, x = bw.grid(3, 3, 0.1)
    cl = bw.Cloth(uv, tris, k_stretch=0.0, k_shear=0.0, k_bend=0.0, kd_stretch=2.0, kd_shear=1.0, kd_bend=0.3)
    y = jiggle(rng, x, 0.03)
    v = [tuple(rng.uniform(-1, 1) for _ in range(3)) for _ in y]
    f, _, dmat = cl.forces(y, v)
    got = dense(dmat, len(y))
    want = numeric_jacobian(lambda w: cl.forces(y, w)[0], v)
    scale = max(abs(c) for row in want for c in row)
    assert max(abs(a - b) for ra, rb in zip(got, want) for a, b in zip(ra, rb)) <= 1e-6 * scale
    # d . v = -sum k_d Cdot^2 <= 0, and the damping forces sum to zero
    assert sum(a * b for a, b in zip(flat(f), flat(v))) < 0.0
    for c in range(3):
        assert abs(sum(fi[c] for fi in f)) < 1e-12


def test_damping_position_jacobian_drops_only_the_asymmetric_term():
    """Equation (12) minus the term dC/dx_i (dCdot/dx_j)^T equals the code's dd/dx."""
    rng = random.Random(6)
    uv, tris, x = bw.grid(3, 3, 0.1)
    cl = bw.Cloth(uv, tris, k_stretch=0.0, k_shear=0.0, kd_stretch=2.0, kd_shear=1.0)
    y = jiggle(rng, x, 0.03)
    v = [tuple(rng.uniform(-1, 1) for _ in range(3)) for _ in y]
    n = len(y)
    got = dense(cl.forces(y, v)[1], n)
    for idx, c, grads, s, base, k, kd in cl.conditions(y):
        for b, j in enumerate(idx):
            # dCdot/dx_j = sum_l s[l][j] B v_l
            dcd = [sum(s[l][b] * sum(base[r][t] * v[idx[l]][t] for t in range(3)) for l in range(3))
                   for r in range(3)]
            for a, i in enumerate(idx):
                for r in range(3):
                    for t in range(3):
                        got[3 * i + r][3 * j + t] -= kd * grads[a][r] * dcd[t]
    want = numeric_jacobian(lambda z: cl.forces(z, v)[0], y)
    scale = max(abs(c) for row in want for c in row)
    assert max(abs(a - b) for ra, rb in zip(got, want) for a, b in zip(ra, rb)) <= 1e-6 * scale


def scene(rng, nx=4):
    uv, tris, x = bw.grid(nx, nx, 0.1)
    cl = bw.Cloth(uv, tris, density=0.4, k_stretch=500.0, k_shear=50.0, k_bend=1e-3,
                  kd_stretch=0.5, kd_shear=0.1, kd_bend=1e-4)
    y = jiggle(rng, x, 0.02)
    v = [tuple(rng.uniform(-0.5, 0.5) for _ in range(3)) for _ in y]
    return cl, y, v


def test_modified_pcg_without_constraints_matches_a_dense_solve():
    cl, y, v = scene(random.Random(7))
    amat, b = cl.system(y, v, 0.02)
    dv, iters = bw.modified_pcg(amat, b, {}, eps=1e-13)
    want = solve(dense(amat, cl.n), flat(b))
    assert max(abs(p - q) for p, q in zip(flat(dv), want)) <= 1e-9 * max(abs(q) for q in want)
    assert iters <= 3 * cl.n * 2


def test_modified_pcg_with_constraints_matches_the_reduced_solve():
    cl, y, v = scene(random.Random(8))
    amat, b = cl.system(y, v, 0.02)
    p = (0.0, 0.6, 0.8)
    cons = {0: bw.pin((0.1, -0.2, 0.3)), 3: bw.pin(), 6: bw.plane(p, -0.25),
            9: bw.plane((1.0, 0.0, 0.0), 0.0)}
    # the basis B of the free directions, dv = z + B alpha
    basis = []
    other = {6: [(1.0, 0.0, 0.0), (0.0, 0.8, -0.6)], 9: [(0.0, 1.0, 0.0), (0.0, 0.0, 1.0)]}
    for i in range(cl.n):
        if i in other:
            dirs = other[i]
        elif i in cons:
            dirs = []
        else:
            dirs = [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)]
        for d in dirs:
            col = [0.0] * (3 * cl.n)
            col[3 * i:3 * i + 3] = d
            basis.append(col)
    a = dense(amat, cl.n)
    z = [0.0] * (3 * cl.n)
    for i, (_, zi) in cons.items():
        z[3 * i:3 * i + 3] = zi
    az = [sum(a[r][c] * z[c] for c in range(3 * cl.n)) for r in range(3 * cl.n)]
    rhs = [sum(col[r] * (flat(b)[r] - az[r]) for r in range(3 * cl.n)) for col in basis]
    ab = [[sum(a[r][c] * col[c] for c in range(3 * cl.n)) for r in range(3 * cl.n)] for col in basis]
    red = [[sum(ci[r] * abj[r] for r in range(3 * cl.n)) for abj in ab] for ci in basis]
    alpha = solve(red, rhs)
    want = [z[r] + sum(al * col[r] for al, col in zip(alpha, basis)) for r in range(3 * cl.n)]
    dv, _ = bw.modified_pcg(amat, b, cons, eps=1e-13)
    assert max(abs(p - q) for p, q in zip(flat(dv), want)) <= 1e-9 * max(abs(q) for q in want)
    # the constrained components equal z after any number of iterations
    for it in (0, 1, 2, 5):
        dv, _ = bw.modified_pcg(amat, b, cons, eps=0.0, max_iter=it)
        for i, (s, zi) in cons.items():
            fixed = [dv[i][r] - sum(s[r][c] * dv[i][c] for c in range(3)) for r in range(3)]
            assert max(abs(fc - zc) for fc, zc in zip(fixed, zi)) < 1e-15


def test_momentum_of_one_step_without_constraints():
    rng = random.Random(9)
    cl, y, v = scene(rng)
    total = sum(cl.mass)
    p0 = [sum(m * vi[c] for m, vi in zip(cl.mass, v)) for c in range(3)]
    h = 0.02
    for k in range(1, 6):
        y, v, _ = cl.step(y, v, h, eps=1e-14, max_iter=400)
        for c in range(3):
            want = p0[c] + k * h * total * bw.GRAVITY[c]
            got = sum(m * vi[c] for m, vi in zip(cl.mass, v))
            assert abs(got - want) <= 1e-10 * max(1.0, abs(p0[c]), abs(want))


def test_large_step_stays_bounded_where_explicit_euler_fails():
    nx = 5
    uv, tris, x0 = bw.grid(nx, nx, 0.1)
    cl = bw.Cloth(uv, tris, density=0.4, k_stretch=1e6, k_shear=1e5, k_bend=1e-4)
    cons = {0: bw.pin(), nx - 1: bw.pin()}
    h = 1.0 / 30.0
    x, v = list(x0), [(0.0, 0.0, 0.0)] * len(x0)
    for _ in range(20):
        x, v, _ = cl.step(x, v, h, cons, eps=1e-6)
        assert cl.energy(x) < 1e-3 and max(math.sqrt(sum(c * c for c in vi)) for vi in v) < 1.0
    assert x[0] == x0[0] and x[nx - 1] == x0[nx - 1]
    # explicit Euler with the same step and forces
    x, v = list(x0), [(0.0, 0.0, 0.0)] * len(x0)
    for _ in range(6):
        f, _, _ = cl.forces(x, v)
        nv = [(0.0, 0.0, 0.0) if i in cons else
              tuple(v[i][c] + h * (f[i][c] + cl.f_ext[i][c]) / cl.mass[i] for c in range(3))
              for i in range(len(x))]
        x = [tuple(x[i][c] + h * v[i][c] for c in range(3)) for i in range(len(x))]
        v = nv
    assert cl.energy(x) > 1e6

History

David Baraff and Andrew Witkin presented the method at SIGGRAPH 1998. Earlier cloth simulators, such as the particle model of Breen, House and Wozny and the spring model of Provot, used explicit steps, and the paper reports running times of several minutes per frame for garments of about a thousand nodes in earlier work. The combination of implicit steps, conditions on triangles and the filtered conjugate gradient method cut this to seconds per frame on the hardware of 1998. Bridson, Fedkiw and Anderson (2002) wrote that it "generated convincing results despite dropping nonsymmetric terms from their matrix".

References

  1. David Baraff and Andrew Witkin, Large steps in cloth simulation, Proceedings of SIGGRAPH 98, pages 43 to 54, 1998, Section 2.2 (masses), Section 3, equations (4) to (6) (the implicit step), Section 4, equations (7) to (12) (conditions, forces, Jacobians and damping), Section 5, equations (13) to (16) and the procedure modified-pcg (constraints), Section 6 (collisions), Section 7 (adaptive steps), Section 8 (timings)
  2. Robert Bridson, Sebastian Marino and Ronald Fedkiw, Simulation of clothing with folds and wrinkles, ACM SIGGRAPH 2005 Courses (first published at the Symposium on Computer Animation 2003), the gradient of the dihedral angle used by the bend condition of the code

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.assembly
  • a full proof of time.iteration
  • a full proof of time.step
  • a full proof of space.matrix
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