Algorithm Search⌘K

Algorithmadvanced

As-rigid-as-possible shape manipulation

Also called Igarashi shape manipulation.

Deform a 2D triangulated shape in real time from moved handles by two least-squares steps that minimize distortion of each triangle.

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

As-rigid-as-possible shape manipulation moves a 2D shape, given as a triangle mesh, by a few handles that the user drags. The rest of the mesh follows so that each triangle changes as little as possible, apart from a rotation. Takeo Igarashi, Tomer Moscovich and John Hughes (2005) made it fast enough for real time with two linear least squares steps and no iteration: the first step allows each triangle to rotate and scale, and the second removes the scale. Both matrices depend only on the mesh and the choice of handles, so they are factored once; each move of a handle costs only back substitutions. It is the classic tool for puppet-style animation of 2D drawings.

In plain words

Draw a figure, fill it with small triangles, and pin a few points. Now drag one pin. The figure should bend like a sheet of rubber, not stretch like soft cheese. The method does this in two quick passes. The first pass asks each triangle to keep its shape but lets it grow or shrink, because that makes the problem easy to solve. The second pass takes each triangle from the first pass, turns a copy of the original triangle to match it, and then asks the mesh to fit these turned copies, which have the original size. Each pass is one linear solve, so the figure moves as fast as the mouse.

The problem

The input is a triangle mesh with the rest positions v1,…,vnv_1, \dots, v_n in the plane, a set HH of at least two handle vertices, and the target positions qkq_k of the handles. The output is new positions v′v' with vk′=qkv'_k = q_k for k∈Hk \in H, such that each triangle of v′v' is close to a rotated copy of the same triangle of vv. Let R90R_{90} be the turn by 90 degrees. For a triangle with the vertices v0,v1,v2v_0, v_1, v_2 in one of its three orders, the third vertex has fixed coordinates (x,y)(x, y) in the frame of the opposite edge: v2=v0+x(v1−v0)+yR90(v1−v0)v_2 = v_0 + x(v_1 - v_0) + yR_{90}(v_1 - v_0). Step 1 minimizes

E1(v′)=∑triangles ∑3 orders∣v2′−v0′−x(v1′−v0′)−yR90(v1′−v0′)∣2,E_1(v') = \sum_{\text{triangles}}\ \sum_{\text{3 orders}} \big|v'_2 - v'_0 - x(v'_1 - v'_0) - yR_{90}(v'_1 - v'_0)\big|^2,

which is 0 exactly when every triangle is similar to its rest triangle. Step 2 minimizes E2(v′)=∑triangles∑edges ij∣(vi′−vj′)−(wi−wj)∣2E_2(v') = \sum_{\text{triangles}}\sum_{\text{edges } ij}|(v'_i - v'_j) - (w_i - w_j)|^2, where ww is the fitted triangle of rest size.

The algorithm

  1. REGISTER(v, triangles, H)
  2. 1for each triangle and each of its 3 vertex orders, compute (x, y) of the third vertex
  3. 2build the matrix G of E_1 and factor its block of the free vertices by Cholesky
  4. 3for each triangle, factor the 4 by 4 matrix of the fit; build the matrix of E_2 and factor its free block
  5. MOVE(q)
  6. 4step 1: solve for the free vertices of v' that minimize E_1, with the handles at q
  7. 5for each triangle, fit the similar copy of its rest triangle closest to its step 1 position, and rescale it to the rest size about its centroid
  8. 6step 2: solve for the free vertices that minimize E_2 with the fitted triangles, for x and y separately
  9. 7return the step 1 and step 2 results

E1E_1 and E2E_2 are quadratic in the free vertices, and the handles enter only on the right side, so lines L4 and L6 are linear systems with the matrices of lines L2 and L3. Line L5 has two unknown vertices w0w_0, w1w_1 for each triangle, with w2w_2 given by the frame relation, and minimizes ∑k∣wk−vk′∣2\sum_k|w_k - v'_k|^2 over them, a 6 by 4 least squares problem whose 4 by 4 normal matrix depends only on the rest triangle. The matrix of E2E_2 is the graph Laplacian of the mesh edges, counted once per triangle, and its xx and yy systems are the same.

Example

The mesh is a bar of 5×15 \times 1 unit squares, each cut into 2 triangles: 12 vertices and 10 triangles, with the vertices (i,j)(i, j) for i=0..5i = 0..5 and j=0,1j = 0, 1. The handles are the four end vertices. The two right handles move up by 1.51.5, to (5,1.5)(5, 1.5) and (5,2.5)(5, 2.5), and the left ones stay. After step 1, the vertex that starts at (2,0)(2, 0) is at (2.18,0.54)(2.18, 0.54), and the vertex that starts at (1,1)(1, 1) is at (0.88,1.18)(0.88, 1.18). After step 2 they are at about (2.1903,0.5898)(2.1903, 0.5898) and (0.8972,1.1624)(0.8972, 1.1624). The bar bends into a smooth S and stays symmetric about its center (2.5,1.25)(2.5, 1.25). The longest change of an edge length is about 13% after step 1 and about 17% after step 2: the handles are now 27.25≈5.22\sqrt{27.25} \approx 5.22 apart instead of 5, and step 2 forbids the uniform growth that step 1 used to absorb this.

To see why step 2 is needed, scale the handles by 2 about the origin. Step 1 then scales the whole mesh by 2 exactly, because a scaled mesh has E1=0E_1 = 0, and the free vertical edges have length 2. After step 2 the free vertical edges have the lengths 1.08 to 1.13: the mesh is stretched between the handles, but its triangles keep close to their rest size.

Correctness

The proof proves the following. E1E_1 is 0 for every mesh that is a similarity image of the rest mesh, because the frame coordinates (x,y)(x, y) do not change under rotation, scale and translation. With two handles at different positions, the free block of GG is positive definite, so step 1 has a unique minimizer, and the Cholesky factorization exists. With one handle it is singular, and the implementation raises an error. If the handle targets are a rigid motion of the rest handles, the rigid image of the whole mesh has E1=0E_1 = 0, so step 1 returns it; every fitted triangle then equals its image, so E2=0E_2 = 0 there, and step 2 returns it too. The fit of line L5, followed by the rescale, equals the rotation of the rest triangle about the centroids that minimizes the squared distances, the 2D Kabsch or Procrustes solution. Each step is the exact minimizer of its energy, but the two steps together do not minimize a single energy, so the result is a heuristic for "as rigid as possible", not the minimizer of a rigidity energy.

Proof: Both steps of as-rigid-as-possible shape manipulation have unique minimizers, rigid motions are reproduced, and the fit is the Procrustes rotationfull

We use the notation of the page and identify the plane with C\mathbb{C}, so R90R_{90} is the multiplication by ii. For a triangle in one vertex order, the frame relation reads v2−v0=ζ(v1−v0)v_2 - v_0 = \zeta(v_1 - v_0) with ζ=x+iy\zeta = x + iy. We assume that the rest triangles are not degenerate and that the mesh is connected through shared edges: any two triangles are joined by a chain of triangles in which neighbours share an edge.

Step 1

Lemma 1. E1(u)=0E_1(u) = 0 if and only if there are α,β∈C\alpha, \beta \in \mathbb{C} with uk=αvk+βu_k = \alpha v_k + \beta for every vertex kk.

Proof. If u=αv+βu = \alpha v + \beta, then u2−u0=α(v2−v0)=αζ(v1−v0)=ζ(u1−u0)u_2 - u_0 = \alpha(v_2 - v_0) = \alpha\zeta(v_1 - v_0) = \zeta(u_1 - u_0) for every triangle and order, so every term of E1E_1 is 0. Conversely, let E1(u)=0E_1(u) = 0. In one triangle, put α=(u1−u0)/(v1−v0)\alpha = (u_1 - u_0)/(v_1 - v_0) and β=u0−αv0\beta = u_0 - \alpha v_0. Then u0=αv0+βu_0 = \alpha v_0 + \beta, u1=αv1+βu_1 = \alpha v_1 + \beta, and u2=u0+ζα(v1−v0)=αv2+βu_2 = u_0 + \zeta\alpha(v_1 - v_0) = \alpha v_2 + \beta. Two triangles that share an edge share two vertices with different rest positions, and two such values fix α\alpha and β\beta, so the neighbours have the same α\alpha, β\beta. By connectivity, all triangles do. □\square

So E1E_1 is 0 on the similarity images αv+β\alpha v + \beta with α≠0\alpha \ne 0, which are rotations and uniform scales followed by translations, and on the constant maps with α=0\alpha = 0.

Theorem 1. If at least two handles have different rest positions, the block of GG for the free vertices is positive definite, and step 1 has a unique minimizer. With one handle, the block is singular.

Proof. E1E_1 is a sum of squares of linear functions of uu, so it is a positive semidefinite quadratic form, and its restriction to free vertices with the handles fixed at 0 is the quadratic form of the free block. If this restriction is 0 for some uu, then E1(u)=0E_1(u) = 0, so u=αv+βu = \alpha v + \beta by Lemma 1. The two handles aa and bb give αva+β=0=αvb+β\alpha v_a + \beta = 0 = \alpha v_b + \beta with va≠vbv_a \ne v_b, so α=β=0\alpha = \beta = 0 and u=0u = 0. So the block is positive definite. A positive definite quadratic plus linear terms has a unique minimizer, the solution of its normal equations, which line L4 solves with the factor of line L2. With one handle aa, u=v−vau = v - v_a on the free vertices and ua=0u_a = 0 is nonzero and has E1=0E_1 = 0, so the block is singular. □\square

Corollary. If the handle targets are qk=αvk+βq_k = \alpha v_k + \beta for all k∈Hk \in H, step 1 returns αv+β\alpha v + \beta for all vertices.

Proof. αv+β\alpha v + \beta meets the handles and has E1=0E_1 = 0, the smallest possible value, so it is the unique minimizer. □\square

This covers the rest handles (α=1\alpha = 1, β=0\beta = 0), rigid motions (∣α∣=1|\alpha| = 1), and uniform scales, as the tests check.

The fit

Theorem 2. For a triangle with the rest vertices r0,r1,r2r_0, r_1, r_2 and the step 1 vertices p0,p1,p2p_0, p_1, p_2, line L5 returns cp+ρ(rk−cr)c_p + \rho(r_k - c_r), where crc_r and cpc_p are the centroids and ρ=γ/∣γ∣\rho = \gamma/|\gamma| with γ=∑k(rk−cr)‾(pk−cp)\gamma = \sum_k\overline{(r_k - c_r)}(p_k - c_p), provided γ≠0\gamma \ne 0. This ρ\rho is the rotation that minimizes ∑k∣cp+ρ(rk−cr)−pk∣2\sum_k|c_p + \rho(r_k - c_r) - p_k|^2 over ∣ρ∣=1|\rho| = 1.

Proof. The triangles ww that satisfy the frame relation of the rest triangle are exactly wk=αrk+βw_k = \alpha r_k + \beta for α,β∈C\alpha, \beta \in \mathbb{C}, by the argument of Lemma 1 on one triangle; w0w_0 and w1w_1 are free, and so are α\alpha and β\beta. So the fit minimizes ∑k∣αrk+β−pk∣2\sum_k|\alpha r_k + \beta - p_k|^2. For fixed α\alpha the best β\beta makes the centroids agree: β=cp−αcr\beta = c_p - \alpha c_r. Then the sum is ∑k∣αsk−tk∣2\sum_k|\alpha s_k - t_k|^2 with sk=rk−crs_k = r_k - c_r and tk=pk−cpt_k = p_k - c_p, minimized by α=γ/∑k∣sk∣2\alpha = \gamma/\sum_k|s_k|^2. The fitted triangle has the centroid cpc_p and the edge w1−w0=α(r1−r0)w_1 - w_0 = \alpha(r_1 - r_0), so the rescale factor is ∣r1−r0∣/∣w1−w0∣=1/∣α∣|r_1 - r_0|/|w_1 - w_0| = 1/|\alpha|, and the rescaled triangle is cp+α∣α∣sk=cp+ρskc_p + \frac{\alpha}{|\alpha|}s_k = c_p + \rho s_k. For ∣ρ∣=1|\rho| = 1, ∑k∣ρsk−tk∣2=∑k∣sk∣2+∑k∣tk∣2−2Re⁡(ρ‾γ)\sum_k|\rho s_k - t_k|^2 = \sum_k|s_k|^2 + \sum_k|t_k|^2 - 2\operatorname{Re}(\overline{\rho}\gamma), which is smallest when ρ\rho has the direction of γ\gamma. □\square

If γ=0\gamma = 0, the step 1 triangle is collapsed or turned so that no rotation fits better than another, and the rescale divides by 0; this happens only for extreme drags.

Step 2

Theorem 3. If every connected part of the mesh has a handle, the block of the matrix of E2E_2 for the free vertices is positive definite, and step 2 has a unique minimizer.

Proof. For the coordinate xx, E2E_2 is ∑edges ij(ui−uj−eij)2\sum_{\text{edges } ij}(u_i - u_j - e_{ij})^2 with fixed numbers eije_{ij} from the fitted triangles. Its quadratic part is ∑(ui−uj)2\sum(u_i - u_j)^2, the form of the graph Laplacian HH. If it is 0 with the handles at 0, uu is constant on each connected part, and that constant is the value 0 at a handle. So the free block is positive definite, and line L6 solves its normal equations. The same holds for yy. □\square

Theorem 4. If the handle targets are a rigid motion qk=αvk+βq_k = \alpha v_k + \beta with ∣α∣=1|\alpha| = 1, the final result is αv+β\alpha v + \beta.

Proof. By the Corollary, step 1 returns p=αv+βp = \alpha v + \beta. In Theorem 2, tk=αskt_k = \alpha s_k, so γ=α∑∣sk∣2\gamma = \alpha\sum|s_k|^2 and ρ=α\rho = \alpha; each fitted triangle is cp+αsk=αrk+βc_p + \alpha s_k = \alpha r_k + \beta, the image of the rest triangle. So u=αv+βu = \alpha v + \beta meets the handles and makes every term of E2E_2 zero, and by Theorem 3 it is the unique minimizer. □\square

What is not proved

Step 2 depends on step 1 through the fitted triangles, so the final mesh minimizes E2E_2 for fixed fitted triangles, not an energy of the final mesh alone. The page therefore makes no claim that the result is the most rigid mesh that meets the handles. For a uniform scale of the handles by 2, the tests measure that step 2 brings the free vertical edges from the length 2 back to below 1.2.

Complexity

Let nn be the number of vertices and mm the number of triangles. Lines L1 and L3, apart from the factorizations, take O(m)O(m) time. The implementation uses dense Cholesky factorizations, which cost O(n3)O(n^3) time and Θ(n2)\Theta(n^2) memory, and each move costs O(n2)O(n^2) for the triangular solves plus O(m)O(m) for line L5. The matrices are sparse, with O(1)O(1) entries per row for meshes of bounded degree, so a sparse Cholesky factorization with a fill-reducing order makes registration and each move much cheaper on large meshes. Registration repeats only when the user adds or removes a handle.

Properties

  • Handles met exactly (proved). The handles are fixed values, not soft constraints.
  • Rigid motions reproduced (proved). If the handles move rigidly, the whole mesh moves by the same rigid motion.
  • Uniform scale removed (proved for step 1, measured for step 2). Step 1 reproduces a uniform scale of the handles exactly; step 2 pulls the triangles back toward their rest size.
  • Each step optimal (proved). Step 1 is the unique minimizer of E1E_1 and step 2 of E2E_2 with the fitted triangles fixed.
  • No iteration. The result is the same every time for the same handles, and its cost per move is fixed, unlike iterative methods.
  • Not a minimizer of rigidity. Two steps give no guarantee that the result is the most rigid shape; large rotations within a short distance can still shear triangles.
  • No fold check. Nothing stops a triangle from flipping under an extreme drag.

Variants and improvements

  • Iterating the second step. Fitting rotations to the result of step 2 and solving again is close to the local and global iteration of as-rigid-as-possible deformation (Sorkine and Alexa 2007), which does decrease one rigidity energy at each step.
  • Surfaces. On 3D surfaces, Laplacian surface editing and the iterative method above play the same role.
  • Interpolation instead of handles. As-rigid-as-possible shape interpolation solves a different problem: it is given two complete shapes in correspondence and makes the shapes in between, by splitting the map of each triangle into a rotation and a stretch and interpolating them. Shape manipulation is given one shape and some handle targets, and has no second shape.
  • Weights from handles. Linear methods such as bounded biharmonic weights or cage coordinates blend handle transforms with precomputed weights, which is faster but not adapted to the drag.
  • Parameterization. The same rotation fitting appears in ARAP parameterization, which flattens a surface with little distortion.

When to use it

Use it to animate a 2D drawing, a character or a logo, by dragging a few points, when the motion should look like bending rather than stretching. It needs a triangle mesh of the shape, which is easy to make from an outline with a Delaunay triangulation. For 3D surfaces, use as-rigid-as-possible deformation; for a 2D shape with a cage around it and no mesh, use Green coordinates or another cage method.

Pitfalls

  • One handle. With a single handle, step 1 has no unique solution: a rotation and a scale about the handle cost nothing. Use at least two handles.
  • Order of the steps. Step 2 needs the step 1 result only to fit the triangles; solving step 2 alone, with the rest triangles unrotated, gives a stiff shape that does not turn.
  • Refactoring. The factorizations depend on which vertices are handles; adding a handle needs a new registration, but moving a handle does not.
  • Coarse meshes. Few, large triangles cannot bend smoothly; use a fine and well-shaped triangulation.
  • Folding. A drag past the shape can flip triangles; check the sign of each triangle area if this matters.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

anim.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small vectors, matrices, polar decomposition, quaternions and transforms.

This file is copied byte for byte into each impl/python folder that needs it.
It holds no method of a page: no curve, no skinning, no integrator step, no
collision test and no solver of a page. The method of each page lives in its
slug file.

Conventions (prompts/graphics-ext.md, "Mathematical conventions"):
- Vectors are tuples. Functions accept lists too and return tuples.
- Matrices are lists of rows, and a matrix acts on a column vector on the
  left: x' = M x.
- Quaternions use the Hamilton convention, scalar first, q = (w, x, y, z)
  with i j = k. A unit quaternion q rotates v by v' = q (0, v) q*.
- The log of a unit quaternion (cos phi, sin phi u) is (0, phi u), and the
  rotation angle is 2 phi. q_exp is the inverse map.
- Angles are in radians.
"""

import math

# Below this angle on the sphere of R^4, slerp uses normalized linear
# interpolation (nlerp), which avoids the division by sin(W).
SLERP_SMALL_ANGLE = 1e-6


# ---------------------------------------------------------------- vectors


def add(a, b):
    """Return a + b."""
    return tuple(x + y for x, y in zip(a, b))


def sub(a, b):
    """Return a - b."""
    return tuple(x - y for x, y in zip(a, b))


def scale(a, s):
    """Return s a for a number s."""
    return tuple(s * x for x in a)


def dot(a, b):
    """Return the dot product of a and b."""
    return sum(x * y for x, y in zip(a, b))


def cross(a, b):
    """Return the cross product of two 3D vectors."""
    return (
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    )


def cross2(a, b):
    """Return the scalar 2D cross product a_x b_y - a_y b_x."""
    return a[0] * b[1] - a[1] * b[0]


def norm(a):
    """Return the Euclidean length of a."""
    return math.sqrt(sum(x * x for x in a))


def normalize(a):
    """Return a / |a|. Raise ValueError for the zero vector."""
    n = norm(a)
    if n == 0.0:
        raise ValueError("cannot normalize the zero vector")
    return tuple(x / n for x in a)


def lerp(a, b, t):
    """Return (1 - t) a + t b."""
    return tuple((1 - t) * x + t * y for x, y in zip(a, b))


# ---------------------------------------------------------------- matrices


def zeros(n, m=None):
    """Return the n by m zero matrix (n by n if m is None)."""
    if m is None:
        m = n
    return [[0.0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def mul(a, b):
    """Return the matrix product a b."""
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the vector a x as a tuple."""
    return tuple(sum(p * q for p, q in zip(row, x)) for row in a)


def transpose(a):
    """Return the transpose of a."""
    return [list(col) for col in zip(*a)]


def _lu(a):
    """Gaussian elimination with partial pivoting on a copy of a square a.

    Return (lu, perm, sign), or None if a pivot is exactly zero.
    """
    n = len(a)
    lu = [list(map(float, row)) for row in a]
    perm = list(range(n))
    sign = 1.0
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(lu[i][k]))
        if lu[p][k] == 0.0:
            return None
        if p != k:
            lu[k], lu[p] = lu[p], lu[k]
            perm[k], perm[p] = perm[p], perm[k]
            sign = -sign
        piv = lu[k][k]
        for i in range(k + 1, n):
            f = lu[i][k] / piv
            lu[i][k] = f
            if f != 0.0:
                rk = lu[k]
                ri = lu[i]
                for j in range(k + 1, n):
                    ri[j] -= f * rk[j]
    return lu, perm, sign


def det(a):
    """Return the determinant of a square matrix."""
    n = len(a)
    if n == 1:
        return a[0][0]
    if n == 2:
        return a[0][0] * a[1][1] - a[0][1] * a[1][0]
    if n == 3:
        return (
            a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
            - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
            + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])
        )
    r = _lu(a)
    if r is None:
        return 0.0
    lu, _, sign = r
    d = sign
    for i in range(n):
        d *= lu[i][i]
    return d


def _lu_solve(lu, perm, b):
    n = len(lu)
    y = [float(b[perm[i]]) for i in range(n)]
    for i in range(n):
        s = y[i]
        row = lu[i]
        for j in range(i):
            s -= row[j] * y[j]
        y[i] = s
    for i in range(n - 1, -1, -1):
        s = y[i]
        row = lu[i]
        for j in range(i + 1, n):
            s -= row[j] * y[j]
        y[i] = s / row[i]
    return y


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a vector (returns a list) or a matrix given as a list of rows
    (returns a list of rows, one column of x per column of b).
    Raise ValueError if a is singular.
    """
    r = _lu(a)
    if r is None:
        raise ValueError("singular matrix")
    lu, perm, _ = r
    if len(b) > 0 and isinstance(b[0], (list, tuple)):
        cols = [_lu_solve(lu, perm, col) for col in zip(*b)]
        return [list(row) for row in zip(*cols)]
    return _lu_solve(lu, perm, b)


def inv(a):
    """Return the inverse of a square matrix. Raise ValueError if singular."""
    return solve(a, eye(len(a)))


# ---------------------------------------------------------------- polar decomposition


def rot2(theta):
    """Return the 2 by 2 rotation matrix by the angle theta."""
    c, s = math.cos(theta), math.sin(theta)
    return [[c, -s], [s, c]]


def _frob(a):
    return math.sqrt(sum(x * x for row in a for x in row))


def _sym_eig3(s):
    """Eigenvalues and eigenvectors of a symmetric 3 by 3 matrix (cyclic Jacobi).

    Return (values, vectors), where vectors[k] is the unit eigenvector of
    values[k].
    """
    a = [list(map(float, row)) for row in s]
    v = eye(3)
    for _ in range(50):
        off = a[0][1] ** 2 + a[0][2] ** 2 + a[1][2] ** 2
        if off <= 1e-30 * (sum(a[i][i] ** 2 for i in range(3)) + 1e-300):
            break
        for p, q in ((0, 1), (0, 2), (1, 2)):
            if a[p][q] == 0.0:
                continue
            theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
            t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
            c = 1.0 / math.sqrt(t * t + 1.0)
            sn = t * c
            for k in range(3):
                akp, akq = a[k][p], a[k][q]
                a[k][p] = c * akp - sn * akq
                a[k][q] = sn * akp + c * akq
            for k in range(3):
                apk, aqk = a[p][k], a[q][k]
                a[p][k] = c * apk - sn * aqk
                a[q][k] = sn * apk + c * aqk
            for k in range(3):
                vkp, vkq = v[k][p], v[k][q]
                v[k][p] = c * vkp - sn * vkq
                v[k][q] = sn * vkp + c * vkq
    values = [a[i][i] for i in range(3)]
    vectors = [tuple(v[k][i] for k in range(3)) for i in range(3)]
    return values, vectors


def polar(f, tol=1e-14, max_iter=100):
    """Return (R, S) with F = R S, det R = +1 and S symmetric.

    2 by 2: closed form. R = rot2(theta) with theta = atan2(f10 - f01, f00 + f11),
    the rotation that maximizes trace(R^T F), and S = R^T F.
    3 by 3: the Newton iteration X <- (X + X^(-T)) / 2 of Higham (1986), with
    the scaling gamma = (|X^(-1)|_F / |X|_F)^(1/2) while the relative change
    is above 1e-2. It stops when the relative change in the Frobenius norm is
    at most tol, or after max_iter steps. The iteration gives the orthogonal
    polar factor U. If det U < 0 (det F < 0), R = U (I - 2 v v^T) for the unit
    eigenvector v of the smallest eigenvalue of U^T F, so that det R = +1.
    If det F > 0, S is symmetric positive definite. If det F < 0, S is
    symmetric with one negative eigenvalue. Raise ValueError for a singular
    3 by 3 F.
    """
    n = len(f)
    if n == 2:
        theta = math.atan2(f[1][0] - f[0][1], f[0][0] + f[1][1])
        r = rot2(theta)
        s = mul(transpose(r), f)
        s01 = 0.5 * (s[0][1] + s[1][0])
        s[0][1] = s[1][0] = s01
        return r, s
    if n != 3:
        raise ValueError("polar supports 2 by 2 and 3 by 3 matrices")
    x = [list(map(float, row)) for row in f]
    change = float("inf")
    for _ in range(max_iter):
        xi = inv(x)
        if change > 1e-2:
            g = math.sqrt(_frob(xi) / _frob(x))
        else:
            g = 1.0
        xit = transpose(xi)
        y = [[0.5 * (g * x[i][j] + xit[i][j] / g) for j in range(3)] for i in range(3)]
        change = _frob([[y[i][j] - x[i][j] for j in range(3)] for i in range(3)]) / _frob(y)
        x = y
        if change <= tol:
            break
    u = x
    s = mul(transpose(u), f)
    s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
    if det(u) < 0.0:
        values, vectors = _sym_eig3(s)
        k = min(range(3), key=lambda i: values[i])
        v = vectors[k]
        h = [[(1.0 if i == j else 0.0) - 2.0 * v[i] * v[j] for j in range(3)] for i in range(3)]
        u = mul(u, h)
        s = mul(h, s)
        s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
    return u, s


# ---------------------------------------------------------------- quaternions


def q_mul(p, q):
    """Return the Hamilton product p q."""
    a1, b1, c1, d1 = p
    a2, b2, c2, d2 = q
    return (
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    )


def q_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return (q[0], -q[1], -q[2], -q[3])


def q_dot(p, q):
    """Return the dot product of p and q as vectors of R^4."""
    return p[0] * q[0] + p[1] * q[1] + p[2] * q[2] + p[3] * q[3]


def q_normalize(q):
    """Return q / |q|."""
    n = math.sqrt(q_dot(q, q))
    if n == 0.0:
        raise ValueError("cannot normalize the zero quaternion")
    return (q[0] / n, q[1] / n, q[2] / n, q[3] / n)


def q_from_axis_angle(axis, angle):
    """Return the unit quaternion of the rotation by angle about axis (any length)."""
    u = normalize(axis)
    s = math.sin(0.5 * angle)
    return (math.cos(0.5 * angle), s * u[0], s * u[1], s * u[2])


def q_to_mat3(q):
    """Return the 3 by 3 rotation matrix of a unit quaternion."""
    w, x, y, z = q
    return [
        [1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
        [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
        [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
    ]


def q_rotate(q, v):
    """Return the vector part of q (0, v) q* for a unit quaternion q."""
    r = q_mul(q_mul(q, (0.0, v[0], v[1], v[2])), q_conj(q))
    return (r[1], r[2], r[3])


def q_log(q):
    """Return the log of a nonzero quaternion as a 4-tuple (ln|q|, phi u).

    For a unit quaternion (cos phi, sin phi u) this is (0, phi u), with
    phi = atan2(|v|, w) in [0, pi]. For a real q the vector part is zero.
    """
    n = math.sqrt(q_dot(q, q))
    if n == 0.0:
        raise ValueError("log of the zero quaternion")
    vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
    lw = math.log(n)
    if vn == 0.0:
        return (lw, 0.0, 0.0, 0.0)
    phi = math.atan2(vn, q[0])
    f = phi / vn
    return (lw, f * q[1], f * q[2], f * q[3])


def q_exp(q):
    """Return exp(q) = e^w (cos|v|, sin|v| v / |v|) for q = (w, v)."""
    vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
    ew = math.exp(q[0])
    if vn == 0.0:
        return (ew, 0.0, 0.0, 0.0)
    f = ew * math.sin(vn) / vn
    return (ew * math.cos(vn), f * q[1], f * q[2], f * q[3])


def slerp(q0, q1, t):
    """Spherical linear interpolation of unit quaternions on the short arc.

    If q0 . q1 < 0, q1 is replaced by -q1 (the same rotation). The angle W
    comes from atan2(|q1 - q0|, |q1 + q0|). Below SLERP_SMALL_ANGLE the
    normalized linear interpolation is returned. See
    robotics/rigid-body-motion/spherical-linear-interpolation.
    """
    if q_dot(q0, q1) < 0.0:
        q1 = (-q1[0], -q1[1], -q1[2], -q1[3])
    a = math.sqrt(sum((y - x) ** 2 for x, y in zip(q0, q1)))
    b = math.sqrt(sum((y + x) ** 2 for x, y in zip(q0, q1)))
    w = 2.0 * math.atan2(a, b)
    if w < SLERP_SMALL_ANGLE:
        return q_normalize(tuple((1 - t) * x + t * y for x, y in zip(q0, q1)))
    s = math.sin(w)
    c0 = math.sin((1 - t) * w) / s
    c1 = math.sin(t * w) / s
    return tuple(c0 * x + c1 * y for x, y in zip(q0, q1))


def q_from_mat3(r):
    """Return the unit quaternion, with w >= 0, of a 3 by 3 rotation matrix.

    Shepperd's method: take the largest of the trace, r00, r11 and r22, and
    divide by the component that it gives. See
    robotics/rigid-body-motion/shepperd-method.
    """
    t = r[0][0] + r[1][1] + r[2][2]
    k = max(range(4), key=lambda i: (t, r[0][0], r[1][1], r[2][2])[i])
    if k == 0:
        w = math.sqrt(1.0 + t) / 2.0
        f = 4.0 * w
        q = (w, (r[2][1] - r[1][2]) / f, (r[0][2] - r[2][0]) / f, (r[1][0] - r[0][1]) / f)
    elif k == 1:
        x = math.sqrt(max(0.0, 1.0 + 2.0 * r[0][0] - t)) / 2.0
        f = 4.0 * x
        q = ((r[2][1] - r[1][2]) / f, x, (r[1][0] + r[0][1]) / f, (r[0][2] + r[2][0]) / f)
    elif k == 2:
        y = math.sqrt(max(0.0, 1.0 + 2.0 * r[1][1] - t)) / 2.0
        f = 4.0 * y
        q = ((r[0][2] - r[2][0]) / f, (r[1][0] + r[0][1]) / f, y, (r[2][1] + r[1][2]) / f)
    else:
        z = math.sqrt(max(0.0, 1.0 + 2.0 * r[2][2] - t)) / 2.0
        f = 4.0 * z
        q = ((r[1][0] - r[0][1]) / f, (r[0][2] + r[2][0]) / f, (r[2][1] + r[1][2]) / f, z)
    if q[0] < 0.0:
        q = (-q[0], -q[1], -q[2], -q[3])
    return q


# ---------------------------------------------------------------- transforms


def make_T(r, t):
    """Return the homogeneous (d + 1) by (d + 1) matrix [[R, t], [0, 1]] for d = len(t)."""
    d = len(t)
    m = [[float(r[i][j]) for j in range(d)] + [float(t[i])] for i in range(d)]
    m.append([0.0] * d + [1.0])
    return m


def T_mul(a, b):
    """Return the product a b of two homogeneous transforms."""
    return mul(a, b)


def T_inv(m):
    """Return the inverse of an affine homogeneous transform [[A, t], [0, 1]].

    The result is [[A^(-1), -A^(-1) t], [0, 1]]; A may hold a scale.
    """
    d = len(m) - 1
    a = [row[:d] for row in m[:d]]
    t = [m[i][d] for i in range(d)]
    ai = inv(a)
    ti = matvec(ai, t)
    return make_T(ai, tuple(-x for x in ti))


def T_apply(m, p):
    """Apply a homogeneous transform to a point p and return a tuple."""
    d = len(m) - 1
    return tuple(sum(m[i][j] * p[j] for j in range(d)) + m[i][d] for i in range(d))


# ---------------------------------------------------------------- derivatives


def num_grad(f, x, h=1e-6):
    """Return the gradient of a scalar f at x by central differences of step h."""
    x = list(x)
    g = []
    for i in range(len(x)):
        xi = x[i]
        x[i] = xi + h
        fp = f(x)
        x[i] = xi - h
        fm = f(x)
        x[i] = xi
        g.append((fp - fm) / (2.0 * h))
    return g
as_rigid_as_possible_shape_manipulation.py 230 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/as-rigid-as-possible-shape-manipulation/. The authors are listed in prov/6TBSNN.jsonl.
"""As-rigid-as-possible shape manipulation of Igarashi, Moscovich and Hughes (2005).

The shape is a 2D triangle mesh. The user pins some vertices (the handles)
and moves them. The free vertices follow in two least squares steps.

Step 1 (scale free): each vertex of a triangle has fixed coordinates (x, y)
in the frame of the opposite edge, v2 = v0 + x (v1 - v0) + y R90 (v1 - v0).
E1 sums the squared errors of these relations over all triangles and all
three vertex orders. A minimizer keeps each triangle close to a similar
copy of itself, so it allows rotation and uniform scale.

Step 2 (scale adjustment): fit to each triangle of the step 1 result the
closest triangle similar to the rest triangle, and rescale it to the rest
size about its centroid. Then E2 sums, over all triangle edges, the
squared difference between the new edge vector and the fitted edge vector.

E1 and E2 are quadratic, and the handles enter only on the right-hand
side, so the matrices of both steps are factored once with a Cholesky
factorization. Each handle move costs only triangular solves.
"""

import math


def r90(v):
    return (-v[1], v[0])


def cholesky(a):
    """Return the lower triangular L with a = L L^T. Raise ValueError if a is not positive definite."""
    n = len(a)
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        s = a[j][j] - sum(low[j][k] * low[j][k] for k in range(j))
        if s <= 0:
            raise ValueError("the matrix is not positive definite; pin at least two vertices")
        d = math.sqrt(s)
        low[j][j] = d
        for i in range(j + 1, n):
            low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / d
    return low


def cholesky_solve(low, b):
    """Solve L L^T x = b."""
    n = len(low)
    y = [0.0] * n
    for i in range(n):
        y[i] = (b[i] - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
    return x


def local_frame(p0, p1, p2):
    """Return (x, y) with p2 = p0 + x (p1 - p0) + y R90 (p1 - p0)."""
    ex, ey = p1[0] - p0[0], p1[1] - p0[1]
    dx, dy = p2[0] - p0[0], p2[1] - p0[1]
    ll = ex * ex + ey * ey
    return (dx * ex + dy * ey) / ll, (ex * dy - ey * dx) / ll


def _blocks(x, y):
    """Return the 2 by 2 coefficient blocks of v0, v1, v2 in v2 - v0 - x (v1 - v0) - y R90 (v1 - v0)."""
    b0 = ((x - 1.0, -y), (y, x - 1.0))
    b1 = ((-x, y), (-y, -x))
    b2 = ((1.0, 0.0), (0.0, 1.0))
    return b0, b1, b2


class ArapManipulator:
    """Registration (the factorizations) and compilation (the solves) for one mesh and one set of handles."""

    def __init__(self, rest, triangles, handles):
        self.rest = [tuple(map(float, p)) for p in rest]
        self.tris = [tuple(t) for t in triangles]
        self.handles = list(handles)
        n = len(self.rest)
        hset = set(self.handles)
        self.free = [v for v in range(n) if v not in hset]
        self.pos = {v: k for k, v in enumerate(self.free)}

        # Step 1 matrix over 2n unknowns, with index 2 v + c for coordinate c of vertex v.
        g = [[0.0] * (2 * n) for _ in range(2 * n)]
        self.frames = []
        for t in self.tris:
            fr = []
            for o in range(3):
                i0, i1, i2 = t[o], t[(o + 1) % 3], t[(o + 2) % 3]
                x, y = local_frame(self.rest[i0], self.rest[i1], self.rest[i2])  # @line L1
                fr.append((x, y))
                blocks = list(zip((i0, i1, i2), _blocks(x, y)))
                for r in range(2):
                    for va, ba in blocks:
                        for ca in range(2):
                            for vb, bb in blocks:
                                for cb in range(2):
                                    g[2 * va + ca][2 * vb + cb] += ba[r][ca] * bb[r][cb]
            self.frames.append(fr)
        self.g = g
        fidx = [2 * v + c for v in self.free for c in range(2)]
        self.fidx = fidx
        self.g_low = cholesky([[g[a][b] for b in fidx] for a in fidx])  # @line L2

        # Step 2a: per triangle, the 4 by 4 normal matrix of the similar-copy fit.
        self.fit = []
        for t, fr in zip(self.tris, self.frames):
            x, y = fr[0]
            b0, b1, _ = _blocks(x, y)
            # w2 = -(b0) w0 - (b1) w1, from b0 w0 + b1 w1 + w2 = 0.
            a_rows = [
                (1.0, 0.0, 0.0, 0.0),
                (0.0, 1.0, 0.0, 0.0),
                (0.0, 0.0, 1.0, 0.0),
                (0.0, 0.0, 0.0, 1.0),
                (-b0[0][0], -b0[0][1], -b1[0][0], -b1[0][1]),
                (-b0[1][0], -b0[1][1], -b1[1][0], -b1[1][1]),
            ]
            f = [[sum(r[i] * r[j] for r in a_rows) for j in range(4)] for i in range(4)]
            self.fit.append((a_rows, cholesky(f)))  # @line L3

        # Step 2b: the edge matrix, the same for x and y.
        h = [[0.0] * n for _ in range(n)]
        for t in self.tris:
            for o in range(3):
                i, j = t[o], t[(o + 1) % 3]
                h[i][i] += 1.0
                h[j][j] += 1.0
                h[i][j] -= 1.0
                h[j][i] -= 1.0
        self.h = h
        self.h_low = cholesky([[h[a][b] for b in self.free] for a in self.free])

    def step1(self, targets):
        """Return the scale-free result for the handle targets (a list, one point per handle)."""
        n = len(self.rest)
        q = [0.0] * (2 * n)
        for v, p in zip(self.handles, targets):
            q[2 * v], q[2 * v + 1] = p
        rhs = [-sum(self.g[a][2 * v + c] * q[2 * v + c] for v in self.handles for c in range(2)) for a in self.fidx]
        u = cholesky_solve(self.g_low, rhs)  # @line L4
        out = [None] * n
        for v, p in zip(self.handles, targets):
            out[v] = tuple(map(float, p))
        for k, v in enumerate(self.free):
            out[v] = (u[2 * k], u[2 * k + 1])
        return out

    def fitted_triangles(self, inter):
        """Return, per triangle, the rest-size copy closest to the step 1 triangle."""
        out = []
        for t, (a_rows, f_low) in zip(self.tris, self.fit):
            b = [inter[t[0]][0], inter[t[0]][1], inter[t[1]][0], inter[t[1]][1], inter[t[2]][0], inter[t[2]][1]]
            rhs = [sum(a_rows[r][i] * b[r] for r in range(6)) for i in range(4)]
            z = cholesky_solve(f_low, rhs)  # @line L5
            w = [sum(a_rows[r][i] * z[i] for i in range(4)) for r in range(6)]
            pts = [(w[0], w[1]), (w[2], w[3]), (w[4], w[5])]
            cx = sum(p[0] for p in pts) / 3
            cy = sum(p[1] for p in pts) / 3
            r0, r1 = self.rest[t[0]], self.rest[t[1]]
            k = math.dist(r0, r1) / math.dist(pts[0], pts[1])
            out.append([(cx + k * (p[0] - cx), cy + k * (p[1] - cy)) for p in pts])
        return out

    def step2(self, targets, fitted):
        """Return the final positions from the fitted triangles."""
        n = len(self.rest)
        out = [None] * n
        for v, p in zip(self.handles, targets):
            out[v] = tuple(map(float, p))
        coords = []
        for c in range(2):
            b = [0.0] * n
            for t, w in zip(self.tris, fitted):
                for o in range(3):
                    i, j = t[o], t[(o + 1) % 3]
                    e = w[o][c] - w[(o + 1) % 3][c]
                    b[i] += e
                    b[j] -= e
            rhs = [b[a] - sum(self.h[a][v] * out[v][c] for v in self.handles) for a in self.free]
            coords.append(cholesky_solve(self.h_low, rhs))  # @line L6
        for k, v in enumerate(self.free):
            out[v] = (coords[0][k], coords[1][k])
        return out

    def solve(self, targets):
        """Return (step 1 result, final result) for the handle targets."""
        inter = self.step1(targets)
        final = self.step2(targets, self.fitted_triangles(inter))
        return inter, final  # @line L7

    def energy1(self, verts):
        total = 0.0
        for t, fr in zip(self.tris, self.frames):
            for o in range(3):
                i0, i1, i2 = t[o], t[(o + 1) % 3], t[(o + 2) % 3]
                x, y = fr[o]
                p0, p1, p2 = verts[i0], verts[i1], verts[i2]
                e = (p1[0] - p0[0], p1[1] - p0[1])
                re = r90(e)
                dx = p2[0] - p0[0] - x * e[0] - y * re[0]
                dy = p2[1] - p0[1] - x * e[1] - y * re[1]
                total += dx * dx + dy * dy
        return total

    def energy2(self, verts, fitted):
        total = 0.0
        for t, w in zip(self.tris, fitted):
            for o in range(3):
                i, j = t[o], t[(o + 1) % 3]
                for c in range(2):
                    d = (verts[i][c] - verts[j][c]) - (w[o][c] - w[(o + 1) % 3][c])
                    total += d * d
        return total


def grid_mesh(nx, ny, size=1.0):
    """Return (vertices, triangles) of an nx by ny grid of squares, each split into two triangles."""
    verts = [(i * size, j * size) for j in range(ny + 1) for i in range(nx + 1)]
    tris = []
    for j in range(ny):
        for i in range(nx):
            a = j * (nx + 1) + i
            b, c, d = a + 1, a + nx + 2, a + nx + 1
            tris.append((a, b, c))
            tris.append((a, c, d))
    return verts, tris
test_as_rigid_as_possible_shape_manipulation.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/as-rigid-as-possible-shape-manipulation/. The authors are listed in prov/6TBSNN.jsonl.
import math
import random

import pytest

from anim import solve
from as_rigid_as_possible_shape_manipulation import ArapManipulator, cholesky, cholesky_solve, grid_mesh, local_frame

VERTS, TRIS = grid_mesh(5, 1)
# Handles: the two left vertices and the two right vertices of the 5 by 1 bar.
HANDLES = [0, 6, 5, 11]
_M = {}


def manip():
    if "m" not in _M:
        _M["m"] = ArapManipulator(VERTS, TRIS, HANDLES)
    return _M["m"]


def close_pts(a, b, eps):
    return all(math.dist(p, q) <= eps for p, q in zip(a, b))


def rigid(p, ang=0.9, t=(2.0, -1.0)):
    c, s = math.cos(ang), math.sin(ang)
    return (c * p[0] - s * p[1] + t[0], s * p[0] + c * p[1] + t[1])


def test_local_frame_reconstructs_the_third_vertex():
    rng = random.Random(61)
    for _ in range(20):
        p = [(rng.uniform(-2, 2), rng.uniform(-2, 2)) for _ in range(3)]
        x, y = local_frame(*p)
        e = (p[1][0] - p[0][0], p[1][1] - p[0][1])
        q = (p[0][0] + x * e[0] - y * e[1], p[0][1] + x * e[1] + y * e[0])
        assert math.dist(q, p[2]) < 1e-12


def test_cholesky_matches_gaussian_elimination():
    rng = random.Random(62)
    n = 8
    b = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
    a = [[sum(b[k][i] * b[k][j] for k in range(n)) + (n if i == j else 0) for j in range(n)] for i in range(n)]
    rhs = [rng.uniform(-1, 1) for _ in range(n)]
    x1 = cholesky_solve(cholesky(a), rhs)
    x2 = solve(a, rhs)
    assert max(abs(u - v) for u, v in zip(x1, x2)) < 1e-12


def test_one_handle_is_not_enough():
    with pytest.raises(ValueError):
        ArapManipulator(VERTS, TRIS, [0])


def test_rest_handles_give_rest_mesh():
    m = manip()
    inter, final = m.solve([VERTS[v] for v in HANDLES])
    assert close_pts(inter, VERTS, 1e-10)
    assert close_pts(final, VERTS, 1e-10)


def test_rigid_motion_of_handles_moves_mesh_rigidly():
    m = manip()
    inter, final = m.solve([rigid(VERTS[v]) for v in HANDLES])
    want = [rigid(p) for p in VERTS]
    assert close_pts(inter, want, 1e-10)
    assert close_pts(final, want, 1e-10)


def test_uniform_scale_survives_step1_only():
    m = manip()
    inter, final = m.solve([(2 * VERTS[v][0], 2 * VERTS[v][1]) for v in HANDLES])
    assert close_pts(inter, [(2 * x, 2 * y) for x, y in VERTS], 1e-10)
    # Step 2 pulls the free triangles back to the rest size: the fitted triangles have the rest
    # edge lengths, and the free vertical edges (length 2 after step 1) come back close to 1.
    fitted = m.fitted_triangles(inter)
    for t, w in zip(m.tris, fitted):
        for o in range(3):
            a, b = t[o], t[(o + 1) % 3]
            assert abs(math.dist(w[o], w[(o + 1) % 3]) - math.dist(VERTS[a], VERTS[b])) < 1e-12
    for a, b in ((1, 7), (2, 8), (3, 9), (4, 10)):
        assert abs(math.dist(inter[a], inter[b]) - 2) < 1e-10
        assert math.dist(final[a], final[b]) < 1.2


def test_handles_are_met_exactly():
    m = manip()
    rng = random.Random(63)
    targets = [(VERTS[v][0] + rng.uniform(-1, 1), VERTS[v][1] + rng.uniform(-1, 1)) for v in HANDLES]
    inter, final = m.solve(targets)
    for v, p in zip(HANDLES, targets):
        assert inter[v] == p and final[v] == p


def test_fit_equals_procrustes_rotation():
    m = manip()
    targets = [(VERTS[v][0], VERTS[v][1] + (1.5 if v in (5, 11) else 0.0)) for v in HANDLES]
    inter, _ = m.solve(targets)
    fitted = m.fitted_triangles(inter)
    for t, w in zip(m.tris, fitted):
        a = [complex(*VERTS[i]) for i in t]
        b = [complex(*inter[i]) for i in t]
        ca, cb = sum(a) / 3, sum(b) / 3
        alpha = sum((x - ca).conjugate() * (y - cb) for x, y in zip(a, b))
        rot = alpha / abs(alpha)
        want = [cb + rot * (x - ca) for x in a]
        assert all(abs(complex(*p) - q) < 1e-12 for p, q in zip(w, want))


def test_each_step_is_a_minimum():
    m = manip()
    rng = random.Random(65)
    targets = [(VERTS[v][0], VERTS[v][1] + (1.5 if v in (5, 11) else 0.0)) for v in HANDLES]
    inter, final = m.solve(targets)
    fitted = m.fitted_triangles(inter)
    e1, e2 = m.energy1(inter), m.energy2(final, fitted)
    for _ in range(10):
        k = rng.choice(m.free)
        d = (rng.uniform(-1e-3, 1e-3), rng.uniform(-1e-3, 1e-3))
        p1 = list(inter)
        p1[k] = (p1[k][0] + d[0], p1[k][1] + d[1])
        p2 = list(final)
        p2[k] = (p2[k][0] + d[0], p2[k][1] + d[1])
        assert m.energy1(p1) > e1
        assert m.energy2(p2, fitted) > e2


def test_worked_example_bend():
    m = manip()
    targets = [(VERTS[v][0], VERTS[v][1] + (1.5 if v in (5, 11) else 0.0)) for v in HANDLES]
    inter, final = m.solve(targets)
    # The free edges keep close to their rest length after step 2.
    worst = 0.0
    for t in TRIS:
        for o in range(3):
            a, b = t[o], t[(o + 1) % 3]
            worst = max(worst, abs(math.dist(final[a], final[b]) / math.dist(VERTS[a], VERTS[b]) - 1))
    assert worst < 0.2
    # The bar stays symmetric about its center point (2.5, 1.25) after the move.
    for v in range(len(VERTS)):
        i, j = v % 6, v // 6
        w = (5 - i) + 6 * (1 - j)
        p, q = final[v], final[w]
        assert abs(p[0] + q[0] - 5) < 1e-9 and abs(p[1] + q[1] - 2.5) < 1e-9
    # The numbers quoted on the page for the vertex that starts at (2, 0).
    assert math.dist(inter[2], (2.18, 0.54)) < 1e-12
    assert math.dist(final[2], (2.1903, 0.5898)) < 1e-4

History

Igarashi, Moscovich and Hughes presented the method at SIGGRAPH 2005, with an interface in which the user places and drags handles on a 2D shape. It followed the as-rigid-as-possible interpolation of Alexa, Cohen-Or and Levin (2000), which used the same idea of rigid triangles for morphing. Its two-step solution made it fast enough for live puppetry, and Sorkine and Alexa (2007) later used an iteration that minimizes a rigidity energy on surfaces.

References

  1. Takeo Igarashi, Tomer Moscovich and John F. Hughes, As-rigid-as-possible shape manipulation, SIGGRAPH 2005, ACM Transactions on Graphics 24(3), 1134-1141, 2005, the whole paper (the scale-free construction, the scale adjustment by fitted triangles, and the precomputed factorizations that make each handle move a pair of back substitutions)

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.per_move
  • a full proof of time.register
  • 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