Algorithmadvanced
As-rigid-as-possible surface deformation
Also called ARAP deformation, ARAP surface modeling.
Sorkine and Alexa's deformation that alternates fitting a rotation to each vertex cell and solving a Laplacian system, so detail stays locally rigid.
- Time
- O(n^3 + s n^2) worst
- Space
- Θ(n^2) extra
- Where
- n = the number of vertices; s = the number of rounds
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Olga Sorkine, Marc Alexa, 2007
As-rigid-as-possible (ARAP) surface deformation lets a user move a few handle vertices of a mesh and finds new positions for all the other vertices, so that the neighbourhood of each vertex, its cell, moves as nearly as possible by a rotation and a translation. Olga Sorkine and Marc Alexa introduced it in 2007. The cell of vertex is the set of its edges, and each cell gets its own rotation . The energy measures how far the edges of each cell are from a rotated copy of their rest shape. The method alternates two steps. The local step keeps the positions and finds the best rotation of each cell with a singular value decomposition, as in the Kabsch algorithm. The global step keeps the rotations and solves one linear system with the cotangent Laplacian, whose matrix never changes, so it is factored once. Neither step increases the energy, and a rigid motion of the whole mesh has energy 0.
In plain words
Think of a mesh as many small hinged stars, one star around each corner, made of the edges at that corner. You hold a few corners in your hands and pull them. Each star may turn and move, but it does not want to stretch or bend.
The method repeats two moves. First, keep every corner where it is, and for each star find the turn that matches its old shape best. Second, keep those turns, and move all the free corners at once so that every edge points as nearly as possible the way its turned star wants. This second move is one large but simple linear solve, and the solver is set up only once.
Each move makes the total mismatch smaller or keeps it the same. After some rounds, the parts bend, and small details on the surface turn with them instead of being sheared.
The problem
The input is a mesh with rest positions , a weight on each edge, and a nonempty set of handle vertices with targets . Every connected component of the edges with positive weight holds a handle. With the neighbours of vertex and , the output is the set of new positions , with on the handles, of small energy
where each is a rotation, a matrix in . The weights are usually the cotangent weights . The exact minimum of is not the target. The method returns positions from which no single step decreases much further.
The algorithm
ARAP(rest positions p, weights w, handles H with targets h, s)- 1
A ← the matrix on the free vertices with A_ii = Σ_j w_ij and A_ij = −w_ij; factor A = L Lᵀ - 2
R_i ← I for each vertex i; q ← the solution of lines L5 and L6 with these rotations - 3
repeat s times - 4
for each vertex i do S_i ← Σ_j w_ij e_ij (q_i − q_j)ᵀ = U Σ Vᵀ; R_i ← V diag(1, 1, d) Uᵀ with d = det(V Uᵀ) - 5
for each free vertex i do b_i ← Σ_j (w_ij / 2)(R_i + R_j) e_ij + Σ over handle neighbours j of w_ij h_j - 6
q ← the solution of L Lᵀ q = b, one coordinate at a time; q_k ← h_k for each k in H - 7
return q
Line L4 is the local step. For fixed positions the energy of cell is a constant minus , so the best rotation maximizes the trace, and the singular value decomposition gives it. The factor keeps the determinant at , so the cell is not mirrored. Lines L5 and L6 are the global step. For fixed rotations the energy is a quadratic function of the positions, and its minimum solves, at each free vertex,
The left side is the Laplacian of and does not depend on the rotations. The right side is the Laplacian of with each edge turned by the average of the rotations at its two ends. The handle values move to the right side. So the matrix of line L1 depends only on the rest mesh and on which vertices are handles, and each global step costs only the two triangular solves of line L6. Line L2 is the first guess: with all rotations equal to , line L6 is the simplest form of Laplacian surface editing, which keeps the differential coordinates as they are.
Example
Bending a bar. The bar is the box with its axis on the axis from to . Each square end is cut into a grid of squares and each long side into a grid, and each square into two triangles: 144 triangles and 74 vertices, with cotangent weights. The 9 vertices of the bottom end are handles that stay in place. The 9 vertices of the top end are handles that are turned by about the axis and moved to the end of a quarter circle of length 4, of radius , which bends the bar toward . The table gives the energy after the first solve of line L2 and then after each local step and each global step.
| step | L2 | local 1 | global 1 | local 2 | global 2 | local 3 | global 30 |
|---|---|---|---|---|---|---|---|
| energy |
The first solve, with no rotations, puts the middle of the bar at , the midpoint of the straight line between the centres of the two ends, so the bar is sheared and cuts the corner, and one edge changes its length by . After 30 rounds the centre of the middle ring is at , close to the midpoint of the quarter circle. The largest change in the length of an edge is and the mean is . That is near , the strain of the inner and outer sides of a bar of width 1 bent to the radius . On a finer bar, with a grid and 164 vertices, the energy after 30 rounds is and the largest change in length is , against for the first solve.
A rigid motion. Turn the bar by rad about the axis and move it by . On these positions, the local step returns the same rotation in every cell and the energy is below , and the global step with that rotation returns the same positions. Starting from the rest shape, with both ends as handles at their moved positions, the energy after the first solve and after round , , , , and is , , , , , and , and after 60 rounds no vertex is more than from its place in the rigid motion. With only the bottom end as a handle, the energy after the same rounds is , , , , , and , and after 60 rounds a vertex is still away.
Correctness
The proof file shows these facts.
- The local step is optimal. For fixed positions, the energy of cell is a constant minus , because a rotation keeps lengths. The rotation maximizes the trace over all rotations, by the lemma behind the Kabsch algorithm.
- The global step is a least squares solve. Each edge appears twice in , and the two terms add to plus a part that does not depend on , where . With nonnegative weights and a handle in every component, the matrix is symmetric positive definite, so the system of line L6 has exactly one solution, and it is the minimum of over the positions.
- The energy never increases. Each local step and each global step replaces one group of variables by its best value with the other group fixed. So , and the algorithm stops after rounds.
- A rigid motion has energy 0. If for a rotation , then every term of is 0 with . When the edges of each cell with positive weight span a plane, is the only best rotation of each cell, and the global step with returns the rigid motion, so it is a fixed point.
The energies converge, because they decrease and are at least 0. That the positions converge, or that they reach the global minimum of , is not proved. The energy is not convex, because the set of rotations is not convex.
Proof: The local step of as-rigid-as-possible deformation is optimal, the global step is a least squares solve, the energy never increases, and a rigid motion has zero energy and is a fixed pointfull
Setup. The mesh has the rest positions . Each edge has a weight , and is the set of the neighbours of vertex . Write . A nonempty set of handle vertices has fixed targets , and the other vertices are free. Every connected component of the graph of the edges with holds a handle. The positions have for , and each vertex has a rotation . The energy is
The local step keeps and sets each to a rotation that maximizes , with . The global step keeps and solves, at each free vertex ,
with for . The algorithm starts with , does one global step, and then does rounds of a local step followed by a global step.
Lemma 1 (the local step is optimal). For a fixed , the local step gives the least value of over all choices of rotations.
Proof. is a sum of one term for each vertex, and depends only on . Write . A rotation keeps lengths, so , and . So
The first sum does not depend on , so is least where is largest. Let be a singular value decomposition and . By Lemma 2 of the proof of the Kabsch algorithm, the maximum of over is attained by , which is what the local step returns.
The code computes as the sign of . That determinant is or up to rounding, far from 0, so the sign is safe in floating point.
Lemma 2 (the global step is a least squares solve). For fixed rotations, the system (1) has exactly one solution, and that solution is the unique minimum of over the positions with on the handles.
Proof. Each edge appears twice in , once from with and once from with . With , and , the two terms add to . By the identity ,
The second part does not depend on . The first part is a quadratic function of the free positions, and it splits into one function for each of the three coordinates. Its gradient with respect to a free is , so its critical points are the solutions of (1). Move the known of the handle neighbours to the right side. The matrix of the system on the free vertices has and for free . For a vector on the free vertices, extended by 0 on the handles,
If , then on every edge with , so is constant on each connected component of those edges. Each component holds a handle, where , so . Thus is symmetric positive definite, the system has exactly one solution, and the quadratic, whose Hessian in each coordinate is , has that solution as its unique minimum. The Cholesky factorization exists because is positive definite, and depends only on the weights and on , so one factorization serves every global step.
Theorem 1 (the energy never increases, and the algorithm stops). Let be the result of the first global step with , and for let be the result of the local step on and the result of the global step with . Then
Proof. The step from to keeps and replaces the rotations by the best ones, so it does not increase by Lemma 1. The step from to keeps and replaces by the minimum over all admissible positions, which include , so it does not increase by Lemma 2. The energy is a sum of squares, so it is at least 0. The algorithm does rounds, each of one local step and one global step, so it stops.
A nonincreasing sequence that is bounded below converges, so the energies converge. It is not proved here that the positions converge, nor that their limit is a global minimum of . The energy is not convex in , because is not a convex set. In the measurements on the page the energy decreases slowly and roughly linearly.
Theorem 2 (a rigid motion). Let and , and let for all .
- , the least value of .
- If the edge vectors of the edges at with span a plane, the local step on returns .
- If all handle targets are , the global step with all returns .
So, when the handles move rigidly and the condition of part 2 holds at every vertex, is a fixed point of the algorithm with energy 0.
Proof. (1) , so every term of is , and .
(2) With , , where is symmetric positive semidefinite. For a rotation let . Then . Write with orthonormal and . Then , because , and equality needs for each with . The range of is the span of the with , which is at least a plane, so at least two of the are positive and fixes two orthonormal vectors . A rotation keeps cross products, so , and fixes a basis, so . Hence is the only maximizer of , and by Lemma 1 the local step returns it.
(3) With all , and for every edge, so satisfies (1), and it takes the handle values. By Lemma 2 the solution of (1) is unique, so it is .
Theorem 2 does not say that the algorithm reaches from the rest shape. With the handles moved rigidly, the tests and the page measure that it tends to , at a rate that depends on how many vertices are handles.
Complexity
Let be the number of vertices. A mesh has edges, so lines L4 and L5 cost for each round. Each singular value decomposition costs a constant. The code stores as a dense matrix, so the factorization of line L1 costs once, and each solve of line L6 costs . The time is on the real RAM, and the extra space is for the factor. In practice is sparse and a sparse Cholesky decomposition with a fill-reducing order is used. Then the factor of a surface mesh has far fewer entries, and each round costs about as much as a few sweeps over the mesh. On the bar of the example, 30 rounds take s with 74 vertices and s with 164 vertices in plain Python with dense matrices.
Properties
- Monotone. The energy never increases from one step to the next.
- Rigid motions are kept. A rigid motion of all the handles is a fixed point with energy 0.
- Invariant under rigid motions. Moving the rest mesh and the targets by the same rigid motion moves the result in the same way, because the energy compares each cell with a rotated copy of itself.
- One factorization. The matrix depends only on the rest mesh and the set of handles. Moving the handles changes only the right side.
- Local optimum. The result depends on the first guess and on the number of rounds.
- Positions only. The handles fix positions, not rotations, so a handle of one vertex does not tell its neighbourhood how to turn.
Variants and improvements
- Uniform weights. All always gives a positive definite matrix, at the cost of a result that depends on how the mesh is cut into triangles.
- Other cells. A cell can also include the edges between the neighbours of a vertex, or be a triangle or a tetrahedron. On a mesh of tetrahedra the same two steps give a deformation of a solid.
- Shape interpolation and 2D shapes. Alexa, Cohen-Or and Levin blended the rotations of the simplices of two shapes to interpolate between them, and Igarashi, Moscovich and Hughes deformed 2D shapes with handles at interactive rates. These are the ancestors of the surface method.
- Parameterization. The same local and global steps flatten a surface into the plane with triangles that are as close to rigid copies as possible, as in ARAP parameterization.
- Smooth rotations. A term that penalizes the difference of the rotations of neighbouring cells makes the result smoother when the handles are few.
- Faster convergence. Starting each frame of an interactive session from the result of the previous frame, solving on a coarse mesh first, or extrapolating from the last few rounds, cuts the number of rounds.
When to use it
Use ARAP deformation for interactive editing of a detailed surface with handles, where parts must bend or twist by large angles and the details must turn with them. Laplacian surface editing needs one linear solve and is good for small changes. In its simplest form its differential coordinates do not turn, so large rotations shear the details, as the first solve of the example shows, and its linearized rotations hold only for small angles. For a character with a skeleton, skinning by the bones is cheaper. For physical behaviour, such as volume, mass or a material law, use a finite element method.
Pitfalls
- Negative cotangent weights. A triangle with an angle above gives a negative weight opposite that angle. The matrix need not be positive definite and the global step need not be a minimum. The code refuses such weights and offers uniform weights. Clamping the weights to 0 or remeshing also works.
- Slow convergence. The energy decreases roughly linearly. In the example, with only one end held, 60 rounds still leave a vertex away from the rigid motion that the energy prefers. Use more handles, a good first guess, or acceleration.
- A component without a handle. Its positions are not fixed, the matrix is singular, and the factorization fails.
- Mirrored cells. Without the factor the local step can return a reflection, and the cell turns inside out.
- Lost twists. The targets are positions only. A twist of the top end by a full turn gives the same targets as no twist, so the method cannot tell the two apart. Add handles along the bar, or turn the targets in small steps from frame to frame.
- Changing the handles. Adding or removing a handle changes the matrix, so it must be factored again. Moving a handle only changes the right side.
- Too few rounds. After one round the result is far better than the first solve, but it is not near the minimum. Stop on the change of the energy, not on a fixed small count.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/as-rigid-as-possible-deformation/. The authors are listed in prov/QG8W8W.jsonl.
"""As-rigid-as-possible surface deformation (Sorkine and Alexa, SGP 2007).
The energy of new positions q against the rest positions p, with one
rotation R_i for the cell of each vertex, is
E(q, R) = sum_i sum_{j in N(i)} w_ij |(q_i - q_j) - R_i (p_i - p_j)|^2.
The handle vertices are fixed at their targets. The method alternates
two steps, and neither increases E.
Local step: for fixed q, R_i maximizes trace(R_i S_i) with
S_i = sum_j w_ij (p_i - p_j)(q_i - q_j)^T, found by a 3 x 3 SVD.
Global step: for fixed R, q minimizes E, which is the linear system
sum_j w_ij (q_i - q_j) = sum_j (w_ij / 2)(R_i + R_j)(p_i - p_j) at each
free vertex. Its matrix depends only on the rest mesh and the handles, so it
is factored once (Cholesky) and each step costs one back substitution.
The weights must be nonnegative, and every connected part of the mesh must
hold a handle. The cotangent weights are nonnegative on meshes without
obtuse triangles, and their signs are decided exactly; weights="uniform"
sets all w_ij = 1.
"""
from mx1mesh import best_rotation, cholesky, cholesky_solve, cot_at, cross, dot, edges, exact, mat_vec, sign, sub
def cotan_sign(points, i, j, opposite):
"""The exact sign of the sum of the cotangents of the angles at the vertices in opposite, against the edge ij.
cot = d / sqrt(c) with d = (a - o) . (b - o) and c = |(a - o) x (b - o)|^2, both exact
rationals of the float input. Two terms of opposite signs are compared through d1^2 c2 and d2^2 c1.
"""
terms = []
for o in opposite:
a, b, c = exact(points[i]), exact(points[j]), exact(points[o])
u, v = sub(a, c), sub(b, c)
x = cross(u, v)
terms.append((dot(u, v), dot(x, x)))
s = [sign(d) for d, _ in terms]
if len(terms) == 1 or s[0] * s[1] >= 0:
return sign(sum(s))
(d1, c1), (d2, c2) = terms
return s[0] * sign(d1 * d1 * c2 - d2 * d2 * c1)
def weight_lists(n, faces, points, weights="cotan"):
"""For each vertex, the list of (neighbour, w_ij)."""
if weights == "uniform":
w = {e: 1.0 for e in edges(faces)}
else:
opposite = {}
for f in faces:
for k in range(3):
i, j, o = f[k], f[(k + 1) % 3], f[(k + 2) % 3]
opposite.setdefault((min(i, j), max(i, j)), []).append(o)
w = {}
for (i, j), opp in opposite.items():
s = cotan_sign(points, i, j, opp)
if s < 0:
raise ValueError("a cotangent weight is negative; use weights='uniform' or remesh")
w[(i, j)] = sum(cot_at(points[o], points[i], points[j]) for o in opp) / 2 if s > 0 else 0.0
nbw = [[] for _ in range(n)]
for (i, j), x in w.items():
nbw[i].append((j, x))
nbw[j].append((i, x))
return nbw
def energy(p, q, nbw, R):
total = 0.0
for i, row in enumerate(nbw):
for j, w in row:
e = mat_vec(R[i], sub(p[i], p[j]))
d = sub(q[i], q[j])
total += w * sum((a - b) ** 2 for a, b in zip(d, e))
return total
def local_step(p, q, nbw):
"""The best rotation of each cell: R_i maximizes trace(R S_i), S_i = sum_j w_ij e_ij e'_ij^T."""
R = []
for i, row in enumerate(nbw):
S = [[0.0] * 3 for _ in range(3)]
for j, w in row:
e, f = sub(p[i], p[j]), sub(q[i], q[j])
for a in range(3):
for b in range(3):
S[a][b] += w * e[a] * f[b]
R.append(best_rotation(S)) # @line L4
return R
class GlobalSolver:
"""The system sum_j w_ij (q_i - q_j) = b_i on the free vertices, factored once."""
def __init__(self, n, nbw, handles):
self.free = [i for i in range(n) if i not in handles]
self.index = {v: k for k, v in enumerate(self.free)}
m = len(self.free)
A = [[0.0] * m for _ in range(m)]
for k, i in enumerate(self.free):
for j, w in nbw[i]:
A[k][k] += w
if j in self.index:
A[k][self.index[j]] -= w
self.L = cholesky(A) # @line L1
def solve(self, p, nbw, R, handles):
q = [None] * len(p)
for i, h in handles.items():
q[i] = tuple(h)
rhs = [[0.0] * len(self.free) for _ in range(3)]
for k, i in enumerate(self.free):
for j, w in nbw[i]:
e = sub(p[i], p[j])
r = mat_vec([[(R[i][a][b] + R[j][a][b]) / 2 for b in range(3)] for a in range(3)], e)
for c in range(3):
rhs[c][k] += w * r[c] # @line L5
if j in handles:
rhs[c][k] += w * handles[j][c]
cols = [cholesky_solve(self.L, rhs[c]) for c in range(3)] # @line L6
for k, i in enumerate(self.free):
q[i] = (cols[0][k], cols[1][k], cols[2][k])
return q
def arap(points, faces, handles, iterations=10, weights="cotan"):
"""Deform the mesh so that each vertex in handles (a dict index -> target) reaches its target.
Returns (q, history): the new positions and the energy after the first
solve and after each local and each global step.
"""
n = len(points)
nbw = weight_lists(n, faces, points, weights)
solver = GlobalSolver(n, nbw, handles)
identity = [[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] for _ in range(n)]
q = solver.solve(points, nbw, identity, handles) # @line L2
history = [energy(points, q, nbw, identity)]
for _ in range(iterations): # @line L3
R = local_step(points, q, nbw)
history.append(energy(points, q, nbw, R))
q = solver.solve(points, nbw, R, handles)
history.append(energy(points, q, nbw, R))
return q, history # @line L7
mx1mesh.py 515 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mx1 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small tools for triangle meshes and dense linear algebra, used by the mx1 pages.
Points are tuples of three numbers. Faces are tuples of three vertex indices,
counterclockwise when seen from outside, so that the face normals point out.
Only the standard library is used. The geometric signs (an obtuse angle, the
side of a plane) are decided exactly, with Fraction, from the float input.
The linear solvers work on float input and on Fraction input.
"""
import math
from fractions import Fraction
# ---------------------------------------------------------------- vectors
def add(a, b):
return tuple(x + y for x, y in zip(a, b))
def sub(a, b):
return tuple(x - y for x, y in zip(a, b))
def scale(s, a):
return tuple(s * x for x in a)
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def cross(a, b):
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 norm(a):
return math.sqrt(dot(a, a))
def unit(a):
n = norm(a)
return tuple(x / n for x in a)
def exact(p):
"""The exact rational value of a point with float or Fraction coordinates."""
return tuple(Fraction(x) for x in p)
def sign(x):
return (x > 0) - (x < 0)
def dot_sign(a, b, c):
"""The exact sign of (b - a) . (c - a): positive for an acute angle at a, negative for an obtuse one."""
a, b, c = exact(a), exact(b), exact(c)
return sign(dot(sub(b, a), sub(c, a)))
def orient3d(a, b, c, d):
"""The exact sign of det(b - a, c - a, d - a): positive when d lies on the side of the plane abc that its normal points to."""
a, b, c, d = exact(a), exact(b), exact(c), exact(d)
return sign(dot(cross(sub(b, a), sub(c, a)), sub(d, a)))
# ---------------------------------------------------------------- topology
def edges(faces):
"""The undirected edges as sorted pairs, in sorted order."""
s = set()
for f in faces:
for k in range(3):
i, j = f[k], f[(k + 1) % 3]
s.add((min(i, j), max(i, j)))
return sorted(s)
def neighbours(n, faces):
nb = [set() for _ in range(n)]
for f in faces:
for k in range(3):
i, j = f[k], f[(k + 1) % 3]
nb[i].add(j)
nb[j].add(i)
return [sorted(s) for s in nb]
def edge_faces(faces):
"""Map each undirected edge to the list of the faces that hold it."""
m = {}
for t, f in enumerate(faces):
for k in range(3):
i, j = f[k], f[(k + 1) % 3]
m.setdefault((min(i, j), max(i, j)), []).append(t)
return m
def face_adjacency(faces):
"""For each face, the sorted list of the faces that share an edge with it."""
adj = [set() for _ in faces]
for fs in edge_faces(faces).values():
for a in fs:
for b in fs:
if a != b:
adj[a].add(b)
return [sorted(s) for s in adj]
def boundary_vertices(faces):
b = set()
for (i, j), fs in edge_faces(faces).items():
if len(fs) == 1:
b.update((i, j))
return b
def vertex_faces(n, faces):
vf = [[] for _ in range(n)]
for t, f in enumerate(faces):
for i in f:
vf[i].append(t)
return vf
# ---------------------------------------------------------------- face geometry
def face_cross(points, f):
"""cross(b - a, c - a): twice the area times the unit normal."""
a, b, c = (points[i] for i in f)
return cross(sub(b, a), sub(c, a))
def face_area(points, f):
return norm(face_cross(points, f)) / 2
def face_normal(points, f):
return unit(face_cross(points, f))
def centroid(points, f):
a, b, c = (points[i] for i in f)
return tuple((x + y + z) / 3 for x, y, z in zip(a, b, c))
def cot_at(a, b, c):
"""The cotangent of the angle at a in the triangle a, b, c."""
u, v = sub(b, a), sub(c, a)
return dot(u, v) / norm(cross(u, v))
def cotan_weights(points, faces):
"""w_ij = (cot alpha_ij + cot beta_ij) / 2, with alpha and beta the angles opposite the edge ij."""
w = {}
for f in faces:
for k in range(3):
i, j, o = f[k], f[(k + 1) % 3], f[(k + 2) % 3]
e = (min(i, j), max(i, j))
w[e] = w.get(e, 0.0) + cot_at(points[o], points[i], points[j]) / 2
return w
def stiffness_rows(n, weights):
"""The cotangent stiffness matrix C = -L as a list of dict rows: C_ij = -w_ij, C_ii = sum of w_ij."""
C = [dict() for _ in range(n)]
for (i, j), w in weights.items():
C[i][j] = C[i].get(j, 0) - w
C[j][i] = C[j].get(i, 0) - w
C[i][i] = C[i].get(i, 0) + w
C[j][j] = C[j].get(j, 0) + w
return C
def barycentric_area(points, faces):
A = [0.0] * len(points)
for f in faces:
a = face_area(points, f) / 3
for i in f:
A[i] += a
return A
def mixed_area(points, faces):
"""The mixed Voronoi area of Meyer, Desbrun, Schroeder and Barr (2003).
A triangle with no obtuse angle gives each corner its Voronoi part,
(|ij|^2 cot k + |ik|^2 cot j) / 8. An obtuse triangle gives half its area
to the obtuse corner and a quarter to each other corner.
"""
A = [0.0] * len(points)
for f in faces:
P = [points[i] for i in f]
obtuse = [dot_sign(P[k], P[(k + 1) % 3], P[(k + 2) % 3]) < 0 for k in range(3)]
area = face_area(points, f)
for k in range(3):
i, pj, pk, pi = f[k], P[(k + 1) % 3], P[(k + 2) % 3], P[k]
if not any(obtuse):
eij, eik = sub(pj, pi), sub(pk, pi)
A[i] += (dot(eij, eij) * cot_at(pk, pi, pj) + dot(eik, eik) * cot_at(pj, pi, pk)) / 8
else:
A[i] += area / 2 if obtuse[k] else area / 4
return A
def mean_curvature_normal(points, faces, area="mixed"):
"""K_i = (1 / (2 A_i)) sum_j (cot alpha_ij + cot beta_ij)(x_i - x_j), which is 2 H n_i with outward n_i."""
A = mixed_area(points, faces) if area == "mixed" else barycentric_area(points, faces)
w = cotan_weights(points, faces)
K = [[0.0, 0.0, 0.0] for _ in points]
for (i, j), wij in w.items():
d = sub(points[i], points[j])
for c in range(3):
K[i][c] += wij * d[c]
K[j][c] -= wij * d[c]
return [tuple(x / A[i] for x in K[i]) for i in range(len(points))]
def area_gradient(points, faces):
"""The gradient of the total area with respect to each vertex, summed face by face.
For a face with corner i and other corners j, k, the gradient at i is
(cot k (x_i - x_j) + cot j (x_i - x_k)) / 2, where cot j is the cotangent of the angle at j.
"""
g = [[0.0, 0.0, 0.0] for _ in points]
for f in faces:
for k in range(3):
i, j, l = f[k], f[(k + 1) % 3], f[(k + 2) % 3]
pi, pj, pl = points[i], points[j], points[l]
cl, cj = cot_at(pl, pi, pj), cot_at(pj, pi, pl)
for c in range(3):
g[i][c] += (cl * (pi[c] - pj[c]) + cj * (pi[c] - pl[c])) / 2
return [tuple(v) for v in g]
def total_area(points, faces):
return sum(face_area(points, f) for f in faces)
# ---------------------------------------------------------------- dense linear algebra
def identity(n, one=1):
return [[one if i == j else 0 * one for j in range(n)] for i in range(n)]
def transpose(A):
return [list(r) for r in zip(*A)]
def mat_mul(A, B):
Bt = transpose(B)
return [[sum(a * b for a, b in zip(r, c)) for c in Bt] for r in A]
def mat_vec(A, x):
return [sum(a * b for a, b in zip(r, x)) for r in A]
def det3(A):
return dot(A[0], cross(A[1], A[2]))
def solve_dense(A, b):
"""Solve A x = b by Gaussian elimination with partial pivoting. Exact on Fraction input."""
n = len(A)
M = [list(A[i]) + [b[i]] for i in range(n)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(M[r][c]))
if M[p][c] == 0:
raise ValueError("singular matrix")
M[c], M[p] = M[p], M[c]
for r in range(c + 1, n):
f = M[r][c] / M[c][c]
if f:
for k in range(c, n + 1):
M[r][k] -= f * M[c][k]
x = [0] * n
for r in range(n - 1, -1, -1):
x[r] = (M[r][n] - sum(M[r][k] * x[k] for k in range(r + 1, n))) / M[r][r]
return x
def cholesky(A):
"""The lower triangular L with A = L L^T, for a symmetric positive definite A."""
n = len(A)
L = [[0.0] * n for _ in range(n)]
for j in range(n):
d = A[j][j] - sum(L[j][k] ** 2 for k in range(j))
if d <= 0:
raise ValueError("matrix is not positive definite")
L[j][j] = math.sqrt(d)
for i in range(j + 1, n):
L[i][j] = (A[i][j] - sum(L[i][k] * L[j][k] for k in range(j))) / L[j][j]
return L
def cholesky_solve(L, b):
n = len(L)
y = [0.0] * n
for i in range(n):
y[i] = (b[i] - sum(L[i][k] * y[k] for k in range(i))) / L[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(L[k][i] * x[k] for k in range(i + 1, n))) / L[i][i]
return x
def _rotation(theta):
"""c, s of the Jacobi rotation for the cotangent theta of twice its angle."""
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1))
c = 1 / math.sqrt(1 + t * t)
return c, t * c
def jacobi_eigen(A, tol=1e-15, sweeps=100):
"""Eigenvalues (ascending) and unit eigenvectors of a symmetric matrix, by cyclic Jacobi rotations."""
n = len(A)
a = [[float(x) for x in r] for r in A]
v = identity(n, 1.0)
for _ in range(sweeps):
off = sum(a[i][j] ** 2 for i in range(n) for j in range(i + 1, n))
if off <= tol * tol * sum(a[i][i] ** 2 for i in range(n)) or off == 0:
break
for p in range(n):
for q in range(p + 1, n):
if a[p][q] == 0:
continue
c, s = _rotation((a[q][q] - a[p][p]) / (2 * a[p][q]))
for k in range(n):
akp, akq = a[k][p], a[k][q]
a[k][p], a[k][q] = c * akp - s * akq, s * akp + c * akq
for k in range(n):
apk, aqk = a[p][k], a[q][k]
a[p][k], a[q][k] = c * apk - s * aqk, s * apk + c * aqk
for k in range(n):
vkp, vkq = v[k][p], v[k][q]
v[k][p], v[k][q] = c * vkp - s * vkq, s * vkp + c * vkq
order = sorted(range(n), key=lambda k: a[k][k])
return [a[k][k] for k in order], [[v[i][k] for i in range(n)] for k in order]
def svd3(A, sweeps=60):
"""A = U diag(s) V^T for a 3 x 3 matrix, with s descending and U, V orthogonal (one-sided Jacobi)."""
U = [[float(x) for x in r] for r in A]
V = identity(3, 1.0)
for _ in range(sweeps):
done = True
for p, q in ((0, 1), (0, 2), (1, 2)):
al = sum(U[i][p] ** 2 for i in range(3))
be = sum(U[i][q] ** 2 for i in range(3))
ga = sum(U[i][p] * U[i][q] for i in range(3))
if ga == 0 or abs(ga) <= 1e-15 * math.sqrt(al * be):
continue
done = False
c, s = _rotation((be - al) / (2 * ga))
for M in (U, V):
for i in range(3):
mp, mq = M[i][p], M[i][q]
M[i][p], M[i][q] = c * mp - s * mq, s * mp + c * mq
if done:
break
sig = [math.sqrt(sum(U[i][k] ** 2 for i in range(3))) for k in range(3)]
order = sorted(range(3), key=lambda k: -sig[k])
s = [sig[k] for k in order]
cols = [[U[i][k] for i in range(3)] for k in order]
vcols = [[V[i][k] for i in range(3)] for k in order]
tiny = 1e-13 * max(s[0], 1e-300)
u = [tuple(x / s[k] for x in cols[k]) for k in range(3) if s[k] > tiny]
while len(u) < 3: # complete U where A has a null direction
if not u:
u.append((1.0, 0.0, 0.0))
elif len(u) == 1:
e = min(((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)), key=lambda t: abs(dot(t, u[0])))
u.append(unit(cross(u[0], e)))
else:
u.append(cross(u[0], u[1]))
Um = [[u[k][i] for k in range(3)] for i in range(3)]
Vm = [[vcols[k][i] for k in range(3)] for i in range(3)]
return Um, s, Vm
def best_rotation(S):
"""The rotation R (det 1) that maximizes trace(R S): with S = U diag(s) V^T, R = V diag(1, 1, d) U^T, d = det(V U^T)."""
U, _, V = svd3(S)
d = 1.0 if det3(mat_mul(V, transpose(U))) > 0 else -1.0
return mat_mul(mat_mul(V, [[1.0, 0, 0], [0, 1.0, 0], [0, 0, d]]), transpose(U))
def rotation_matrix(axis, angle):
"""The rotation by angle about the unit vector axis (Rodrigues)."""
x, y, z = unit(axis)
c, s = math.cos(angle), math.sin(angle)
C = 1 - c
return [[c + x * x * C, x * y * C - z * s, x * z * C + y * s],
[y * x * C + z * s, c + y * y * C, y * z * C - x * s],
[z * x * C - y * s, z * y * C + x * s, c + z * z * C]]
# ---------------------------------------------------------------- test meshes
def orient_outward(points, faces):
"""Flip each face of a mesh around the origin so that its normal points away from the origin (exact test)."""
out = []
o = (0, 0, 0)
for f in faces:
a, b, c = (points[i] for i in f)
out.append(tuple(f) if orient3d(a, b, c, o) < 0 else (f[0], f[2], f[1]))
return out
def octahedron():
p = [(1.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, -1.0)]
f = [(0, 2, 4), (2, 1, 4), (1, 3, 4), (3, 0, 4), (2, 0, 5), (1, 2, 5), (3, 1, 5), (0, 3, 5)]
return p, orient_outward(p, f)
def icosahedron():
t = (1 + math.sqrt(5)) / 2
raw = [(-1, t, 0), (1, t, 0), (-1, -t, 0), (1, -t, 0), (0, -1, t), (0, 1, t), (0, -1, -t), (0, 1, -t),
(t, 0, -1), (t, 0, 1), (-t, 0, -1), (-t, 0, 1)]
p = [unit(tuple(float(x) for x in q)) for q in raw]
f = [(0, 11, 5), (0, 5, 1), (0, 1, 7), (0, 7, 10), (0, 10, 11), (1, 5, 9), (5, 11, 4), (11, 10, 2), (10, 7, 6),
(7, 1, 8), (3, 9, 4), (3, 4, 2), (3, 2, 6), (3, 6, 8), (3, 8, 9), (4, 9, 5), (2, 4, 11), (6, 2, 10),
(8, 6, 7), (9, 8, 1)]
return p, orient_outward(p, f)
def icosphere(level, radius=1.0):
"""The icosahedron with each triangle cut into four `level` times, projected to the sphere."""
p, f = icosahedron()
p = list(p)
for _ in range(level):
mid = {}
def m(i, j):
e = (min(i, j), max(i, j))
if e not in mid:
mid[e] = len(p)
p.append(unit(scale(0.5, add(p[i], p[j]))))
return mid[e]
nf = []
for a, b, c in f:
ab, bc, ca = m(a, b), m(b, c), m(c, a)
nf += [(a, ab, ca), (b, bc, ab), (c, ca, bc), (ab, bc, ca)]
f = nf
return [scale(radius, q) for q in p], f
def cylinder(radius, height, m, k, twisted=False):
"""An open tube of m vertices around and k + 1 rings, axis z, centred at the origin, normals outward.
Plain: each rectangle is cut by the same diagonal. Twisted: ring l is turned by l half steps,
so that each vertex has six neighbours, as in a grid of near-equilateral triangles.
"""
p = []
for l in range(k + 1):
z = height * l / k - height / 2
for s in range(m):
th = 2 * math.pi * (s + (l / 2 if twisted else 0)) / m
p.append((radius * math.cos(th), radius * math.sin(th), z))
f = []
for l in range(k):
for s in range(m):
a, b = l * m + s, l * m + (s + 1) % m
c, d = b + m, a + m
if twisted: # the ring above is turned half a step forward
f += [(a, b, d), (b, c, d)]
else:
f += [(a, b, c), (a, c, d)]
return p, f
def box_mesh(size, div):
"""The closed surface of the box [-a/2, a/2] x [-b/2, b/2] x [-c/2, c/2], each side a grid of div cells.
size = (a, b, c) may hold Fractions, div = (na, nb, nc) are the numbers of cells along each axis.
Each grid cell is cut into two triangles. The normals point out.
"""
index, p, f = {}, [], []
def vid(key):
if key not in index:
index[key] = len(p)
p.append(tuple(size[a] * Fraction(key[a], div[a]) - Fraction(size[a]) / 2 for a in range(3)))
return index[key]
for ax in range(3):
u, w = [a for a in range(3) if a != ax]
for side in (0, div[ax]):
out = 1 if side else -1
eu = [0, 0, 0]
ew = [0, 0, 0]
eu[u], ew[w] = 1, 1
flip = cross(eu, ew)[ax] != out
for s in range(div[u]):
for t in range(div[w]):
q = []
for ds, dt in ((0, 0), (1, 0), (1, 1), (0, 1)):
key = [0, 0, 0]
key[ax], key[u], key[w] = side, s + ds, t + dt
q.append(vid(tuple(key)))
tris = [(q[0], q[1], q[2]), (q[0], q[2], q[3])]
f += [(a, c, b) if flip else (a, b, c) for a, b, c in tris]
return p, f
def to_float(points):
return [tuple(float(x) for x in q) for q in points]
test_as_rigid_as_possible_deformation.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/as-rigid-as-possible-deformation/. The authors are listed in prov/QG8W8W.jsonl.
import math
import random
import pytest
from as_rigid_as_possible_deformation import GlobalSolver, arap, cotan_sign, energy, local_step, weight_lists
from mx1mesh import (best_rotation, box_mesh, det3, edges, mat_mul, mat_vec, norm, rotation_matrix, sub, to_float,
transpose)
def bar():
p, f = box_mesh((1, 1, 4), (2, 2, 8))
return to_float(p), f
def bent_bar_handles(p):
"""Fix the bottom cap; turn the top cap by 90 degrees and put it at the end of a quarter circle of length 4."""
rho = 8 / math.pi
R = rotation_matrix((1, 0, 0), math.pi / 2) # takes +z to -y
H = {}
for i, x in enumerate(p):
if x[2] == -2.0:
H[i] = x
elif x[2] == 2.0:
r = mat_vec(R, (x[0], x[1], 0.0))
H[i] = (r[0], r[1] - rho, r[2] - 2 + rho)
return H
def trace(A):
return A[0][0] + A[1][1] + A[2][2]
def random_rotation(rng):
return rotation_matrix((rng.gauss(0, 1), rng.gauss(0, 1), rng.gauss(0, 1)), rng.uniform(0, math.pi))
def test_the_local_step_is_optimal() -> None:
rng = random.Random(3)
for _ in range(100):
S = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(3)]
R = best_rotation(S)
assert abs(det3(R) - 1) < 1e-12
RtR = mat_mul(transpose(R), R)
assert all(abs(RtR[a][b] - (a == b)) < 1e-12 for a in range(3) for b in range(3))
best = trace(mat_mul(R, S))
for _ in range(30):
assert trace(mat_mul(random_rotation(rng), S)) <= best + 1e-12
def test_a_rigid_motion_has_zero_energy() -> None:
p, f = bar()
nbw = weight_lists(len(p), f, p)
Q = rotation_matrix((1, 2, 3), 0.8)
t = (0.3, -1.0, 2.0)
q = [tuple(a + b for a, b in zip(mat_vec(Q, x), t)) for x in p]
R = local_step(p, q, nbw)
for Ri in R: # the local step finds Q in every cell
assert all(abs(Ri[a][b] - Q[a][b]) < 1e-9 for a in range(3) for b in range(3))
assert energy(p, q, nbw, R) < 1e-20
H = {i: q[i] for i in range(len(p)) if p[i][2] == -2.0}
q2 = GlobalSolver(len(p), nbw, H).solve(p, nbw, [Q] * len(p), H)
assert max(norm(sub(a, b)) for a, b in zip(q, q2)) < 1e-12 # the global step keeps the rigid motion
# from the rest shape, with both caps moved rigidly, the iteration tends to the rigid motion, slowly
caps = {i: q[i] for i in range(len(p)) if abs(p[i][2]) == 2.0}
q3, h = arap(p, f, caps, iterations=60)
assert h[-1] < 1e-5 * h[0] and max(norm(sub(a, b)) for a, b in zip(q, q3)) < 0.01
def test_the_energy_never_increases() -> None:
p, f = bar()
for weights in ("cotan", "uniform"):
_, h = arap(p, f, bent_bar_handles(p), iterations=15, weights=weights)
assert all(b <= a + 1e-12 * h[0] for a, b in zip(h, h[1:]))
assert h[-1] < h[0] / 10
def test_the_global_step_is_a_least_squares_solve() -> None:
rng = random.Random(5)
p, f = bar()
nbw = weight_lists(len(p), f, p)
H = bent_bar_handles(p)
R = [random_rotation(rng) for _ in p]
solver = GlobalSolver(len(p), nbw, H)
q = solver.solve(p, nbw, R, H)
e = energy(p, q, nbw, R)
for _ in range(20):
d = [(0.0, 0.0, 0.0) if i in H else tuple(rng.gauss(0, 1e-3) for _ in range(3)) for i in range(len(p))]
q2 = [tuple(a + b for a, b in zip(x, y)) for x, y in zip(q, d)]
assert energy(p, q2, nbw, R) >= e - 1e-12
def test_bending_a_bar_keeps_its_shape() -> None:
p, f = bar()
H = bent_bar_handles(p)
q, _ = arap(p, f, H, iterations=30)
nbw = weight_lists(len(p), f, p)
ident = [[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] for _ in p]
naive = GlobalSolver(len(p), nbw, H).solve(p, nbw, ident, H)
rho = 8 / math.pi
arc_mid = (0.0, -rho * (1 - math.cos(math.pi / 4)), -2 + rho * math.sin(math.pi / 4))
mid = [i for i, x in enumerate(p) if x[2] == 0.0]
def centre(x):
return tuple(sum(x[i][c] for i in mid) / len(mid) for c in range(3))
assert norm(sub(centre(q), arc_mid)) < 0.02
assert norm(sub(centre(naive), arc_mid)) > 0.5
def worst_stretch(x):
return max(abs(norm(sub(x[i], x[j])) / norm(sub(p[i], p[j])) - 1) for i, j in edges(f))
assert worst_stretch(q) < 0.2 < 0.9 < worst_stretch(naive)
def test_negative_cotangent_weights_are_refused() -> None:
p = [(0.0, 0.0, 0.0), (1.0, -0.1, 0.0), (2.0, 0.0, 0.0), (1.0, 0.1, 0.0)]
f = [(0, 1, 2), (0, 2, 3)]
with pytest.raises(ValueError):
weight_lists(4, f, p)
assert all(w == 1.0 for row in weight_lists(4, f, p, "uniform") for _, w in row)
def test_the_sign_of_a_weight_is_exact() -> None:
# four points on the circle of radius 5: the angles opposite the edge 0-2 add to 180 degrees, so w_02 = 0
p = [(5.0, 0.0, 0.0), (4.0, 3.0, 0.0), (0.0, 5.0, 0.0), (-3.0, -4.0, 0.0)]
f = [(0, 1, 2), (0, 2, 3)]
assert cotan_sign(p, 0, 2, [1, 3]) == 0
assert dict(weight_lists(4, f, p)[0])[2] == 0.0
q = [(5.0, 0.0, 0.0), (4.0, 3.0, 0.0), (0.0, 5.0, 0.0), (-3.0, -4.000001, 0.0)] # just outside: still >= 0
assert cotan_sign(q, 0, 2, [1, 3]) == 1
q[3] = (-3.0, -3.999999, 0.0) # just inside the circle: the angles add to more than 180 degrees
assert cotan_sign(q, 0, 2, [1, 3]) == -1
History
In 2000 Alexa, Cohen-Or and Levin used the phrase as-rigid-as-possible for the interpolation between two shapes that turns their simplices instead of moving their vertices along straight lines. In 2004 Sorkine and coauthors edited surfaces through their Laplacian coordinates, which keeps local detail but does not turn it. In 2005 Igarashi, Moscovich and Hughes deformed 2D shapes with handles, keeping each triangle as rigid as possible. In 2007 Sorkine and Alexa gave each vertex cell of a surface its own rotation, wrote a single energy for the whole surface, and minimized it by the alternation of a local fit of the rotations and a global linear solve with a fixed matrix. The same local and global steps were later used for parameterization, for meshes of tetrahedra, and for the simulation of elastic objects.
References
- Olga Sorkine and Marc Alexa, As-rigid-as-possible surface modeling, Proceedings of the Eurographics Symposium on Geometry Processing, 2007, 109 to 116, the energy of the vertex cells, the best rotation of a cell by a 3 by 3 singular value decomposition, the linear system with the averaged rotations, the cotangent weights, and the alternation of the two steps
- Marc Alexa, Daniel Cohen-Or and David Levin, As-rigid-as-possible shape interpolation, Proceedings of SIGGRAPH 2000, 157 to 164, the name as-rigid-as-possible, and the interpolation of two shapes through the rotations of their simplices
- Takeo Igarashi, Tomer Moscovich and John F. Hughes, As-rigid-as-possible shape manipulation, ACM Transactions on Graphics 24(3), 2005, 1134 to 1141, the interactive deformation of a 2D shape by handles, with an error that tries to keep each triangle rigid
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag QG8W8W Edit this page History Report an error Markdown