Algorithmcore
Motion retargeting
Also called retargetting motion to new characters.
Adapt a motion recorded on one character to another with different proportions, keeping constraints such as foot contacts by spacetime optimization.
- Time
- O(I (m^2 s + m^3)) total
- Space
- O(m s + m^2) extra
- Where
- I = the number of iterations; m = the number of constraint rows; s = the number of control points of the displacement
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Motion retargeting adapts a motion made for one character to a second character with other proportions. If you copy the joint angles of a walk from a tall actor to a short character, the feet of the short character do not reach the floor, slide during the contacts, or go through the floor. Gleicher (1998) wrote the fix as an optimization over the whole motion at once: add a smooth displacement to every degree of freedom, as small as possible, so that the new character meets the constraints of the motion, such as a planted foot. The displacement is a B-spline curve in time, so the change is smooth and keeps the details of the original motion. It is a kinematic form of spacetime constraints: there are no forces and no dynamics, only constraints over time and a preference for a small change.
In plain words
The source motion is good, and we want to keep as much of it as we can. The new character has shorter or longer bones, so some important facts of the motion break: the foot no longer touches the floor where and when it should. We write down these facts as constraints: at these frames, the foot is at this point. Then we add a correction curve to every joint angle and to the root, over the whole motion. The correction curve is smooth, so it cannot add jitter. Among all smooth corrections that make the constraints true, we take the smallest one. Frames far from all constraints keep their original values. Frames near a constraint change a little, and the change fades in and out over a few frames.
The problem
A character has the degrees of freedom : a root position and joint angles. The source motion is at the frames . The new character has the same skeleton with other bone lengths, so the same gives other end positions through forward kinematics. The constraints are equations at chosen frames, for example the position of a foot during a contact, often taken from the source motion. The output is a new motion that meets the constraints and stays close to the source.
The displacement is for each degree of freedom , where is the uniform cubic B-spline basis and is the spacing of the control points in frames. The problem is
with a diagonal matrix of weights per degree of freedom. The weights are tuning: they say how much a change of the root position costs against a change of an angle. The spacing is also tuning: a smaller spacing allows faster changes.
The algorithm
RETARGET(source q, new lengths, constraints (t_f, p_f), spacing δ, weights W)- 1
c ← 0 ▷ start from the source motion - 2
repeat - 3
for each constraint f: compute q(t_f) + d(t_f), the residual r_f = g_f - p_f and the Jacobian rows J_f in c - 4
b ← J c - r ▷ the linearized constraints are J c = b - 5
solve (J W⁻¹ Jᵀ) μ = b - 6
c ← W⁻¹ Jᵀ μ ▷ the smallest c with J c = b - 7
until c does not change and r is small - 8
return q(t) + d(t) for every frame
Line L3 is forward kinematics and its Jacobian at each constrained frame, multiplied by the B-spline basis values: the derivative of in is . Lines L4 to L6 replace the constraints by their linearization and take the solution of smallest weighted norm, which is the pseudoinverse solution. This is a step of sequential quadratic programming with the Hessian of the objective only. At a fixed point, the constraints hold and is in the row space of , which is the first order condition of the constrained problem.
The code in impl/python uses a planar leg with a root , a hip angle and a knee angle, so , and a foot position constraint at each frame of a contact.
Gleicher's paper works with full 3D skeletons and more kinds of constraints; the toy keeps only the part that defines the method.
Example
Take a straight leg that hangs down, with all angles 0 and the root at height 2. The source bones have the lengths 1 and 1, so the foot is on the floor at height 0. The new character has the lengths 0.9 and 0.9, so its foot is at height 0.2. Ask for the foot on the floor at frame 8 only, with the spacing , and make the angles very costly, so that only the root moves.
The root height needs the displacement at frame 8, which is a knot. At a knot, the three basis functions that are not zero have the values , and , and the sum of their squares is . The smallest control points with are proportional to the basis values: .
| frame | 2 | 4 | 6 | 8 | 10 | 12 | 14 |
|---|---|---|---|---|---|---|---|
| root height change | 0 | 0 |
At frame 10 the change is , and at frame 12 it is . So the root drops smoothly into the contact and comes back up, and frames 2 and 14 and beyond do not change. The tests check these numbers.
For the walk in the tests, with 24 frames, 10 frames of contact and the bone lengths 0.8 and 0.9 instead of 1 and 1, the method converges in 22 iterations, and the root drops by about 0.22 to 0.30 during the contact.
Correctness
The proofs are in proofs/correctness.md.
- Each step meets the linearized constraints with the smallest change. If has full row rank, is positive definite, and line L6 gives the unique minimizer of subject to .
- A fixed point is a first order optimum. If the iteration stops with , then the constraints hold, and , which is the Lagrange condition of the constrained problem.
- The same character gives the source motion. If the source already meets the constraints, at , so the first step gives .
- Frames far from all constraints do not change. A control point whose basis does not reach any constrained frame has a zero column in , so line L6 gives it the value 0. A frame where only such control points act keeps the source pose.
The method does not have a global guarantee: the constraints are nonlinear, the iteration can fail to converge, and the fixed point can be a local optimum. The tests check the constraints, the first order condition, that feasible neighbors are not better, the far frames and the check value.
Proof: Each retargeting step is the smallest change that meets the linearized constraints, and a fixed point is a first order optimumfull
We use the notation of the page. holds the control points, is diagonal with positive entries, and collects the constraint rows . is the Jacobian of , and . The displacement is linear in , so is a smooth function of whenever the forward kinematics is smooth. The arithmetic is exact.
One step
Lemma 1. If has full row rank, then is symmetric positive definite.
Proof. For , , and because the rows of are independent.
Theorem 1. Let , the right side of line L4. Line L6 gives the unique minimizer of subject to .
Proof. The problem is a strictly convex quadratic with linear equality constraints, so a point is the unique minimizer if and only if it is feasible and satisfies the Lagrange condition for some . The point of line L6 satisfies the Lagrange condition with . It is feasible because by line L5, which has exactly one solution by Lemma 1.
The constraint is , the linearization of at . So each step is a step of sequential quadratic programming for subject to , with the Hessian of the objective and without the curvature of the constraints.
Fixed points
Theorem 2. If and , then is a first order point of the constrained problem: and for some .
Proof. By line L6, , so .
The test checks this condition by projecting onto the null space of , with . Theorem 2 gives a necessary condition only. The tests add a second check: from random feasible neighbors, the value of is not smaller.
The same character
Theorem 3. If the source motion meets the constraints of the new character, the first step gives , and the method returns the source motion.
Proof. At , , so , and line L5 gives , so . Then and , so line L7 stops, and line L8 returns .
Frames far from the constraints
Theorem 4. If a control point has for every constrained frame , then line L6 gives . A frame at which every control point with has this property keeps its source pose.
Proof. The entries of in the column of are , so the column is zero, and the entry of is zero. At such a frame, has only zero terms.
The check value
With one constraint at a knot, only on the root height, and the other degrees of freedom made very costly, has the single row in the root height control points, and the constraint is linear. By Theorem 1, with , and . So and .
Complexity
The costs are in the real RAM model. With constraint rows and unknowns, line L3 costs for the kinematics and the nonzero entries, because each constrained frame meets only four control points per degree of freedom. The code builds densely in and solves it in , so one iteration costs . With the sparsity of , the matrix is banded in time, and one iteration costs for a fixed bandwidth. The number of iterations depends on the problem; it is 22 in the test walk.
Properties
- Smooth: the change is a cubic B-spline, so it is twice continuously differentiable in time, and its frequency content is bounded by the spacing.
- Local in time: frames far from all constraints keep the source values.
- Minimal: among the smooth changes that meet the linearized constraints, it takes the smallest one in the weighted norm.
- Kinematic: there are no forces and no dynamics, so physical effects of the new size, such as a different timing, are not modeled.
- Not exact in general: the constraints hold to the tolerance of the iteration, and only at the constrained frames.
Variants and improvements
- Per frame inverse kinematics. Solve inverse kinematics at each frame of a contact, then smooth the changes. This is faster but can add jitter, because nothing ties the frames together. The spacetime form with a smooth displacement avoids that.
- Foot contact cleanup. Footskate cleanup fixes the foot positions during the contacts with analytic two-bone inverse kinematics per frame and small changes of the bone lengths.
- Displacement maps. The idea of adding a smooth curve to a motion is also the base of motion warping, where the user gives the key changes by hand.
- Other objectives. The objective can measure the change in other quantities, such as end positions, instead of the degrees of freedom. The choice changes the result.
- Shapes instead of skeletons. To copy a deformation of a mesh to a different mesh, use deformation transfer.
When to use it
Use motion retargeting when a motion capture clip or an animation must play on a character with different proportions, and contacts or other spatial facts of the motion must still hold. It is the right tool when the motion matters more than the exact pose at each frame. If the only problem is the foot sliding during contacts, footskate cleanup is simpler and faster.
Pitfalls
- Too many constraints for the spacing. If many constrained frames fall in the support of few control points, is close to rank deficient and the iteration converges slowly or not at all. A smaller spacing, or fewer constrained frames, fixes it. In the toy, a spacing of 4 frames with 10 constrained frames converges much more slowly than a spacing of 2.
- Constraints that cannot all hold. A foot target out of the reach of the new leg has no solution. Choose the targets for the new character, for example by scaling the positions of the source with the size of the character.
- Weights. Without weights, a change of one radian costs as much as a change of one length unit. Set the weights for the units of the skeleton.
- Constraints only at the frames. The constraints hold at the constrained frames and not in between. Add constraints at all frames of a contact.
- Local optima. The method starts from the source motion and finds a nearby solution. For a very different character, the result can be a poor local optimum.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small vectors, matrices, polar decomposition, quaternions and transforms.
This file is copied byte for byte into each impl/python folder that needs it.
It holds no method of a page: no curve, no skinning, no integrator step, no
collision test and no solver of a page. The method of each page lives in its
slug file.
Conventions (prompts/graphics-ext.md, "Mathematical conventions"):
- Vectors are tuples. Functions accept lists too and return tuples.
- Matrices are lists of rows, and a matrix acts on a column vector on the
left: x' = M x.
- Quaternions use the Hamilton convention, scalar first, q = (w, x, y, z)
with i j = k. A unit quaternion q rotates v by v' = q (0, v) q*.
- The log of a unit quaternion (cos phi, sin phi u) is (0, phi u), and the
rotation angle is 2 phi. q_exp is the inverse map.
- Angles are in radians.
"""
import math
# Below this angle on the sphere of R^4, slerp uses normalized linear
# interpolation (nlerp), which avoids the division by sin(W).
SLERP_SMALL_ANGLE = 1e-6
# ---------------------------------------------------------------- vectors
def add(a, b):
"""Return a + b."""
return tuple(x + y for x, y in zip(a, b))
def sub(a, b):
"""Return a - b."""
return tuple(x - y for x, y in zip(a, b))
def scale(a, s):
"""Return s a for a number s."""
return tuple(s * x for x in a)
def dot(a, b):
"""Return the dot product of a and b."""
return sum(x * y for x, y in zip(a, b))
def cross(a, b):
"""Return the cross product of two 3D vectors."""
return (
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
)
def cross2(a, b):
"""Return the scalar 2D cross product a_x b_y - a_y b_x."""
return a[0] * b[1] - a[1] * b[0]
def norm(a):
"""Return the Euclidean length of a."""
return math.sqrt(sum(x * x for x in a))
def normalize(a):
"""Return a / |a|. Raise ValueError for the zero vector."""
n = norm(a)
if n == 0.0:
raise ValueError("cannot normalize the zero vector")
return tuple(x / n for x in a)
def lerp(a, b, t):
"""Return (1 - t) a + t b."""
return tuple((1 - t) * x + t * y for x, y in zip(a, b))
# ---------------------------------------------------------------- matrices
def zeros(n, m=None):
"""Return the n by m zero matrix (n by n if m is None)."""
if m is None:
m = n
return [[0.0] * m for _ in range(n)]
def eye(n):
"""Return the n by n identity matrix."""
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
def mul(a, b):
"""Return the matrix product a b."""
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""Return the vector a x as a tuple."""
return tuple(sum(p * q for p, q in zip(row, x)) for row in a)
def transpose(a):
"""Return the transpose of a."""
return [list(col) for col in zip(*a)]
def _lu(a):
"""Gaussian elimination with partial pivoting on a copy of a square a.
Return (lu, perm, sign), or None if a pivot is exactly zero.
"""
n = len(a)
lu = [list(map(float, row)) for row in a]
perm = list(range(n))
sign = 1.0
for k in range(n):
p = max(range(k, n), key=lambda i: abs(lu[i][k]))
if lu[p][k] == 0.0:
return None
if p != k:
lu[k], lu[p] = lu[p], lu[k]
perm[k], perm[p] = perm[p], perm[k]
sign = -sign
piv = lu[k][k]
for i in range(k + 1, n):
f = lu[i][k] / piv
lu[i][k] = f
if f != 0.0:
rk = lu[k]
ri = lu[i]
for j in range(k + 1, n):
ri[j] -= f * rk[j]
return lu, perm, sign
def det(a):
"""Return the determinant of a square matrix."""
n = len(a)
if n == 1:
return a[0][0]
if n == 2:
return a[0][0] * a[1][1] - a[0][1] * a[1][0]
if n == 3:
return (
a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
- a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
+ a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])
)
r = _lu(a)
if r is None:
return 0.0
lu, _, sign = r
d = sign
for i in range(n):
d *= lu[i][i]
return d
def _lu_solve(lu, perm, b):
n = len(lu)
y = [float(b[perm[i]]) for i in range(n)]
for i in range(n):
s = y[i]
row = lu[i]
for j in range(i):
s -= row[j] * y[j]
y[i] = s
for i in range(n - 1, -1, -1):
s = y[i]
row = lu[i]
for j in range(i + 1, n):
s -= row[j] * y[j]
y[i] = s / row[i]
return y
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a vector (returns a list) or a matrix given as a list of rows
(returns a list of rows, one column of x per column of b).
Raise ValueError if a is singular.
"""
r = _lu(a)
if r is None:
raise ValueError("singular matrix")
lu, perm, _ = r
if len(b) > 0 and isinstance(b[0], (list, tuple)):
cols = [_lu_solve(lu, perm, col) for col in zip(*b)]
return [list(row) for row in zip(*cols)]
return _lu_solve(lu, perm, b)
def inv(a):
"""Return the inverse of a square matrix. Raise ValueError if singular."""
return solve(a, eye(len(a)))
# ---------------------------------------------------------------- polar decomposition
def rot2(theta):
"""Return the 2 by 2 rotation matrix by the angle theta."""
c, s = math.cos(theta), math.sin(theta)
return [[c, -s], [s, c]]
def _frob(a):
return math.sqrt(sum(x * x for row in a for x in row))
def _sym_eig3(s):
"""Eigenvalues and eigenvectors of a symmetric 3 by 3 matrix (cyclic Jacobi).
Return (values, vectors), where vectors[k] is the unit eigenvector of
values[k].
"""
a = [list(map(float, row)) for row in s]
v = eye(3)
for _ in range(50):
off = a[0][1] ** 2 + a[0][2] ** 2 + a[1][2] ** 2
if off <= 1e-30 * (sum(a[i][i] ** 2 for i in range(3)) + 1e-300):
break
for p, q in ((0, 1), (0, 2), (1, 2)):
if a[p][q] == 0.0:
continue
theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
sn = t * c
for k in range(3):
akp, akq = a[k][p], a[k][q]
a[k][p] = c * akp - sn * akq
a[k][q] = sn * akp + c * akq
for k in range(3):
apk, aqk = a[p][k], a[q][k]
a[p][k] = c * apk - sn * aqk
a[q][k] = sn * apk + c * aqk
for k in range(3):
vkp, vkq = v[k][p], v[k][q]
v[k][p] = c * vkp - sn * vkq
v[k][q] = sn * vkp + c * vkq
values = [a[i][i] for i in range(3)]
vectors = [tuple(v[k][i] for k in range(3)) for i in range(3)]
return values, vectors
def polar(f, tol=1e-14, max_iter=100):
"""Return (R, S) with F = R S, det R = +1 and S symmetric.
2 by 2: closed form. R = rot2(theta) with theta = atan2(f10 - f01, f00 + f11),
the rotation that maximizes trace(R^T F), and S = R^T F.
3 by 3: the Newton iteration X <- (X + X^(-T)) / 2 of Higham (1986), with
the scaling gamma = (|X^(-1)|_F / |X|_F)^(1/2) while the relative change
is above 1e-2. It stops when the relative change in the Frobenius norm is
at most tol, or after max_iter steps. The iteration gives the orthogonal
polar factor U. If det U < 0 (det F < 0), R = U (I - 2 v v^T) for the unit
eigenvector v of the smallest eigenvalue of U^T F, so that det R = +1.
If det F > 0, S is symmetric positive definite. If det F < 0, S is
symmetric with one negative eigenvalue. Raise ValueError for a singular
3 by 3 F.
"""
n = len(f)
if n == 2:
theta = math.atan2(f[1][0] - f[0][1], f[0][0] + f[1][1])
r = rot2(theta)
s = mul(transpose(r), f)
s01 = 0.5 * (s[0][1] + s[1][0])
s[0][1] = s[1][0] = s01
return r, s
if n != 3:
raise ValueError("polar supports 2 by 2 and 3 by 3 matrices")
x = [list(map(float, row)) for row in f]
change = float("inf")
for _ in range(max_iter):
xi = inv(x)
if change > 1e-2:
g = math.sqrt(_frob(xi) / _frob(x))
else:
g = 1.0
xit = transpose(xi)
y = [[0.5 * (g * x[i][j] + xit[i][j] / g) for j in range(3)] for i in range(3)]
change = _frob([[y[i][j] - x[i][j] for j in range(3)] for i in range(3)]) / _frob(y)
x = y
if change <= tol:
break
u = x
s = mul(transpose(u), f)
s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
if det(u) < 0.0:
values, vectors = _sym_eig3(s)
k = min(range(3), key=lambda i: values[i])
v = vectors[k]
h = [[(1.0 if i == j else 0.0) - 2.0 * v[i] * v[j] for j in range(3)] for i in range(3)]
u = mul(u, h)
s = mul(h, s)
s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
return u, s
# ---------------------------------------------------------------- quaternions
def q_mul(p, q):
"""Return the Hamilton product p q."""
a1, b1, c1, d1 = p
a2, b2, c2, d2 = q
return (
a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
)
def q_conj(q):
"""Return the conjugate (w, -x, -y, -z)."""
return (q[0], -q[1], -q[2], -q[3])
def q_dot(p, q):
"""Return the dot product of p and q as vectors of R^4."""
return p[0] * q[0] + p[1] * q[1] + p[2] * q[2] + p[3] * q[3]
def q_normalize(q):
"""Return q / |q|."""
n = math.sqrt(q_dot(q, q))
if n == 0.0:
raise ValueError("cannot normalize the zero quaternion")
return (q[0] / n, q[1] / n, q[2] / n, q[3] / n)
def q_from_axis_angle(axis, angle):
"""Return the unit quaternion of the rotation by angle about axis (any length)."""
u = normalize(axis)
s = math.sin(0.5 * angle)
return (math.cos(0.5 * angle), s * u[0], s * u[1], s * u[2])
def q_to_mat3(q):
"""Return the 3 by 3 rotation matrix of a unit quaternion."""
w, x, y, z = q
return [
[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
[2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
[2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
]
def q_rotate(q, v):
"""Return the vector part of q (0, v) q* for a unit quaternion q."""
r = q_mul(q_mul(q, (0.0, v[0], v[1], v[2])), q_conj(q))
return (r[1], r[2], r[3])
def q_log(q):
"""Return the log of a nonzero quaternion as a 4-tuple (ln|q|, phi u).
For a unit quaternion (cos phi, sin phi u) this is (0, phi u), with
phi = atan2(|v|, w) in [0, pi]. For a real q the vector part is zero.
"""
n = math.sqrt(q_dot(q, q))
if n == 0.0:
raise ValueError("log of the zero quaternion")
vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
lw = math.log(n)
if vn == 0.0:
return (lw, 0.0, 0.0, 0.0)
phi = math.atan2(vn, q[0])
f = phi / vn
return (lw, f * q[1], f * q[2], f * q[3])
def q_exp(q):
"""Return exp(q) = e^w (cos|v|, sin|v| v / |v|) for q = (w, v)."""
vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
ew = math.exp(q[0])
if vn == 0.0:
return (ew, 0.0, 0.0, 0.0)
f = ew * math.sin(vn) / vn
return (ew * math.cos(vn), f * q[1], f * q[2], f * q[3])
def slerp(q0, q1, t):
"""Spherical linear interpolation of unit quaternions on the short arc.
If q0 . q1 < 0, q1 is replaced by -q1 (the same rotation). The angle W
comes from atan2(|q1 - q0|, |q1 + q0|). Below SLERP_SMALL_ANGLE the
normalized linear interpolation is returned. See
robotics/rigid-body-motion/spherical-linear-interpolation.
"""
if q_dot(q0, q1) < 0.0:
q1 = (-q1[0], -q1[1], -q1[2], -q1[3])
a = math.sqrt(sum((y - x) ** 2 for x, y in zip(q0, q1)))
b = math.sqrt(sum((y + x) ** 2 for x, y in zip(q0, q1)))
w = 2.0 * math.atan2(a, b)
if w < SLERP_SMALL_ANGLE:
return q_normalize(tuple((1 - t) * x + t * y for x, y in zip(q0, q1)))
s = math.sin(w)
c0 = math.sin((1 - t) * w) / s
c1 = math.sin(t * w) / s
return tuple(c0 * x + c1 * y for x, y in zip(q0, q1))
def q_from_mat3(r):
"""Return the unit quaternion, with w >= 0, of a 3 by 3 rotation matrix.
Shepperd's method: take the largest of the trace, r00, r11 and r22, and
divide by the component that it gives. See
robotics/rigid-body-motion/shepperd-method.
"""
t = r[0][0] + r[1][1] + r[2][2]
k = max(range(4), key=lambda i: (t, r[0][0], r[1][1], r[2][2])[i])
if k == 0:
w = math.sqrt(1.0 + t) / 2.0
f = 4.0 * w
q = (w, (r[2][1] - r[1][2]) / f, (r[0][2] - r[2][0]) / f, (r[1][0] - r[0][1]) / f)
elif k == 1:
x = math.sqrt(max(0.0, 1.0 + 2.0 * r[0][0] - t)) / 2.0
f = 4.0 * x
q = ((r[2][1] - r[1][2]) / f, x, (r[1][0] + r[0][1]) / f, (r[0][2] + r[2][0]) / f)
elif k == 2:
y = math.sqrt(max(0.0, 1.0 + 2.0 * r[1][1] - t)) / 2.0
f = 4.0 * y
q = ((r[0][2] - r[2][0]) / f, (r[1][0] + r[0][1]) / f, y, (r[2][1] + r[1][2]) / f)
else:
z = math.sqrt(max(0.0, 1.0 + 2.0 * r[2][2] - t)) / 2.0
f = 4.0 * z
q = ((r[1][0] - r[0][1]) / f, (r[0][2] + r[2][0]) / f, (r[2][1] + r[1][2]) / f, z)
if q[0] < 0.0:
q = (-q[0], -q[1], -q[2], -q[3])
return q
# ---------------------------------------------------------------- transforms
def make_T(r, t):
"""Return the homogeneous (d + 1) by (d + 1) matrix [[R, t], [0, 1]] for d = len(t)."""
d = len(t)
m = [[float(r[i][j]) for j in range(d)] + [float(t[i])] for i in range(d)]
m.append([0.0] * d + [1.0])
return m
def T_mul(a, b):
"""Return the product a b of two homogeneous transforms."""
return mul(a, b)
def T_inv(m):
"""Return the inverse of an affine homogeneous transform [[A, t], [0, 1]].
The result is [[A^(-1), -A^(-1) t], [0, 1]]; A may hold a scale.
"""
d = len(m) - 1
a = [row[:d] for row in m[:d]]
t = [m[i][d] for i in range(d)]
ai = inv(a)
ti = matvec(ai, t)
return make_T(ai, tuple(-x for x in ti))
def T_apply(m, p):
"""Apply a homogeneous transform to a point p and return a tuple."""
d = len(m) - 1
return tuple(sum(m[i][j] * p[j] for j in range(d)) + m[i][d] for i in range(d))
# ---------------------------------------------------------------- derivatives
def num_grad(f, x, h=1e-6):
"""Return the gradient of a scalar f at x by central differences of step h."""
x = list(x)
g = []
for i in range(len(x)):
xi = x[i]
x[i] = xi + h
fp = f(x)
x[i] = xi - h
fm = f(x)
x[i] = xi
g.append((fp - fm) / (2.0 * h))
return g
motion_retargeting.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/motion-retargeting/. The authors are listed in prov/0KV7A9.jsonl.
"""Motion retargeting by a minimal displacement curve (after Gleicher 1998).
The character is a planar leg: a root position (rx, ry), a hip angle a1
measured from the downward direction, and a knee angle a2 relative to the
thigh, with the link lengths l1 and l2. The foot is at
root + l1 (sin a1, -cos a1) + l2 (sin(a1 + a2), -cos(a1 + a2)).
The new motion is q(t) + d(t), where q is the source motion sampled at the
frames and d is a displacement, one uniform cubic B-spline per degree of
freedom, with control points c spaced `spacing` frames apart. The method
solves
min c^T W c subject to foot(q(t_f) + d(t_f)) = p_f for every constrained frame f,
with W diagonal (one weight per degree of freedom). Each step linearizes the
constraints at the current c and takes the minimum norm solution of the
linear constraints, c = W^(-1) J^T (J W^(-1) J^T)^(-1) (J c - r), which is a
step of sequential quadratic programming with the Hessian of the objective.
"""
import math
from anim import solve
DOF = 4
def bspline(s):
"""Return the centered uniform cubic B-spline basis B(s), with support (-2, 2)."""
s = abs(s)
if s < 1.0:
return (4.0 - 6.0 * s * s + 3.0 * s ** 3) / 6.0
if s < 2.0:
return (2.0 - s) ** 3 / 6.0
return 0.0
def control_count(frames, spacing):
"""Return the number of control points per degree of freedom."""
return int(math.floor((frames - 1) / spacing)) + 4
def basis(frame, spacing, count):
"""Return [(j, B(frame / spacing - j + 1))] for the control points that are not zero."""
u = frame / spacing + 1.0
lo = max(0, int(math.floor(u)) - 1)
hi = min(count - 1, int(math.floor(u)) + 2)
return [(j, bspline(u - j)) for j in range(lo, hi + 1) if bspline(u - j) != 0.0]
def displacement(c, frame, spacing, count):
"""Return d(frame), one value per degree of freedom; c is indexed [dof * count + j]."""
b = basis(frame, spacing, count)
return [sum(w * c[k * count + j] for j, w in b) for k in range(DOF)]
def foot(q, lengths):
"""Return the foot position of the pose q = (rx, ry, a1, a2)."""
rx, ry, a1, a2 = q
l1, l2 = lengths
return (
rx + l1 * math.sin(a1) + l2 * math.sin(a1 + a2),
ry - l1 * math.cos(a1) - l2 * math.cos(a1 + a2),
)
def foot_jacobian(q, lengths):
"""Return the 2 by 4 Jacobian of the foot position in (rx, ry, a1, a2)."""
_, _, a1, a2 = q
l1, l2 = lengths
c12, s12 = math.cos(a1 + a2), math.sin(a1 + a2)
return [
[1.0, 0.0, l1 * math.cos(a1) + l2 * c12, l2 * c12],
[0.0, 1.0, l1 * math.sin(a1) + l2 * s12, l2 * s12],
]
def retarget(source, lengths, constraints, spacing=2, weights=(1.0, 1.0, 1.0, 1.0), max_iter=50, tol=1e-11):
"""Return (motion, c, iterations) for the new character.
source is a list of poses (rx, ry, a1, a2), one per frame. constraints is
a list of (frame, (px, py)): the foot of the new character must be at p
at that frame.
"""
frames = len(source)
count = control_count(frames, spacing)
size = DOF * count
winv = [1.0 / weights[k] for k in range(DOF) for _ in range(count)]
c = [0.0] * size # @line L1
for it in range(1, max_iter + 1): # @line L2
jac, res = [], []
for f, p in constraints: # @line L3
q = [a + b for a, b in zip(source[f], displacement(c, f, spacing, count))]
g = foot(q, lengths)
jq = foot_jacobian(q, lengths)
b = basis(f, spacing, count)
for row in range(2):
r = [0.0] * size
for k in range(DOF):
for j, w in b:
r[k * count + j] = jq[row][k] * w
jac.append(r)
res.append(g[row] - p[row])
m = len(res)
jc = [sum(x * y for x, y in zip(r, c)) for r in jac]
rhs = [a - b for a, b in zip(jc, res)] # @line L4
gram = [[sum(jac[a][i] * winv[i] * jac[b][i] for i in range(size)) for b in range(m)] for a in range(m)]
mu = solve(gram, rhs) # @line L5
new = [winv[i] * sum(jac[a][i] * mu[a] for a in range(m)) for i in range(size)] # @line L6
change = max(abs(x - y) for x, y in zip(new, c))
c = new
if change <= tol * (1.0 + max(abs(v) for v in c)) and max(abs(v) for v in res) <= 1e-9: # @line L7
break
motion = []
for f in range(frames): # @line L8
motion.append(tuple(a + b for a, b in zip(source[f], displacement(c, f, spacing, count))))
return motion, c, it
test_motion_retargeting.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/motion-retargeting/. The authors are listed in prov/0KV7A9.jsonl.
"""Tests of motion retargeting with a minimal B-spline displacement.
The foot constraints of the new character hold. The same character needs no
displacement. The solution meets the first order optimality condition (W c
in the row space of the constraint Jacobian), and feasible neighbors have a
larger objective. Frames far from all constraints do not change. The check
value of the page, one constraint on a straight leg, holds.
"""
import math
import random
import anim
from motion_retargeting import basis, control_count, displacement, foot, foot_jacobian, retarget
FRAMES = 24
SRC_LEN = (1.0, 1.0)
NEW_LEN = (0.8, 0.9)
PLANT = (0.6, 0.0)
CONS = [(f, PLANT) for f in range(6, 16)]
def source():
out = []
for f in range(FRAMES):
a1 = 0.5 * math.sin(2 * math.pi * f / FRAMES)
a2 = 0.3 + 0.3 * math.cos(2 * math.pi * f / FRAMES)
if 6 <= f <= 15:
p = PLANT
elif f < 6:
p = (0.6 - 0.1 * (6 - f), 0.05 * (6 - f))
else:
p = (0.6 + 0.1 * (f - 15), 0.05 * (f - 15))
o = foot((0.0, 0.0, a1, a2), SRC_LEN)
out.append((p[0] - o[0], p[1] - o[1], a1, a2))
return out
def jac_and_res(src, c, lengths, cons, spacing):
count = control_count(len(src), spacing)
jac, res = [], []
for f, p in cons:
q = [a + b for a, b in zip(src[f], displacement(c, f, spacing, count))]
g = foot(q, lengths)
jq = foot_jacobian(q, lengths)
for row in range(2):
r = [0.0] * len(c)
for k in range(4):
for j, w in basis(f, spacing, count):
r[k * count + j] = jq[row][k] * w
jac.append(r)
res.append(g[row] - p[row])
return jac, res
def test_source_plants_the_foot():
src = source()
for f, p in CONS:
assert max(abs(a - b) for a, b in zip(foot(src[f], SRC_LEN), p)) < 1e-12
def test_constraints_hold_for_the_new_character():
src = source()
motion, _, it = retarget(src, NEW_LEN, CONS)
assert it < 50
for f, p in CONS:
assert max(abs(a - b) for a, b in zip(foot(motion[f], NEW_LEN), p)) < 1e-9
# The source does not meet them: the leg is shorter.
assert max(abs(foot(src[f], NEW_LEN)[1]) for f, _ in CONS) > 0.1
def test_same_character_needs_no_displacement():
src = source()
motion, c, _ = retarget(src, SRC_LEN, CONS)
assert max(abs(v) for v in c) < 1e-12
assert all(abs(a - b) < 1e-12 for p, q in zip(motion, src) for a, b in zip(p, q))
def test_first_order_optimality():
src = source()
_, c, _ = retarget(src, NEW_LEN, CONS)
jac, _ = jac_and_res(src, c, NEW_LEN, CONS, 2)
m = len(jac)
gram = [[sum(x * y for x, y in zip(jac[a], jac[b])) for b in range(m)] for a in range(m)]
mu = anim.solve(gram, [sum(x * y for x, y in zip(r, c)) for r in jac])
proj = [ci - sum(jac[a][i] * mu[a] for a in range(m)) for i, ci in enumerate(c)]
assert max(abs(v) for v in proj) < 1e-8
def test_feasible_neighbors_are_not_better():
src = source()
_, c, _ = retarget(src, NEW_LEN, CONS)
best = sum(v * v for v in c)
rng = random.Random(5)
for _ in range(10):
x = [v + rng.gauss(0, 0.01) for v in c]
for _ in range(30):
jac, res = jac_and_res(src, x, NEW_LEN, CONS, 2)
m = len(jac)
gram = [[sum(p * q for p, q in zip(jac[a], jac[b])) for b in range(m)] for a in range(m)]
mu = anim.solve(gram, res)
x = [xi - sum(jac[a][i] * mu[a] for a in range(m)) for i, xi in enumerate(x)]
_, res = jac_and_res(src, x, NEW_LEN, CONS, 2)
assert max(abs(v) for v in res) < 1e-9
assert sum(v * v for v in x) >= best - 1e-12
def test_far_frames_do_not_change():
src = source()
motion, _, _ = retarget(src, NEW_LEN, CONS)
for f in (0, 22, 23):
assert motion[f] == tuple(src[f])
assert any(abs(a - b) > 1e-3 for a, b in zip(motion[3], src[3]))
def test_check_value_one_constraint_on_a_straight_leg():
src = [(0.0, 2.0, 0.0, 0.0)] * 17
cons = [(8, (0.0, 0.0))]
big = 1e12
motion, c, _ = retarget(src, (0.9, 0.9), cons, spacing=2, weights=(1.0, 1.0, big, big))
count = control_count(17, 2)
cy = c[count : 2 * count]
j = 8 // 2 + 1
for jj, want in ((j - 1, -0.2 / 3), (j, -0.8 / 3), (j + 1, -0.2 / 3)):
assert abs(cy[jj] - want) < 1e-9
assert all(abs(v) < 1e-9 for i, v in enumerate(cy) if abs(i - j) > 1)
for f, want in ((8, -0.2), (10, -0.2 * 8 / 18), (12, -0.2 / 18), (14, 0.0)):
assert abs((motion[f][1] - 2.0) - want) < 1e-9
assert abs((motion[16 - f][1] - 2.0) - want) < 1e-9
History
Before Gleicher's paper, motions were adapted to new characters by hand, or by per frame inverse kinematics. Witkin and Kass (1988) had introduced spacetime constraints, optimization over a whole motion under constraints, with dynamics. Gleicher (1998) used the same frame without the dynamics, wrote the change as a displacement of B-splines that is as small as possible, and solved for the whole motion at once. Later systems added faster solvers and per frame methods with filtering, and the problem remains a standard step in pipelines that use motion capture.
References
- Michael Gleicher, Retargetting motion to new characters, SIGGRAPH 98, 33-42, the formulation of retargeting as a spacetime problem over the whole motion, with the change written as a displacement curve of B-splines, kinematic constraints of the new character and an objective that keeps the displacement small (general locator)
- Andrew Witkin and Michael Kass, Spacetime constraints, SIGGRAPH 88, Computer Graphics 22(4), 159-168, the spacetime frame of an optimization over the whole trajectory under constraints (general locator)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 0KV7A9 Edit this page History Report an error Markdown