Algorithm Search⌘K

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.

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
Properties
deterministicexactofflineiterative

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 rcr_c by least squares, as the point that the rigid skinning transforms CjC_j of the vertex's joints move the least apart, and then computes

v′=Q (v−rc)+∑jwj Cjrc,v' = Q\,(v - r_c) + \sum_j w_j\, C_j r_c,

where QQ 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 viv_i and the normals nin_i, the weights wij≥0w_{ij} \ge 0 with ∑jwij=1\sum_j w_{ij} = 1, and the rigid skinning transforms Cj=MjBj−1C_j = M_j B_j^{-1} of the current pose, where MjM_j comes from forward kinematics and BjB_j is the bind pose transform. Write Cjx=Rjx+tjC_j x = R_j x + t_j, with the rotation RjR_j and its unit quaternion qjq_j. 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 JJ of joints, the center rcr_c minimizes

f(r)=∑a<b∈J∣Car−Cbr∣2=∑a<b∈J∣(Ra−Rb) r−(tb−ta)∣2.f(r) = \sum_{a < b \in J} \lvert C_a r - C_b r \rvert^2 = \sum_{a < b \in J} \lvert (R_a - R_b)\, r - (t_b - t_a) \rvert^2.

If the minimizer is not unique, SBS takes the one of minimal norm.

  1. SPHERICAL-BLEND-SKINNING(V, N, W, C) ▷ rest mesh, weights, joint transforms
  2. 1for each vertex i
  3. 2J ← the set of joints with w_ij > 0
  4. 3if J is not in the cache of this frame
  5. 4r ← minimal norm minimizer of Σ_{a<b ∈ J} |(R_a - R_b) r - (t_b - t_a)|²
  6. 5cache[J] ← r
  7. 6r_c ← cache[J]
  8. 7Q ← normalize(Σ_j s_j w_ij q_j) ▷ s_j = ±1, so that q_p · s_j q_j ≥ 0 for the pivot p
  9. 8v'_i ← Q (v_i - r_c) + Σ_j w_ij C_j r_c
  10. 9n'_i ← Q n_i
  11. 10return V', N'

Line L4 is a linear least squares problem with 3 unknowns. Its normal equations are Nr=gN r = g with N=∑(Ra−Rb)⊤(Ra−Rb)N = \sum (R_a - R_b)^\top (R_a - R_b) and g=∑(Ra−Rb)⊤(tb−ta)g = \sum (R_a - R_b)^\top (t_b - t_a). The code takes the pseudo-inverse of the symmetric 3×33 \times 3 matrix NN 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 pp 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 rcr_c and then moves rcr_c to the blend of its images; for one joint it gives CjvC_j v.

Example

Take two joints with the weights 0.50.5 and 0.50.5, C0=IC_0 = I, and C1C_1 a turn by π\pi about the xx axis, the twist of the candy wrapper. The center minimizes ∣(I−Rx(π)) r∣2|(I - R_x(\pi))\, r|^2, which is zero on the whole xx axis, and the point of minimal norm is the origin. QLERP blends q0=(1,0,0,0)q_0 = (1, 0, 0, 0) and q1=(0,1,0,0)q_1 = (0, 1, 0, 0) into (1,1,0,0)/2(1, 1, 0, 0)/\sqrt2, the turn by π/2\pi/2 about xx.

vertex LBS SBS
(0,1,0)(0, 1, 0) (0,0,0)(0, 0, 0) (0,0,1)(0, 0, 1)
(0.3,1,0)(0.3, 1, 0) (0.3,0,0)(0.3, 0, 0) (0.3,0,1)(0.3, 0, 1)

LBS collapses the vertex onto the axis; SBS turns it by half the twist and keeps the radius 1. For a twist θ≤π\theta \le \pi the SBS vertex turns by exactly θ/2\theta/2.

For a bend, let C1C_1 turn by π/2\pi/2 about the zz axis through c=(1,0,0)c = (1, 0, 0), the elbow. The least squares problem is zero on the line through cc parallel to zz, so rc=(1,0,0)r_c = (1, 0, 0). The vertex (1.5,0,0)(1.5, 0, 0) goes to (1.35355,0.35355,0)(1.35355, 0.35355, 0), at the distance 0.50.5 from the elbow, while LBS gives (1.25,0.25,0)(1.25, 0.25, 0) at the distance 0.353550.35355. 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 CjC_j.
  • If the joints of a set turn about a common point cc and the minimizer is unique, then rc=cr_c = c.
  • 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 QQ always exists.
  • For a fixed joint set and fixed weights, the map v↦v′v \mapsto v' 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 QQ is replaced by the matrix ∑jwjRj\sum_j w_j R_j, 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 Cjx=Rjx+tjC_j x = R_j x + t_j is rigid. Quaternions are in the Hamilton convention, scalar first; qjq_j is a unit quaternion of RjR_j, and p⋅qp \cdot q is the dot product in R4\mathbb R^4. For a vertex with the joint set JJ and the weights wjw_j, let m(r)=∑jwjCjrm(r) = \sum_j w_j C_j r and S(r)=Q(v−r)+m(r)S(r) = Q(v - r) + m(r), so that line L8 gives S(rc)S(r_c).

The center

Let Dab=Ra−RbD_{ab} = R_a - R_b, eab=tb−tae_{ab} = t_b - t_a, N=∑a<bDab⊤DabN = \sum_{a<b} D_{ab}^\top D_{ab} and g=∑a<bDab⊤eabg = \sum_{a<b} D_{ab}^\top e_{ab}.

Lemma 1. The minimizers of ff are the set r0+Kr_0 + K, where r0r_0 is any solution of Nr=gN r = g and K={s:Ras=Rbs for all a,b∈J}K = \{ s : R_a s = R_b s \text{ for all } a, b \in J \}. Line L4 returns the unique minimizer in the orthogonal complement of KK.

Proof. f(r)=∑∣Dabr−eab∣2f(r) = \sum \lvert D_{ab} r - e_{ab} \rvert^2 is a convex quadratic with the gradient 2(Nr−g)2(N r - g), so its minimizers are the solutions of Nr=gN r = g, which exist because gg is in the range of NN. Two solutions differ by an element of the null space of NN. Since s⊤Ns=∑∣Dabs∣2s^\top N s = \sum \lvert D_{ab} s \rvert^2 and NN is positive semidefinite, Ns=0N s = 0 if and only if Dabs=0D_{ab} s = 0 for all pairs, that is s∈Ks \in K. The code writes N=∑kλkukuk⊤N = \sum_k \lambda_k u_k u_k^\top and returns ∑λk>0(uk⋅g/λk) uk\sum_{\lambda_k > 0} (u_k \cdot g / \lambda_k)\, u_k, which solves Nr=gN r = g and is orthogonal to the null space; such a solution is unique. □\square

Lemma 2. If Cjc=cC_j c = c for all j∈Jj \in J and K={0}K = \{0\}, then rc=cr_c = c.

Proof. f(c)=0f(c) = 0, so cc is a minimizer, and by Lemma 1 the minimizer is unique. □\square

The rotation exists

Lemma 3. Let pp be the quaternion of the joint with the largest weight wpw_p, and b=∑jwjsjqjb = \sum_j w_j s_j q_j with sj=±1s_j = \pm 1 chosen so that p⋅sjqj≥0p \cdot s_j q_j \ge 0. Then ∣b∣≥wp>0\lvert b \rvert \ge w_p > 0.

Proof. ∣b∣≥p⋅b=∑jwj p⋅sjqj≥wp p⋅p=wp\lvert b \rvert \ge p \cdot b = \sum_j w_j\, p \cdot s_j q_j \ge w_p\, p \cdot p = w_p, since every term is nonnegative and sp=1s_p = 1. wp>0w_p > 0 because the weights sum to 1. □\square

So Q=b/∣b∣Q = b / \lvert b \rvert is a unit quaternion, and line L7 never divides by zero.

The choice of the center does not matter

Lemma 4. If rr and r′r' both minimize ff, then S(r)=S(r′)S(r) = S(r').

Proof. By Lemma 1, r′=r+sr' = r + s with s∈Ks \in K; let s≠0s \ne 0 and u=s/∣s∣u = s / \lvert s \rvert. Fix a∈Ja \in J. For every jj, Ra⊤Rju=uR_a^\top R_j u = u, so Ra⊤RjR_a^\top R_j is a turn about uu, and qj=±qa(cos⁡φj2,sin⁡φj2 u)q_j = \pm q_a (\cos\tfrac{\varphi_j}{2}, \sin\tfrac{\varphi_j}{2}\, u) for some angle φj\varphi_j. Then b=qahb = q_a h, where hh is a sum of quaternions of the form (α,βu)(\alpha, \beta u) and so has this form too. Hence Q=qah/∣h∣Q = q_a h / \lvert h \rvert is the rotation RaR_a after a turn about uu, and Qs=RasQ s = R_a s. Also ∑jwjRjs=∑jwjRas=Ras\sum_j w_j R_j s = \sum_j w_j R_a s = R_a s. So S(r+s)−S(r)=−Qs+∑jwjRjs=−Ras+Ras=0S(r + s) - S(r) = -Q s + \sum_j w_j R_j s = -R_a s + R_a s = 0. □\square

Rigid motion per joint set

Lemma 5. For a fixed joint set and fixed weights, v↦S(rc)v \mapsto S(r_c) is a rotation by QQ followed by a translation, and ∣Qn∣=∣n∣\lvert Q n \rvert = \lvert n \rvert.

Proof. S(rc)=Qv+(m(rc)−Qrc)S(r_c) = Q v + (m(r_c) - Q r_c), and the second term does not depend on vv. A unit quaternion rotation keeps lengths. □\square

So two vertices with the same joints and weights keep their distance, and normals stay unit vectors.

Lemma 6. In the bind pose, with Cj=IC_j = I for all jj, S(rc)=vS(r_c) = v and Qn=nQ n = n. For a vertex with one joint, S(rc)=CjvS(r_c) = C_j v.

Proof. In the bind pose qj=(1,0,0,0)q_j = (1, 0, 0, 0), so QQ is the identity and S(r)=v−r+r=vS(r) = v - r + r = v. For one joint, Q=qjQ = q_j (up to a sign that gives the same rotation), and S(r)=Rj(v−r)+Rjr+tj=CjvS(r) = R_j (v - r) + R_j r + t_j = C_j v for any rr. □\square

Coordinate invariance

Lemma 7. Let Gx=GRx+gG x = G_R x + g be rigid, and replace CjC_j by GCjG−1G C_j G^{-1}, vv by GvG v and nn by GRnG_R n. Then the new result is GS(rc)G S(r_c) and the new normal is GRQnG_R Q n.

Proof. Let γ\gamma be the unit quaternion of GRG_R. The new joint quaternions are γqjγ∗\gamma q_j \gamma^*, and x↦γxγ∗x \mapsto \gamma x \gamma^* is an orthogonal map of R4\mathbb R^4, so all dot products, and so the signs sjs_j, stay the same, and the new rotation is γQγ∗\gamma Q \gamma^*, that is GRQGR⊤G_R Q G_R^\top. The new objective is f′(r′)=∑∣GCaG−1r′−GCbG−1r′∣2=f(G−1r′)f'(r') = \sum \lvert G C_a G^{-1} r' - G C_b G^{-1} r' \rvert^2 = f(G^{-1} r'), because GG keeps distances, so its minimizers are the images GrG r of the minimizers rr of ff. By Lemma 4 we may evaluate the new result at GrcG r_c: GRQGR⊤(Gv−Grc)+∑jwjGCjrc=GRQ(v−rc)+GR m(rc)+g=GS(rc)G_R Q G_R^\top (G v - G r_c) + \sum_j w_j G C_j r_c = G_R Q (v - r_c) + G_R\, m(r_c) + g = G S(r_c), since Gv−Grc=GR(v−rc)G v - G r_c = G_R (v - r_c) and ∑jwj=1\sum_j w_j = 1. The normal is GRQGR⊤GRn=GRQnG_R Q G_R^\top G_R n = G_R Q n. □\square

Relation to linear blend skinning

Lemma 8. If QQ in line L8 is replaced by the matrix A=∑jwjRjA = \sum_j w_j R_j, the result is ∑jwjCjv\sum_j w_j C_j v for any rr.

Proof. A(v−r)+∑jwj(Rjr+tj)=∑jwjRjv−Ar+Ar+∑jwjtj=∑jwjCjvA(v - r) + \sum_j w_j (R_j r + t_j) = \sum_j w_j R_j v - A r + A r + \sum_j w_j t_j = \sum_j w_j C_j v. □\square

The twist check value

Lemma 9. Let C0=IC_0 = I, C1C_1 the turn by θ∈(0,π]\theta \in (0, \pi] about the xx axis, and the weights 12,12\tfrac12, \tfrac12. Then rc=0r_c = 0, and SBS turns every vertex by θ/2\theta / 2 about the xx axis. For θ=π\theta = \pi it maps (0,1,0)(0, 1, 0) to (0,0,1)(0, 0, 1).

Proof. KK is the xx axis and g=0g = 0, so the minimal norm minimizer is rc=0r_c = 0 by Lemma 1. q0=(1,0,0,0)q_0 = (1, 0, 0, 0) and q1=(cos⁡θ2,sin⁡θ2,0,0)q_1 = (\cos\tfrac\theta2, \sin\tfrac\theta2, 0, 0) with q0⋅q1=cos⁡θ2≥0q_0 \cdot q_1 = \cos\tfrac\theta2 \ge 0, so no sign changes, and b=12(1+cos⁡θ2,sin⁡θ2,0,0)b = \tfrac12 (1 + \cos\tfrac\theta2, \sin\tfrac\theta2, 0, 0). With 1+cos⁡θ2=2cos⁡2θ41 + \cos\tfrac\theta2 = 2\cos^2\tfrac\theta4 and sin⁡θ2=2sin⁡θ4cos⁡θ4\sin\tfrac\theta2 = 2 \sin\tfrac\theta4 \cos\tfrac\theta4, Q=(cos⁡θ4,sin⁡θ4,0,0)Q = (\cos\tfrac\theta4, \sin\tfrac\theta4, 0, 0), the turn by θ/2\theta / 2. m(0)=0m(0) = 0, so S(0)=QvS(0) = Q v. For θ=π\theta = \pi this is the turn by π/2\pi / 2, which maps (0,1,0)(0, 1, 0) to (0,0,1)(0, 0, 1). □\square

Linear blend skinning maps the same vertex to (0,0,0)(0, 0, 0) for θ=π\theta = \pi, by Lemma 8 with A=12(I+Rx(π))A = \tfrac12 (I + R_x(\pi)).

Complexity

The quaternions of the palette cost O(j)O(j) per frame. A center costs O(k2)O(k^2) for the k(k−1)/2k(k-1)/2 pairs and O(1)O(1) for the 3×33 \times 3 solve, and a vertex costs O(k)O(k) after that. In the worst case each vertex has its own joint set, which gives O(j+nk2)O(j + n k^2) 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 O(j+n)O(j + n).

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 CjC_j 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 ∑jwjRj\sum_j w_j R_j in place of QQ 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. qq and −q-q 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 uu with Rau=RbuR_a u = R_b u, and a move along uu does not change ff. 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 QQ 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.

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

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

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

import math

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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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

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


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


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


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

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


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


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


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


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


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

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


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

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


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


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


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


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


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


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


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


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


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

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


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


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

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


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

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


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


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


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


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

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


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


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


def num_grad(f, x, h=1e-6):
    """Return the gradient of a scalar f at x by central differences of step h."""
    x = list(x)
    g = []
    for i in range(len(x)):
        xi = x[i]
        x[i] = xi + h
        fp = f(x)
        x[i] = xi - h
        fm = f(x)
        x[i] = xi
        g.append((fp - fm) / (2.0 * h))
    return g
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

  1. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.frame
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • at least three sources
  • a scene preset for the example