Algorithm Search⌘K

Algorithmadvanced

Delta mush

Also called direct delta mush.

Smooths the skinned mesh and adds back the rest detail, stored as offsets in frames of the smoothed rest mesh. It hides the faults of rough skinning weights.

Time
O(j + n k + K (n + f)) frameO(K (n + f)) precompute
Space
O(n + f) extra
Where
K = the number of smoothing steps; f = the number of triangles; j = the number of joints; k = the largest number of joints per vertex; n = the number of vertices
Properties
deterministicexactofflineiterative

Delta mush is a correction step that runs after a skinning method such as linear blend skinning. It smooths the skinned mesh until the faults of the skinning are gone, and then adds back the detail that the smoothing removed. That detail comes from the rest pose: the rest mesh is smoothed in the same way once, and the difference between each rest vertex and its smoothed position is the delta of the vertex. The delta is stored in a frame of the smoothed rest surface at the vertex, so it turns with the surface when the mesh moves:

ui′=u~i+Gi δi,δi=FiT(vi−v~i),u'_i = \tilde u_i + G_i\, \delta_i, \qquad \delta_i = F_i^{\mathsf T} (v_i - \tilde v_i),

where v~\tilde v and u~\tilde u are the smoothed rest and skinned meshes, and FiF_i and GiG_i are their orthonormal frames at vertex ii. Joe Mancewicz, Matt Derksen, Hans Rijpkema and Cyrus Wilson described it in 2014. It needs no extra data from an artist, so rough weights, even weights of only 0 and 1, give a smooth result.

In plain words

Skinning with rough weights gives a mesh with dents and sharp folds at the joints. If you blur that mesh, the dents go away, but so do the small shapes of the model, such as wrinkles and muscles. Delta mush blurs the model once in its rest pose and records, for each point, how far the point sits from its blurred place. It records this offset in a small frame that sits on the blurred surface, so the offset turns when the surface turns. In each frame of the animation, it skins the mesh, blurs it the same way, and puts each recorded offset back. The small shapes come back, and the dents of the skinning stay blurred away.

The problem

The input is the rest mesh VV with its triangles, the skinning weights, and in each frame the skinning transforms of the pose (see bind pose). The output is the deformed mesh. The goal is a smooth deformation near the joints that keeps the detail of the rest mesh, with weights that need little painting. This is the character skinning problem with a correction step.

The algorithm

The smoothing is KK steps of uniform Laplacian smoothing with the step λ\lambda, done for all vertices at once, as in the Jacobi method: each vertex moves the fraction λ\lambda of the way to the mean of its neighbors. The frame of a vertex has the normal nin_i, the normalized sum of the cross products of the triangles around it; the tangent tit_i, the edge to a fixed neighbor with its part along nin_i removed, normalized; and bi=ni×tib_i = n_i \times t_i.

  1. DELTA-MUSH(V, triangles, W, C)
  2. 1Ṽ ← SMOOTH(V) ▷ precomputation, once
  3. 2for each vertex i: F_i ← FRAME(Ṽ, i); δ_i ← F_iᵀ (v_i - ṽ_i)
  4. 3U ← the skinned mesh, here u_i = Σ_j w_ij C_j v_i ▷ each frame
  5. 4Ũ ← SMOOTH(U)
  6. 5for each vertex i: G_i ← FRAME(Ũ, i)
  7. 6u'_i ← ũ_i + G_i δ_i
  8. 7return U'
  9. SMOOTH(X)
  10. 8repeat K times: x_i ← x_i + λ (mean of x_k over the neighbors k of i - x_i), for all i at once
  11. FRAME(X, i)
  12. 9n ← normalized Σ of the face cross products at i; t ← normalized (e - (e·n) n) for the edge e to the first neighbor; return (t, n × t, n)

Lines L1 and L2 depend only on the rest mesh, so they run once. Line L6 is the only use of the deltas: the frame GiG_i of the smoothed pose carries the rest detail to its place in the pose. Any skinning can give UU in line L3; the code of this page takes LBS by default and also accepts a given deformed mesh. The tuning values of the code are λ=0.5\lambda = 0.5 and K=10K = 10.

Example

Take an open tube of radius 0.50.5 along the yy axis from y=0y = 0 to y=2y = 2, with 12 vertices around and 13 rings. Joint 0 is at the origin and joint 1 at (0,1,0)(0, 1, 0), and the weight of joint 1 rises smoothly over 0.6≤y≤1.40.6 \le y \le 1.4. The table gives the mean distance of the middle ring, at y=1y = 1, from the joint (0,1,0)(0, 1, 0); in the rest pose it is 0.50.5.

pose of joint 1 LBS delta mush on LBS
twist by π/2\pi/2 about yy 0.3540.354 0.3320.332
twist by π\pi about yy 0.0000.000 0.2890.289
bend by π/2\pi/2 about zz through the joint 0.4300.430 0.4670.467

In the bend, delta mush keeps more of the radius than LBS. In the twist by π\pi, LBS puts the whole middle ring on the axis, and delta mush keeps the tube open. In the twist by π/2\pi/2, it is a little worse than LBS: it does not cure the candy wrapper artifact. Even when the input twists each ring rigidly, so that every ring keeps the radius 0.50.5, the output middle ring has the radius 0.3800.380, and the output moves up to 0.120.12 from the input.

With rigid weights, 0 below y=1y = 1 and 1 above, and a bend by π/3\pi/3, LBS tears the tube between the rings at y=1y = 1 and y=1.1667y = 1.1667, whose rest gap is 0.16670.1667. The worst change of that gap is 0.4830.483 with LBS and 0.1500.150 with delta mush. These values come from the code of this page and are measurements, not proved properties.

Correctness

The proofs are in proofs/correctness.md; they are proved properties in exact arithmetic.

  • SMOOTH is the linear map (I−λL)K(I - \lambda L)^K with the random-walk Laplacian L=I−D−1AL = I - D^{-1} A; each row of I−λLI - \lambda L sums to 1.
  • The frames are orthonormal and right-handed wherever the normal sum is not zero and the tangent edge is not along the normal.
  • In the bind pose the output is the rest mesh exactly, because FiFiT=IF_i F_i^{\mathsf T} = I; the same holds for any skinning that returns the rest mesh.
  • If all the joints move by one rigid motion GG, the output is GVG V: the smoothing commutes with affine maps, and the frames turn with the mesh.

These do not say that the output is close to a "true" deformation; how well the method hides the faults of the skinning is a measurement, as in the example.

Proof: Delta mush is a linear smoothing with orthonormal frames, gives the rest mesh in the bind pose, and commutes with a common rigid motionfull

We use the notation of the page. The arithmetic is exact, every vertex has at least one neighbor, and the weights of each vertex sum to 1. Write the positions of a mesh as the rows of an n×3n \times 3 matrix XX, the adjacency matrix as AA, and the diagonal matrix of the degrees as DD.

The smoothing

Lemma 1. One step of line L8 is X↦PXX \mapsto P X with P=I−λLP = I - \lambda L and L=I−D−1AL = I - D^{-1} A, so SMOOTH is X↦PKXX \mapsto P^K X. Each row of PP, and so each row of PKP^K, sums to 1.

Proof. Row ii of D−1AXD^{-1} A X is the mean of the neighbors of ii, so row ii of X+λ(D−1AX−X)X + \lambda (D^{-1} A X - X) is the update of line L8; all rows use the old XX, as in the code. The rows of D−1AD^{-1} A sum to 1, so the rows of LL sum to 0 and those of PP sum to 1. If the rows of PP and QQ sum to 1, then PQ1=P1=1P Q \mathbf 1 = P \mathbf 1 = \mathbf 1, so by induction the rows of PKP^K sum to 1. □\square

Lemma 2. For an affine map G(x)=Rx+cG(x) = R x + c, applied to each vertex, SMOOTH(GX)=G SMOOTH(X)\mathrm{SMOOTH}(G X) = G\, \mathrm{SMOOTH}(X).

Proof. Let pikp_{ik} be the entries of PKP^K. Vertex ii of the smoothed GXG X is ∑kpik(Rxk+c)=R∑kpikxk+c∑kpik=R x~i+c\sum_k p_{ik} (R x_k + c) = R \sum_k p_{ik} x_k + c \sum_k p_{ik} = R\, \tilde x_i + c, by Lemma 1. □\square

The frames

Lemma 3. If the normal sum sis_i at vertex ii is not zero and the edge ee to the first neighbor is not parallel to it, line L9 returns a right-handed orthonormal frame (t,b,n)(t, b, n).

Proof. n=si/∣si∣n = s_i / \lvert s_i \rvert is a unit vector. e−(e⋅n)ne - (e \cdot n) n is not zero, because ee is not parallel to nn, and its dot product with nn is e⋅n−(e⋅n)=0e \cdot n - (e \cdot n) = 0; so tt is a unit vector orthogonal to nn. b=n×tb = n \times t is orthogonal to nn and tt, and ∣b∣=∣n∣∣t∣sin⁡90°=1\lvert b \rvert = \lvert n \rvert \lvert t \rvert \sin 90° = 1. Finally t×b=t×(n×t)=n(t⋅t)−t(t⋅n)=nt \times b = t \times (n \times t) = n (t \cdot t) - t (t \cdot n) = n, so the frame is right-handed. □\square

So the matrix Fi=[t  b  n]F_i = [t\; b\; n] is a rotation, and FiTFi=FiFiT=IF_i^{\mathsf T} F_i = F_i F_i^{\mathsf T} = I.

Lemma 4. For a rigid motion G(x)=Rx+cG(x) = R x + c with RR a rotation, the frame of vertex ii of GXG X is RFiR F_i, where FiF_i is the frame of XX.

Proof. Each difference of two vertices turns to RR times the old difference, and Ra×Rb=R(a×b)R a \times R b = R (a \times b) for a rotation. So each face cross product, and their sum sis_i, turns to RR times the old one, and since ∣Rsi∣=∣si∣\lvert R s_i \rvert = \lvert s_i \rvert, the normal turns to RnR n. The edge turns to ReR e, and Re−(Re⋅Rn)Rn=R(e−(e⋅n)n)R e - (R e \cdot R n) R n = R (e - (e \cdot n) n), so the tangent turns to RtR t. Then Rn×Rt=R(n×t)=RbR n \times R t = R (n \times t) = R b. □\square

Bind pose and rigid motions

Lemma 5. If the skinned mesh of line L3 is the rest mesh, U=VU = V, the output is VV. In particular this holds in the bind pose, where every Cj=IC_j = I and ui=∑jwijvi=viu_i = \sum_j w_{ij} v_i = v_i.

Proof. U~=V~\tilde U = \tilde V, so Gi=FiG_i = F_i for every ii, and line L6 gives v~i+FiFiT(vi−v~i)=vi\tilde v_i + F_i F_i^{\mathsf T} (v_i - \tilde v_i) = v_i by Lemma 3. □\square

Lemma 6. If every CjC_j is the same rigid motion G(x)=Rx+cG(x) = R x + c, the output is GviG v_i for every vertex.

Proof. Line L3 gives ui=∑jwijGvi=Gviu_i = \sum_j w_{ij} G v_i = G v_i, because the weights sum to 1. By Lemma 2, u~i=Rv~i+c\tilde u_i = R \tilde v_i + c, and by Lemma 4, Gi=RFiG_i = R F_i. So line L6 gives Rv~i+c+RFiFiT(vi−v~i)=Rvi+cR \tilde v_i + c + R F_i F_i^{\mathsf T} (v_i - \tilde v_i) = R v_i + c. □\square

What is not proved

The lemmas say nothing about how close the output is to a good deformation in a general pose. The smoothing of a bent or twisted mesh does not shrink it in the same way as the rest mesh, so the deltas restore the rest shape only in part; the tables of the page are measurements.

Complexity

One smoothing step visits each vertex and its neighbors, which costs O(n+f)O(n + f) on a triangle mesh, so SMOOTH costs O(K(n+f))O(K (n + f)). The frames cost O(n+f)O(n + f). The precomputation costs O(K(n+f))O(K (n + f)), and each frame costs O(j+nk)O(j + n k) for LBS plus O(K(n+f))O(K (n + f)) for the correction. The extra space is O(n+f)O(n + f) for the neighbor lists, the deltas and the work arrays. The cost grows with KK, so a large KK for a wide blur makes delta mush much slower than LBS.

Properties

  • It is a correction step: any skinning can come before it, and the bind pose and common rigid motions pass through unchanged (proved).
  • It keeps the detail of the rest mesh in the local frames, so wrinkles and other small shapes move with the surface.
  • It hides rough weights: with weights of only 0 and 1 the joint still bends smoothly (a measurement on the example).
  • It does not keep volume in twists: on the tube it is no better than LBS at π/2\pi/2 (a measurement).
  • It is global within the reach of the smoothing: a vertex depends on the skinned positions of all vertices within about KK edges.
  • λ\lambda, KK and the choice of the tangent edge are tuning values.

Variants and improvements

  • Masks. Production tools let the artist scale the correction per vertex, so that some regions follow the skinning directly.
  • Other smoothing. Taubin smoothing shrinks the mesh less per step, and a cotangent Laplacian depends less on the triangulation than the uniform one.
  • Direct delta mush. Binh Huy Le and J. P. Lewis (2019) rewrote the method as a direct skinning with precomputed data per vertex and joint, which avoids the smoothing at run time; it is a different method and has its own trade-offs.
  • Better input. Since delta mush corrects any skinning, dual quaternion skinning can give UU in line L3, but the example shows that a good input alone does not keep the twist radius.
  • Other corrections. Implicit skinning corrects the skinning with fields of the bones and models contact; Laplacian surface editing also stores detail as differential coordinates.

When to use it

Use it when the weights are rough or the rig is in early work, and smooth joints with the rest detail kept matter more than the cost per frame. For twist-heavy joints, add a twist bone or another fix, since delta mush does not keep the radius in a twist.

Pitfalls

  • Shrinking. The smoothing shrinks the mesh, and the deltas restore the rest shape only where the deformation is close to rigid; with large KK the results can drift.
  • Degenerate frames. A vertex whose normal sum is near zero, or whose tangent edge is near the normal, has an unstable frame, and its delta can jump.
  • Boundaries. On an open boundary the uniform smoothing pulls vertices inward along the surface; the deltas restore this in the rest pose, but a pose that stretches the boundary changes it.
  • Topology. The neighbor lists and the frames depend on the mesh connectivity, so the rest mesh and the skinned mesh must have the same triangles and the same vertex order.
  • Cost. A wide blur needs a large KK, and the cost per frame grows with 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
delta_mush.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/delta-mush/. The authors are listed in prov/118N6H.jsonl.
"""Delta mush (Mancewicz, Derksen, Rijpkema and Wilson 2014).

Precomputation, once in the rest pose:
1. Smooth the rest mesh V into S(V) by K steps of uniform Laplacian
   smoothing with the step lam.
2. At each smoothed vertex build an orthonormal frame F_i (tangent,
   bitangent, normal), and store the delta d_i = F_i^T (v_i - S(V)_i), the
   detail that the smoothing removed, in that frame.

Each frame:
3. Deform the mesh with any skinning, here linear blend skinning: U.
4. Smooth U into S(U) with the same K and lam.
5. Build the frames G_i of S(U) and add back the details:
   u_i' = S(U)_i + G_i d_i.

The frame of vertex i has the normal n_i (the sum of the cross products of
the faces around i, normalized), the tangent t_i (the edge to the first
neighbor of i in the vertex list, with its part along n_i removed,
normalized) and b_i = n_i x t_i. K and lam are tuning values.
"""

from anim import add, cross, dot, normalize, scale, sub

LAM = 0.5
ITERS = 10


def neighbors(n, triangles):
    """Return the sorted neighbor lists of the n vertices of a triangle mesh."""
    nb = [set() for _ in range(n)]
    for a, b, c in triangles:
        nb[a] |= {b, c}
        nb[b] |= {a, c}
        nb[c] |= {a, b}
    return [sorted(s) for s in nb]


def smooth(points, nbrs, lam=LAM, iters=ITERS):
    """K steps of x_i <- x_i + lam (mean of the neighbors - x_i), all at once."""
    x = [tuple(p) for p in points]
    for _ in range(iters):  # @line L8
        new = []
        for i, p in enumerate(x):
            m = (0.0, 0.0, 0.0)
            for k in nbrs[i]:
                m = add(m, x[k])
            m = scale(m, 1.0 / len(nbrs[i]))
            new.append(add(p, scale(sub(m, p), lam)))
        x = new
    return x


def frames(points, triangles, nbrs):
    """Return the frame of each vertex as the columns (t, b, n)."""
    nsum = [(0.0, 0.0, 0.0) for _ in points]
    for a, b, c in triangles:
        fn = cross(sub(points[b], points[a]), sub(points[c], points[a]))
        for v in (a, b, c):
            nsum[v] = add(nsum[v], fn)
    out = []
    for i, p in enumerate(points):
        nrm = normalize(nsum[i])  # @line L9
        e = sub(points[nbrs[i][0]], p)
        t = normalize(sub(e, scale(nrm, dot(e, nrm))))
        out.append((t, cross(nrm, t), nrm))
    return out


def to_local(f, v):
    return (dot(f[0], v), dot(f[1], v), dot(f[2], v))


def to_world(f, d):
    return add(add(scale(f[0], d[0]), scale(f[1], d[1])), scale(f[2], d[2]))


def precompute(rest, triangles, lam=LAM, iters=ITERS):
    """Return (nbrs, deltas) of the rest mesh."""
    nbrs = neighbors(len(rest), triangles)
    s = smooth(rest, nbrs, lam, iters)  # @line L1
    fr = frames(s, triangles, nbrs)
    deltas = [to_local(fr[i], sub(rest[i], s[i])) for i in range(len(rest))]  # @line L2
    return nbrs, deltas


def lbs(vertices, weights, palette):
    """Linear blend skinning with sparse weights (joint, weight)."""
    out = []
    for v, wi in zip(vertices, weights):
        p = (0.0, 0.0, 0.0)
        for j, w in wi:
            m = palette[j]
            q = tuple(m[r][0] * v[0] + m[r][1] * v[1] + m[r][2] * v[2] + m[r][3] for r in range(3))
            p = add(p, scale(q, w))
        out.append(p)
    return out


def delta_mush(rest, triangles, weights, palette, pre=None, lam=LAM, iters=ITERS, deformed=None):
    """Return the delta mush result of one frame.

    deformed: the skinned mesh to correct; if None, linear blend skinning of
    rest with weights and palette is used.
    """
    if pre is None:
        pre = precompute(rest, triangles, lam, iters)
    nbrs, deltas = pre
    u = deformed if deformed is not None else lbs(rest, weights, palette)  # @line L3
    su = smooth(u, nbrs, lam, iters)  # @line L4
    fr = frames(su, triangles, nbrs)  # @line L5
    out = [add(su[i], to_world(fr[i], deltas[i])) for i in range(len(rest))]  # @line L6
    return out  # @line L7
test_delta_mush.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/delta-mush/. The authors are listed in prov/118N6H.jsonl.
"""Tests of delta mush.

They check the smoothing against powers of the dense smoothing matrix, the
frames, the bind pose, a common rigid motion, a full twist of a tube (the
middle ring does not collapse to the axis), a bend of the tube (the middle
ring keeps more of its radius than with linear blend skinning), and the
case of rigid weights.
"""

import math
import random

import anim
from delta_mush import delta_mush, frames, lbs, neighbors, precompute, smooth


def smoothstep(x):
    x = min(1.0, max(0.0, x))
    return x * x * (3.0 - 2.0 * x)


def tube(nr=12, ny=13, radius=0.5, length=2.0, rigid=False):
    """An open tube along y with two joints, at y = 0 and y = 1."""
    verts, weights = [], []
    for r in range(ny):
        y = length * r / (ny - 1)
        w1 = (1.0 if y > 1.0 else 0.0) if rigid else smoothstep((y - 0.6) / 0.8)
        for k in range(nr):
            a = 2.0 * math.pi * k / nr
            verts.append((radius * math.cos(a), y, radius * math.sin(a)))
            weights.append([jw for jw in ((0, 1.0 - w1), (1, w1)) if jw[1] > 0.0])
    tris = []
    for r in range(ny - 1):
        for k in range(nr):
            a, b = r * nr + k, r * nr + (k + 1) % nr
            c, d = a + nr, b + nr
            tris += [(a, c, b), (b, c, d)]
    return verts, tris, weights


def rand_T(rng):
    q = anim.q_normalize([rng.gauss(0.0, 1.0) for _ in range(4)])
    return anim.make_T(anim.q_to_mat3(q), tuple(rng.uniform(-2.0, 2.0) for _ in range(3)))


def about(axis, angle, c):
    r = anim.q_to_mat3(anim.q_from_axis_angle(axis, angle))
    return anim.make_T(r, anim.sub(c, anim.matvec(r, c)))


def close(a, b, tol):
    return all(abs(x - y) <= tol for x, y in zip(a, b))


def ring_radius(points, ring, nr, center):
    pts = points[ring * nr : (ring + 1) * nr]
    return sum(anim.norm(anim.sub(p, center)) for p in pts) / nr


def test_smoothing_matches_matrix_power():
    rng = random.Random(1)
    verts, tris, _ = tube(nr=6, ny=5)
    verts = [anim.add(v, tuple(rng.uniform(-0.05, 0.05) for _ in range(3))) for v in verts]
    nb = neighbors(len(verts), tris)
    n = len(verts)
    m = anim.eye(n)
    for i in range(n):
        for k in nb[i]:
            m[i][k] += 0.4 / len(nb[i])
        m[i][i] -= 0.4
    p = anim.eye(n)
    for _ in range(7):
        p = anim.mul(m, p)
    ref = anim.mul(p, [list(v) for v in verts])
    got = smooth(verts, nb, 0.4, 7)
    for a, b in zip(got, ref):
        assert close(a, b, 1e-12)


def test_frames_are_orthonormal():
    rng = random.Random(2)
    verts, tris, _ = tube()
    verts = [anim.add(v, tuple(rng.uniform(-0.05, 0.05) for _ in range(3))) for v in verts]
    nb = neighbors(len(verts), tris)
    for t, b, n in frames(smooth(verts, nb), tris, nb):
        for u in (t, b, n):
            assert abs(anim.norm(u) - 1.0) < 1e-12
        assert abs(anim.dot(t, b)) < 1e-12 and abs(anim.dot(t, n)) < 1e-12 and abs(anim.dot(b, n)) < 1e-12
        assert close(anim.cross(t, b), n, 1e-12)
    # the normals of the tube point outward
    for v, (_, _, n) in zip(verts, frames(verts, tris, nb)):
        assert n[0] * v[0] + n[2] * v[2] > 0.0


def test_bind_pose_gives_rest_mesh():
    verts, tris, weights = tube()
    out = delta_mush(verts, tris, weights, [anim.eye(4), anim.eye(4)])
    for a, b in zip(out, verts):
        assert close(a, b, 1e-12)


def test_common_rigid_motion():
    rng = random.Random(3)
    verts, tris, weights = tube()
    pre = precompute(verts, tris)
    for _ in range(3):
        g = rand_T(rng)
        out = delta_mush(verts, tris, weights, [g, g], pre=pre)
        for a, v in zip(out, verts):
            assert close(a, anim.T_apply(g, v), 1e-9)


def test_full_twist_does_not_collapse_to_the_axis():
    # LBS puts the middle ring of a twist by pi on the axis; delta mush keeps
    # it open, but it does not restore the rest radius (see the page)
    verts, tris, weights = tube()
    pre = precompute(verts, tris)
    pal = [anim.eye(4), about((0.0, 1.0, 0.0), math.pi, (0.0, 0.0, 0.0))]
    out = delta_mush(verts, tris, weights, pal, pre=pre)
    ref = lbs(verts, weights, pal)
    c = (0.0, 1.0, 0.0)
    assert ring_radius(ref, 6, 12, c) < 1e-9
    assert 0.25 < ring_radius(out, 6, 12, c) < 0.5


def test_bend_keeps_more_radius_than_lbs():
    verts, tris, weights = tube()
    pre = precompute(verts, tris)
    pal = [anim.eye(4), about((0.0, 0.0, 1.0), math.pi / 2, (0.0, 1.0, 0.0))]
    out = delta_mush(verts, tris, weights, pal, pre=pre)
    ref = lbs(verts, weights, pal)
    c = (0.0, 1.0, 0.0)
    assert abs(ring_radius(out, 6, 12, c) - 0.5) < abs(ring_radius(ref, 6, 12, c) - 0.5)


def test_rigid_weights_are_smoothed():
    # with weights of 0 or 1 linear blend skinning tears the tube at the
    # joint; delta mush gives a gap between rings close to the rest one
    verts, tris, weights = tube(rigid=True)
    pal = [anim.eye(4), about((0.0, 0.0, 1.0), math.pi / 3, (0.0, 1.0, 0.0))]
    out = delta_mush(verts, tris, weights, pal)
    ref = lbs(verts, weights, pal)
    rest_edge = anim.norm(anim.sub(verts[6 * 12], verts[7 * 12]))

    def worst(points):
        return max(abs(anim.norm(anim.sub(points[6 * 12 + k], points[7 * 12 + k])) - rest_edge) for k in range(12))

    assert worst(out) < worst(ref)


def test_any_deformer_and_identity():
    # the correction of the rest mesh itself is the rest mesh, whatever the
    # weights and the palette
    rng = random.Random(4)
    verts, tris, weights = tube()
    out = delta_mush(verts, tris, weights, [rand_T(rng), rand_T(rng)], deformed=list(verts))
    for a, b in zip(out, verts):
        assert close(a, b, 1e-12)

History

Joe Mancewicz, Matt Derksen, Hans Rijpkema and Cyrus Wilson of Rhythm and Hues presented delta mush at DigiPro 2014. Commercial animation tools soon added it as a deformer. In 2019 Binh Huy Le and J. P. Lewis turned it into direct delta mush, a direct skinning method with precomputed data.

References

  1. Joe Mancewicz, Matt L. Derksen, Hans Rijpkema and Cyrus A. Wilson, Delta mush, smoothing deformations while preserving detail, Proceedings of the Fourth Symposium on Digital Production (DigiPro '14), pages 7-11, 2014, the smoothing of the rest mesh and the skinned mesh, the deltas in local frames, and the examples

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 time.precompute
  • 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