To animate is to make transformations depend on time. The ship of "Stellar Lighthouse" has a model matrix; if that matrix is different in every frame, the ship moves. In "Physics Simulation" the change was dictated by the forces; here it is decided by a person—the animator—or by a formula, and the mathematical problem is a different one: starting from a few pieces of data (where the ship must be at certain instants, which points it must pass through, what angles the joints of an arm have), obtain a transformation for any instant, in a smooth and controllable way. Almost everything comes down to two tools we already have, interpolation and the composition of transformations, used with a little more cunning.
The code assumes that all the functions from the previous lessons have been imported (from mini3d import *).
Transformations that depend on time
An animation is a function that assigns a transformation to each instant \(t\): \(M(t)\). What is stored is not the matrix, but the parameters it depends on—a position, a quaternion, a scale, the angle of a joint—and each one is animated separately. The reason is the one we saw in "Interpolating Rotations: Lerp, Nlerp and Slerp": interpolating the entries of a matrix directly deforms the object along the way.
| Source of the motion | Who decides | Mathematical tool | Where it is covered |
|---|---|---|---|
| Keyframes | The animator fixes values at certain instants | Interpolation | Sections 2 to 7 |
| Hierarchies and skeletons | The animator fixes joint angles | Composition of matrices | Sections 8 to 10 |
| Procedural | A formula or a rule | Functions of \(t\), rotate_toward |
Section 11 |
| Motion capture | A real actor | The same tracks, measured instead of drawn | Section 11 |
| Simulation | The laws of physics | Numerical integration | "Physics Simulation" |
As a note for context: the animator's craft rests on the so-called twelve principles of animation (anticipation, slow in and slow out, arcs, exaggeration...), formulated in the classic cartoon studios. They are artistic criteria, not mathematical ones; but several of them—slow in and slow out, arcs—are exactly what the curves of this lesson let us control.
Keyframes and animation tracks
A keyframe is a pair (instant, value). A track is the list of keys of one parameter, sorted by time. To find the value at an arbitrary instant \(t\):
- We locate the two keys that enclose it, \((t_0, v_0)\) and \((t_1, v_1)\).
- We compute the fraction covered of the stretch: \(u = \dfrac{t - t_0}{t_1 - t_0}\), between 0 and 1.
- We interpolate: \(v = \operatorname{blend}(v_0, v_1, u)\).
The blend function depends on the type of data: lerp for positions, scales or single angles; quaternion_slerp for orientations; lerp_pose for a complete pose. Before the first key and after the last one, the value is held.
import numpy as np
from mini3d import *
np.set_printoptions(suppress=True)
def sample_track(keys, t, blend=lerp, curve=None):
"""Value of a track of keys [(time, value), ...] at the instant t.
blend(v0, v1, u): how to interpolate between two keys (lerp by default).
curve(u): optional reparameterization of the fraction u of each stretch."""
if t <= keys[0][0]:
return keys[0][1]
if t >= keys[-1][0]:
return keys[-1][1]
for (t0, v0), (t1, v1) in zip(keys[:-1], keys[1:]):
if t <= t1:
u = (t - t0) / (t1 - t0)
return blend(v0, v1, u if curve is None else curve(u))
ship, arrival, touchdown = np.array([8.0, 3.0, 6.0]), np.array([12.0, 3.0, 4.0]), np.array([11.0, 0.0, 3.0])
ship_orientation = np.array([[0.6, 0.0, 0.8], [0.0, 1.0, 0.0], [-0.8, 0.0, 0.6]])
q_ship = matrix_to_quaternion(ship_orientation)
q_lighthouse = matrix_to_quaternion(orthonormal_basis(-arrival)) # looking at the lighthouse from `arrival`
position_track = [(0.0, ship), (2.0, arrival), (5.0, touchdown)]
orientation_track = [(0.0, q_ship), (2.0, q_lighthouse)]
for t in (0.0, 1.0, 2.0, 3.5, 5.0):
q = sample_track(orientation_track, t, blend=quaternion_slerp)
print(t, sample_track(position_track, t), np.round(rotate_with_quaternion(q, [0.0, 0.0, 1.0]), 3))
print(round(distance(ship, arrival) / 2.0, 3), round(distance(arrival, touchdown) / 3.0, 3))0.0 [8. 3. 6.] [0.8 0. 0.6] 1.0 [10. 3. 5.] [-0.451 -0.116 0.885] 2.0 [12. 3. 4.] [-0.923 -0.231 -0.308] 3.5 [11.5 1.5 3.5] [-0.923 -0.231 -0.308] 5.0 [11. 0. 3.] [-0.923 -0.231 -0.308] 2.236 1.106
The position track has three keys: the ship leaves from \((8, 3, 6)\), at 2 s it is at the arrival point \((12, 3, 4)\) and at 5 s it touches the strip at \((11, 0, 3)\). The orientation track turns the nose (third column of the output) from \(\mathbf{n}_3\) until it looks at the lighthouse. The last line gives away the flaw of linear interpolation between keys: on the first stretch the ship travels at 2.24 m/s and on the second, at 1.11 m/s. At the middle key the velocity changes abruptly, in magnitude and in direction, and on top of that the motion starts and stops dead. The next two sections fix these two problems.
Easing curves: reparameterizing time
Nothing heavy starts or stops instantaneously. An easing curve is a function \(s(u)\) that turns the fraction of time \(u\) into a fraction of the path, with \(s(0) = 0\) and \(s(1) = 1\). The path is the same; what changes is the pace at which it is traveled: it is a reparameterization.
\[ v = \operatorname{blend}\big(v_0,\ v_1,\ s(u)\big) \]
| Curve | Formula | Slope at 0 and at 1 | Effect |
|---|---|---|---|
| Linear | \(s = u\) | 1 and 1 | Constant speed, abrupt start and stop |
| Ease-in | \(s = u^2\) | 0 and 2 | Starts slowly and accelerates |
| Ease-out | \(s = 1 - (1 - u)^2\) | 2 and 0 | Leaves fast and brakes |
| Ease-in-out (smoothstep) | \(s = 3u^2 - 2u^3\) | 0 and 0 | Accelerates, cruises and brakes |
The slope of \(s\) is the factor by which the speed is multiplied: slope 0 means "stopped". The smoothstep polynomial, \(3u^2 - 2u^3\), is the simplest cubic that equals 0 and 1 at the ends with zero slope at both; its maximum slope, at the center, is 1.5: to arrive at the same time having started and braked slowly, you have to go faster in the middle of the way.
def smoothstep(t):
"""Smoothstep: 3t^2 - 2t^3. Starts and ends with zero speed."""
t = np.clip(t, 0.0, 1.0)
return t * t * (3.0 - 2.0 * t)
def ease_in(t):
return t * t
def ease_out(t):
return 1.0 - (1.0 - t) ** 2
for u in (0.0, 0.25, 0.5, 0.75, 1.0):
print(u, ease_in(u), ease_out(u), float(smoothstep(u)))
descent = [(2.0, arrival), (5.0, touchdown)]
print(sample_track(descent, 2.75), sample_track(descent, 2.75, curve=smoothstep))0.0 0.0 0.0 0.0 0.25 0.0625 0.4375 0.15625 0.5 0.25 0.75 0.5 0.75 0.5625 0.9375 0.84375 1.0 1.0 1.0 1.0 [11.75 2.25 3.75] [11.84375 2.53125 3.84375]
A quarter of the way through the time, ease-in has covered only 6% of the path; ease-out, 44%; smoothstep, 16%. The last line applies the curve to the descent stretch: at 2.75 s (a quarter of the stretch), the ship with linear interpolation has already come down 0.75 m; with smoothstep, only 0.47 m, because it is still accelerating.
Smooth trajectories: Hermite and Catmull-Rom splines
Easing fixes the pace, but not the shape: between keys the ship still goes in a straight line, and at each key the trajectory turns a corner. To pass smoothly through several points we need curves. The Bézier curves of "Surface Modeling" are smooth, but they do not pass through their intermediate control points; an animator wants the opposite: a curve that passes through the points they mark.
Hermite: two points and two tangents
The cubic Hermite spline defines a piece with four pieces of data: the endpoints \(\mathbf{p}_0\), \(\mathbf{p}_1\) and the tangents (velocities) at them, \(\mathbf{m}_0\), \(\mathbf{m}_1\). A cubic polynomial \(\mathbf{p}(t) = \mathbf{a} + \mathbf{b},t + \mathbf{c},t^2 + \mathbf{d},t^3\) has four coefficients, and the four conditions determine them:
\[ \mathbf{p}(0) = \mathbf{a} = \mathbf{p}_0 \qquad \mathbf{p}'(0) = \mathbf{b} = \mathbf{m}_0 \qquad \mathbf{p}(1) = \mathbf{a} + \mathbf{b} + \mathbf{c} + \mathbf{d} = \mathbf{p}_1 \qquad \mathbf{p}'(1) = \mathbf{b} + 2\mathbf{c} + 3\mathbf{d} = \mathbf{m}_1 \]
It is a linear system like those of Module 1. Solving it (\(\mathbf{c} = 3(\mathbf{p}_1 - \mathbf{p}_0) - 2\mathbf{m}_0 - \mathbf{m}_1\), \(\mathbf{d} = -2(\mathbf{p}_1 - \mathbf{p}_0) + \mathbf{m}_0 + \mathbf{m}_1\)) and grouping by data:
\[ \mathbf{p}(t) = (2t^3 - 3t^2 + 1),\mathbf{p}_0 + (t^3 - 2t^2 + t),\mathbf{m}_0 + (-2t^3 + 3t^2),\mathbf{p}_1 + (t^3 - t^2),\mathbf{m}_1 \]
A curiosity: the weight of \(\mathbf{p}_1\), \(3t^2 - 2t^3\), is the smoothstep.
Relationship with Bézier. A cubic Bézier curve with control points \(\mathbf{b}_0 \dots \mathbf{b}_3\) has tangents \(3(\mathbf{b}_1 - \mathbf{b}_0)\) and \(3(\mathbf{b}_3 - \mathbf{b}_2)\) at its endpoints. Therefore, the Hermite piece is the cubic Bézier curve with control points
\[ \mathbf{b}_0 = \mathbf{p}_0 \qquad \mathbf{b}_1 = \mathbf{p}_0 + \tfrac{1}{3},\mathbf{m}_0 \qquad \mathbf{b}_2 = \mathbf{p}_1 - \tfrac{1}{3},\mathbf{m}_1 \qquad \mathbf{b}_3 = \mathbf{p}_1 \]
They are two ways of writing the same polynomial: with "handles" (Bézier) or with velocities (Hermite).
Catmull-Rom: the tangents are deduced from the neighbors
With Hermite a tangent has to be given at each point. The Catmull-Rom spline computes it automatically: at each point, the tangent is parallel to the chord that joins the previous point to the next one.
\[ \mathbf{m}i = \frac{\mathbf{p}{i+1} - \mathbf{p}_{i-1}}{2} \]
The piece between \(\mathbf{p}_1\) and \(\mathbf{p}_2\) therefore needs four points: \(\mathbf{p}_0\) and \(\mathbf{p}_3\) only serve to fix the tangents. Two properties:
- It interpolates: the curve passes through all the points.
- \(C^1\) continuity: at each point, the piece that arrives and the one that leaves share position and tangent (the same \(\mathbf{m}_i\)), so the velocity does not jump. The acceleration can: it is not \(C^2\).
def hermite(p0, m0, p1, m1, t):
"""Cubic Hermite piece: endpoints p0, p1 and tangents m0, m1; t in [0, 1]."""
p0, m0, p1, m1 = (np.asarray(x, dtype=float) for x in (p0, m0, p1, m1))
t2, t3 = t * t, t * t * t
return ((2 * t3 - 3 * t2 + 1) * p0 + (t3 - 2 * t2 + t) * m0
+ (-2 * t3 + 3 * t2) * p1 + (t3 - t2) * m1)
def catmull_rom(p0, p1, p2, p3, t):
"""Point of the piece p1 -> p2 of the Catmull-Rom spline; t in [0, 1]."""
p0, p1, p2, p3 = (np.asarray(x, dtype=float) for x in (p0, p1, p2, p3))
return hermite(p1, (p2 - p0) / 2.0, p2, (p3 - p1) / 2.0, t)
def catmull_rom_path(points, u):
"""Catmull-Rom spline through all the points; u in [0, n - 1] (u = k: point k)."""
points = np.asarray(points, dtype=float)
extended = np.vstack([points[0], points, points[-1]]) # duplicated endpoints
k = min(int(u), len(points) - 2)
return catmull_rom(*extended[k:k + 4], u - k)
alpha, beacon2 = np.array([12.0, 7.0, 4.0]), np.array([9.0, 4.0, 0.0])
patrol = [ship, arrival, alpha, beacon2]
print(catmull_rom(*patrol, 0.0), catmull_rom(*patrol, 1.0), catmull_rom(*patrol, 0.5))
m1, m2 = (alpha - ship) / 2.0, (beacon2 - arrival) / 2.0
print(np.allclose(catmull_rom(*patrol, 0.3), bezier([arrival, arrival + m1 / 3.0, alpha - m2 / 3.0, alpha], 0.3)))
h = 1e-6
print(np.round((catmull_rom_path(patrol, 1.0) - catmull_rom_path(patrol, 1.0 - h)) / h, 3),
np.round((catmull_rom_path(patrol, 1.0 + h) - catmull_rom_path(patrol, 1.0)) / h, 3))The surveillance patrol passes through four points: the ship's position, the arrival point, beacon Alpha \((12, 7, 4)\) and beacon \(B_2 = (9, 4, 0)\) of the strip. The central piece starts exactly at arrival, ends at Alpha and halfway along passes through \((12.44, 5.19, 4.13)\): it bulges 0.44 m outward in \(x\) instead of going straight. The second line confirms the equivalence with Bézier. The third measures the velocity just before and just after the arrival point: it is \((2, 2, -1)\) on both sides, half the chord from the ship to Alpha. There is no corner.
For the first and the last piece a neighbor is missing; catmull_rom_path duplicates the endpoints, which is the simplest solution.
Constant speed: arc-length reparameterization
The parameter \(t\) of a curve is not distance. The ship's approach route to the strip is the cubic Bézier curve with control points \((8, 3, 6)\), \((12, 3, 9)\), \((9, 2, 5)\) and \((11, 0, 3)\). Its derivative has magnitude 15 at the beginning, drops to 6 around the middle and rises again to 10.4 at the end: if we advance \(t\) at a constant pace, the ship shoots off, slows down in the bend and accelerates again. Nobody chose that pace: it is an accident of where the control points are.
To control the speed we have to parameterize the curve by its arc length \(s\): the distance traveled from the start. There is no exact formula for a cubic, so it is tabulated:
- The curve is sampled at many values of \(t\) and the distances between consecutive samples are accumulated: a table \(t \to s\).
- To find the point located at a distance \(s\), the table is searched in reverse (interpolating linearly between rows): \(s \to t\).
def arc_length_table(curve, samples=200):
"""Table (parameters, accumulated lengths) of a curve `curve(t)`, t in [0, 1]."""
parameters = np.linspace(0.0, 1.0, samples + 1)
points = np.array([curve(t) for t in parameters])
segments = np.linalg.norm(np.diff(points, axis=0), axis=1)
return parameters, np.concatenate(([0.0], np.cumsum(segments)))
def parameter_at_length(table, s):
"""Parameter t at which the curve has covered the distance s (reverse lookup in the table)."""
parameters, lengths = table
return float(np.interp(s, lengths, parameters))
route = np.array([[8.0, 3.0, 6.0], [12.0, 3.0, 9.0], [9.0, 2.0, 5.0], [11.0, 0.0, 3.0]])
approach = lambda t: bezier(route, t)
table = arc_length_table(approach)
total_length = table[1][-1]
print(round(total_length, 3))
for fraction in (0.0, 0.25, 0.5, 0.75, 1.0):
t_arc = parameter_at_length(table, fraction * total_length)
print(fraction, round(float(np.interp(fraction, table[0], table[1])), 3), round(t_arc, 4),
np.round(approach(t_arc), 3))7.496 0.0 0.0 0.0 [8. 3. 6.] 0.25 2.199 0.1842 [9.573 2.898 7.002] 0.5 3.271 0.5724 [10.239 2.017 5.959] 0.75 5.162 0.8025 [10.308 1.068 4.35 ] 1.0 7.496 1.0 [11. 0. 3.]
| Fraction | Distance traveled if \(t\) = fraction | \(t\) needed to travel that fraction of the length | Point |
|---|---|---|---|
| 0.25 | 2.199 m (29%) | 0.1842 | \((9.573, 2.898, 7.002)\) |
| 0.50 | 3.271 m (44%) | 0.5724 | \((10.239, 2.017, 5.959)\) |
| 0.75 | 5.162 m (69%) | 0.8025 | \((10.308, 1.068, 4.350)\) |
The route is 7.50 m long. With the original parameter, 29% of the path is covered in the first quarter of the time and only 14% in the second. With the table, we ask for "half the path" and get \(t = 0.5724\). Now the speed is constant, and on top of it we can apply whatever easing curve we like: first the pace is decided, then it is converted to distance and finally to parameter.
\[ \text{time} ;\xrightarrow{\ \text{easing}\ }; \text{fraction of the path} ;\xrightarrow{\ \times L\ }; s ;\xrightarrow{\ \text{table}\ }; t ;\xrightarrow{\ \text{curve}\ }; \mathbf{p} \]
Orienting an object along its trajectory
A ship that follows a curve must point in the direction in which it is advancing. That direction is the tangent to the curve, \(\mathbf{p}'(t)\) (for the Bézier curve, bezier_tangent). With it as the "forward" axis and a reference "up" vector, orthonormal_basis builds the complete orientation matrix, exactly as when we oriented the ship toward a target; from there, matrix_to_quaternion.
There is a basis that needs no external "up": the Frenet frame, formed by the tangent, the normal (toward where the trajectory bends, obtained from the second derivative) and their cross product, the binormal. It is elegant, but not very practical for animating: it is not defined on straight stretches and it flips 180° at inflection points. That is why a fixed "up" is almost always used, or one interpolated between keys to simulate the roll in the bends.
Example: the ship's approach and landing
Let us put it all together. The ship travels the approach route in 6 seconds:
- Pace:
smoothstepover the total time (it starts and settles gently), converted to distance and to parameter with the arc-length table. - Position: the Bézier curve at that parameter.
- Orientation: the nose follows the tangent; during the last 40% of the time it is blended with
quaternion_slerptoward the landing orientation, in which the ship's "up" is the normal of the strip, \(\left(\tfrac{1}{3}, \tfrac{2}{3}, \tfrac{2}{3}\right)\), and the nose is the final tangent flattened onto the strip withslide.
strip_normal = np.array([1.0, 2.0, 2.0]) / 3.0
end_nose = slide(bezier_tangent(route, 1.0), strip_normal)
q_strip = matrix_to_quaternion(orthonormal_basis(end_nose, strip_normal))
DURATION = 6.0
def approach_pose(t):
"""Pose (position, quaternion) of the ship at the instant t of the maneuver."""
fraction = float(smoothstep(t / DURATION))
parameter = parameter_at_length(table, fraction * total_length)
q_tangent = matrix_to_quaternion(orthonormal_basis(bezier_tangent(route, parameter)))
blend = float(smoothstep((t / DURATION - 0.6) / 0.4)) # 0 up to 60%, 1 at the end
return bezier(route, parameter), quaternion_slerp(q_tangent, q_strip, blend)
for t in (0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0):
p, q = approach_pose(t)
speed = distance(approach_pose(t + 0.01)[0], approach_pose(t - 0.01)[0]) / 0.02
print(t, np.round(p, 2), round(speed, 2), np.round(rotate_with_quaternion(q, [0.0, 0.0, 1.0]), 2),
np.round(rotate_with_quaternion(q, [0.0, 1.0, 0.0]), 2))0.0 [8. 3. 6.] 0.0 [0.8 0. 0.6] [0. 1. 0.] 1.0 [8.45 3. 6.33] 1.04 [ 0.82 -0.02 0.58] [0.02 1. 0.01] 2.0 [9.64 2.88 7.03] 1.66 [ 0.92 -0.21 0.32] [0.2 0.98 0.07] 3.0 [10.24 2.02 5.96] 1.87 [-0.03 -0.48 -0.87] [-0.02 0.87 -0.48] 4.0 [10.3 1.11 4.41] 1.67 [ 0.23 -0.49 -0.84] [ 0.17 0.87 -0.46] 5.0 [10.71 0.32 3.35] 1.04 [ 0.81 -0.31 -0.49] [0.48 0.84 0.26] 6.0 [11. 0. 3.] 0.0 [ 0.94 -0.24 -0.24] [0.33 0.67 0.67]
Each row shows the instant, the position, the speed, the nose and the "up" of the ship. The speed follows the bell shape of the smoothstep: zero on leaving, greatest halfway through the maneuver (\(1.5 \cdot 7.5 / 6 = 1.87\) m/s) and zero on settling. The nose starts at \((0.8, 0, 0.6)\)—the route leaves in the direction of \(\mathbf{n}_3\)—turns and tilts downward following the curve and, from 3.6 s on (60% of the maneuver), gradually rises until it is parallel to the strip, while the "up" goes from the vertical to the normal of the strip, \((0.33, 0.67, 0.67)\). The ship settles at \((11, 0, 3)\), the touchdown point we computed in Module 3, resting on the plane.
Hierarchical animation and forward kinematics
Many objects are articulated: an arm, a leg, the ship's folding antenna. Their parts form a parent-child hierarchy, like the scene graph of "Composition of Transformations", and what is animated is not positions, but joint angles. Forward kinematics (FK) answers the question: given the angles, where does each part end up? The answer is a product of matrices, from the root toward the end.
The ship has an articulated arm with two segments, anchored at the point \((1, 2, 0)\) of the ship (the old hinge of the antenna). The first segment, of length \(\ell_1 = 2\), rotates at the shoulder; the second, of \(\ell_2 = 1.5\), at the elbow. Both rotate about the local \(Z\) axis, so the arm moves in a plane. Each joint contributes "translate to the joint and rotate":
\[ M_{\text{shoulder}} = M_{\text{ship}};T(1, 2, 0);R_z(\theta_1) \qquad M_{\text{elbow}} = M_{\text{shoulder}};T(\ell_1, 0, 0);R_z(\theta_2) \qquad \mathbf{p}{\text{tip}} = M{\text{elbow}},(\ell_2, 0, 0) \]
In the plane of the arm, with the origin at the shoulder, the product reduces to the classic formula (the angles accumulate as we go down the chain):
\[ x = \ell_1 \cos\theta_1 + \ell_2 \cos(\theta_1 + \theta_2) \qquad y = \ell_1 \sin\theta_1 + \ell_2 \sin(\theta_1 + \theta_2) \]
ship_world = model_matrix(ship, ship_orientation)
arm_base = ship_world @ translation_matrix(1.0, 2.0, 0.0) # the shoulder's system, unrotated
L1, L2 = 2.0, 1.5
def forward_kinematics(theta1, theta2):
"""World matrices of the shoulder and of the elbow, and position of the tip of the arm."""
shoulder = arm_base @ rotation_matrix_z(theta1)
elbow = shoulder @ translation_matrix(L1, 0.0, 0.0) @ rotation_matrix_z(theta2)
return shoulder, elbow, transform_point(elbow, [L2, 0.0, 0.0])
theta1, theta2 = np.radians(60.0), np.radians(-90.0)
shoulder, elbow, tip = forward_kinematics(theta1, theta2)
print(np.round(transform_point(elbow, [0.0, 0.0, 0.0]), 3), np.round(tip, 3))
print(np.round([L1 * np.cos(theta1) + L2 * np.cos(theta1 + theta2),
L1 * np.sin(theta1) + L2 * np.sin(theta1 + theta2)], 3),
np.round(world_to_local(arm_base, tip), 3) + 0.0)With the shoulder at 60° and the elbow at −90°, the tip ends up at \((2.299, 0.982)\) in the plane of the arm; the trigonometric formula and the product of matrices agree. Animating the arm means animating two numbers, \(\theta_1(t)\) and \(\theta_2(t)\), with tracks like those at the beginning; if the ship moves, the arm follows it without our touching anything, because \(M_{\text{ship}}\) heads the chain.
Two-bone inverse kinematics
Often we want the opposite: for the tip of the arm to reach a point (grabbing a container, planting a foot on the ground) without having to guess the angles. This is inverse kinematics (IK): given the position of the end, find the angles. In general it is a hard problem, with no solution, one or infinitely many; for a chain of two bones in a plane it has an exact solution, and it is pure trigonometry.
The shoulder, the elbow and the target form a triangle whose three sides are known: \(\ell_1\), \(\ell_2\) and the distance \(d\) from the shoulder to the target \((x, y)\). The law of cosines gives its angles:
\[ d^2 = \ell_1^2 + \ell_2^2 - 2,\ell_1 \ell_2 \cos\gamma \]
where \(\gamma\) is the interior angle at the elbow. The elbow's rotation angle is its supplement, \(\theta_2 = \pi - \gamma\), so that \(\cos\theta_2 = -\cos\gamma\):
\[ \cos\theta_2 = \frac{d^2 - \ell_1^2 - \ell_2^2}{2,\ell_1 \ell_2} \qquad\qquad \theta_1 = \operatorname{atan2}(y, x) - \operatorname{atan2}\big(\ell_2 \sin\theta_2,\ \ell_1 + \ell_2 \cos\theta_2\big) \]
The second formula says: the shoulder angle is the direction toward the target, corrected by the angle that the bent arm makes with that direction. Three cases:
| Situation | Condition | What happens |
|---|---|---|
| Reachable | \(\lvert \ell_1 - \ell_2 \rvert \le d \le \ell_1 + \ell_2\) | Two solutions, \(\pm\theta_2\): elbow to one side or the other |
| Too far | \(d > \ell_1 + \ell_2\) | The cosine comes out greater than 1: it is clamped to 1 and the arm stretches toward the target |
| Too close | \(d < \lvert \ell_1 - \ell_2 \rvert\) | The cosine comes out less than −1: it is clamped and the arm folds completely |
def two_bone_ik(l1, l2, x, y, positive_elbow=True):
"""Angles (theta1, theta2) of a planar two-bone chain so that its tip reaches (x, y).
If the target is not reachable, it returns the pose that gets closest."""
d2 = x * x + y * y
cosine = np.clip((d2 - l1 * l1 - l2 * l2) / (2.0 * l1 * l2), -1.0, 1.0)
theta2 = np.arccos(cosine) if positive_elbow else -np.arccos(cosine)
theta1 = np.arctan2(y, x) - np.arctan2(l2 * np.sin(theta2), l1 + l2 * np.cos(theta2))
return float(theta1), float(theta2)
connector = np.array([9.8, 6.5, 3.6]) # world point that the arm must reach
target = world_to_local(arm_base, connector) # in the shoulder's system
print(np.round(target, 4) + 0.0)
for positive_elbow in (True, False):
a1, a2 = two_bone_ik(L1, L2, target[0], target[1], positive_elbow)
print(np.round(np.degrees([a1, a2]), 2) + 0.0, np.round(forward_kinematics(a1, a2)[2], 4))
a1, a2 = two_bone_ik(L1, L2, 3.0, 3.0)
print(np.round(np.degrees([a1, a2]), 2) + 0.0)The connector is at \((2, 1.5, 0)\) relative to the shoulder: in the plane of the arm, at a distance \(d = 2.5\). With sides 2, 1.5 and 2.5—a scaled 3-4-5 triangle—the angle at the elbow is a right angle. The two solutions are shoulder at 0° with the elbow at +90° (the first segment along \(X\) and the second pointing up) and shoulder at 73.74° with the elbow at −90°. In both cases, forward kinematics confirms that the tip reaches the connector. The last case is a target out of reach, 4.24 m away with a 3.5 m arm: the elbow stays at 0° and the arm points at 45°, toward it.
If the target is not in the plane of the arm, first that plane is rotated about an axis through the shoulder until it contains the target, and then the problem is solved in 2D. For chains of more bones (a tail, a spine, a tentacle) there is no closed formula and iterative methods are used: CCD, which rotates one joint at a time to bring the tip closer to the target, and FABRIK, which repositions the points of the chain forward and backward while preserving the lengths.
Skeletal animation and linear skinning
A character is not animated vertex by vertex. A skeleton is placed inside it—a hierarchy of bones, like our arm—and only the skeleton is animated; the mesh, the "skin", follows it. The process of deforming the mesh with the bones is called skinning.
The mesh is modeled in a reference pose, the bind pose. Let \(B_i\) be the world matrix of bone \(i\) in that pose and \(M_i\) its world matrix in the animated pose. For a vertex \(\mathbf{v}\) that depends on a single bone:
\[ \mathbf{v}' = M_i,B_i^{-1},\mathbf{v} \]
It is a change of coordinate system in two steps, like those of "Inverse Transformations and Change of Coordinate System": \(B_i^{-1}\)—the inverse bind matrix—expresses the vertex in the local system of the bone, where it will stay fixed forever; \(M_i\) returns it to the world with the bone in its current pose. If the bone has not moved, \(M_i = B_i\) and the vertex stays where it was.
Near a joint, a vertex rigidly attached to a single bone would produce an abrupt crease. The solution is for it to depend on several bones, with weights \(w_i\) that add up to 1, and to blend the results:
\[ \mathbf{v}' = \sum_i w_i,M_i,B_i^{-1},\mathbf{v} \qquad \sum_i w_i = 1 \]
This is linear skinning (in full, linear blend skinning): a convex combination—an interpolation—of the positions that each bone proposes for the vertex.
Example. We work in the plane of the arm, with the shoulder at the origin. In the bind pose the arm is stretched out along the \(X\) axis: \(B_1 = I\) (shoulder) and \(B_2 = T(2, 0, 0)\) (elbow). The arm's sleeve has a vertex at \(\mathbf{v} = (2, 0.2, 0)\), right above the elbow, with weights \((0.5, 0.5)\). We bend the elbow 90°: \(M_1 = I\), \(M_2 = T(2, 0, 0),R_z(90°)\).
- Bone 1: \(M_1 B_1^{-1},\mathbf{v} = (2, 0.2, 0)\). It does not move.
- Bone 2: \(B_2^{-1},\mathbf{v} = (0, 0.2, 0)\); rotated 90°, \((-0.2, 0, 0)\); translated, \((1.8, 0, 0)\).
- Blend: \(0.5,(2, 0.2, 0) + 0.5,(1.8, 0, 0) = (1.9, 0.1, 0)\).
def linear_skinning(vertices, weights, bone_matrices, inverse_binds):
"""Linear skinning: v' = sum_i w_i M_i B_i^-1 v.
vertices: (n, 3); weights: (n, h), each row adds up to 1; bone_matrices and inverse_binds:
h 4x4 matrices (current pose of each bone and inverse of its bind pose)."""
vertices, weights = np.asarray(vertices, dtype=float), np.asarray(weights, dtype=float)
result = np.zeros_like(vertices)
for i, (m, b_inv) in enumerate(zip(bone_matrices, inverse_binds)):
result += weights[:, [i]] * transform_points(m @ b_inv, vertices)
return result
bind = [np.eye(4), translation_matrix(L1, 0.0, 0.0)]
inverse_binds = [rigid_inverse(b) for b in bind]
sleeve = np.array([[1.0, 0.2, 0.0], [2.0, 0.2, 0.0], [3.0, 0.2, 0.0]])
weights = np.array([[1.0, 0.0], [0.5, 0.5], [0.0, 1.0]])
bent = [np.eye(4), translation_matrix(L1, 0.0, 0.0) @ rotation_matrix_z(np.radians(90.0))]
print(np.round(linear_skinning(sleeve, weights, bind, inverse_binds), 3))
skin = linear_skinning(sleeve, weights, bent, inverse_binds)
print(np.round(skin, 3) + 0.0, round(distance(skin[1], [2.0, 0.0, 0.0]), 4))
twisted = [np.eye(4), translation_matrix(L1, 0.0, 0.0) @ rotation_matrix_x(np.radians(180.0))]
print(np.round(linear_skinning(sleeve, weights, twisted, inverse_binds), 3) + 0.0)[[1. 0.2 0. ] [2. 0.2 0. ] [3. 0.2 0. ]] [[1. 0.2 0. ] [1.9 0.1 0. ] [1.8 1. 0. ]] 0.1414 [[ 1. 0.2 0. ] [ 2. 0. 0. ] [ 3. -0.2 0. ]]
The first matrix checks that, in the bind pose, the skin does not move. The second is the bent elbow: the vertex that depends only on the first bone stays in place, the one that depends only on the second rotates with it to \((1.8, 1, 0)\), and the one at the elbow ends up at \((1.9, 0.1, 0)\), halfway between. But that vertex was 0.2 from the axis of the arm and now it is 0.141 away: the linear blend of two positions shortens distances, just as the lerp of quaternions cut through the inside of the sphere. The elbow gets thinner.
The third matrix takes the flaw to the extreme: the second bone rotates 180° about its own axis, like a wrist twisting. Bone 2 proposes \((2, -0.2, 0)\), bone 1 proposes \((2, 0.2, 0)\), and the average is \((2, 0, 0)\): the vertex falls onto the axis and the sleeve is pinched to a point, like the wrapper of a candy. It is the famous "candy wrapper" artifact of linear skinning. It is mitigated by spreading the twist over several auxiliary bones or by replacing the blend of matrices with a blend of dual quaternions, which interpolates rigid transformations without losing volume, like slerp compared with lerp.
On a GPU, skinning is done in the vertex shader: each vertex carries as attributes the indices of its bones (normally up to four) and their weights, and the matrices \(M_i B_i^{-1}\) of the whole skeleton are sent once per frame.
Procedural animation and motion capture
Not all motion is drawn with keys. In procedural animation the value of each parameter comes from a formula or from a rule evaluated every frame:
| Motion | Formula or rule | Example in the scene |
|---|---|---|
| Orbit | \(\mathbf{p}(t) = \mathbf{c} + r,(\cos\omega t,\ 0,\ \sin\omega t)\), or a rotation of angle \(\omega t\) | The escort drone circles the ship |
| Oscillation | \(A \sin(2\pi f,t + \varphi)\) | A beacon bobbing up and down; the flicker of a light |
| Continuous rotation | Angle \(= \omega,t\) | The lighthouse lamp |
| Tracking | Rotate toward a target without exceeding an angular velocity | A turret aiming at the ship |
The sine is the universal tool for oscillation: amplitude \(A\), frequency \(f\) (cycles per second) and phase \(\varphi\) (so that several objects do not move in unison). Tracking uses rotate_toward, from "Interpolating Rotations: Lerp, Nlerp and Slerp": every frame we compute the orientation that would look at the target and rotate toward it by at most \(\omega_{\text{max}},\Delta t\).
DT = 0.1
turret, q_turret = np.array([0.0, 12.0, 0.0]), np.array([1.0, 0.0, 0.0, 0.0])
for step in range(31):
t = step * DT
drone = ship + 2.0 * np.array([np.cos(1.5 * t), 0.0, np.sin(1.5 * t)]) # orbit of radius 2
drone[1] += 0.3 * np.sin(2.0 * np.pi * 0.5 * t) # vertical bobbing
q_target = matrix_to_quaternion(orthonormal_basis(drone - turret))
q_turret = rotate_toward(q_turret, q_target, np.radians(60.0) * DT) # 60 degrees/s at most
if step % 5 == 0:
print(round(t, 1), np.round(drone, 2),
round(np.degrees(angle_between_orientations(q_turret, q_target)), 1))0.0 [10. 3. 6.] 63.1 0.5 [9.46 3.3 7.36] 26.6 1.0 [8.14 3. 7.99] 0.0 1.5 [6.74 2.7 7.56] 0.0 2.0 [6.02 3. 6.28] 0.0 2.5 [6.36 3.3 4.86] 0.0 3.0 [7.58 3. 4.04] 0.0
The drone describes an orbit of radius 2 around the ship while it rises and falls 0.3 m. The lighthouse turret, which starts out looking toward \(+Z\), chases it at 60°/s: the last column is the angle it still has to cover. During the first second it reduces it at its maximum rate, 6° per step; when it catches up, the error stays at zero and the turret follows the drone with no lag, because the drone moves, as seen from the lighthouse, much more slowly than the turret's maximum turning speed.
Motion capture (mocap) reverses the division of roles: instead of the animator drawing the tracks, they are measured. An actor wears markers or sensors; a system of cameras reconstructs their 3D positions (by triangulating, with the same pinhole camera geometry as in "Virtual and Augmented Reality"), and from them the rotation of each bone of the skeleton is solved, frame by frame: an inverse kinematics problem. The result is tracks with one key per frame, which are then filtered, trimmed and blended with one another—walking with running, for example—by interpolating poses bone by bone with lerp_pose.
Common Mistakes and Tips
- Interpolating orientations with a lerp of Euler angles or of matrices. Use quaternions and slerp, and take care of the shortest path between consecutive keys.
- Applying the easing to the value instead of to the time. The easing curve transforms the fraction \(u\); the blend of values stays the same.
- Assuming that the parameter of a curve is distance. Advancing \(t\) at a constant pace does not give constant speed: reparameterize by arc length.
- Forgetting the neighbors in Catmull-Rom. Each piece needs four points; at the ends one has to be duplicated or invented.
- Composing the hierarchy in the wrong order. The world matrix of a bone is \(M_{\text{parent}} \cdot M_{\text{local}}\), from the root toward the tip.
- Not clamping the cosine in inverse kinematics. With a target out of reach,
arccosreceives a value greater than 1 and returnsnan: the arm disappears. - Skinning weights that do not add up to 1. The vertex drifts toward the origin or away from it even though the skeleton does not move.
- Forgetting the inverse bind matrix. Without \(B_i^{-1}\), the vertex is transformed as if it were expressed in the bone's system, and the mesh comes out torn to pieces.
- Orienting with the tangent at a point where the velocity is zero.
normalizefails with the zero vector: keep the last valid orientation. - Tip. Always check the bind pose: with \(M_i = B_i\),
linear_skinningmust return the mesh intact. And for inverse kinematics, run the result through forward kinematics.
Exercises
Exercise 1. The ship's descent stretch has the keys \((2\ \text{s}, (12, 3, 4))\) and \((5\ \text{s}, (11, 0, 3))\).
a) Compute by hand the position at 3.5 s with linear interpolation.
b) Compute the position at 4.25 s with the smoothstep curve.
c) At what instant is the speed greatest with smoothstep, and what is its value?
Exercise 2. For the central piece of the patrol, with \(\mathbf{p}_0 = (8, 3, 6)\), \(\mathbf{p}_1 = (12, 3, 4)\), \(\mathbf{p}_2 = (12, 7, 4)\) and \(\mathbf{p}_3 = (9, 4, 0)\):
a) Compute the Catmull-Rom tangents at \(\mathbf{p}_1\) and \(\mathbf{p}_2\). b) Show that at \(t = \tfrac{1}{2}\) the spline equals \(\dfrac{-\mathbf{p}_0 + 9,\mathbf{p}_1 + 9,\mathbf{p}_2 - \mathbf{p}_3}{16}\) and compute that point. c) Write the four control points of the equivalent Bézier curve.
Exercise 3. The ship's arm (\(\ell_1 = 2\), \(\ell_2 = 1.5\)) must reach the point \((2.4, 0.7)\) of the plane of the arm.
a) Compute by hand the angles of the two solutions.
b) Check it with two_bone_ik and forward_kinematics, and give the position of the elbow in the world for each solution.
c) A vertex of the sleeve located at \((2, -0.2, 0)\), with weights \((0.5, 0.5)\): where does it end up in each of the two poses?
Solutions
Solution 1.
a) \(u = \dfrac{3.5 - 2}{5 - 2} = 0.5\). Position: the midpoint, \((11.5, 1.5, 3.5)\).
b) \(u = \dfrac{4.25 - 2}{3} = 0.75\); \(s = 3 \cdot 0.75^2 - 2 \cdot 0.75^3 = 1.6875 - 0.84375 = 0.84375\). Position: \((12, 3, 4) + 0.84375,(-1, -3, -1) = (11.156, 0.469, 3.156)\).
c) The derivative of \(3u^2 - 2u^3\) is \(6u - 6u^2 = 6u(1 - u)\), greatest at \(u = 0.5\), where it equals 1.5. That is, at 3.5 s, and the speed is 1.5 times that of the linear motion: \(1.5 \cdot \dfrac{\lVert (-1, -3, -1) \rVert}{3} = 1.5 \cdot \dfrac{3.317}{3} = 1.658\) m/s.
Solution 2.
a) \(\mathbf{m}_1 = \dfrac{\mathbf{p}_2 - \mathbf{p}_0}{2} = \dfrac{(4, 4, -2)}{2} = (2, 2, -1)\); \(\mathbf{m}_2 = \dfrac{\mathbf{p}_3 - \mathbf{p}_1}{2} = \dfrac{(-3, 1, -4)}{2} = (-1.5, 0.5, -2)\).
b) At \(t = \tfrac{1}{2}\), the four Hermite weights equal \(\tfrac{1}{2}\), \(\tfrac{1}{8}\), \(\tfrac{1}{2}\) and \(-\tfrac{1}{8}\):
\[ \mathbf{p}\left(\tfrac{1}{2}\right) = \tfrac{1}{2},\mathbf{p}_1 + \tfrac{1}{8} \cdot \tfrac{\mathbf{p}_2 - \mathbf{p}_0}{2} + \tfrac{1}{2},\mathbf{p}_2 - \tfrac{1}{8} \cdot \tfrac{\mathbf{p}_3 - \mathbf{p}_1}{2} = \frac{-\mathbf{p}_0 + 9,\mathbf{p}_1 + 9,\mathbf{p}_2 - \mathbf{p}_3}{16} \]
Numerically: \(\dfrac{(-8 + 108 + 108 - 9,\ -3 + 27 + 63 - 4,\ -6 + 36 + 36 - 0)}{16} = \dfrac{(199, 83, 66)}{16} = (12.4375,\ 5.1875,\ 4.125)\).
c) \(\mathbf{b}_0 = (12, 3, 4)\); \(\mathbf{b}_1 = \mathbf{p}_1 + \tfrac{1}{3}\mathbf{m}_1 = (12.667, 3.667, 3.667)\); \(\mathbf{b}_2 = \mathbf{p}_2 - \tfrac{1}{3}\mathbf{m}_2 = (12.5, 6.833, 4.667)\); \(\mathbf{b}_3 = (12, 7, 4)\).
Solution 3.
a) \(d^2 = 2.4^2 + 0.7^2 = 5.76 + 0.49 = 6.25\), \(d = 2.5\). \(\cos\theta_2 = \dfrac{6.25 - 4 - 2.25}{6} = 0\): \(\theta_2 = \pm 90°\). Direction to the target: \(\operatorname{atan2}(0.7, 2.4) = 16.26°\). Correction: \(\operatorname{atan2}(\pm 1.5, 2) = \pm 36.87°\). Solutions: \((\theta_1, \theta_2) = (-20.61°, 90°)\) and \((53.13°, -90°)\).
b) and c)
print(sample_track(descent, 3.5), np.round(sample_track(descent, 4.25, curve=smoothstep), 4),
round(1.5 * distance(arrival, touchdown) / 3.0, 3))
print(m1, m2, catmull_rom(*patrol, 0.5), np.round([arrival + m1 / 3.0, alpha - m2 / 3.0], 3).tolist())
for positive_elbow in (True, False):
a1, a2 = two_bone_ik(L1, L2, 2.4, 0.7, positive_elbow)
shoulder, elbow, tip = forward_kinematics(a1, a2)
shoulder_local = rotation_matrix_z(a1) # the same matrices, in the plane of the arm
elbow_local = shoulder_local @ translation_matrix(L1, 0.0, 0.0) @ rotation_matrix_z(a2)
skin = linear_skinning([[2.0, -0.2, 0.0]], [[0.5, 0.5]], [shoulder_local, elbow_local], inverse_binds)
print(np.round(np.degrees([a1, a2]), 2), np.round(world_to_local(arm_base, tip), 4) + 0.0,
np.round(transform_point(elbow, [0.0, 0.0, 0.0]), 3), np.round(skin[0], 3) + 0.0)[11.5 1.5 3.5] [11.1562 0.4688 3.1562] 1.658 [ 2. 2. -1.] [-1.5 0.5 -2. ] [12.4375 5.1875 4.125 ] [[12.667, 3.667, 3.667], [12.5, 6.833, 4.667]] [-20.61 90. ] [2.4 0.7 0. ] [9.723 4.296 3.702] [ 1.93 -0.833 0. ] [ 53.13 -90. ] [2.4 0.7 0. ] [9.32 6.6 4.24] [1.22 1.46 0. ]
Both solutions take the tip to \((2.4, 0.7)\); the output shows, for each one, the angles, the check, the position of the elbow in the world and the vertex of the sleeve. In both poses the blended vertex ends up 0.141 from the elbow, instead of the original 0.2: with the elbow at 90°, linear skinning has shortened the distance once again.
Conclusion
To animate is to evaluate transformations as a function of time. With keyframes, the value at an instant is obtained by interpolating between the two keys that enclose it—lerp for positions, slerp for orientations—and an easing curve such as the smoothstep reparameterizes time so as to start and brake smoothly. The Hermite and Catmull-Rom splines give trajectories that pass through the marked points without corners, and they are the usual cubic Bézier curves written with tangents; the arc-length table lets us travel them at the desired speed, and the tangent orients the object. Articulated objects are animated through their angles: forward kinematics is a product of parent-child matrices, two-bone inverse kinematics comes out of the law of cosines, and linear skinning, \(\mathbf{v}' = \sum w_i M_i B_i^{-1} \mathbf{v}\), makes a mesh follow its skeleton. Procedural formulas and motion capture complete the possible sources. mini3d gains sample_track, smoothstep, ease_in, ease_out, hermite, catmull_rom, catmull_rom_path, arc_length_table, parameter_at_length, forward_kinematics, two_bone_ik and linear_skinning.
With this lesson the engine is complete: it knows how to describe the scene, measure it, orient it, draw it, simulate it and animate it. Only one thing is missing, the most satisfying one: getting it all running at once. In the next and last lesson, "Final Project: a Complete 3D Scene", we will organize mini3d as a module, assemble the entire scene of "Stellar Lighthouse" with its scene graph and write the main loop that updates it, queries it and draws it frame by frame.
