Algorithmresearch
Smooth skinning decomposition with rigid bones
Also called SSDR.
Fit bone transforms and sparse convex skinning weights to a sequence of example meshes by alternating least squares, to compress mesh animation.
- Solves
- Character skinning
- Time
- O(n 2^B (B^3 + B^2 F) + B F n K) iteration
- Space
- O(n B + B F) extra
- Where
- B = the number of bones; F = the number of frames; K = the largest number of bones per vertex; n = the number of vertices
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Smooth skinning decomposition with rigid bones (SSDR) takes an animation given as a sequence of meshes and finds a skeleton-free linear blend skinning model that reproduces it. The output is a set of bones, one rigid transform per bone and frame, and skinning weights per vertex. The weights are nonnegative, sum to 1 and have only a few nonzero entries per vertex, so the model plays in any engine that supports linear blend skinning. Le and Deng (2012) fit the model by alternating least squares: fix the bones and solve for the weights, then fix the weights and solve for each bone. Uses are the compression of mesh animations, such as a cloth or a muscle simulation, and the conversion of such data to a rig that a game engine can play.
In plain words
You have a simulation that moves thousands of vertices in each frame, and you want to replay it cheaply. Linear blend skinning moves each vertex as a weighted average of a few rigid motions. If you can find a few rigid motions and a few weights per vertex that explain the data well, you store much less: one transform per bone and frame, and a few weights per vertex. SSDR finds them. It starts by grouping the vertices that move together, with k-means, and fits one rigid motion to each group. Then it repeats two steps. With the motions fixed, each vertex gets the best few weights. With the weights fixed, each bone gets the best rigid motion in each frame, which is a classic problem with a closed form solution. Each step can only lower the error.
The problem
The input is a rest mesh with vertices , , and example meshes with the vertices . The unknowns are the rigid transforms for the bones and the frames , and the weights . The problem is
subject to , , at most nonzero per vertex, and a rotation. The number of bones and the sparsity are inputs. The problem is not convex, and the sparsity constraint is combinatorial, so the method finds a local minimum.
The algorithm
SSDR(rest v, frames q, bones B, sparsity K)- 1
cluster the vertex trajectories with k-means into B groups; fit one rigid transform per group and frame; give each vertex weight 1 for its group - 2
repeat - 3
for each vertex i: w_i ← the least squares weights over the simplex, using all bones - 4
keep the K largest entries of w_i and solve again on them only - 5
if the old weights of i give a smaller error, keep the old weights - 6
for each bone b and frame f: r_(f,i) ← q_(f,i) minus the part of the other bones, for every vertex i - 7
(R_(f,b), T_(f,b)) ← the weighted Procrustes fit of w_(i,b) v_i to r_(f,i) - 8
until the error decreases by less than a tolerance - 9
return the weights and the transforms
Line L3 is a small least squares problem per vertex: stack the positions of vertex over all frames as one column per bone, and find the convex combination of the columns closest to the stacked targets.
The paper solves it with an active set method for least squares with nonnegative weights that sum to 1.
The code in impl/python is for a few bones, so it tries every support: on each support it solves the equality-constrained system of the KKT conditions and keeps the solution if it is nonnegative.
This gives the exact minimizer over the simplex.
Line L4 makes the weights sparse. Line L5 is a safeguard that this code adds, not a step of the paper: the sparse solution is the best on its support but can be worse than the old weights, and the safeguard keeps the error monotone.
Lines L6 and L7 update one bone with all other bones and all weights fixed. With , the problem is , a Kabsch problem with weights. The centers are and , the rotation comes from the singular value decomposition of the cross covariance of and , and . In 2D the rotation angle is of the sums of the cross and dot products, so the code needs no SVD.
The code works in 2D with rigid transforms . The paper also re-initializes bones that end up with too few vertices; the code does not need this for its test data.
Example
The weight step for one vertex with two bones and one 2D frame: let the two candidate positions be for bone 1 and for bone 2.
| target | weights | squared error |
|---|---|---|
| 0 | ||
| 0.5 | ||
| 1 |
The target is on the segment between the two positions, so the error is zero. The target projects onto the middle of the segment, and the distance is . The target projects onto the line beyond , at the weights , which are not allowed, so the best convex weights are with the squared error .
In the tests, a strip of 39 vertices is skinned to a chain of three bones in six poses, with blended weights near the two joints. From the k-means start, the error goes from 0.0798 to in 40 iterations with , and it never increases. With , every vertex follows one bone, and the error stops at 0.0753.
Correctness
The proofs are in proofs/correctness.md.
- The weight step is exact. The minimizer over the simplex is the solution of the KKT system on its support, so trying every support and keeping the best nonnegative solution gives the minimizer.
- The bone step is exact. The weighted Procrustes formula gives the global minimizer over rotations and translations of the error of one bone in one frame, with the rest fixed.
- The error does not increase. Line L5 makes the weight step at least as good as the old weights, and each bone step is exact, so it is at least as good as the old transform.
- The ground truth is a fixed point. If the data come from linear blend skinning with weights and bones of the allowed form, the true weights and bones give the error zero, and no step can leave the zero error.
A monotone error that is bounded below converges, but the limit can be a poor local minimum, and nothing bounds its distance to the global one. Le and Deng show convergence in their experiments, not in a proof.
Proof: Each step of the skinning decomposition is an exact minimization, and the error does not increasefull
We use the notation of the page. For one vertex , let be the stacked positions over the frames, and the stacked targets , with in the code. The error of vertex is with , and . The arithmetic is exact.
The weight step
Let for a set of bones.
Lemma 1. For a support , if the matrix
is invertible, its solution of gives the unique minimizer of over the affine set , when has full column rank.
Proof. On this set, is a convex quadratic in , and the Lagrange conditions of subject to are and , which is the system above up to the sign of . For a convex problem with linear constraints, these conditions are sufficient, and the minimizer is unique when is positive definite.
Theorem 1. simplex_lsq(A, y, S) returns a minimizer of over , when every with has full column rank.
Proof. is compact and is continuous, so a minimizer exists. Let be the support of . Then minimizes over the relative interior of , which is open in the affine set of Lemma 1, so it is a local and therefore a global minimizer of the convex over that affine set. By Lemma 1, the code finds when it tries the support , and is nonnegative, so it is a candidate. Every other candidate is a point of , so its error is at least , and the code returns a point with the error .
If a matrix is singular, the code skips . The minimizer over then still has a support with an invertible whenever has full column rank, because a subset of independent columns is independent. For the tests, the columns are random or come from distinct rigid motions, and the rank condition holds.
Corollary. Line L3 gives the minimizer over all of the simplex, and line L4 gives the minimizer over for the set of the largest entries, which has at most nonzero entries. Line L5 then returns the weights with . The old weights are feasible: they are one-hot after line L1, and every later value comes from line L4 or line L5.
The bone step
Theorem 2. Fix all weights, all bones except , and the frame . Let , and , with from line L6, and assume . Then of line L7 minimizes over all rotations and translations .
Proof. The error of frame is , by the definition of . For fixed , is a convex quadratic in with the gradient . It is zero at , which is the minimizer in . With this , . Let and . Then , because keeps lengths. So minimizing over is maximizing . In 2D, with the rotation by , , where is the scalar cross product. This is with , which is largest at , the angle of line L7. Every rotation has this form, so is the global minimizer.
In 3D, the same reduction gives the Kabsch problem , which the SVD solves. If , the bone has no influence, does not depend on , and any value is a minimizer; the code returns the identity.
The error does not increase
Theorem 3. The values errors[k] returned by ssdr are nonincreasing in .
Proof. One iteration first replaces the weights of every vertex. is the sum of the , and each depends only on the weights of vertex for fixed bones, so by the Corollary does not increase. Then it replaces bone in turn. For fixed weights and other bones, is the sum over the frames of the of Theorem 2, and the transforms of bone in different frames appear in different terms, so the new transforms minimize over bone , and the old transforms are feasible. So does not increase in any step.
, so the values converge. The theorem does not say that the limit is a global minimum, or that the weights and bones converge.
The ground truth is a fixed point
Theorem 4. If with and at most nonzero entries per vertex, then from one iteration keeps .
Proof. and at the start, and by Theorem 3 does not increase.
The check values
With and , the set is the segment from to . For , the point gives , so . For , the support gives , and , so , and . For , the support gives , , so and , which is not allowed. The support gives , and the support gives , so the result is with .
Complexity
The costs are in the real RAM model, for one iteration. The weight step of the code solves up to systems of size at most per vertex, each built from dot products of length , so it costs . The active set method of the paper replaces the factor by the number of its iterations, which is small in practice. Each bone step costs , because each vertex has at most nonzero weights, so all bones cost . The extra space is for the weights and for the transforms.
Properties
- Output fits standard pipelines: the result is plain linear blend skinning with rigid bones and convex, sparse weights.
- Monotone in this code: the error does not increase over the iterations.
- Local: the result depends on the k-means start and can be a local minimum.
- No hierarchy: the bones are free rigid transforms, not a skeleton with joints.
- Lossy: with few bones, the error of a nonrigid motion, such as cloth, does not go to zero.
Variants and improvements
- Skinning mesh animations. James and Twigg (2005) also fit a skinning model to mesh animations, starting from groups of triangles that rotate together.
- Skeleton extraction. Later work fits a hierarchy of bones with joints, so that the result is a skeleton an animator can use.
- Better weights. Instead of the per vertex simplex fit, one can add smoothness of the weights over the mesh, which helps when the examples do not cover all motions.
- Corrections. Residual errors can be stored as per pose corrections, as in pose space deformation.
- Other skinning models. The same alternating fit works with dual quaternion skinning, with a harder bone step.
- Linear compression. Principal component analysis of the frames is the main alternative for the compression of mesh animations, but its output is not a rig.
When to use it
Use SSDR when you have an animation as a sequence of meshes, for example from a simulation or a capture, and you want to play it in a real-time engine that supports only linear blend skinning. It is also useful to compress such data, and to start a rig from examples. If the deformation is far from rigid pieces, such as a wave on water, a skinning model with few bones fits poorly. If you already have a skeleton and want weights for it, use automatic rigging or bounded biharmonic weights instead.
Pitfalls
- The number of bones. It is an input. Too few bones give a large error, and too many give bones with few vertices that fit noise.
- The start. k-means can split a rigid part into two clusters or join two parts. Run with several seeds and keep the best fit.
- Sparse weights can be worse. Keeping the largest weights of the full solution does not give the best weights with entries. Without a safeguard such as line L5, the error can increase.
- Rounding of the weights. On a support of one bone, the weight is exactly 1 in theory, but a linear solve can give . The code sets it to 1, so the tests that compare the weights exactly pass.
- Bones with too few vertices. A bone with fewer than three vertices of weight is not determined in 3D. The paper re-initializes such bones.
- Few frames. With few example frames, the weights are not determined, and the result does not generalize to new poses.
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
# 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
skinning_decomposition.py 219 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/skinning-decomposition/. The authors are listed in prov/H700TR.jsonl.
"""Smooth skinning decomposition with rigid bones (SSDR, Le and Deng 2012), in 2D.
Input: rest vertices v_i and example meshes q_(f,i) for the frames f. Output:
weights w_(i,b) and one rigid transform (R_(f,b), T_(f,b)) per frame and bone,
so that linear blend skinning reproduces the examples:
E = sum_f sum_i | q_(f,i) - sum_b w_(i,b) (R_(f,b) v_i + T_(f,b)) |^2.
The weights are nonnegative, sum to 1 and have at most K nonzero entries per
vertex. The method alternates two steps.
- Weights, per vertex: least squares over the simplex. This code solves it
exactly for a few bones by trying every support (the equality-constrained
solution on each support, kept if it is nonnegative), then keeps the K
largest weights and solves again on them. If the sparse weights give a
larger error than the old weights of the vertex, the old ones are kept;
this safeguard is ours, not the paper's.
- Bones, one at a time with the others fixed, per frame: a weighted
Procrustes problem with a closed form solution.
The initial bones come from k-means on the vertex trajectories and a rigid
fit per cluster.
"""
import itertools
import math
import random
from anim import cross2, dot, solve
def transform(rt, v):
"""Apply (theta, (tx, ty)) to a 2D point."""
theta, t = rt
c, s = math.cos(theta), math.sin(theta)
return (c * v[0] - s * v[1] + t[0], s * v[0] + c * v[1] + t[1])
def skin(rest, weights, bones, f):
"""Return the skinned mesh of frame f; bones[b][f] = (theta, t)."""
out = []
for v, w in zip(rest, weights):
x = y = 0.0
for b, wb in enumerate(w):
if wb != 0.0:
p = transform(bones[b][f], v)
x += wb * p[0]
y += wb * p[1]
out.append((x, y))
return out
def error(rest, frames, weights, bones):
"""Return E, the sum of squared distances over all frames and vertices."""
e = 0.0
for f, q in enumerate(frames):
for p, r in zip(skin(rest, weights, bones, f), q):
e += (p[0] - r[0]) ** 2 + (p[1] - r[1]) ** 2
return e
def weighted_procrustes(points, targets, w):
"""Return (theta, t) minimizing sum_i |targets_i - w_i (R points_i + t)|^2."""
sw2 = sum(x * x for x in w)
if sw2 == 0.0:
return 0.0, (0.0, 0.0)
pbar = tuple(sum(x * x * p[k] for x, p in zip(w, points)) / sw2 for k in range(2))
qbar = tuple(sum(x * r[k] for x, r in zip(w, targets)) / sw2 for k in range(2))
sc = sd = 0.0
for x, p, r in zip(w, points, targets):
pt = (x * (p[0] - pbar[0]), x * (p[1] - pbar[1]))
qt = (r[0] - x * qbar[0], r[1] - x * qbar[1])
sc += cross2(pt, qt)
sd += dot(pt, qt)
theta = math.atan2(sc, sd)
c, s = math.cos(theta), math.sin(theta)
t = (qbar[0] - (c * pbar[0] - s * pbar[1]), qbar[1] - (s * pbar[0] + c * pbar[1]))
return theta, t
def simplex_lsq(cols, target, allowed):
"""Return the w >= 0 with sum 1 and support in allowed minimizing |sum_b w_b cols_b - target|^2.
cols[b] is a vector; every support inside allowed is tried.
"""
best, best_e = None, math.inf
for r in range(1, len(allowed) + 1):
for sup in itertools.combinations(allowed, r):
k = len(sup)
a = [[0.0] * (k + 1) for _ in range(k + 1)]
rhs = [0.0] * (k + 1)
for i, bi in enumerate(sup):
for j, bj in enumerate(sup):
a[i][j] = 2.0 * dot(cols[bi], cols[bj])
a[i][k] = a[k][i] = 1.0
rhs[i] = 2.0 * dot(cols[bi], target)
rhs[k] = 1.0
try:
sol = solve(a, rhs)
except ValueError:
continue
if min(sol[:k]) < 0.0:
continue
w = [0.0] * len(cols)
if k == 1:
sol[0] = 1.0 # the only point of a one-bone simplex, without rounding
for i, bi in enumerate(sup):
w[bi] = sol[i]
res = [-t for t in target]
for b in sup:
res = [x + w[b] * y for x, y in zip(res, cols[b])]
e = dot(res, res)
if e < best_e:
best, best_e = w, e
return best, best_e
def vertex_columns(v, bones, nframes):
"""Return, per bone, the stacked positions of v under the bone over all frames."""
cols = []
for bone in bones:
col = []
for f in range(nframes):
col.extend(transform(bone[f], v))
cols.append(col)
return cols
def update_weights(rest, frames, weights, bones, k_max):
"""Return the new weights of every vertex (the weight step)."""
nb = len(bones)
out = []
for i, v in enumerate(rest):
cols = vertex_columns(v, bones, len(frames))
target = [c for q in frames for c in q[i]]
w, _ = simplex_lsq(cols, target, list(range(nb))) # @line L3
keep = sorted(range(nb), key=lambda b: -w[b])[:k_max]
w, e = simplex_lsq(cols, target, sorted(keep)) # @line L4
old = weights[i]
res = [-t for t in target]
for b in range(nb):
if old[b] != 0.0:
res = [x + old[b] * y for x, y in zip(res, cols[b])]
if dot(res, res) < e: # @line L5
w = list(old)
out.append(w)
return out
def update_bone(rest, frames, weights, bones, b):
"""Return the new transforms of bone b for all frames, with the others fixed."""
w = [weights[i][b] for i in range(len(rest))]
new = []
for f, q in enumerate(frames):
targets = []
for i, v in enumerate(rest): # @line L6
r = list(q[i])
for c, wc in enumerate(weights[i]):
if c != b and wc != 0.0:
p = transform(bones[c][f], v)
r[0] -= wc * p[0]
r[1] -= wc * p[1]
targets.append(tuple(r))
new.append(weighted_procrustes(rest, targets, w)) # @line L7
return new
def kmeans(points, k, rng, iters=100):
"""Return the cluster index of each point (Lloyd's algorithm, k-means++ seeding)."""
centers = [points[rng.randrange(len(points))]]
while len(centers) < k:
d = [min(sum((a - b) ** 2 for a, b in zip(p, c)) for c in centers) for p in points]
r = rng.random() * sum(d)
acc = 0.0
for p, x in zip(points, d):
acc += x
if acc >= r:
centers.append(p)
break
labels = None
for _ in range(iters):
new = [min(range(k), key=lambda j: sum((a - b) ** 2 for a, b in zip(p, centers[j]))) for p in points]
if new == labels:
break
labels = new
for j in range(k):
members = [p for p, lab in zip(points, labels) if lab == j]
if members:
centers[j] = tuple(sum(c) / len(members) for c in zip(*members))
return labels
def initialize(rest, frames, nbones, rng):
"""Return (weights, bones) from k-means on the trajectories and a rigid fit per cluster."""
traj = [tuple(c for q in frames for c in q[i]) for i in range(len(rest))]
labels = kmeans(traj, nbones, rng)
weights = [[1.0 if labels[i] == b else 0.0 for b in range(nbones)] for i in range(len(rest))]
bones = []
for b in range(nbones):
w = [weights[i][b] for i in range(len(rest))]
bones.append([weighted_procrustes(rest, q, w) for q in frames])
return weights, bones
def ssdr(rest, frames, nbones, k_max=2, iters=30, seed=0, tol=1e-12):
"""Return (weights, bones, errors), errors[0] being the error after initialization."""
rng = random.Random(seed)
weights, bones = initialize(rest, frames, nbones, rng) # @line L1
errors = [error(rest, frames, weights, bones)]
for _ in range(iters): # @line L2
weights = update_weights(rest, frames, weights, bones, k_max)
for b in range(nbones):
bones[b] = update_bone(rest, frames, weights, bones, b)
errors.append(error(rest, frames, weights, bones))
if errors[-2] - errors[-1] <= tol * (1.0 + errors[-2]): # @line L8
break
return weights, bones, errors # @line L9
test_skinning_decomposition.py 166 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/skinning-decomposition/. The authors are listed in prov/H700TR.jsonl.
"""Tests of smooth skinning decomposition with rigid bones.
The weight step is checked against a brute force search over a grid of the
simplex and against the KKT conditions, and the bone step against a brute
force search over the angle. The error does not increase over the
iterations, the ground truth is a fixed point, and data made by linear blend
skinning is fitted closely from the k-means start. The weights are
nonnegative, sum to 1 and have at most K nonzero entries. The check values of
the page hold.
"""
import math
import random
from skinning_decomposition import (
error,
simplex_lsq,
skin,
ssdr,
transform,
update_bone,
update_weights,
weighted_procrustes,
)
REST = [(0.25 * k, y) for k in range(13) for y in (-0.2, 0.0, 0.2)]
def true_weights(x):
if x <= 0.75:
return [1.0, 0.0, 0.0]
if x < 1.25:
t = (x - 0.75) / 0.5
return [1.0 - t, t, 0.0]
if x <= 1.75:
return [0.0, 1.0, 0.0]
if x < 2.25:
t = (x - 1.75) / 0.5
return [0.0, 1.0 - t, t]
return [0.0, 0.0, 1.0]
def chain(a, b, c):
def child(theta, pivot, parent):
pt = transform(parent, pivot)
th = parent[0] + theta
co, si = math.cos(th), math.sin(th)
return (th, (pt[0] - (co * pivot[0] - si * pivot[1]), pt[1] - (si * pivot[0] + co * pivot[1])))
b0 = (a, (0.0, 0.0))
b1 = child(b, (1.0, 0.0), b0)
return [b0, b1, child(c, (2.0, 0.0), b1)]
POSES = [(0, 0, 0), (0.3, 0.5, -0.4), (-0.2, 0.8, 0.6), (0.5, -0.6, 0.9), (0.1, 1.0, -0.8), (-0.4, -0.3, 0.3)]
W_TRUE = [true_weights(v[0]) for v in REST]
B_TRUE = [[chain(*p)[b] for p in POSES] for b in range(3)]
FRAMES = [skin(REST, W_TRUE, B_TRUE, f) for f in range(len(POSES))]
def sq(cols, w, target):
r = [-t for t in target]
for b, wb in enumerate(w):
r = [x + wb * y for x, y in zip(r, cols[b])]
return sum(x * x for x in r)
def test_simplex_lsq_against_a_grid():
rng = random.Random(1)
for _ in range(20):
cols = [[rng.gauss(0, 1) for _ in range(6)] for _ in range(3)]
target = [rng.gauss(0, 1) for _ in range(6)]
w, e = simplex_lsq(cols, target, [0, 1, 2])
assert all(x >= 0.0 for x in w) and abs(sum(w) - 1.0) < 1e-12
assert abs(e - sq(cols, w, target)) < 1e-9
steps = 60
best = min(
sq(cols, (i / steps, j / steps, 1 - (i + j) / steps), target)
for i in range(steps + 1)
for j in range(steps + 1 - i)
)
assert e <= best + 1e-12
def test_simplex_lsq_kkt():
rng = random.Random(2)
for _ in range(20):
cols = [[rng.gauss(0, 1) for _ in range(8)] for _ in range(4)]
target = [rng.gauss(0, 1) for _ in range(8)]
w, _ = simplex_lsq(cols, target, [0, 1, 2, 3])
r = [-t for t in target]
for b in range(4):
r = [x + w[b] * y for x, y in zip(r, cols[b])]
g = [2.0 * sum(x * y for x, y in zip(c, r)) for c in cols]
lam = min(g[b] for b in range(4) if w[b] > 1e-12)
for b in range(4):
if w[b] > 1e-12:
assert abs(g[b] - lam) < 1e-8
else:
assert g[b] >= lam - 1e-8
def test_weighted_procrustes_against_an_angle_search():
rng = random.Random(3)
pts = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(10)]
tg = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(10)]
w = [rng.uniform(0, 1) for _ in range(10)]
def cost(theta, t):
return sum(
(r[0] - x * transform((theta, t), p)[0]) ** 2 + (r[1] - x * transform((theta, t), p)[1]) ** 2
for x, p, r in zip(w, pts, tg)
)
def best_t(theta):
sw2 = sum(x * x for x in w)
c, s = math.cos(theta), math.sin(theta)
return tuple(
sum(x * (r[k] - x * (c * p[0] - s * p[1] if k == 0 else s * p[0] + c * p[1])) for x, p, r in zip(w, pts, tg))
/ sw2
for k in range(2)
)
theta, t = weighted_procrustes(pts, tg, w)
e = cost(theta, t)
grid = min(cost(a, best_t(a)) for a in (2 * math.pi * i / 3600 for i in range(3600)))
assert e <= grid + 1e-12
def test_ground_truth_is_a_fixed_point():
w = update_weights(REST, FRAMES, W_TRUE, B_TRUE, 2)
assert error(REST, FRAMES, w, B_TRUE) < 1e-20
bones = [list(b) for b in B_TRUE]
for b in range(3):
bones[b] = update_bone(REST, FRAMES, w, bones, b)
assert error(REST, FRAMES, w, bones) < 1e-20
def test_error_does_not_increase_and_fit_is_close():
w, bones, errs = ssdr(REST, FRAMES, 3, k_max=2, iters=40, seed=0)
assert all(errs[i + 1] <= errs[i] + 1e-12 for i in range(len(errs) - 1))
assert errs[-1] < 1e-5 * errs[0]
for row in w:
assert all(x >= 0.0 for x in row)
assert abs(sum(row) - 1.0) < 1e-12
assert sum(1 for x in row if x > 0.0) <= 2
def test_sparsity_one_bone_per_vertex():
w, _, errs = ssdr(REST, FRAMES, 3, k_max=1, iters=10, seed=0)
assert all(sorted(row) == [0.0, 0.0, 1.0] for row in w)
assert all(errs[i + 1] <= errs[i] + 1e-12 for i in range(len(errs) - 1))
def test_check_values_of_the_page():
cols = [[1.0, 0.0], [0.0, 1.0]]
for target, want, e_want in (
([0.5, 0.5], [0.5, 0.5], 0.0),
([1.0, 1.0], [0.5, 0.5], 0.5),
([2.0, 0.0], [1.0, 0.0], 1.0),
):
w, e = simplex_lsq(cols, target, [0, 1])
assert all(abs(a - b) < 1e-12 for a, b in zip(w, want))
assert abs(e - e_want) < 1e-12
History
Fitting a skinning model to examples was studied before SSDR, for example by James and Twigg (2005). Bones that are general affine maps can fit more motions, but many engines expect rigid bones, and weights without constraints are hard to edit. Le and Deng (2012) kept the bones rigid and the weights convex and sparse, and showed that alternating least squares with these constraints fits many mesh animations with a small number of bones. The method is now a common way to convert simulations to rigs for games.
References
- Binh Huy Le and Zhigang Deng, Smooth skinning decomposition with rigid bones, ACM Transactions on Graphics 31(6), SIGGRAPH Asia 2012, article 199, the formulation of the fit as linear blend skinning with rigid bones and nonnegative, affine and sparse weights, the k-means initialization, the weight update and the bone update by weighted Procrustes (general locator)
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 H700TR Edit this page History Report an error Markdown