Drawing

Morph targets: a mesh that blends between shapes

A face smiles, an eye blinks, a muscle bulges. A skeleton cannot do this well: these are changes of shape, not turns of bones. A morph target (also called a blend shape or shape key) is the same mesh in another shape. The mesh blends from its base toward each target by a weight. This page explains the deltas, the weights, the normals, how to store and read targets on the GPU, the order with skinning, the bounds and the motion vectors. The last part shows how RASM does it.

In short

  • A target stores one delta per vertex: how far the vertex moves to reach that shape.
  • The posed vertex is v′ = v + Σ wₜ · Δₜ. Weights are usually 0 to 1, but any value works.
  • Weights come from the mesh's rest weights, from a clip's weights channel, or from the application (sliders, lip sync).
  • Normals and tangents have deltas too. Add them, then make the result unit length again.
  • Store the deltas target-major (all vertices of target 0, then target 1, ...). Then the GPU reads a target for many neighbour vertices at once, and skips a target whose weight is 0.
  • Morph first, then skin: the targets are modelled in the bind pose.
  • The bound grows by Σ |wₜ| · rₜ, where rₜ is target t's longest delta.

1A target is a set of deltas

The artist makes each target from the base mesh by moving vertices. Only the change is kept: one delta per vertex. A vertex that the target does not move has a delta of 0.

base v target "thin": the deltas Δ Δ Δ = 0 at the bottom weight 0.5 v + 0.5 · Δ
A target has the same vertices as the base, in the same order. It stores where they go, as deltas from the base.

Several targets add up. Each one moves the vertex along its own delta, scaled by its weight:

v′ = v + w₀ · Δ₀ + w₁ · Δ₁ + … = v + Σ wₜ · Δₜ

v
the vertex in the base shape
Δₜ
target t's delta for this vertex
wₜ
target t's weight, the same for every vertex of the mesh in this frame
w = 0

0: the base

The target has no effect. Its deltas are not even needed.

w = 1

1: the target

The vertex lands exactly where the artist put it.

w = −0.2

Below 0, above 1

Allowed. The shape goes the other way, or past the target: a cartoon squash and stretch.

2Where the weights come from

The deltas are fixed at import. Only the weights change, so a mesh with 50 targets is animated by 50 numbers per frame. They come from three places, and the later one wins:

  1. Rest weights. The file gives the weights of the shape at rest. In glTF, a node's weights, else the mesh's, else 0.
  2. A clip. A channel with the path weights animates all the targets of one node at once.
  3. The application. Sliders in an editor, lip sync from audio, a face tracker: the program sets the weights each frame.

A weights channel keys every target together. Each key holds one value per target. With cubic splines each key holds three groups: the in-tangents of all targets, then the values, then the out-tangents.

LINEAR, STEP: per key, one weight per target w₀ w₁ w₂ w₀ w₁ w₂ key 0 key 1 CUBICSPLINE: per key, in-tangents, values, out-tangents a₀ a₁ a₂ w₀ w₁ w₂ b₀ b₁ b₂ key 0 (key 1 follows) split curve of target 0: keys of w₀ curve of target 1: keys of w₁ curve of target 2: keys of w₂
Split per target, each weight is a curve with its own values and tangents, sampled like a translation: hold for STEP, mix for LINEAR, a Hermite curve for CUBICSPLINE.

3Normals and tangents blend too

When the shape changes, the surface turns, so the light on it must change too. A target can carry deltas for the normal and the tangent as well. They add up the same way. The sum is not unit length any more, so make it unit length again.

Positions only

The ramp keeps the base's normals. It is shaded like flat ground.

Normal deltas, then normalize

n′ = normalize(n + Σ wₜ · ΔNₜ). The tangent the same way; its sign (w) stays.

4Storing the deltas for the GPU

Files often store a target sparse: only the vertices it moves, as a list of indices and values (glTF sparse accessors). On the GPU a dense array is simpler: every vertex has a delta in every target, so the address of a delta is a multiply and an add. The import fills the gaps with 0.

The order of the dense array decides how the GPU reads it. One GPU thread poses one vertex, and 32 or 64 threads run together on neighbour vertices:

vertex-major: [vertex][target] vertex 0 vertex 1 vertex 7 8 threads read target 0 with gaps; the unused target 1 rides along in every cache line target-major: [target][vertex] target 0, vertices 0 to 7 target 1: weight 0, never read target 2, vertices 0 to 7 8 threads read one block of neighbour deltas; a target at weight 0 costs nothing
The address of vertex v in target t, target-major: first + t · vertexCount + v. Before the loop, a group lists the targets whose weight is not 0, once, so every thread loops only over those.

Each delta needs some precision. A normal delta is at most 2 long and the result is normalized, so a half float (16 bits, 11 significant bits) is plenty. A position delta is in the mesh's units, and a half float keeps about 3 digits: 0.03 m of error on a delta of 50 m. So positions stay 32-bit floats.

24 Bone delta: position as 3 floats, normal and tangent as 6 half floats12 + 6 · 2
9.1 · 10⁻⁵largest half-float error of a normal delta in AnimatedMorphCubedeltas up to 0.705 long
1.2 · 10⁻⁵what half-float positions would lose in MorphStressTest, a 4 unit modelit grows with the model's size

5Morph first, then skin

A character often has both: a skeleton for the body and targets for the face. The artist models the targets on the mesh in its bind pose, before any joint moves it. So the targets come first, and skinning moves the result:

v′ = Σ sᵢ · Jᵢ · (v + Σ wₜ · Δₜ)

sᵢ, Jᵢ
the vertex's skin weights and joint matrices (skinning)
wₜ, Δₜ
the morph weights and the vertex's deltas
bulge goes up

Skin, then morph

The delta was modelled for the straight arm. Added after the turn, it points the wrong way.

bulge turns with the arm

Morph, then skin

The delta is added in the bind pose, and the joint turns it with the rest of the vertex.

Like skinning, morphing is best done once per frame, in a compute pass that writes the posed vertices. Every view (the camera and each shadow map) then draws them. Morphing in the vertex shader repeats the loop over the targets in every view.

6Bounds that grow with the weights

Culling needs a sphere that holds the mesh in this frame. The base mesh's sphere is not enough: a target can move vertices out of it. Measuring the posed vertices each frame costs a pass over them before culling. A cheaper bound needs only the weights:

radius = base radius + Σ |wₜ| · rₜ

rₜ
the longest position delta of target t, measured once at import

No vertex moves more than |wₜ| · rₜ by target t, and the moves add up at most to the sum. So the bound is always safe. It is loose when the targets move different vertices: the sum adds their longest moves anyway. With a skeleton, grow each joint's sphere by the same amount before the joint matrix moves it.

Move the weights. The solid circle is the grown bound: it always holds every vertex. Set "tall" and "bump" together to see it get loose; set every weight to 0 to see no target read.

7Motion vectors of morphed vertices

TAA and motion blur need each vertex's place in the frame before. A morphed vertex moves in its object's own space, so the object's matrix of the frame before is not enough. Keep the posed vertices of the frame before too, and read the same vertex there.

When the weights jump (a new clip starts, the application sets new weights out of nowhere), the frame before shows another shape. Then use this frame's vertex for both frames, so the jump makes no long motion vector. Weights that change a little each frame are normal motion.

8Pitfalls

The shape is right, but its lighting is flat
The normal deltas were not added, or the sum was not normalized.
A target moves the wrong vertices
The base mesh's vertices were welded or reordered at import, but the deltas were not. Weld and reorder the deltas with the vertices, and compare deltas too when welding.
A face part disappears at the edge of the screen
The mesh was culled with its base sphere. Grow the bound by the weights.
A smile bulges sideways on a turned head
Skinning ran before morphing. Morph in the bind pose first.
Many targets cost as much at rest as in motion
The loop reads every target. Skip the targets at weight 0, and store the deltas target-major so a skipped target costs no memory traffic.
A large model shakes slightly as it morphs
Position deltas stored as half floats lose precision on big meshes. Keep positions as 32-bit floats.

9In RASM

RASM morphs on the GPU, once per frame, in the same Skin pass that skins. The import puts each primitive's deltas into a morph stream of the geometry pool, target-major. The Animate pass writes every posed entity's weights and grows its bounds. The Skin pass adds the deltas of the targets whose weight is not 0, then applies the joints when the mesh has a skin. Every view draws the posed vertices.

Import, once per mesh targets: POSITION, NORMAL, TANGENT (sparse filled in) morph stream, target-major MorphDelta, 24 B animation pool rest weights · longest deltas CPU: setMorphWeights Morph Weight Override Table 4 B per weight, NaN: not set Animate: a group per entity row 1 weight = override, else clip, else rest weight 2 bound + Σ |wₜ| · rₜ (each joint sphere too) Morph Weight Buffer (slot) 4 B per weight per entity Animated Transform Buffer bounds read by every Cull Skin: x = entity row, y = 64 vertices of one sub-mesh 1 load the weights once; list the targets with w ≠ 0 2 v + Σ wₜ · Δₜ from the morph stream; normalize normal, tangent 3 with a skin: Σ sᵢ · Jᵢ · v (skinning) Skinned Vertex Buffer 64 B per vertex, one per slot every view: camera, cascades, spot maps, cube faces getVertex · getPreviousObjectPosition · getWorldSphere
A posed sub-mesh starts at a multiple of 64 among its entity's skinned vertices, so a group of the Skin pass never mixes two sub-meshes' targets. A mesh with targets and no skin is posed the same way and keeps following its node.

An entity of a morphed mesh plays a clip like any animated entity. To drive the weights from the application, set them each frame; clearMorphWeights gives them back to the clip:

const rasm::MeshHandle face = engine.loadGLTF("models/face.glb");
engine.waitForLoads();
const std::vector<std::string> names = engine.getMorphTargetNames(face);
std::vector<float> weights(names.size(), 0.0f);
for (size_t i = 0; i < names.size(); ++i)
{
    if (names[i] == "Smile")
        weights[i] = smile;
}
engine.setMorphWeights(entity, weights.data(), static_cast<uint32_t>(weights.size()));

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Deltasposition, normal, tangentreadMorphTargets reads each target's POSITION, NORMAL and TANGENT (xyz) through readFloatAccessor, which fills in sparse accessors. A missing or malformed attribute moves nothing. A primitive keeps at most MAX_MORPH_TARGETS (256) targets, and one whose targets move nothing gets none. A primitive with no NORMAL keeps the normals computed for its base shape (B32).
Storagedense, target-majorA MorphDelta of 24 B per vertex and target in the geometry pool's morph stream (EngineConfig::geometryPoolMorphs, 220, 24 MiB). GeometryData::morphOffset (−1 for none) and morphTargetCount find it. MorphStressTest takes 282 KiB: 1504 vertices × 8 targets.
Precisionfloat positions, half normalspackMorphDelta: the position as floats, the normal and the tangent's xyz as half floats, two per uint. The Skin pass decodes the halves with bit math, so the device needs no 16-bit types.
Rest weightsthe node's, else the mesh's, else 0importMorphWeights gives each node that draws a morphed mesh its range of weights in AnimationRaw::morphWeights, with the names of mesh.extras.targetNames (else target N). An entity's weights are those of all such nodes of its mesh, one node after another.
Clipsa weights channelimportAnimations splits a weights sampler into one sampler per target, its value in x, and adds one AnimationPath::WEIGHTS channel per weight. A clip's channel row has three channels per node, then one per weight. STEP, LINEAR and CUBICSPLINE sample as for a translation. Each split sampler keeps its own key times and a 16-byte value per key (P20).
The applicationsets the weightssetMorphWeights writes the morph weight override table through GpuTable::setRow, uploaded in syncGpuScene. The weights it does not set hold a quiet NaN, which the Animate pass compares by its bits, and there the clip's or the rest weight counts.
Where it morphsonce per frame, before skinningThe Skin pass, which also skins. A mesh with targets and no skin gets posed vertices too, and its node stays among the animated nodes, so it still follows that node.
Weight 0skip the targetA group loads its sub-mesh's weights into shared memory, and one thread lists those that are not 0. The threads loop only over that list.
Boundsgrow by Σ |wₜ| · rₜgetMorphRadii at import (the rₜ, in the animation pool), getMorphGrowth in animate.slang. A mesh without a skin gets its geometry's sphere grown; a skinned one grows each joint's sphere before its joint matrix moves it.
Motion vectorsthe posed vertex of the frame beforeAs for skinning: InstanceTransform::skinnedMotion. It is 0 in the frame an entity starts, a play jumps, the first setMorphWeights after none, a clearMorphWeights, or a growth of the buffers. Later setMorphWeights calls are motion.
At restthe rest weightsAn entity of a morphed mesh takes its animation row with its instance rows, like a skinned one (poseAtRest). With no clip, the rest row of channels has none, so every weight is its rest weight.
LODs—The LODs share the vertices, so every LOD is morphed. weldVertices welds two vertices only when their deltas match too, and moves the deltas with them. It compares at most 13 targets: a mesh with more gets no LODs. The simplification ignores the deltas (D29).

The cost, with --bench --crowd 1000 --active K: 1000 MorphStressTest share one mesh of 1504 morphed vertices and 8 targets, and K of the weights are 0.5, the others 0.

0.88 msSkin with every weight at 0: the cost of writing 1.5M posed verticesRTX 3060, 1080p
0.92 mswith 4 of the 8 targets active6.0M deltas read
1.11 mswith all 8 active2000 entities: 1.87 ms at 0, 2.11 ms at 8

A target at weight 0 costs nothing. The crowd shares one mesh, so its 282 KiB of deltas stay in the GPU's L2 cache; many different meshes would read their deltas from memory and cost more per active target.

See also the API reference, skinning, keyframe animation and vertex pulling. examples/14_morph_targets plays MorphStressTest, AnimatedMorphCube and SimpleMorph, drives a cube's weight with a sine, and shows SimpleMorph at its rest weights; --crowd 1000 adds a crowd and --active 2 drives the crowd's weights.

Where it lives in code

WhatWhere
The public types and callsMorphDelta, MAX_MORPH_TARGETS, ObjRaw, SubGLTFRaw in include/rasm/mesh.h; AnimationPath::WEIGHTS, AnimationRaw in include/rasm/animation.h; Renderer::setMorphWeights, clearMorphWeights, getMorphTargetNames in include/rasm/renderer.h; EngineConfig::geometryPoolMorphs, maxMorphWeights in include/rasm/types.h
Import: deltas, weights, namesreadMorphTargets, importMorphWeights, getMorphRadii, packMorphDelta in src/assets/morphImport.cpp; sparse accessors in src/assets/gltfAccessor.cpp; the weights channel in src/assets/animationImport.cpp
The morph streamGeometryPool::upload in src/renderer/geometryPool.cpp; weldVertices in src/assets/meshLod.cpp
Weights, rows, passesRenderer::setMorphWeights, Renderer::writeMorphWeightRows, Renderer::uploadMeshAnimation, buildAnimationPoolData in src/renderer/animation.cpp
The shadersanimateMain, getMorphGrowth in shaders/passes/animate.slang; skinMain in shaders/passes/skin.slang
The GPU structsMorphDelta and GeometryData in shaders/lib/geometryTypes.slang; AnimationFrame, AnimatedEntity, AnimationMeshData in shaders/lib/animationTypes.slang; their C++ mirrors in src/renderer/uberMaterialTypes.h
Teststests/morphTargetsTests.cpp
Keep these true
  • The morph stream is welded and reordered with its vertices, target by target.
  • A posed sub-mesh starts on a multiple of 64 among its entity's skinned vertices: a Skin group holds one sub-mesh's weights.
  • Morph before skin, in the bind pose.
  • A weight's override is a quiet NaN's exact bits when it is not set, never a NaN test, which fast math may drop.
  • The bound uses the longest delta of each target: a new kind of delta that moves positions must be measured into it.

Further reading