@margoengine/animation 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,1054 +1,1173 @@
1
- # Margo Engine Animation
2
-
3
- Import `margoengine/animation` from the `margoengine` package, or `@margoengine/animation` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
-
5
- Optional WebGPU skeletal animation and morph targets, isolated from core and stage.
6
-
7
- ```ts
8
- import {createStage} from 'margoengine';
9
- import {loadGLTF} from 'margoengine/gltf/pbr';
10
- import {Animation} from 'margoengine/animation';
11
- const stage = await createStage('#viewport', {backend:'webgpu',capacity:2048});
12
- const model = await loadGLTF(stage.engine, '/RobotExpressive.glb');
13
- const animation = Animation.attach(model);
14
- animation.play('Walking');
15
- animation.playing = false;
16
- animation.seek(0.5);
17
- animation.destroy();
18
- model.destroy();
19
- stage.dispose();
20
- ```
21
-
22
- `playing`, `time` and `clip` are plain fields. `time` is the seconds into the current clip; while the clip loops (the
23
- default `loop: true`) it wraps at the clip's end, so a scrub bar can show it as is.
24
-
25
- Parses glTF skins, joint hierarchies and inverse bind matrices. Samples STEP, LINEAR (quaternion slerp), and CUBICSPLINE tracks. Animation advances in seconds before the engine updates world matrices. A compute pass blends position/normal/tangent morphs before skinning and writes the vertex draw buffer. Bone matrices use read-only storage buffers, bounded by the GPU's storage limits rather than a fixed bone count.
26
-
27
- Every skinned or morphed primitive of a device, across all its Animations, lives in a few shared storage buffers and deforms in one compute dispatch per buffer page and influence format (100 morphed models with two primitives each: one dispatch, not 200). Copies of one asset primitive (`cloneModel`) share one copy of its bind-pose vertices, morph deltas and skin influences; only the deformed output, weights and bones are per copy, and a copy's output starts as a GPU copy of the bind pose, so a hundred characters upload their vertices once. A primitive's deformed vertices start `primitive.deformedOffset` bytes (a multiple of 256) into `primitive.deformed`; gltf/pbr, shadows, TAA, selection and picking read them there, and a custom reader binds or copies from that offset.
28
-
29
- Use `animation.setMorph(nodeIndex, targetIndex, weight)` for manual expressions. Play a clip by name/index; set `loop:false` for one-shot playback. Up to eight influences per vertex are supported through paired `JOINTS_0`/`WEIGHTS_0` and optional `JOINTS_1`/`WEIGHTS_1`. Higher sets reject explicitly. No blending between clips is included.
30
-
31
- `nodeIndex` is the glTF mesh node with morph targets, which can be a child of an
32
- armature root. Invalid node/target/weight input throws `RangeError` before changing
33
- weights; its diagnostic lists available mesh node indices and target counts.
34
- Find candidates through `model.primitives` (`nodeIndex` and `weights.length`), then
35
- call `setMorph` with a target index below that count. For a named expression, `setMorph(name, weight)` matches glTF
36
- `extras.targetNames` across every mesh node and sets every matching target
37
- atomically. Missing names and invalid weights leave all targets unchanged.
38
- Names exposed by `primitive.targetNames` include the loader's indexed fallback
39
- names when the asset omits names. The indexed overload keeps its precise node
40
- selection and its existing hot path.
41
-
42
- ```ts
43
- import {Engine} from '@margoengine/core';
44
- import {loadGLTF} from '@margoengine/gltf/pbr';
45
- import {Animation} from '@margoengine/animation';
46
- const engine = await Engine.create(document.querySelector('canvas')!);
47
- const model = await loadGLTF(engine, '/robot-expressive.glb');
48
- const animation = Animation.attach(model);
49
- animation.setMorph('Surprised', 0.8);
50
- animation.dispose(); model.dispose(); engine.dispose();
51
- ```
52
-
53
- Clip names preserve the glTF `name`, including an explicit empty string. An absent
54
- name is synthesized as `Animation <i>` with the zero-based glTF animation index,
55
- for example `Animation 0`. `animation.clips` exposes the resulting names; `play(i)`
56
- also selects by the original unchanged glTF index. An unnamed RiggedFigure clip is covered by the contract test.
57
-
58
- Four-influence primitives keep their 32-byte influence records and the arithmetic of the per-primitive shader, bit for bit. An eight-influence primitive uses a 64-byte record and a second, lazily created compute pipeline; both formats can coexist in one model. Weights normalize across all present sets, including assets whose positive weights are entirely in the secondary set. Joint indices accept unsigned 8-bit or 16-bit accessors; weights accept Float32 or normalized unsigned 8-bit/16-bit accessors. Both sets require matching vertex counts, valid palette indices, nonnegative weights, and a positive combined sum.
59
-
60
- Single-clip playback reuses sample buffers, quaternion arrays, palette matrices, and each skin's inverse-bind array (read at joint offsets, no view per joint). Making an Animation reads each channel's morph width from the node grouping, without searching the primitives per channel. The animation hot path allocates no new typed arrays, quaternion copies, or GPU resources. Each frame re-checks the options and morph widths without allocating (the primitives are grouped by node once), each track continues from the key it found last frame instead of searching again (a seek back or a loop wrap searches), and node translations and scales go through `node.position.set` and `node.scale.set`, the same store writes as `setPosition` and `setScale`. The skinned primitives of one node (same joints and inverse binds) share one bone range: their palette is computed, checked, encoded and uploaded once a frame, not once per primitive. An Animation's palettes sit back to back in one array, so when their bone ranges are contiguous (the usual case) one write uploads all of them, and the copy kept to skip unchanged uploads is a second array swapped with the live one, not copied. Device restoration recreates both pipeline variants and the shared buffers. `sampleTrack()` retains its independently owned return value by default; an optional seventh `target: Float32Array` argument lets other consumers reuse their own output storage.
61
-
62
- `createMaterialAnimation(model, {clip?, loop?})` plays a clip's `KHR_animation_pointer` STEP tracks on base-color `KHR_texture_transform` offset and scale (what `@margoengine/exporters` writes from `materialAnimations`): `seek(seconds)` writes the sampled UV transform into every primitive material of the targeted glTF material, and `dispose()` releases its claim on those properties. Given the opt-in `pointers` option, `Animation` also plays those channels, with every other `KHR_animation_pointer` channel it supports (see below); without it, it skips them and counts them in the clip's duration.
63
-
64
- The separate `@margoengine/animator` package adds gameplay states, blend trees, additive masks and foot IK while reusing this pass's palette buffers. `sampleTrack()` is exported for animation consumers (matrix products: `@margoengine/math/mat4`).
65
-
66
- Animation installs an optional `model.prepareDeformation` encoding hook. GPU
67
- picking and explicit CPU snapshots use it to update the same skin/morph output
68
- after a seek, bone edit or weight change without needing a beauty frame. Queries
69
- do not advance playback time. The hook survives device restoration; disposal
70
- removes only the animation instance's own hook. No CPU skinning copy is added to
71
- the playback path.
72
-
73
- Synchronous CPU raycasts (`Raycaster.intersectEngine`, `intersectObjects`, `SceneBVH`
74
- and `RaycastSnapshot` of `@margoengine/bvh`) hit an animated model at its current
75
- pose with no readback: for the ray, `Animation` evaluates the deformation pass's
76
- arithmetic on the CPU (morph targets, then the linear blend of four or eight
77
- joints, positions and normals) from the node matrices and morph weights as they
78
- are at the call. It is redone only when a bone, a morph weight or the bind
79
- vertices changed, and nothing is kept for a model no ray ever asks about; the
80
- first query reads the influences and morph deltas from the asset once (32 or 64
81
- bytes per skinned vertex, 48 bytes per vertex and target). `Skin` and
82
- `GeometryCachePlayer` do the same from their own CPU data. An `Animation` with
83
- a `skinning` mode, or one whose weights a `MorphWeightPlayer` drives, has no CPU
84
- pose: those raycasts throw MargoError `unsupported`, and
85
- `await raycaster.intersectModel(model)` reads the pose back from the GPU.
86
-
87
- ```ts
88
- import {Engine} from '@margoengine/core';
89
- import {loadGLTF} from '@margoengine/gltf/pbr';
90
- import {Animation} from '@margoengine/animation';
91
- import {Raycaster} from '@margoengine/bvh';
92
- const engine = await Engine.create(document.querySelector('canvas')!);
93
-
94
- const hero = await loadGLTF(engine, '/hero.glb');
95
- const animation = Animation.attach(hero);
96
- animation.seek(0.4);
97
- const [hit] = new Raycaster().setFromEngine(engine, 320, 240).intersectObjects(engine, [hero]);
98
- console.log(hit ? hit.distance : 'the ray misses the pose');
99
- ```
100
-
101
- Run the character demo at `/examples/robot-expressive.html` (also `character-animation.html`). RobotExpressive is by Tomás Laulhé with morphs by Don McCurdy (CC0). It is not a Khronos sample.
102
-
103
- The demo leaves facial weights under the sliders' control by removing weight tracks from its clips. Expressions persist while playing, pausing and switching clips. Presets include a neutral reset; playback speed and a reset-view button accompany touch-enabled orbit controls. The studio floor uses the optional shadows and tone-mapping packages.
104
-
105
- After building the packages, run `node --test packages/animation/tests/*.test.js` for influence validation, packed formats, lifecycle, and allocation checks. `node scripts/animation-influences-browser-tests.js` checks real WebGPU deformation against an independent CPU reference, four-influence parity, eight active influences with morphs, a 1,001-joint palette, and device restoration. Its Margo-made [rig fixture](tests/fixtures/README.md) (`scripts/make-rig-fixture.js`) has 273 vertices, 8 joints, two clips, and 247 vertices with secondary skin weights (up to eight influences); it is committed in the repository and not bundled with the package.
106
-
107
- ## Hidden models and shared skeletons
108
-
109
- A scale key of 0 on any axis plays like any other (glTF 2.0 section 3.5.3): pop-in animations that grow a node from
110
- zero work as exported, and CPU poses (`skin.pose`, `bakeVAT`) give a flattened vertex a finite normal.
111
-
112
-
113
- A model whose primitives are all hidden skips its GPU deformation: its clips keep running, its joints keep moving, and its deformed vertices wait at the last pose shown. They catch up in the first frame it shows, before anything draws it. `GPUDynamicBVH` and `readPickingGeometry` on a hidden model read that last pose. A hidden model that `DeformedPoints` draws (`@margoengine/animation/deformed-points`) keeps deforming, because the points read its vertices.
114
-
115
- `skeleton` plays a model on the joints of another model of the same file, so the two can never drift apart. It has no clips of its own, and `@margoengine/lod/auto` uses it for the levels of a skinned model:
116
-
117
- ```ts
118
- import { Animation } from '@margoengine/animation';
119
- import { cloneModel } from '@margoengine/animation/skeleton-utils';
120
- import { loadGLTF } from '@margoengine/gltf/pbr';
121
- import {Engine} from '@margoengine/core';
122
- const engine = await Engine.create(document.querySelector('canvas')!);
123
-
124
- const hero = await loadGLTF(engine, '/hero.glb');
125
- const animation = Animation.attach(hero);
126
- const copy = await cloneModel(hero);
127
- Animation.attach(copy, { skeleton: hero }); // moves with hero, whatever moves hero
128
- animation.play(0);
129
- ```
130
-
131
- A copy is ready to draw when `cloneModel` resolves: it makes its own nodes, uniforms and bind groups up front (three's clone defers that to the first render) and writes the source's node transforms straight into the transform store, with no arrays per node.
132
-
133
- ## Skeletons and skins from raw data
134
-
135
- `Skeleton` and `Skin` rig a mesh from plain arrays, for editors that author bones and weights themselves (no glTF
136
- document needed). Bones live in the skinned mesh's local space; exactly one bone is the root (`parent: -1`).
137
-
138
- ```ts
139
- import {createStage} from 'margoengine';
140
- import {boxGeometry} from 'margoengine/geometry';
141
- import {Material, createMesh} from 'margoengine/materials';
142
- import {Skeleton, Skin} from 'margoengine/animation';
143
- const stage = await createStage('#viewport', {backend: 'webgpu'});
144
- const skeleton = new Skeleton([
145
- {name: 'upper', parent: -1},
146
- {name: 'forearm', parent: 0, translation: [0, 1, 0]},
147
- ]); // inverse bind matrices come from this base pose unless passed as a second argument
148
- const geometry = boxGeometry(1, 2, 1);
149
- const mesh = createMesh(stage.engine, geometry, new Material({color: '#c08060'}));
150
- // Four bone indices and four weights per vertex; weights normalise to sum 1, a zero sum follows the root bone.
151
- const count = geometry.positions.length / 3, joints = new Uint16Array(count * 4), weights = new Float32Array(count * 4);
152
- for (let v = 0; v < count; v++) {
153
- joints[v * 4] = geometry.positions[v * 3 + 1] > 0 ? 1 : 0; // the top half follows the forearm
154
- weights[v * 4] = 1;
155
- }
156
- const skin = Skin.attach(mesh, skeleton, joints, weights); // or new Skin(...) for CPU-only skinning
157
- skeleton.setPose(1, {rotation: [0, 0, Math.SQRT1_2, Math.SQRT1_2]}); // posing; the GPU follows next frame
158
- skeleton.restorePose(1); // Restore Pose; restorePose(1, true) also resets nested bones; restorePose() resets all
159
- skeleton.setBindPose(); // the current pose becomes the base pose, inverse binds recomputed
160
- skin.setInfluences(0, [1, 0, 0, 0], [1, 0, 0, 0]); // weight painting: vertex 0 now follows the forearm
161
- const world = skeleton.worldMatrix(1, mesh.primitives[0].node.matrix); // for drawing and picking bones
162
- const posed = skin.pose(geometry.positions, geometry.normals); // CPU skinning: picking, Export Static Pose (OBJ/DAE)
163
- skin.dispose();
164
- ```
165
-
166
- `Skin.attach` reuses the four-influence compute shader above and swaps the mesh's draw buffer (`primitive.deformed`), so
167
- textures, nearest sampling, vertex colours, shadows and GPU picking follow the pose; the mesh needs one shared vertex
168
- array (any `createMesh` mesh). An unchanged pose dispatches nothing. A pose change uploads 64 bytes per bone;
169
- `setInfluences` costs O(changed vertices) on the CPU, then the next frame uploads 32 bytes per vertex spanning the
170
- changed ones.
171
- Validation rejects bad indices and counts, repeated names, parent cycles and anything but one root (`RangeError` /
172
- `TypeError`). Material meshes do not render through `model.createRenderer(otherDevice)`, so neither does a skin.
173
-
174
- ## Keyframe clips from raw keys
175
-
176
- ```ts
177
- import {createStage} from 'margoengine';
178
- import {loadGLTF} from 'margoengine/gltf/pbr';
179
- import {
180
- Animation,
181
- Skeleton,
182
- applyKeyframeClip,
183
- bakeKeyframeClip,
184
- compileRigidClip,
185
- createKeyframeClip,
186
- sampleKeyframes,
187
- segmentTime,
188
- } from 'margoengine/animation';
189
- const stage = await createStage('#viewport', {backend: 'webgpu'});
190
- const model = await loadGLTF(stage.engine, '/face.glb');
191
- const skeleton = new Skeleton([{name: 'forearm', parent: -1}]);
192
- const exportNodes = new Map([['forearm', 0], ['door', 1]]); // track target -> exporter node index
193
- const elapsed = 1.25; // seconds since the segment started
194
- const wave = createKeyframeClip({name: 'Wave', tracks: [
195
- {target: 'forearm', path: 'rotation', keys: [
196
- {time: 0, value: [0, 0, 0, 1], interpolation: 'easeInOut'}, // shapes the time until the next key
197
- {time: 0.5, value: [0, 0, 0.38268, 0.92388], interpolation: 'discrete'},
198
- {time: 1, value: [0, 0, 0, 1]},
199
- ]},
200
- {target: 'door', path: 'translation', keys: [{time: 0, value: [0, 0, 0]}, {time: 1, value: [2, 0, 0]}]},
201
- ]});
202
- const t = segmentTime(elapsed, wave.duration, {loop: true, timeScale: -1}); // a reversed, looping segment
203
- applyKeyframeClip(wave, skeleton, t); // poses bones named by track targets
204
- const door = sampleKeyframes(wave.tracks[1], t); // any other target: sample it yourself
205
- const baked = bakeKeyframeClip(wave, 30, (target) => exportNodes.get(target)); // exporters AnimationData
206
- ```
207
-
208
- Tracks target a bone (by name) or the caller's node by a stable string id, for translation, rotation, scale and morph
209
- `weights` (one number per morph target in every key, blended per component and never normalised). Each
210
- key carries its own interpolation for the time until the next key: `discrete` (hold, then jump at the next key),
211
- `linear`, `easeIn`, `easeOut` or `easeInOut` (cubic); rotations slerp along the shortest path by the eased factor.
212
- Sampling is a pure function of time, so editing, scrubbing, playback and offline rendering agree at any frame rate.
213
- `bakeKeyframeClip` writes glTF samplers: a track of only discrete keys becomes STEP and one of only linear keys becomes
214
- LINEAR, both at their keys and exact everywhere; other tracks are LINEAR at the keys plus every `1 / fps` second inside
215
- eased segments, exact at those times. Pass the result to `@margoengine/exporters` as an `ExportScene` animation; tracks
216
- whose target `resolve` maps to undefined are left out.
217
-
218
- A track's `blend` picks the arithmetic between keys a and b at eased factor f. The default, `'delta'`, is
219
- `a + (b - a) * f`. `'weighted'` is for saved data that needs a finite, exactly held result: a sample at a key, before
220
- the first, after the last or inside a discrete segment copies the key's value before any arithmetic, and translation
221
- and scale between keys are `(1 - f) * a + f * b`, finite for all finite keys (keys of ±1e308 included, where
222
- `'delta'`'s b - a overflows to NaN). Rotations slerp the same way in both. `'weighted'` reproduces Margo Voxel Studio's
223
- saved vector-track evaluation bit for bit (`tests/keyframes-blend.test.js`).
224
-
225
- Code clips also drive glTF PBR models: pass the model's `Animation` instead of a skeleton. Tracks then name model nodes
226
- (the first node with that name); transform tracks set the node's local transform and `weights` tracks set every morph
227
- weight through `animation.setMorph`, so expressions authored in code play on loaded characters. Pause the model's own
228
- clip (`animation.playing = false`) while a code clip drives it. A `weights` track whose width differs from the node's
229
- morph target count throws `RangeError`; a `Skeleton` skips `weights` tracks. `bakeKeyframeClip` writes `weights`
230
- tracks as glTF `weights` channels, which gltf/pbr and `Animation` play back (`tests/keyframes-weights.test.js` checks
231
- the round trip through `exportGLB`).
232
-
233
- ```ts
234
- const blink = createKeyframeClip({name: 'Blink', tracks: [
235
- {target: 'Face', path: 'weights', keys: [{time: 0, value: [0, 0]}, {time: 0.1, value: [1, 0]}, {time: 0.2, value: [0, 0]}]},
236
- ]});
237
- const animation = Animation.attach(model);
238
- animation.playing = false;
239
- applyKeyframeClip(blink, animation, t); // node 'Face' has two morph targets
240
- ```
241
-
242
- `skin.pose()` runs the GPU pass's maths on the CPU (linear blend of the four bone matrices; normals by the cofactor
243
- matrix, flipped under mirroring scales) and returns Float32 positions and normals in the mesh's space.
244
- `tests/raw-rig-roundtrip.test.js` writes a raw rig and clip with `@margoengine/exporters` `exportGLB` (bones as export
245
- nodes under the mesh node, `skeleton.inverseBindMatrices`, `bakeKeyframeClip`), reads it back through gltf/pbr and
246
- `Animation`, and matches `skin.pose()` within 1e-4 at frame and key times.
247
- `node scripts/animation-skin-browser-tests.js` (real WebGPU, after building the packages) reads back the deformed
248
- buffer of a skinned `createMesh` strip and matches `skin.pose()` positions and normals within 1e-5 after posing, a
249
- ranged `setInfluences` and a device restore, with no validation errors.
250
-
251
- ## Rigid rigs: whole meshes bound to bones
252
-
253
- `compileRigidClip(bones, bindings, keys, {name, duration})` turns keys of meshes rigidly bound to bones into stepped
254
- bone translation and rotation tracks. A key moves its bone by the mesh's offset from its rest pose and rotates it by
255
- the key rotation times the inverse rest rotation; each bone follows the first bound mesh (in binding order) keyed so
256
- far, and holds the last pose until `duration`. Times are seconds; rotations are `[x, y, z, w]`.
257
-
258
- ```ts
259
- const clip = compileRigidClip(
260
- [{id: 'arm', translation: [0.5, 1.5, 0]}],
261
- [{object: 'sword', bone: 'arm', position: [1, 1, 0], rotation: [0, 0, 0, 1]}],
262
- [{object: 'sword', time: 0.5, position: [1, 2, 0], rotation: [0, 0, 0, 1]}],
263
- {duration: 2},
264
- );
265
- applyKeyframeClip(clip, skeleton, t);
266
- ```
267
-
268
- ## Property tracks: any number, vector or colour
269
-
270
- ```ts
271
- import {applyKeyframeClip, bakeKeyframeTrack, createKeyframeClip, sampleKeyframes} from 'margoengine/animation';
272
- const lamp = {intensity: 0, material: {roughness: 1, color: new Float32Array([1, 1, 1, 1])}};
273
- let fov = 60;
274
- const pulse = createKeyframeClip({name: 'Pulse', tracks: [
275
- {target: lamp, property: 'intensity', keys: [{time: 0, value: [0], interpolation: 'easeOut'}, {time: 1, value: [5]}]},
276
- {target: lamp, property: 'material.roughness', keys: [{time: 0, value: [1], interpolation: 'discrete'}, {time: 0.5, value: [0.2]}]},
277
- {target: lamp, property: 'material.color', type: 'color', keys: [{time: 0, value: [1, 0, 0]}, {time: 1, value: [0, 0, 1]}]},
278
- {target: lamp, name: 'fov', get: () => fov, set: (value) => { fov = value[0]; }, keys: [
279
- {time: 0, value: [40], interpolation: 'cubicSpline', outTangent: [30]},
280
- {time: 1, value: [60], inTangent: [0]},
281
- ]},
282
- ]});
283
- applyKeyframeClip(pulse, 0.5); // writes all four properties
284
- const color = sampleKeyframes(pulse.properties![2], 0.25); // [0.75, 0, 0.25]
285
- const baked = bakeKeyframeTrack(pulse.properties![0], 30); // a glTF sampler for one property track
286
- ```
287
-
288
- A track whose `target` is an object drives a property of it instead of a bone or node: name it with a dot path
289
- (`'material.roughness'`, `'intensity'`, `'position'`, `'lights.0.color'`) or pass `set` (and `get`, for
290
- `track.read()`) accessors. Keys hold 1 to 4 numbers; `type` says what they are: `'number'`, `'vector'`, `'color'`
291
- (linear RGB or RGBA, blended per channel in linear space) or `'quaternion'` (normalised, slerped along the shortest
292
- path). They take the same interpolations (`'cubicSpline'` is a glTF CUBICSPLINE segment through the key's
293
- `outTangent` and the next key's `inTangent`, in units per second) and the same `blend` modes as transform tracks.
294
- `createKeyframeClip` resolves each path once into a setter, so playback does no lookups and allocates nothing: a
295
- number property is assigned, a boolean gets `value >= 0.5`, an array or typed array (a materials `Material`'s live
296
- `color`, a clustered light's `color`) is written in place, a getter that returns a fresh array is assigned through its
297
- setter, and an `{x, y, z}` object such as a mesh's `position` is set through its `set(x, y, z)`. A path that does not
298
- resolve throws `RangeError` naming the segment; one that ends on a value it cannot write throws `TypeError`. Engine
299
- objects work the same way: `{target: mesh, property: 'visible'}`, `{target: material, property: 'roughness'}`,
300
- `{target: stage.engine.camera, property: 'fov'}`. Replacing an object along a path later leaves the track driving the
301
- old one: create the clip again. Property tracks land in `clip.properties`; `applyKeyframeClip(clip, time)` writes
302
- them, and `applyKeyframeClip(clip, skeleton, time)` writes them and poses the skeleton. `bakeKeyframeClip` leaves them
303
- out (glTF nodes have no such paths); `AnimationGroup` and `retarget` ignore them.
304
-
305
- ## KHR_animation_pointer playback
306
-
307
- Transmission can start at `0` (or its omitted default) and animate to a positive
308
- factor. Seeking back to `0` restores the opaque path. Volume attenuation and native
309
- capture follow the transition; the source document stays unchanged. The
310
- [self-contained triangle example](../gltf/README.md#animate-an-opaque-material-into-glass)
311
- builds this channel without a downloaded model.
312
-
313
- Volume pointer writes update attenuation and optical depth together. Optical depth
314
- is retained before transmittance underflows, so a thick volume scaled down in the
315
- scene keeps its absorption. Backward seeks recompute those values from the source
316
- volume and the sampled keys.
317
-
318
- ```ts
319
- import {createStage} from 'margoengine';
320
- import {loadGLTF, viewGLTFCamera} from 'margoengine/gltf/pbr';
321
- import {Animation} from 'margoengine/animation';
322
- import {pointerChannels} from 'margoengine/animation/pointer';
323
- const stage = await createStage('#viewport', {backend: 'webgpu'});
324
- const model = await loadGLTF(stage.engine, '/pointer-show.glb');
325
- const animation = Animation.attach(model, {pointers: pointerChannels});
326
- for (const warning of animation.warnings) console.warn(warning); // pointers this player skips
327
- animation.playing = false;
328
- animation.seek(1.5);
329
- viewGLTFCamera(model, 0); // cameras and lights are data: hand them on after each update
330
- ```
331
-
332
- Pointer playback is opt-in, like gltf/pbr's optional decoders: import `pointerChannels` from
333
- `@margoengine/animation/pointer` and pass it as the `pointers` option, so apps whose files have no pointer channels do
334
- not ship it. Without it, `Animation` skips every pointer channel (still counting it in the clip's duration) and lists
335
- it in `animation.warnings` with the fix. With it, `Animation` plays a clip's `KHR_animation_pointer` channels with its
336
- ordinary ones, at the same time, speed and loop, with glTF's STEP, LINEAR and CUBICSPLINE sampling. It drives:
337
-
338
- - nodes: `/nodes/i/translation`, `rotation` (slerp), `scale`, `weights`, `/meshes/i/weights` (every node using the mesh,
339
- unless the node's own weights are animated) and `/nodes/i/extensions/KHR_node_visibility/visible` (STEP, unsigned
340
- byte);
341
- - materials (every primitive material of the glTF material): `pbrMetallicRoughness/baseColorFactor`, `metallicFactor`,
342
- `roughnessFactor`, `emissiveFactor`, `alphaCutoff`, `normalTexture/scale`, `occlusionTexture/strength`,
343
- `KHR_materials_emissive_strength`, `KHR_materials_dispersion`, and with the physical renderer the clearcoat,
344
- transmission, specular, sheen, IOR and volume factors (the transmission tint and volume follow);
345
- - `KHR_texture_transform` `offset`, `scale` and `rotation` on the base, metallic-roughness, normal, occlusion,
346
- emissive, clearcoat, transmission, sheen and specular textures (the map and its uniform rows);
347
- - `KHR_lights_punctual`: `color`, `intensity`, `range`, `spot/innerConeAngle`, `spot/outerConeAngle` on `model.lights`,
348
- so `model.clusteredLights()` and `applyGLTFLights` pick them up;
349
- - cameras: `perspective/yfov`, `aspectRatio`, `znear`, `zfar` and `orthographic/xmag`, `ymag`, `znear`, `zfar` on
350
- `model.cameras`, for `viewGLTFCamera`.
351
-
352
- Values are written to copies the model owns, never to `model.asset.doc`, and bound on the clip's first playback.
353
- Pointers that break the glTF rules throw: malformed or out-of-range indices, properties animations may not change
354
- (`/materials/0/name`), a repeated pointer, a node property animated both by pointer and by an ordinary channel,
355
- accessors of the wrong type or count, booleans that are not STEP unsigned bytes, and an IOR sampler with a key below 1
356
- (`KHR_materials_ior` keeps 0 as a mode set in the file, never an animated value). Valid pointers this player cannot
357
- drive are skipped and listed in `animation.warnings`: other extensions (iridescence, anisotropy and diffuse
358
- transmission factors, unknown extensions), `extras`, `texCoord`, textures of extended materials, properties the file
359
- leaves undefined (a camera without `zfar`, a light without `range`), factors gltf/pbr did not load (physical factors
360
- without the materials decoder, transmission on a material loaded without it), the IOR of a material whose file sets it to
361
- 0 (the extension ignores updates of that mode) and targets no scene node or primitive uses. A cubic IOR spline that dips
362
- below 1 between its keys writes 1.
363
-
364
- ## Behaviour graphs (`@margoengine/animation/interactivity`)
365
-
366
- A glTF file can carry its own behaviour: on a click, play this clip, turn that material green. `GLTFInteractivity` runs the `KHR_interactivity` graph of a loaded model on the engine's frame loop, so the file behaves with no code of the app's. The graph itself lives in [`@margoengine/gltf/interactivity`](../gltf/README.md#behaviour-graphs-in-gltf-interactivity); this entry reaches the engine, and sits in this package because it plays clips and writes the same live properties as `KHR_animation_pointer`.
367
-
368
- ```ts
369
- import {createStage} from 'margoengine';
370
- import {loadGLTF} from 'margoengine/gltf/pbr';
371
- import {GLTFInteractivity} from 'margoengine/animation/interactivity';
372
-
373
- const stage = await createStage('#viewport', {backend: 'webgpu'});
374
- const model = await loadGLTF(stage.engine, '/product.glb');
375
- const behaviour = GLTFInteractivity.attach(model);
376
- if (behaviour.rejected) console.warn(behaviour.rejected);
377
- behaviour.graph?.on('checkout', ({variant}) => console.log(variant));
378
- ```
379
-
380
- | Option | Default | Meaning |
381
- | --- | --- | --- |
382
- | `pointer` | `true` | Turns pointer input on the canvas into select and hover events. Attaches `Picking` of `@margoengine/selection`, an optional peer loaded on first use, unless the engine has a picker. |
383
- | `physics` | none | The `GLTFPhysics` of `@margoengine/gltf/physics`, for `rigid_body/*` operations and trigger events. |
384
- | `shareCamera` | `true` | Reports the viewer's camera to the graph. `false` makes `activeCamera` read as NaN, for a file you do not trust with where the viewer looks. |
385
- | `log` | none | Receives `debug/log` text. |
386
- | `maxActivations` | 1,000,000 | Node activations one step may run before the graph halts. |
387
- | `maxEventsPerTick` | 10,000 | Custom events one tick delivers. |
388
-
389
- A file's clips start only when its graph says so, so do not also play them with `Animation`. A press that moves over 4 CSS pixels is a drag and selects nothing. A click passes through unselectable nodes to what is behind them, and the graph receives the point it hit. `behaviour.notes` lists properties the graph wrote that it can read back but that change nothing on screen. `dispose()` stops the input.
390
-
391
- ## Groups: one clip for many models
392
-
393
- `AnimationGroup` is one clip and one clock for a crowd. Members are glTF PBR models'
394
- `Animation`s playing a glTF clip they all have (by name or index), or, for a code-authored `KeyframeClip`, `Skeleton`s
395
- and `Animation`s whose bones or nodes the tracks name. Each member can run ahead or behind by an offset in seconds.
396
-
397
- ```ts
398
- import {createStage} from 'margoengine';
399
- import {loadGLTF} from 'margoengine/gltf/pbr';
400
- import {Animation, AnimationGroup} from 'margoengine/animation';
401
- const stage = await createStage('#viewport', {backend: 'webgpu'});
402
- const walkers = await Promise.all([0, 1, 2].map(() => loadGLTF(stage.engine, '/RobotExpressive.glb')));
403
- const crowd = new AnimationGroup('Walking', {speed: 1});
404
- const animations = walkers.map((model) => Animation.attach(model));
405
- for (const [i, animation] of animations.entries()) crowd.add(animation, i * 0.37); // offset per walker
406
- const walkerAnimation = animations[0];
407
- stage.engine.use(crowd); // advances in onPreUpdate; or call crowd.update(delta) yourself
408
- crowd.seek(2); crowd.playing = false; crowd.setOffset(walkerAnimation, 0.5); crowd.remove(walkerAnimation);
409
- ```
410
-
411
- Adding an `Animation` pauses its own playback; the group seeks it each frame through its usual sampling path. A glTF
412
- clip loops as each member's own `loop` option says (a negative member time wraps back from the end); code clips take
413
- the group's `loop` option (default true; false holds the first and last frames). Code-clip tracks are bound to bones,
414
- nodes and morph weights once, in `add`, and group playback creates no typed arrays per frame
415
- (`tests/group.test.js` traps the constructors over 120 frames). Each member still deforms on the GPU through its own
416
- `Animation`; the group adds no GPU work.
417
-
418
- ## Sampling (`@margoengine/animation/sampling`)
419
-
420
- `sampleTrack` and `sampleTrackInto` (also on the root) without the deformation pipeline or
421
- gltf/pbr, for code that samples tracks itself (`@margoengine/animator` does).
422
-
423
- ```ts
424
- import {sampleTrack} from 'margoengine/animation/sampling';
425
-
426
- const times = new Float32Array([0, 1]);
427
- const values = new Float32Array([0, 0, 0, 10, 0, 0]); // x, y, z per key
428
- const position = sampleTrack(times, values, 3, 0.5, 'LINEAR'); // Float32Array [5, 0, 0]
429
- ```
430
-
431
- ### Clip markers
432
-
433
- `ClipMarkers` reports the named moments a play position passes: footsteps, hits, sound cues. A marker counts as passed
434
- once the position is at or beyond it, so moving forward from a to b reports markers in (a, b], moving back reports (b, a],
435
- and a loop repeats them every lap (a step longer than the clip reports every lap). `seek` is silent unless you pass
436
- `fire`. `createKeyframeClip` takes `markers` and sorts them onto `clip.markers`.
437
-
438
- ```ts
439
- import {ClipMarkers} from 'margoengine/animation/sampling';
440
- import {createKeyframeClip} from 'margoengine/animation';
441
-
442
- const clip = createKeyframeClip({
443
- tracks: [{target: 'hips', path: 'translation', keys: [{time: 0, value: [0, 0, 0]}, {time: 1, value: [0, 0, 2]}]}],
444
- markers: [{time: 0.25, name: 'footstep'}, {time: 0.75, name: 'footstep'}],
445
- });
446
- const player = new ClipMarkers(clip.markers ?? [], clip.duration); // loops by default
447
- player.advance(0.5).map((m) => m.time); // [0.25]
448
- player.advance(0.5).map((m) => m.time); // [0.75]
449
- player.advance(-0.5).map((m) => m.time); // [0.75] (leaving 0.75 backward)
450
- ```
451
-
452
- ### Clip compression
453
-
454
- `compressTrack` removes keys a track does not need and `quantizeTrack` stores what is left as 16-bit integers. Both keep
455
- the sampling call the same (`dequantizeTrack` gives the Float32 track back), and both report the error you can check:
456
- after `compressTrack(track, tolerance)` every original key time samples within `tolerance` per component
457
- (`result.error` is the measured maximum); quantisation adds at most half a `step` (range / 131070) per component.
458
- `LINEAR` and `STEP` tracks only; rotation tracks take `quaternion: true`. On six KayKit Rig_Medium clips (rotations and
459
- translations, 0.0005 tolerance) the keys went from 4,589 to 3,441 and the bytes from 88,440 to 50,832; a 2 second, 60 fps
460
- walk bob at 1 cm keeps 33 of 121 keys and shrinks from 1,936 to 354 bytes (`tests/clip-tools.test.js`).
461
-
462
- ```ts
463
- import {compressTrack, dequantizeTrack, quantizeTrack, sampleTrack} from 'margoengine/animation/sampling';
464
-
465
- const times = Float32Array.from({length: 61}, (_, i) => i / 30);
466
- const values = Float32Array.from(times, (t) => Math.sin(t * 3));
467
- const track = {times, values, width: 1, interpolation: 'LINEAR' as const};
468
-
469
- const small = compressTrack(track, 0.001); // fewer keys, small.error <= 0.001
470
- const packed = quantizeTrack(small); // packed.data is a Uint16Array
471
- const back = dequantizeTrack(packed);
472
- const x = sampleTrack(back.times, back.values, 1, 0.5, 'LINEAR'); // within 0.001 plus half a step of sin(1.5)
473
- ```
474
-
475
- ## GPU morph weights (`@margoengine/animation/morph-gpu`)
476
-
477
- The deformation pass always blends morph targets on the GPU. `MorphWeightPlayer` moves the rest of the work there too:
478
- a clip's weight tracks upload once, and one compute dispatch per deformation buffer page samples every copy's weights
479
- each frame, so the CPU writes 16 bytes a frame however many faces play.
480
-
481
- ```ts
482
- import {createStage} from 'margoengine';
483
- import {loadGLTF} from 'margoengine/gltf/pbr';
484
- import {Animation} from 'margoengine/animation';
485
- import {MorphWeightPlayer} from 'margoengine/animation/morph-gpu';
486
- import {cloneModel} from 'margoengine/animation/skeleton-utils';
487
- const stage = await createStage('#viewport', {backend: 'webgpu', capacity: 16384});
488
- // Copy this repository's CC0 RobotExpressive asset to the same public URL in your app.
489
- const source = await loadGLTF(stage.engine, '/examples/assets/robot-expressive.glb');
490
- const models = [source, ...(await Promise.all(Array.from({length: 99}, () => cloneModel(source))))];
491
- const talk = MorphWeightPlayer.attach(stage.engine, 'Dance'); // this asset's clip includes weight tracks
492
- for (const [i, model] of models.entries()) {
493
- const animation = Animation.attach(model);
494
- animation.playing = false; // or keep it playing a body clip: only weights are driven here
495
- talk.add(animation, {offset: i * 0.13, speed: 1}); // defaults 0 and 1; add again to change them
496
- }
497
- talk.speed = 0.5; // every copy; talk.time, talk.playing and talk.remove(animation) work as you would expect
498
- talk.dispose();
499
- ```
500
-
501
- A copy samples `time * speed + offset`, with `sampleTrack`'s arithmetic for STEP, LINEAR and CUBICSPLINE. Copies must
502
- share one asset (`cloneModel`), because they share the tracks; a disposed copy leaves by itself. Weights the player
503
- drives are overwritten every frame, so `setMorph` has no effect on them, and `primitive.weights` on the CPU does not
504
- follow them. `scripts/animation-morph-gpu-tests.js` reads the weights back on real WebGPU and matches `sampleTrack`
505
- within 1e-5 on 70 copies, looping and held.
506
-
507
- ## Animation LOD (`@margoengine/animation/lod`)
508
-
509
- `AnimationLOD` updates each character as often as its distance and visibility call for, so a big crowd spends its CPU
510
- on the characters people can see. Time keeps running for every copy, so one that is updated again lands exactly where
511
- it would have been.
512
-
513
- ```ts
514
- import {createStage} from 'margoengine';
515
- import {loadGLTF} from 'margoengine/gltf/pbr';
516
- import {Animation} from 'margoengine/animation';
517
- import {AnimationLOD} from 'margoengine/animation/lod';
518
- import {cloneModel} from 'margoengine/animation/skeleton-utils';
519
- const stage = await createStage('#viewport', {backend: 'webgpu'});
520
- const source = await loadGLTF(stage.engine, '/RobotExpressive.glb');
521
- const models = [source, ...(await Promise.all(Array.from({length: 199}, () => cloneModel(source))))];
522
- const lod = AnimationLOD.attach(stage.engine, {
523
- tiers: [
524
- {distance: 0, interval: 1}, // the default tiers are these three
525
- {distance: 15, interval: 2}, // every second frame from 15 units
526
- {distance: 40, interval: 4, depth: 4}, // every fourth frame, and nodes below level 4 hold
527
- ],
528
- hidden: {distance: 0, interval: 16, depth: 1}, // off screen, at any distance
529
- });
530
- const walkers = models.map((model, i) => {
531
- model.root.setPosition([(i % 20) * 3, 0, -Math.floor(i / 20) * 6]);
532
- return Animation.attach(model).play('Walking');
533
- });
534
- for (const walker of walkers) lod.add(walker, {radius: 1.5}); // the sphere tested against the view; default 2
535
- stage.onTick(() => console.log(lod.stats)); // {updated, skipped, hidden} of the last frame
536
- lod.remove(walkers[0]); // hands a copy back, fully posed, playing as it was
537
- ```
538
-
539
- `add` takes over a copy's playback; its clip, `speed` and `loop` still come from its `Animation`. A copy takes the last
540
- tier whose `distance` it has reached, and copies on one interval take turns, so no frame carries them all. `depth`
541
- counts node levels from the scene roots, so what level 4 means depends on the rig: pick it per character. Weight tracks
542
- always play. Distance and visibility use the root's position from the previous frame.
543
-
544
- ## Clip editing (`@margoengine/animation/clip-utils`)
545
-
546
- `subclip` cuts a time range into a new clip, and `makeAdditive` turns a clip into differences from a reference pose.
547
-
548
- ```ts
549
- import {Skeleton, applyKeyframeClip, createKeyframeClip} from 'margoengine/animation';
550
- import {applyAdditiveClip, makeAdditive, subclip, subclipFrames} from 'margoengine/animation/clip-utils';
551
- const skeleton = new Skeleton([{name: 'hips', parent: -1}, {name: 'head', parent: 0, translation: [0, 1, 0]}]);
552
- const walk = createKeyframeClip({
553
- name: 'Walk',
554
- tracks: [{target: 'hips', path: 'translation', keys: [
555
- {time: 0, value: [0, 0, 0]}, {time: 1, value: [0, 0.1, 1]}, {time: 2, value: [0, 0, 2]},
556
- ]}],
557
- markers: [{time: 0.75, name: 'footstep'}],
558
- });
559
- const nod = createKeyframeClip({
560
- name: 'Nod',
561
- tracks: [{target: 'head', path: 'rotation', keys: [
562
- {time: 0, value: [0, 0, 0, 1]}, {time: 0.5, value: [0.2588, 0, 0, 0.9659]}, {time: 1, value: [0, 0, 0, 1]},
563
- ]}],
564
- });
565
- const stride = subclip(walk, 0.5, 1.5, {name: 'Stride'}); // seconds; starts at 0, markers come along
566
- const opening = subclipFrames(walk, 0, 15); // frames, both included, at 30 per second unless you pass a rate
567
- const additive = makeAdditive(nod); // against the first frame; or {clip: idle, time: 0.5}
568
- const t = 0.25;
569
- applyKeyframeClip(stride, skeleton, t); // pose the base first, every frame
570
- applyAdditiveClip(additive, skeleton, t, 0.5); // then add half of the nod
571
- ```
572
-
573
- A cut plays exactly as the source did: both ends are sampled, keys inside keep their interpolation, and only an eased or
574
- cubic segment the cut passes through becomes short straight keys, 60 per second unless you pass `fps`. Property tracks
575
- stay bound to their targets, and `blend` carries over. `makeAdditive` uses the sums `@margoengine/animator` additive
576
- layers use: translation and weights subtract, scale divides (a zero reference axis gives 1) and rotation is
577
- `inverse(reference) * rotation`. Every key keeps its time and interpolation, so the result is exact between keys too.
578
- `applyAdditiveClip` adds to whatever pose the skeleton holds, so applying it twice adds twice.
579
-
580
- ## Dual quaternion skinning (`@margoengine/animation/dqs`)
581
-
582
- Blended matrices pinch a joint that twists: a forearm turned 170 degrees shrinks to under a tenth of its radius halfway
583
- along. Pass `dualQuaternionSkinning` and the bones blend as rigid motions, so the arm keeps its volume. It is a per
584
- `Animation` choice, made when you create it. The cost is one matrix split per bone per frame on the CPU, and more
585
- arithmetic per vertex on the GPU.
586
-
587
- ```ts
588
- import {createStage} from 'margoengine';
589
- import {loadGLTF} from 'margoengine/gltf/pbr';
590
- import {Animation} from 'margoengine/animation';
591
- import {dualQuaternionSkinning} from 'margoengine/animation/dqs';
592
- const stage = await createStage('#viewport', {backend:'webgpu',capacity:2048});
593
- const model = await loadGLTF(stage.engine, '/RobotExpressive.glb');
594
- const animation = Animation.attach(model, {skinning: dualQuaternionSkinning});
595
- animation.play('Walking');
596
- ```
597
-
598
- Scaled, stretched, sheared and mirrored bones keep working: each bone's matrix splits exactly into a rotation, a
599
- translation and a symmetric stretch, the stretch blends linearly and applies first, then the blended rigid motion. A
600
- vertex held by one bone lands where the matrix puts it. A bone scaled to nothing still encodes, so hiding a part that
601
- way works. Between two bones of different scale the result differs from a linear blend, because the stretch applies
602
- about the mesh origin rather than each joint. Four and eight influences, morph targets under the skin, clones and
603
- models of both kinds in one scene all work; each kind is its own dispatch.
604
-
605
- `encodeDualQuaternions(palette, out?)` turns 16-float bone matrices into 16-float slots (rotation, dual part, stretch),
606
- and `skinDualQuaternion(slots, joints, weights, position, normal?)` is the shader's CPU twin, for tests and CPU picking.
607
- `blendSkinning` is the same dual quaternion skin with a share per vertex: each vertex mixes the linear skin of its bones
608
- with the dual quaternion skin by a number in [0, 1], which is what an FBX `Blend` skin means. The shares come from the
609
- node's glTF `extras.fbxSkinning.blendWeights` (one per vertex of its primitive, written by `@margoengine/fbx/deformers`);
610
- a node without them is all dual quaternion, and a list of the wrong length or a share outside [0, 1] throws. Position,
611
- normal and tangent blend between the two skins. `skinDualQuaternion(slots, joints, weights, position, normal, share)` takes
612
- the share as its sixth argument, and matches the GPU to 7e-6 on a twisted tube (`npm run test:gpu:dqs`).
613
-
614
- ```ts
615
- import {createStage} from 'margoengine';
616
- import {loadGLTF} from 'margoengine/gltf/pbr';
617
- import {Animation} from 'margoengine/animation';
618
- import {blendSkinning} from 'margoengine/animation/dqs';
619
- const stage = await createStage('#viewport', {backend:'webgpu',capacity:2048});
620
- const model = await loadGLTF(stage.engine, '/RobotExpressive.glb'); // an FBX Blend skin: loadFBX with the deformers extension
621
- const animation = Animation.attach(model, {skinning: blendSkinning});
622
- animation.play('Walking');
623
- ```
624
-
625
- Only `Animation` has the option: `Skin` on raw data, `bakeVAT` and the bone-texture crowd stay linear.
626
-
627
- ## Bone-texture crowds (`@margoengine/animation/instanced-skin`)
628
-
629
- A vertex animation texture stores finished vertices, so a crowd member can only play one clip. `bakeBones` stores bone
630
- matrices instead, one row per clip frame, and `SkinnedCrowd` skins each member in the vertex shader: any number of
631
- characters in one draw, and each can blend two clips, with its own offsets and speeds. The CPU does nothing per member
632
- per frame. The texture is also far smaller: three texels per bone per frame, whatever the vertex count.
633
-
634
- ```ts
635
- import {createStage} from 'margoengine';
636
- import {loadGLTF} from 'margoengine/gltf/pbr';
637
- import {Animation} from 'margoengine/animation';
638
- import {SkinnedCrowd, bakeBones} from 'margoengine/animation/instanced-skin';
639
- const stage = await createStage('#viewport', {backend:'webgpu',capacity:2048});
640
- const model = await loadGLTF(stage.engine, '/RobotExpressive.glb');
641
- const bake = bakeBones(new Animation(model), {fps: 30, clips: ['Walking', 'Running']});
642
- model.dispose();
643
-
644
- const crowd = SkinnedCrowd.attach(stage.engine, bake);
645
- for (let i = 0; i < 1000; i++)
646
- crowd.add({
647
- matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, (i % 40) * 2, 0, Math.floor(i / 40) * 2, 1],
648
- clip: 0,
649
- offset: i * 0.13,
650
- blendClip: 1,
651
- blend: (i % 10) / 10, // a jog: part walk, part run
652
- });
653
- crowd.set(0, {blend: 1});
654
- ```
655
-
656
- `bakeBones(animation, {fps = 30, clips})` bakes clips by name or index, all primitives merged in the model root's space,
657
- up to eight influences per vertex; an unskinned part becomes a bone of its own. The animation's clip, time and playing
658
- state are restored. A member takes `VATCrowd`'s `matrix`, `clip`, `offset`, `speed` and `uvTransform`, and adds
659
- `blendClip` (default 0), `blendOffset` (default 0), `blendSpeed` (default 1) and `blend` (0 to 1, default 0, all of the
660
- first clip). Clips mix as matrices, and bones blend linearly. Everything else follows `VATCrowd`: one material, opaque,
661
- `shadows.add(crowd)` and `lighting.add(crowd)`, no CPU culling. One vertex entry draws colour and shadow, its position `@invariant` (WGSL 12.10) as every Margo shadow caster's is, so another program drawing the same surface writes the same depth bit for bit. `poseBones(bake, member, time, out?)` is the shader's CPU
662
- twin, for bounds and picking. `poseBone(bake, member, bone, time, out?)` is the twin for one bone: its skinning matrix as
663
- the 12 numbers of its 3x4 rows, both clips and the blend applied, for what follows a member (a rider on a horse's back,
664
- a rifle in a hand):
665
-
666
- ```ts
667
- import {poseBone} from 'margoengine/animation/instanced-skin';
668
- const bake = {bones: 1, rows: 2, width: 2048, texels: new Float32Array(2048 * 4), vertexCount: 0, vertices: new Float32Array(0),
669
- joints: new Uint32Array(0), weights: new Float32Array(0), indices: new Uint32Array(0), uvs: new Float32Array(0),
670
- clips: [{name: 'still', start: 0, frames: 1, duration: 1, loop: true}]};
671
- for (const row of [0, 1]) bake.texels.set([1, 0, 0, 0, 0, 1, 0, 2, 0, 0, 1, 0], row * 12); // lifted 2 m
672
- const m = poseBone(bake, {clip: 0}, 0, 0.5);
673
- console.log(m[7]); // 2: a point on this bone rides 2 m up
674
- ```
675
-
676
- Morph targets stay at the weights they had when baked; `MorphedCrowd` (next section) gives each member its own.
677
-
678
- ## Morph weights per crowd member (`@margoengine/animation/instanced-morph`)
679
-
680
- `MorphedCrowd` is a `SkinnedCrowd` whose members each carry their own morph weights, set from JavaScript at any time:
681
- one face smiles while the next one frowns, in the same instanced draw. `bakeMorphBones` bakes like `bakeBones` but
682
- leaves the live targets out of the vertices and stores their position and normal offsets in the bone texture, after the
683
- bone rows; each member's weights ride in its instance row, and the vertex shader adds the weighted offsets before it
684
- skins. The CPU does no per-vertex work.
685
-
686
- ```ts
687
- import {createStage} from 'margoengine';
688
- import {loadGLTF} from 'margoengine/gltf/pbr';
689
- import {Animation} from 'margoengine/animation';
690
- import {MorphedCrowd, bakeMorphBones} from 'margoengine/animation/instanced-morph';
691
- const stage = await createStage('#viewport', {backend: 'webgpu', capacity: 2048});
692
- // Copy this repository's CC0 RobotExpressive asset to the same public URL in your app.
693
- const model = await loadGLTF(stage.engine, '/examples/assets/robot-expressive.glb');
694
- const bake = bakeMorphBones(new Animation(model), {fps: 30, clips: ['Walking']});
695
- model.dispose();
696
-
697
- const crowd = MorphedCrowd.attach(stage.engine, bake);
698
- const [first, second] = bake.morphs.names; // the live targets, in weight order
699
- for (let i = 0; i < 100; i++)
700
- crowd.add({
701
- matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, (i % 10) * 2, 0, Math.floor(i / 10) * 2, 1],
702
- offset: i * 0.13,
703
- morphs: [i % 2], // weights in bake.morphs.names order; a short array sets the first ones
704
- });
705
- crowd.setMorph(0, first, 0.5); // one weight of one member, by name or index
706
- crowd.set(1, {morphs: {[second]: 1}}); // by name; the weights not named keep their value
707
- console.log(crowd.getMorph(1, second)); // 1
708
- ```
709
-
710
- `bakeMorphBones(animation, {fps = 30, clips, morphs})` takes `bakeBones`'s options and `morphs`: the targets that stay
711
- live, by name or by index (default: every target of the model). Targets are joined by name across primitives, in
712
- first-seen order, so a face split over three primitives has one weight per expression; an unnamed target is
713
- `'Target <index>'`. A target left out of `morphs` is baked in at the weight it has now, as `bakeBones` bakes it. The
714
- result is a `BoneBake` with `morphs.names` (the live targets), `morphs.weights` (the model's weights when baked: what a
715
- new member starts with), `morphs.vertices` and `morphs.blocks` (where each vertex finds its offsets).
716
-
717
- A member takes everything a `SkinnedCrowd` member does, and `morphs`: an array in `bake.morphs.names` order, or an
718
- object of weights by name. Weights may be any finite number (below 0 and above 1 extrapolate, as glTF allows); a weight
719
- of 0 costs no texture reads. `setMorph(index, target, weight)` and `getMorph(index, target)` set and read one weight. A
720
- weight that is not finite, an unknown target or a member that does not exist throws RangeError and changes nothing.
721
- Changed weights upload with the next frame.
722
-
723
- A bake holds at most 64 live targets (`MORPH_TARGET_LIMIT`): the weights are part of the instance row, four to a
724
- vector, so a member row is 28 floats plus the target count rounded up to 4. Name the targets you animate in `morphs`
725
- when a model has more. Offsets cost two texels (32 bytes) per vertex of each primitive that has the target, and nothing
726
- for primitives without it. Tangent offsets are not carried (the crowd has no tangents). `morphVertices(bake, weights)`
727
- and `poseMorphedBones(bake, member, time)` are the shader's CPU twins, for bounds and picking. Everything else is
728
- `SkinnedCrowd`'s: two clips and a blend per member, one material, `shadows.add(crowd)`, `lighting.add(crowd)`.
729
-
730
- `packages/animation/tests/instanced-morph-browser.mjs` runs the vertex stage's own morph and skin functions from a
731
- compute shader on real WebGPU and on the WebGL2 compatibility layer: 48 members with their own weights, clips and blends
732
- match `poseMorphedBones` within 1e-5 at every vertex, and a member drawn at given weights covers the same pixels as the
733
- model itself at those weights.
734
-
735
- ## Points on a deforming mesh (`@margoengine/animation/deformed-points`)
736
-
737
- `DeformedPoints` draws every vertex of a model as a point where the model's deformer last put it, so a skinned or
738
- morphed triangle mesh shows as a moving cloud of its own vertices. The points are instanced straight from the buffer the
739
- deformation pass wrote: no second skinning pass, no CPU work per vertex, one draw per primitive.
740
-
741
- ```ts
742
- import {createStage} from 'margoengine';
743
- import {loadGLTF} from 'margoengine/gltf/pbr';
744
- import {Animation} from 'margoengine/animation';
745
- import {DeformedPoints} from 'margoengine/animation/deformed-points';
746
- const stage = await createStage('#viewport', {backend: 'webgpu', capacity: 2048});
747
- // Copy this repository's CC0 RobotExpressive asset to the same public URL in your app.
748
- const model = await loadGLTF(stage.engine, '/examples/assets/robot-expressive.glb');
749
- Animation.attach(model).play('Dance');
750
-
751
- const points = DeformedPoints.attach(model, {size: 3, color: '#ffcc00'});
752
- model.root.visible = false; // the points alone; leave it true to draw them over the mesh
753
- points.set({shape: 'round', sizeUnits: 'world', size: 0.02}); // 2 cm discs that shrink with distance
754
- points.opacity = 0.8; // every option is also a live field
755
- ```
756
-
757
- | Option | Default | Meaning |
758
- | --- | --- | --- |
759
- | `size` | `4` | Point diameter: pixels of the view, or world units with `sizeUnits: 'world'`. Finite, 0 or more |
760
- | `sizeUnits` | `'pixels'` | `'pixels'` keeps a constant screen size; `'world'` shrinks with distance |
761
- | `color` | white | `'#rrggbb'`, `'#rgb'` or `0xrrggbb` (sRGB), or a linear `[r, g, b]` array. Change it with `set({color})`; `points.color` reads the linear RGB |
762
- | `opacity` | `1` | 0 to 1. Below 1 the points blend over what is already drawn and still write depth |
763
- | `shape` | `'square'` | `'square'`, or `'round'` (a disc cut from the square, no antialiasing of its own) |
764
- | `vertexColors` | `true` | Multiplies `color` by each vertex's colour (glTF `COLOR_0`; white where the mesh has none) |
765
-
766
- `points.visible` (default `true`) turns the points off and on, `points.count` is the number of points, and
767
- `points.dispose()` (or `using`) frees them; disposing the model disposes its points. `set(options)` checks every value
768
- and changes nothing when one is out of range (RangeError; TypeError for a `vertexColors` that is not a boolean or a
769
- colour that is not one).
770
-
771
- The deformer can be `Animation` (skins and morph targets, any skinning mode), `Skin` on raw data, `MorphWeightPlayer`
772
- or a geometry cache player. A primitive no deformer writes draws its own vertices at its node, so the rigid parts of a
773
- model show too. The points are unlit, depth tested against the scene, and written in the target's own encoding (sRGB on
774
- a display target, linear on an HDR one). They cast no shadows, are not fogged and are not picked. A primitive drawn with
775
- `EXT_mesh_gpu_instancing` shows its points once, at its node. `pointScale(cameraMatrix, size, sizeUnits, width, height)`
776
- is the size maths the shader uses, for tools that need a point's footprint on screen.
777
-
778
- `packages/animation/tests/deformed-points-browser.mjs` draws a skinned strip and a morphed triangle, both hidden, as
779
- points on real WebGPU and on the WebGL2 compatibility layer: every vertex's point is on the pixel its pose projects to
780
- at three clip times and three morph weights, covers its 5 x 5 pixels within 10 percent, and nothing else draws.
781
-
782
- ## Geometry caches (`@margoengine/animation/geometry-cache`)
783
-
784
- Cloth, destruction and fluid simulations from a DCC tool end up as baked vertices, frame by frame. `GeometryCachePlayer`
785
- plays such a file while it downloads. It holds a few chunks at a time, so a long cache never has to fit in memory, and each
786
- chunk carries its own triangles, so a fluid can change vertex count as it plays.
787
-
788
- ```ts
789
- import {createStage} from 'margoengine';
790
- import {GeometryCachePlayer, encodeGeometryCache} from 'margoengine/animation/geometry-cache';
791
- const stage = await createStage('#viewport', {backend:'webgpu',capacity:2048});
792
- // Two frames of one triangle, generated here so no external cache file is needed.
793
- const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1]);
794
- const bytes = encodeGeometryCache(30, [{frameCount: 2, positions, indices: new Uint32Array([0, 1, 2])}]);
795
- const flag = await GeometryCachePlayer.attach(stage.engine, bytes, {ahead: 3});
796
- flag.seek(1 / 60);
797
- flag.speed = 0.5;
798
- ```
799
-
800
- `attach(engine, source, options)` resolves once the first chunk is in. `source` is a URL, a `ReadableStream` or other async
801
- iterable of bytes, one `Uint8Array`, or `(signal) => bytes`. Options: `loop` (default true), `speed` (default 1), `ahead`
802
- (chunks read past the one playing, default 2), `signal`, `material` (a glTF material, default plain white) and
803
- `maxChunkBytes` (default 1 GiB). The player owns `player.model`: move it through `player.model.root`, and dispose the player.
804
-
805
- The clock waits when the stream falls behind, so playback never jumps; `player.stats.stalls` counts the frames it waited.
806
- Between two frames of one mesh the vertices interpolate. A chunk with other triangles or another vertex count swaps the mesh
807
- at its first frame, and the last frame of the chunk before it holds, since there is no mesh to mix towards. A URL, an array
808
- or a function can start over, so played chunks are let go, a seek back reads again and a loop reads the file once a lap, with
809
- the first chunk held so the wrap does not wait; a stream cannot, so it keeps every chunk it read. `player.done` settles when the read ends, which follows the clock by `ahead` chunks, so a paused player may
810
- never get there. A failure rejects it and leaves the last frame up.
811
-
812
- `readGeometryCache(bytes, {signal, maxChunkBytes})` is the same reader without a player, an async iterator of chunks, and
813
- `encodeGeometryCache(rate, chunks)` writes a file, so an exporter is a few lines:
814
-
815
- ```ts
816
- import {encodeGeometryCache, readGeometryCache} from 'margoengine/animation/geometry-cache';
817
-
818
- const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1]);
819
- const file = encodeGeometryCache(30, [{frameCount: 2, positions, indices: new Uint32Array([0, 1, 2])}]);
820
- for await (const chunk of readGeometryCache(file)) console.log(chunk.firstFrame, chunk.vertexCount);
821
- ```
822
-
823
- A cache from a DCC tool is usually a PC2 or MDD file. `parsePointCache` from `@margoengine/animation/point-cache` reads both. They hold vertices and no triangles, so give it the triangles of the mesh it was baked from:
824
-
825
- ```ts
826
- import {encodeGeometryCache} from 'margoengine/animation/geometry-cache';
827
- import {parsePointCache} from 'margoengine/animation/point-cache';
828
-
829
- const bytes = new Uint8Array(await (await fetch('/ball.pc2')).arrayBuffer()); // written by Blender's PC2 add-on
830
- const cache = parsePointCache(bytes, {fps: 24});
831
- // A fan over the points stands in here: use the triangles of the mesh the cache was baked from.
832
- const indices = new Uint32Array(3 * (cache.vertexCount - 2)).map((_, n) => (n % 3 ? Math.floor(n / 3) + (n % 3) : 0));
833
- const file = encodeGeometryCache(cache.rate, [{frameCount: cache.frameCount, positions: cache.positions, indices}]);
834
- ```
835
-
836
- `fps` (default 24) is for PC2, which does not say; an MDD file's own times win. `zUp: true` turns a Z-up file to Y-up as `(x, z, -y)`; Blender's MDD add-on writes Z-up and its PC2 add-on Y-up by default. `maxFloats` (default 2^28) refuses a larger file. A header that asks for more than the file holds is refused as a cut file or no point cache at all, before the limit: MDD has no magic, so any other file reads as an MDD header. Alembic is not read: it has no published file specification to build from. The result fits the player as it is, so the file above goes straight to `GeometryCachePlayer.attach`.
837
-
838
- A meshed fluid, a fracture or any bake that writes one whole mesh a frame is a mesh sequence: the triangles change every
839
- frame. `encodeMeshSequence(rate, frames, {maxChunkFrames})` groups it into chunks for the player, frames with the same
840
- triangles, vertex count, UVs and normals-or-not sharing one (up to `maxChunkFrames`, default the rate rounded, about a
841
- second) and a frame whose topology changes starting the next; a chunk with the triangles or UVs of the one before leaves
842
- them out. `frames` is any iterable or async iterable of `{positions, indices, normals?, uvs?}`, and
843
- `streamMeshSequence` yields the file a chunk at a time (its header then says 0 total frames), so a long bake read file by
844
- file never sits in memory whole. A frame with an index past its vertices, a non-finite position, or normals or UVs of the
845
- wrong size is refused by number. From the command line, `margo-convert sequence <folder>` does the same for a folder of
846
- per-frame OBJ, PLY or STL files (Blender's OBJ export with Animation on, a fluid add-on's mesh export).
847
-
848
- ```ts
849
- import {GeometryCachePlayer, encodeMeshSequence} from 'margoengine/animation/geometry-cache';
850
- import {createStage} from 'margoengine';
851
-
852
- const stage = await createStage('#viewport', {backend: 'webgpu', capacity: 2048});
853
- // A fan whose triangle count grows each frame, as a fluid surface's does.
854
- const fan = (sides: number, z: number) => {
855
- const positions = new Float32Array((sides + 1) * 3), indices: number[] = [];
856
- for (let s = 0; s < sides; s++) {
857
- const a = (s / sides) * Math.PI * 2;
858
- positions.set([Math.cos(a), Math.sin(a), z], (s + 1) * 3);
859
- indices.push(0, s + 1, ((s + 1) % sides) + 1);
860
- }
861
- return {positions, indices: new Uint32Array(indices)};
862
- };
863
- const file = await encodeMeshSequence(24, [fan(6, 0), fan(6, 0.1), fan(9, 0.2), fan(12, 0.3)]);
864
- const water = await GeometryCachePlayer.attach(stage.engine, file);
865
- ```
866
-
867
- The format is little endian. A 16 byte header holds the magic `MGCH`, version 1, frames per second (f32) and the total
868
- frames (0 if unknown). Chunks follow, each a 64 byte header and its payload.
869
-
870
- | Chunk header offset | Field |
871
- | --- | --- |
872
- | 0 | magic `CHNK` |
873
- | 4 | payload bytes |
874
- | 8 | first frame, which must follow the last chunk's end |
875
- | 12 | frame count |
876
- | 16 | vertex count, 3 to 1,000,000 |
877
- | 20 | index count, 0 to repeat the last chunk's triangles |
878
- | 24 | flags: 1 normals stored, 2 UVs stored |
879
- | 32 | bounds over the chunk: min xyz, max xyz (f32) |
880
-
881
- The payload is the indices (u32), then UVs (2 floats a vertex), positions (3 floats a vertex, all frames), then normals
882
- (same shape). A chunk without normals gets smooth ones when it is read; a chunk without UVs repeats the last chunk's if the
883
- vertex count matches, else zero. A damaged or cut off file rejects with a `failed` error, and a bad chunk header is refused
884
- before its payload is held.
885
-
886
- ## Cloning and retargeting (`@margoengine/animation/skeleton-utils`)
887
-
888
- Cloning skinned models and retargeting poses and clips between skeletons, in their own entry:
889
-
890
- ```ts
891
- import {Animation, Skeleton, createKeyframeClip, applyKeyframeClip} from 'margoengine/animation';
892
- import {Retarget, cloneModel, retargetRig} from 'margoengine/animation/skeleton-utils';
893
- import {createStage} from 'margoengine';
894
- import {loadGLTF} from 'margoengine/gltf/pbr';
895
- const stage = await createStage('#viewport', {backend: 'webgpu'});
896
- // Copy this repository's CC0 RobotExpressive asset to the same public URL in your app.
897
- const robot = await loadGLTF(stage.engine, '/examples/assets/robot-expressive.glb');
898
-
899
- const second = await cloneModel(robot); // own nodes and skeleton; shares the parsed asset
900
- Animation.attach(second).play('Dance'); // animates apart from `robot`
901
-
902
- // Explicit miniature rigs make the required names and reference poses reproducible.
903
- const source = new Skeleton([
904
- {name: 'mixamorig:Hips', parent: -1, translation: [0, 1, 0]},
905
- {name: 'mixamorig:Spine', parent: 0, translation: [0, 0.5, 0]},
906
- ]);
907
- const hero = new Skeleton([
908
- {name: 'Hips', parent: -1, translation: [0, 2, 0]},
909
- {name: 'Spine', parent: 0, translation: [0, 1, 0]},
910
- ]);
911
- const retarget = new Retarget(retargetRig(source), retargetRig(hero), {
912
- names: {Hips: 'mixamorig:Hips', Spine: 'mixamorig:Spine'},
913
- hip: 'Hips', // follows the source hips' movement, scaled by the rest hip heights unless hipScale is given
914
- });
915
- source.setPose(0, {translation: [0.3, 1, 0]});
916
- retarget.apply(source, hero); // hero's hips now move 0.6 along x
917
- const sourceClip = createKeyframeClip({name: 'Walk', tracks: [{
918
- target: 'mixamorig:Hips', path: 'translation', keys: [
919
- {time: 0, value: [0, 1, 0]}, {time: 1, value: [1, 1, 0]},
920
- ],
921
- }]});
922
- const walk = retarget.clip(sourceClip, {fps: 30});
923
- applyKeyframeClip(walk, hero, 0.5);
924
- ```
925
-
926
- `cloneModel(model)` resolves to a new `PBRModel` with its own root and nodes, starting in the source's current local
927
- transforms, visibility and morph weights, and registered with the engine when the source is. It shares the source's
928
- parsed asset (document, buffers, accessors), decoded images and packed vertex arrays. Copies share the GPU textures of
929
- those images, the GPU vertex and index buffers of those arrays and, once animated, the deformation inputs (bind-pose
930
- vertices, morph deltas, skin influences), so a clone uploads no geometry and no texture; what it adds on the GPU is its
931
- own deformed output, weights, bones, uniforms and bind groups. Disposing any model, source included, leaves the others
932
- working: each image, texture and buffer goes with its last holder. Materials are rebuilt from the document, so runtime material edits on the source are not copied.
933
-
934
- A copy costs no engine tick, so spawning a crowd does not touch the rest of the scene: it takes the source's baked
935
- static batches instead of baking its own. Its world matrices therefore publish with the next tick. Every frame and
936
- pick runs one first, as do `model.bounds`, `extras()`, `clusteredLights()`, `readPickingGeometry()` and `compile()`, so
937
- only a direct read of `node.matrix` right after `cloneModel` sees the old value, as after any `setPosition`. A source
938
- that was moved since baking, or has a parent, costs its copy one tick to bake for itself.
939
-
940
- `retargetRig(skeletonOrModel)` reads a bone hierarchy and its current local pose, which becomes the rig's rest pose; a
941
- model's rig is every node, so armature and mesh nodes count toward bone orientations. `new Retarget(source, target,
942
- options)` maps target bones to source bones by name (`names` overrides, `''` leaves a bone at rest; unnamed glTF nodes
943
- map only through `names`). Each mapped target bone turns in model space by the rotation its source bone has turned
944
- from rest, which absorbs different bone axes and rest orientations; bones keep their own lengths and scales, unmapped
945
- bones keep their rest local pose, and the `hip` bone's position follows the source hip's movement times `hipScale`.
946
- `pose(sourceLocal, out?)` does this on raw arrays (10 numbers per bone: translation, quaternion, scale) without
947
- allocating, `apply(source, target)` reads and writes Skeletons or models, and `clip(source, {fps, name})` samples a
948
- source `KeyframeClip`, or a glTF clip through the source model's `Animation` (restoring its clip, time and playing
949
- state), into a target `KeyframeClip` with a rotation track per mapped bone and a translation track for the hip. Both
950
- characters' model spaces must face the same way; morph weight tracks are not carried over.
951
- `tests/retarget.test.js` checks analytic poses (bone directions, lengths, scaled hip motion, unmapped bones) across
952
- renamed rigs with different bone axes, and models driven by their `Animation`.
953
-
954
- ### Scene of the result
955
-
956
- `cloneModel` makes the copy in the scene of its source model (the scene the source is registered in), so a clone of a model in a second scene stays beside it, whichever scene is active when you call it. An abort or a failure leaves nothing in either scene.
957
-
958
- ## Mixer: blended actions (`@margoengine/animation/mixer`)
959
-
960
- `AnimationMixer` plays several clips on one root at the same time and blends them per property. The root is a
961
- model, an `Animation`, a `Skeleton`, or a plain object that hosts bound property tracks. `AnimationMixer.attach(engine,
962
- root)` registers the mixer with the engine, so its clock advances in each frame. `new AnimationMixer(root)` builds the
963
- same mixer unregistered, for a caller that drives it with `update(delta)` or `advanceTime(delta)`. Attaching a model
964
- makes an `Animation` for it and pauses that `Animation`, so the mixer alone poses the model. Transform tracks need a
965
- `Skeleton` or `Animation` root; a plain object takes property tracks only (clips from `createKeyframeClip`).
966
-
967
- ```ts
968
- import {createStage} from 'margoengine';
969
- import {loadGLTF} from 'margoengine/gltf/pbr';
970
- import {AnimationMixer} from 'margoengine/animation/mixer';
971
- const stage = await createStage('#viewport', {backend: 'webgpu', capacity: 2048});
972
- const model = await loadGLTF(stage.engine, '/RobotExpressive.glb');
973
- const mixer = AnimationMixer.attach(stage.engine, model);
974
- const idle = mixer.clipAction('Idle').play();
975
- const walk = mixer.clipAction('Walking').play();
976
- idle.crossFadeTo(walk, 0.5); // idle fades out and walking fades in over half a second
977
- walk.setDuration(2); // one walking cycle takes 2 s
978
- mixer.dispose(); // restores the original pose and disposes the Animation the mixer made
979
- model.dispose();
980
- stage.dispose();
981
- ```
982
-
983
- ### Exports
984
-
985
- - `AnimationMixer` (class). `static attach(engine, root)` creates, registers and returns a mixer; disposing it removes
986
- its registration. `time` (default `0`) is the global clock in seconds and `timeScale` (default `1`) its signed rate.
987
- `clipAction(clip, root = the mixer's root, blendMode = NormalAnimationBlendMode)` returns the cached action for that
988
- clip, root and blend mode, creating it once; `clip` is a glTF clip name or index (an `Animation` root), or an
989
- `ActionClip` object. `existingAction(clip, root?)` returns the cached action or `null` and never creates one.
990
- `update(delta)` advances the clocks and blends once; `advanceTime(delta)` moves the clocks without writing a pose;
991
- `setTime(time)` rewinds every action and seeks to `time`; `stopAllAction()` stops every action and restores the
992
- original pose. `uncacheAction(clip, root?)`, `uncacheClip(clip)` and `uncacheRoot(root)` drop cached actions (stop
993
- them first); `uncacheRoot` also disposes the `Animation` the mixer made for that root. `getRoot()` returns the default
994
- root. `dispose()` and `[Symbol.dispose]()` stop everything, restore the originals and dispose only the `Animation`s
995
- the mixer created, never the model. The engine calls `setup(engine)` and `onPreUpdate(delta)`, its plugin hooks.
996
- - `AnimationAction` (class), made by `clipAction`. Options with their defaults: `time` (`0`), `timeScale` (`1`),
997
- `weight` (`1`), `enabled` (`true`), `paused` (`false`), `clampWhenFinished` (`false` disables the action when it ends;
998
- `true` holds its end pose), `loop` (`LoopRepeat`) and `repetitions` (`Infinity`). `blendMode` is
999
- read-only and set at creation. Methods: `play()` starts or resumes without resetting the clock; `stop()` stops, restores
1000
- the original pose on the next update and rewinds; `reset()` rewinds and clears envelopes; `startAt(time)` delays the
1001
- start to a mixer time; `isScheduled()` reports whether `play()` was called and not stopped, and `isRunning()` also needs it enabled, at a non-zero rate and past its `startAt` time; `getClip()`,
1002
- `getMixer()`, `getRoot()`, `getEffectiveWeight()` and `getEffectiveTimeScale()` read it back;
1003
- `setEffectiveWeight(weight)` sets the weight and cancels a fade, `setEffectiveTimeScale(scale)` sets the rate and cancels a warp;
1004
- `setDuration(seconds)` sets the time scale so one pass takes `seconds` (positive); `syncWith(action)` copies another
1005
- action's clock and rate; `setLoop(mode, repetitions = Infinity)` takes `LoopOnce`, `LoopRepeat` or `LoopPingPong` and a
1006
- count of at least 1; `fadeIn(duration)` and `fadeOut(duration)` ramp the weight from 0 to 1 or 1 to 0 (`fadeIn` does
1007
- not start the action: call `play()`); `stopFading()` cancels a fade; `warp(from, to, duration)` ramps the rate from
1008
- `from` to `to` over `duration` seconds; `halt(duration)` slows the rate to 0 over `duration`; `stopWarping()` cancels
1009
- a warp; `crossFadeTo(action, duration, warp = false)` fades this action out and `action` in, and `crossFadeFrom(action,
1010
- duration, warp = false)` does the same from the other side. `warp` matches the two cycle rates during the fade (both
1011
- clips need a positive duration). `step`, `contribute`, `uses`, `usesDiscrete` and `rewind` are the mixer's own
1012
- per-frame hooks; app code does not call them.
1013
- - `LoopOnce` (`2200`): play once, clamped at the end. `LoopRepeat` (`2201`): repeat from the opposite end. This is the
1014
- default. `LoopPingPong` (`2202`): alternate forward and backward passes.
1015
- - `NormalAnimationBlendMode` (`2500`): weighted replacement, with the original pose filling the weight below one. This
1016
- is the default. `AdditiveAnimationBlendMode` (`2501`): adds translation and property deltas, multiplies scale deltas
1017
- and composes rotation deltas. Categorical (boolean or string) tracks have no additive arithmetic and throw with it.
1018
- - Types: `ActionLoop` (the three loop constants), `ActionClip` (a glTF clip, a `KeyframeClip` or a discrete clip) and
1019
- `MixerRoot` (`object`).
1020
-
1021
- Blending normalises by the total weight of the actions that touch a property, so two full-weight actions average, and a
1022
- property that no action touches returns to its original value.
1023
-
1024
- ## Film time: seeking animation to a cut
1025
-
1026
- `Animation`, `PlaybackAnimation`, `AnimationGroup`, `AnimationMixer`, `AnimationLOD`, `MorphWeightPlayer`, `VATCrowd`
1027
- and `GeometryCachePlayer` have `advanceTime(delta)`, the CPU part of their frame update, and a `time` that reads 0 on a
1028
- fresh clock. A replayed step moves the clip clock (loops, ends, fades, warps, start times, LOD turns) and poses nothing;
1029
- the next frame update poses the place reached. So `seek` from `@margoengine/cutscene/seek` lands a fresh scene on the
1030
- pose a continuous run shows there, bit for bit to 54,000 steps (`tests/seek.test.js`, `tests/geometry-cache.test.js`).
1031
- A replayed `PlaybackAnimation` sends no `loop` or `finished` event (a replayed end still settles `finished`).
1032
- `AnimationLOD` gives the same turns when the camera is where the continuous run had it. `GeometryCachePlayer` waits for a
1033
- chunk it does not hold only in a live update, so seek a cache whose file is held in memory (`await player.done`).
1034
- Behaviour graphs (`interactivity`) have no `advanceTime`: they fire listeners and random nodes, so `seek` lists them in
1035
- `unseekable` and they start at the cut.
1036
-
1037
- ```ts
1038
- import {createStage} from 'margoengine';
1039
- import {loadGLTF} from 'margoengine/gltf/pbr';
1040
- import {Animation} from 'margoengine/animation';
1041
- import {seek} from 'margoengine/cutscene/seek';
1042
- const stage = await createStage('#viewport', {backend: 'webgpu'});
1043
- const hero = await loadGLTF(stage.engine, '/hero.glb');
1044
- const walk = Animation.attach(hero, {speed: 1.2});
1045
- // The scene starts 95 s into the film: replay the clocks, then the first frame poses what a continuous run poses there.
1046
- const {clocks, unseekable} = await seek(stage.engine, 95, {fps: 60});
1047
- console.log(walk.time, clocks, unseekable);
1048
- ```
1049
-
1050
- ## Preview tier contract
1051
-
1052
- The small `@margoengine/webgl2-compat/preview` renderer reports `backend: 'webgl2'` and has no GPU device. GPU-only attachments throw a linked `MargoError` with code `unsupported` before allocating resources. Native WebGPU and the full WebGL2 compatibility layer both report `backend: 'webgpu'`. Use [`autoEngine` with `loadCompat`](../webgl2-compat/README.md#automatic-escalation) during scene setup to select a complete tier automatically.
1053
-
1054
- This includes `VATCrowd` (and its crowd subclasses) and `MorphWeightPlayer`.
1
+ # Margo Engine Animation
2
+
3
+ Import `margoengine/animation` from the `margoengine` package, or `@margoengine/animation` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ Optional WebGPU skeletal animation and morph targets, isolated from core and stage.
6
+
7
+ ```ts
8
+ import {createStage} from 'margoengine';
9
+ import {loadGLTF} from 'margoengine/gltf/pbr';
10
+ import {Animation} from 'margoengine/animation';
11
+ const stage = await createStage('#viewport', {backend:'webgpu',capacity:2048});
12
+ const model = await loadGLTF(stage.engine, '/RobotExpressive.glb');
13
+ const animation = Animation.attach(model);
14
+ animation.play('Walking');
15
+ animation.playing = false;
16
+ animation.seek(0.5);
17
+ animation.destroy();
18
+ model.destroy();
19
+ stage.dispose();
20
+ ```
21
+
22
+ `playing`, `time` and `clip` are plain fields. `time` is the seconds into the current clip; while the clip loops (the
23
+ default `loop: true`) it wraps at the clip's end, so a scrub bar can show it as is.
24
+
25
+ Parses glTF skins, joint hierarchies and inverse bind matrices. Samples STEP, LINEAR (quaternion slerp), and CUBICSPLINE tracks. Animation advances in seconds before the engine updates world matrices. A compute pass blends position/normal/tangent morphs before skinning and writes the vertex draw buffer. Bone matrices use read-only storage buffers, bounded by the GPU's storage limits rather than a fixed bone count.
26
+
27
+ Every skinned or morphed primitive of a device, across all its Animations, lives in a few shared storage buffers and deforms in one compute dispatch per buffer page and influence format (100 morphed models with two primitives each: one dispatch, not 200). Copies of one asset primitive (`cloneModel`) share one copy of its bind-pose vertices, morph deltas and skin influences; only the deformed output, weights and bones are per copy, and a copy's output starts as a GPU copy of the bind pose, so a hundred characters upload their vertices once. A primitive's deformed vertices start `primitive.deformedOffset` bytes (a multiple of 256) into `primitive.deformed`; gltf/pbr, shadows, TAA, selection and picking read them there, and a custom reader binds or copies from that offset.
28
+
29
+ Use `animation.setMorph(nodeIndex, targetIndex, weight)` for manual expressions. Play a clip by name/index; set `loop:false` for one-shot playback. Up to eight influences per vertex are supported through paired `JOINTS_0`/`WEIGHTS_0` and optional `JOINTS_1`/`WEIGHTS_1`. Higher sets reject explicitly. No blending between clips is included.
30
+
31
+ `nodeIndex` is the glTF mesh node with morph targets, which can be a child of an
32
+ armature root. Invalid node/target/weight input throws `RangeError` before changing
33
+ weights; its diagnostic lists available mesh node indices and target counts.
34
+ Find candidates through `model.primitives` (`nodeIndex` and `weights.length`), then
35
+ call `setMorph` with a target index below that count. For a named expression, `setMorph(name, weight)` matches glTF
36
+ `extras.targetNames` across every mesh node and sets every matching target
37
+ atomically. Missing names and invalid weights leave all targets unchanged.
38
+ Names exposed by `primitive.targetNames` include the loader's indexed fallback
39
+ names when the asset omits names. The indexed overload keeps its precise node
40
+ selection and its existing hot path.
41
+
42
+ ```ts
43
+ import {Engine} from '@margoengine/core';
44
+ import {loadGLTF} from '@margoengine/gltf/pbr';
45
+ import {Animation} from '@margoengine/animation';
46
+ const engine = await Engine.create(document.querySelector('canvas')!);
47
+ const model = await loadGLTF(engine, '/robot-expressive.glb');
48
+ const animation = Animation.attach(model);
49
+ animation.setMorph('Surprised', 0.8);
50
+ animation.dispose(); model.dispose(); engine.dispose();
51
+ ```
52
+
53
+ Clip names preserve the glTF `name`, including an explicit empty string. An absent
54
+ name is synthesized as `Animation <i>` with the zero-based glTF animation index,
55
+ for example `Animation 0`. `animation.clips` exposes the resulting names; `play(i)`
56
+ also selects by the original unchanged glTF index. An unnamed RiggedFigure clip is covered by the contract test.
57
+
58
+ Four-influence primitives keep their 32-byte influence records and the arithmetic of the per-primitive shader, bit for bit. An eight-influence primitive uses a 64-byte record and a second, lazily created compute pipeline; both formats can coexist in one model. Weights normalize across all present sets, including assets whose positive weights are entirely in the secondary set. Joint indices accept unsigned 8-bit or 16-bit accessors; weights accept Float32 or normalized unsigned 8-bit/16-bit accessors. Both sets require matching vertex counts, valid palette indices, nonnegative weights, and a positive combined sum.
59
+
60
+ Single-clip playback reuses sample buffers, quaternion arrays, palette matrices, and each skin's inverse-bind array (read at joint offsets, no view per joint). Making an Animation reads each channel's morph width from the node grouping, without searching the primitives per channel. The animation hot path allocates no new typed arrays, quaternion copies, or GPU resources. Each frame re-checks the options and morph widths without allocating (the primitives are grouped by node once), each track continues from the key it found last frame instead of searching again (a seek back or a loop wrap searches), and node translations and scales go through `node.position.set` and `node.scale.set`, the same store writes as `setPosition` and `setScale`. The skinned primitives of one node (same joints and inverse binds) share one bone range: their palette is computed, checked, encoded and uploaded once a frame, not once per primitive. An Animation's palettes sit back to back in one array, so when their bone ranges are contiguous (the usual case) one write uploads all of them, and the copy kept to skip unchanged uploads is a second array swapped with the live one, not copied. Device restoration recreates both pipeline variants and the shared buffers. `sampleTrack()` retains its independently owned return value by default; an optional seventh `target: Float32Array` argument lets other consumers reuse their own output storage.
61
+
62
+ `createMaterialAnimation(model, {clip?, loop?})` plays a clip's `KHR_animation_pointer` STEP tracks on base-color `KHR_texture_transform` offset and scale (what `@margoengine/exporters` writes from `materialAnimations`): `seek(seconds)` writes the sampled UV transform into every primitive material of the targeted glTF material, and `dispose()` releases its claim on those properties. Given the opt-in `pointers` option, `Animation` also plays those channels, with every other `KHR_animation_pointer` channel it supports (see below); without it, it skips them and counts them in the clip's duration.
63
+
64
+ The separate `@margoengine/animator` package adds gameplay states, blend trees, additive masks and foot IK while reusing this pass's palette buffers. `sampleTrack()` is exported for animation consumers (matrix products: `@margoengine/math/mat4`).
65
+
66
+ Animation installs an optional `model.prepareDeformation` encoding hook. GPU
67
+ picking and explicit CPU snapshots use it to update the same skin/morph output
68
+ after a seek, bone edit or weight change without needing a beauty frame. Queries
69
+ do not advance playback time. The hook survives device restoration; disposal
70
+ removes only the animation instance's own hook. No CPU skinning copy is added to
71
+ the playback path.
72
+
73
+ Synchronous CPU raycasts (`Raycaster.intersectEngine`, `intersectObjects`, `SceneBVH`
74
+ and `RaycastSnapshot` of `@margoengine/bvh`) hit an animated model at its current
75
+ pose with no readback: for the ray, `Animation` evaluates the deformation pass's
76
+ arithmetic on the CPU (morph targets, then the linear blend of four or eight
77
+ joints, positions and normals) from the node matrices and morph weights as they
78
+ are at the call. It is redone only when a bone, a morph weight or the bind
79
+ vertices changed, and nothing is kept for a model no ray ever asks about; the
80
+ first query reads the influences and morph deltas from the asset once (32 or 64
81
+ bytes per skinned vertex, 48 bytes per vertex and target). `Skin` and
82
+ `GeometryCachePlayer` do the same from their own CPU data, and so does a
83
+ `MorphWeightPlayer` for the weights it drives (its shader's sampling on the CPU,
84
+ at the copy's time). An `Animation` with `dualQuaternionSkinning` or
85
+ `blendSkinning` is posed by the mode's `blend`, the shader's steps on the CPU. A
86
+ `skinning` mode of your own without a `blend` has no CPU pose: those raycasts
87
+ throw MargoError `unsupported`, and `await raycaster.intersectModel(model)`
88
+ reads the pose back from the GPU.
89
+
90
+ ```ts
91
+ import {Engine} from '@margoengine/core';
92
+ import {loadGLTF} from '@margoengine/gltf/pbr';
93
+ import {Animation} from '@margoengine/animation';
94
+ import {Raycaster} from '@margoengine/bvh';
95
+ const engine = await Engine.create(document.querySelector('canvas')!);
96
+
97
+ const hero = await loadGLTF(engine, '/hero.glb');
98
+ const animation = Animation.attach(hero);
99
+ animation.seek(0.4);
100
+ const [hit] = new Raycaster().setFromEngine(engine, 320, 240).intersectObjects(engine, [hero]);
101
+ console.log(hit ? hit.distance : 'the ray misses the pose');
102
+ ```
103
+
104
+ Run the character demo at `/examples/robot-expressive.html` (also `character-animation.html`). RobotExpressive is by Tomás Laulhé with morphs by Don McCurdy (CC0). It is not a Khronos sample.
105
+
106
+ The demo leaves facial weights under the sliders' control by removing weight tracks from its clips. Expressions persist while playing, pausing and switching clips. Presets include a neutral reset; playback speed and a reset-view button accompany touch-enabled orbit controls. The studio floor uses the optional shadows and tone-mapping packages.
107
+
108
+ After building the packages, run `node --test packages/animation/tests/*.test.js` for influence validation, packed formats, lifecycle, and allocation checks. `node scripts/animation-influences-browser-tests.js` checks real WebGPU deformation against an independent CPU reference, four-influence parity, eight active influences with morphs, a 1,001-joint palette, and device restoration. Its Margo-made [rig fixture](tests/fixtures/README.md) (`scripts/make-rig-fixture.js`) has 273 vertices, 8 joints, two clips, and 247 vertices with secondary skin weights (up to eight influences); it is committed in the repository and not bundled with the package.
109
+
110
+ ## Hidden models and shared skeletons
111
+
112
+ A scale key of 0 on any axis plays like any other (glTF 2.0 section 3.5.3): pop-in animations that grow a node from
113
+ zero work as exported, and CPU poses (`skin.pose`, `bakeVAT`) give a flattened vertex a finite normal.
114
+
115
+
116
+ A model whose primitives are all hidden skips its GPU deformation: its clips keep running, its joints keep moving, and its deformed vertices wait at the last pose shown. They catch up in the first frame it shows, before anything draws it. `GPUDynamicBVH` and `readPickingGeometry` on a hidden model read that last pose. A hidden model that `DeformedPoints` draws (`@margoengine/animation/deformed-points`) keeps deforming, because the points read its vertices.
117
+
118
+ `skeleton` plays a model on the joints of another model of the same file, so the two can never drift apart. It has no clips of its own, and `@margoengine/lod/auto` uses it for the levels of a skinned model:
119
+
120
+ ```ts
121
+ import { Animation } from '@margoengine/animation';
122
+ import { cloneModel } from '@margoengine/animation/skeleton-utils';
123
+ import { loadGLTF } from '@margoengine/gltf/pbr';
124
+ import {Engine} from '@margoengine/core';
125
+ const engine = await Engine.create(document.querySelector('canvas')!);
126
+
127
+ const hero = await loadGLTF(engine, '/hero.glb');
128
+ const animation = Animation.attach(hero);
129
+ const copy = await cloneModel(hero);
130
+ Animation.attach(copy, { skeleton: hero }); // moves with hero, whatever moves hero
131
+ animation.play(0);
132
+ ```
133
+
134
+ A copy is ready to draw when `cloneModel` resolves: it makes its own nodes, uniforms and bind groups up front (three's clone defers that to the first render) and writes the source's node transforms straight into the transform store, with no arrays per node.
135
+
136
+ ## Skeletons and skins from raw data
137
+
138
+ `Skeleton` and `Skin` rig a mesh from plain arrays, for editors that author bones and weights themselves (no glTF
139
+ document needed). Bones live in the skinned mesh's local space; exactly one bone is the root (`parent: -1`).
140
+
141
+ ```ts
142
+ import {createStage} from 'margoengine';
143
+ import {boxGeometry} from 'margoengine/geometry';
144
+ import {Material, createMesh} from 'margoengine/materials';
145
+ import {Skeleton, Skin} from 'margoengine/animation';
146
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
147
+ const skeleton = new Skeleton([
148
+ {name: 'upper', parent: -1},
149
+ {name: 'forearm', parent: 0, translation: [0, 1, 0]},
150
+ ]); // inverse bind matrices come from this base pose unless passed as a second argument
151
+ const geometry = boxGeometry(1, 2, 1);
152
+ const mesh = createMesh(stage.engine, geometry, new Material({color: '#c08060'}));
153
+ // Four bone indices and four weights per vertex; weights normalise to sum 1, a zero sum follows the root bone.
154
+ const count = geometry.positions.length / 3, joints = new Uint16Array(count * 4), weights = new Float32Array(count * 4);
155
+ for (let v = 0; v < count; v++) {
156
+ joints[v * 4] = geometry.positions[v * 3 + 1] > 0 ? 1 : 0; // the top half follows the forearm
157
+ weights[v * 4] = 1;
158
+ }
159
+ const skin = Skin.attach(mesh, skeleton, joints, weights); // or new Skin(...) for CPU-only skinning
160
+ skeleton.setPose(1, {rotation: [0, 0, Math.SQRT1_2, Math.SQRT1_2]}); // posing; the GPU follows next frame
161
+ skeleton.restorePose(1); // Restore Pose; restorePose(1, true) also resets nested bones; restorePose() resets all
162
+ skeleton.setBindPose(); // the current pose becomes the base pose, inverse binds recomputed
163
+ skin.setInfluences(0, [1, 0, 0, 0], [1, 0, 0, 0]); // weight painting: vertex 0 now follows the forearm
164
+ const world = skeleton.worldMatrix(1, mesh.primitives[0].node.matrix); // for drawing and picking bones
165
+ const posed = skin.pose(geometry.positions, geometry.normals); // CPU skinning: picking, Export Static Pose (OBJ/DAE)
166
+ skin.dispose();
167
+ ```
168
+
169
+ `Skin.attach` reuses the four-influence compute shader above and swaps the mesh's draw buffer (`primitive.deformed`), so
170
+ textures, nearest sampling, vertex colours, shadows and GPU picking follow the pose; the mesh needs one shared vertex
171
+ array (any `createMesh` mesh). An unchanged pose dispatches nothing. A pose change uploads 64 bytes per bone;
172
+ `setInfluences` costs O(changed vertices) on the CPU, then the next frame uploads 32 bytes per vertex spanning the
173
+ changed ones.
174
+ Validation rejects bad indices and counts, repeated names, parent cycles and anything but one root (`RangeError` /
175
+ `TypeError`). Material meshes do not render through `model.createRenderer(otherDevice)`, so neither does a skin.
176
+
177
+ ## Keyframe clips from raw keys
178
+
179
+ ```ts
180
+ import {createStage} from 'margoengine';
181
+ import {loadGLTF} from 'margoengine/gltf/pbr';
182
+ import {
183
+ Animation,
184
+ Skeleton,
185
+ applyKeyframeClip,
186
+ bakeKeyframeClip,
187
+ compileRigidClip,
188
+ createKeyframeClip,
189
+ sampleKeyframes,
190
+ segmentTime,
191
+ } from 'margoengine/animation';
192
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
193
+ const model = await loadGLTF(stage.engine, '/face.glb');
194
+ const skeleton = new Skeleton([{name: 'forearm', parent: -1}]);
195
+ const exportNodes = new Map([['forearm', 0], ['door', 1]]); // track target -> exporter node index
196
+ const elapsed = 1.25; // seconds since the segment started
197
+ const wave = createKeyframeClip({name: 'Wave', tracks: [
198
+ {target: 'forearm', path: 'rotation', keys: [
199
+ {time: 0, value: [0, 0, 0, 1], interpolation: 'easeInOut'}, // shapes the time until the next key
200
+ {time: 0.5, value: [0, 0, 0.38268, 0.92388], interpolation: 'discrete'},
201
+ {time: 1, value: [0, 0, 0, 1]},
202
+ ]},
203
+ {target: 'door', path: 'translation', keys: [{time: 0, value: [0, 0, 0]}, {time: 1, value: [2, 0, 0]}]},
204
+ ]});
205
+ const t = segmentTime(elapsed, wave.duration, {loop: true, timeScale: -1}); // a reversed, looping segment
206
+ applyKeyframeClip(wave, skeleton, t); // poses bones named by track targets
207
+ const door = sampleKeyframes(wave.tracks[1], t); // any other target: sample it yourself
208
+ const baked = bakeKeyframeClip(wave, 30, (target) => exportNodes.get(target)); // exporters AnimationData
209
+ ```
210
+
211
+ Tracks target a bone (by name) or the caller's node by a stable string id, for translation, rotation, scale and morph
212
+ `weights` (one number per morph target in every key, blended per component and never normalised). Each
213
+ key carries its own interpolation for the time until the next key: `discrete` (hold, then jump at the next key),
214
+ `linear`, `easeIn`, `easeOut` or `easeInOut` (cubic); rotations slerp along the shortest path by the eased factor.
215
+ Sampling is a pure function of time, so editing, scrubbing, playback and offline rendering agree at any frame rate.
216
+ `bakeKeyframeClip` writes glTF samplers: a track of only discrete keys becomes STEP and one of only linear keys becomes
217
+ LINEAR, both at their keys and exact everywhere; other tracks are LINEAR at the keys plus every `1 / fps` second inside
218
+ eased segments, exact at those times. Pass the result to `@margoengine/exporters` as an `ExportScene` animation; tracks
219
+ whose target `resolve` maps to undefined are left out.
220
+
221
+ A track's `blend` picks the arithmetic between keys a and b at eased factor f. The default, `'delta'`, is
222
+ `a + (b - a) * f`. `'weighted'` is for saved data that needs a finite, exactly held result: a sample at a key, before
223
+ the first, after the last or inside a discrete segment copies the key's value before any arithmetic, and translation
224
+ and scale between keys are `(1 - f) * a + f * b`, finite for all finite keys (keys of ±1e308 included, where
225
+ `'delta'`'s b - a overflows to NaN). Rotations slerp the same way in both. `'weighted'` reproduces Margo Voxel Studio's
226
+ saved vector-track evaluation bit for bit (`tests/keyframes-blend.test.js`).
227
+
228
+ Code clips also drive glTF PBR models: pass the model's `Animation` instead of a skeleton. Tracks then name model nodes
229
+ (the first node with that name); transform tracks set the node's local transform and `weights` tracks set every morph
230
+ weight through `animation.setMorph`, so expressions authored in code play on loaded characters. Pause the model's own
231
+ clip (`animation.playing = false`) while a code clip drives it. A `weights` track whose width differs from the node's
232
+ morph target count throws `RangeError`; a `Skeleton` skips `weights` tracks. `bakeKeyframeClip` writes `weights`
233
+ tracks as glTF `weights` channels, which gltf/pbr and `Animation` play back (`tests/keyframes-weights.test.js` checks
234
+ the round trip through `exportGLB`).
235
+
236
+ ```ts
237
+ const blink = createKeyframeClip({name: 'Blink', tracks: [
238
+ {target: 'Face', path: 'weights', keys: [{time: 0, value: [0, 0]}, {time: 0.1, value: [1, 0]}, {time: 0.2, value: [0, 0]}]},
239
+ ]});
240
+ const animation = Animation.attach(model);
241
+ animation.playing = false;
242
+ applyKeyframeClip(blink, animation, t); // node 'Face' has two morph targets
243
+ ```
244
+
245
+ `skin.pose()` runs the GPU pass's maths on the CPU (linear blend of the four bone matrices; normals by the cofactor
246
+ matrix, flipped under mirroring scales) and returns Float32 positions and normals in the mesh's space.
247
+ `tests/raw-rig-roundtrip.test.js` writes a raw rig and clip with `@margoengine/exporters` `exportGLB` (bones as export
248
+ nodes under the mesh node, `skeleton.inverseBindMatrices`, `bakeKeyframeClip`), reads it back through gltf/pbr and
249
+ `Animation`, and matches `skin.pose()` within 1e-4 at frame and key times.
250
+ `node scripts/animation-skin-browser-tests.js` (real WebGPU, after building the packages) reads back the deformed
251
+ buffer of a skinned `createMesh` strip and matches `skin.pose()` positions and normals within 1e-5 after posing, a
252
+ ranged `setInfluences` and a device restore, with no validation errors.
253
+
254
+ ## Rigid rigs: whole meshes bound to bones
255
+
256
+ `compileRigidClip(bones, bindings, keys, {name, duration})` turns keys of meshes rigidly bound to bones into stepped
257
+ bone translation and rotation tracks. A key moves its bone by the mesh's offset from its rest pose and rotates it by
258
+ the key rotation times the inverse rest rotation; each bone follows the first bound mesh (in binding order) keyed so
259
+ far, and holds the last pose until `duration`. Times are seconds; rotations are `[x, y, z, w]`.
260
+
261
+ ```ts
262
+ const clip = compileRigidClip(
263
+ [{id: 'arm', translation: [0.5, 1.5, 0]}],
264
+ [{object: 'sword', bone: 'arm', position: [1, 1, 0], rotation: [0, 0, 0, 1]}],
265
+ [{object: 'sword', time: 0.5, position: [1, 2, 0], rotation: [0, 0, 0, 1]}],
266
+ {duration: 2},
267
+ );
268
+ applyKeyframeClip(clip, skeleton, t);
269
+ ```
270
+
271
+ ## Property tracks: any number, vector or colour
272
+
273
+ ```ts
274
+ import {applyKeyframeClip, bakeKeyframeTrack, createKeyframeClip, sampleKeyframes} from 'margoengine/animation';
275
+ const lamp = {intensity: 0, material: {roughness: 1, color: new Float32Array([1, 1, 1, 1])}};
276
+ let fov = 60;
277
+ const pulse = createKeyframeClip({name: 'Pulse', tracks: [
278
+ {target: lamp, property: 'intensity', keys: [{time: 0, value: [0], interpolation: 'easeOut'}, {time: 1, value: [5]}]},
279
+ {target: lamp, property: 'material.roughness', keys: [{time: 0, value: [1], interpolation: 'discrete'}, {time: 0.5, value: [0.2]}]},
280
+ {target: lamp, property: 'material.color', type: 'color', keys: [{time: 0, value: [1, 0, 0]}, {time: 1, value: [0, 0, 1]}]},
281
+ {target: lamp, name: 'fov', get: () => fov, set: (value) => { fov = value[0]; }, keys: [
282
+ {time: 0, value: [40], interpolation: 'cubicSpline', outTangent: [30]},
283
+ {time: 1, value: [60], inTangent: [0]},
284
+ ]},
285
+ ]});
286
+ applyKeyframeClip(pulse, 0.5); // writes all four properties
287
+ const color = sampleKeyframes(pulse.properties![2], 0.25); // [0.75, 0, 0.25]
288
+ const baked = bakeKeyframeTrack(pulse.properties![0], 30); // a glTF sampler for one property track
289
+ ```
290
+
291
+ A track whose `target` is an object drives a property of it instead of a bone or node: name it with a dot path
292
+ (`'material.roughness'`, `'intensity'`, `'position'`, `'lights.0.color'`) or pass `set` (and `get`, for
293
+ `track.read()`) accessors. Keys hold 1 to 4 numbers; `type` says what they are: `'number'`, `'vector'`, `'color'`
294
+ (linear RGB or RGBA, blended per channel in linear space) or `'quaternion'` (normalised, slerped along the shortest
295
+ path). They take the same interpolations (`'cubicSpline'` is a glTF CUBICSPLINE segment through the key's
296
+ `outTangent` and the next key's `inTangent`, in units per second) and the same `blend` modes as transform tracks.
297
+ `createKeyframeClip` resolves each path once into a setter, so playback does no lookups and allocates nothing: a
298
+ number property is assigned, a boolean gets `value >= 0.5`, an array or typed array (a materials `Material`'s live
299
+ `color`, a clustered light's `color`) is written in place, a getter that returns a fresh array is assigned through its
300
+ setter, and an `{x, y, z}` object such as a mesh's `position` is set through its `set(x, y, z)`. A path that does not
301
+ resolve throws `RangeError` naming the segment; one that ends on a value it cannot write throws `TypeError`. Engine
302
+ objects work the same way: `{target: mesh, property: 'visible'}`, `{target: material, property: 'roughness'}`,
303
+ `{target: stage.engine.camera, property: 'fov'}`. Replacing an object along a path later leaves the track driving the
304
+ old one: create the clip again. Property tracks land in `clip.properties`; `applyKeyframeClip(clip, time)` writes
305
+ them, and `applyKeyframeClip(clip, skeleton, time)` writes them and poses the skeleton. `bakeKeyframeClip` leaves them
306
+ out (glTF nodes have no such paths); `AnimationGroup` and `retarget` ignore them.
307
+
308
+ ## KHR_animation_pointer playback
309
+
310
+ Transmission can start at `0` (or its omitted default) and animate to a positive
311
+ factor. Seeking back to `0` restores the opaque path. Volume attenuation and native
312
+ capture follow the transition; the source document stays unchanged. The
313
+ [self-contained triangle example](../gltf/README.md#animate-an-opaque-material-into-glass)
314
+ builds this channel without a downloaded model.
315
+
316
+ Volume pointer writes update attenuation and optical depth together. Optical depth
317
+ is retained before transmittance underflows, so a thick volume scaled down in the
318
+ scene keeps its absorption. Backward seeks recompute those values from the source
319
+ volume and the sampled keys.
320
+
321
+ ```ts
322
+ import {createStage} from 'margoengine';
323
+ import {loadGLTF, viewGLTFCamera} from 'margoengine/gltf/pbr';
324
+ import {Animation} from 'margoengine/animation';
325
+ import {pointerChannels} from 'margoengine/animation/pointer';
326
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
327
+ const model = await loadGLTF(stage.engine, '/pointer-show.glb');
328
+ const animation = Animation.attach(model, {pointers: pointerChannels});
329
+ for (const warning of animation.warnings) console.warn(warning); // pointers this player skips
330
+ animation.playing = false;
331
+ animation.seek(1.5);
332
+ viewGLTFCamera(model, 0); // cameras and lights are data: hand them on after each update
333
+ ```
334
+
335
+ Pointer playback is opt-in, like gltf/pbr's optional decoders: import `pointerChannels` from
336
+ `@margoengine/animation/pointer` and pass it as the `pointers` option, so apps whose files have no pointer channels do
337
+ not ship it. Without it, `Animation` skips every pointer channel (still counting it in the clip's duration) and lists
338
+ it in `animation.warnings` with the fix. With it, `Animation` plays a clip's `KHR_animation_pointer` channels with its
339
+ ordinary ones, at the same time, speed and loop, with glTF's STEP, LINEAR and CUBICSPLINE sampling. It drives:
340
+
341
+ - nodes: `/nodes/i/translation`, `rotation` (slerp), `scale`, `weights`, `/meshes/i/weights` (every node using the mesh,
342
+ unless the node's own weights are animated) and `/nodes/i/extensions/KHR_node_visibility/visible` (STEP, unsigned
343
+ byte);
344
+ - materials (every primitive material of the glTF material): `pbrMetallicRoughness/baseColorFactor`, `metallicFactor`,
345
+ `roughnessFactor`, `emissiveFactor`, `alphaCutoff`, `normalTexture/scale`, `occlusionTexture/strength`,
346
+ `KHR_materials_emissive_strength`, `KHR_materials_dispersion`, and with the physical renderer the clearcoat,
347
+ transmission, specular, sheen, IOR and volume factors (the transmission tint and volume follow);
348
+ - `KHR_texture_transform` `offset`, `scale` and `rotation` on the base, metallic-roughness, normal, occlusion,
349
+ emissive, clearcoat, transmission, sheen and specular textures (the map and its uniform rows);
350
+ - `KHR_lights_punctual`: `color`, `intensity`, `range`, `spot/innerConeAngle`, `spot/outerConeAngle` on `model.lights`,
351
+ so `model.clusteredLights()` and `applyGLTFLights` pick them up;
352
+ - cameras: `perspective/yfov`, `aspectRatio`, `znear`, `zfar` and `orthographic/xmag`, `ymag`, `znear`, `zfar` on
353
+ `model.cameras`, for `viewGLTFCamera`.
354
+
355
+ Values are written to copies the model owns, never to `model.asset.doc`, and bound on the clip's first playback.
356
+ Pointers that break the glTF rules throw: malformed or out-of-range indices, properties animations may not change
357
+ (`/materials/0/name`), a repeated pointer, a node property animated both by pointer and by an ordinary channel,
358
+ accessors of the wrong type or count, booleans that are not STEP unsigned bytes, and an IOR sampler with a key below 1
359
+ (`KHR_materials_ior` keeps 0 as a mode set in the file, never an animated value). Valid pointers this player cannot
360
+ drive are skipped and listed in `animation.warnings`: other extensions (iridescence, anisotropy and diffuse
361
+ transmission factors, unknown extensions), `extras`, `texCoord`, textures of extended materials, properties the file
362
+ leaves undefined (a camera without `zfar`, a light without `range`), factors gltf/pbr did not load (physical factors
363
+ without the materials decoder, transmission on a material loaded without it), the IOR of a material whose file sets it to
364
+ 0 (the extension ignores updates of that mode) and targets no scene node or primitive uses. A cubic IOR spline that dips
365
+ below 1 between its keys writes 1.
366
+
367
+ ## Behaviour graphs (`@margoengine/animation/interactivity`)
368
+
369
+ A glTF file can carry its own behaviour: on a click, play this clip, turn that material green. `GLTFInteractivity` runs the `KHR_interactivity` graph of a loaded model on the engine's frame loop, so the file behaves with no code of the app's. The graph itself lives in [`@margoengine/gltf/interactivity`](../gltf/README.md#behaviour-graphs-in-gltf-interactivity); this entry reaches the engine, and sits in this package because it plays clips and writes the same live properties as `KHR_animation_pointer`.
370
+
371
+ ```ts
372
+ import {createStage} from 'margoengine';
373
+ import {loadGLTF} from 'margoengine/gltf/pbr';
374
+ import {GLTFInteractivity} from 'margoengine/animation/interactivity';
375
+
376
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
377
+ const model = await loadGLTF(stage.engine, '/product.glb');
378
+ const behaviour = GLTFInteractivity.attach(model);
379
+ if (behaviour.rejected) console.warn(behaviour.rejected);
380
+ behaviour.graph?.on('checkout', ({variant}) => console.log(variant));
381
+ ```
382
+
383
+ | Option | Default | Meaning |
384
+ | --- | --- | --- |
385
+ | `pointer` | `true` | Turns pointer input on the canvas into select and hover events. Attaches `Picking` of `@margoengine/selection`, an optional peer loaded on first use, unless the engine has a picker. |
386
+ | `physics` | none | The `GLTFPhysics` of `@margoengine/gltf/physics`, for `rigid_body/*` operations and trigger events. |
387
+ | `shareCamera` | `true` | Reports the viewer's camera to the graph. `false` makes `activeCamera` read as NaN, for a file you do not trust with where the viewer looks. |
388
+ | `log` | none | Receives `debug/log` text. |
389
+ | `maxActivations` | 1,000,000 | Node activations one step may run before the graph halts. |
390
+ | `maxEventsPerTick` | 10,000 | Custom events one tick delivers. |
391
+
392
+ A file's clips start only when its graph says so, so do not also play them with `Animation`. A press that moves over 4 CSS pixels is a drag and selects nothing. A click passes through unselectable nodes to what is behind them, and the graph receives the point it hit. `behaviour.notes` lists properties the graph wrote that it can read back but that change nothing on screen. `dispose()` stops the input.
393
+
394
+ ## Groups: one clip for many models
395
+
396
+ `AnimationGroup` is one clip and one clock for a crowd. Members are glTF PBR models'
397
+ `Animation`s playing a glTF clip they all have (by name or index), or, for a code-authored `KeyframeClip`, `Skeleton`s
398
+ and `Animation`s whose bones or nodes the tracks name. Each member can run ahead or behind by an offset in seconds.
399
+
400
+ ```ts
401
+ import {createStage} from 'margoengine';
402
+ import {loadGLTF} from 'margoengine/gltf/pbr';
403
+ import {Animation, AnimationGroup} from 'margoengine/animation';
404
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
405
+ const walkers = await Promise.all([0, 1, 2].map(() => loadGLTF(stage.engine, '/RobotExpressive.glb')));
406
+ const crowd = new AnimationGroup('Walking', {speed: 1});
407
+ const animations = walkers.map((model) => Animation.attach(model));
408
+ for (const [i, animation] of animations.entries()) crowd.add(animation, i * 0.37); // offset per walker
409
+ const walkerAnimation = animations[0];
410
+ stage.engine.use(crowd); // advances in onPreUpdate; or call crowd.update(delta) yourself
411
+ crowd.seek(2); crowd.playing = false; crowd.setOffset(walkerAnimation, 0.5); crowd.remove(walkerAnimation);
412
+ ```
413
+
414
+ Adding an `Animation` pauses its own playback; the group seeks it each frame through its usual sampling path. A glTF
415
+ clip loops as each member's own `loop` option says (a negative member time wraps back from the end); code clips take
416
+ the group's `loop` option (default true; false holds the first and last frames). Code-clip tracks are bound to bones,
417
+ nodes and morph weights once, in `add`, and group playback creates no typed arrays per frame
418
+ (`tests/group.test.js` traps the constructors over 120 frames). Each member still deforms on the GPU through its own
419
+ `Animation`; the group adds no GPU work.
420
+
421
+ ## Sampling (`@margoengine/animation/sampling`)
422
+
423
+ `sampleTrack` and `sampleTrackInto` (also on the root) without the deformation pipeline or
424
+ gltf/pbr, for code that samples tracks itself (`@margoengine/animator` does).
425
+
426
+ ```ts
427
+ import {sampleTrack} from 'margoengine/animation/sampling';
428
+
429
+ const times = new Float32Array([0, 1]);
430
+ const values = new Float32Array([0, 0, 0, 10, 0, 0]); // x, y, z per key
431
+ const position = sampleTrack(times, values, 3, 0.5, 'LINEAR'); // Float32Array [5, 0, 0]
432
+ ```
433
+
434
+ ### Clip markers
435
+
436
+ `ClipMarkers` reports the named moments a play position passes: footsteps, hits, sound cues. A marker counts as passed
437
+ once the position is at or beyond it, so moving forward from a to b reports markers in (a, b], moving back reports (b, a],
438
+ and a loop repeats them every lap (a step longer than the clip reports every lap). `seek` is silent unless you pass
439
+ `fire`. `createKeyframeClip` takes `markers` and sorts them onto `clip.markers`.
440
+
441
+ ```ts
442
+ import {ClipMarkers} from 'margoengine/animation/sampling';
443
+ import {createKeyframeClip} from 'margoengine/animation';
444
+
445
+ const clip = createKeyframeClip({
446
+ tracks: [{target: 'hips', path: 'translation', keys: [{time: 0, value: [0, 0, 0]}, {time: 1, value: [0, 0, 2]}]}],
447
+ markers: [{time: 0.25, name: 'footstep'}, {time: 0.75, name: 'footstep'}],
448
+ });
449
+ const player = new ClipMarkers(clip.markers ?? [], clip.duration); // loops by default
450
+ player.advance(0.5).map((m) => m.time); // [0.25]
451
+ player.advance(0.5).map((m) => m.time); // [0.75]
452
+ player.advance(-0.5).map((m) => m.time); // [0.75] (leaving 0.75 backward)
453
+ ```
454
+
455
+ ### Clip compression
456
+
457
+ `compressTrack` removes keys a track does not need and `quantizeTrack` stores what is left as 16-bit integers. Both keep
458
+ the sampling call the same (`dequantizeTrack` gives the Float32 track back), and both report the error you can check:
459
+ after `compressTrack(track, tolerance)` every original key time samples within `tolerance` per component
460
+ (`result.error` is the measured maximum); quantisation adds at most half a `step` (range / 131070) per component.
461
+ `LINEAR` and `STEP` tracks only; rotation tracks take `quaternion: true`. On six KayKit Rig_Medium clips (rotations and
462
+ translations, 0.0005 tolerance) the keys went from 4,589 to 3,441 and the bytes from 88,440 to 50,832; a 2 second, 60 fps
463
+ walk bob at 1 cm keeps 33 of 121 keys and shrinks from 1,936 to 354 bytes (`tests/clip-tools.test.js`).
464
+
465
+ ```ts
466
+ import {compressTrack, dequantizeTrack, quantizeTrack, sampleTrack} from 'margoengine/animation/sampling';
467
+
468
+ const times = Float32Array.from({length: 61}, (_, i) => i / 30);
469
+ const values = Float32Array.from(times, (t) => Math.sin(t * 3));
470
+ const track = {times, values, width: 1, interpolation: 'LINEAR' as const};
471
+
472
+ const small = compressTrack(track, 0.001); // fewer keys, small.error <= 0.001
473
+ const packed = quantizeTrack(small); // packed.data is a Uint16Array
474
+ const back = dequantizeTrack(packed);
475
+ const x = sampleTrack(back.times, back.values, 1, 0.5, 'LINEAR'); // within 0.001 plus half a step of sin(1.5)
476
+ ```
477
+
478
+ ## GPU morph weights (`@margoengine/animation/morph-gpu`)
479
+
480
+ The deformation pass always blends morph targets on the GPU. `MorphWeightPlayer` moves the rest of the work there too:
481
+ a clip's weight tracks upload once, and one compute dispatch per deformation buffer page samples every copy's weights
482
+ each frame, so the CPU writes 16 bytes a frame however many faces play.
483
+
484
+ ```ts
485
+ import {createStage} from 'margoengine';
486
+ import {loadGLTF} from 'margoengine/gltf/pbr';
487
+ import {Animation} from 'margoengine/animation';
488
+ import {MorphWeightPlayer} from 'margoengine/animation/morph-gpu';
489
+ import {cloneModel} from 'margoengine/animation/skeleton-utils';
490
+ const stage = await createStage('#viewport', {backend: 'webgpu', capacity: 16384});
491
+ // Copy this repository's CC0 RobotExpressive asset to the same public URL in your app.
492
+ const source = await loadGLTF(stage.engine, '/examples/assets/robot-expressive.glb');
493
+ const models = [source, ...(await Promise.all(Array.from({length: 99}, () => cloneModel(source))))];
494
+ const talk = MorphWeightPlayer.attach(stage.engine, 'Dance'); // this asset's clip includes weight tracks
495
+ for (const [i, model] of models.entries()) {
496
+ const animation = Animation.attach(model);
497
+ animation.playing = false; // or keep it playing a body clip: only weights are driven here
498
+ talk.add(animation, {offset: i * 0.13, speed: 1}); // defaults 0 and 1; add again to change them
499
+ }
500
+ talk.speed = 0.5; // every copy; talk.time, talk.playing and talk.remove(animation) work as you would expect
501
+ // A synchronous raycast hits each face at the weights the player draws. talk.weightsInto(animation, primitive, out)
502
+ // gives them; remove(animation) and dispose() leave the weights last drawn in primitive.weights.
503
+ talk.dispose();
504
+ ```
505
+
506
+ A copy samples `time * speed + offset`, with `sampleTrack`'s arithmetic for STEP, LINEAR and CUBICSPLINE. Copies must
507
+ share one asset (`cloneModel`), because they share the tracks; a disposed copy leaves by itself. Weights the player
508
+ drives are overwritten every frame, so `setMorph` has no effect on them, and `primitive.weights` on the CPU does not
509
+ follow them. `scripts/animation-morph-gpu-tests.js` reads the weights back on real WebGPU and matches `sampleTrack`
510
+ within 1e-5 on 70 copies, looping and held.
511
+
512
+ ## Large faces: sparse morph targets
513
+
514
+ Morph deltas stay sparse from the file to the GPU. Each deformed primitive keeps a table by vertex (compressed sparse
515
+ row): one row pointer per vertex, then only the (vertex, target) pairs a target moves, in target order, each 32 bytes
516
+ (48 with tangent targets). The deformation pass walks a vertex's own entries, so a Character Creator head with 395
517
+ expression targets costs what its targets move, not vertices times targets. The sum is the dense one term for term (a
518
+ target that does not move a vertex adds zero), so the output is the same bits: `scripts/animation-batched-deformation-tests.js`
519
+ checks it against the dense per-primitive shader on real WebGPU, and the synchronous CPU pose reads the same table.
520
+
521
+ | Measured on the CC old man (230,909 welded body vertices, 395 targets; 24 morphed primitives) | GPU morph data |
522
+ | --- | --- |
523
+ | Dense, 48 bytes per vertex and target (before) | 6,574 MiB, refused at setup |
524
+ | Sparse table (now) | 226 MiB; the largest primitive's table 115 MiB, under the default 128 MiB storage binding |
525
+
526
+ Nothing to set. The deltas are read with `asset.sparseAccessor` (`@margoengine/gltf`) and nothing dense is kept on the
527
+ CPU. A primitive whose own table passes the device's storage-binding limit is refused with "Animation buffer exceeds
528
+ device limit"; load it with a smaller `maxPartVertices` so it splits into parts, each with its own table.
529
+
530
+ ```ts
531
+ import {Engine} from 'margoengine/core';
532
+ import {loadGLTF} from 'margoengine/gltf/pbr';
533
+ import {Animation} from 'margoengine/animation';
534
+
535
+ const engine = await Engine.create(document.querySelector<HTMLCanvasElement>('canvas')!);
536
+ const head = await loadGLTF(engine, '/models/head.glb', {maxPartVertices: 65536}); // parts only if a table is too big
537
+ const animation = Animation.attach(head);
538
+ const face = head.primitives.find((p) => p.targetNames.includes('Eye_Blink_L'))!;
539
+ animation.setMorph(face.nodeIndex, face.targetNames.indexOf('Eye_Blink_L'), 1);
540
+ engine.start();
541
+ ```
542
+
543
+ ## Animation LOD (`@margoengine/animation/lod`)
544
+
545
+ `AnimationLOD` updates each character as often as its distance and visibility call for, so a big crowd spends its CPU
546
+ on the characters people can see. Time keeps running for every copy, so one that is updated again lands exactly where
547
+ it would have been.
548
+
549
+ ```ts
550
+ import {createStage} from 'margoengine';
551
+ import {loadGLTF} from 'margoengine/gltf/pbr';
552
+ import {Animation} from 'margoengine/animation';
553
+ import {AnimationLOD} from 'margoengine/animation/lod';
554
+ import {cloneModel} from 'margoengine/animation/skeleton-utils';
555
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
556
+ const source = await loadGLTF(stage.engine, '/RobotExpressive.glb');
557
+ const models = [source, ...(await Promise.all(Array.from({length: 199}, () => cloneModel(source))))];
558
+ const lod = AnimationLOD.attach(stage.engine, {
559
+ tiers: [
560
+ {distance: 0, interval: 1}, // the default tiers are these three
561
+ {distance: 15, interval: 2}, // every second frame from 15 units
562
+ {distance: 40, interval: 4, depth: 4}, // every fourth frame, and nodes below level 4 hold
563
+ ],
564
+ hidden: {distance: 0, interval: 16, depth: 1}, // off screen, at any distance
565
+ });
566
+ const walkers = models.map((model, i) => {
567
+ model.root.setPosition([(i % 20) * 3, 0, -Math.floor(i / 20) * 6]);
568
+ return Animation.attach(model).play('Walking');
569
+ });
570
+ for (const walker of walkers) lod.add(walker, {radius: 1.5}); // the sphere tested against the view; default 2
571
+ stage.onTick(() => console.log(lod.stats)); // {updated, skipped, hidden} of the last frame
572
+ lod.remove(walkers[0]); // hands a copy back, fully posed, playing as it was
573
+ ```
574
+
575
+ `add` takes over a copy's playback; its clip, `speed` and `loop` still come from its `Animation`. A copy takes the last
576
+ tier whose `distance` it has reached, and copies on one interval take turns, so no frame carries them all. `depth`
577
+ counts node levels from the scene roots, so what level 4 means depends on the rig: pick it per character. Weight tracks
578
+ always play. Distance and visibility use the root's position from the previous frame.
579
+
580
+ ## Clip editing (`@margoengine/animation/clip-utils`)
581
+
582
+ `subclip` cuts a time range into a new clip, and `makeAdditive` turns a clip into differences from a reference pose.
583
+
584
+ ```ts
585
+ import {Skeleton, applyKeyframeClip, createKeyframeClip} from 'margoengine/animation';
586
+ import {applyAdditiveClip, makeAdditive, subclip, subclipFrames} from 'margoengine/animation/clip-utils';
587
+ const skeleton = new Skeleton([{name: 'hips', parent: -1}, {name: 'head', parent: 0, translation: [0, 1, 0]}]);
588
+ const walk = createKeyframeClip({
589
+ name: 'Walk',
590
+ tracks: [{target: 'hips', path: 'translation', keys: [
591
+ {time: 0, value: [0, 0, 0]}, {time: 1, value: [0, 0.1, 1]}, {time: 2, value: [0, 0, 2]},
592
+ ]}],
593
+ markers: [{time: 0.75, name: 'footstep'}],
594
+ });
595
+ const nod = createKeyframeClip({
596
+ name: 'Nod',
597
+ tracks: [{target: 'head', path: 'rotation', keys: [
598
+ {time: 0, value: [0, 0, 0, 1]}, {time: 0.5, value: [0.2588, 0, 0, 0.9659]}, {time: 1, value: [0, 0, 0, 1]},
599
+ ]}],
600
+ });
601
+ const stride = subclip(walk, 0.5, 1.5, {name: 'Stride'}); // seconds; starts at 0, markers come along
602
+ const opening = subclipFrames(walk, 0, 15); // frames, both included, at 30 per second unless you pass a rate
603
+ const additive = makeAdditive(nod); // against the first frame; or {clip: idle, time: 0.5}
604
+ const t = 0.25;
605
+ applyKeyframeClip(stride, skeleton, t); // pose the base first, every frame
606
+ applyAdditiveClip(additive, skeleton, t, 0.5); // then add half of the nod
607
+ ```
608
+
609
+ A cut plays exactly as the source did: both ends are sampled, keys inside keep their interpolation, and only an eased or
610
+ cubic segment the cut passes through becomes short straight keys, 60 per second unless you pass `fps`. Property tracks
611
+ stay bound to their targets, and `blend` carries over. `makeAdditive` uses the sums `@margoengine/animator` additive
612
+ layers use: translation and weights subtract, scale divides (a zero reference axis gives 1) and rotation is
613
+ `inverse(reference) * rotation`. Every key keeps its time and interpolation, so the result is exact between keys too.
614
+ `applyAdditiveClip` adds to whatever pose the skeleton holds, so applying it twice adds twice.
615
+
616
+ ## Dual quaternion skinning (`@margoengine/animation/dqs`)
617
+
618
+ Blended matrices pinch a joint that twists: a forearm turned 170 degrees shrinks to under a tenth of its radius halfway
619
+ along. Pass `dualQuaternionSkinning` and the bones blend as rigid motions, so the arm keeps its volume. It is a per
620
+ `Animation` choice, made when you create it. The cost is one matrix split per bone per frame on the CPU, and more
621
+ arithmetic per vertex on the GPU.
622
+
623
+ ```ts
624
+ import {createStage} from 'margoengine';
625
+ import {loadGLTF} from 'margoengine/gltf/pbr';
626
+ import {Animation} from 'margoengine/animation';
627
+ import {dualQuaternionSkinning} from 'margoengine/animation/dqs';
628
+ const stage = await createStage('#viewport', {backend:'webgpu',capacity:2048});
629
+ const model = await loadGLTF(stage.engine, '/RobotExpressive.glb');
630
+ const animation = Animation.attach(model, {skinning: dualQuaternionSkinning});
631
+ animation.play('Walking');
632
+ ```
633
+
634
+ Scaled, stretched, sheared and mirrored bones keep working: each bone's matrix splits exactly into a rotation, a
635
+ translation and a symmetric stretch, the stretch blends linearly and applies first, then the blended rigid motion. A
636
+ vertex held by one bone lands where the matrix puts it. A bone scaled to nothing still encodes, so hiding a part that
637
+ way works. Between two bones of different scale the result differs from a linear blend, because the stretch applies
638
+ about the mesh origin rather than each joint. Four and eight influences, morph targets under the skin, clones and
639
+ models of both kinds in one scene all work; each kind is its own dispatch.
640
+
641
+ `encodeDualQuaternions(palette, out?)` turns 16-float bone matrices into 16-float slots (rotation, dual part, stretch),
642
+ and `skinDualQuaternion(slots, joints, weights, position, normal?)` is the shader's CPU twin, for tests and CPU picking.
643
+ `blendSkinning` is the same dual quaternion skin with a share per vertex: each vertex mixes the linear skin of its bones
644
+ with the dual quaternion skin by a number in [0, 1], which is what an FBX `Blend` skin means. The shares come from the
645
+ node's glTF `extras.fbxSkinning.blendWeights` (one per vertex of its primitive, written by `@margoengine/fbx/deformers`);
646
+ a node without them is all dual quaternion, and a list of the wrong length or a share outside [0, 1] throws. Position,
647
+ normal and tangent blend between the two skins. `skinDualQuaternion(slots, joints, weights, position, normal, share)` takes
648
+ the share as its sixth argument, and matches the GPU to 7e-6 on a twisted tube (`npm run test:gpu:dqs`).
649
+
650
+ Synchronous raycasts (`@margoengine/bvh`) hit a model under either mode where the GPU draws it: each `SkinningMode` may
651
+ give `blend(palette, joints, weights, position, normal, share)`, its blend on the CPU, and both modes here do (it is
652
+ `skinDualQuaternion`). `Animation`'s CPU pose runs it after the morph targets, with the palette `encode` wrote and each
653
+ vertex's share; on a real GPU it matches the read-back pose to 1e-6. A mode without `blend` refuses those raycasts.
654
+
655
+ ```ts
656
+ import {createStage} from 'margoengine';
657
+ import {loadGLTF} from 'margoengine/gltf/pbr';
658
+ import {Animation} from 'margoengine/animation';
659
+ import {blendSkinning} from 'margoengine/animation/dqs';
660
+ const stage = await createStage('#viewport', {backend:'webgpu',capacity:2048});
661
+ const model = await loadGLTF(stage.engine, '/RobotExpressive.glb'); // an FBX Blend skin: loadFBX with the deformers extension
662
+ const animation = Animation.attach(model, {skinning: blendSkinning});
663
+ animation.play('Walking');
664
+ ```
665
+
666
+ ```ts
667
+ import {createStage} from 'margoengine';
668
+ import {loadGLTF} from 'margoengine/gltf/pbr';
669
+ import {Animation} from 'margoengine/animation';
670
+ import {dualQuaternionSkinning} from 'margoengine/animation/dqs';
671
+ import {Raycaster} from 'margoengine/bvh';
672
+ const stage = await createStage('#viewport', {backend:'webgpu',capacity:2048});
673
+ const model = await loadGLTF(stage.engine, '/RobotExpressive.glb');
674
+ Animation.attach(model, {skinning: dualQuaternionSkinning}).play('Walking');
675
+ // Hit at the dual quaternion pose drawn this frame, with no GPU readback.
676
+ const [hit] = new Raycaster([0, 1, 5], [0, 0, -1]).intersectObjects(stage.engine, [model]);
677
+ ```
678
+
679
+ Only `Animation` has the option: `Skin` on raw data, `bakeVAT` and the bone-texture crowd stay linear.
680
+
681
+ ## Skinning about centres of rotation (`@margoengine/animation/cor`)
682
+
683
+ Dual quaternions keep a twisted limb's volume but turn every blended vertex about its bones' joint, so cloth weighed
684
+ between a still bone and a turning one swings out: a coat's side panel balloons when the arm goes up, a coat skirt
685
+ over bent hips turns into a sack. `centerOfRotationSkinning` (Le and Hodgins 2016) turns each vertex by the blended
686
+ rotation about its own centre of rotation, and moves that centre as a linear blend would. The centre is the middle of
687
+ the surface whose weights are like the vertex's, so the panel turns about itself: no linear collapse, no dual
688
+ quaternion bulge, and a twist keeps its volume. `@margoengine/humans` `addPerson` uses it by default.
689
+
690
+ ```ts
691
+ import {createStage} from 'margoengine';
692
+ import {loadGLTF} from 'margoengine/gltf/pbr';
693
+ import {Animation} from 'margoengine/animation';
694
+ import {centerOfRotationSkinning} from 'margoengine/animation/cor';
695
+ const stage = await createStage('#viewport', {backend:'webgpu',capacity:2048});
696
+ const model = await loadGLTF(stage.engine, '/RobotExpressive.glb');
697
+ Animation.attach(model, {skinning: centerOfRotationSkinning}).play('Walking');
698
+ ```
699
+
700
+ The centres are computed once per skinned mesh, from all of its primitives in the bind pose, and shared by every copy
701
+ and clone of the model: about 0.3 s for a 75,525 vertex coat and 2.4 s for a 154,923 vertex Character Creator body
702
+ in Node on the workstation. They ride with each vertex's joints and weights (four more numbers per vertex), and the
703
+ bones use the dual quaternion slots, so scaled and mirrored bones work as there. `rotationCentres(parts, options?)`
704
+ returns the centres (four numbers per vertex: the centre then 1, or the vertex itself then 0 on a single bone) and
705
+ `skinCenterOfRotation(slots, joints, weights, position, normal?, centre?)` is the shader's CPU twin; Animation's CPU
706
+ pose uses it, so a synchronous raycast hits the drawn pose (within 5.4e-7 of the GPU on WebGPU and 4.8e-7 on the
707
+ WebGL2 layer, `npm run test:gpu:cor`). A skinning mode of your own gets the same per-vertex channel with
708
+ `vertexData(parts)`.
709
+
710
+ ## Bone-texture crowds (`@margoengine/animation/instanced-skin`)
711
+
712
+ A vertex animation texture stores finished vertices, so a crowd member can only play one clip. `bakeBones` stores bone
713
+ matrices instead, one row per clip frame, and `SkinnedCrowd` skins each member in the vertex shader: any number of
714
+ characters in one draw, and each can blend two clips, with its own offsets and speeds. The CPU does nothing per member
715
+ per frame. The texture is also far smaller: three texels per bone per frame, whatever the vertex count.
716
+
717
+ ```ts
718
+ import {createStage} from 'margoengine';
719
+ import {loadGLTF} from 'margoengine/gltf/pbr';
720
+ import {Animation} from 'margoengine/animation';
721
+ import {SkinnedCrowd, bakeBones} from 'margoengine/animation/instanced-skin';
722
+ const stage = await createStage('#viewport', {backend:'webgpu',capacity:2048});
723
+ const model = await loadGLTF(stage.engine, '/RobotExpressive.glb');
724
+ const bake = bakeBones(new Animation(model), {fps: 30, clips: ['Walking', 'Running']});
725
+ model.dispose();
726
+
727
+ const crowd = SkinnedCrowd.attach(stage.engine, bake);
728
+ for (let i = 0; i < 1000; i++)
729
+ crowd.add({
730
+ matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, (i % 40) * 2, 0, Math.floor(i / 40) * 2, 1],
731
+ clip: 0,
732
+ offset: i * 0.13,
733
+ blendClip: 1,
734
+ blend: (i % 10) / 10, // a jog: part walk, part run
735
+ });
736
+ crowd.set(0, {blend: 1});
737
+ ```
738
+
739
+ `bakeBones(animation, {fps = 30, clips})` bakes clips by name or index, all primitives merged in the model root's space,
740
+ up to eight influences per vertex; an unskinned part becomes a bone of its own. The animation's clip, time and playing
741
+ state are restored. A member takes `VATCrowd`'s `matrix`, `clip`, `offset`, `speed` and `uvTransform`, and adds
742
+ `blendClip` (default 0), `blendOffset` (default 0), `blendSpeed` (default 1) and `blend` (0 to 1, default 0, all of the
743
+ first clip). Clips mix as matrices, and bones blend linearly. Everything else follows `VATCrowd`: one material, opaque,
744
+ `shadows.add(crowd)` and `lighting.add(crowd)`, no CPU culling. One vertex entry draws colour and shadow, its position `@invariant` (WGSL 12.10) as every Margo shadow caster's is, so another program drawing the same surface writes the same depth bit for bit. `poseBones(bake, member, time, out?)` is the shader's CPU
745
+ twin, for bounds and picking. `poseBone(bake, member, bone, time, out?)` is the twin for one bone: its skinning matrix as
746
+ the 12 numbers of its 3x4 rows, both clips and the blend applied, for what follows a member (a rider on a horse's back,
747
+ a rifle in a hand):
748
+
749
+ ```ts
750
+ import {poseBone} from 'margoengine/animation/instanced-skin';
751
+ const bake = {bones: 1, rows: 2, width: 2048, texels: new Float32Array(2048 * 4), vertexCount: 0, vertices: new Float32Array(0),
752
+ joints: new Uint32Array(0), weights: new Float32Array(0), indices: new Uint32Array(0), uvs: new Float32Array(0),
753
+ clips: [{name: 'still', start: 0, frames: 1, duration: 1, loop: true}]};
754
+ for (const row of [0, 1]) bake.texels.set([1, 0, 0, 0, 0, 1, 0, 2, 0, 0, 1, 0], row * 12); // lifted 2 m
755
+ const m = poseBone(bake, {clip: 0}, 0, 0.5);
756
+ console.log(m[7]); // 2: a point on this bone rides 2 m up
757
+ ```
758
+
759
+ Morph targets stay at the weights they had when baked; `MorphedCrowd` (next section) gives each member its own.
760
+
761
+ ## Morph weights per crowd member (`@margoengine/animation/instanced-morph`)
762
+
763
+ `MorphedCrowd` is a `SkinnedCrowd` whose members each carry their own morph weights, set from JavaScript at any time:
764
+ one face smiles while the next one frowns, in the same instanced draw. `bakeMorphBones` bakes like `bakeBones` but
765
+ leaves the live targets out of the vertices and stores their position and normal offsets in the bone texture, after the
766
+ bone rows; each member's weights ride in its instance row, and the vertex shader adds the weighted offsets before it
767
+ skins. The CPU does no per-vertex work.
768
+
769
+ ```ts
770
+ import {createStage} from 'margoengine';
771
+ import {loadGLTF} from 'margoengine/gltf/pbr';
772
+ import {Animation} from 'margoengine/animation';
773
+ import {MorphedCrowd, bakeMorphBones} from 'margoengine/animation/instanced-morph';
774
+ const stage = await createStage('#viewport', {backend: 'webgpu', capacity: 2048});
775
+ // Copy this repository's CC0 RobotExpressive asset to the same public URL in your app.
776
+ const model = await loadGLTF(stage.engine, '/examples/assets/robot-expressive.glb');
777
+ const bake = bakeMorphBones(new Animation(model), {fps: 30, clips: ['Walking']});
778
+ model.dispose();
779
+
780
+ const crowd = MorphedCrowd.attach(stage.engine, bake);
781
+ const [first, second] = bake.morphs.names; // the live targets, in weight order
782
+ for (let i = 0; i < 100; i++)
783
+ crowd.add({
784
+ matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, (i % 10) * 2, 0, Math.floor(i / 10) * 2, 1],
785
+ offset: i * 0.13,
786
+ morphs: [i % 2], // weights in bake.morphs.names order; a short array sets the first ones
787
+ });
788
+ crowd.setMorph(0, first, 0.5); // one weight of one member, by name or index
789
+ crowd.set(1, {morphs: {[second]: 1}}); // by name; the weights not named keep their value
790
+ console.log(crowd.getMorph(1, second)); // 1
791
+ ```
792
+
793
+ `bakeMorphBones(animation, {fps = 30, clips, morphs})` takes `bakeBones`'s options and `morphs`: the targets that stay
794
+ live, by name or by index (default: every target of the model). Targets are joined by name across primitives, in
795
+ first-seen order, so a face split over three primitives has one weight per expression; an unnamed target is
796
+ `'Target <index>'`. A target left out of `morphs` is baked in at the weight it has now, as `bakeBones` bakes it. The
797
+ result is a `BoneBake` with `morphs.names` (the live targets), `morphs.weights` (the model's weights when baked: what a
798
+ new member starts with), `morphs.vertices` and `morphs.blocks` (where each vertex finds its offsets).
799
+
800
+ A member takes everything a `SkinnedCrowd` member does, and `morphs`: an array in `bake.morphs.names` order, or an
801
+ object of weights by name. Weights may be any finite number (below 0 and above 1 extrapolate, as glTF allows); a weight
802
+ of 0 costs no texture reads. `setMorph(index, target, weight)` and `getMorph(index, target)` set and read one weight. A
803
+ weight that is not finite, an unknown target or a member that does not exist throws RangeError and changes nothing.
804
+ Changed weights upload with the next frame.
805
+
806
+ A bake holds at most 64 live targets (`MORPH_TARGET_LIMIT`): the weights are part of the instance row, four to a
807
+ vector, so a member row is 28 floats plus the target count rounded up to 4. Name the targets you animate in `morphs`
808
+ when a model has more. Offsets cost two texels (32 bytes) per vertex of each primitive that has the target, and nothing
809
+ for primitives without it. Tangent offsets are not carried (the crowd has no tangents). `morphVertices(bake, weights)`
810
+ and `poseMorphedBones(bake, member, time)` are the shader's CPU twins, for bounds and picking. Everything else is
811
+ `SkinnedCrowd`'s: two clips and a blend per member, one material, `shadows.add(crowd)`, `lighting.add(crowd)`.
812
+
813
+ `packages/animation/tests/instanced-morph-browser.mjs` runs the vertex stage's own morph and skin functions from a
814
+ compute shader on real WebGPU and on the WebGL2 compatibility layer: 48 members with their own weights, clips and blends
815
+ match `poseMorphedBones` within 1e-5 at every vertex, and a member drawn at given weights covers the same pixels as the
816
+ model itself at those weights.
817
+
818
+ ## Points on a deforming mesh (`@margoengine/animation/deformed-points`)
819
+
820
+ `DeformedPoints` draws every vertex of a model as a point where the model's deformer last put it, so a skinned or
821
+ morphed triangle mesh shows as a moving cloud of its own vertices. The points are instanced straight from the buffer the
822
+ deformation pass wrote: no second skinning pass, no CPU work per vertex, one draw per primitive.
823
+
824
+ ```ts
825
+ import {createStage} from 'margoengine';
826
+ import {loadGLTF} from 'margoengine/gltf/pbr';
827
+ import {Animation} from 'margoengine/animation';
828
+ import {DeformedPoints} from 'margoengine/animation/deformed-points';
829
+ const stage = await createStage('#viewport', {backend: 'webgpu', capacity: 2048});
830
+ // Copy this repository's CC0 RobotExpressive asset to the same public URL in your app.
831
+ const model = await loadGLTF(stage.engine, '/examples/assets/robot-expressive.glb');
832
+ Animation.attach(model).play('Dance');
833
+
834
+ const points = DeformedPoints.attach(model, {size: 3, color: '#ffcc00'});
835
+ model.root.visible = false; // the points alone; leave it true to draw them over the mesh
836
+ points.set({shape: 'round', sizeUnits: 'world', size: 0.02}); // 2 cm discs that shrink with distance
837
+ points.opacity = 0.8; // every option is also a live field
838
+ ```
839
+
840
+ | Option | Default | Meaning |
841
+ | --- | --- | --- |
842
+ | `size` | `4` | Point diameter: CSS pixels, or world units with `sizeUnits: 'world'`. Finite, 0 or more |
843
+ | `sizeUnits` | `'pixels'` | `'pixels'` keeps a constant screen size; `'world'` shrinks with distance |
844
+ | `color` | white | `'#rrggbb'`, `'#rgb'` or `0xrrggbb` (sRGB), or a linear `[r, g, b]` array. Change it with `set({color})`; `points.color` reads the linear RGB |
845
+ | `opacity` | `1` | 0 to 1. Below 1 the points blend over what is already drawn and still write depth |
846
+ | `shape` | `'square'` | `'square'`, or `'round'` (a disc cut from the square, no antialiasing of its own) |
847
+ | `vertexColors` | `true` | Multiplies `color` by each vertex's colour (glTF `COLOR_0`; white where the mesh has none) |
848
+
849
+ `points.visible` (default `true`) turns the points off and on, `points.count` is the number of points, and
850
+ `points.dispose()` (or `using`) frees them; disposing the model disposes its points. `set(options)` checks every value
851
+ and changes nothing when one is out of range (RangeError; TypeError for a `vertexColors` that is not a boolean or a
852
+ colour that is not one).
853
+
854
+ The deformer can be `Animation` (skins and morph targets, any skinning mode), `Skin` on raw data, `MorphWeightPlayer`
855
+ or a geometry cache player. A primitive no deformer writes draws its own vertices at its node, so the rigid parts of a
856
+ model show too. The points are unlit, depth tested against the scene, and written in the target's own encoding (sRGB on
857
+ a display target, linear on an HDR one). They cast no shadows, are not fogged and are not picked. A primitive drawn with
858
+ `EXT_mesh_gpu_instancing` shows its points once, at its node. `pointScale(cameraMatrix, size, sizeUnits, width, height)`
859
+ is the size maths the shader uses, for tools that need a point's footprint on screen.
860
+
861
+ `packages/animation/tests/deformed-points-browser.mjs` draws a skinned strip and a morphed triangle, both hidden, as
862
+ points on real WebGPU and on the WebGL2 compatibility layer: every vertex's point is on the pixel its pose projects to
863
+ at three clip times and three morph weights, covers its 5 x 5 pixels within 10 percent, and nothing else draws.
864
+
865
+ ## Geometry caches (`@margoengine/animation/geometry-cache`)
866
+
867
+ Cloth, destruction and fluid simulations from a DCC tool end up as baked vertices, frame by frame. `GeometryCachePlayer`
868
+ plays such a file while it downloads. It holds a few chunks at a time, so a long cache never has to fit in memory, and each
869
+ chunk carries its own triangles, so a fluid can change vertex count as it plays.
870
+
871
+ ```ts
872
+ import {createStage} from 'margoengine';
873
+ import {GeometryCachePlayer, encodeGeometryCache} from 'margoengine/animation/geometry-cache';
874
+ const stage = await createStage('#viewport', {backend:'webgpu',capacity:2048});
875
+ // Two frames of one triangle, generated here so no external cache file is needed.
876
+ const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1]);
877
+ const bytes = encodeGeometryCache(30, [{frameCount: 2, positions, indices: new Uint32Array([0, 1, 2])}]);
878
+ const flag = await GeometryCachePlayer.attach(stage.engine, bytes, {ahead: 3});
879
+ flag.seek(1 / 60);
880
+ flag.speed = 0.5;
881
+ ```
882
+
883
+ `attach(engine, source, options)` resolves once the first chunk is in. `source` is a URL, a `ReadableStream` or other async
884
+ iterable of bytes, one `Uint8Array`, or `(signal) => bytes`. Options: `loop` (default true), `speed` (default 1), `ahead`
885
+ (chunks read past the one playing, default 2), `signal`, `material` (a glTF material, default plain white) and
886
+ `maxChunkBytes` (default 1 GiB). The player owns `player.model`: move it through `player.model.root`, and dispose the player.
887
+
888
+ The clock waits when the stream falls behind, so playback never jumps; `player.stats.stalls` counts the frames it waited.
889
+ Between two frames of one mesh the vertices interpolate. A chunk with other triangles or another vertex count swaps the mesh
890
+ at its first frame, and the last frame of the chunk before it holds, since there is no mesh to mix towards. A URL, an array
891
+ or a function can start over, so played chunks are let go, a seek back reads again and a loop reads the file once a lap, with
892
+ the first chunk held so the wrap does not wait; a stream cannot, so it keeps every chunk it read. `player.done` settles when the read ends, which follows the clock by `ahead` chunks, so a paused player may
893
+ never get there. A failure rejects it and leaves the last frame up.
894
+
895
+ `readGeometryCache(bytes, {signal, maxChunkBytes})` is the same reader without a player, an async iterator of chunks, and
896
+ `encodeGeometryCache(rate, chunks)` writes a file, so an exporter is a few lines:
897
+
898
+ ```ts
899
+ import {encodeGeometryCache, readGeometryCache} from 'margoengine/animation/geometry-cache';
900
+
901
+ const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1]);
902
+ const file = encodeGeometryCache(30, [{frameCount: 2, positions, indices: new Uint32Array([0, 1, 2])}]);
903
+ for await (const chunk of readGeometryCache(file)) console.log(chunk.firstFrame, chunk.vertexCount);
904
+ ```
905
+
906
+ A cache from a DCC tool is usually a PC2 or MDD file. `parsePointCache` from `@margoengine/animation/point-cache` reads both. They hold vertices and no triangles, so give it the triangles of the mesh it was baked from:
907
+
908
+ ```ts
909
+ import {encodeGeometryCache} from 'margoengine/animation/geometry-cache';
910
+ import {parsePointCache} from 'margoengine/animation/point-cache';
911
+
912
+ const bytes = new Uint8Array(await (await fetch('/ball.pc2')).arrayBuffer()); // written by Blender's PC2 add-on
913
+ const cache = parsePointCache(bytes, {fps: 24});
914
+ // A fan over the points stands in here: use the triangles of the mesh the cache was baked from.
915
+ const indices = new Uint32Array(3 * (cache.vertexCount - 2)).map((_, n) => (n % 3 ? Math.floor(n / 3) + (n % 3) : 0));
916
+ const file = encodeGeometryCache(cache.rate, [{frameCount: cache.frameCount, positions: cache.positions, indices}]);
917
+ ```
918
+
919
+ `fps` (default 24) is for PC2, which does not say; an MDD file's own times win. `zUp: true` turns a Z-up file to Y-up as `(x, z, -y)`; Blender's MDD add-on writes Z-up and its PC2 add-on Y-up by default. `maxFloats` (default 2^28) refuses a larger file. A header that asks for more than the file holds is refused as a cut file or no point cache at all, before the limit: MDD has no magic, so any other file reads as an MDD header. Alembic is not read: it has no published file specification to build from. The result fits the player as it is, so the file above goes straight to `GeometryCachePlayer.attach`.
920
+
921
+ A meshed fluid, a fracture or any bake that writes one whole mesh a frame is a mesh sequence: the triangles change every
922
+ frame. `encodeMeshSequence(rate, frames, {maxChunkFrames})` groups it into chunks for the player, frames with the same
923
+ triangles, vertex count, UVs and normals-or-not sharing one (up to `maxChunkFrames`, default the rate rounded, about a
924
+ second) and a frame whose topology changes starting the next; a chunk with the triangles or UVs of the one before leaves
925
+ them out. `frames` is any iterable or async iterable of `{positions, indices, normals?, uvs?}`, and
926
+ `streamMeshSequence` yields the file a chunk at a time (its header then says 0 total frames), so a long bake read file by
927
+ file never sits in memory whole. A frame with an index past its vertices, a non-finite position, or normals or UVs of the
928
+ wrong size is refused by number. From the command line, `margo-convert sequence <folder>` does the same for a folder of
929
+ per-frame OBJ, PLY or STL files (Blender's OBJ export with Animation on, a fluid add-on's mesh export).
930
+
931
+ ```ts
932
+ import {GeometryCachePlayer, encodeMeshSequence} from 'margoengine/animation/geometry-cache';
933
+ import {createStage} from 'margoengine';
934
+
935
+ const stage = await createStage('#viewport', {backend: 'webgpu', capacity: 2048});
936
+ // A fan whose triangle count grows each frame, as a fluid surface's does.
937
+ const fan = (sides: number, z: number) => {
938
+ const positions = new Float32Array((sides + 1) * 3), indices: number[] = [];
939
+ for (let s = 0; s < sides; s++) {
940
+ const a = (s / sides) * Math.PI * 2;
941
+ positions.set([Math.cos(a), Math.sin(a), z], (s + 1) * 3);
942
+ indices.push(0, s + 1, ((s + 1) % sides) + 1);
943
+ }
944
+ return {positions, indices: new Uint32Array(indices)};
945
+ };
946
+ const file = await encodeMeshSequence(24, [fan(6, 0), fan(6, 0.1), fan(9, 0.2), fan(12, 0.3)]);
947
+ const water = await GeometryCachePlayer.attach(stage.engine, file);
948
+ ```
949
+
950
+ The format is little endian. A 16 byte header holds the magic `MGCH`, version 1, frames per second (f32) and the total
951
+ frames (0 if unknown). Chunks follow, each a 64 byte header and its payload.
952
+
953
+ | Chunk header offset | Field |
954
+ | --- | --- |
955
+ | 0 | magic `CHNK` |
956
+ | 4 | payload bytes |
957
+ | 8 | first frame, which must follow the last chunk's end |
958
+ | 12 | frame count |
959
+ | 16 | vertex count, 3 to 1,000,000 |
960
+ | 20 | index count, 0 to repeat the last chunk's triangles |
961
+ | 24 | flags: 1 normals stored, 2 UVs stored |
962
+ | 32 | bounds over the chunk: min xyz, max xyz (f32) |
963
+
964
+ The payload is the indices (u32), then UVs (2 floats a vertex), positions (3 floats a vertex, all frames), then normals
965
+ (same shape). A chunk without normals gets smooth ones when it is read; a chunk without UVs repeats the last chunk's if the
966
+ vertex count matches, else zero. A damaged or cut off file rejects with a `failed` error, and a bad chunk header is refused
967
+ before its payload is held.
968
+
969
+ ## Cloning and retargeting (`@margoengine/animation/skeleton-utils`)
970
+
971
+ Cloning skinned models and retargeting poses and clips between skeletons, in their own entry:
972
+
973
+ ```ts
974
+ import {Animation, Skeleton, createKeyframeClip, applyKeyframeClip} from 'margoengine/animation';
975
+ import {Retarget, cloneModel, retargetRig} from 'margoengine/animation/skeleton-utils';
976
+ import {createStage} from 'margoengine';
977
+ import {loadGLTF} from 'margoengine/gltf/pbr';
978
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
979
+ // Copy this repository's CC0 RobotExpressive asset to the same public URL in your app.
980
+ const robot = await loadGLTF(stage.engine, '/examples/assets/robot-expressive.glb');
981
+
982
+ const second = await cloneModel(robot); // own nodes and skeleton; shares the parsed asset
983
+ Animation.attach(second).play('Dance'); // animates apart from `robot`
984
+
985
+ // Explicit miniature rigs make the required names and reference poses reproducible.
986
+ const source = new Skeleton([
987
+ {name: 'mixamorig:Hips', parent: -1, translation: [0, 1, 0]},
988
+ {name: 'mixamorig:Spine', parent: 0, translation: [0, 0.5, 0]},
989
+ ]);
990
+ const hero = new Skeleton([
991
+ {name: 'Hips', parent: -1, translation: [0, 2, 0]},
992
+ {name: 'Spine', parent: 0, translation: [0, 1, 0]},
993
+ ]);
994
+ const retarget = new Retarget(retargetRig(source), retargetRig(hero), {
995
+ names: {Hips: 'mixamorig:Hips', Spine: 'mixamorig:Spine'},
996
+ hip: 'Hips', // follows the source hips' movement, scaled by the rest hip heights unless hipScale is given
997
+ });
998
+ source.setPose(0, {translation: [0.3, 1, 0]});
999
+ retarget.apply(source, hero); // hero's hips now move 0.6 along x
1000
+ const sourceClip = createKeyframeClip({name: 'Walk', tracks: [{
1001
+ target: 'mixamorig:Hips', path: 'translation', keys: [
1002
+ {time: 0, value: [0, 1, 0]}, {time: 1, value: [1, 1, 0]},
1003
+ ],
1004
+ }]});
1005
+ const walk = retarget.clip(sourceClip, {fps: 30});
1006
+ applyKeyframeClip(walk, hero, 0.5);
1007
+ ```
1008
+
1009
+ `cloneModel(model)` resolves to a new `PBRModel` with its own root and nodes, starting in the source's current local
1010
+ transforms, visibility and morph weights, and registered with the engine when the source is. It shares the source's
1011
+ parsed asset (document, buffers, accessors), decoded images and packed vertex arrays. Copies share the GPU textures of
1012
+ those images, the GPU vertex and index buffers of those arrays and, once animated, the deformation inputs (bind-pose
1013
+ vertices, morph deltas, skin influences), so a clone uploads no geometry and no texture; what it adds on the GPU is its
1014
+ own deformed output, weights, bones, uniforms and bind groups. Disposing any model, source included, leaves the others
1015
+ working: each image, texture and buffer goes with its last holder. Materials are rebuilt from the document, so runtime material edits on the source are not copied.
1016
+
1017
+ A copy costs no engine tick, so spawning a crowd does not touch the rest of the scene: it takes the source's baked
1018
+ static batches instead of baking its own. Its world matrices therefore publish with the next tick. Every frame and
1019
+ pick runs one first, as do `model.bounds`, `extras()`, `clusteredLights()`, `readPickingGeometry()` and `compile()`, so
1020
+ only a direct read of `node.matrix` right after `cloneModel` sees the old value, as after any `setPosition`. A source
1021
+ that was moved since baking, or has a parent, costs its copy one tick to bake for itself.
1022
+
1023
+ `retargetRig(skeletonOrModel)` reads a bone hierarchy and its current local pose, which becomes the rig's rest pose; a
1024
+ model's rig is every node, so armature and mesh nodes count toward bone orientations. `new Retarget(source, target,
1025
+ options)` maps target bones to source bones by name (`names` overrides, `''` leaves a bone at rest; unnamed glTF nodes
1026
+ map only through `names`). Each mapped target bone turns in model space by the rotation its source bone has turned
1027
+ from rest, which absorbs different bone axes and rest orientations; bones keep their own lengths and scales, unmapped
1028
+ bones keep their rest local pose, and the `hip` bone's position follows the source hip's movement times `hipScale`.
1029
+ `hold: ['LeftHandIndex1', ...]` names unmapped bones that `apply` writes at the target rig's rest rotation and `clip`
1030
+ keys, for a rig whose rest is not the pose the target holds now; `@margoengine/rigging`'s `prepareRetarget` returns
1031
+ the list for the finger bones it lays along a fingerless source hand.
1032
+ `pose(sourceLocal, out?)` does this on raw arrays (10 numbers per bone: translation, quaternion, scale) without
1033
+ allocating, `apply(source, target)` reads and writes Skeletons or models, and `clip(source, {fps, name})` samples a
1034
+ source `KeyframeClip`, or a glTF clip through the source model's `Animation` (restoring its clip, time and playing
1035
+ state), into a target `KeyframeClip` with a rotation track per mapped bone and a translation track for the hip. Both
1036
+ characters' model spaces must face the same way; morph weight tracks are not carried over.
1037
+ `tests/retarget.test.js` checks analytic poses (bone directions, lengths, scaled hip motion, unmapped bones) across
1038
+ renamed rigs with different bone axes, and models driven by their `Animation`.
1039
+
1040
+ ### Scene of the result
1041
+
1042
+ `cloneModel` makes the copy in the scene of its source model (the scene the source is registered in), so a clone of a model in a second scene stays beside it, whichever scene is active when you call it. An abort or a failure leaves nothing in either scene.
1043
+
1044
+ ## Mixer: blended actions (`@margoengine/animation/mixer`)
1045
+
1046
+ `AnimationMixer` plays several clips on one root at the same time and blends them per property. The root is a
1047
+ model, an `Animation`, a `Skeleton`, or a plain object that hosts bound property tracks. `AnimationMixer.attach(engine,
1048
+ root)` registers the mixer with the engine, so its clock advances in each frame. `new AnimationMixer(root)` builds the
1049
+ same mixer unregistered, for a caller that drives it with `update(delta)` or `advanceTime(delta)`. Attaching a model
1050
+ makes an `Animation` for it and pauses that `Animation`, so the mixer alone poses the model. Transform tracks need a
1051
+ `Skeleton` or `Animation` root; a plain object takes property tracks only (clips from `createKeyframeClip`).
1052
+
1053
+ ```ts
1054
+ import {createStage} from 'margoengine';
1055
+ import {loadGLTF} from 'margoengine/gltf/pbr';
1056
+ import {AnimationMixer} from 'margoengine/animation/mixer';
1057
+ const stage = await createStage('#viewport', {backend: 'webgpu', capacity: 2048});
1058
+ const model = await loadGLTF(stage.engine, '/RobotExpressive.glb');
1059
+ const mixer = AnimationMixer.attach(stage.engine, model);
1060
+ const idle = mixer.clipAction('Idle').play();
1061
+ const walk = mixer.clipAction('Walking').play();
1062
+ idle.crossFadeTo(walk, 0.5); // idle fades out and walking fades in over half a second
1063
+ walk.setDuration(2); // one walking cycle takes 2 s
1064
+ mixer.dispose(); // restores the original pose and disposes the Animation the mixer made
1065
+ model.dispose();
1066
+ stage.dispose();
1067
+ ```
1068
+
1069
+ ### Exports
1070
+
1071
+ - `AnimationMixer` (class). `static attach(engine, root)` creates, registers and returns a mixer; disposing it removes
1072
+ its registration. `time` (default `0`) is the global clock in seconds and `timeScale` (default `1`) its signed rate.
1073
+ `clipAction(clip, root = the mixer's root, blendMode = NormalAnimationBlendMode)` returns the cached action for that
1074
+ clip, root and blend mode, creating it once; `clip` is a glTF clip name or index (an `Animation` root), or an
1075
+ `ActionClip` object. `existingAction(clip, root?)` returns the cached action or `null` and never creates one.
1076
+ `update(delta)` advances the clocks and blends once; `advanceTime(delta)` moves the clocks without writing a pose;
1077
+ `setTime(time)` rewinds every action and seeks to `time`; `stopAllAction()` stops every action and restores the
1078
+ original pose. `uncacheAction(clip, root?)`, `uncacheClip(clip)` and `uncacheRoot(root)` drop cached actions (stop
1079
+ them first); `uncacheRoot` also disposes the `Animation` the mixer made for that root. `getRoot()` returns the default
1080
+ root. `dispose()` and `[Symbol.dispose]()` stop everything, restore the originals and dispose only the `Animation`s
1081
+ the mixer created, never the model. The engine calls `setup(engine)` and `onPreUpdate(delta)`, its plugin hooks.
1082
+ - `AnimationAction` (class), made by `clipAction`. Options with their defaults: `time` (`0`), `timeScale` (`1`),
1083
+ `weight` (`1`), `enabled` (`true`), `paused` (`false`), `clampWhenFinished` (`false` disables the action when it ends;
1084
+ `true` holds its end pose), `loop` (`LoopRepeat`) and `repetitions` (`Infinity`). `blendMode` is
1085
+ read-only and set at creation. Methods: `play()` starts or resumes without resetting the clock; `stop()` stops, restores
1086
+ the original pose on the next update and rewinds; `reset()` rewinds and clears envelopes; `startAt(time)` delays the
1087
+ start to a mixer time; `isScheduled()` reports whether `play()` was called and not stopped, and `isRunning()` also needs it enabled, at a non-zero rate and past its `startAt` time; `getClip()`,
1088
+ `getMixer()`, `getRoot()`, `getEffectiveWeight()` and `getEffectiveTimeScale()` read it back;
1089
+ `setEffectiveWeight(weight)` sets the weight and cancels a fade, `setEffectiveTimeScale(scale)` sets the rate and cancels a warp;
1090
+ `setDuration(seconds)` sets the time scale so one pass takes `seconds` (positive); `syncWith(action)` copies another
1091
+ action's clock and rate; `setLoop(mode, repetitions = Infinity)` takes `LoopOnce`, `LoopRepeat` or `LoopPingPong` and a
1092
+ count of at least 1; `fadeIn(duration)` and `fadeOut(duration)` ramp the weight from 0 to 1 or 1 to 0 (`fadeIn` does
1093
+ not start the action: call `play()`); `stopFading()` cancels a fade; `warp(from, to, duration)` ramps the rate from
1094
+ `from` to `to` over `duration` seconds; `halt(duration)` slows the rate to 0 over `duration`; `stopWarping()` cancels
1095
+ a warp; `crossFadeTo(action, duration, warp = false)` fades this action out and `action` in, and `crossFadeFrom(action,
1096
+ duration, warp = false)` does the same from the other side. `warp` matches the two cycle rates during the fade (both
1097
+ clips need a positive duration). `step`, `contribute`, `uses`, `usesDiscrete` and `rewind` are the mixer's own
1098
+ per-frame hooks; app code does not call them.
1099
+ - `LoopOnce` (`2200`): play once, clamped at the end. `LoopRepeat` (`2201`): repeat from the opposite end. This is the
1100
+ default. `LoopPingPong` (`2202`): alternate forward and backward passes.
1101
+ - `NormalAnimationBlendMode` (`2500`): weighted replacement, with the original pose filling the weight below one. This
1102
+ is the default. `AdditiveAnimationBlendMode` (`2501`): adds translation and property deltas, multiplies scale deltas
1103
+ and composes rotation deltas. Categorical (boolean or string) tracks have no additive arithmetic and throw with it.
1104
+ - Types: `ActionLoop` (the three loop constants), `ActionClip` (a glTF clip, a `KeyframeClip` or a discrete clip) and
1105
+ `MixerRoot` (`object`).
1106
+
1107
+ Blending normalises by the total weight of the actions that touch a property, so two full-weight actions average, and a
1108
+ property that no action touches returns to its original value.
1109
+
1110
+ ## Film time: seeking animation to a cut
1111
+
1112
+ `Animation`, `PlaybackAnimation`, `AnimationGroup`, `AnimationMixer`, `AnimationLOD`, `MorphWeightPlayer`, `VATCrowd`
1113
+ and `GeometryCachePlayer` have `advanceTime(delta)`, the CPU part of their frame update, and a `time` that reads 0 on a
1114
+ fresh clock. A replayed step moves the clip clock (loops, ends, fades, warps, start times, LOD turns) and poses nothing;
1115
+ the next frame update poses the place reached. So `seek` from `@margoengine/cutscene/seek` lands a fresh scene on the
1116
+ pose a continuous run shows there, bit for bit to 54,000 steps (`tests/seek.test.js`, `tests/geometry-cache.test.js`).
1117
+ A replayed `PlaybackAnimation` sends no `loop` or `finished` event (a replayed end still settles `finished`).
1118
+ `AnimationLOD` gives the same turns when the camera is where the continuous run had it. `GeometryCachePlayer` waits for a
1119
+ chunk it does not hold only in a live update, so seek a cache whose file is held in memory (`await player.done`).
1120
+ Behaviour graphs (`interactivity`) have no `advanceTime`: they fire listeners and random nodes, so `seek` lists them in
1121
+ `unseekable` and they start at the cut.
1122
+
1123
+ ```ts
1124
+ import {createStage} from 'margoengine';
1125
+ import {loadGLTF} from 'margoengine/gltf/pbr';
1126
+ import {Animation} from 'margoengine/animation';
1127
+ import {seek} from 'margoengine/cutscene/seek';
1128
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
1129
+ const hero = await loadGLTF(stage.engine, '/hero.glb');
1130
+ const walk = Animation.attach(hero, {speed: 1.2});
1131
+ // The scene starts 95 s into the film: replay the clocks, then the first frame poses what a continuous run poses there.
1132
+ const {clocks, unseekable} = await seek(stage.engine, 95, {fps: 60});
1133
+ console.log(walk.time, clocks, unseekable);
1134
+ ```
1135
+
1136
+ ## Saving and restoring playback
1137
+
1138
+ `animation.captureState()` returns where an `Animation` is as plain JSON: `{version: 1, clip, time, playing, loop,
1139
+ speed}`. `restoreState(state)` puts a player back there, for a save game, an undo step, a hot reload or a second
1140
+ `Animation` of the same model. A snapshot is a copy: later playback does not change it.
1141
+
1142
+ ```ts
1143
+ import {createStage} from 'margoengine';
1144
+ import {loadGLTF} from 'margoengine/gltf/pbr';
1145
+ import {Animation} from 'margoengine/animation';
1146
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
1147
+ const hero = await loadGLTF(stage.engine, '/hero.glb');
1148
+ const walk = Animation.attach(hero, {loop: false, speed: 1.5});
1149
+ walk.seek(0.4).playing = false; // paused at 0.4 s
1150
+ const saved = JSON.stringify(walk.captureState()); // {"version":1,"clip":0,"time":0.4,"playing":false,"loop":false,"speed":1.5}
1151
+ walk.play(0); // later: start the clip over from 0 s
1152
+ walk.restoreState(JSON.parse(saved)); // the pose at 0.4 s, paused, no loop, speed 1.5
1153
+ console.log(walk.time, walk.captureState().playing); // 0.4 false
1154
+ ```
1155
+
1156
+ - `clip` is the clip's index in `animation.clips`, the order of the glTF file's `animations`, so a snapshot belongs
1157
+ to that model, or one loaded from the same file. Keep the clip's name beside it (`animation.clips[state.clip].name`)
1158
+ if the file can change between saves.
1159
+ - `time` is the clip clock in seconds, as `seek` takes it; restoring poses the model at that time at once, then
1160
+ `playing` decides whether the clock runs on. `loop` and `speed` are the player's options and are restored with it,
1161
+ so they replace what the player was made with.
1162
+ - `restoreState` checks the whole snapshot before it changes anything: a version other than 1, a clip index the
1163
+ model does not have, a negative or non-finite time or speed, or a missing field throws a MargoError with code
1164
+ `state`, and the player stays as it was. Either call on a disposed player throws (`disposed` for `captureState`).
1165
+ - Node transforms are not part of the snapshot: the pose comes from the clip at `time`. Bones moved by other code
1166
+ (IK, an `Animator`, spring bones) keep their own state; `@margoengine/animator` captures its graphs with its own
1167
+ `captureState`.
1168
+
1169
+ ## Preview tier contract
1170
+
1171
+ The small `@margoengine/webgl2-compat/preview` renderer reports `backend: 'webgl2'` and has no GPU device. GPU-only attachments throw a linked `MargoError` with code `unsupported` before allocating resources. Native WebGPU and the full WebGL2 compatibility layer both report `backend: 'webgpu'`. Use [`autoEngine` with `loadCompat`](../webgl2-compat/README.md#automatic-escalation) during scene setup to select a complete tier automatically.
1172
+
1173
+ This includes `VATCrowd` (and its crowd subclasses) and `MorphWeightPlayer`.