Algorithm Search⌘K

Algorithmadvanced

As-rigid-as-possible shape interpolation

Also called ARAP shape interpolation.

Morph between two compatible triangulations by interpolating the rotation and stretch of each triangle separately and solving for a consistent mesh.

Time
O(n^3 + m) buildO(n^2 + m) query
Space
Θ(n^2) extra
Where
m = the number of triangles; n = the number of vertices
Properties
deterministicexactofflineiterative

As-rigid-as-possible shape interpolation morphs one 2D shape into another when both are triangulated with the same triangles. For each triangle it takes the affine map from the source triangle to the target triangle, splits it into a rotation and a stretch, and interpolates the angle of the rotation and the entries of the stretch separately. The interpolated triangles do not fit together, so the vertices at each time are the least squares fit to them. Marc Alexa, Daniel Cohen-Or and David Levin (2000) introduced the method. It avoids the shrinking and the kinks of linear interpolation of the vertices, because a triangle that only turns keeps its shape and area at every time.

In plain words

Picture a cartoon arm drawn as a mesh of small triangles, first held down and then raised. If every corner moves in a straight line to its new place, the arm shrinks in the middle of the move, as if it were made of rubber. This method looks at each small triangle instead. It asks how much the triangle turns and how much it is stretched, and makes it turn and stretch a little at a time. Those little triangles no longer fit together, like tiles cut a bit wrong. So the method finds the mesh that comes closest to all of them at once. That mesh turns the arm as a whole, and the arm keeps its size.

The problem

The input is a source shape P=(p1,…,pn)P = (p_1, \dots, p_n) and a target shape Q=(q1,…,qn)Q = (q_1, \dots, q_n) of points in the plane, a list of triangles on the vertex indices that triangulates both shapes, and a time t∈[0,1]t \in [0, 1]. The two triangulations must be compatible: the same triangles, with the same orientation, in both shapes. The output is the shape V(t)=(v1(t),…,vn(t))V(t) = (v_1(t), \dots, v_n(t)), with V(0)=PV(0) = P and V(1)=QV(1) = Q. The shapes in between should keep each triangle as close to a rotated and gradually stretched copy of itself as possible.

For a triangle f=(i,j,k)f = (i, j, k), AfA_f is the 2 by 2 matrix with Af(pj−pi)=qj−qiA_f(p_j - p_i) = q_j - q_i and Af(pk−pi)=qk−qiA_f(p_k - p_i) = q_k - q_i, the linear part of the affine map of the triangle. In the same way, Bf(V)B_f(V) is the linear part of the map from the source triangle to the triangle ff of VV; it is linear in VV.

The algorithm

R(θ)R(\theta) is the rotation by θ\theta. The polar decomposition of a 2 by 2 matrix AA with det⁡A>0\det A > 0 is A=R(γ)SA = R(\gamma)S with SS symmetric positive definite; in 2D it has the closed form γ=atan2⁡(a21−a12,a11+a22)\gamma = \operatorname{atan2}(a_{21} - a_{12}, a_{11} + a_{22}) and S=R(γ)TAS = R(\gamma)^{\mathsf T}A.

  1. ARAP-INTERPOLATION(P, Q, triangles) ▷ build, once
  2. 1for each triangle f do
  3. 2A_f ← the linear part of the map from triangle f of P to triangle f of Q
  4. 3(R(γ_f), S_f) ← polar(A_f)
  5. 4walk over neighbouring triangles: γ_g ← γ_g + 2πk with |γ_g - γ_f| ≤ π
  6. 5H ← the matrix of Σ_f |B_f(V)|²_F, without vertex 1 ▷ does not depend on t
  7. AT(t) ▷ query, for each frame
  8. 6A_f(t) ← R(t γ_f) ((1 - t) I + t S_f) for each triangle f
  9. 7v_1(t) ← (1 - t) p_1 + t q_1
  10. 8for each coordinate x and y: solve H z = b(t) for the free vertices
  11. 9return V(t)

Lines L1 to L3 compute the matrices and their polar decompositions. Line L4 makes the angles consistent, as Baxter, Barla and Anjyo (2008) propose: the polar decomposition gives angles in (−π,π](-\pi, \pi], and two neighbouring triangles that both turn by about 180 degrees could get the angles +3.1+3.1 and −3.1-3.1 and turn in opposite directions. Line L5 builds the normal equations of the energy

E(V)=∑f∥Bf(V)−Af(t)∥F2,E(V) = \sum_f \bigl\lVert B_f(V) - A_f(t)\bigr\rVert_F^2,

which Alexa et al. minimize at each time. Each entry of Bf(V)B_f(V) depends only on the xx coordinates or only on the yy coordinates of VV, so the energy splits into an xx part and a yy part with the same matrix HH. Fixing v1v_1 removes the free translation, and HH is then positive definite for a connected triangulation. Only the right side b(t)b(t) of line L8 depends on tt, so HH is factored once and each frame costs two solves.

Example

One triangle. Let P=((0,0),(1,0),(0,1))P = ((0, 0), (1, 0), (0, 1)) and Q=((0,0),(0,2),(−1,0))Q = ((0, 0), (0, 2), (-1, 0)). Line L2 gives A=(0−120)A = \begin{pmatrix} 0 & -1 \\ 2 & 0 \end{pmatrix}, and line L3 gives γ=atan2⁡(3,0)=π/2\gamma = \operatorname{atan2}(3, 0) = \pi/2 and S=diag⁡(2,1)S = \operatorname{diag}(2, 1): the triangle is stretched by 2 along xx and turned by 90 degrees. At t=0.5t = 0.5, line L6 gives A(0.5)=R(π/4)diag⁡(1.5,1)A(0.5) = R(\pi/4)\operatorname{diag}(1.5, 1). With one triangle the fit is exact, so V(0.5)=((0,0),(1.06066,1.06066),(−0.70711,0.70711))V(0.5) = ((0, 0), (1.06066, 1.06066), (-0.70711, 0.70711)), with the area 0.750.75. Linear interpolation of the vertices gives ((0,0),(0.5,1),(−0.5,0.5))((0, 0), (0.5, 1), (-0.5, 0.5)), with the area 0.3750.375, less than both the source area 0.50.5 and the target area 11. The area of the interpolated triangle is 12det⁡A(t)=12(1+t)\frac12\det A(t) = \frac12(1 + t), which grows steadily from 0.50.5 to 11.

A turn by almost 180 degrees. Let QQ be a 3 by 3 grid of vertices with 8 triangles, turned by 33 radians. Every AfA_f is R(3)R(3), so the interpolation turns the grid rigidly, and V(0.5)V(0.5) is the grid turned by 1.51.5 radians, with the full area. Linear interpolation of the vertices maps the grid by 12(I+R(3))\frac12(I + R(3)), whose determinant is 12(1+cos⁡3)=0.005\frac12(1 + \cos 3) = 0.005, so the grid at t=0.5t = 0.5 has only 0.5 percent of its area.

Consistent angles. On a strip of four triangles with the angles 3.0,−3.1,3.05,−3.03.0, -3.1, 3.05, -3.0 from line L3, line L4 adds 2π2\pi to the second and the fourth, which gives 3.0,3.183,3.05,3.2833.0, 3.183, 3.05, 3.283. All four triangles then turn the same way.

Correctness

The matrix path of line L6 starts at Af(0)=IA_f(0) = I and ends at Af(1)=R(γf)Sf=AfA_f(1) = R(\gamma_f)S_f = A_f. At t=0t = 0, the source shape has Bf=IB_f = I for every triangle, so it has the energy 0, and with v1(0)=p1v_1(0) = p_1 it is the only minimizer; so V(0)=PV(0) = P. At t=1t = 1, the target shape has the energy 0 in the same way, so V(1)=QV(1) = Q.

If the target is a rigid motion of the source by the angle θ∈(−π,π)\theta \in (-\pi, \pi), every AfA_f is R(θ)R(\theta), every SfS_f is II, and the path is R(tθ)R(t\theta). The shape PP turned by tθt\theta about p1p_1 and moved to v1(t)v_1(t) fits every triangle exactly, so the morph is rigid.

If det⁡Af>0\det A_f > 0, then SfS_f is positive definite, so (1−t)I+tSf(1 - t)I + tS_f is positive definite and det⁡Af(t)>0\det A_f(t) > 0 for all tt: each target triangle keeps its orientation. The least squares fit of line L8 can still flip a triangle, because it only approximates the targets. The proof gives the details, including why HH is positive definite for a connected triangulation.

Proof: As-rigid-as-possible shape interpolation has a unique solution that starts at the source, ends at the target and keeps rigid motions rigidfull

We use the notation of the page. The triangulation has the vertices 1,…,n1, \dots, n and the triangles f=(i,j,k)f = (i, j, k), each with a nondegenerate source triangle. For a triangle ff, let Ef(V)E_f(V) be the 2 by 2 matrix with the columns vj−viv_j - v_i and vk−viv_k - v_i, and Mf=Ef(P)−1M_f = E_f(P)^{-1}. Then Bf(V)=Ef(V)MfB_f(V) = E_f(V)M_f and Af=Ef(Q)MfA_f = E_f(Q)M_f.

The matrix path

Lemma 1. For a 2 by 2 matrix AA with a11+a22a_{11} + a_{22} and a21−a12a_{21} - a_{12} not both zero, let γ=atan2⁡(a21−a12,a11+a22)\gamma = \operatorname{atan2}(a_{21} - a_{12}, a_{11} + a_{22}) and S=R(γ)TAS = R(\gamma)^{\mathsf T}A. Then SS is symmetric and A=R(γ)SA = R(\gamma)S. If det⁡A>0\det A > 0, SS is positive definite.

Proof. With c=cos⁡γc = \cos\gamma and s=sin⁡γs = \sin\gamma, the off-diagonal entries of S=R(γ)TAS = R(\gamma)^{\mathsf T}A are s12=c a12+s a22s_{12} = c\,a_{12} + s\,a_{22} and s21=−s a11+c a21s_{21} = -s\,a_{11} + c\,a_{21}. Their difference is s21−s12=c(a21−a12)−s(a11+a22)s_{21} - s_{12} = c(a_{21} - a_{12}) - s(a_{11} + a_{22}), which is 0 because (c,s)(c, s) is parallel to (a11+a22,a21−a12)(a_{11} + a_{22}, a_{21} - a_{12}). So SS is symmetric, and R(γ)S=AR(\gamma)S = A since R(γ)R(\gamma) is orthogonal. The trace of SS is c(a11+a22)+s(a21−a12)=(a11+a22)2+(a21−a12)2>0c(a_{11} + a_{22}) + s(a_{21} - a_{12}) = \sqrt{(a_{11} + a_{22})^2 + (a_{21} - a_{12})^2} > 0 and det⁡S=det⁡A\det S = \det A. A symmetric 2 by 2 matrix with a positive trace and a positive determinant has two positive eigenvalues. □\square

The implementation uses this closed form (the function polar of the helper file for 2 by 2 matrices) and then sets the off-diagonal entries of SS to their mean, which changes them only by roundoff.

Lemma 2. Af(0)=IA_f(0) = I, Af(1)=AfA_f(1) = A_f, and if det⁡Af>0\det A_f > 0 then det⁡Af(t)>0\det A_f(t) > 0 for all t∈[0,1]t \in [0, 1]. Adding 2πk2\pi k to γf\gamma_f changes Af(t)A_f(t) for 0<t<10 < t < 1 but not Af(1)A_f(1).

Proof. Af(0)=R(0)I=IA_f(0) = R(0)I = I and Af(1)=R(γf)Sf=AfA_f(1) = R(\gamma_f)S_f = A_f by Lemma 1. By Lemma 1, SfS_f is positive definite, so (1−t)I+tSf(1 - t)I + tS_f is positive definite as a convex combination of positive definite matrices, and det⁡Af(t)=det⁡((1−t)I+tSf)>0\det A_f(t) = \det((1 - t)I + tS_f) > 0. R(γf+2πk)=R(γf)R(\gamma_f + 2\pi k) = R(\gamma_f), but R(t(γf+2πk))=R(tγf)R(2πkt)R(t(\gamma_f + 2\pi k)) = R(t\gamma_f)R(2\pi kt), which differs for ktkt not an integer. □\square

Lemma 3. After line L4, the angles of two triangles ff and gg are within π\pi of each other whenever gg was first reached from ff in the walk.

Proof. When gg is first reached from ff, the walk adds 2πk2\pi k with k=round⁡((γf−γg)/(2π))k = \operatorname{round}((\gamma_f - \gamma_g)/(2\pi)), so the new difference γf−γg−2πk\gamma_f - \gamma_g - 2\pi k is at most π\pi in absolute value. The angle of ff is not changed again, because ff was reached before. □\square

The walk is a breadth-first search, so the pairs of Lemma 3 are the edges of a spanning tree of each connected part of the dual graph. Other neighbouring pairs are not checked; for meshes whose triangles turn by similar angles they are close as well.

The least squares problem

Lemma 4. The energy E(V)=∑f∥Bf(V)−Af(t)∥F2E(V) = \sum_f \lVert B_f(V) - A_f(t)\rVert_F^2 is the sum of a function of the xx coordinates and a function of the yy coordinates of VV, and both have the same quadratic part zTHzz^{\mathsf T}Hz, which does not depend on tt.

Proof. Row rr of Bf(V)=Ef(V)MfB_f(V) = E_f(V)M_f is row rr of Ef(V)E_f(V) times MfM_f, and row rr of Ef(V)E_f(V) contains only the coordinate rr of the vertices. So entry (r,c)(r, c) of Bf(V)B_f(V) is af,c⋅zra_{f,c}\cdot z_r, where zrz_r is the vector of coordinate rr of all vertices and af,ca_{f,c} has the entries −(Mf)1c−(Mf)2c-(M_f)_{1c} - (M_f)_{2c}, (Mf)1c(M_f)_{1c} and (Mf)2c(M_f)_{2c} at ii, jj and kk. The energy is ∑r∑f,c(af,c⋅zr−Af(t)rc)2\sum_r\sum_{f,c}(a_{f,c}\cdot z_r - A_f(t)_{rc})^2, whose quadratic part in zrz_r is zrTHzrz_r^{\mathsf T}Hz_r with H=∑f,caf,caf,cTH = \sum_{f,c}a_{f,c}a_{f,c}^{\mathsf T}, the same for both rr and free of tt. □\square

Lemma 5. If the triangulation is connected through shared edges and every vertex is in some triangle, the matrix H′H' obtained from HH by removing the row and the column of vertex 1 is positive definite.

Proof. By the proof of Lemma 4, zTHz=∑f∥ef(z)Mf∥2z^{\mathsf T}Hz = \sum_f\lVert e_f(z)M_f\rVert^2, where ef(z)=(zj−zi,zk−zi)e_f(z) = (z_j - z_i, z_k - z_i) is a row vector. Each term is at least 0, so HH is positive semidefinite. If zTHz=0z^{\mathsf T}Hz = 0, then ef(z)Mf=0e_f(z)M_f = 0 for every ff, and since MfM_f is invertible, zi=zj=zkz_i = z_j = z_k on every triangle. Triangles that share an edge share two vertices, so by connectedness zz is constant on all vertices. If also z1=0z_1 = 0, then z=0z = 0. So the quadratic form of H′H', which is zTHzz^{\mathsf T}Hz restricted to z1=0z_1 = 0, is positive for z≠0z \ne 0. □\square

Theorem 1. For each tt, with v1(t)v_1(t) fixed, EE has exactly one minimizer, and line L8 computes it.

Proof. With z1z_1 fixed, each coordinate part of the energy is a quadratic function of the free coordinates whose quadratic part is given by the positive definite H′H' (Lemmas 4 and 5). Such a function is strictly convex and has exactly one minimizer, the solution of its normal equations H′z′=b′−h1z1H'z' = b' - h_1z_1, where bb collects ∑f,cAf(t)rcaf,c\sum_{f,c}A_f(t)_{rc}a_{f,c} and h1h_1 is the column of HH for vertex 1 without its first entry. This is the system of line L8. □\square

The ends and rigid motions

Theorem 2. V(0)=PV(0) = P and V(1)=QV(1) = Q.

Proof. At t=0t = 0, Af(0)=IA_f(0) = I by Lemma 2, and Bf(P)=Ef(P)Mf=IB_f(P) = E_f(P)M_f = I, so E(P)=0E(P) = 0, and PP has v1=p1=v1(0)v_1 = p_1 = v_1(0). A point with the energy 0 is a minimizer, and by Theorem 1 it is the only one, so V(0)=PV(0) = P. At t=1t = 1, Af(1)=Af=Ef(Q)Mf=Bf(Q)A_f(1) = A_f = E_f(Q)M_f = B_f(Q), so E(Q)=0E(Q) = 0 with v1=q1=v1(1)v_1 = q_1 = v_1(1), and V(1)=QV(1) = Q. □\square

Theorem 3. If qi=R(θ)pi+cq_i = R(\theta)p_i + c for all ii, with −π<θ<π-\pi < \theta < \pi, then V(t)V(t) is the source turned by tθt\theta about p1p_1 and moved so that p1p_1 goes to v1(t)v_1(t): vi(t)=v1(t)+R(tθ)(pi−p1)v_i(t) = v_1(t) + R(t\theta)(p_i - p_1).

Proof. Ef(Q)=R(θ)Ef(P)E_f(Q) = R(\theta)E_f(P), so Af=R(θ)A_f = R(\theta). By Lemma 1, γf=atan2⁡(2sin⁡θ,2cos⁡θ)=θ\gamma_f = \operatorname{atan2}(2\sin\theta, 2\cos\theta) = \theta and Sf=IS_f = I. All angles are equal, so line L4 changes none of them, and Af(t)=R(tθ)A_f(t) = R(t\theta). The shape WW with wi=v1(t)+R(tθ)(pi−p1)w_i = v_1(t) + R(t\theta)(p_i - p_1) has Ef(W)=R(tθ)Ef(P)E_f(W) = R(t\theta)E_f(P), so Bf(W)=R(tθ)=Af(t)B_f(W) = R(t\theta) = A_f(t) and E(W)=0E(W) = 0, with w1=v1(t)w_1 = v_1(t). By Theorem 1, V(t)=WV(t) = W. □\square

Remark. BfB_f does not change when all vertices move by the same vector, so the minimizers of EE without a fixed vertex are the translates of one shape, by Lemma 5. Fixing a different vertex picks a different translate, so the shapes for two choices of the fixed vertex differ at each time by a translation.

Complexity

Lines L1 to L4 take Θ(m)\Theta(m) time for mm triangles. HH has one row and column per free vertex and a nonzero entry for each edge of the triangulation, so it is sparse, with O(n+m)O(n + m) nonzero entries. The implementation stores HH as a dense matrix and inverts it once, at the cost O(n3)O(n^3) and Θ(n2)\Theta(n^2) memory, and then each frame costs O(n2+m)O(n^2 + m). With a sparse Cholesky factorization of HH, as in practice, the factor is computed once and each frame costs two sparse triangular solves, close to linear in nn for planar meshes with a good ordering.

Properties

  • Exact ends. V(0)=PV(0) = P and V(1)=QV(1) = Q.
  • Rigid motions are kept. A target that is a rotation and a translation of the source gives a rigid morph.
  • Triangle orientations are kept in the targets. Each Af(t)A_f(t) has a positive determinant when AfA_f has.
  • Not symmetric. Interpolating from QQ to PP at the time 1−t1 - t does not give the same shapes in general, because the decomposition depends on which shape is the source. Alexa et al. give a symmetric variant.
  • Translation by one vertex. The motion of the whole shape is set by the path of the fixed vertex; a different choice of the fixed vertex moves the shapes by a translation that depends on tt.
  • Smooth in tt. For fixed angles, V(t)V(t) is an analytic function of tt, because the right side of line L8 is.

Variants and improvements

  • Other matrix paths. Alexa et al. also consider the decomposition A=RαDRβA = R_\alpha D R_\beta from the singular value decomposition, and they prefer the symmetric polar form because the singular value form behaves worse.
  • Symmetric variant. Alexa et al. (Section 2.3) give a variant of the energy that treats the two shapes in the same way, so that the morph from QQ to PP is the reverse of the morph from PP to QQ.
  • Consistent angles. Baxter, Barla and Anjyo (2008) make the angles of neighbouring triangles consistent and write the energy as normal equations that are factored once, which makes the interpolation interactive. They also interpolate more than two shapes.
  • Three dimensions. The same construction works for compatible tetrahedral meshes, with the polar decomposition of 3 by 3 matrices and rotations interpolated as quaternions, for example by slerp.
  • Compatible triangulations. If the two shapes are given only as outlines, a compatible triangulation of both must be built first, often with added interior vertices. Alexa et al. do this with compatible dissections.

When to use it

Use as-rigid-as-possible shape interpolation to morph the outline of a 2D character or object between two poses, as in cartoon in-betweening, when both poses can be triangulated with the same triangles. It is the right tool when parts of the shape turn by large angles, where linear interpolation shrinks them. For images rather than shapes, use a warp such as Beier-Neely morphing, which needs only line correspondences and no triangulation. For an interactive deformation of one shape by handles, use as-rigid-as-possible shape manipulation instead: it fits a shape to handle positions, while this method blends between two given shapes. The as-rigid-as-possible deformation of surfaces and the ARAP parameterization of a surface onto the plane use the same idea of local rotations, but they alternate local fits and a global solve and are not interpolations between two shapes.

Pitfalls

  • Incompatible triangulations. The method needs the same triangles in both shapes. A triangle that is flipped in the target has det⁡Af<0\det A_f < 0, and its path passes through a degenerate triangle.
  • Inconsistent angles. Without line L4, two neighbours that turn by about 180 degrees can turn in opposite directions, and the fit tears the mesh in the middle of the morph.
  • Turns beyond 180 degrees. The polar decomposition only sees the angle modulo 2π2\pi. A shape that should spin more than half a turn needs the extra turns added to the angles by hand.
  • Thin triangles. Long thin triangles in the source make AfA_f sensitive to small moves of the vertices. A good triangulation of the source helps.
  • The fixed vertex. The path of vertex 1 is a straight line; if the whole shape should move on an arc, move the result by a rigid motion of its own.

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
as_rigid_as_possible_shape_interpolation.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/as-rigid-as-possible-shape-interpolation/. The authors are listed in prov/B6HGFM.jsonl.
"""As-rigid-as-possible shape interpolation of 2D triangulations (Alexa, Cohen-Or and Levin 2000).

The source and the target are two lists of 2D points with the same triangles
(compatible triangulations). For each triangle f, A_f is the linear part of
the affine map that takes the source triangle to the target triangle. Its
polar decomposition A_f = R(gamma_f) S_f, with a rotation R and a symmetric
S, gives the interpolated matrix

    A_f(t) = R(t gamma_f) ((1 - t) I + t S_f).

The angles gamma_f are made consistent first: walking over the triangles
that share an edge, each angle is moved by a multiple of 2 pi to within pi of
its neighbour's angle (Baxter, Barla and Anjyo 2008). The vertices V(t)
minimize sum_f |B_f(V) - A_f(t)|_F^2, where B_f(V) is the linear part of the
affine map that takes the source triangle f to the triangle f of V. Vertex 0
is fixed at (1 - t) p_0 + t q_0. The energy is quadratic, the x and the y
coordinates separate, and both use the same matrix H, which does not depend
on t. H is inverted once.
"""

import math
from collections import deque

from anim import inv, lerp, matvec, mul, polar, rot2


def triangle_edges(points, tri):
    """Return the 2 by 2 matrix whose columns are the edges v_j - v_i and v_k - v_i of tri = (i, j, k)."""
    i, j, k = tri
    return [
        [points[j][0] - points[i][0], points[k][0] - points[i][0]],
        [points[j][1] - points[i][1], points[k][1] - points[i][1]],
    ]


def affine_part(source, target, tri):
    """Return the linear part of the affine map that takes triangle tri of source to that of target."""
    return mul(triangle_edges(target, tri), inv(triangle_edges(source, tri)))


def triangle_neighbours(triangles):
    """Return, for each triangle, the list of triangles that share an edge with it."""
    by_edge = {}
    for f, tri in enumerate(triangles):
        for a, b in ((tri[0], tri[1]), (tri[1], tri[2]), (tri[2], tri[0])):
            by_edge.setdefault((min(a, b), max(a, b)), []).append(f)
    nb = [[] for _ in triangles]
    for fs in by_edge.values():
        for f in fs:
            nb[f].extend(g for g in fs if g != f)
    return nb


def consistent_angles(angles, triangles):
    """Shift each angle by a multiple of 2 pi so that it is within pi of the neighbour it is reached from."""
    nb = triangle_neighbours(triangles)
    out = list(angles)
    seen = [False] * len(out)
    for start in range(len(out)):
        if seen[start]:
            continue
        seen[start] = True
        queue = deque([start])
        while queue:
            f = queue.popleft()
            for g in nb[f]:
                if not seen[g]:
                    out[g] += 2.0 * math.pi * round((out[f] - out[g]) / (2.0 * math.pi))
                    seen[g] = True
                    queue.append(g)
    return out


class ARAPShapeInterpolation:
    """Interpolate between two compatible 2D triangulations; call the object with t in [0, 1]."""

    def __init__(self, source, target, triangles, consistent=True):
        n = len(source)
        if len(target) != n or n < 3 or not triangles:
            raise ValueError("source and target need the same three or more points and at least one triangle")
        self.source = [tuple(map(float, p)) for p in source]
        self.target = [tuple(map(float, p)) for p in target]
        self.triangles = [tuple(tri) for tri in triangles]
        self.stretch = []
        angles = []
        # Each row is a linear form on one coordinate of the vertices: entry (f, c) of B_f(V).
        self.rows = []
        for f, tri in enumerate(self.triangles):  # @line L1
            a = affine_part(self.source, self.target, tri)  # @line L2
            r, s = polar(a)  # @line L3
            angles.append(math.atan2(r[1][0], r[0][0]))
            self.stretch.append(s)
            m = inv(triangle_edges(self.source, tri))
            i, j, k = tri
            for c in range(2):
                self.rows.append((f, c, ((i, -(m[0][c] + m[1][c])), (j, m[0][c]), (k, m[1][c]))))
        self.angles = consistent_angles(angles, self.triangles) if consistent else angles  # @line L4
        h = [[0.0] * n for _ in range(n)]
        for _, _, coef in self.rows:  # @line L5
            for va, ca in coef:
                for vb, cb in coef:
                    h[va][vb] += ca * cb
        self._h0 = [h[i][0] for i in range(1, n)]
        try:
            self._hinv = inv([row[1:] for row in h[1:]])
        except ValueError:
            raise ValueError("the triangulation must be connected") from None

    def triangle_targets(self, t):
        """Return the matrices A_f(t) = R(t gamma_f) ((1 - t) I + t S_f)."""
        out = []
        for g, s in zip(self.angles, self.stretch):
            blend = [[(1 - t) + t * s[0][0], t * s[0][1]], [t * s[1][0], (1 - t) + t * s[1][1]]]
            out.append(mul(rot2(t * g), blend))  # @line L6
        return out

    def __call__(self, t):
        n = len(self.source)
        a = self.triangle_targets(t)
        v0 = lerp(self.source[0], self.target[0], t)  # @line L7
        coords = []
        for r in range(2):  # @line L8
            b = [0.0] * n
            for f, c, coef in self.rows:
                val = a[f][r][c]
                for v, cv in coef:
                    b[v] += cv * val
            rhs = [b[i] - self._h0[i - 1] * v0[r] for i in range(1, n)]
            coords.append([v0[r]] + list(matvec(self._hinv, rhs)))
        return [(x, y) for x, y in zip(coords[0], coords[1])]  # @line L9

    def energy(self, points, t):
        """Return sum_f |B_f(points) - A_f(t)|_F^2."""
        a = self.triangle_targets(t)
        e = 0.0
        for f, c, coef in self.rows:
            for r in range(2):
                e += (sum(cv * points[v][r] for v, cv in coef) - a[f][r][c]) ** 2
        return e
test_as_rigid_as_possible_shape_interpolation.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/as-rigid-as-possible-shape-interpolation/. The authors are listed in prov/B6HGFM.jsonl.
import math
import random

import pytest

import anim
from as_rigid_as_possible_shape_interpolation import (
    ARAPShapeInterpolation,
    affine_part,
    consistent_angles,
)


def grid(nx, ny):
    pts = [(float(x), float(y)) for y in range(ny) for x in range(nx)]
    tris = []
    for y in range(ny - 1):
        for x in range(nx - 1):
            a, b, c, d = y * nx + x, y * nx + x + 1, (y + 1) * nx + x, (y + 1) * nx + x + 1
            tris.append((a, b, d))
            tris.append((a, d, c))
    return pts, tris


def rigid(points, ang, shift):
    c, s = math.cos(ang), math.sin(ang)
    return [(c * x - s * y + shift[0], s * x + c * y + shift[1]) for x, y in points]


def area(points, tri):
    i, j, k = tri
    return 0.5 * anim.cross2(anim.sub(points[j], points[i]), anim.sub(points[k], points[i]))


def max_gap(ps, qs):
    return max(anim.norm(anim.sub(p, q)) for p, q in zip(ps, qs))


def bent(points, rng):
    return [(x + 0.15 * y * y + rng.uniform(-0.05, 0.05), 1.2 * y + 0.1 * x + rng.uniform(-0.05, 0.05)) for x, y in points]


def test_ends_are_the_source_and_the_target(rng=random.Random(1)):
    src, tris = grid(4, 3)
    tgt = rigid(bent(src, rng), 1.1, (2.0, -1.0))
    interp = ARAPShapeInterpolation(src, tgt, tris)
    assert max_gap(interp(0.0), src) < 1e-12
    assert max_gap(interp(1.0), tgt) < 1e-12


def test_rigid_motion_gives_a_rigid_morph():
    src, tris = grid(3, 3)
    ang, shift = 2.5, (4.0, 1.0)
    tgt = rigid(src, ang, shift)
    interp = ARAPShapeInterpolation(src, tgt, tris)
    for t in (0.2, 0.5, 0.9):
        v0 = anim.lerp(src[0], tgt[0], t)
        ref = [anim.add(v0, p) for p in rigid([anim.sub(p, src[0]) for p in src], t * ang, (0.0, 0.0))]
        assert max_gap(interp(t), ref) < 1e-12


def test_solution_minimizes_the_energy(rng=random.Random(2)):
    src, tris = grid(4, 4)
    tgt = rigid(bent(src, rng), -0.7, (1.0, 1.0))
    interp = ARAPShapeInterpolation(src, tgt, tris)
    t = 0.4
    v = interp(t)
    flat = [c for p in v[1:] for c in p]

    def e(x):
        pts = [v[0]] + [(x[2 * i], x[2 * i + 1]) for i in range(len(v) - 1)]
        return interp.energy(pts, t)

    g = anim.num_grad(e, flat)
    assert max(abs(x) for x in g) < 1e-6
    e0 = e(flat)
    for _ in range(20):
        d = [rng.gauss(0, 1e-2) for _ in flat]
        assert e([a + b for a, b in zip(flat, d)]) > e0


def test_single_triangle_follows_the_matrix_path():
    src = [(0.0, 0.0), (2.0, 0.0), (0.0, 1.0)]
    tgt = [(1.0, 1.0), (1.0, 4.0), (0.0, 1.0)]
    interp = ARAPShapeInterpolation(src, tgt, [(0, 1, 2)])
    for t in (0.0, 0.3, 0.5, 1.0):
        v = interp(t)
        b = affine_part(src, v, (0, 1, 2))
        a = interp.triangle_targets(t)[0]
        assert max(abs(b[r][c] - a[r][c]) for r in range(2) for c in range(2)) < 1e-12


def test_polar_path_keeps_the_area_better_than_linear_interpolation():
    src, tris = grid(3, 3)
    tgt = rigid(src, 3.0, (0.0, 0.0))
    interp = ARAPShapeInterpolation(src, tgt, tris)
    mid = interp(0.5)
    lin = [anim.lerp(p, q, 0.5) for p, q in zip(src, tgt)]
    total = sum(area(src, tri) for tri in tris)
    assert sum(area(mid, tri) for tri in tris) == pytest.approx(total, rel=1e-12)
    # Linear interpolation of a turn by almost 180 degrees nearly collapses the shape.
    assert abs(sum(area(lin, tri) for tri in tris)) < 0.01 * total


def test_consistent_angles_on_a_strip():
    tris = [(0, 1, 2), (1, 3, 2), (2, 3, 4), (3, 5, 4)]
    angles = [3.0, -3.1, 3.05, -3.0]
    out = consistent_angles(angles, tris)
    assert out[0] == 3.0
    for a, b in zip(out, out[1:]):
        assert abs(a - b) < math.pi
    assert out[1] == pytest.approx(-3.1 + 2 * math.pi)


def test_consistent_angles_make_the_triangles_turn_the_same_way(rng=random.Random(3)):
    src, tris = grid(4, 3)
    # A turn by nearly 180 degrees with a small bend: some polar angles wrap around to near -pi.
    tgt = rigid([(x + rng.uniform(-0.1, 0.1), y + 0.05 * x * x) for x, y in src], math.pi - 0.03, (0.0, 0.0))
    raw = ARAPShapeInterpolation(src, tgt, tris, consistent=False)
    assert max(raw.angles) > 0 and min(raw.angles) < 0
    good = ARAPShapeInterpolation(src, tgt, tris)
    assert max(good.angles) - min(good.angles) < 0.5
    mid = good(0.5)
    assert all(area(mid, tri) > 0 for tri in tris)
    bad = raw(0.5)
    assert min(area(bad, tri) for tri in tris) < 0.5 * min(area(mid, tri) for tri in tris)


def test_bad_input():
    with pytest.raises(ValueError):
        ARAPShapeInterpolation([(0.0, 0.0), (1.0, 0.0)], [(0.0, 0.0), (1.0, 0.0)], [(0, 1, 0)])
    pts = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (5.0, 5.0), (6.0, 5.0), (5.0, 6.0)]
    with pytest.raises(ValueError):
        ARAPShapeInterpolation(pts, pts, [(0, 1, 2), (3, 4, 5)])

History

Alexa, Cohen-Or and Levin presented the method at SIGGRAPH 2000, with compatible triangulations of the two shapes made from compatible dissections, and with examples in 2D and 3D. Earlier shape morphs interpolated vertices or the intrinsic data of polygons, such as edge lengths and angles. Baxter, Barla and Anjyo (2008) made the angles consistent, wrote the energy as normal equations, and extended the method to more than two shapes. The idea of fitting a mesh to local rotations later led to as-rigid-as-possible shape manipulation and surface deformation.

References

  1. Marc Alexa, Daniel Cohen-Or and David Levin, As-rigid-as-possible shape interpolation, SIGGRAPH 2000, 157-164, Section 2 (the decomposition of each affine map, equation 5 for A(t), the quadratic energy of equation 8 with one fixed vertex, and the symmetric variant of Section 2.3) and Section 3 (compatible dissections)
  2. William Baxter, Pascal Barla and Ken-ichi Anjyo, Rigid shape interpolation using normal equations, NPAR 2008, 59-64, the choice of consistent rotation angles for neighbouring triangles, and the normal equations that are factored once

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.build
  • a full proof of time.query
  • a full proof of space.extra
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
  • History with a source
  • at least three sources
  • a scene preset for the example