Algorithm Search⌘K

Algorithmintro

Linear blend skinning

Also called LBS, skeletal subspace deformation, smooth skinning.

Deforms a mesh by a skeleton. Each vertex goes to the weighted sum of its positions under the skinning matrices of its joints. Fast and simple, but twisted joints collapse.

Time
O(j + n k) frame
Space
O(j) extra
Where
j = the number of joints; k = the largest number of joints per vertex; n = the number of vertices
Properties
deterministicexactofflineiterative

Linear blend skinning (LBS) moves the vertices of a character mesh with the joints of its skeleton. Each vertex vv in the bind pose has weights wj≥0w_j \ge 0 with ∑jwj=1\sum_j w_j = 1, and it goes to

v′=(∑jwj MjBj−1)v,v' = \Bigl(\sum_j w_j\, M_j B_j^{-1}\Bigr) v,

where BjB_j is the world transform of joint jj in the bind pose and MjM_j is its world transform in the current pose. The matrix MjBj−1M_j B_j^{-1} moves a point that is attached rigidly to joint jj from the bind pose to the current pose. LBS is the standard skinning method of games and of most animation tools, because it costs a few multiply-adds per weight and runs well on a GPU. Its known defect is that a weighted sum of rotation matrices is not a rotation, so a twisted joint loses volume (the candy wrapper artifact).

In plain words

Think of each bone as a hand that holds a part of the skin. If a point of the skin is held by one hand, it moves with that hand as if it were glued to it. Near a joint, two or more hands hold the same point. LBS asks each hand where it would carry the point, and then takes the average of these places, with the weights as the shares. This gives smooth skin across the joint, and it is very cheap. But the average of two places on a circle lies inside the circle. So when one hand turns far relative to the other, the skin between them shrinks toward the bone.

The problem

The input is a rest mesh with vertices viv_i and normals nin_i in the bind pose, the bind transforms BjB_j, the current world transforms MjM_j of jj joints (from forward kinematics over the skeleton), and for each vertex a sparse list of at most kk pairs (j,wij)(j, w_{ij}) with wij≥0w_{ij} \ge 0 and ∑jwij=1\sum_j w_{ij} = 1. The output is the deformed position vi′v'_i and the deformed unit normal ni′n'_i of each vertex. This is one method for the character skinning problem. Transforms are 4×44 \times 4 homogeneous matrices that act on column vectors.

The algorithm

  1. LBS(v, n, W, M, B⁻¹) ▷ rest mesh, weights, pose and bind transforms
  2. 1for each joint j: Pⱼ ← Mⱼ Bⱼ⁻¹ ▷ the skinning matrix palette
  3. 2for each vertex i do
  4. 3A ← 0 ▷ a 4 × 4 matrix
  5. 4for each (j, w) in Wᵢ: A ← A + w Pⱼ
  6. 5v′ᵢ ← A vᵢ ▷ vᵢ as the point (x, y, z, 1)
  7. 6n′ᵢ ← normalize(A₃⁻ᵀ nᵢ) ▷ A₃ is the upper left 3 × 3 block
  8. 7return v′, n′

Line L1 runs once per frame for the whole skeleton. Lines L3 and L4 blend the matrices first, which costs one matrix per vertex; transforming the point by each PjP_j and blending the points gives the same result, because the map is linear. Line L6 uses the inverse transpose, because normals must stay orthogonal to the tangents, and the tangents move by A3A_3. The code uses the cofactor matrix cof⁡(A3)=det⁡(A3) A3−T\operatorname{cof}(A_3) = \det(A_3)\, A_3^{-T} with the sign of the determinant, which gives the same unit normal and does not divide by a small determinant.

Example

Take two joints at the origin with B1=B2=IB_1 = B_2 = I. Joint 1 stays still, and joint 2 twists by the angle θ\theta about the xx axis. The vertex v=(0,1,0)v = (0, 1, 0) has the weights 12\tfrac12 and 12\tfrac12.

twist θ\theta P1vP_1 v P2vP_2 v v′v' distance from the axis
00 (0,1,0)(0, 1, 0) (0,1,0)(0, 1, 0) (0,1,0)(0, 1, 0) 11
π/2\pi/2 (0,1,0)(0, 1, 0) (0,0,1)(0, 0, 1) (0,0.5,0.5)(0, 0.5, 0.5) 0.707110.70711
π\pi (0,1,0)(0, 1, 0) (0,−1,0)(0, -1, 0) (0,0,0)(0, 0, 0) 00

In general the distance is ∣cos⁡(θ/2)∣\bigl|\cos(\theta/2)\bigr|. At the half turn the vertex falls onto the axis, which is the candy wrapper collapse. A method that blends rotations instead of matrices, such as dual quaternion skinning, keeps the distance 1 and turns the vertex by θ/2\theta/2.

Correctness

LBS has no target shape to match, so correctness here means that it computes the stated blend and has the properties that skinning needs. These are proved properties of the formula, in exact arithmetic; the proofs are in proofs/correctness.md.

  • Line L5 equals ∑jwjPjv\sum_j w_j P_j v, the blend of the rigidly moved points, because matrix products are linear.
  • Because ∑jwj=1\sum_j w_j = 1, the bottom row of AA is (0,0,0,1)(0, 0, 0, 1), so AA is an affine map.
  • In the bind pose, Mj=BjM_j = B_j, so every Pj=IP_j = I, A=IA = I, and the mesh is the rest mesh.
  • A vertex with one weight of 1 moves rigidly with its joint.
  • If every joint moves by the same rigid motion GG, the whole mesh moves by GG.
  • The normal of line L6 is orthogonal to every deformed tangent A3tA_3 t with t⋅n=0t \cdot n = 0.

LBS does not keep lengths or volume in general: A3A_3 is a rotation only when all the rotations of the joints of the vertex agree.

Proof: Linear blend skinning computes the blend of the rigidly moved points and has the basic skinning propertiesfull

We use the notation of the page. All transforms are 4×44 \times 4 matrices that act on column vectors, and a point vv is the column (x,y,z,1)(x, y, z, 1). A rigid or affine transform has the bottom row (0,0,0,1)(0, 0, 0, 1). For one vertex, the weights are wj≥0w_j \ge 0 with ∑jwj=1\sum_j w_j = 1, and A=∑jwjPjA = \sum_j w_j P_j with Pj=MjBj−1P_j = M_j B_j^{-1} is the matrix of lines L3 and L4. The arithmetic is exact.

The blend

Lemma 1. Line L5 gives v′=∑jwj(Pjv)v' = \sum_j w_j (P_j v).

Proof. Matrix multiplication is linear in the matrix: (∑jwjPj)v=∑jwj(Pjv)(\sum_j w_j P_j) v = \sum_j w_j (P_j v). □\square

Lemma 2. AA is an affine transform.

Proof. Each PjP_j is a product of affine transforms, so its bottom row is (0,0,0,1)(0, 0, 0, 1). The bottom row of AA is ∑jwj(0,0,0,1)=(0,0,0,1)\sum_j w_j (0, 0, 0, 1) = (0, 0, 0, 1), because ∑jwj=1\sum_j w_j = 1. □\square

So v′v' is a point (its last coordinate is 1), and by Lemma 1 it is a convex combination of the points PjvP_j v.

Bind pose, single weights and rigid motions

Lemma 3. If Mj=BjM_j = B_j for every joint, then v′=vv' = v and n′=nn' = n for every vertex.

Proof. Then Pj=BjBj−1=IP_j = B_j B_j^{-1} = I, so A=∑jwjI=IA = \sum_j w_j I = I. Line L5 gives vv, and line L6 gives normalize⁡(In)=n\operatorname{normalize}(I n) = n for a unit nn. □\square

Lemma 4. If a vertex has the single weight wj=1w_j = 1, then v′=Pjvv' = P_j v, and all such vertices of joint jj move by the same rigid transform.

Proof. Then A=PjA = P_j. MjM_j and BjB_j are rigid, so PjP_j is rigid, and it is the same matrix for all these vertices. □\square

Lemma 5. Let GG be a rigid transform. If every MjM_j is replaced by GMjG M_j, then every v′v' is replaced by Gv′G v'.

Proof. The new palette is GMjBj−1=GPjG M_j B_j^{-1} = G P_j, so the new blend is ∑jwjGPj=GA\sum_j w_j G P_j = G A by linearity. □\square

Normals

Lemma 6. Let A3A_3 be invertible, nn a normal and tt a tangent with t⋅n=0t \cdot n = 0. Then (A3−Tn)⋅(A3t)=0(A_3^{-T} n) \cdot (A_3 t) = 0.

Proof. (A3−Tn)T(A3t)=nTA3−1A3t=nTt=0(A_3^{-T} n)^T (A_3 t) = n^T A_3^{-1} A_3 t = n^T t = 0. The translation column of AA does not act on direction vectors, so a tangent of the surface moves by A3A_3. □\square

Lemma 7. If det⁡A3≠0\det A_3 \ne 0, the vector sign⁡(det⁡A3)cof⁡(A3)n\operatorname{sign}(\det A_3)\operatorname{cof}(A_3) n used by the code has the direction of A3−TnA_3^{-T} n.

Proof. For the columns c0,c1,c2c_0, c_1, c_2 of A3A_3, the code builds the matrix KK with the columns c1×c2c_1 \times c_2, c2×c0c_2 \times c_0 and c0×c1c_0 \times c_1. Then (A3TK)ab=ca⋅(cb+1×cb+2)(A_3^T K)_{ab} = c_a \cdot (c_{b+1} \times c_{b+2}) with indices mod 3, which is det⁡A3\det A_3 for a=ba = b and 0 for a≠ba \ne b, because a triple product with a repeated column is 0. So K=det⁡(A3)A3−TK = \det(A_3) A_3^{-T}, and sign⁡(det⁡A3)Kn=∣det⁡A3∣ A3−Tn\operatorname{sign}(\det A_3) K n = |\det A_3|\, A_3^{-T} n, a positive multiple. □\square

After the normalization of line L6, the normal has length 1.

The twist check value

Lemma 8. Let P1=IP_1 = I, P2=Rx(θ)P_2 = R_x(\theta) and w1=w2=12w_1 = w_2 = \tfrac12. The vertex (0,1,0)(0, 1, 0) goes to (0,1+cos⁡θ2,sin⁡θ2)(0, \tfrac{1 + \cos\theta}{2}, \tfrac{\sin\theta}{2}), at the distance ∣cos⁡(θ/2)∣|\cos(\theta/2)| from the xx axis.

Proof. Rx(θ)(0,1,0)=(0,cos⁡θ,sin⁡θ)R_x(\theta)(0, 1, 0) = (0, \cos\theta, \sin\theta), and Lemma 1 averages it with (0,1,0)(0, 1, 0). The squared distance is (1+cos⁡θ)2+sin⁡2θ4=2+2cos⁡θ4=cos⁡2(θ/2)\frac{(1 + \cos\theta)^2 + \sin^2\theta}{4} = \frac{2 + 2\cos\theta}{4} = \cos^2(\theta/2). □\square

At θ=π\theta = \pi the vertex goes to the origin. So A3=12(I+Rx(π))=diag⁡(1,0,0)A_3 = \tfrac12 (I + R_x(\pi)) = \operatorname{diag}(1, 0, 0) is not a rotation, which proves that LBS does not keep lengths.

Complexity

Line L1 costs O(j)O(j) matrix products per frame. Lines L2 to L6 cost O(k)O(k) per vertex, so O(nk)O(n k) in total, and the time per frame is O(j+nk)O(j + n k). The extra space is the palette, O(j)O(j). The vertices are independent, so a vertex shader or a compute kernel runs them in parallel.

Properties

  • Linear in the vertex and in the weights; affine invariant when ∑jwj=1\sum_j w_j = 1.
  • Deterministic, with a fixed cost per weight.
  • Handles any affine joint transform, including scale and shear, because it blends matrices.
  • Not volume preserving. The blended matrix can be close to singular at a twisted joint, and shrinks the skin at a bent joint (the collapsing elbow).
  • The result depends only on the weights and the palette. It has no state between frames.

Variants and improvements

When to use it

Use LBS as the default for real-time characters, crowds and mobile targets. It is the method that file formats and engines expect, and it supports scale. Use dual quaternion skinning or a corrective method where joints twist far, for example forearms, wrists and shoulders.

Pitfalls

  • Weights that do not sum to 1. Then AA is not affine, and the mesh drifts or scales. Normalize the weights after you clamp or prune them.
  • Wrong matrix order. The palette is MjBj−1M_j B_j^{-1}, not Bj−1MjB_j^{-1} M_j. With row vectors the order is reversed; keep one convention.
  • Normals by A3A_3. Multiplying the normal by A3A_3 is correct only for a rotation. Use the inverse transpose and normalize, or use the rotation of a rigid method.
  • Singular blends. At a twist of π\pi between two joints with equal weights, A3A_3 has rank 1 and the normal is not defined. The cofactor of a rank 1 matrix is zero, so the code raises an error there.
  • Too many influences. Hardware paths often limit kk to 4. Pruning the small weights changes the shape; renormalize after it.

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
linear_blend_skinning.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/linear-blend-skinning/. The authors are listed in prov/1WQ6KE.jsonl.
"""Linear blend skinning (LBS) of a mesh by a skeleton.

Each joint j has a bind world transform B_j and a current world transform
M_j, both 4 by 4 homogeneous matrices (lists of rows, column vectors). The
skinning matrix of joint j is P_j = M_j B_j^(-1). A vertex v with the sparse
weights w_j >= 0, sum w_j = 1, goes to

    v' = (sum_j w_j P_j) v.

The normal goes through the inverse transpose of the blended 3 by 3 part,
and is normalized again. The cofactor matrix cof(A) = det(A) A^(-T) is used,
so that a singular blend does not raise in the matrix inverse.
"""

from anim import cross, mul, normalize, zeros

WEIGHT_SUM_TOL = 1e-9


def skinning_matrices(world, bind_inv):
    """Return the palette P_j = M_j B_j^(-1) for all joints."""
    return [mul(m, b) for m, b in zip(world, bind_inv)]  # @line L1


def check_weights(influences):
    """Raise ValueError unless the weights are nonnegative and sum to 1."""
    if any(w < 0.0 for _, w in influences):
        raise ValueError("negative skinning weight")
    if abs(sum(w for _, w in influences) - 1.0) > WEIGHT_SUM_TOL:
        raise ValueError("skinning weights do not sum to 1")


def blend_matrix(influences, palette):
    """Return the 4 by 4 matrix A = sum_j w_j P_j of one vertex."""
    a = zeros(4)  # @line L3
    for j, w in influences:  # @line L4
        p = palette[j]
        for r in range(4):
            for c in range(4):
                a[r][c] += w * p[r][c]
    return a


def cofactor3(a):
    """Return the cofactor matrix of the 3 by 3 part of a, det(A) A^(-T)."""
    c0 = (a[0][0], a[1][0], a[2][0])
    c1 = (a[0][1], a[1][1], a[2][1])
    c2 = (a[0][2], a[1][2], a[2][2])
    k0, k1, k2 = cross(c1, c2), cross(c2, c0), cross(c0, c1)
    return [[k0[i], k1[i], k2[i]] for i in range(3)]


def transform_normal(a, n):
    """Return the unit normal A^(-T) n / |A^(-T) n| for the 3 by 3 part of a."""
    k = cofactor3(a)
    d = sum(a[0][i] * k[0][i] for i in range(3))  # det A, by the first row
    m = tuple(sum(k[r][c] * n[c] for c in range(3)) for r in range(3))
    if d < 0.0:
        m = (-m[0], -m[1], -m[2])
    return normalize(m)


def apply_point(a, v):
    """Return the point A v for a 4 by 4 affine A and a 3D point v."""
    return tuple(a[r][0] * v[0] + a[r][1] * v[1] + a[r][2] * v[2] + a[r][3] for r in range(3))


def linear_blend_skinning(vertices, weights, palette, normals=None):
    """Return (positions, normals) of the skinned mesh.

    vertices: rest positions in the bind pose (3-tuples).
    weights: per vertex, a list of (joint index, weight) pairs.
    palette: the skinning matrices P_j = M_j B_j^(-1).
    normals: optional rest normals; the result is None if they are None.
    """
    out_v = []
    out_n = [] if normals is not None else None
    for i, v in enumerate(vertices):  # @line L2
        check_weights(weights[i])
        a = blend_matrix(weights[i], palette)
        out_v.append(apply_point(a, v))  # @line L5
        if normals is not None:
            out_n.append(transform_normal(a, normals[i]))  # @line L6
    return out_v, out_n  # @line L7


def skin_by_points(vertices, weights, palette):
    """Reference form: transform the vertex by each joint, then blend the points."""
    out = []
    for i, v in enumerate(vertices):
        acc = [0.0, 0.0, 0.0]
        for j, w in weights[i]:
            p = apply_point(palette[j], v)
            for k in range(3):
                acc[k] += w * p[k]
        out.append(tuple(acc))
    return out
test_linear_blend_skinning.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/linear-blend-skinning/. The authors are listed in prov/1WQ6KE.jsonl.
"""Tests of linear blend skinning.

They check that the bind pose gives the rest mesh, that a vertex with one
weight of 1 moves rigidly, that the blend of matrices equals the blend of
the transformed points, the candy wrapper check value, the radius cos(t/2)
of a twist t, unit normals, and the invariance under a common rigid motion.
"""

import math
import random

import pytest

import anim
from linear_blend_skinning import (
    blend_matrix,
    linear_blend_skinning,
    skin_by_points,
    skinning_matrices,
)


def rand_rot(rng):
    v = [rng.gauss(0.0, 1.0) for _ in range(4)]
    return anim.q_to_mat3(anim.q_normalize(v))


def rand_T(rng):
    t = tuple(rng.uniform(-2.0, 2.0) for _ in range(3))
    return anim.make_T(rand_rot(rng), t)


def fk(parents, local):
    """World transforms of joints stored in parent order."""
    world = []
    for j, p in enumerate(parents):
        world.append(local[j] if p < 0 else anim.T_mul(world[p], local[j]))
    return world


def chain(rng, nj):
    parents = [j - 1 for j in range(nj)]
    bind_local = [anim.make_T(anim.eye(3), (0.0, 1.0 if j else 0.0, 0.0)) for j in range(nj)]
    pose_local = [anim.T_mul(bl, anim.make_T(rand_rot(rng), (0.0, 0.0, 0.0))) for bl in bind_local]
    return parents, fk(parents, bind_local), fk(parents, pose_local)


def mesh(rng, n, nj, k):
    verts, normals, weights = [], [], []
    for _ in range(n):
        verts.append((rng.uniform(-0.5, 0.5), rng.uniform(0.0, nj - 1.0), rng.uniform(-0.5, 0.5)))
        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 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)
    _, bind, _ = chain(rng, 5)
    verts, normals, weights = mesh(rng, 60, 5, 3)
    pal = skinning_matrices(bind, [anim.T_inv(b) for b in bind])
    out_v, out_n = linear_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)
    _, bind, pose = chain(rng, 4)
    pal = skinning_matrices(pose, [anim.T_inv(b) for b in bind])
    verts, _, _ = mesh(rng, 40, 4, 1)
    j = 2
    weights = [[(j, 1.0)] for _ in verts]
    out, _ = linear_blend_skinning(verts, weights, pal)
    for a, v in zip(out, verts):
        assert close(a, anim.T_apply(pal[j], v), 1e-12)
    for p in range(len(verts)):
        for q in range(p + 1, len(verts)):
            d0 = anim.norm(anim.sub(verts[p], verts[q]))
            d1 = anim.norm(anim.sub(out[p], out[q]))
            assert abs(d0 - d1) <= 1e-12


def test_blend_of_matrices_equals_blend_of_points():
    rng = random.Random(3)
    _, bind, pose = chain(rng, 6)
    pal = skinning_matrices(pose, [anim.T_inv(b) for b in bind])
    verts, _, weights = mesh(rng, 100, 6, 4)
    out, _ = linear_blend_skinning(verts, weights, pal)
    ref = skin_by_points(verts, weights, pal)
    for a, b in zip(out, ref):
        assert close(a, b, 1e-12)


def rx(theta):
    c, s = math.cos(theta), math.sin(theta)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def test_candy_wrapper_check_value():
    pal = [anim.make_T(rx(0.0), (0.0, 0.0, 0.0)), anim.make_T(rx(math.pi), (0.0, 0.0, 0.0))]
    out, _ = linear_blend_skinning([(0.0, 1.0, 0.0)], [[(0, 0.5), (1, 0.5)]], pal)
    assert close(out[0], (0.0, 0.0, 0.0), 1e-15)


def test_twist_radius_is_cos_half_angle():
    for theta in [0.1 * k for k in range(32)]:
        pal = [anim.make_T(rx(0.0), (0.0, 0.0, 0.0)), anim.make_T(rx(theta), (0.0, 0.0, 0.0))]
        out, _ = linear_blend_skinning([(0.3, 1.0, 0.0)], [[(0, 0.5), (1, 0.5)]], pal)
        r = math.hypot(out[0][1], out[0][2])
        assert abs(r - abs(math.cos(theta / 2.0))) <= 1e-12
        assert abs(out[0][0] - 0.3) <= 1e-15


def test_normals_stay_unit():
    rng = random.Random(4)
    _, bind, pose = chain(rng, 5)
    pal = skinning_matrices(pose, [anim.T_inv(b) for b in bind])
    verts, normals, weights = mesh(rng, 80, 5, 3)
    _, out_n = linear_blend_skinning(verts, weights, pal, normals)
    for n in out_n:
        assert abs(anim.norm(n) - 1.0) <= 1e-12


def test_normal_is_inverse_transpose():
    rng = random.Random(5)
    _, bind, pose = chain(rng, 3)
    pal = skinning_matrices(pose, [anim.T_inv(b) for b in bind])
    verts, normals, weights = mesh(rng, 20, 3, 3)
    _, out_n = linear_blend_skinning(verts, weights, pal, normals)
    for i in range(len(verts)):
        a = blend_matrix(weights[i], pal)
        a3 = [row[:3] for row in a[:3]]
        m = anim.matvec(anim.transpose(anim.inv(a3)), normals[i])
        assert close(out_n[i], anim.normalize(m), 1e-10)
        # the normal stays orthogonal to any tangent t, which maps to A t
        t = anim.cross(normals[i], (1.0, 0.0, 0.0))
        assert abs(anim.dot(out_n[i], anim.matvec(a3, t))) <= 1e-10


def test_common_rigid_motion_moves_mesh_rigidly():
    rng = random.Random(6)
    _, bind, pose = chain(rng, 4)
    g = rand_T(rng)
    bind_inv = [anim.T_inv(b) for b in bind]
    verts, _, weights = mesh(rng, 50, 4, 3)
    out, _ = linear_blend_skinning(verts, weights, skinning_matrices(pose, bind_inv))
    moved = [anim.T_mul(g, m) for m in pose]
    out_g, _ = linear_blend_skinning(verts, weights, skinning_matrices(moved, bind_inv))
    for a, b in zip(out, out_g):
        assert close(anim.T_apply(g, a), b, 1e-12)


def test_bad_weights_raise():
    pal = [anim.eye(4)]
    with pytest.raises(ValueError):
        linear_blend_skinning([(0.0, 0.0, 0.0)], [[(0, 0.7)]], pal)
    with pytest.raises(ValueError):
        linear_blend_skinning([(0.0, 0.0, 0.0)], [[(0, 1.5), (0, -0.5)]], pal)

History

The roots of LBS are hard to trace, as Kavan notes in the 2014 skinning course. Magnenat-Thalmann, Laperrière and Thalmann (1988) used joint-dependent local deformations of a hand mesh, and the method spread in games and tools under many names: vertex blending, enveloping, smooth skinning and matrix palette skinning. Lewis, Cordner and Fong (2000) gave an exact description of it under the name skeleton subspace deformation, also written skeletal subspace deformation, as the base layer of pose space deformation. Kavan, Collins, Žára and O'Sullivan (2008) gave the candy wrapper example with a twist of 180 degrees and replaced the matrix blend with a dual quaternion blend.

References

  1. 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, Section 2 (linear blend skinning, its other names, its history and the candy wrapper artifact)
  2. Ladislav Kavan, Steven Collins, Jiří Žára and Carol O'Sullivan, Geometric skinning with approximate dual quaternion blending, ACM Transactions on Graphics 27(4), article 105, 2008, Section 2.2 (linear blend skinning, equation 2, and the candy wrapper example)

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