@margoengine/cutscene 0.0.0-stage → 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,3 +1,774 @@
1
- # Temporary Holding Version
1
+ # @margoengine/cutscene
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Import `margoengine/cutscene` from the `margoengine` package, or `@margoengine/cutscene` 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
+ A timeline sequencer for cutscenes and in-game cinematics: tracks of keys and clips in a JSON document, a pure
6
+ `evaluate(t)` that gives the whole scene state at any time, and a player with play, pause, reverse, speed, scrubbing,
7
+ skip and fast-forward that fires every event in order. It renders nothing itself and imports nothing heavy: apply the
8
+ state to your camera, objects, animation mixer, audio and UI.
9
+
10
+ ```ts
11
+ import { Camera } from 'margoengine/core';
12
+ import { CutscenePlayer, type CutsceneDocument } from 'margoengine/cutscene';
13
+
14
+ const intro: CutsceneDocument = {
15
+ format: 'margo-cutscene',
16
+ version: 1,
17
+ duration: 6,
18
+ markers: [{ time: 3, name: 'reveal' }],
19
+ tracks: [
20
+ {
21
+ type: 'camera',
22
+ id: 'cam',
23
+ keys: [
24
+ { time: 0, position: [0, 2, 8], target: [0, 1, 0] },
25
+ { time: 3, position: [5, 3, 4], target: [0, 1, 0], ease: 'easeInOutCubic' },
26
+ { time: 4, position: [0, 1.6, 2], target: [0, 1.5, 0], fov: 35, cut: true },
27
+ ],
28
+ },
29
+ { type: 'transform', id: 'door', target: 'door', keys: [{ time: 3, rotation: [0, 0, 0, 1] }, { time: 4, rotation: [0, 0.7071, 0, 0.7071] }] },
30
+ { type: 'animation', id: 'hero', target: 'hero', clips: [{ start: 0, duration: 6, clip: 'Walk', loop: true, length: 1.2 }] },
31
+ { type: 'audio', id: 'music', clips: [{ start: 0, duration: 6, sound: 'theme', fadeIn: 1 }] },
32
+ { type: 'subtitle', id: 'subs', clips: [{ start: 1, duration: 2, text: 'Someone left the door open.', speaker: 'Ada' }] },
33
+ { type: 'event', id: 'cues', events: [{ time: 3.5, name: 'spawnBats', data: { count: 12 } }] },
34
+ ],
35
+ };
36
+
37
+ const camera = new Camera();
38
+ const player = new CutscenePlayer(intro);
39
+ player.on('event', (event) => console.log('event', event.name, event.data));
40
+ player.on('marker', (marker) => console.log('marker', marker.name));
41
+ const done = player.play();
42
+
43
+ // Each frame:
44
+ player.update(1 / 60);
45
+ const state = player.state;
46
+ if (state.camera) {
47
+ camera.position = state.camera.position;
48
+ camera.target = state.camera.target;
49
+ camera.fov = state.camera.fov;
50
+ camera.up = state.camera.up;
51
+ }
52
+ // state.transforms.door.rotation, state.animations, state.audio, state.subtitles: apply them the same way.
53
+
54
+ player.skip(); // "Skip cutscene": jumps to the end and still fires spawnBats and the marker, in order.
55
+ await done; // true: it finished
56
+ ```
57
+
58
+ ## Tracks
59
+
60
+ Every track has an `id` (unique in its timeline) and may be `muted`. Key tracks interpolate between keys sorted by
61
+ `time`, holding the first value before the first key and the last after the last; `ease` on a key shapes the move into
62
+ it (`'linear'` default, `'step'`, `'smoothstep'`, any `ease*` easing of `@margoengine/tween` such as
63
+ `'easeOutBack'`, or cubic-bezier points `[x1, y1, x2, y2]`). Clip tracks hold spans `start` + `duration` (start
64
+ inclusive, end exclusive) that may overlap.
65
+
66
+ | Track | Fields | State |
67
+ | --- | --- | --- |
68
+ | `camera` | `keys: [{time, position, target, fov?, roll?, ease?, cut?}]`, `path` (`'catmull-rom'` default, `'linear'`) | `camera`: `position`, `target`, `fov` (degrees, default 60), `roll`, `up` |
69
+ | `transform` | `target`, `keys: [{time, position?, rotation?, scale?, ease?}]` | `transforms[target]`; each channel among the keys that set it; rotations slerp |
70
+ | `property` | `target`, `property`, `keys: [{time, value, ease?}]` (a number or an array) | `properties[target][property]` |
71
+ | `animation` | `target`, `clips: [{start, duration, clip, speed?, offset?, loop?, length?, blendIn?, blendOut?}]` | `animations`: clip name, clip time and blend weight |
72
+ | `audio` | `clips: [{start, duration, sound, volume?, offset?, fadeIn?, fadeOut?}]` | `audio`: sound, time into it, volume |
73
+ | `subtitle` | `clips: [{start, duration, text, speaker?}]` | `subtitles` |
74
+ | `event` | `events: [{time, name, data?}]` | fired by the player |
75
+ | `timeline` | `clips: [{start, duration, timeline, speed?, offset?}]` naming one of the document's `timelines` | the nested timeline's state, merged in |
76
+
77
+ Camera keys with `cut: true` jump instead of moving there, and the Catmull-Rom path never bends across a cut, so one
78
+ track holds a whole edit. The first unmuted camera track wins; a later transform or property track wins a channel two
79
+ tracks key. Markers name points in time; `state.marker` is the last one passed.
80
+
81
+ Nested timelines live under `timelines` and are placed by timeline clips with their own speed and offset; they may
82
+ nest (up to 16 levels, no cycles). Their tracks report paths like `intro/sfx`. A nested clip cut by the window of
83
+ its timeline clip still enters and exits, at the window's edges.
84
+
85
+ ## Evaluating, scrubbing and seeking
86
+
87
+ ```ts
88
+ import { Cutscene } from 'margoengine/cutscene';
89
+
90
+ const cutscene = new Cutscene({ format: 'margo-cutscene', version: 1, duration: 2, tracks: [
91
+ { type: 'property', id: 'fade', target: 'screen', property: 'opacity', keys: [{ time: 0, value: 1 }, { time: 2, value: 0 }] },
92
+ ] });
93
+ const half = cutscene.evaluate(1); // { time: 1, properties: { screen: { opacity: 0.5 } }, ... }
94
+ const passed = cutscene.eventsBetween(0, 2); // instants in the order they are passed
95
+ ```
96
+
97
+ `evaluate(t)` is a pure function of the document and `t`: it keeps no playback state and returns a new object, so a
98
+ scrub bar, a seek, a reversed playback and a straight play reach exactly the same state at the same time. Documents
99
+ are validated and deep-frozen when loaded, so they cannot change underneath.
100
+
101
+ Instants are custom events, markers and clip starts (`enter`) and ends (`exit`), nested ones included, each with its
102
+ time on the top-level timeline. `eventsBetween(from, to)` returns them in a fixed order (time, then exits, markers,
103
+ events, enters, then document order); splitting a range anywhere returns the same list, so the frame rate never
104
+ changes what fires. Backwards ranges return them latest first.
105
+
106
+ ## Seeking a world to film time
107
+
108
+ A film rendered scene by scene starts each scene in a fresh process. The clouds, wind, waves, wetness and lightning
109
+ all add up frame deltas, so without help they restart at 0 at every cut and the sky jumps. `@margoengine/cutscene/seek`
110
+ brings a fresh world to film time T: it replays every clock's `advanceTime(1 / fps)` in the same order a continuous run
111
+ made, without drawing, so the next frame draws what a run started at 0 draws at T, bit for bit.
112
+
113
+ ```ts
114
+ import { Engine, type EngineKernel } from 'margoengine/core';
115
+ import { seek } from 'margoengine/cutscene/seek';
116
+
117
+ const engine = await Engine.create(document.querySelector('canvas')!, { backend: 'webgpu' });
118
+ // A time-driven plugin: its frame update runs advanceTime, so a live frame and a replayed step do the same sums.
119
+ class Drift {
120
+ name = 'drift';
121
+ time = 0;
122
+ offset = 0;
123
+ setup(_engine: EngineKernel) {}
124
+ advanceTime(delta: number) {
125
+ this.time += delta;
126
+ this.offset += delta * 8;
127
+ }
128
+ onPreUpdate(delta: number) {
129
+ this.advanceTime(delta);
130
+ }
131
+ }
132
+ engine.use(new Drift());
133
+ // Scene 2 starts 95 s into the film: replay the clocks to there, then draw on as a continuous run would.
134
+ const { steps, clocks, unseekable } = await seek(engine, 95, { fps: 30 }); // 2850, ['drift'], []
135
+ engine.render({ delta: 1 / 30 });
136
+ ```
137
+
138
+ - A clock is any plugin with `advanceTime(delta)` and a `time` getter (seconds since it started). `advanceTime` is the
139
+ CPU part of its frame update only: no GPU call, no listener call (a replayed lightning strike stays silent).
140
+ - `seek(engine, seconds, { fps = 60, steps, scenes, extra, onStep, signal })` runs `Math.round(seconds * fps)` steps
141
+ of `1 / fps` (or the `steps` you list, each 0 to 1 second: the deltas a sub-framed film's renders gave, from
142
+ `subFrameSteps` of `@margoengine/headless/accumulate`) over the
143
+ plugins of each scene (default `[engine.scene]`) in attach order, then `extra` (clocks that are not plugins, such as
144
+ an unattached `WeatherMachine`). `onStep(step, time)` runs before each step, so film code can set what the clocks
145
+ read (a wind, a rate) as it did live. It resolves with the steps, the clocks it moved and `unseekable`: plugins with
146
+ a frame update but no `advanceTime`, which restart at a seek.
147
+ - Every clock must read 0: seek a fresh world once, before its first frame. A clock that already moved throws a
148
+ `MargoError` with code `state` ([film-seek](https://margoengine.com/errors#film-seek)).
149
+ - `advanceTime(engine, delta, { scenes, extra })` runs one step, for a host that runs its own loop.
150
+ - `seekSync(engine, seconds, options)` is the same seek without waiting (no `onStep`), for code that cannot await.
151
+ - `renderCutscene(engine, cutscene, { from })` with `from` after 0 seeks the engine first, in steps of the render's
152
+ `1 / fps` (with `samples` or `shutter`, the sub-frames' own steps), so its first frame equals the frame at `from`
153
+ of a render from 0; `cutsceneFrames(cutscene, { from,
154
+ engine })` does the same when you pass the engine you draw with. Until 2026-11-16 both started every clock at 0.
155
+ - Cost: steps x clocks calls, CPU only: 15 minutes at 60 fps is 54,000 steps. Rates of 1 or more steps per second.
156
+ - Exact only for state that is a clock. History on the GPU (particles alive, foam, ripples) and history of the view
157
+ (TAA, auto exposure) come from the scene's own warm-up frames; `docs/limits.md` lists each with its bound.
158
+
159
+ ### Several scenes in one process
160
+
161
+ A render worker that keeps one process for several scenes (fresh processes cost 2 to 3 s each) puts the clocks back
162
+ to 0 with `resetClocks(engine)` and then seeks the next scene's start time (GAP-FILM-RESET):
163
+
164
+ ```ts
165
+ import { Engine } from 'margoengine/core';
166
+ import { resetClocks, seekSync } from 'margoengine/cutscene/seek';
167
+
168
+ const engine = await Engine.create(document.querySelector('canvas')!, { backend: 'webgpu' });
169
+ seekSync(engine, 95, { fps: 30 }); // scene 2
170
+ engine.render({ delta: 1 / 30 });
171
+ // Scene 3 starts at 40 s: back to 0, then the seek a fresh world would make.
172
+ const { clocks, unresettable } = resetClocks(engine);
173
+ seekSync(engine, 40, { fps: 30 });
174
+ engine.render({ delta: 1 / 30 });
175
+ ```
176
+
177
+ - A clock that can go back has `resetTime()`: its time, counters, seeds and history (TAA, auto exposure, fog history)
178
+ return to what a new one with the same options holds; its options and GPU resources stay. A seek after the reset
179
+ then gives what a fresh world seeked as far gives.
180
+ - `resetClocks(engine, { scenes, extra })` runs `resetTime` on every clock of the scenes and `extra`, and returns the
181
+ `clocks` it reset and `unresettable`: clocks with no `resetTime` yet and plugins with a frame update but no clock.
182
+ Those keep their time, so a seek after the reset refuses the clocks among them; use a fresh process while a scene
183
+ holds one.
184
+ - Clocks with `resetTime` today: `TAA`, `TAAUpscale`, `Tonemap`, `Shadows`, `VirtualShadows` (and their
185
+ `lightPattern`), `HeatHaze`, `Stylize`, `Reflector`, `Refractor`, `VolumetricFog`, `Lines` and `Trail`, creative
186
+ `PostProcessing`, `LODSystem`, `XRaySelection`, `ShaderClock`, `Scatter` and `ScatterInstances`, every sky clock
187
+ (`Sky`, `HillaireSky`, `AstroSky`, `Aurora`, `TornadoCloud`, `VolumetricClouds`, `Weather`), every water clock
188
+ (`Water`, `FFTOcean`, `WaterFlow`, `WaterRain`, `ShipWakes`, `ShotSplash`, `Floater`, `Iceberg`, `SeaIce`, `Flood`)
189
+ every vfx clock (`VFX`, `BlownSand`, `Clouds`, `Flame`, `Smoke`, `FireFront`, `Battery`, `HullFire`) and every
190
+ weather clock (`WeatherMachine`, `WeatherDrive`, `WeatherRegions`, `Hail`, `LensDrops`, `Puddles`, `GLTFWeather`,
191
+ `Eruption`, `LavaFlow`, `Avalanche`, `SnowDrift`). The rest are listed in
192
+ `tests/film-reset-pending.json`, which only shrinks.
193
+
194
+ ## Film captions and chapter cards
195
+
196
+ A documentary shows its words on film time: captions under the narration, a chapter card at each chapter ("03 / 13",
197
+ the title and a place and date line) and a closing card. `@margoengine/cutscene/film-titles` draws them with
198
+ `@margoengine/ui`, as a pure function of film time, so a film rendered shot by shot (each shot a fresh page started at
199
+ its own film time) shows exactly what one continuous run shows at that second.
200
+
201
+ ```ts
202
+ import { Engine } from 'margoengine/core';
203
+ import { FilmTitles, filmTitlesAt } from 'margoengine/cutscene/film-titles';
204
+ import { parseSrt } from 'margoengine/text/captions';
205
+ import { Ui, UiRenderer } from 'margoengine/ui';
206
+
207
+ const engine = await Engine.create(document.querySelector('canvas')!, { backend: 'webgpu' });
208
+ const ui = new Ui({ scale: { reference: [1920, 1080], match: 0.5 } });
209
+ UiRenderer.attach(engine, ui);
210
+ const srt = '1\n00:00:01,000 --> 00:00:04,000\nNovember 1944.\n';
211
+ const titles = new FilmTitles(ui, {
212
+ title: 'Fauld',
213
+ cues: parseSrt(srt).cues,
214
+ chapters: [
215
+ { start: 0, title: 'Cold open', card: false },
216
+ { start: 43, title: 'Gentle country', place: 'Fauld, Staffordshire, 1944' },
217
+ ],
218
+ chapterCount: 13,
219
+ closing: { start: 880 },
220
+ });
221
+ // A shot that starts 44 s into the film shows the card "01 / 13" from its first frame.
222
+ let filmTime = 44;
223
+ engine.onFrame((_, dt) => {
224
+ filmTime += dt;
225
+ titles.update(filmTime);
226
+ });
227
+ filmTitlesAt(titles.spec, 2).caption; // { text: 'November 1944.', opacity: 1 }
228
+ ```
229
+
230
+ - Cues are `{ start, end, text }`, `[start, end, text]` tuples or the cues of `@margoengine/text/captions`
231
+ (`{ start, end, lines }`, lines joined by newlines), in seconds, `end` exclusive; order does not matter, and where two
232
+ overlap the one that starts first shows.
233
+ - Captions and cards fade in over `fadeIn` (default 0.22 s) and out over `fadeOut` (default 0.24 s), each held inside
234
+ half of a short cue so it still reaches full opacity. The closing card fades in over `closingFade` (default 1 s) and
235
+ stays.
236
+ - Chapters are in film order. A card numbers each chapter by its place in the list from `firstNumber` (default 0, so a
237
+ cold open is 00) unless it sets `number`; the count is `chapterCount` (default the highest number), both padded to
238
+ two digits. A card holds `chapterHold` seconds (default 4, or the chapter's `hold`) and ends early at the next
239
+ chapter; `card: false` shows none.
240
+ - The closing card's lines default to `defaultClosingLines(title)`: "Made with Margo Engine", the title and "Please
241
+ subscribe"; pass `closing.lines` (`{ text, size, color }`) for others.
242
+ - The third argument sets the looks (`captionSize` 39, `titleSize` 64, `placeSize` 32, `numberSize` 30, `background`
243
+ `#111a23cf`, `captionMargin` `[0, 0, 74, 97]`, `cardMargin` `[0, 0, 200, 98]`, for a 1920 by 1080 reference UI).
244
+ - A bad spec throws a `TypeError` when it is made ([film-titles](https://margoengine.com/errors#film-titles));
245
+ `checkFilmTitles(spec)` checks one without drawing. `dispose()` (or `using`) removes the panels from the UI, and
246
+ `update` after it throws a `MargoError` with code `disposed`.
247
+
248
+ ## Playing
249
+
250
+ `CutscenePlayer` adds a time and a signed `speed` (negative plays backwards; `reverse()` flips it) and fires
251
+ instants as `update(delta)` passes them. `seek(t)` scrubs and fires nothing; `skip(t)` (default: the end) and
252
+ `fastForward(seconds)` fire everything on the way, in order. `loop: true` wraps at the ends. `play({signal})` returns
253
+ a promise that resolves `true` when playback finishes and `false` when paused or stopped first, and rejects with the
254
+ signal's reason on abort. Listen with `on('event' | 'marker' | 'enter' | 'exit' | 'finish' | '*', listener)` (it
255
+ returns an unsubscribe function), or stream:
256
+
257
+ ```ts
258
+ import { CutscenePlayer } from 'margoengine/cutscene';
259
+
260
+ const cues = new CutscenePlayer({ format: 'margo-cutscene', version: 1, duration: 1, tracks: [
261
+ { type: 'event', id: 'cues', events: [{ time: 0.5, name: 'flash' }] },
262
+ ] });
263
+ const controller = new AbortController();
264
+ const reader = (async () => {
265
+ for await (const event of cues.events({ signal: controller.signal })) console.log(event.name);
266
+ })();
267
+ void cues.play();
268
+ cues.update(1);
269
+ await reader; // the stream ends when the player finishes
270
+ ```
271
+
272
+ A listener that seeks or skips takes over: the rest of that step's instants are not fired. `update` from inside a
273
+ listener throws `MargoError` `'state'`. `using player = new CutscenePlayer(...)` disposes it at the end of the scope.
274
+
275
+ ## Virtual camera shots
276
+
277
+ `@margoengine/cutscene/shots` adds a `shot` track: name your cameras once, then write the edit as shots that cut or
278
+ blend from one to the next, instead of keying raw camera transforms. Both cameras keep moving through a blend.
279
+
280
+ ```ts
281
+ import { CutscenePlayer } from 'margoengine/cutscene';
282
+ import { shotOf, shotTrack, type ShotTrack } from 'margoengine/cutscene/shots';
283
+
284
+ const edit: ShotTrack = {
285
+ type: 'shot',
286
+ id: 'edit',
287
+ cameras: {
288
+ wide: { position: [0, 3, 12], target: [0, 1, 0], fov: 50 },
289
+ dolly: {
290
+ keys: [
291
+ { time: 0, position: [-6, 1.5, 4], target: [0, 1, 0] },
292
+ { time: 4, position: [-2, 1.5, 4], target: [0, 1, 0], fov: 35 },
293
+ ],
294
+ },
295
+ chase: { follow: 'hero', position: [0, 2, 5], lookAt: 'hero', lookOffset: [0, 1, 0] },
296
+ game: { live: 'game' },
297
+ },
298
+ clips: [
299
+ { start: 0, duration: 2, camera: 'game' },
300
+ { start: 2, duration: 3, camera: 'wide', blendIn: 1.5 },
301
+ { start: 5, duration: 4, camera: 'dolly' },
302
+ { start: 9, duration: 3, camera: 'chase', blendIn: 1, blend: 'orbit', ease: 'easeInOutCubic' },
303
+ { start: 12, duration: 2, camera: 'game', blendIn: 1 },
304
+ ],
305
+ };
306
+ const heroPosition = [0, 0, 0];
307
+ const gameCamera = { position: [0, 2, 8], target: [0, 1, 0], fov: 60 };
308
+ const player = new CutscenePlayer(
309
+ { format: 'margo-cutscene', version: 1, duration: 14, tracks: [edit] },
310
+ {
311
+ tracks: [
312
+ shotTrack({
313
+ locate: (name) => (name === 'hero' ? { position: heroPosition } : undefined),
314
+ live: { game: () => gameCamera },
315
+ }),
316
+ ],
317
+ },
318
+ );
319
+ void player.play();
320
+ player.update(1 / 60);
321
+ const { camera } = player.state; // Apply it as any camera track's state: position, target, fov, up.
322
+ const shot = shotOf(player.state); // { camera: 'game', weight: 1, track: 'edit' }
323
+ ```
324
+
325
+ | Camera field | Meaning | Default |
326
+ | --- | --- | --- |
327
+ | `keys`, `path` | A camera move, the keys of a camera track with time 0 at the start of the shot | none, `'catmull-rom'` |
328
+ | `live` | A camera of the running game, from the `live` option, read at every evaluate, so a cutscene blends out of play and back | none |
329
+ | `position`, `target` | A fixed camera | `[0, 0, 0]`, needed unless `lookAt` is set |
330
+ | `follow`, `followRotation` | `position` is measured from this object, in its own axes when `followRotation` is true | none, `false` |
331
+ | `lookAt`, `lookOffset` | Aims at this object, plus the offset | none, `[0, 0, 0]` |
332
+ | `fov`, `roll` | Degrees and radians | `60`, `0` |
333
+
334
+ | Shot field | Meaning | Default |
335
+ | --- | --- | --- |
336
+ | `camera` | Key of the camera | required |
337
+ | `blendIn` | Seconds of blend from the shot before, up to the shot's `duration`; 0 is a cut | `0` |
338
+ | `ease` | Shape of the blend, any key `ease` | `'smoothstep'` |
339
+ | `blend` | `'direct'` moves the camera straight across and turns the view. `'orbit'` swings it around the point looked at, for two cameras on one subject | `'direct'` |
340
+ | `speed`, `offset` | Rate of the camera's move and seconds into it at the start of the shot | `1`, `0` |
341
+
342
+ Shots follow each other and may not overlap; in a gap the last one holds, and before the first the first shows. A
343
+ blend starts exactly on the old camera and ends exactly on the new one, and the view turns at even speed rather than
344
+ the target sliding, so the target never passes through the camera. A shot track sets `state.camera` in place of any
345
+ camera track, and the first unmuted shot track wins. Objects come from the document's transform tracks first, wherever
346
+ those tracks sit, then from `locate`; a shot needing an object or a live camera nothing provides throws a `RangeError`
347
+ naming the fix. Shots fire `enter` and `exit` like clips, and nested timelines cut them the same way. A shot has no
348
+ memory, so a follow camera sits exactly at its offset: for damped follow in play, use `@margoengine/cinematic` and
349
+ bring it in as a `live` camera.
350
+
351
+ ## Render to video
352
+
353
+ `@margoengine/cutscene/render` renders a cutscene at a fixed frame rate to a WebM or MP4 file with WebCodecs, for
354
+ trailers. Time is the render's own, so a slow machine makes the same frames as a fast one. It needs
355
+ `@margoengine/headless`, and the engine must sit on a `createHeadlessCanvas` canvas of the video's size, in a browser
356
+ or worker: Node has no WebCodecs.
357
+
358
+ ```ts
359
+ import { Camera, Engine, PbrMaterial, box } from 'margoengine/core';
360
+ import { Cutscene } from 'margoengine/cutscene';
361
+ import { renderCutscene } from 'margoengine/cutscene/render';
362
+ import { createHeadlessCanvas, installGPU } from 'margoengine/headless';
363
+
364
+ installGPU({ gpu: navigator.gpu });
365
+ const engine = await Engine.create(createHeadlessCanvas({ width: 1280, height: 720 }), { backend: 'webgpu' });
366
+ const cube = engine.createMesh().setGeometry(box()).setMaterial(new PbrMaterial({ color: '#e8d44d' }));
367
+ const trailer = new Cutscene({
368
+ format: 'margo-cutscene',
369
+ version: 1,
370
+ duration: 4,
371
+ tracks: [
372
+ { type: 'camera', id: 'cam', keys: [{ time: 0, position: [0, 1, 5], target: [0, 0, 0] }] },
373
+ { type: 'transform', id: 'spin', target: 'cube', keys: [{ time: 0, position: [-1, 0, 0] }, { time: 4, position: [1, 0, 0] }] },
374
+ { type: 'audio', id: 'music', clips: [{ start: 0, duration: 4, sound: 'theme', fadeOut: 1 }] },
375
+ ],
376
+ });
377
+ const theme = await new AudioContext().decodeAudioData(await (await fetch('theme.ogg')).arrayBuffer());
378
+
379
+ const video = await renderCutscene(engine, trailer, {
380
+ format: 'mp4',
381
+ fps: 60,
382
+ camera: new Camera(),
383
+ sounds: { theme },
384
+ apply(state) {
385
+ cube.setPosition(state.transforms.cube.position!);
386
+ },
387
+ onProgress: (done, total) => console.log(`${done} of ${total}`),
388
+ });
389
+ const url = URL.createObjectURL(new Blob([video.bytes], { type: video.mimeType }));
390
+ ```
391
+
392
+ | Option | Meaning | Default |
393
+ | --- | --- | --- |
394
+ | `apply(state, frame)` | Puts a frame's state on your scene; may be async | required |
395
+ | `camera` | Renders through this camera, set from `state.camera` before `apply` | the engine's, left to `apply` |
396
+ | `fps` | Frames per second; frame `i` shows `from + i / fps`, and the last starts before `to` | `30` |
397
+ | `from`, `to` | The span to render, seconds | the whole cutscene |
398
+ | `sounds` | The sounds the audio tracks name, as `AudioBuffer`s or the same shape | none: the file has no sound |
399
+ | `sampleRate`, `audioBitrate` | Of the sound | `48000`, `128000` |
400
+ | `format`, `codec`, `bitrate`, `keyFrameInterval`, `webCodecs` | As `encodeVideo` of `@margoengine/headless/video` | as there |
401
+ | `tracks` | Custom track types, for a document you pass as data | none |
402
+ | `samples` | Renders per frame, averaged in linear light (`renderFrames` of `@margoengine/headless/video`): anti-aliasing, and motion blur with `shutter` | `1` |
403
+ | `shutter`, `shutterPhase` | Share of the frame interval the shutter is open (0 to 1), and `'start'`, `'center'` or `'end'` of it against the frame's time | `0`, `'start'` |
404
+ | `filter`, `filterWidth`, `seed`, `pattern`, `accumulate` | As `renderAccumulated` of `@margoengine/headless/accumulate`: pixel filter, sample pattern, your `Accumulate` stage | as there |
405
+ | `onProgress(done, total)` | After each frame | none |
406
+ | `signal` | Stops the render; the promise rejects with its reason | none |
407
+
408
+ With `samples` or `shutter`, `apply` and the camera run before every render at that render's own time inside the
409
+ open shutter, so everything you move blurs, and a player fires each instant at the first render past it. Times before
410
+ the cutscene's start (a `'center'` shutter on frame 0) show its first instant.
411
+
412
+ ```ts
413
+ const film = await renderCutscene(engine, trailer, {
414
+ fps: 24,
415
+ samples: 16, // 16 renders a frame
416
+ shutter: 0.5, // a 180 degree shutter
417
+ camera: new Camera(),
418
+ apply(state) {
419
+ cube.setPosition(state.transforms.cube.position!);
420
+ },
421
+ });
422
+ ```
423
+
424
+ Pass a `CutscenePlayer` in place of the cutscene and it fires every instant in order as the frames go by, so listeners
425
+ can spawn things and the frames show them. The result is `encodeVideo`'s, with `audioCodec` when the file has sound:
426
+ Opus in WebM, and AAC or else Opus in MP4.
427
+
428
+ `mixCutsceneAudio(cutscene, sounds, { sampleRate?, channels?, from?, to? })` is the mix on its own, plain samples from
429
+ plain code, so it runs in Node. It holds every audio clip, in nested timelines too, with its volume, fades, offset and
430
+ nested speed. The mix is a sum with no limiter: `peak` above 1 means it will clip, so lower the clips' `volume`. A clip
431
+ naming a sound `sounds` does not hold is a `RangeError`. `cutsceneFrames(cutscene, { fps?, from?, to? })` gives each
432
+ frame's time and state with no engine, for a pipeline of your own.
433
+
434
+ ## Recording takes
435
+
436
+ `@margoengine/cutscene/record` records live play into cutscene tracks: say what to record, call `capture()` once a
437
+ tick, and `stop()` gives a take to put in a document. It needs `@margoengine/input` only if you record input.
438
+
439
+ ```ts
440
+ import { Camera } from 'margoengine/core';
441
+ import { Cutscene } from 'margoengine/cutscene';
442
+ import { TakeRecorder, appendTake, takeDocument } from 'margoengine/cutscene/record';
443
+
444
+ const camera = new Camera();
445
+ const hero = { position: [0, 0, 0], rotation: [0, 0, 0] }; // A Mesh works as it is.
446
+ let health = 100;
447
+
448
+ const recorder = new TakeRecorder({ tolerance: { position: 0.01 } });
449
+ recorder.transform('hero', hero).camera(camera).property('hero', 'health', () => health);
450
+ // recorder.input(input) records every binding of an Input; capture after input.update().
451
+
452
+ for (let tick = 0; tick < 120; tick++) {
453
+ hero.position = [tick * 0.05, 0, 0];
454
+ health -= 0.1;
455
+ if (tick === 60) recorder.event('door', { open: true }).marker('halfway');
456
+ recorder.capture(tick / 60); // Your fixed-step clock; with no argument the wall clock runs.
457
+ }
458
+ const take = recorder.stop();
459
+ console.log(take.kept['transform-hero']); // { samples: 120, keys: 1 or more, far fewer than the samples }
460
+
461
+ const cutscene = new Cutscene(takeDocument(take));
462
+ const position = cutscene.evaluate(1).transforms.hero.position;
463
+ const longer = appendTake({ format: 'margo-cutscene', version: 1, duration: 3, tracks: [] }, take, { at: 1 });
464
+ ```
465
+
466
+ | Record | Source | Comes out as |
467
+ | --- | --- | --- |
468
+ | `transform(name, source)` | A `Mesh`, anything with `position`, `rotation` or `scale`, or a function giving them; 3 rotation values are Euler radians as a `Mesh` holds them, 4 a quaternion | `transform` track `transform-<name>` |
469
+ | `camera(source)` | A `Camera`, or a function giving `position`, `target`, `fov` and `roll` | `camera` track `camera` with a straight-line path |
470
+ | `property(target, name, read)` | A function giving a number or a numeric array | `property` track `property-<target>-<name>` |
471
+ | `input(input, { target? })` | An `Input`; it starts at the next capture | one stepped `property` track for each binding (`state.properties.input.jump`, later bindings `jump#1`), and an event track with `jump` as a binding leaves 0 and `jump:up` as it comes back |
472
+ | `event(name, data?)`, `marker(name)` | Noted at the time of the last capture | `event` track `events`, the take's `markers` |
473
+
474
+ Keys are thinned on the track's own straight-line interpolation (Ramer-Douglas-Peucker), so every captured sample
475
+ stays within the tolerance of what the tracks play: `position` (world units, also the camera's position and target),
476
+ `rotation` (radians), `scale` and `value` (properties and fields of view, on each component), each default `0.001`. A
477
+ tolerance of 0 keeps every change a straight line cannot explain. Input is never thinned. `take.kept` says how many
478
+ samples each track came from. Signs of quaternions are put on one side, so a source that flips them still turns the
479
+ short way. A recorded rotation is a quaternion: apply it with `mesh.setQuaternion`, and the mesh's world matrix comes
480
+ back as it was.
481
+
482
+ `takeDocument(take)` makes the take a document; `appendTake(document, take, { at?, prefix? })` gives a new document
483
+ with it added at a time, longer if it must be, and a `prefix` lets a second take of one object sit beside the first.
484
+ `inputTracks(clip, { at?, target? })` turns a saved `InputRecorder` clip of `@margoengine/input/replay` into the same
485
+ tracks. A sample that is not finite is a `RangeError`, and so is a capture time going backwards. `stop()` with nothing
486
+ captured and any use after `stop()` throw `MargoError` `'state'`.
487
+
488
+ ## Dialogue and lip sync
489
+
490
+ `@margoengine/cutscene/lipsync` adds a `lipsync` track: timed phonemes go in, weights for 15 visemes come out as a pure
491
+ function of the time, so scrubbing moves the mouth as playing does. Phonemes come from a tool (a forced aligner gives
492
+ the best mouth), or `analyseSpeech` reads them out of the dialogue audio itself.
493
+
494
+ ```ts
495
+ import { CutscenePlayer } from 'margoengine/cutscene';
496
+ import { analyseSpeech, lipSyncTrack, mouthOf, mouthShapes, type LipSyncTrack } from 'margoengine/cutscene/lipsync';
497
+
498
+ const dialogue: LipSyncTrack = {
499
+ type: 'lipsync',
500
+ id: 'ada-lines',
501
+ target: 'ada',
502
+ clips: [
503
+ // Phoneme data: ARPAbet, with or without stress digits, or viseme names. Times are from the start of the clip.
504
+ {
505
+ start: 0.5,
506
+ duration: 1,
507
+ phonemes: [
508
+ { time: 0, phoneme: 'HH' },
509
+ { time: 0.1, phoneme: 'AH0' },
510
+ { time: 0.2, phoneme: 'L' },
511
+ { time: 0.3, end: 0.7, phoneme: 'OW1' },
512
+ ],
513
+ },
514
+ ],
515
+ };
516
+ // Or from audio: an AudioBuffer's channel gives the samples.
517
+ const rate = 16_000;
518
+ const speech = new Float32Array(rate).map((_, i) => 0.5 * Math.sin(i / 3) * Math.sin(i / 900));
519
+ dialogue.clips.push({ start: 2, duration: 1, phonemes: analyseSpeech(speech, rate) });
520
+
521
+ const player = new CutscenePlayer(
522
+ { format: 'margo-cutscene', version: 1, duration: 4, tracks: [dialogue] },
523
+ { tracks: [lipSyncTrack()] },
524
+ );
525
+ void player.play();
526
+ player.update(0.9);
527
+ const mouth = mouthOf(player.state, 'ada'); // { oh: 1 }
528
+ const shapes = mouthShapes(mouth, 'vrm'); // { oh: 1 }: VRM's five mouth expressions
529
+ ```
530
+
531
+ | Field | Meaning | Default |
532
+ | --- | --- | --- |
533
+ | `target` | The character, the key `mouthOf` reads | required |
534
+ | `blend` | Seconds a mouth takes to move into and out of a sound | `0.06` |
535
+ | clip `phonemes` | `{ time, end?, phoneme, weight? }` sorted by `time`; `end` defaults to the next sound's time, and `weight` (0 to 1) to 1 | required |
536
+ | clip `gain` | Scale on every weight | `1` |
537
+
538
+ The visemes are `sil PP FF TH DD kk CH SS nn RR aa E ih oh ou`, the names game and avatar tools use (`VISEMES`, and
539
+ `visemeOf(phoneme)` for one sound). Weights of neighbouring sounds cross over the blend and never sum past 1; what is
540
+ left of 1 is the mouth at rest, so a line opens into its first sound and closes after its last with no jump. Two
541
+ tracks on one character add up, within 1. Clips fire `enter` and `exit`, named after the character, and nest in
542
+ timelines like any clip. `visemesAt(clip, t, blend?)` is the same reading with no document.
543
+
544
+ `mouthShapes(weights, set)` turns weights into blend shapes to set. `'visemes'` (default) names them `viseme_aa` and
545
+ so on, as avatar tools do. `'vrm'` gives the VRM 1.0 presets `aa ih ou ee oh`, for `vrm.expressions.set` of
546
+ `@margoengine/rigging/vrm`. `'arkit'` gives Apple's face shape names, a frame `face.push` of
547
+ `@margoengine/rigging/face` takes as it is. Each sound's mix of shapes is a choice of ours, not a standard.
548
+
549
+ `analyseSpeech(samples, sampleRate, { step?, floor?, shortest? })` needs no words and no transcript. It finds silence
550
+ by level, hiss by its share of high sound, and each vowel's mouth from its formants, by linear prediction, on a chart
551
+ scaled to the speaker. It is a rough mouth, not a transcript: it tells closed, hiss and open apart but no other
552
+ consonants, a pause under about 70 ms goes unseen, and it gets about half of vowel frames right. Use phonemes from an
553
+ aligner when the mouth must be exact.
554
+
555
+
556
+ ## Particle effects and activation
557
+
558
+ `@margoengine/cutscene/vfx` adds a `vfx` track that starts, stops and bursts particle effects on the timeline, and an
559
+ `activation` track that shows and hides objects. Both are pure, as every track is. Particles have a past, so
560
+ `VfxDirector` turns the state into starts, stops and bursts, and a seek runs the same frames again.
561
+
562
+ ```ts
563
+ import { Engine } from 'margoengine/core';
564
+ import { Cutscene, CutscenePlayer } from 'margoengine/cutscene';
565
+ import { VfxDirector, activationTrack, applyActivation, vfxTrack } from 'margoengine/cutscene/vfx';
566
+ import { VFX } from 'margoengine/vfx';
567
+
568
+ const engine = await Engine.create(document.querySelector('canvas')!, { backend: 'webgpu' });
569
+ const sparks = VFX.attach(engine, { capacity: 10_000, lifetime: [0.5, 1.5], velocity: [0, 3, 0] });
570
+ const door = engine.createMesh();
571
+
572
+ const cutscene = new Cutscene(
573
+ {
574
+ format: 'margo-cutscene',
575
+ version: 1,
576
+ duration: 6,
577
+ tracks: [
578
+ {
579
+ type: 'vfx',
580
+ id: 'fire',
581
+ target: 'sparks',
582
+ clips: [{ start: 1, duration: 3, rate: 800, bursts: [{ time: 0.5, count: 2000 }] }],
583
+ },
584
+ { type: 'activation', id: 'door-on', target: 'door', clips: [{ start: 2, duration: 4 }] },
585
+ ],
586
+ },
587
+ { tracks: [vfxTrack(), activationTrack()] },
588
+ );
589
+ const player = new CutscenePlayer(cutscene);
590
+ const director = new VfxDirector(cutscene, { sparks }, { step: (delta) => engine.render({ delta }) });
591
+
592
+ // Each frame, in this order:
593
+ function frame(delta: number): void {
594
+ player.update(delta);
595
+ director.apply(player.state);
596
+ applyActivation(player.state, { door });
597
+ engine.render({ delta });
598
+ }
599
+ void player.play();
600
+ frame(1 / 60);
601
+
602
+ player.seek(3.2); // A scrub, however far: the frame drawn next is the one playing to 3.2 s shows.
603
+ director.apply(player.state);
604
+ engine.render({ delta: 1 / 60 });
605
+ ```
606
+
607
+ | Field | Meaning | Default |
608
+ | --- | --- | --- |
609
+ | `vfx` `target` | The effect's name in the director | required |
610
+ | `vfx` clip `rate` | Births a second while the clip runs | the rate the effect had when the director took it |
611
+ | `vfx` clip `bursts` | `{ time, count }` sorted by time, seconds into the clip | none |
612
+ | `activation` `target`, `clips` | The object, and spans it shows | required |
613
+ | `activation` `invert` | Hides it during the spans instead | `false` |
614
+ | director `step(delta)` | Draws one frame of the replay. Required | |
615
+ | director `stepSize` | Seconds of a replay frame: use your frame time | `1 / 60` |
616
+ | director `longest` | Seconds a seek replays at most | `10` |
617
+
618
+ `effectsOf(state)` and `activeOf(state)` give the plain state, for an effect or object of your own; clips fire `enter`
619
+ and `exit`, and bursts fire an event `<target>:burst` with `{ count }`. The director needs only `options.rate`,
620
+ `burst(count)` and `reset()`, so `VFX` of `@margoengine/vfx` fits and so does your own. Objects you do not pass to
621
+ `applyActivation` are left alone, and a `Mesh` fits as it is.
622
+
623
+ The director holds an effect off until a clip. Playing, an effect a clip finds empty starts fresh, so its random
624
+ numbers depend on the cutscene alone. A frame that is not the next one (a seek, a step back, a leap past 8 frames)
625
+ wipes the effects and plays again from when they were last empty, through as many clips as still have particles alive
626
+ by `options.lifetime`. It costs one drawn frame for each step of replay. With the same `stepSize` as your frames it
627
+ lands on the same particles, byte for byte; with frames of another length it lands near them. Past `longest` it starts
628
+ that far back, so the particles are alike in kind only. Playing backward is a seek on every frame. A pause stops the
629
+ cutscene and not the particles: stop drawing, or `delta` 0, to hold them.
630
+
631
+
632
+ ## Timeline editor
633
+
634
+ `@margoengine/cutscene/editor` is an optional panel for authoring in your own page: scrub, zoom, snap, and add, move
635
+ and delete keys, clips, events and markers with undo. Margo has no visual editor by design, so this stays a separate
636
+ tool: nothing else in the package imports it. It needs `@margoengine/inspector` for its undo stack.
637
+
638
+ ```ts
639
+ import { CutscenePlayer } from 'margoengine/cutscene';
640
+ import { TimelineEditor } from 'margoengine/cutscene/editor';
641
+
642
+ const editor = new TimelineEditor(
643
+ {
644
+ format: 'margo-cutscene',
645
+ version: 1,
646
+ duration: 8,
647
+ tracks: [
648
+ { type: 'transform', id: 'door', target: 'door', keys: [{ time: 1, position: [0, 0, 0] }, { time: 3, position: [2, 0, 0] }] },
649
+ { type: 'audio', id: 'music', clips: [{ start: 0, duration: 6, sound: 'theme' }] },
650
+ ],
651
+ },
652
+ { parent: document.body, zoom: 120 },
653
+ );
654
+
655
+ let player = new CutscenePlayer(editor.model.cutscene());
656
+ editor.on('seek', (time) => player.seek(time)); // The scene follows the scrub.
657
+ editor.on('change', () => {
658
+ player = new CutscenePlayer(editor.model.cutscene()); // A document is frozen once loaded, so edits make a new one.
659
+ player.seek(editor.time);
660
+ });
661
+ localStorage.setItem('intro', editor.model.save());
662
+ ```
663
+
664
+ Pass `tracks` for custom track types, as for `Cutscene`; their clips show and move like any others.
665
+
666
+ | Option | Meaning | Default |
667
+ | --- | --- | --- |
668
+ | `parent` | Where the panel goes; or place `editor.element` yourself | none |
669
+ | `zoom` | Pixels a second, 10 to 2000 | `100` |
670
+ | `step` | Grid in seconds, also what an arrow key moves | `0.1` |
671
+ | `snap` | Snap to the grid, other items and the playhead while dragging | `true` |
672
+ | `fileName` | Name of the file the Export button saves | `'cutscene.json'` |
673
+ | `tracks`, `history` | Custom track types, and an `EditHistory` to share with your tool | none, a new one |
674
+
675
+ Drag the ruler to scrub and an item to move it; Shift or Ctrl adds to the selection and a selection moves together.
676
+ Ctrl and the wheel zoom about the pointer. Every action is on the keyboard too, and each item is a button a screen
677
+ reader names:
678
+
679
+ | Key | Does |
680
+ | --- | --- |
681
+ | Left, Right | Moves the selection a step, or the playhead with nothing selected; Shift makes it ten |
682
+ | Home, End | Playhead to the ends |
683
+ | K | Adds a key at the playhead on the current row, the one last clicked |
684
+ | Delete, Backspace | Deletes the selection |
685
+ | Ctrl+Z, Ctrl+Shift+Z, Ctrl+Y | Undo and redo; Cmd works too |
686
+ | +, - | Zoom |
687
+ | Escape | Clears the selection |
688
+
689
+ `editor.on('seek' | 'select' | 'change', listener)` returns an unsubscribe function; `editor.time`, `editor.zoom` and
690
+ `editor.selection` read and set; `dispose()` or `using` removes it. The panel's colours are CSS variables on `.mtl`
691
+ (`--bg`, `--panel`, `--line`, `--text`, `--dim`, `--accent`, `--clip`).
692
+
693
+ `editor.model` is a `TimelineModel`, the editing itself with no DOM, so it runs in Node and in your own panel:
694
+
695
+ ```ts
696
+ import { MARKERS, TimelineModel } from 'margoengine/cutscene/editor';
697
+
698
+ const model = new TimelineModel({
699
+ format: 'margo-cutscene',
700
+ version: 1,
701
+ duration: 8,
702
+ tracks: [{ type: 'property', id: 'fade', target: 'screen', property: 'opacity', keys: [{ time: 0, value: 1 }, { time: 4, value: 0 }] }],
703
+ });
704
+ const key = model.addKey('fade', 2); // Holds 0.5, what the track gives there.
705
+ const [moved] = model.moveItems([key], 0.5);
706
+ model.setItem(moved, { value: 0.25, ease: 'easeOutCubic' });
707
+ model.addKey(MARKERS, 6, { name: 'reveal' });
708
+ model.undo();
709
+ model.redo();
710
+ const text = model.save(); // JSON text; new Cutscene(text) reads it.
711
+ ```
712
+
713
+ | Member | Does |
714
+ | --- | --- |
715
+ | `rows` | Each track with its items, then the markers row (`MARKERS`) |
716
+ | `addKey(track, time, fields?)` | A key holding the track's value there, or an event or marker; `addItem(track, item)` adds a whole key or clip |
717
+ | `moveItems(items, delta)` | Moves them together, stopping at the ends of the timeline, and gives their new refs |
718
+ | `setItem(ref, fields)`, `deleteItems(items)`, `setDuration(seconds)` | Give false when the document refuses, and then change nothing |
719
+ | `begin(label)`, `commit()` | A run of edits that undoes as one, such as a drag |
720
+ | `undo()`, `redo()`, `history` | The `EditHistory` behind them |
721
+ | `snap(time, { step?, reach?, ignore?, times? })` | The time to use: on an item or given time within `reach`, else on the grid |
722
+ | `on('change', listener)` | After every change, undo and redo included |
723
+ | `document`, `toJSON()`, `save()`, `cutscene()` | A copy, for `JSON.stringify`, JSON text, a `Cutscene` to play or render |
724
+
725
+ Every edit leaves a valid document: one that would break it, such as two shots overlapping or a track's last key
726
+ going, is refused whole. Refs are places in a list, so use the ones the last edit gave. What is inside a nested
727
+ timeline does not show: its clip moves as one piece, and to edit inside it, open that timeline as a document of its
728
+ own. There is no curve editor, and clip lengths and key values are set by `setItem`, not by dragging.
729
+
730
+
731
+ ## Custom tracks
732
+
733
+ `shotTrack()` is a `CutsceneTrackType`, and you can write your own for anything a document should hold: pass types in
734
+ the `tracks` option of `Cutscene` or `CutscenePlayer`, and a document using a type you did not pass is refused. A type
735
+ gives `validate(track, check)`, `evaluate(track, time, state, path)` and optionally `instants(track)`. It runs after
736
+ the built-in tracks, reads what they set, and puts its own results in `state.extras`.
737
+
738
+ ```ts
739
+ import { Cutscene, type CutsceneTrackType } from 'margoengine/cutscene';
740
+
741
+ const weather: CutsceneTrackType = {
742
+ type: 'weather',
743
+ validate(track, { path, add }) {
744
+ if (typeof track.rain !== 'number') add(`${path}.rain`, 'must be a number');
745
+ },
746
+ evaluate(track, time, state) {
747
+ (state.extras ??= {}).rain = (track.rain as number) * time;
748
+ },
749
+ };
750
+ const scene = new Cutscene(
751
+ { format: 'margo-cutscene', version: 1, duration: 2, tracks: [{ type: 'weather', id: 'storm', rain: 0.5 }] },
752
+ { tracks: [weather] },
753
+ );
754
+ const rain = scene.evaluate(1).extras?.rain; // 0.5
755
+ ```
756
+
757
+ ## Saving and validating
758
+
759
+ ```ts
760
+ import { Cutscene, validateCutscene } from 'margoengine/cutscene';
761
+
762
+ const text = JSON.stringify({ format: 'margo-cutscene', version: 1, duration: 3, tracks: [] });
763
+ const problems = validateCutscene(JSON.parse(text)); // [] when valid, else [{path, message}]
764
+ const loaded = new Cutscene(text);
765
+ ```
766
+
767
+ `validateCutscene` never throws and lists every problem with its path and fix (`tracks[0].keys[1].time: is earlier
768
+ than the one before; sort the list by time`). `new Cutscene`, `parseCutscene` and `new CutscenePlayer` throw a
769
+ `TypeError` naming the first one. Bad arguments throw `RangeError` (`Cutscene time must be a finite number of
770
+ seconds`); use after `dispose()` throws `MargoError` `'disposed'`.
771
+
772
+ Apache-2.0. Optional, tree-shakable package; no core dependency.
773
+
774
+ Build and unit tests: npm test --workspace @margoengine/cutscene