Algorithmadvanced
Spherical blend skinning
Also called spherical skinning.
Blends the joint rotations as quaternions about a center of rotation that least squares finds for each set of joints. Each vertex moves rigidly, so twisted joints keep their volume.
- Solves
- Character skinning
- Time
- O(j + n k^2) frame
- Space
- O(j + n) extra
- Where
- j = the number of joints; k = the largest number of joints per vertex; n = the number of vertices
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Spherical blend skinning (SBS) deforms a mesh by a skeleton, like linear blend skinning, but it blends the rotations of the joints as quaternions instead of blending matrices. A rotation needs a center, and the joints that move a vertex do not share one in general. SBS finds the center by least squares, as the point that the rigid skinning transforms of the vertex's joints move the least apart, and then computes
where is the normalized weighted sum of the joint quaternions. The center depends only on the set of joints, so one center serves every vertex with the same set. Each vertex moves by a rigid transform, so a twisted joint keeps its radius and the candy wrapper artifact does not occur. SBS came two years before dual quaternion skinning, which removed the need for a center.
In plain words
Plain skinning averages the positions that each bone would give a point. When two bones turn in opposite directions, the average falls inside the limb, and the skin collapses. Spherical blend skinning averages the turns instead. It first finds a pivot point that the bones of a region agree on as well as possible. Then it turns the point about that pivot by the average turn of the bones. Because the point is only turned and moved, never squeezed, the limb keeps its thickness. Points that use the same bones share one pivot, so the extra cost is small.
The problem
The input is the rest mesh with the vertices and the normals , the weights with , and the rigid skinning transforms of the current pose, where comes from forward kinematics and is the bind pose transform. Write , with the rotation and its unit quaternion . The output is the deformed mesh. This is the character skinning problem with rigid joint transforms; SBS does not handle scale.
The algorithm
For a set of joints, the center minimizes
If the minimizer is not unique, SBS takes the one of minimal norm.
SPHERICAL-BLEND-SKINNING(V, N, W, C) ▷ rest mesh, weights, joint transforms- 1
for each vertex i - 2
J ← the set of joints with w_ij > 0 - 3
if J is not in the cache of this frame - 4
r ← minimal norm minimizer of Σ_{a<b ∈ J} |(R_a - R_b) r - (t_b - t_a)|² - 5
cache[J] ← r - 6
r_c ← cache[J] - 7
Q ← normalize(Σ_j s_j w_ij q_j) ▷ s_j = ±1, so that q_p · s_j q_j ≥ 0 for the pivot p - 8
v'_i ← Q (v_i - r_c) + Σ_j w_ij C_j r_c - 9
n'_i ← Q n_i - 10
return V', N'
Line L4 is a linear least squares problem with 3 unknowns. Its normal equations are with and . The code takes the pseudo-inverse of the symmetric matrix from its eigenvalues; an SVD of the stacked matrix is more accurate. Line L7 is QLERP, the normalized linear blend of quaternions, with the pivot taken as the joint of the largest weight; it is a cheap stand-in for a true spherical average of the rotations. Line L8 rotates the vertex about and then moves to the blend of its images; for one joint it gives .
Example
Take two joints with the weights and , , and a turn by about the axis, the twist of the candy wrapper. The center minimizes , which is zero on the whole axis, and the point of minimal norm is the origin. QLERP blends and into , the turn by about .
| vertex | LBS | SBS |
|---|---|---|
LBS collapses the vertex onto the axis; SBS turns it by half the twist and keeps the radius 1. For a twist the SBS vertex turns by exactly .
For a bend, let turn by about the axis through , the elbow. The least squares problem is zero on the line through parallel to , so . The vertex goes to , at the distance from the elbow, while LBS gives at the distance . In this example the result equals that of dual quaternion skinning.
Correctness
The proofs are in proofs/correctness.md; they are proved properties in exact arithmetic.
- In the bind pose every vertex and normal stays where it is, and a vertex with one joint moves by .
- If the joints of a set turn about a common point and the minimizer is unique, then .
- The result does not depend on which minimizer line L4 picks, so the minimal norm choice is only a way to make the choice unique.
- With the pivot alignment, the sum in line L7 has a norm of at least the pivot weight, so always exists.
- For a fixed joint set and fixed weights, the map is a rotation followed by a translation: the vertices keep their distances and the normals stay unit vectors.
- If the whole pose and mesh are moved by a rigid change of coordinates, the result moves with them.
- If is replaced by the matrix , line L8 gives linear blend skinning for any center, so the difference between the methods is only the blend of the rotations.
Proof: Spherical blend skinning moves each vertex rigidly, does not depend on the choice of the center, and is coordinate invariantfull
We use the notation of the page. The arithmetic is exact, the weights of a vertex are nonnegative with the sum 1, and each is rigid. Quaternions are in the Hamilton convention, scalar first; is a unit quaternion of , and is the dot product in . For a vertex with the joint set and the weights , let and , so that line L8 gives .
The center
Let , , and .
Lemma 1. The minimizers of are the set , where is any solution of and . Line L4 returns the unique minimizer in the orthogonal complement of .
Proof. is a convex quadratic with the gradient , so its minimizers are the solutions of , which exist because is in the range of . Two solutions differ by an element of the null space of . Since and is positive semidefinite, if and only if for all pairs, that is . The code writes and returns , which solves and is orthogonal to the null space; such a solution is unique.
Lemma 2. If for all and , then .
Proof. , so is a minimizer, and by Lemma 1 the minimizer is unique.
The rotation exists
Lemma 3. Let be the quaternion of the joint with the largest weight , and with chosen so that . Then .
Proof. , since every term is nonnegative and . because the weights sum to 1.
So is a unit quaternion, and line L7 never divides by zero.
The choice of the center does not matter
Lemma 4. If and both minimize , then .
Proof. By Lemma 1, with ; let and . Fix . For every , , so is a turn about , and for some angle . Then , where is a sum of quaternions of the form and so has this form too. Hence is the rotation after a turn about , and . Also . So .
Rigid motion per joint set
Lemma 5. For a fixed joint set and fixed weights, is a rotation by followed by a translation, and .
Proof. , and the second term does not depend on . A unit quaternion rotation keeps lengths.
So two vertices with the same joints and weights keep their distance, and normals stay unit vectors.
Lemma 6. In the bind pose, with for all , and . For a vertex with one joint, .
Proof. In the bind pose , so is the identity and . For one joint, (up to a sign that gives the same rotation), and for any .
Coordinate invariance
Lemma 7. Let be rigid, and replace by , by and by . Then the new result is and the new normal is .
Proof. Let be the unit quaternion of . The new joint quaternions are , and is an orthogonal map of , so all dot products, and so the signs , stay the same, and the new rotation is , that is . The new objective is , because keeps distances, so its minimizers are the images of the minimizers of . By Lemma 4 we may evaluate the new result at : , since and . The normal is .
Relation to linear blend skinning
Lemma 8. If in line L8 is replaced by the matrix , the result is for any .
Proof. .
The twist check value
Lemma 9. Let , the turn by about the axis, and the weights . Then , and SBS turns every vertex by about the axis. For it maps to .
Proof. is the axis and , so the minimal norm minimizer is by Lemma 1. and with , so no sign changes, and . With and , , the turn by . , so . For this is the turn by , which maps to .
Linear blend skinning maps the same vertex to for , by Lemma 8 with .
Complexity
The quaternions of the palette cost per frame. A center costs for the pairs and for the solve, and a vertex costs after that. In the worst case each vertex has its own joint set, which gives time per frame; in a real mesh most vertices share a few joint sets, and the centers add little. The cache holds at most one center per vertex, so the extra space is .
Properties
- Rigid per vertex: no volume loss under twist, unlike LBS (a proved property).
- QLERP is not the exact spherical average of the rotations; for the turn angles of real joints it is close, and the paper analyzes its error (Section 4.1). This is a heuristic choice for speed.
- The center of a set of joints is the same for all its vertices, so vertices that use the same joints with different weights turn about the same point.
- The center can jump when the least squares problem is close to rank deficient, for example when the relative turns of the joints have nearly parallel axes.
- It needs rigid joint transforms; scale and shear in are outside the method.
Variants and improvements
- Dual quaternion skinning. DQS blends rotation and translation together as dual quaternions, with no center and no least squares, and it is coordinate invariant in the same way.
- Optimized centers of rotation. CoR skinning computes a center per vertex from the weights in a precomputation, instead of per joint set in each frame, which removes the bulge of DQS in bends.
- Better rotation averages. QLERP can be replaced by a true spherical average or by rotation averaging, at a higher cost.
- Linear rotation blend. With in place of the method becomes LBS again, which shows that the center has no effect on LBS.
When to use it
Use it where twist collapse is a problem and the joint transforms are rigid, and where a per-joint-set solve per frame is acceptable. Today DQS is the usual choice for the same job, because it needs no center and runs in the same way on the GPU; SBS is mainly of interest as the step between LBS and DQS, and as the source of the idea of a center of rotation.
Pitfalls
- Cache per frame. The center depends on the pose, so the cache must be cleared every frame; it is keyed by the joint set, not by the weights.
- Sign of the quaternions. and give the same rotation; without the pivot alignment of line L7 the blend can turn the long way or reach zero.
- Rank deficiency. A set of two joints always has a line of solutions, because the relative turn of the two joints has an axis with , and a move along does not change . Without the minimal norm rule the solver fails or picks an arbitrary point.
- Large weight sets. The center of many joints is a compromise for all of them and can lie far from every joint; limit the joints per vertex to a few.
- Normals. Rotate normals by only; they are not moved by the translation.
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
spherical_blend_skinning.py 132 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spherical-blend-skinning/. The authors are listed in prov/E1S4SH.jsonl.
"""Spherical blend skinning (SBS) of Kavan and Zara (2005).
Each joint has a rigid skinning transform C_j x = R_j x + t_j (that is
P_j = M_j B_j^(-1)). For a vertex with the joint set J and the weights w_j:
1. The center of rotation r_c is the least squares solution of the
equations C_a r_c = C_b r_c for all pairs a < b in J, that is
(R_a - R_b) r_c = t_b - t_a. If the solution is not unique, the one of
minimal norm is taken. The center depends only on J, so it is cached.
2. The rotation Q is the normalized linear blend (QLERP) of the joint
quaternions after the sign alignment with a pivot.
3. v' = Q (v - r_c) + sum_j w_j C_j r_c, and the normal goes to Q n.
The minimal norm solution is N^+ g with N = D^T D and g = D^T e, where D
stacks the blocks R_a - R_b and e the blocks t_b - t_a. The pseudo-inverse
of the symmetric 3 by 3 matrix N comes from its eigenvalues (cyclic Jacobi),
with the eigenvalues at most RANK_TOL times the largest one treated as zero.
An SVD of D is more accurate, because the normal equations square its
condition number; for this small test code the eigenvalues are enough.
"""
import math
from anim import add, matvec, q_dot, q_from_mat3, q_rotate, scale, sub
RANK_TOL = 1e-12
def sym_eig3(s):
"""Eigenvalues and unit eigenvectors of a symmetric 3 by 3 matrix (cyclic Jacobi)."""
a = [list(map(float, row)) for row in s]
v = [[1.0 if i == j else 0.0 for j in range(3)] for i in range(3)]
for _ in range(60):
off = a[0][1] ** 2 + a[0][2] ** 2 + a[1][2] ** 2
if off <= 1e-32 * (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
th = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
t = math.copysign(1.0, th) / (abs(th) + math.sqrt(th * th + 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], a[k][q] = c * akp - sn * akq, sn * akp + c * akq
for k in range(3):
apk, aqk = a[p][k], a[q][k]
a[p][k], a[q][k] = c * apk - sn * aqk, sn * apk + c * aqk
for k in range(3):
vkp, vkq = v[k][p], v[k][q]
v[k][p], v[k][q] = c * vkp - sn * vkq, sn * vkp + c * vkq
return [a[i][i] for i in range(3)], [tuple(v[k][i] for k in range(3)) for i in range(3)]
def split(m):
"""Return (R, t) of a 4 by 4 rigid transform."""
return [row[:3] for row in m[:3]], (m[0][3], m[1][3], m[2][3])
def center_of_rotation(joints, palette):
"""Return the minimal norm least squares center of the joint set."""
n = [[0.0] * 3 for _ in range(3)]
g = [0.0, 0.0, 0.0]
js = sorted(joints)
for ia in range(len(js)):
ra, ta = split(palette[js[ia]])
for ib in range(ia + 1, len(js)):
rb, tb = split(palette[js[ib]])
d = [[ra[r][c] - rb[r][c] for c in range(3)] for r in range(3)]
e = (tb[0] - ta[0], tb[1] - ta[1], tb[2] - ta[2])
for r in range(3):
for c in range(3):
n[r][c] += sum(d[k][r] * d[k][c] for k in range(3))
g[r] += sum(d[k][r] * e[k] for k in range(3))
vals, vecs = sym_eig3(n)
top = max(vals)
out = [0.0, 0.0, 0.0]
for lam, u in zip(vals, vecs): # minimal norm: drop the null space
if top > 0.0 and lam > RANK_TOL * top:
c = sum(u[k] * g[k] for k in range(3)) / lam
for k in range(3):
out[k] += c * u[k]
return tuple(out)
def qlerp(influences, quats):
"""Return the normalized linear blend of the joint quaternions with aligned signs."""
pivot = quats[max(influences, key=lambda jw: jw[1])[0]]
s = [0.0, 0.0, 0.0, 0.0]
for j, w in influences:
q = quats[j]
f = -w if q_dot(pivot, q) < 0.0 else w
for k in range(4):
s[k] += f * q[k]
n = math.sqrt(q_dot(s, s))
return tuple(x / n for x in s)
def spherical_blend_skinning(vertices, weights, palette, normals=None, cache=None, linear_rotation=False):
"""Return (positions, normals) of the mesh skinned by SBS.
palette: rigid skinning matrices P_j = M_j B_j^(-1). cache: an optional
dict from joint sets to centers, kept by the caller for one frame.
linear_rotation=True replaces Q by the matrix sum_j w_j R_j, which turns
the formula into linear blend skinning (for the tests).
"""
if cache is None:
cache = {}
quats = [q_from_mat3(split(p)[0]) for p in palette]
out_v = []
out_n = [] if normals is not None else None
for i, v in enumerate(vertices): # @line L1
key = tuple(sorted(j for j, _ in weights[i])) # @line L2
if key not in cache: # @line L3
rc = center_of_rotation(key, palette) # @line L4
cache[key] = rc # @line L5
rc = cache[key] # @line L6
m = (0.0, 0.0, 0.0)
for j, w in weights[i]:
m = add(m, scale(add(matvec(split(palette[j])[0], rc), split(palette[j])[1]), w))
if linear_rotation:
a = [[sum(w * split(palette[j])[0][r][c] for j, w in weights[i]) for c in range(3)] for r in range(3)]
out_v.append(add(matvec(a, sub(v, rc)), m))
continue
q = qlerp(weights[i], quats) # @line L7
out_v.append(add(q_rotate(q, sub(v, rc)), m)) # @line L8
if normals is not None:
out_n.append(q_rotate(q, normals[i])) # @line L9
return out_v, out_n # @line L10
test_spherical_blend_skinning.py 228 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spherical-blend-skinning/. The authors are listed in prov/E1S4SH.jsonl.
"""Tests of spherical blend skinning.
They check the bind pose, the single weight case, the recovery of a common
center of rotation, the minimal norm center against a direct solve and a
zero gradient, the candy wrapper case, rigidity per joint set, the
invariance under a change of coordinates, the cache, and that the linear
rotation blend gives linear blend skinning.
"""
import math
import random
import anim
from spherical_blend_skinning import center_of_rotation, qlerp, spherical_blend_skinning
def rand_quat(rng):
return anim.q_normalize([rng.gauss(0.0, 1.0) for _ in range(4)])
def rand_rot(rng):
return anim.q_to_mat3(rand_quat(rng))
def rand_T(rng):
return anim.make_T(rand_rot(rng), tuple(rng.uniform(-2.0, 2.0) for _ in range(3)))
def about(c, r):
"""The rigid transform that rotates by r about the point c."""
return anim.make_T(r, anim.sub(c, anim.matvec(r, c)))
def rot_x(t):
return anim.q_to_mat3(anim.q_from_axis_angle((1.0, 0.0, 0.0), t))
def mesh(rng, n, nj, k):
verts, normals, weights = [], [], []
for _ in range(n):
verts.append(tuple(rng.uniform(-1.0, 1.0) for _ in range(3)))
normals.append(anim.normalize([rng.gauss(0.0, 1.0) for _ in range(3)]))
js = rng.sample(range(nj), k)
ws = [rng.random() + 0.05 for _ in js]
s = sum(ws)
weights.append([(j, w / s) for j, w in zip(js, ws)])
return verts, normals, weights
def lbs(v, infl, palette):
out = (0.0, 0.0, 0.0)
for j, w in infl:
out = anim.add(out, anim.scale(anim.T_apply(palette[j], v), w))
return out
def close(a, b, tol):
return all(abs(x - y) <= tol for x, y in zip(a, b))
def test_bind_pose_gives_rest_mesh():
rng = random.Random(1)
verts, normals, weights = mesh(rng, 50, 4, 3)
pal = [anim.eye(4) for _ in range(4)]
out_v, out_n = spherical_blend_skinning(verts, weights, pal, normals)
for a, b in zip(out_v, verts):
assert close(a, b, 1e-12)
for a, b in zip(out_n, normals):
assert close(a, b, 1e-12)
def test_single_weight_is_rigid():
rng = random.Random(2)
pal = [rand_T(rng) for _ in range(3)]
verts = [tuple(rng.uniform(-1.0, 1.0) for _ in range(3)) for _ in range(20)]
weights = [[(i % 3, 1.0)] for i in range(20)]
out_v, _ = spherical_blend_skinning(verts, weights, pal)
for i, (a, v) in enumerate(zip(out_v, verts)):
assert close(a, anim.T_apply(pal[i % 3], v), 1e-12)
def test_common_center_is_recovered():
rng = random.Random(3)
for _ in range(20):
c = tuple(rng.uniform(-3.0, 3.0) for _ in range(3))
pal = [about(c, rand_rot(rng)) for _ in range(3)]
rc = center_of_rotation((0, 1, 2), pal)
assert close(rc, c, 1e-8)
def test_minimal_norm_center_on_a_shared_axis():
# both joints turn about the same line, so the center is not unique and
# the method takes the point of the line nearest to the origin
rng = random.Random(4)
for _ in range(20):
c = tuple(rng.uniform(-3.0, 3.0) for _ in range(3))
u = anim.normalize([rng.gauss(0.0, 1.0) for _ in range(3)])
ra = anim.q_to_mat3(anim.q_from_axis_angle(u, rng.uniform(-3.0, 3.0)))
rb = anim.q_to_mat3(anim.q_from_axis_angle(u, rng.uniform(-3.0, 3.0)))
rc = center_of_rotation((0, 1), [about(c, ra), about(c, rb)])
nearest = anim.sub(c, anim.scale(u, anim.dot(c, u)))
assert close(rc, nearest, 1e-8)
def objective(palette, js):
def f(r):
s = 0.0
for ia in range(len(js)):
for ib in range(ia + 1, len(js)):
d = anim.sub(anim.T_apply(palette[js[ia]], r), anim.T_apply(palette[js[ib]], r))
s += anim.dot(d, d)
return s
return f
def test_center_matches_direct_least_squares():
rng = random.Random(5)
for _ in range(20):
pal = [rand_T(rng) for _ in range(4)]
js = (0, 1, 2, 3)
rc = center_of_rotation(js, pal)
# reference: the normal equations solved by Gaussian elimination
n = anim.zeros(3)
g = [0.0, 0.0, 0.0]
for ia in range(4):
for ib in range(ia + 1, 4):
ra = [row[:3] for row in pal[ia][:3]]
rb = [row[:3] for row in pal[ib][:3]]
d = [[ra[r][c] - rb[r][c] for c in range(3)] for r in range(3)]
e = [pal[ib][r][3] - pal[ia][r][3] for r in range(3)]
dt = anim.transpose(d)
n = [[n[r][c] + anim.mul(dt, d)[r][c] for c in range(3)] for r in range(3)]
g = [g[r] + anim.matvec(dt, e)[r] for r in range(3)]
assert close(rc, anim.solve(n, g), 1e-7)
grad = anim.num_grad(objective(pal, js), rc, h=1e-5)
assert max(abs(x) for x in grad) < 1e-6
def test_candy_wrapper_keeps_the_radius():
for t in (0.5, 1.0, math.pi / 2, 2.5, math.pi):
pal = [anim.eye(4), anim.make_T(rot_x(t), (0.0, 0.0, 0.0))]
out_v, _ = spherical_blend_skinning([(0.3, 1.0, 0.0)], [[(0, 0.5), (1, 0.5)]], pal)
p = out_v[0]
assert abs(p[0] - 0.3) < 1e-12
assert abs(math.hypot(p[1], p[2]) - 1.0) < 1e-12
assert abs(math.atan2(p[2], p[1]) - t / 2) < 1e-12
pal = [anim.eye(4), anim.make_T(rot_x(math.pi), (0.0, 0.0, 0.0))]
out_v, _ = spherical_blend_skinning([(0.0, 1.0, 0.0)], [[(0, 0.5), (1, 0.5)]], pal)
assert close(out_v[0], (0.0, 0.0, 1.0), 1e-12)
def test_rigid_per_joint_set_and_unit_normals():
rng = random.Random(6)
pal = [rand_T(rng) for _ in range(3)]
infl = [(0, 0.2), (1, 0.5), (2, 0.3)]
verts = [tuple(rng.uniform(-1.0, 1.0) for _ in range(3)) for _ in range(15)]
normals = [anim.normalize([rng.gauss(0.0, 1.0) for _ in range(3)]) for _ in range(15)]
out_v, out_n = spherical_blend_skinning(verts, [infl] * 15, pal, normals)
for a in range(15):
assert abs(anim.norm(out_n[a]) - 1.0) < 1e-12
for b in range(a + 1, 15):
d0 = anim.norm(anim.sub(verts[a], verts[b]))
d1 = anim.norm(anim.sub(out_v[a], out_v[b]))
assert abs(d0 - d1) < 1e-12
def test_change_of_coordinates():
rng = random.Random(7)
verts, normals, weights = mesh(rng, 40, 4, 3)
pal = [rand_T(rng) for _ in range(4)]
# one joint set with a shared axis, so the minimal norm choice is used
u = (0.0, 0.0, 1.0)
pal[3] = anim.T_mul(pal[2], about((0.5, -1.0, 0.0), anim.q_to_mat3(anim.q_from_axis_angle(u, 1.1))))
weights[0] = [(2, 0.4), (3, 0.6)]
g = rand_T(rng)
gi = anim.T_inv(g)
gr = [row[:3] for row in g[:3]]
pal_g = [anim.T_mul(g, anim.T_mul(p, gi)) for p in pal]
out_v, out_n = spherical_blend_skinning(verts, weights, pal, normals)
out_vg, out_ng = spherical_blend_skinning([anim.T_apply(g, v) for v in verts], weights, pal_g, [anim.matvec(gr, n) for n in normals])
for a, b in zip(out_v, out_vg):
assert close(anim.T_apply(g, a), b, 1e-9)
for a, b in zip(out_n, out_ng):
assert close(anim.matvec(gr, a), b, 1e-9)
def test_cache_gives_the_same_result():
rng = random.Random(8)
verts, normals, weights = mesh(rng, 60, 4, 2)
pal = [rand_T(rng) for _ in range(4)]
cache = {}
out1, _ = spherical_blend_skinning(verts, weights, pal, cache=cache)
assert len(cache) <= 6
out2, _ = spherical_blend_skinning(verts, weights, pal, cache=cache)
for i, v in enumerate(verts):
assert close(out1[i], out2[i], 0.0)
alone, _ = spherical_blend_skinning([v], [weights[i]], pal)
assert close(out1[i], alone[0], 1e-12)
def test_linear_rotation_gives_lbs():
rng = random.Random(9)
verts, _, weights = mesh(rng, 40, 5, 3)
pal = [rand_T(rng) for _ in range(5)]
out_v, _ = spherical_blend_skinning(verts, weights, pal, linear_rotation=True)
for v, infl, a in zip(verts, weights, out_v):
assert close(a, lbs(v, infl, pal), 1e-12)
def test_qlerp_is_sign_invariant():
rng = random.Random(10)
quats = [rand_quat(rng) for _ in range(3)]
infl = [(0, 0.5), (1, 0.3), (2, 0.2)]
q = qlerp(infl, quats)
flipped = [quats[0], tuple(-x for x in quats[1]), quats[2]]
q2 = qlerp(infl, flipped)
assert close(q, q2, 1e-12)
assert abs(anim.q_dot(q, q) - 1.0) < 1e-12
# the aligned sum is at least the pivot weight away from zero
for _ in range(50):
quats = [rand_quat(rng) for _ in range(4)]
ws = [rng.random() + 0.01 for _ in range(4)]
s = sum(ws)
q = qlerp([(j, w / s) for j, w in enumerate(ws)], quats)
assert abs(anim.q_dot(q, q) - 1.0) < 1e-12
History
Ladislav Kavan and Jiří Žára presented spherical blend skinning at I3D 2005 as a fix for the volume loss of linear blend skinning in twists. Two years later Kavan, Collins, Žára and O'Sullivan introduced dual quaternion skinning, which gives a rigid blend without the center of rotation. The idea of a center of rotation per vertex came back in 2016 with the optimized centers of Le and Hodgins.
References
- Ladislav Kavan and Jiří Žára, Spherical blend skinning, a real-time deformation of articulated models, Proceedings of the 2005 Symposium on Interactive 3D Graphics and Games (I3D), 9-16, 2005, Section 4 (the center of rotation by least squares, equation 9), Section 4.1 (QLERP) and Section 4.2 (the sign of the quaternions)
Where this leads
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 E1S4SH Edit this page History Report an error Markdown