Algorithm Search⌘K

Algorithmadvanced

Footskate cleanup

Also called foot sliding removal.

Remove the sliding of planted feet in edited motion by moving the root, changing the leg joint angles with analytic inverse kinematics, and stretching the legs a little if needed.

Time
O(f^2) cleanupO(f) cleanup_with_sweep
Space
O(f) extra
Where
f = the number of frames
Properties
deterministicexactofflineiterative
Origin
Lucas Kovar, John Schreiner, Michael Gleicher, 2002

Footskate cleanup removes the small sliding of feet that should stand still. Blends, transitions, retargeting and filters all change the joint angles a little, and a small change at the hip or knee moves the foot on the floor; this is footskate. The method takes the motion and a list of footplants, the frames at which each foot should be planted. For each plant it chooses one target place for the foot; on each planted frame it moves the root as little as needed so that the targets are in reach, solves each planted leg with two-bone inverse kinematics, and lets the bones stretch a little if a leg must be nearly straight. Near the start and the end of each plant the changes blend smoothly to zero, so that the motion has no jump. Kovar, Schreiner and Gleicher (2002) presented the method; the code here is a planar version with its own choices, listed below.

In plain words

A captured walk is changed, and now the feet slide a bit on the floor while they should stand still. You mark the moments when each foot should be on the ground. For each such moment, you pick one spot on the floor where that foot must stay. Then, on each of those frames, you bend the hip and the knee so that the foot reaches its spot. If the spot is a bit too far, you move the hips a little toward it, and as a last step you let the leg get a bit longer. Just before and after the foot is down, you fade the changes in and out, so nobody sees a jump.

The problem

The input is a motion of ff frames, a list of footplants (for each leg, runs of frames during which the foot must not move), the bone lengths l1l_1 (thigh) and l2l_2 (shin), an allowed stretch ϵ≥0\epsilon \ge 0 and a blend length bb. In the planar code, a frame is the root (hip) position hh and, for each leg, the thigh angle φ\varphi and the knee angle κ\kappa, with the ankle at h+l1e(φ)+l2e(φ+κ)h + l_1 e(\varphi) + l_2 e(\varphi + \kappa) for e(φ)=(sin⁡φ,−cos⁡φ)e(\varphi) = (\sin\varphi, -\cos\varphi).

The output is a motion in which:

  • every planted ankle is at one fixed place for the whole plant;
  • each bone length changes by a factor in [1,1+ϵ][1, 1 + \epsilon];
  • a motion that has no footskate is not changed;
  • frames far from every plant are not changed, and the change fades in and out smoothly.

Finding the footplants is a separate step, and here they are an input. They can be marked by hand or found by a test on the height and speed of the foot.

The algorithm

  1. FOOTSKATE-CLEANUP(frames, plants, l₁, l₂, ε, b)
  2. for each plant of a leg
  3. 1c ← the mean ankle position over the plant ▷ the target, a choice of the code
  4. for each frame i with at least one planted leg
  5. 2ĥ ← the point nearest to the root h inside every disk of radius (1 + ε)(l₁ + l₂) around a target
  6. for each planted leg with target c
  7. 3s ← max(1, |ĥ - c| / (l₁ + l₂)) ▷ the stretch, at most 1 + ε
  8. 4(φ, κ) ← two-bone IK from ĥ to c with the bones s l₁ and s l₂, knee on the side of the input
  9. for each frame j
  10. 5w ← 1 - u²(3 - 2u) with u = δ / (b + 1), δ the distance to the nearest planted frame i
  11. 6root, angles and bone lengths of j ← input + w · (the change at frame i)
  12. return the new frames

Line L2 is a projection onto the intersection of one or two disks. If the root is already in reach of every target, it does not move. Otherwise the code compares the projection onto each disk and the intersection points of the two circles, and keeps the nearest point that is inside both disks.

Line L4 is the planar law of cosines solution: the angle at the hip between the thigh and the line to the target, and the inner angle at the knee. Of the two mirror solutions it takes the one with the knee on the same side as in the input, so a knee never flips. For a straight leg the code returns the straight pose directly, because the arc cosine near −1-1 loses precision.

Choices of the code. The paper changes the root position and the joint orientations, uses analytic inverse kinematics, allows a small change of bone length when the leg is nearly straight, and blends the changes off when a constraint starts or ends. The following details are the choices of this code, not taken from the paper: the mean ankle as the target, the root moved by the smallest distance, the same stretch factor for both bones of a leg, and the smoothstep weight of line L5.

Example

The test builds a planar walk of 60 frames with the thigh l1=0.45l_1 = 0.45 and the shin l2=0.50l_2 = 0.50. The root moves forward at 0.04 per frame at a height of about 0.85, and each foot is planted for 18 frames in each step of 30 frames, the right foot 15 frames after the left. During a plant the ankle slides by 0.003 per frame plus a small noise, about 0.053 over the plant; the leg angles come from inverse kinematics on these sliding ankles.

The walk has three full plants: the left foot on frames 0 to 17 and 30 to 47, and the right foot on frames 15 to 32. With ϵ=0.05\epsilon = 0.05, b=4b = 4 and the noise seed 3, the planted ankle moves by at most 4⋅10−164 \cdot 10^{-16} in each plant after cleanup. The root does not move and the bones do not stretch, because the hip is always in reach of the targets.

In a second walk at the height 0.94 with a larger slide (0.006 per frame) and the speed 0.05, the targets are farther away, and both bones of a leg stretch by up to 1.94 percent on some frames, inside the allowed 5 percent.

Correctness

The proof file works under two assumptions: (A1) on every planted frame the disks of radius (1+ϵ)(l1+l2)(1 + \epsilon)(l_1 + l_2) around the planted targets meet, else the code raises an error; (A2) the new root is not too close to a target, so the target is not inside the inner limit s∣l1−l2∣s |l_1 - l_2| of the leg. Under them it shows:

  • Line L2 returns the nearest point of the disk intersection, so the root moves as little as possible.
  • The stretch factor of line L3 is in [1,1+ϵ][1, 1 + \epsilon], and the stretched leg reaches the target.
  • The angles of line L4 put the ankle exactly on the target, so every planted ankle stays still during its plant (Theorem 1).
  • Every bone length changes by a factor in [1,1+ϵ][1, 1 + \epsilon], the same for the thigh and the shin of a leg (Theorem 2).
  • A motion whose planted ankles already stand still and are in reach, with bent knees, is returned unchanged (Theorem 3).
  • A frame farther than bb from every planted frame is unchanged, and the weight goes from 1 to 0 with zero slope at both ends (Theorem 4).

That the result looks right is a visual heuristic. The change of the root and the knees can be seen as a small dip or bounce, the stretch is a cheat on the skeleton, and the blend length bb and the stretch limit ϵ\epsilon are tuning.

Proof: Footskate cleanup keeps every planted ankle on its target, changes the bones by at most the allowed factor, and leaves clean motion alonefull

We use the notation of the page. The arithmetic is exact. The character is planar, with the hip (root) hh, a thigh of length l1>0l_1 > 0 and a shin of length l2>0l_2 > 0 in each leg, and ϵ≥0\epsilon \ge 0. The direction e(φ)=(sin⁡φ,−cos⁡φ)e(\varphi) = (\sin\varphi, -\cos\varphi) points down for φ=0\varphi = 0, and the ankle of a leg with thigh angle φ\varphi and knee angle κ\kappa is h+l1e(φ)+l2e(φ+κ)h + l_1 e(\varphi) + l_2 e(\varphi + \kappa). A plant of a leg is a run of frames; its target cc is the mean of the ankle positions of the input over the run (line L1). On a frame with planted legs, ρ=(1+ϵ)(l1+l2)\rho = (1 + \epsilon)(l_1 + l_2) is the longest allowed leg.

We assume that on every planted frame:

  • (A1) the disks of radius ρ\rho around the targets of the planted legs meet (else the code raises an error);
  • (A2) the new hip is not too close to a target: ∣h^−c∣≥s ∣l1−l2∣|\hat h - c| \ge s\,|l_1 - l_2| for the stretch factor ss of line L3.

The root

Lemma 1. For one or two closed disks with a common point and a point hh, line L2 returns the point h^\hat h of the intersection KK nearest to hh.

Proof. KK is convex, closed and not empty, so it has a unique nearest point h^\hat h. If h∈Kh \in K, h^=h\hat h = h, and the code returns hh. Otherwise h^\hat h is on the boundary of KK. If h^\hat h is strictly inside one disk D2D_2, then near h^\hat h the set KK equals the other disk D1D_1, so h^\hat h is a local minimum of the distance to hh over D1D_1; a local minimum of a convex function on a convex set is global, so h^\hat h is the projection of hh onto D1D_1. If h^\hat h is on both circles, it is one of the at most two intersection points of the circles. The code lists the projections onto each disk and the intersection points of the circles, keeps those inside KK, and returns the nearest to hh; the list contains h^\hat h and only points of KK. □\square

So the root moves as little as possible, and not at all when every planted target is already in reach of the longest allowed leg.

The legs

Lemma 2. On a planted frame, for each planted leg with target cc and d=∣h^−c∣d = |\hat h - c|, the factor s=max⁡(1,d/(l1+l2))s = \max(1, d/(l_1 + l_2)) of line L3 satisfies 1≤s≤1+ϵ1 \le s \le 1 + \epsilon and d≤s(l1+l2)d \le s (l_1 + l_2).

Proof. d≤ρd \le \rho by Lemma 1, so d/(l1+l2)≤1+ϵd/(l_1 + l_2) \le 1 + \epsilon. If d≤l1+l2d \le l_1 + l_2, s=1s = 1 and d≤l1+l2d \le l_1 + l_2; otherwise s(l1+l2)=ds (l_1 + l_2) = d. □\square

Lemma 3. Let a=sl1a = s l_1, b′=sl2b' = s l_2 and ∣a−b′∣≤d≤a+b′|a - b'| \le d \le a + b' with d>0d > 0. Let ψ\psi be the angle with e(ψ)=(c−h^)/de(\psi) = (c - \hat h)/d, let α∈[0,π]\alpha \in [0, \pi] and β∈[0,π]\beta \in [0, \pi] be the angles of the triangle with sides aa, b′b', dd at the hip and at the knee (law of cosines), and let σ=±1\sigma = \pm 1. Then the leg with φ=ψ−σα\varphi = \psi - \sigma\alpha and κ=σ(π−β)\kappa = \sigma(\pi - \beta) puts the ankle at cc, and σκ≥0\sigma\kappa \ge 0.

Proof. The knee is k=h^+a e(ψ−σα)k = \hat h + a\, e(\psi - \sigma\alpha), at the angle α\alpha from the line to the target, on the side that σ\sigma selects. In the triangle h^,k,c\hat h, k, c the inner angle at kk is β\beta, so the direction from kk to cc is the direction of the thigh turned by the outer angle π−β\pi - \beta, toward the line h^c\hat h c, which is the turn by σ(π−β)\sigma(\pi - \beta). The side ∣k−c∣|k - c| of this triangle is b′b' by the law of cosines, so k+b′ e(φ+κ)=ck + b'\, e(\varphi + \kappa) = c. σκ=π−β≥0\sigma\kappa = \pi - \beta \ge 0. □\square

Theorem 1. On every frame of every plant, the ankle of the planted leg after cleanup is exactly its target cc. So the planted foot does not move during the plant.

Proof. By Lemma 2 and A2, s∣l1−l2∣≤d≤s(l1+l2)s|l_1 - l_2| \le d \le s(l_1 + l_2), so the target is reachable by a leg with the bones sl1s l_1 and sl2s l_2. Line L4 computes the angles of Lemma 3, so the ankle is at cc. The frame keeps these angles and lengths, because the blend weight is 1 on planted frames. ■\blacksquare

Theorem 2. On every frame, each bone length is (1+w(s−1))(1 + w(s - 1)) times its original length for some w∈[0,1]w \in [0, 1] and some s∈[1,1+ϵ]s \in [1, 1 + \epsilon], so it changes by a factor in [1,1+ϵ][1, 1 + \epsilon], and the thigh and the shin of a leg change by the same factor.

Proof. On planted frames w=1w = 1 and ss is the factor of Lemma 2. On other frames the code takes ss from the nearest planted frame and ww from the blend weight in [0,1][0, 1]. ■\blacksquare

Clean motion and far frames

Theorem 3. Suppose that in the input every planted ankle is constant over its plant, is at most l1+l2l_1 + l_2 from the hip, and its knee is not straight. Then the output equals the input.

Proof. Each target cc equals the constant ankle position, so every target is within ρ\rho of the hip, and Lemma 1 returns h^=h\hat h = h. Then d≤l1+l2d \le l_1 + l_2 and s=1s = 1. For a reachable target with a bent knee there are exactly two planar solutions, one for each side of the knee, and line L4 takes the side of the input knee, so it returns the input angles. All offsets and angle changes are zero, so every blended frame is also unchanged. ■\blacksquare

Theorem 4. A frame whose distance to every planted frame is more than bb is unchanged.

Proof. Line L5 gives the weight 1−u2(3−2u)1 - u^2(3 - 2u) with u=δ/(b+1)u = \delta/(b + 1) for a distance δ\delta, and 0 for δ≥b+1\delta \ge b + 1. A frame farther than bb from every planted frame has δ≥b+1\delta \ge b + 1 for the nearest one, so its root offset and its leg changes are multiplied by 0 at lines L5 and L6. ■\blacksquare

The weight is 1 at δ=0\delta = 0, decreases, and has zero slope at both ends, so the change fades in and out without a jump of the root or the joint angles.

In floating point

The straight leg is the hard case: at d=l1+l2d = l_1 + l_2 the knee angle is an arc cosine near −1-1, where a rounding error of uu in the cosine gives an angle error near 2u\sqrt{2u}. The code returns the straight leg directly when d≥(l1+l2)(1−10−12)d \ge (l_1 + l_2)(1 - 10^{-12}), so the test can check Theorem 1 within 10−910^{-9} on frames that need the full stretch.

Complexity

Lines L1 to L4 cost O(1)O(1) per planted frame and leg, plus O(f)O(f) in total for the means of line L1. The code finds the nearest planted frame for each frame by a scan over all planted frames, which costs O(f2)O(f^2) in the worst case. Two sweeps over the frames, one forward and one backward, give the nearest planted frame for every frame in O(f)O(f), so the whole method can run in O(f)O(f) time. The extra space is O(f)O(f) for the changes. In 3D with a full skeleton, each frame also needs a forward kinematics pass over the joints, which is linear in the number of joints.

Properties

  • Exact on plants. The planted feet are on their targets, up to rounding.
  • Minimal root move. The root moves only if a target is out of reach, and then as little as possible.
  • Bounded stretch. No bone changes by more than the factor 1+ϵ1 + \epsilon.
  • Local. Only planted frames and frames within bb of them change.
  • Offline. The targets need the whole plant, so the method runs on a finished clip.

Variants and improvements

  • Toe and heel. Plant the heel and the toe in turn with separate constraints, so the foot can roll.
  • Ground height. Use the floor height under the target for uneven ground.
  • Online cleanup. Games run a simpler version every frame: when a foot is planted, keep its last place and solve the leg with two-bone inverse kinematics, with no look ahead.
  • Retargeting. Motion retargeting to a skeleton with other bone lengths always needs a cleanup of this kind; spacetime methods solve the whole motion at once with the contacts as constraints.
  • Automatic plants. Detect plants from the foot height and speed, or by a classifier trained on marked data.

When to use it

Use footskate cleanup after every edit that changes the joint angles of a captured motion with contacts: blends, motion graph transitions, motion warping, filtering and retargeting. It is fast and changes only what it must. It does not fix contacts that the edit removed, and it does not keep the balance of the character; for a body that must stay balanced, use a physics based method.

Pitfalls

  • Wrong plants. A plant marked too long holds a foot that should lift, and the leg stretches or the root drops.
  • Root steps. Moving the root only on planted frames can make the root move unevenly; blend the root change over a few frames, and keep bb large enough.
  • Knee flips. The inverse kinematics has two solutions. Without the side test of line L4, a knee can bend backward for one frame.
  • Straight legs. Near full extension the knee angle is badly conditioned, and small target changes give large knee changes; the stretch limit helps.
  • Feet too far apart. If two planted feet are farther apart than two stretched legs, no root position works, and the code raises an error.

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.

footskate_cleanup.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/footskate-cleanup/. The authors are listed in prov/QJ3V2G.jsonl.
"""Footskate cleanup in the spirit of Kovar, Schreiner and Gleicher (2002).

The character lives in the sagittal plane (x forward, y up). A frame holds
the root (hip) position and, for each leg, the world angle of the thigh
(measured from straight down, counterclockwise) and the relative knee
angle. The thigh has length l1 and the shin length l2; the ankle is

    ankle = root + l1 e(phi) + l2 e(phi + knee),  e(a) = (sin a, -cos a).

The input also lists the plant intervals of each leg: runs of frames in
which the foot must stay still. The cleanup:
  1. picks one target ankle position per plant (here the mean of the
     ankle positions over the plant);
  2. moves the root as little as possible so that every planted target is
     within the longest allowed leg, (1 + eps)(l1 + l2);
  3. solves each planted leg in closed form (two-bone IK, knee on the side
     of the original knee), and stretches both bones by the same factor,
     at most 1 + eps, when the target is beyond l1 + l2;
  4. blends the root offset and the leg changes off over b frames before
     and after each plant with a smooth weight, so the motion stays
     continuous.
"""

import math


def e(a):
    return (math.sin(a), -math.cos(a))


def leg_points(root, phi, knee, l1, l2):
    k = (root[0] + l1 * math.sin(phi), root[1] - l1 * math.cos(phi))
    a = (k[0] + l2 * math.sin(phi + knee), k[1] - l2 * math.cos(phi + knee))
    return k, a


def two_bone(root, target, l1, l2, bend_sign):
    """Planar two-bone IK: thigh angle and knee angle so that the ankle is
    at target. bend_sign = -1 bends the knee backward (knee < 0)."""
    dx, dy = target[0] - root[0], target[1] - root[1]
    d = math.hypot(dx, dy)
    # world angle of the line root -> target, measured from straight down
    base = math.atan2(dx, -dy)
    if d >= (l1 + l2) * (1.0 - 1e-12):
        # straight leg; acos near -1 would lose half the digits
        return base, 0.0
    d = max(d, abs(l1 - l2) + 1e-12)
    c =(l1 * l1 + l2 * l2 - d * d) / (2 * l1 * l2)
    inner = math.acos(max(-1.0, min(1.0, c)))
    knee = bend_sign * (math.pi - inner)
    ca = (l1 * l1 + d * d - l2 * l2) / (2 * l1 * d)
    alpha = math.acos(max(-1.0, min(1.0, ca)))
    phi = base - bend_sign * alpha
    return phi, knee


def project_root(h, disks):
    """The point nearest to h inside every disk (center, radius), for one
    or two disks. Return None if the disks do not meet."""
    def inside(p, tol=1e-12):
        return all(math.dist(p, c) <= r + tol for c, r in disks)

    if inside(h):
        return h
    cands = []
    for c, r in disks:
        d = math.dist(h, c)
        p = (c[0] + (h[0] - c[0]) * r / d, c[1] + (h[1] - c[1]) * r / d)
        if inside(p):
            cands.append(p)
    if len(disks) == 2:
        (c1, r1), (c2, r2) = disks
        d = math.dist(c1, c2)
        if 0 < d <= r1 + r2 and d >= abs(r1 - r2):
            a = (r1 * r1 - r2 * r2 + d * d) / (2 * d)
            hh = math.sqrt(max(0.0, r1 * r1 - a * a))
            mx = c1[0] + a * (c2[0] - c1[0]) / d
            my = c1[1] + a * (c2[1] - c1[1]) / d
            for s in (1, -1):
                cands.append((mx + s * hh * (c2[1] - c1[1]) / d, my - s * hh * (c2[0] - c1[0]) / d))
    cands = [p for p in cands if inside(p, 1e-9)]
    if not cands:
        return None
    return min(cands, key=lambda p: math.dist(p, h))


def smooth_weight(delta, b):
    """1 at delta = 0, 0 for delta >= b + 1, smooth in between."""
    if delta >= b + 1:
        return 0.0
    s = delta / (b + 1.0)
    return 1.0 - s * s * (3.0 - 2.0 * s)


def cleanup(frames, plants, l1, l2, eps=0.05, b=4):
    """frames: list of dicts {"root": (x, y), "L": (phi, knee), "R": (phi, knee)}.
    plants: dict leg -> list of (start, end), inclusive.
    Return (new frames, targets) where each new frame also has the bone
    lengths per leg in "len_L" and "len_R"."""
    f = len(frames)
    legs = ("L", "R")
    targets = {leg: [] for leg in legs}
    planted = [dict() for _ in range(f)]
    for leg in legs:
        for s, t in plants.get(leg, []):
            pts = [leg_points(frames[i]["root"], *frames[i][leg], l1, l2)[1] for i in range(s, t + 1)]
            c = (sum(p[0] for p in pts) / len(pts), sum(p[1] for p in pts) / len(pts))  # @line L1
            targets[leg].append(((s, t), c))
            for i in range(s, t + 1):
                planted[i][leg] = c
    reach = (1.0 + eps) * (l1 + l2)
    # solve the constrained frames
    root_off = [None] * f
    leg_new = [dict() for _ in range(f)]
    for i in range(f):
        if not planted[i]:
            continue
        h = frames[i]["root"]
        hn = project_root(h, [(c, reach) for c in planted[i].values()])  # @line L2
        if hn is None:
            raise ValueError("the planted feet are too far apart at frame %d" % i)
        root_off[i] = (hn[0] - h[0], hn[1] - h[1])
        for leg, c in planted[i].items():
            d = math.dist(hn, c)
            s = max(1.0, d / (l1 + l2))  # @line L3
            phi0, knee0 = frames[i][leg]
            sign = -1.0 if knee0 <= 0 else 1.0
            phi, knee = two_bone(hn, c, s * l1, s * l2, sign)  # @line L4
            leg_new[i][leg] = (phi - phi0, knee - knee0, s)
    # blend the changes off around the constraints
    const = [i for i in range(f) if planted[i]]
    out = []
    for i in range(f):
        fr = frames[i]
        if root_off[i] is not None:
            off = root_off[i]
        else:
            off = (0.0, 0.0)
            if const:
                j = min(const, key=lambda c: (abs(c - i), c))
                w = smooth_weight(abs(j - i), b)  # @line L5
                off = (w * root_off[j][0], w * root_off[j][1])
        new = {"root": (fr["root"][0] + off[0], fr["root"][1] + off[1])}
        for leg in legs:
            phi, knee = fr[leg]
            if leg in leg_new[i]:
                dphi, dknee, s = leg_new[i][leg]
                w = 1.0
            else:
                js = [j for j in const if leg in leg_new[j]]
                if js:
                    j = min(js, key=lambda c: (abs(c - i), c))
                    dphi, dknee, s = leg_new[j][leg]
                    w = smooth_weight(abs(j - i), b)
                else:
                    dphi = dknee = 0.0
                    s, w = 1.0, 0.0
            new[leg] = (phi + w * dphi, knee + w * dknee)  # @line L6
            new["len_" + leg] = ((1 + w * (s - 1)) * l1, (1 + w * (s - 1)) * l2)
        out.append(new)
    return out, targets


def ankle(frame, leg, l1=None, l2=None):
    a, b = frame.get("len_" + leg, (l1, l2))
    return leg_points(frame["root"], *frame[leg], a, b)[1]
test_footskate_cleanup.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/footskate-cleanup/. The authors are listed in prov/QJ3V2G.jsonl.
"""Tests of footskate cleanup.

A planar walk is made in code: the ankles follow planned paths, with a
slow slide (the footskate) during each plant, and the leg angles come from
two-bone IK. After cleanup each planted ankle stays on its target, no bone
grows by more than eps, a clean walk is not changed, frames far from every
plant are not changed, and the root projection matches a grid search.
"""

import math
import random

import footskate_cleanup as fc

L1, L2 = 0.45, 0.50


def walk(frames=60, slide=0.003, height=0.85, v=0.04, rng=None):
    """Plants: left on [30k, 30k + 17], right shifted by 15 frames."""
    plants = {"L": [], "R": []}
    paths = {"L": [None] * frames, "R": [None] * frames}
    for leg, shift in (("L", 0), ("R", 15)):
        starts = list(range(shift - 30, frames, 30))
        for s in starts:
            t = s + 17
            mid = v * (s + 8.5)
            if 0 <= s and t < frames:
                plants[leg].append((s, t))
            for i in range(max(s, 0), min(t, frames - 1) + 1):
                noise = rng.uniform(-0.002, 0.002) if rng else 0.0
                paths[leg][i] = (mid + slide * (i - s - 8.5) + noise, 0.08)
            # swing to the next plant
            nmid = v * (s + 30 + 8.5)
            for i in range(t + 1, min(s + 30, frames)):
                if i < 0:
                    continue
                u = (i - t) / 13.0
                x = (mid + slide * 8.5) * (1 - u) + (nmid - slide * 8.5) * u
                paths[leg][i] = (x, 0.08 + 0.1 * math.sin(math.pi * u))
    out = []
    for i in range(frames):
        root = (v * i, height + 0.01 * math.cos(2 * math.pi * i / 15.0))
        fr = {"root": root}
        for leg in ("L", "R"):
            fr[leg] = fc.two_bone(root, paths[leg][i], L1, L2, -1.0)
        out.append(fr)
    return out, plants


def test_two_bone_reaches_target():
    rng = random.Random(1)
    for _ in range(500):
        root = (rng.uniform(-1, 1), rng.uniform(-1, 1))
        d = rng.uniform(0.06, L1 + L2)
        a = rng.uniform(-math.pi, math.pi)
        target = (root[0] + d * math.cos(a), root[1] + d * math.sin(a))
        for sign in (-1.0, 1.0):
            phi, knee = fc.two_bone(root, target, L1, L2, sign)
            p = fc.leg_points(root, phi, knee, L1, L2)[1]
            assert math.dist(p, target) < 1e-9
            assert knee * sign >= -1e-12


def test_planted_ankles_stay_on_target():
    rng = random.Random(2)
    frames, plants = walk(rng=rng)
    before = max(math.dist(fc.ankle(frames[s], leg, L1, L2), fc.ankle(frames[t], leg, L1, L2))
                 for leg in plants for s, t in plants[leg])
    out, targets = fc.cleanup(frames, plants, L1, L2, eps=0.05, b=4)
    assert before > 0.04  # the input slides
    for leg in targets:
        for (s, t), c in targets[leg]:
            for i in range(s, t + 1):
                assert math.dist(fc.ankle(out[i], leg), c) < 1e-9


def test_bone_change_is_bounded():
    rng = random.Random(3)
    frames, plants = walk(rng=rng, height=0.94, slide=0.006, v=0.05)
    eps = 0.05
    out, targets = fc.cleanup(frames, plants, L1, L2, eps=eps, b=4)
    stretched = 0
    for fr in out:
        for leg in ("L", "R"):
            a, b = fr["len_" + leg]
            assert 1.0 - 1e-12 <= a / L1 <= 1.0 + eps + 1e-12
            assert abs(a / L1 - b / L2) < 1e-12
            stretched += a > L1 * (1 + 1e-9)
    assert stretched > 0  # this input needs some stretch or root motion
    for leg in targets:
        for (s, t), c in targets[leg]:
            for i in range(s, t + 1):
                assert math.dist(fc.ankle(out[i], leg), c) < 1e-9


def test_clean_walk_is_unchanged():
    frames, plants = walk(slide=0.0)
    out, _ = fc.cleanup(frames, plants, L1, L2)
    for a, b in zip(frames, out):
        assert math.dist(a["root"], b["root"]) < 1e-12
        for leg in ("L", "R"):
            assert abs(a[leg][0] - b[leg][0]) < 1e-9 and abs(a[leg][1] - b[leg][1]) < 1e-9


def test_far_frames_unchanged_and_blend_is_smooth():
    frames, _ = walk(frames=60, slide=0.004)
    plants = {"L": [(25, 34)], "R": []}
    b = 4
    out, _ = fc.cleanup(frames, plants, L1, L2, b=b)
    for i in list(range(0, 25 - b - 1)) + list(range(34 + b + 2, 60)):
        assert out[i] == {**frames[i], "len_L": (L1, L2), "len_R": (L1, L2)}
    assert fc.smooth_weight(0, b) == 1.0 and fc.smooth_weight(b + 1, b) == 0.0
    ws = [fc.smooth_weight(k, b) for k in range(b + 2)]
    assert all(x > y for x, y in zip(ws, ws[1:]))


def grid_nearest(h, disks, step=0.002, box=2.0):
    best = None
    n = int(2 * box / step)
    for a in range(n + 1):
        x = h[0] - box + a * step
        for c in range(n + 1):
            y = h[1] - box + c * step
            if all(math.dist((x, y), q) <= r for q, r in disks):
                d = math.dist((x, y), h)
                if best is None or d < best:
                    best = d
    return best


def test_root_projection_matches_grid_search():
    rng = random.Random(4)
    for _ in range(6):
        c1 = (rng.uniform(-0.5, 0.5), rng.uniform(-0.2, 0.2))
        c2 = (c1[0] + rng.uniform(0.4, 1.6), c1[1] + rng.uniform(-0.3, 0.3))
        r = 0.95
        h = (rng.uniform(-0.5, 1.5), rng.uniform(0.2, 1.2))
        disks = [(c1, r), (c2, r)]
        p = fc.project_root(h, disks)
        g = grid_nearest(h, disks, step=0.01, box=1.5)
        if g is None:
            assert p is None or math.dist(c1, c2) > 2 * r - 0.03
            continue
        assert p is not None
        assert all(math.dist(p, c) <= r + 1e-9 for c, _ in disks)
        assert math.dist(p, h) <= g + 1e-9
        assert math.dist(p, h) >= g - 0.015
    assert fc.project_root((0.0, 0.0), [((-1.0, 0.0), 0.4), ((1.0, 0.0), 0.4)]) is None

History

Lucas Kovar, John Schreiner and Michael Gleicher presented footskate cleanup at the ACM SIGGRAPH/Eurographics Symposium on Computer Animation in 2002, the same year as their motion graphs, whose transitions make the problem common. Earlier editing methods kept contacts with general constraint solvers, such as per frame inverse kinematics or spacetime optimization; the new step was a fast analytic method that only changes what it must.

References

  1. Lucas Kovar, John Schreiner and Michael Gleicher, Footskate cleanup for motion capture editing, ACM SIGGRAPH/Eurographics Symposium on Computer Animation, 2002, 97 to 104, the footplant constraints, the change of the root position and of the leg joint orientations by analytic inverse kinematics, the small change of bone lengths, and the blend of the changes around the constraints
  2. Lucas Kovar, Michael Gleicher and Frederic Pighin, Motion graphs, ACM Transactions on Graphics 21(3) (SIGGRAPH 2002), 473 to 482, the transitions whose blends cause footskate
  3. Rick Parent, Computer Animation, Algorithms and Techniques, 3rd edition, Morgan Kaufmann, 2012, the chapter on kinematic linkages (inverse kinematics)

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.cleanup
  • a full proof of time.cleanup_with_sweep
  • 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
  • a scene preset for the example