Algorithmadvanced
Pose space deformation
Also called pose-space deformation.
Add sculpted corrective offsets to the skinned mesh, interpolated over the space of poses by radial basis functions.
- Solves
- Character skinning
- Time
- O(m j + j + n (m + k)) frameO(m^3 + m^2 n + m n k) training
- Space
- O(m n + m^2) extra
- Where
- j = the number of joints; k = the largest number of joints per vertex; m = the number of example poses; n = the number of vertices
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Pose space deformation (PSD) fixes the shapes that linear blend skinning gets wrong, such as a collapsing elbow or a flat biceps. An artist poses the skeleton, sculpts the mesh as it should look in that pose, and stores the result as an example. PSD turns each sculpt into a corrective offset in the rest frame of the mesh, and at any new pose it computes the offset by radial basis function interpolation over the pose space. The corrected rest mesh then goes through the skinning as usual. Lewis, Cordner and Fong (2000) introduced the method, and it is the base of most corrective shape systems in production rigs.
In plain words
Skinning gives a good shape for most poses, but not for all of them. For the poses where it fails, an artist fixes the mesh by hand: these are the examples. Now the character moves to a pose that is between the examples. PSD asks how close the new pose is to each example, and mixes the fixes by that closeness. Near an example, its fix counts the most; far from all examples, no fix applies and the plain skinning shows. The fixes are stored as if the character were in its rest pose, and they are added before the skinning. So a fix made with the arm bent still sits on the right part of the arm when the arm also turns.
The problem
The input is a skinned mesh: rest vertices , skinning weights, and the bind transforms of joints, as for linear blend skinning. A pose is a vector of joint parameters, for example joint angles. The artist gives example poses and for each a sculpted mesh in the posed space. The output is a function that maps any pose to a mesh that equals the sculpt at every example pose, equals the plain skinning where no example is near, and varies smoothly in between.
Let be the blended skinning matrix of vertex , so that plain skinning gives . The kernel is the Gaussian . The width is tuning: it sets how far the influence of an example reaches in pose space.
The algorithm
PSD-TRAIN(v, A, p₁ … p_m, s₁ … s_m, σ)- 1
for each example e and vertex i: d_e,i ← A_i(p_e)⁻¹ s_e,i - vᵢ ▷ the correction in the rest frame - 2
Φ_ef ← φ(‖p_e - p_f‖) for all pairs of examples - 3
solve Φ C = D ▷ one coefficient per example, vertex and coordinate PSD-DEFORM(p)- 4
for each example e: r_e ← φ(‖p - p_e‖) - 5
for each vertex i do - 6
uᵢ ← vᵢ + Σ_e r_e C_e,i ▷ the corrected rest vertex - 7
v′ᵢ ← A_i(p) uᵢ ▷ plain skinning of the corrected vertex - 8
return v′
Line L1 inverts the skinning of each sculpted vertex. The sculpt tells where the vertex must be in the posed space, and maps that point back to the rest frame, where the correction is a fixed offset. Lines L2 and L3 are RBF interpolation: one dense matrix for all vertices, with right-hand sides in 2D (or in 3D). Lines L4 to L7 run every frame.
The code in impl/python does this for a planar chain of two joints with LBS in homogeneous form.
The paper uses skeleton subspace deformation, its name for LBS, as the base layer; any skinning that is invertible per vertex works the same way.
Example
Take one joint angle and one vertex, and track only the size of its correction along the normal. The examples are with (the rest pose needs no fix) and with (a bulge at the bent elbow), with .
Then , and gives and .
| correction | |
|---|---|
The correction is exact at both examples and falls off on both sides of .
At , halfway, it is with , much less than the half of 0.1 that linear interpolation would give.
That is a property of the Gaussian with this , and a wider gives a value closer to 0.05.
The tests in impl/python check these numbers and the full 2D case.
Correctness
The proofs are in proofs/correctness.md. They hold in exact arithmetic, for distinct example poses and invertible blended matrices .
- The system has one solution. The Gaussian kernel is strictly positive definite on , so is symmetric positive definite for distinct poses. This is a proved property of the Gaussian (a theorem of Bochner type, see radial basis function interpolation).
- Examples are reproduced. At , the interpolant gives , so line L7 gives , the sculpt.
- No sculpt, no change. If every sculpt equals plain skinning, every , so and PSD equals plain skinning at every pose.
- Far poses. The correction is bounded by , which tends to 0 as moves away from all examples.
- Corrections move with the bones. Because the offset is added before skinning, a rigid motion of the whole skeleton moves the corrected shape rigidly. An offset added after skinning, in world space, does not.
The tests check all of these, the last one by turning the root joint of the chain.
Proof: Pose space deformation reproduces its examples, reduces to plain skinning without sculpts, and moves corrections with the bonesfull
We use the notation of the page. The example poses are distinct, every blended matrix is invertible, and with . For a vertex , the interpolated correction at a pose is , and the output of line L7 is . The arithmetic is exact.
The interpolation system
Lemma 1. is symmetric positive definite, so line L3 has exactly one solution.
Proof. is symmetric because the distance is symmetric. The Gaussian is the Fourier transform of a positive Gaussian, so by Bochner's theorem it is a positive definite function on , and since its Fourier transform is positive everywhere, the quadratic form is positive for distinct points and . In detail: with the Fourier transform of the kernel, . The integrand is nonnegative, and it is zero almost everywhere only if the exponential sum vanishes on an open set, which for distinct forces , because exponentials with distinct frequencies are linearly independent.
Reproduction and the plain case
Theorem 1. For every example and vertex , .
Proof. Line L3 makes , and , so . By line L1, . So .
Theorem 2. If for every and , then for every pose .
Proof. Line L1 gives . By Lemma 1 the only solution of is , so for every .
Theorem 3. , where is the distance from to the nearest example pose. So the correction tends to 0, and when the blended matrices stay bounded, as moves away from all examples.
Proof. Each , because decreases in . Apply the triangle inequality to the sum.
Corrections move with the bones
Theorem 4. Let be a rigid motion, and let a pose give the joint transforms for every joint, with the same pose distances to the examples as . Then .
Proof. . The correction depends on only through the distances to the examples, so . So .
In the test, the pose turns the root by , which multiplies every joint transform by the rotation , and the example is placed at that same pose so that the distance is 0 in both cases. If instead the correction were added after skinning, as , the result at would be , which differs from unless fixes .
The check value
For one scalar correction with , , values and , and , the system is , so . At both kernel values equal , so the correction is .
Complexity
The costs are in the real RAM model. Line L1 costs to build and invert the blended matrices. Line L2 costs , and line L3 costs to factor plus for the right-hand sides. Per frame, line L4 costs , lines L5 and L6 cost , and line L7 costs as for LBS. The extra space is for the coefficients and for . In practice is small for each region (a few examples per joint), and the corrections are sparse in , so a rig stores them like blendshape deltas.
Properties
- Interpolating: every example pose gives its sculpt exactly.
- Local in pose space with a Gaussian kernel; the reach is set by .
- Linear in the sculpts: the result depends linearly on the corrections .
- Not local on the mesh unless the sculpts are: every example can move every vertex.
- Works with any base skinning that is invertible per vertex, for example LBS or dual quaternion skinning.
- The pose space is the space of joint parameters, so the distance depends on the parameterization. Angles that wrap at need care.
Variants and improvements
- Other kernels. Lewis and others use Gaussians; thin-plate splines and other radial functions with a polynomial term also work, and they extrapolate instead of falling to 0. The choice changes the result between and outside the examples.
- Per joint pose spaces. A correction near the elbow should depend on the elbow angle only. Using a small pose vector per region keeps and small and stops unrelated joints from changing the correction.
- Weighted PSD. Later work weights the interpolation per vertex by the skinning weights, so that each vertex reacts to the joints that move it. That is a variant, not part of the original paper.
- Probabilistic interpolation. The RBF interpolant with a Gaussian kernel is the mean of a Gaussian process with that covariance and no noise; adding a noise term gives a smoother fit that no longer reproduces the examples exactly.
- Related interpolation of motions. Verbs and adverbs interpolates whole motions over a space of style parameters with radial basis functions, in the same way.
- Corrective shapes from data. Instead of sculpting, the examples can come from scans or simulation, and skinning decomposition can give the base layer.
When to use it
Use PSD when the skinning of a character is good in most poses and needs sculpted fixes in a few, for example at the elbows, knees, shoulders and hips. It is the right tool when the artist wants exact control over a shape in given poses. If the problem is the volume loss of LBS at twisted joints, try dual quaternion skinning first, and use PSD for the shapes that remain wrong.
Pitfalls
- Correcting in world space. Adding the interpolated offsets after skinning breaks as soon as the limb also turns, because the offset does not turn with it. Invert the skinning as in line L1, and add the offset before skinning.
- Singular blended matrices. can be close to singular at a strongly twisted LBS joint, and then line L1 amplifies small sculpting noise. Avoid examples at the collapse pose, or use a rigid base skinning there.
- Close examples. Two examples with nearly equal poses make ill conditioned, and the coefficients large and of opposite sign. Merge them, or use a wider or a regularized kernel.
- too small or too large. Too small, and the corrections appear only very near the examples and the mesh pops in between. Too large, and becomes ill conditioned and the examples influence each other far away. Tune per region, and in the units of the pose vector.
- No rest example. Without an example at the rest pose with zero correction, the corrections of the other examples leak into the rest pose. Add the rest pose as an example.
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
pose_space_deformation.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pose-space-deformation/. The authors are listed in prov/1BB6ZV.jsonl.
"""Pose space deformation (Lewis, Cordner and Fong 2000) on a 2D skinned mesh.
The base layer is linear blend skinning: vertex i goes to A_i(p) v_i with
A_i(p) = sum_j w_ij M_j(p) B_j^(-1), a 3 by 3 homogeneous matrix in 2D.
For each example pose p_e an artist sculpts the shape s_e. The correction
d_ei = A_i(p_e)^(-1) s_ei - v_i is stored in the rest frame, before skinning,
and it is interpolated over the poses by Gaussian radial basis functions
phi(r) = exp(-r^2 / (2 sigma^2)).
The width sigma is a tuning choice. At a pose p the mesh is
v'_i = A_i(p) (v_i + sum_e c_ei phi(|p - p_e|)),
where the coefficients c solve Phi c = d with Phi_ef = phi(|p_e - p_f|).
"""
import math
from anim import T_apply, T_inv, make_T, mul, rot2, solve
def gaussian(r, sigma):
"""Return the Gaussian radial basis function exp(-r^2 / (2 sigma^2))."""
return math.exp(-r * r / (2.0 * sigma * sigma))
def pose_distance(p, q):
"""Return the Euclidean distance between two pose vectors (joint angles)."""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(p, q)))
def chain_transforms(pose, joints):
"""World transforms of a planar chain with joints at the rest points joints[j].
Joint j turns by pose[j] about its rest point, after its parent j - 1.
Return (M, B_inv), the current and inverse bind transforms (3 by 3).
"""
m, b_inv = [], []
parent = make_T(rot2(0.0), (0.0, 0.0))
prev = (0.0, 0.0)
for j, c in enumerate(joints):
local = make_T(rot2(pose[j]), (c[0] - prev[0], c[1] - prev[1]))
parent = mul(parent, local)
m.append(parent)
b_inv.append(T_inv(make_T(rot2(0.0), c)))
prev = c
return m, b_inv
def blend(influences, m, b_inv):
"""Return A = sum_j w_j M_j B_j^(-1) for one vertex."""
a = [[0.0] * 3 for _ in range(3)]
for j, w in influences:
p = mul(m[j], b_inv[j])
for r in range(3):
for c in range(3):
a[r][c] += w * p[r][c]
return a
def skin(rest, weights, pose, joints):
"""Linear blend skinning of the rest vertices at a pose."""
m, b_inv = chain_transforms(pose, joints)
return [T_apply(blend(wi, m, b_inv), v) for v, wi in zip(rest, weights)]
def train(rest, weights, joints, poses, shapes, sigma):
"""Return the RBF coefficients c[e][i] (2D offsets) for the example poses and shapes."""
d = []
for p, s in zip(poses, shapes): # @line L1
m, b_inv = chain_transforms(p, joints)
row = []
for v, wi, si in zip(rest, weights, s):
u = T_apply(T_inv(blend(wi, m, b_inv)), si)
row.extend((u[0] - v[0], u[1] - v[1]))
d.append(row)
phi = [[gaussian(pose_distance(p, q), sigma) for q in poses] for p in poses] # @line L2
c = solve(phi, d) # @line L3
n = len(rest)
return [[(row[2 * i], row[2 * i + 1]) for i in range(n)] for row in c]
def deform(rest, weights, joints, poses, coeffs, sigma, pose):
"""Return the pose space deformation of the mesh at a new pose."""
r = [gaussian(pose_distance(pose, pe), sigma) for pe in poses] # @line L4
m, b_inv = chain_transforms(pose, joints)
out = []
for i, (v, wi) in enumerate(zip(rest, weights)): # @line L5
ox = sum(re * ce[i][0] for re, ce in zip(r, coeffs))
oy = sum(re * ce[i][1] for re, ce in zip(r, coeffs))
u = (v[0] + ox, v[1] + oy) # @line L6
out.append(T_apply(blend(wi, m, b_inv), u)) # @line L7
return out # @line L8
test_pose_space_deformation.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pose-space-deformation/. The authors are listed in prov/1BB6ZV.jsonl.
"""Tests of pose space deformation.
They check that every example pose gives its sculpted shape, that sculpts
equal to plain skinning give plain skinning at every pose, that the
corrections fade far from all examples, that the Gaussian matrix is
symmetric positive definite, that a correction moves with its bone, and the
check value of the page.
"""
import math
import random
from pose_space_deformation import deform, gaussian, skin, train
JOINTS = [(0.0, 0.0), (1.0, 0.0)]
SIGMA = 0.5
def strip():
rest, weights = [], []
for k in range(9):
x = 0.25 * k
t = min(1.0, max(0.0, (x - 0.75) / 0.5))
w1 = t * t * (3 - 2 * t)
for y in (-0.2, 0.2):
rest.append((x, y))
weights.append([(0, 1.0 - w1), (1, w1)])
return rest, weights
def sculpt(rest, weights, pose):
base = skin(rest, weights, pose, JOINTS)
out = []
for v, b in zip(rest, base):
g = max(0.0, 1.0 - abs(v[0] - 1.0) / 0.5)
amount = 0.1 * math.sin(abs(pose[1])) * g
out.append((b[0], b[1] + math.copysign(amount, v[1])))
return out
POSES = [(0.0, 0.0), (0.0, math.pi / 2), (0.0, -math.pi / 2), (math.pi / 4, math.pi / 3)]
def trained():
rest, weights = strip()
shapes = [sculpt(rest, weights, p) for p in POSES]
coeffs = train(rest, weights, JOINTS, POSES, shapes, SIGMA)
return rest, weights, shapes, coeffs
def close(a, b, tol):
return all(abs(x - y) <= tol for p, q in zip(a, b) for x, y in zip(p, q))
def test_examples_are_reproduced():
rest, weights, shapes, coeffs = trained()
for p, s in zip(POSES, shapes):
assert close(deform(rest, weights, JOINTS, POSES, coeffs, SIGMA, p), s, 1e-9)
def test_plain_skinning_sculpts_give_plain_skinning():
rest, weights = strip()
shapes = [skin(rest, weights, p, JOINTS) for p in POSES]
coeffs = train(rest, weights, JOINTS, POSES, shapes, SIGMA)
rng = random.Random(1)
for _ in range(10):
p = (rng.uniform(-1, 1), rng.uniform(-2, 2))
got = deform(rest, weights, JOINTS, POSES, coeffs, SIGMA, p)
assert close(got, skin(rest, weights, p, JOINTS), 1e-9)
def test_rest_pose_is_the_rest_mesh():
rest, weights, _, coeffs = trained()
assert close(deform(rest, weights, JOINTS, POSES, coeffs, SIGMA, (0.0, 0.0)), rest, 1e-9)
def test_corrections_fade_far_from_examples():
rest, weights, _, coeffs = trained()
p = (0.0, 6.0)
got = deform(rest, weights, JOINTS, POSES, coeffs, SIGMA, p)
assert close(got, skin(rest, weights, p, JOINTS), 1e-6)
def test_gaussian_matrix_is_positive_definite():
rng = random.Random(2)
pts = [(rng.uniform(-2, 2), rng.uniform(-2, 2)) for _ in range(8)]
phi = [[gaussian(math.dist(p, q), SIGMA) for q in pts] for p in pts]
for i in range(8):
for j in range(8):
assert phi[i][j] == phi[j][i]
for _ in range(50):
x = [rng.gauss(0, 1) for _ in range(8)]
assert sum(x[i] * phi[i][j] * x[j] for i in range(8) for j in range(8)) > 0.0
def test_correction_turns_with_the_bone():
# One example, evaluated at its own pose with the root turned: the RBF
# value is 1 in both cases, and the corrected shape turns as a whole.
rest, weights, _, coeffs = trained()
turn = 0.7
c, s = math.cos(turn), math.sin(turn)
plain = deform(rest, weights, JOINTS, [(0.0, math.pi / 2)], [coeffs[1]], SIGMA, (0.0, math.pi / 2))
turned = deform(rest, weights, JOINTS, [(turn, math.pi / 2)], [coeffs[1]], SIGMA, (turn, math.pi / 2))
assert close(turned, [(c * x - s * y, s * x + c * y) for x, y in plain], 1e-12)
def test_check_value_one_joint():
phi12 = gaussian(math.pi / 2, SIGMA)
c1 = -0.1 * phi12 / (1 - phi12 * phi12)
c2 = 0.1 / (1 - phi12 * phi12)
r = gaussian(math.pi / 4, SIGMA)
assert abs(r * (c1 + c2) - 0.1 * r / (1 + phi12)) < 1e-15
assert abs(phi12 - 0.0071918833) < 1e-9
assert abs(r * (c1 + c2) - 0.0289135) < 1e-6
History
Before PSD, production rigs mixed two separate ideas: shape interpolation between sculpted keys, driven by hand or by simple joint-angle rules, and skeleton-driven skinning. Lewis, Cordner and Fong (2000) joined them: they treated the sculpts as samples of a function on the pose space, interpolated them by radial basis functions, and applied the result in the rest frame before skinning. Their paper also pointed out why the correction must be applied before skinning and not after it.
References
- J. P. Lewis, Matt Cordner and Nickson Fong, Pose space deformation: a unified approach to shape interpolation and skeleton-driven deformation, SIGGRAPH 2000, 165-172, the sections on scattered interpolation over the pose space with Gaussian radial basis functions, and on applying the correction in the rest frame before skeleton subspace deformation (general locator)
- Ladislav Kavan, Part I, Direct skinning methods and deformation primitives, in Alec Jacobson, Zhigang Deng, Ladislav Kavan and J. P. Lewis, Skinning, Real-time Shape Deformation, SIGGRAPH 2014 course, the discussion of the artifacts of linear blend skinning that example-based corrections fix (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 1BB6ZV Edit this page History Report an error Markdown