Algorithm Search⌘K

Algorithmadvanced

Bounded biharmonic weights

Also called BBW.

Compute smooth, local and positive skinning weights for points, bones and cages by minimizing the Laplacian energy under bound constraints.

Time
O(n^3 + m I n^3) total
Space
O(n^2 + m n) extra
Where
I = the number of active set iterations per handle; m = the number of handles; n = the number of mesh vertices
Properties
deterministicexactofflineiterative

Bounded biharmonic weights (BBW) are skinning weights that an artist can use with any mix of handles: points, bones and cages. For each handle, the weight is the function on the shape that is 1 at the handle, 0 at the other handles, stays between 0 and 1, and is as smooth as possible in the sense of the Laplacian energy ∫(Δw)2\int (\Delta w)^2. Jacobson, Baran, Popović and Sorkine (2011) showed that the bounds are the key: without them, the smoothest weights go negative or above 1, which moves parts of the shape in the wrong direction. After discretization on a triangle or tetrahedral mesh, each weight is the solution of a convex quadratic program. The weights then drive linear blend skinning in real time.

In plain words

A skinning weight says how much a point of the shape follows a handle. It should be 1 on the handle, fade smoothly, and be 0 on the other handles. The smoothest such function has no corners and no sharp peaks, but it can overshoot: past a handle, it can keep going down below 0, and then the point moves against its handle. BBW keeps the smoothest function, but forbids values below 0 or above 1. The result is smooth where it is free, and exactly 0 in the regions that the handle should not touch. Computing it means solving one small optimization problem per handle on a mesh of the shape. The fast version solves the handles one at a time, then divides the weights at each point by their sum.

The problem

The input is a mesh of the shape (triangles in 2D, tetrahedra in 3D) with vertices viv_i, i=1,…,ni = 1, \ldots, n, and mm handles. The output is a weight wk(vi)w_k(v_i) for each handle kk and vertex ii. In the continuous form, the weights minimize ∑k12∫Ω(Δwk)2 dV\sum_k \frac12 \int_\Omega (\Delta w_k)^2 \, dV subject to:

  • wk=δjkw_k = \delta_{jk} on handle jj, which is the interpolation of the handles;
  • wkw_k is linear on each face of a cage, if there are cages;
  • ∑kwk=1\sum_k w_k = 1 everywhere, which is the partition of unity;
  • 0≤wk≤10 \le w_k \le 1 everywhere, which are the bounds.

The discrete energy of one weight is 12w⊤Qw\frac12 w^\top Q w with Q=LM−1LQ = L M^{-1} L, where LL is the cotangent Laplacian of the mesh as a stiffness matrix and MM is the lumped mass matrix. In the faster variant, the partition of unity is dropped, each handle is solved on its own, and the weights are divided by their sum at the end. The code in impl/python implements the faster variant for point handles on a 2D triangle mesh.

The algorithm

  1. BBW(mesh, handles)
  2. 1build the cotangent stiffness matrix L and the lumped mass matrix M
  3. 2Q ← L M⁻¹ L
  4. 3for each handle k:
  5. 4w_k ← argmin ½ wᵀ Q w subject to w = δ_jk at handle j for every j, and 0 ≤ w ≤ 1
  6. 5for each vertex i: divide every w_k(v_i) by Σ_k w_k(v_i)
  7. 6return the weights

Line L4 is a convex quadratic program with bound constraints. The paper solves it with a general solver (MOSEK). The code uses a primal active set method: it keeps a working set of variables held at a bound, solves the equality problem in the other variables, steps to the first bound that blocks the step, and releases the bound with the most negative multiplier when the step is zero. It stops when every multiplier is nonnegative, which is the KKT condition of the problem.

Line L5 enforces the partition of unity. The division changes the weights a little, so the result is not exactly the solution of the full problem with the constraint ∑kwk=1\sum_k w_k = 1, but it keeps the bounds, the interpolation and the smoothness in practice.

Example

Take a strip of width 4 and height 1, meshed as a grid with five vertices along the bottom at x=0,1,2,3,4x = 0, 1, 2, 3, 4, five along the top, and two triangles per square. Put handle 1 at the bottom vertex x=0x = 0 and handle 2 at the bottom vertex x=2x = 2. The weights of handle 1 along the bottom row are:

xx 0 1 2 3 4
unbounded biharmonic 1 0.5914 0 −0.3326-0.3326 −0.4325-0.4325
bounded biharmonic 1 0.5428 0 0 0

Without the bounds, the smooth weight keeps its slope past handle 2 and reaches −0.43-0.43 at the end of the strip. With that weight, the end of the strip moves away from handle 1 when handle 1 moves. The bounded weight is exactly 0 past handle 2, so the end of the strip follows only handle 2. With two handles, the two weights already sum to 1 at every vertex, so line L5 changes nothing here. The tests check these numbers to four decimals.

Correctness

The proofs are in proofs/correctness.md.

  • Each problem has one solution. QQ is positive semidefinite, and its null space is the constant vectors. A weight that is fixed at a handle vertex rules out the constants, so QQ is positive definite on the free variables, and the problem is strictly convex.
  • The active set method returns it. When the method stops, the point is feasible and satisfies the KKT conditions, which are sufficient for a convex problem. The energy never increases, and if no step has length zero, no working set repeats, so the method stops after a finite number of steps.
  • The weights interpolate the handles and are bounded. These are constraints of line L4, and line L5 keeps them, because it divides by a positive sum.
  • The weights sum to 1. This is the effect of line L5.

The paper reports that the weights are local, with small supports, in its experiments; this is not proved.

Proof: Each bounded biharmonic weight is the unique minimizer of a strictly convex box QP, and the active set method finds itfull

We use the notation of the page. LL is the symmetric stiffness matrix with zero row sums of a connected mesh, MM is diagonal with positive entries, and Q=LM−1LQ = L M^{-1} L. For one handle, DD is the set of handle vertices with the fixed values xDx_D, and FF is the set of the other vertices. The arithmetic is exact.

The problem is strictly convex

Lemma 1. x⊤Lx≥0x^\top L x \ge 0, with equality exactly for constant xx.

Proof. LL is the stiffness matrix of piecewise linear finite elements, so x⊤Lx=∫Ω∥∇xh∥2x^\top L x = \int_\Omega \lVert \nabla x_h \rVert^2 for the piecewise linear function xhx_h with the values xx at the vertices. This is at least 0, and it is 0 exactly when ∇xh=0\nabla x_h = 0 on every triangle, that is, when xhx_h is constant on every triangle. Neighboring triangles share vertices, so on a connected mesh xx is constant. □\square

This holds on every mesh, also with obtuse angles, where some cotangent weights are negative.

Lemma 2. QQ is positive semidefinite, its null space is the constant vectors, and if D≠∅D \ne \emptyset, the block QFFQ_{FF} is positive definite.

Proof. x⊤Qx=(Lx)⊤M−1(Lx)≥0x^\top Q x = (L x)^\top M^{-1} (L x) \ge 0, with equality if and only if Lx=0L x = 0. Lx=0L x = 0 implies x⊤Lx=0x^\top L x = 0, so xx is constant by Lemma 1, and constants satisfy Lx=0L x = 0. For y∈RFy \in \mathbb{R}^F, let xx be yy on FF and 0 on DD. Then y⊤QFFy=x⊤Qxy^\top Q_{FF} y = x^\top Q x, which is zero only if xx is constant, and x=0x = 0 on D≠∅D \ne \emptyset, so y=0y = 0. □\square

Theorem 1. The problem of line L4, min⁡12x⊤Qx\min \frac12 x^\top Q x subject to xDx_D fixed and 0≤xF≤10 \le x_F \le 1, has exactly one minimizer, and a feasible xx is the minimizer if and only if, with g=Qxg = Q x, for every i∈Fi \in F: gi=0g_i = 0 if 0<xi<10 < x_i < 1, gi≥0g_i \ge 0 if xi=0x_i = 0, and gi≤0g_i \le 0 if xi=1x_i = 1.

Proof. In the variables xFx_F, the objective is 12xF⊤QFFxF+xF⊤QFDxD+const\frac12 x_F^\top Q_{FF} x_F + x_F^\top Q_{FD} x_D + \text{const}, which is strictly convex by Lemma 2, and the feasible set is a nonempty compact box. So a minimizer exists and is unique. The gradient in xFx_F is (Qx)F=gF(Q x)_F = g_F, and the conditions above are the KKT conditions of a box, with the multiplier gig_i of a lower bound and −gi-g_i of an upper bound. For a convex problem with linear constraints, they are necessary and sufficient. □\square

The active set method

Let W⊆FW \subseteq F be the working set, with each i∈Wi \in W held at a bound bi∈{0,1}b_i \in \{0, 1\}. One iteration computes the minimizer x^\hat x of the objective with xDx_D fixed and xW=bWx_W = b_W, over the free variables F∖WF \setminus W with no bounds; it exists and is unique by Lemma 2.

Lemma 3. Every iterate is feasible, and the objective never increases.

Proof. The first iterate is xF=0x_F = 0, which is feasible. The step p=x^−xp = \hat x - x is taken with the length α∈[0,1]\alpha \in [0, 1], the largest that keeps every free variable in [0,1][0, 1], so the new point is feasible. The objective along the segment from xx to x^\hat x is a convex quadratic with its minimum at x^\hat x, so it does not increase on [0,1][0, 1]. □\square

Theorem 2. If the method stops, it returns the minimizer of Theorem 1.

Proof. It stops only when p=0p = 0, that is, x=x^x = \hat x, and every multiplier of WW is nonnegative. x=x^x = \hat x means gi=0g_i = 0 for every i∈F∖Wi \in F \setminus W. The multipliers are gig_i for ii at the lower bound and −gi-g_i at the upper bound, so the KKT conditions of Theorem 1 hold for i∈Wi \in W. For i∈F∖Wi \in F \setminus W with xix_i at a bound, gi=0g_i = 0 satisfies the condition too. □\square

Theorem 3. If no step has the length α=0\alpha = 0, the method stops after a finite number of iterations.

Proof. After a release, the point xx minimizes the objective on the old working set, and the released variable rr has a negative multiplier, so moving xrx_r into the box decreases the objective to first order, and x^\hat x on the new working set has a strictly smaller objective than xx. With α>0\alpha > 0, the new point has a strictly smaller objective. Between two releases, each blocked step adds one variable to WW, so there are at most ∣F∣|F| steps before p=0p = 0. When p=0p = 0 for a working set WW, the point is the minimizer of the objective on WW, and its value is a function of WW. These values strictly decrease from one release to the next, so no working set repeats at a release, and there are finitely many working sets. □\square

Steps of the length zero can happen at degenerate points, where a variable is at a bound but not in WW. The tests compare the result with a brute force search on small problems and check the KKT conditions on a larger one.

The brute force reference

For every assignment of each i∈Fi \in F to {0,1,free}\{0, 1, \text{free}\}, the reference solves the equality problem and keeps the feasible result of the smallest objective. The minimizer of Theorem 1 has some assignment: its variables at a bound and the others free. On that face, it minimizes the objective over the open set of its free variables inside the box, so it is the unconstrained minimizer of the face, which the reference computes. So the reference returns the minimizer.

The normalization

Line L4 gives wk(vi)∈[0,1]w_k(v_i) \in [0, 1] and wk=δjkw_k = \delta_{jk} at handle jj. At a handle vertex hjh_j, ∑kwk(hj)=1\sum_k w_k(h_j) = 1, so line L5 changes nothing there, and the interpolation holds. At any other vertex, the sum sis_i is positive whenever some weight is positive, and then wk(vi)/si∈[0,1]w_k(v_i) / s_i \in [0, 1] and the new sum is 1. If all weights at a vertex are 0, the division is not defined; this does not happen on a connected mesh in the tests, and the code would raise an error.

Complexity

The costs are in the real RAM model. The code builds QQ as a dense matrix in O(n3)O(n^3) and solves a dense system of size up to nn in each active set iteration, so the total is O(n3+mIn3)O(n^3 + m I n^3). LL and MM are sparse, and QQ is sparse with the pattern of the two-ring neighborhoods, so a sparse solver is much faster on real meshes. The weights are computed once, before the animation; at run time, skinning costs O(nm)O(n m) per frame, or O(nK)O(n K) if only the KK largest weights of each vertex are kept.

Properties

  • Smooth: the weights are smooth where the bounds are not active, also at point handles.
  • Bounded: 0≤wk≤10 \le w_k \le 1.
  • Interpolating: each weight is 1 on its handle and 0 on the others.
  • Shape aware: the weights follow the mesh, so they do not cross a gap of the shape.
  • Local in practice: the bounds make a weight exactly 0 in the regions behind other handles.
  • Precomputed: the cost is all before the animation.

Variants and improvements

  • Full problem. Solve all handles together with the partition of unity as a constraint. The problem is larger, but it gives the exact minimizer with ∑kwk=1\sum_k w_k = 1.
  • Harmonic weights. Minimize ∫∥∇w∥2\int \lVert \nabla w \rVert^2 instead. The maximum principle gives the bounds for free, but at a point handle the weight has a sharp peak, which is a reason to use the biharmonic energy. Harmonic coordinates use this energy for cages.
  • Heat weights. Automatic rigging computes weights by heat diffusion on the surface, which is a single linear solve for all bones with nonnegative weights, but it works on the surface and needs a visibility test.
  • Other deformation models. The same weights can blend affine transforms of the handles in other schemes, for example with as-rigid-as-possible deformation on a reduced space.

When to use it

Use bounded biharmonic weights when an artist wants to deform a shape with a few handles of mixed types and needs smooth weights that are positive and local. It works for 2D images and drawings with a triangle mesh, and for 3D characters with a tetrahedral mesh of the volume. If you only have bones and a closed surface, the heat weights of automatic rigging are faster to compute. If you have examples of the deformed shape, fit the weights to them with skinning decomposition.

Pitfalls

  • Forgetting the bounds. The unbounded minimizer is a single linear solve, but it overshoots, as in the example. The bounds are the main idea of the method.
  • Normalizing is not free. Line L5 changes the weights. If the sums are far from 1, the result can lose smoothness, and the full problem is the better choice.
  • The mesh. The weights live on the mesh, so the mesh must cover the shape and its handles must be mesh vertices. In 3D, the method needs a volume mesh, not only the surface.
  • Obtuse triangles. Cotangent weights can be negative on meshes with obtuse angles. QQ stays positive semidefinite, but the weights can lose quality. Use a mesh with good triangles.
  • Solver time. A general QP solver on a large mesh takes seconds to minutes. The weights are a precomputation, so this is often acceptable, but it limits interactive editing of the handles.

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
bounded_biharmonic_weights.py 178 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bounded-biharmonic-weights/. The authors are listed in prov/W8RNMB.jsonl.
"""Bounded biharmonic weights (Jacobson, Baran, Popovic and Sorkine 2011), in 2D.

The domain is a triangle mesh with vertices v_i, and the handles are points
at mesh vertices. For each handle k, the weight w_k minimizes the discrete
Laplacian energy

    (1/2) w^T Q w,   Q = L M^(-1) L,

where L is the cotangent stiffness matrix and M the lumped mass matrix,
subject to w_k = 1 at handle k, w_k = 0 at the other handles, and
0 <= w_k <= 1 at every vertex. This is the faster variant of the paper: the
partition of unity is not a constraint, each handle is solved on its own,
and the weights are divided by their sum at the end.

Each problem is a convex quadratic program with box constraints. It is
solved by a primal active set method: keep a working set of variables held
at a bound, solve the equality problem on the others, step to the first
bound that blocks, and release the bound with the most negative multiplier
when no step is possible.
"""

import itertools
import math

from anim import solve, sub


def cotangent_laplacian(verts, tris):
    """Return the symmetric stiffness matrix L with L_ij = -(cot a + cot b) / 2 and zero row sums."""
    n = len(verts)
    lap = [[0.0] * n for _ in range(n)]
    for t in tris:
        for c in range(3):
            o, u, v = t[c], t[(c + 1) % 3], t[(c + 2) % 3]
            a, b = sub(verts[u], verts[o]), sub(verts[v], verts[o])
            cot = (a[0] * b[0] + a[1] * b[1]) / abs(a[0] * b[1] - a[1] * b[0])
            lap[u][v] -= 0.5 * cot
            lap[v][u] -= 0.5 * cot
            lap[u][u] += 0.5 * cot
            lap[v][v] += 0.5 * cot
    return lap


def lumped_mass(verts, tris):
    """Return the lumped (barycentric) mass of each vertex: a third of the area of its triangles."""
    m = [0.0] * len(verts)
    for t in tris:
        a, b = sub(verts[t[1]], verts[t[0]]), sub(verts[t[2]], verts[t[0]])
        area = 0.5 * abs(a[0] * b[1] - a[1] * b[0])
        for i in t:
            m[i] += area / 3.0
    return m


def bilaplacian(lap, m):
    """Return Q = L M^(-1) L."""
    n = len(lap)
    return [[sum(lap[i][k] * lap[k][j] / m[k] for k in range(n)) for j in range(n)] for i in range(n)]


def energy(q, w):
    """Return (1/2) w^T Q w."""
    return 0.5 * sum(w[i] * sum(q[i][j] * w[j] for j in range(len(w))) for i in range(len(w)))


def _solve_free(q, x, free):
    """Return the values on free that minimize (1/2) x^T Q x with the other entries of x fixed."""
    others = [j for j in range(len(x)) if j not in free]
    a = [[q[i][j] for j in free] for i in free]
    rhs = [-sum(q[i][j] * x[j] for j in others) for i in free]
    return solve(a, rhs)


def box_qp(q, fixed, lo=0.0, hi=1.0, tol=1e-12, max_iter=10000):
    """Minimize (1/2) x^T Q x subject to x_i = fixed[i] for i in fixed and lo <= x <= hi elsewhere.

    Q restricted to the variables that are not fixed must be positive
    definite. Return (x, iterations).
    """
    n = len(q)
    x = [fixed.get(i, lo) for i in range(n)]
    var = [i for i in range(n) if i not in fixed]
    work = {i: lo for i in var}  # every variable starts at its lower bound
    for it in range(max_iter):
        free = [i for i in var if i not in work]
        p = {}
        if free:
            new = _solve_free(q, x, free)
            p = {i: new[k] - x[i] for k, i in enumerate(free)}
        if all(abs(d) <= tol for d in p.values()):
            for i, d in p.items():
                x[i] += d
            g = [sum(q[i][j] * x[j] for j in range(n)) for i in range(n)]
            mult = {i: (g[i] if b == lo else -g[i]) for i, b in work.items()}
            if not mult or min(mult.values()) >= -tol:
                return x, it
            del work[min(mult, key=mult.get)]
            continue
        alpha, block = 1.0, None
        for i, d in p.items():
            if d < 0.0 and (lo - x[i]) / d < alpha:
                alpha, block = (lo - x[i]) / d, (i, lo)
            elif d > 0.0 and (hi - x[i]) / d < alpha:
                alpha, block = (hi - x[i]) / d, (i, hi)
        for i, d in p.items():
            x[i] += alpha * d
        if block is not None:
            x[block[0]] = block[1]
            work[block[0]] = block[1]
    raise RuntimeError("active set method did not converge")


def brute_force_box_qp(q, fixed, lo=0.0, hi=1.0):
    """Return the minimizer of the same problem by trying every face of the box."""
    n = len(q)
    var = [i for i in range(n) if i not in fixed]
    best, best_e = None, math.inf
    for states in itertools.product((lo, hi, None), repeat=len(var)):
        x = [fixed.get(i, 0.0) for i in range(n)]
        free = []
        for i, s in zip(var, states):
            if s is None:
                free.append(i)
            else:
                x[i] = s
        if free:
            for i, val in zip(free, _solve_free(q, x, free)):
                x[i] = val
        if any(x[i] < lo - 1e-12 or x[i] > hi + 1e-12 for i in var):
            continue
        e = energy(q, x)
        if e < best_e:
            best, best_e = x, e
    return best, best_e


def bbw(verts, tris, handles, bounded=True, normalize=True):
    """Return w with w[k][i] the weight of handle k at vertex i.

    handles is a list of vertex indices. With bounded=False the weights are
    the unbounded biharmonic weights (the same problem without 0 <= w <= 1).
    """
    lap = cotangent_laplacian(verts, tris)  # @line L1
    m = lumped_mass(verts, tris)
    q = bilaplacian(lap, m)  # @line L2
    n = len(verts)
    weights = []
    for k in range(len(handles)):  # @line L3
        fixed = {h: (1.0 if j == k else 0.0) for j, h in enumerate(handles)}
        if bounded:
            w, _ = box_qp(q, fixed)  # @line L4
        else:
            w = [fixed.get(i, 0.0) for i in range(n)]
            free = [i for i in range(n) if i not in fixed]
            for i, val in zip(free, _solve_free(q, w, free)):
                w[i] = val
        weights.append(w)
    if normalize:
        for i in range(n):  # @line L5
            s = sum(w[i] for w in weights)
            for w in weights:
                w[i] /= s
    return weights  # @line L6


def grid(nx, ny, width=1.0, height=1.0):
    """Return (verts, tris) of a regular grid split into right triangles."""
    verts = [(width * i / (nx - 1), height * j / (ny - 1)) for j in range(ny) for i in range(nx)]
    tris = []
    for j in range(ny - 1):
        for i in range(nx - 1):
            a, b = j * nx + i, j * nx + i + 1
            c, d = a + nx, b + nx
            tris.append((a, b, d))
            tris.append((a, d, c))
    return verts, tris
test_bounded_biharmonic_weights.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bounded-biharmonic-weights/. The authors are listed in prov/W8RNMB.jsonl.
"""Tests of bounded biharmonic weights.

The active set solver is compared with a brute force search over every face
of the box and checked against the KKT conditions. The weights interpolate
the handles, lie in [0, 1], sum to 1 after normalization and keep the
symmetry of the domain. Without the bounds, the weights of a strip go
negative, which the bounds prevent. The check values of the page hold.
"""

import random

from bounded_biharmonic_weights import (
    bbw,
    bilaplacian,
    box_qp,
    brute_force_box_qp,
    cotangent_laplacian,
    energy,
    grid,
    lumped_mass,
)


def q_of(verts, tris):
    return bilaplacian(cotangent_laplacian(verts, tris), lumped_mass(verts, tris))


def test_laplacian_and_mass():
    verts, tris = grid(4, 3, width=3.0, height=2.0)
    lap = cotangent_laplacian(verts, tris)
    n = len(verts)
    for i in range(n):
        assert abs(sum(lap[i])) < 1e-12
        for j in range(n):
            assert abs(lap[i][j] - lap[j][i]) < 1e-12
    assert abs(sum(lumped_mass(verts, tris)) - 6.0) < 1e-12


def test_active_set_against_brute_force_on_meshes():
    for nx, ny, w, handles in ((3, 2, 2.0, (0, 1)), (3, 3, 1.0, (0, 8)), (4, 2, 3.0, (0, 1, 7))):
        verts, tris = grid(nx, ny, width=w)
        q = q_of(verts, tris)
        for k in range(len(handles)):
            fixed = {h: (1.0 if j == k else 0.0) for j, h in enumerate(handles)}
            x, _ = box_qp(q, fixed)
            _, e = brute_force_box_qp(q, fixed)
            assert abs(energy(q, x) - e) <= 1e-10 * (1.0 + e)


def test_active_set_against_brute_force_on_random_problems():
    rng = random.Random(6)
    for _ in range(15):
        n = 7
        b = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(n)]
        q = [[sum(b[k][i] * b[k][j] for k in range(n)) + (0.1 if i == j else 0.0) for j in range(n)] for i in range(n)]
        fixed = {0: 1.0, 1: 0.0}
        x, _ = box_qp(q, fixed)
        _, e = brute_force_box_qp(q, fixed)
        assert abs(energy(q, x) - e) <= 1e-10 * (1.0 + e)


def test_kkt_conditions():
    verts, tris = grid(7, 7)
    q = q_of(verts, tris)
    handles = (0, 6, 24, 45)
    for k in range(len(handles)):
        fixed = {h: (1.0 if j == k else 0.0) for j, h in enumerate(handles)}
        x, _ = box_qp(q, fixed)
        g = [sum(q[i][j] * x[j] for j in range(len(x))) for i in range(len(x))]
        for i in range(len(x)):
            if i in fixed:
                continue
            assert -1e-15 <= x[i] <= 1.0 + 1e-15
            if 1e-12 < x[i] < 1.0 - 1e-12:
                assert abs(g[i]) < 1e-9
            elif x[i] <= 1e-12:
                assert g[i] > -1e-9
            else:
                assert g[i] < 1e-9


def test_interpolation_bounds_and_partition_of_unity():
    verts, tris = grid(7, 7)
    handles = [0, 6, 24, 45]
    w = bbw(verts, tris, handles)
    for k, h in enumerate(handles):
        for j in range(len(handles)):
            assert abs(w[j][h] - (1.0 if j == k else 0.0)) < 1e-12
    for i in range(len(verts)):
        assert abs(sum(wk[i] for wk in w) - 1.0) < 1e-12
        assert all(-1e-15 <= wk[i] <= 1.0 + 1e-12 for wk in w)


def test_symmetry():
    verts, tris = grid(7, 7)
    w = bbw(verts, tris, [0, 6, 42, 48])
    for i in range(7):
        for j in range(7):
            assert abs(w[0][j * 7 + i] - w[0][i * 7 + j]) < 1e-9
            assert abs(w[1][j * 7 + i] - w[2][i * 7 + j]) < 1e-9


def test_bounds_matter_on_a_strip():
    verts, tris = grid(5, 2, width=4.0)
    q = q_of(verts, tris)
    free = bbw(verts, tris, [0, 2], bounded=False, normalize=False)
    bound = bbw(verts, tris, [0, 2], normalize=False)
    assert min(free[0]) < -0.4 and max(free[1]) > 1.4
    assert min(bound[0]) >= 0.0 and max(bound[1]) <= 1.0
    assert energy(q, bound[0]) >= energy(q, free[0])
    verts, tris = grid(3, 3)
    a = bbw(verts, tris, [0, 8], bounded=False)
    b = bbw(verts, tris, [0, 8])
    assert max(abs(x - y) for x, y in zip(a[0], b[0])) < 1e-12


def test_check_values_of_the_page():
    verts, tris = grid(5, 2, width=4.0)
    free = bbw(verts, tris, [0, 2], bounded=False, normalize=False)
    bound = bbw(verts, tris, [0, 2], normalize=False)
    want_free = (1.0, 0.5914, 0.0, -0.3326, -0.4325)
    want_bound = (1.0, 0.5428, 0.0, 0.0, 0.0)
    for i in range(5):
        assert abs(free[0][i] - want_free[i]) < 5e-5
        assert abs(bound[0][i] - want_bound[i]) < 5e-5
    for i in range(10):
        assert abs(bound[0][i] + bound[1][i] - 1.0) < 1e-12

History

Linear blend skinning with painted weights was the standard for years, and automatic weights came from heat diffusion, as in automatic rigging (Baran and Popović 2007), or from harmonic coordinates for cages. Jacobson, Baran, Popović and Sorkine (2011) wrote weights for any mix of handles as the minimizers of the Laplacian energy with bounds, which made the weights smooth at point handles and kept them positive. Later work by the same group and others added faster solvers, weights with fewer overshoots of other kinds, and weights for other skinning models.

References

  1. Alec Jacobson, Ilya Baran, Jovan Popović and Olga Sorkine, Bounded biharmonic weights for real-time deformation, ACM Transactions on Graphics 30(4), SIGGRAPH 2011, article 78, the energy with the constraints (3) to (6), where (5) is the partition of unity; the discrete energy with L M^(-1) L in equation (8); and the faster variant that drops (5), solves each weight on its own and normalizes (Fig. 6)

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.total
  • 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