motlab.js 0.0.0-stage → 0.1.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.
Files changed (108) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/LICENSE +21 -0
  3. package/README.md +86 -2
  4. package/docs/stability.md +53 -0
  5. package/llms.txt +794 -0
  6. package/package.json +107 -6
  7. package/src/adapters/canvas.js +68 -0
  8. package/src/adapters/lottie.js +102 -0
  9. package/src/adapters/pixi.js +62 -0
  10. package/src/adapters/rapier.js +163 -0
  11. package/src/adapters/rive.js +316 -0
  12. package/src/adapters/three.js +81 -0
  13. package/src/addons/audio.js +422 -0
  14. package/src/addons/camera.js +319 -0
  15. package/src/addons/cel.js +498 -0
  16. package/src/addons/clone.js +299 -0
  17. package/src/addons/color.js +223 -0
  18. package/src/addons/deform.js +441 -0
  19. package/src/addons/dom.js +68 -0
  20. package/src/addons/edit.js +317 -0
  21. package/src/addons/fx.js +64 -0
  22. package/src/addons/game.js +106 -0
  23. package/src/addons/input.js +209 -0
  24. package/src/addons/machine.js +240 -0
  25. package/src/addons/media.js +581 -0
  26. package/src/addons/particles.js +179 -0
  27. package/src/addons/path.js +596 -0
  28. package/src/addons/physics.js +980 -0
  29. package/src/addons/player.js +170 -0
  30. package/src/addons/rig.js +851 -0
  31. package/src/addons/text.js +133 -0
  32. package/src/addons/trace.js +456 -0
  33. package/src/core/combinators.js +129 -0
  34. package/src/core/component.js +90 -0
  35. package/src/core/dmath.js +256 -0
  36. package/src/core/ease.js +136 -0
  37. package/src/core/guard.js +139 -0
  38. package/src/core/hash.js +74 -0
  39. package/src/core/markers.js +49 -0
  40. package/src/core/math.js +43 -0
  41. package/src/core/nodes.js +328 -0
  42. package/src/core/noise.js +340 -0
  43. package/src/core/path.js +295 -0
  44. package/src/core/rand.js +135 -0
  45. package/src/core/scene.js +678 -0
  46. package/src/core/simulate.js +289 -0
  47. package/src/core/spring.js +129 -0
  48. package/src/core/timeline.js +193 -0
  49. package/src/core/track.js +258 -0
  50. package/src/core/verify.js +208 -0
  51. package/src/core/version.js +2 -0
  52. package/src/index.js +19 -0
  53. package/src/renderer/canvas2d.js +950 -0
  54. package/src/renderer/pixels.js +57 -0
  55. package/src/renderer/svg.js +589 -0
  56. package/src/renderer/text-layout.js +80 -0
  57. package/src/renderer/webgl2.js +1331 -0
  58. package/types/adapters/canvas.d.ts +46 -0
  59. package/types/adapters/lottie.d.ts +45 -0
  60. package/types/adapters/pixi.d.ts +46 -0
  61. package/types/adapters/rapier.d.ts +116 -0
  62. package/types/adapters/rive.d.ts +62 -0
  63. package/types/adapters/three.d.ts +51 -0
  64. package/types/addons/audio.d.ts +124 -0
  65. package/types/addons/camera.d.ts +134 -0
  66. package/types/addons/cel.d.ts +215 -0
  67. package/types/addons/clone.d.ts +167 -0
  68. package/types/addons/color.d.ts +73 -0
  69. package/types/addons/deform.d.ts +112 -0
  70. package/types/addons/dom.d.ts +68 -0
  71. package/types/addons/edit.d.ts +293 -0
  72. package/types/addons/fx.d.ts +65 -0
  73. package/types/addons/game.d.ts +78 -0
  74. package/types/addons/input.d.ts +56 -0
  75. package/types/addons/machine.d.ts +111 -0
  76. package/types/addons/media.d.ts +117 -0
  77. package/types/addons/particles.d.ts +110 -0
  78. package/types/addons/path.d.ts +61 -0
  79. package/types/addons/physics.d.ts +265 -0
  80. package/types/addons/player.d.ts +48 -0
  81. package/types/addons/rig.d.ts +273 -0
  82. package/types/addons/text.d.ts +63 -0
  83. package/types/addons/trace.d.ts +110 -0
  84. package/types/core/combinators.d.ts +73 -0
  85. package/types/core/component.d.ts +50 -0
  86. package/types/core/dmath.d.ts +52 -0
  87. package/types/core/ease.d.ts +50 -0
  88. package/types/core/guard.d.ts +23 -0
  89. package/types/core/hash.d.ts +6 -0
  90. package/types/core/markers.d.ts +52 -0
  91. package/types/core/math.d.ts +38 -0
  92. package/types/core/nodes.d.ts +442 -0
  93. package/types/core/noise.d.ts +65 -0
  94. package/types/core/path.d.ts +82 -0
  95. package/types/core/rand.d.ts +47 -0
  96. package/types/core/scene.d.ts +189 -0
  97. package/types/core/simulate.d.ts +169 -0
  98. package/types/core/spring.d.ts +41 -0
  99. package/types/core/timeline.d.ts +86 -0
  100. package/types/core/track.d.ts +58 -0
  101. package/types/core/verify.d.ts +42 -0
  102. package/types/core/version.d.ts +2 -0
  103. package/types/index.d.ts +18 -0
  104. package/types/renderer/canvas2d.d.ts +184 -0
  105. package/types/renderer/pixels.d.ts +28 -0
  106. package/types/renderer/svg.d.ts +19 -0
  107. package/types/renderer/text-layout.d.ts +45 -0
  108. package/types/renderer/webgl2.d.ts +71 -0
package/llms.txt ADDED
@@ -0,0 +1,794 @@
1
+ # motlab.js
2
+
3
+ > JavaScript deterministic motion engine, with no runtime dependencies. A scene is a tree of
4
+ > nodes whose properties are functions of time. `scene.evaluate(t)` turns it into a display list for any t, in any
5
+ > order, and a renderer draws that list. Release 0.1.0: the API below is what exists today.
6
+
7
+ ## The one rule
8
+
9
+ Every frame must be a pure function of time. Draw the same thing every time you get the same `t`.
10
+
11
+ - Never call `Math.random`, `crypto.getRandomValues`, `crypto.randomUUID`, `Date.now`, `new Date()`,
12
+ `performance.now` or `requestAnimationFrame` inside a scene. They throw while a scene is evaluated or drawn. Use
13
+ `rand(...keys)` for randomness and `t` for time.
14
+ - Never keep state that changes from frame to frame (counters, arrays you push to, "previous value" variables).
15
+ - Build nodes once, outside time functions, unless the structure itself must change over time.
16
+ - Check your scene with `verify(scene)`. It evaluates every frame in order and shuffled and reports what changed.
17
+
18
+ ## Imports
19
+
20
+ ```js
21
+ import { scene, timeline, group, rect, ellipse, text, image, video, mesh, transition, shape, draw, instances, STRIDE,
22
+ EFFECTS, TRANSITIONS, path, component, track, key, ease, spring, step, loop, delay, speed, add, mul, map, wiggle,
23
+ rand, noise, stagger, markers, at, clamp, lerp, prog, verify, hash, dmath, simulate, prepare, memoryStore,
24
+ inputTrack, VERSION } from 'motlab.js'
25
+ import { canvas2d, verifyPixels, toPNG, toPNGSequence, toSpriteSheet, planSpriteSheet } from 'motlab.js/renderer/canvas2d'
26
+ import { svg } from 'motlab.js/renderer/svg'
27
+ import { webgl2 } from 'motlab.js/renderer/webgl2' // also exports its own verifyPixels and toPNG
28
+ import { blur, glow, diffusion, grain, para, vignette, satsuei } from 'motlab.js/addons/fx'
29
+ import { mix, oklch, oklab, srgb, linearGradient, radialGradient, parse as parseColor } from 'motlab.js/addons/color'
30
+ import { parse as parsePath, length, trim, along, toCurves } from 'motlab.js/addons/path'
31
+ import { animate, cascade, range, wiggly } from 'motlab.js/addons/text'
32
+ import { bind } from 'motlab.js/addons/dom'
33
+ import { player } from 'motlab.js/addons/player'
34
+ import { xsheet, on, slot, palette, aseprite, spriteSheet, sprite, onion, lightTable } from 'motlab.js/addons/cel'
35
+ import { camera, plane, vcam, shots, follow, trauma, shake, punch } from 'motlab.js/addons/camera'
36
+ import { cloner, grid, radial, line, points, onPath, radialField, linearField, noiseField, invert, transform,
37
+ timeOffset, jitter } from 'motlab.js/addons/clone'
38
+ import { particles } from 'motlab.js/addons/particles'
39
+ import { rig, driver, driven, ik, fabrik, aim, limit, pendulum, layers, bonesView } from 'motlab.js/addons/rig'
40
+ import { keyform, blendShapes, shapeType, lattice, warp, skin, gridMesh } from 'motlab.js/addons/deform'
41
+ import { trace } from 'motlab.js/addons/trace'
42
+ import { physics, circle, box, pin, link, simParticles } from 'motlab.js/addons/physics'
43
+ import { machine, blendTree } from 'motlab.js/addons/machine'
44
+ import { decodeAudio, analyze, levels, pulse, beatClock, beatMarkers, playSound } from 'motlab.js/addons/audio'
45
+ import { demux, openVideo } from 'motlab.js/addons/media'
46
+ import { edit, clip, gap, cuts, split, ripple, roll, slip, slide, footage, toOTIO, fromOTIO } from 'motlab.js/addons/edit'
47
+ import { controls, recorder, fromRecording } from 'motlab.js/addons/input'
48
+ import { game } from 'motlab.js/addons/game'
49
+ import { rapier } from 'motlab.js/adapters/rapier' // these need the library installed, see Adapters
50
+ import { lottie } from 'motlab.js/adapters/lottie'
51
+ import { rive } from 'motlab.js/adapters/rive'
52
+ import { threeLayer, threeTexture } from 'motlab.js/adapters/three'
53
+ import { pixiLayer, pixiTexture } from 'motlab.js/adapters/pixi'
54
+ import { canvasLayer, sceneCanvas } from 'motlab.js/adapters/canvas'
55
+ ```
56
+
57
+ In a page without a bundler, import from the files: `./src/index.js`, `./src/renderer/<name>.js`,
58
+ `./src/addons/<name>.js` and `./src/adapters/<name>.js`.
59
+
60
+ ## Values and time
61
+
62
+ A Value is a constant or a function `(t) => value`, where `t` is in seconds. Every node prop accepts a Value.
63
+
64
+ - `track(keys, { before, after })` returns `(t) => value`. Keys are `[t, value]`, `[t, value, ease]` or
65
+ `key(t, value, { ease })`, sorted by time. The ease on a key shapes the segment that ends at that key; the default
66
+ is linear. Values are numbers or same-length arrays of numbers. `before`/`after`: `'hold'` (default), `'cycle'`,
67
+ `'pingpong'`, `'extend'`. `track.duration` is the time of the last key. `track.velocity(t)` is the derivative.
68
+ - `ease`: `linear`, `inSine outSine inOutSine`, `inQuad outQuad inOutQuad`, `inCubic outCubic inOutCubic`,
69
+ `inQuart outQuart inOutQuart`, `inExpo outExpo inOutExpo`, `inBack outBack inOutBack`, `outBounce`, `hold`
70
+ (keeps the start value, then jumps at the end of the segment). Builders: `ease.bezier(x1, y1, x2, y2)` (same as CSS
71
+ cubic-bezier) and `ease.steps(n)`.
72
+ - `spring({ duration, bounce })` or `spring({ stiffness, damping, mass, velocity })` returns `(t) => 0..1`. It is 0
73
+ before t = 0 and exactly 1 from `spring.duration` on. With `duration`, that is when it settles. `bounce` is 0 (no
74
+ overshoot) up to below 1. Map it to your range: `t => 300 + 200 * pop(t)`.
75
+ - Combinators return new functions of time: `step(f, { rate: 24, on: 2 })` (hold each drawing for 2 frames at 24
76
+ fps, "on twos"), `loop(f, { period, mode: 'cycle' | 'pingpong' })`, `delay(f, seconds)`, `speed(f, factor)`,
77
+ `add(a, b, ...)`, `mul(a, b, ...)` (numbers or arrays; a number applies to every element), `map(f, (value, t) => ...)`,
78
+ `wiggle({ freq, amp, octaves, seed })` (smooth random motion around 0, like After Effects wiggle).
79
+ - `rand(...keys)` is a number in [0, 1) hashed from its keys: the same keys always give the same number.
80
+ `rand.range(min, max, ...keys)`, `rand.int(min, max, ...keys)` (both ends included), `rand.pick(list, ...keys)`.
81
+ Use a seed name and the index: `rand('stars', i, 'x')`.
82
+ - `noise.simplex1(x, { seed })` to `simplex4`, `noise.fbm1(x, { octaves, lacunarity, gain, seed })` to `fbm4`, and
83
+ `noise.loop2(x, y, t, { period, freq, seed })`, which repeats exactly every `period` seconds. All return -1..1.
84
+ - Helpers: `at(value, t)`, `clamp(x, min = 0, max = 1)`, `lerp(a, b, k)`, `prog(t, a, b)` (0..1 between two times).
85
+
86
+ ## Nodes
87
+
88
+ Every node takes these props: `id` (letters, digits, `-`, `_`; unique in the scene), `x`, `y` (px from the parent),
89
+ `rotation` (degrees, clockwise), `scale` (number or `[sx, sy]`), `skew` (degrees, like CSS skewX, between rotation
90
+ and scale), `anchor` (`[ax, ay]` in px: the point that `x, y`
91
+ place and that rotation and scale turn around), `opacity` (0..1, multiplies into children), `visible`, `z` (draw
92
+ order among siblings; higher is in front), `blend` (`'normal'`, `'multiply'`, `'screen'`, `'overlay'`, `'darken'`,
93
+ `'lighten'`, `'color-dodge'`, `'color-burn'`, `'hard-light'`, `'soft-light'`, `'difference'`, `'exclusion'`, `'hue'`,
94
+ `'saturation'`, `'color'`, `'luminosity'`, `'add'`).
95
+
96
+ - `group(props, children)`: children is an array of nodes, or a pure function `(t) => nodes`.
97
+ - `rect({ w, h, radius })`: from (0, 0) to (w, h). Set `anchor: [w / 2, h / 2]` to place it by its center.
98
+ - `ellipse({ w, h })`: fills the box from (0, 0) to (w, h).
99
+ - `shape({ path })` with `path()`: `moveTo lineTo bezierCurveTo quadraticCurveTo arc arcTo ellipse rect roundRect
100
+ closePath`, the same as Path2D. Angles in `arc` and `ellipse` are radians.
101
+ - Shapes take `fill`, `stroke`, `strokeWidth`, `lineCap`, `lineJoin`, `dash`, `dashOffset`. With neither fill nor
102
+ stroke they fill black.
103
+ - `text({ text, font, align, baseline, fill, stroke, strokeWidth, lineHeight, width, split, perUnit })`: drawn at
104
+ (0, 0) of the node, like `fillText`. `font` is a CSS font string such as `'700 64px Inter'`. `\n` breaks lines,
105
+ `lineHeight` is in px (default 1.2 times the font size) and `width` wraps at spaces. A font family that is not
106
+ generic (`sans-serif`, `serif`, `monospace`, `system-ui` and the like) must be listed in the scene's
107
+ `assets.fonts`, or evaluating the text throws, so every machine draws the same letters.
108
+ - `image({ src, w, h, crop, smooth })`: `src` is a key of the scene's `assets.images`. `crop: [x, y, w, h]` draws only
109
+ that part of the source (w and h default to the crop's size); `smooth: false` keeps pixel art sharp when scaled.
110
+ - `video({ src, time, w, h, crop, smooth })`: a frame of footage. `src` is a key of the scene's `assets.videos` (MP4
111
+ files: H.264, HEVC, VP9 or AV1); `time` is the moment of the footage to show, in its own seconds, and defaults to
112
+ the node's local time. The frame for every time is exact.
113
+ - `mesh({ src, points, uvs, triangles, smooth })`: an image from `assets.images` drawn through triangles whose points
114
+ can move, like an ArtMesh in Live2D or a mesh in Spine. `points` (a Value) and `uvs` are flat `x, y` lists of the
115
+ same length: where each vertex sits in node px, and which image px it shows. `triangles` holds three vertex indices
116
+ per triangle. `gridMesh` from the deform addon builds all three over a box; bend the picture by passing its points
117
+ through `warp`, `skin` or a keyform.
118
+ - `transition({ progress, effect, params, box }, [from, to])`: mixes two nodes. `progress` runs 0 (all `from`) to 1
119
+ (all `to`). `effect` is one of `TRANSITIONS`: `'fade'` (default), `'wipe'` and `'slide'` (`angle` in degrees,
120
+ wipe also `softness`), `'circle'` (`x`, `y` as 0..1 of the area, `softness`), `'zoom'` (`strength`), `'dissolve'`
121
+ (`size` in px). Set those in `params`. `effect` can also be `{ glsl }`, a gl-transitions shader
122
+ (`vec4 transition(vec2 uv)` using `getFromColor`, `getToColor`, `progress` and `ratio`; uniforms come from
123
+ `params`), which only the WebGL2 renderer runs. Without `box` it plays across the whole frame, like a cut between
124
+ shots. `box: [x, y, w, h]` in node px plays it across that area, such as a phone screen, and draws nothing outside.
125
+ - `instances({ base, data, colors })`: many copies of one shape, text or image node in a single display item.
126
+ `data` is a Value giving a `Float32Array` with `STRIDE` (7) numbers per copy: x, y, rotation in degrees, scale x,
127
+ scale y, opacity, and an index into `colors` (-1 keeps the base's fill). Return a new array on every call. Cloners
128
+ and particles build these for you.
129
+ - `draw({ draw: (ctx, t) => { ... } })`: free drawing with the canvas API. `ctx` already has the node's transform and
130
+ opacity. It must be pure too.
131
+
132
+ Colours are CSS strings. `fill` and `stroke` also take a gradient from the color addon.
133
+
134
+ ## Layers: blend, matte, precomp, motion blur
135
+
136
+ These props work on `group` and component instances. A group with any of them is composited as one layer, so its
137
+ opacity and blend apply to the whole.
138
+
139
+ - `blend: 'screen'` blends the group as one layer with what is under it.
140
+ - `isolate: true` composites the children first, so overlapping children do not show through each other at low opacity.
141
+ - `matte: { node, mode }` shows the group only where `node` is drawn. `mode` is `'alpha'` (default),
142
+ `'alpha-inverted'`, `'luma'` or `'luma-inverted'`. The matte node uses the group's coordinates and time and is not
143
+ drawn by itself. Text makes a good matte: `matte: { node: text({ text: 'SALE', font: '900 200px sans-serif' }) }`.
144
+ - `time: t => t / 2` remaps time for the children, like an After Effects precomp: slow motion, freeze frames
145
+ (`time: 1.2`) or reverse (`time: t => 3 - t`).
146
+ - `motionBlur: { samples: 8, shutter: 1 / 60 }` averages moments across the shutter, including the group's own motion.
147
+ - `effects: [glow(), grain()]` runs image effects over the layer, in order. Every parameter may be a Value. The fx
148
+ addon builds them: `blur(radius)`, `glow({ radius, strength, threshold })` (what is brighter than `threshold` 0..1
149
+ spreads and is screened back on), `diffusion({ radius, strength })` (the soft bloom of anime photography),
150
+ `grain({ amount, size, seed })` (new noise every frame, the same each time a frame is drawn),
151
+ `para({ from, to, angle, blend, opacity })` (a gradient laid over the layer, inside its shape) and
152
+ `vignette({ strength, radius })`. `satsuei()` returns the anime finishing pass as a list (diffusion, a warm light
153
+ from above, a vignette, fine grain); pass `false` or options per part: `satsuei({ vignette: false })`. Spread it
154
+ into the list: `effects: [glow(), ...satsuei()]`. Defaults are in `EFFECTS`.
155
+
156
+ ## Colour (motlab.js/addons/color)
157
+
158
+ - `mix(a, b, k, space)` blends two CSS colours; `space` is `'oklab'` (default), `'oklch'` or `'srgb'`.
159
+ - Tracks blend colours with a type: `fill: track([[0, '#0b1020'], [2, '#ff5a1f']], { type: oklch })`.
160
+ - `linearGradient({ from: [x0, y0], to: [x1, y1], stops: [[0, '#f60'], [1, '#60f']], space: 'oklch' })` and
161
+ `radialGradient({ from, r0, to, r1, stops })` give a fill or stroke, in the node's own coordinates.
162
+ - `parseColor` reads hex, `rgb()`, `hsl()`, `oklab()`, `oklch()` and basic names (black, white, red, navy, ...).
163
+
164
+ ## Paths (motlab.js/addons/path)
165
+
166
+ - `parsePath('M10 10 C 50 80, 150 80, 190 10')` reads SVG path data into a path.
167
+ - `length(p)` is its length in px. `trim(p, start, end)` keeps the part between two fractions of the length:
168
+ `shape({ path: t => trim(p, 0, prog(t, 0, 1)), stroke: '#fff', strokeWidth: 6 })` draws a line on.
169
+ - `along(p, k)` gives `{ x, y, angle }` at fraction k, for moving things along a path:
170
+ `x: t => along(p, prog(t, 0, 2)).x`, `rotation: t => along(p, prog(t, 0, 2)).angle`.
171
+ - `toCurves(p)` redraws a path with moves, lines, cubics and closes only (arcs, ellipses and rounded corners become
172
+ cubics), so deformers can move every point.
173
+
174
+ ## Text animation (motlab.js/addons/text)
175
+
176
+ Set `split: 'grapheme'` (or `'word'`, `'line'`) on a text node and give `perUnit` one or more functions. Each unit gets
177
+ offsets from where the layout puts it: `x`, `y`, `rotation` (around its centre), `scale`, `opacity`, `fill`.
178
+
179
+ ```js
180
+ text({
181
+ text: 'HELLO', font: '900 120px sans-serif', align: 'center', baseline: 'middle', fill: '#fff', split: 'grapheme',
182
+ perUnit: animate(cascade({ each: 0.06, duration: 0.6, ease: ease.outBack }), { y: 80, rotation: -20, opacity: 0 }),
183
+ })
184
+ ```
185
+
186
+ - `animate(selector, { x, y, rotation, scale, opacity })`: where a fully selected unit goes. x, y and rotation are
187
+ offsets; scale and opacity are the values at full selection.
188
+ - `cascade({ each, duration, ease, from, delay, direction })`: units arrive one after another (`direction: 'out'`
189
+ makes them leave). Spaces are skipped.
190
+ - `range({ start, end, offset, shape })`: selects a span of the text by fraction, like After Effects' range selector;
191
+ animate `offset` to sweep it. `shape` is `'square'`, `'rampUp'`, `'rampDown'`, `'triangle'`, `'round'`, `'smooth'`.
192
+ - `wiggly({ min, max, freq, seed, correlation })`: a changing random amount per unit.
193
+ - A plain function works too: `perUnit: (i, n, t, unit, units) => ({ y: 10 * Math.sin(t * 4 + i) })`.
194
+
195
+ ## Cel animation (motlab.js/addons/cel)
196
+
197
+ Exposure sheets, drawing swaps, indexed palettes and sprite sheets, timed the way 2D studios time them.
198
+
199
+ ```js
200
+ const sheet = xsheet({ rate: 24, end: 'loop', columns: {
201
+ body: '1 . 2 . 3 . 4 .', // one token per frame at 24 fps: on twos
202
+ eyes: 'o:50 c:3 o:40', // 'name:n' holds for n frames
203
+ } })
204
+ const colours = palette({ day: { skin: '#ffd9bc', line: '#2a1f1d' }, night: { skin: '#b7a5c8', line: '#0d0a14' } },
205
+ { use: 'night' })
206
+ const hero = slot({ id: 'hero', x: 400, show: sheet.column('body'), drawings: { 1: pose1, 2: pose2, 3: pose3, 4: pose4 } })
207
+ rect({ w: 60, h: 90, fill: colours('skin'), stroke: colours('line') })
208
+ ```
209
+
210
+ - `xsheet({ rate, end, columns })`: tokens are a drawing name, `.` or `|` (hold), `-`, `x` or `×` (empty cel), each
211
+ optionally `:n` frames. A column cannot start with a hold. `end` is `'hold'` (default), `'loop'` or `'blank'` and
212
+ applies to each column at its own length. `sheet.cell(column, t)` is the drawing name or null;
213
+ `sheet.column(column)` is the same as a Value; `sheet.keys(column)` lists the times the drawing changes.
214
+ - `slot({ show, drawings, skins, skin, ...groupProps })` shows `drawings[show(t)]` (null shows nothing). Its own
215
+ transform stays put while drawings swap. `skins: { winter: { 2: coatPose } }` with `skin: 'winter'` replaces only
216
+ the drawings the skin names.
217
+ - `on(2)` is a `time` remap: `group({ time: on(2) }, children)` animates the children on twos while the group's own
218
+ x, y and the rest still move on ones.
219
+ - `palette(sets, { use })` returns `style => colour`. Every set must name the same styles. `use` may be a function of
220
+ t to switch sets over time (a hit flash). Swap `use` to make a night version without touching any drawing.
221
+ - `aseprite(json)` reads Aseprite's sprite sheet JSON with durations, trim and tags (forward, reverse, pingpong,
222
+ repeat). `spriteSheet({ count, columns, size: [w, h], fps })` describes a sheet of equal frames.
223
+ `sprite({ sheet, src, tag, frame, smooth, ...groupProps })` plays it; its box is the full frame from (0, 0), so set
224
+ `anchor` at the feet. Aseprite sheets draw sharp by default.
225
+ - `onion(node, { before, after, step, keys, opacity, colors })` adds faded copies before (red) and after (green).
226
+ Pass `keys: sheet.keys('body')` to step by drawing instead of by `step` seconds. `lightTable(node, { at: [t1, t2] })`
227
+ pins copies at fixed times. Both are ordinary nodes, so they render and verify.
228
+
229
+ ## Camera (motlab.js/addons/camera)
230
+
231
+ ```js
232
+ const view = shots([
233
+ { at: 0, view: vcam({ position: follow(t => [heroX(t), 0], { duration: 1.2, lead: 0.3 }),
234
+ shake: shake({ trauma: trauma([{ at: 2, amount: 0.8 }]) }) }) },
235
+ { at: 4, view: { x: 600, y: -80, zoom: 1.5 }, blend: 0.8 },
236
+ ])
237
+ camera({ view, size: [1280, 720] }, [
238
+ plane(-3000, [mountains]), // far: pans at a quarter speed, drawn at screen size
239
+ plane(-1000, [hills]),
240
+ ground, hero, // z = 0: the main plane
241
+ plane(300, [grass]), // in front: passes faster
242
+ ])
243
+ ```
244
+
245
+ - `camera({ view, size, focal = 1000 }, children)` frames its children through a view: `{ x, y }` is the world point at
246
+ the frame's centre, `zoom` scales like a lens, `rotation` rolls in degrees, `dolly` moves the camera in px (near
247
+ planes grow faster than far ones), `ox, oy` shift the picture (shake). Each child's `z` is its depth in px toward
248
+ the viewer: `z = -focal` moves at half speed and looks half size. Children at or behind the camera hide.
249
+ - `plane(z, children)` scales a group so its children look their drawn size when the camera rests at zoom 1 and dolly
250
+ 0. Draw plane contents around (0, 0), the point the resting camera centres.
251
+ - `vcam({ x, y, position, zoom, rotation, dolly, shake })` builds a view from Values. `shots([{ at, view, blend, ease }])`
252
+ cuts, or blends over `blend` seconds from what was showing. Zoom blends on a log scale.
253
+ - `follow(target, { duration, lead })` trails a number or `[x, y]` Value like a critically damped spring: no
254
+ overshoot, caught up after `duration` seconds. It is exact and pure, so frames can be computed in any order.
255
+ - `trauma(hits, { decay })` is a 0..1 level from `[{ at, amount }]` hits, draining `decay` per second.
256
+ `shake({ trauma, x, y, rotation, freq, seed })` turns its square into noise offsets for `vcam`'s `shake`.
257
+ `punch(hits, { duration, freq })` jumps to each amount and rings back to 0: `zoom: t => 1 + kick(t)`.
258
+
259
+ ## Cloners (motlab.js/addons/clone)
260
+
261
+ ```js
262
+ const pop = track([[0, 0], [0.5, 1, ease.outBack]])
263
+ cloner({
264
+ x: 640, y: 360,
265
+ base: rect({ w: 40, h: 28, radius: 5, anchor: [20, 14], fill: '#2b3140' }),
266
+ layout: grid({ count: [20, 15], spacing: [56, 40] }), // 300 copies centred on (0, 0)
267
+ colors: ['#ff7a45'],
268
+ effectors: [
269
+ timeOffset({ seconds: 1, field: invert(radialField({ radius: 800 })) }), // a wave from the centre
270
+ transform({ scale: pop }), // played at each copy's own time
271
+ jitter({ rotation: 4, seed: 'deck' }),
272
+ (clone, t) => { if (clone.i % 7 === 0) clone.color = 0 }, // any function is an effector
273
+ ],
274
+ })
275
+ ```
276
+
277
+ - Layouts: `grid({ count: [columns, rows], spacing })`, `radial({ count, radius, start, sweep, align })` (tops face
278
+ outward), `line({ count, from, to })`, `points([[x, y, rotation?], ...])`, `onPath(path, { count, align, closed })`.
279
+ - Fields give 0..1 by position and time: `radialField({ center, radius, softness, ease })` (animate `radius` for a
280
+ spreading wave), `linearField({ from, to, ease })`, `noiseField({ scale, speed, seed })`, `invert(field)`, or any
281
+ `(x, y, t) => number`.
282
+ - Effectors run in order on `{ i, n, x, y, rotation, sx, sy, opacity, color, t }`. `transform({ x, y, rotation,
283
+ scale, opacity, field })` adds or multiplies by the field's weight; its values may be functions
284
+ `(t, clone) => number`, read at the copy's own time. `timeOffset({ seconds, each, field })` delays that time.
285
+ `jitter({ x, y, rotation, scale, opacity, time, freq, seed, field })` adds fixed random offsets, or drifting ones
286
+ with `freq`.
287
+ - The result is one `instances` item however many copies there are.
288
+
289
+ ## Particles (motlab.js/addons/particles)
290
+
291
+ ```js
292
+ particles({
293
+ base: ellipse({ w: 8, h: 8, anchor: [4, 4] }),
294
+ rate: 120, start: 0, end: 3, // births per second, evenly
295
+ bursts: [{ at: 1.5, count: 200 }],
296
+ origin: t => [heroX(t), 300], // read at each particle's birth, so a moving emitter leaves a trail
297
+ area: { radius: 20 }, // or { w, h }
298
+ life: [0.6, 1.4], speed: [200, 600], angle: [-120, -60], // [min, max] picks per particle
299
+ gravity: [0, 400], drag: 1.2, spin: [-180, 180],
300
+ grow: u => 1 - 0.5 * u, opacity: u => 1 - u, // u runs 0..1 over each particle's life
301
+ colors: ['#ffd166', '#ff7a45'], blend: 'add', seed: 'sparks',
302
+ })
303
+ ```
304
+
305
+ Each particle's state follows from its birth time, its own random numbers and its age, with exact gravity and drag,
306
+ so any frame can be drawn first and scrubbing backwards is free. Also: `rotation`, `align: true` (face the direction
307
+ of travel), `scale`, `turbulence: { amount, freq }`, and `color: (u, random) => index` to pick colours over life.
308
+ `rate` is a constant; use bursts or several emitters for changing rates.
309
+
310
+ ## Rigs (motlab.js/addons/rig)
311
+
312
+ A rig is solved once per time and read by any number of nodes. Bone props and params take a constant, a function of
313
+ t, or a `driver` that names other rig values. The evaluation order comes from those names, and a rig whose values
314
+ depend on themselves throws when it is built.
315
+
316
+ ```js
317
+ const r = rig({
318
+ params: { turn: track([[0, -1], [2, 1]]), reach: track([[0, 0], [1, 1]]) },
319
+ bones: {
320
+ body: { x: 0, y: 0 },
321
+ head: { parent: 'body', y: -160, rotation: driver('turn', turn => 8 * turn) },
322
+ hair: { parent: 'head', y: -90, length: 30, rotation: driver('head.angle', track([[-20, -60], [20, -120]])) },
323
+ upper: { parent: 'body', x: 80, y: -100, length: 50 },
324
+ lower: { parent: 'upper', x: 50, length: 45 },
325
+ },
326
+ constraints: [ik({ bones: ['upper', 'lower'], target: t => [150, -200], mix: driver('reach') })],
327
+ })
328
+
329
+ group({ x: 640, y: 600 }, [ // rig space: every bone() below is relative to this group
330
+ group({ ...r.bone('body') }, [bodyShape]),
331
+ group({ ...r.bone('head') }, [headShape]), // draw order is yours, not the bone tree's
332
+ shape({ path: t => path().moveTo(...r.point('upper')(t)).lineTo(...r.point('lower')(t)).lineTo(...r.tip('lower')(t)),
333
+ stroke: '#f80', strokeWidth: 20, lineJoin: 'round', lineCap: 'round' }),
334
+ bonesView(r), // debug: bones as lines
335
+ ])
336
+ ```
337
+
338
+ - Bones: `{ parent, x, y, rotation, scale, length }`. A bone points along its own +x; `length` places its tip for IK
339
+ and skinning. Children sit in the parent's space, so a child at `x: 50` starts where a 50 px parent ends.
340
+ - Reading the rig: `r.bone(name)` gives world `{ x, y, rotation, scale, skew }` props for a group placed in rig space
341
+ (exact, shear included); `r.local(name)` the final local props for groups nested like the bones; `r.point(name,
342
+ [lx, ly])`, `r.tip(name)`, `r.angle(name)`, `r.matrix(name)` and `r.param(name)` are Values.
343
+ - `driver(from, map)`: inputs are param names or `bone.x`, `bone.y`, `bone.angle` (world, degrees) and
344
+ `bone.rotation` (final local). `map` gets the inputs in order, then t. A track as map is a set driven key:
345
+ `driver('head.angle', track([[-20, 30], [20, -30]]))`. Outside a rig, `driven(value, keys)` does the same.
346
+ - Constraints, applied after the bones' own values: `ik({ bones: [parent, child], target, bend: 1 | -1, mix })` (two
347
+ bones, exact), `fabrik({ bones: [...chain], target, iterations, tolerance, mix })`, `aim({ bone, target, offset,
348
+ mix })`, `limit({ bone, min, max })`, and `pendulum({ bone, gravity, stiffness, damping, start })` for secondary
349
+ motion: the bone's tip swings around the pose its own rotation gives, lagging and overshooting as what it hangs
350
+ from moves. Bones need a `length` to swing. The swing is simulated from `start`, so any time can still be asked first. A target is `[x, y]` in rig space, a function of t, a driver, or
351
+ `{ bone, point }` to follow a point on another bone. `mix` blends from the pose before (0) to the solved one (1).
352
+ - `layers([{ clip, mode, weight, mask }, ...])` mixes clips of Values by channel name (`'arm.rotation'`, a param
353
+ name). `'replace'` (default) mixes toward the clip by weight; `'add'` adds weight times the value, and channels
354
+ ending in `scale` multiply. `mask: ['arm']` limits a layer to that bone's channels. Pass it as
355
+ `rig({ animation })`: each bone prop is the base its layers start from.
356
+
357
+ ## Deformers (motlab.js/addons/deform)
358
+
359
+ These return Values, so they plug into any prop: `shape({ path: warp(...) })`.
360
+
361
+ - `keyform(input, [[-1, shapeA], [0, shapeB], [1, shapeC]])` blends shapes stored at key values of an input, like
362
+ Live2D keyforms. With several inputs, give one key value per input and every combination:
363
+ `keyform([turn, nod], [[[-1, -1], a], [[1, -1], b], [[-1, 1], c], [[1, 1], d]])`. Shapes are numbers, arrays,
364
+ paths with the same commands in the same order, or objects of these.
365
+ - `blendShapes(base, [[smileShape, smileWeight], [openShape, openWeight]])` adds each target's difference from the
366
+ base by its weight.
367
+ - `track(keys, { type: shapeType })` tweens paths point by point.
368
+ - `lattice({ box: [x, y, w, h], columns, rows })` and `warp(shape, grid, points)`: a grid warp. `grid.rest` is the
369
+ resting points; `grid.map((x, y, u, v) => [x2, y2])` makes a moved copy; keyform those lists to animate the warp.
370
+ - `skin(shape, r, { bones, bindAt, falloff })` bends a path drawn in rig space at the pose of time `bindAt` with
371
+ the rig's bones, weighting each point by its distance to each bone.
372
+ - `gridMesh({ box, columns, rows, crop })` gives `{ points, uvs, triangles }` for a `mesh` node: a grid over `box`
373
+ (node px) showing the image px in `crop` (default: the same numbers as `box`). Its points are a plain list, so
374
+ `warp(m.points, grid, points)` and `skin(m.points, r, options)` bend it like a path.
375
+
376
+ ## Traced line art (motlab.js/addons/trace)
377
+
378
+ `trace(pixels, { threshold, speck, close, tolerance, corner })` turns scanned or drawn line art into vector cels.
379
+ `pixels` is RGBA `{ width, height, data }`, as `getImageData` gives. It returns:
380
+
381
+ - `lines`: the ink as one filled path, in image px. Pale lines, such as blue construction lines, stay out when they
382
+ are lighter than `threshold` (0..1, default 0.5); specks and pinholes smaller than `speck` px are cleaned up.
383
+ - `regions`: the closed areas between lines, `{ id, area, box, point, outside }`, numbered in reading order.
384
+ `regionAt(x, y)` gives the area under a point, or -1 on a line. `close` (px) seals small gaps in the lines first.
385
+ - `fill(areas, { trap })`: one path over areas picked by id or by a point inside, grown `trap` px under the lines.
386
+ - `node({ fills, paint, line, trap, ...groupProps })`: the coloured areas under the lines as a group. `fills` maps a
387
+ style to points or ids: `{ skin: [[310, 420]], hair: [[300, 120], [420, 150]] }`. Pass a cel palette as `paint`
388
+ and its line style as `line`, and the traced drawing recolours with the palette set in use.
389
+
390
+ Trace once, outside time functions: it reads every pixel. Load the scan in the page, draw it on a canvas, read it
391
+ with `getImageData`, then build the scene.
392
+
393
+ ## Simulations
394
+
395
+ Anything that needs history (physics, collisions, input-driven state) runs as a simulation: fixed ticks from a known
396
+ start, with snapshots, so `sim.at(t)` answers any t in any order by stepping from the nearest snapshot.
397
+
398
+ ```js
399
+ const ball = simulate({
400
+ hz: 120, // ticks per second
401
+ init: () => ({ y: 0, v: 0 }), // plain data only: numbers, arrays, typed arrays, objects
402
+ step: (s, input, dt, tick) => { // change s in place, or return a new state
403
+ s.v += dt * 980
404
+ s.y += dt * s.v
405
+ if (s.y > 300) { s.y = 300; s.v *= -0.7 }
406
+ },
407
+ input: inputTrack([[0, {}], [240, { kick: true }], [241, {}]]), // [tick, input], held until the next
408
+ })
409
+ rect({ w: 20, h: 20, y: t => ball.at(t).y }) // mixed between ticks; treat the result as read-only
410
+ ```
411
+
412
+ - Options: `start` (scene time of tick 0; the initial state shows before it), `snapshotEvery` (ticks, default hz / 2;
413
+ smaller makes backward scrubbing cheaper), `lerp` (custom mix, or `false` to show each tick until the next),
414
+ `params` (anything the steps read from outside, so the bake key changes with it).
415
+ - `await prepare(sim, { until, store })` bakes the simulation once and reuses the bake while nothing that decides it
416
+ changed: the key hashes the engine VERSION, hz, the source of init, step and input, and params. `memoryStore()` is
417
+ the default store; any `{ get, set }` with async methods works.
418
+ - `dmath` has `sin cos tan atan atan2 asin acos exp log log2 log10 pow sinh cosh tanh sqrt hypot`, built from + - * /
419
+ and sqrt, so they return the same bits on every engine. Math.sin and the rest differ between V8 and JavaScriptCore.
420
+ Use dmath (and `x * x`, not `x ** 2`) inside steps whose state must hash the same on every machine.
421
+
422
+ ## Physics (motlab.js/addons/physics)
423
+
424
+ 2D rigid bodies solved with XPBD. The state hashes the same on every engine.
425
+
426
+ ```js
427
+ const world = physics({
428
+ hz: 60, substeps: 4, start: 1, gravity: [0, 980],
429
+ planes: [{ point: [0, 600], normal: [0, -1] }], // the floor; solid below the point
430
+ bodies: [
431
+ { id: 'ball', shape: circle(40), x: -500, y: 200, vx: 1600, vy: -500, density: 20 },
432
+ ...cards.map(c => ({ shape: box(40, 28), x: c.x, y: c.y })),
433
+ ],
434
+ joints: cards.map((_, i) => pin({ body: i + 1, hz: 3, angleHz: 2, breakAt: 30 })),
435
+ })
436
+ group({ ...world.body('ball') }, [ellipse({ x: -40, y: -40, w: 80, h: 80 })])
437
+ instances({ base: rect({ w: 40, h: 28, anchor: [20, 14] }), data: world.instances(cardIds, { color: (i, t) => ... }) })
438
+ ```
439
+
440
+ - Bodies: `{ id, shape: circle(r) | box(w, h), x, y, angle, vx, vy, spin, density, restitution, friction, damping,
441
+ group, fixed, kinematic }`. `fixed` never moves; `kinematic: t => [x, y, angle]` follows a path and pushes others;
442
+ bodies sharing a non-zero `group` pass through each other.
443
+ - Joints: `pin({ body, at, local, hz, angleHz, breakAt })` springs a body (or its `local: [x, y]` anchor) to a world
444
+ point (rigid without hz) and lets go for good past `breakAt` px; `link({ a, b, localA, localB, length, hz })` keeps
445
+ two bodies or anchor points apart.
446
+ - Reading: `world.at(t)` is the state (`x`, `y`, `c`, `s` cosine and sine of the angle, `vx`, `vy`, `w`, `broken` per
447
+ joint); `world.body(ref)` gives group props; `world.instances(refs, { scale, opacity, color })` gives instances
448
+ data; `world.hash(tick)` hashes the exact state; `world.sim` is the simulation for `prepare`.
449
+ - `simParticles({ base, rate, bursts, life, origin, speed, angle, gravity, drag, restitution, friction, planes, world,
450
+ ... })`: particles that bounce off planes and off a world's bodies, as one instances node. The same birth options
451
+ as the analytic particles addon.
452
+
453
+ ## State machines (motlab.js/addons/machine)
454
+
455
+ ```js
456
+ const hero = machine({
457
+ initial: 'idle', hz: 60, input: inputTrack([...]), fade: 0.15,
458
+ states: {
459
+ idle: { on: { walk: 'walk', jump: 'jump' } }, // a truthy input field moves to that state
460
+ walk: { on: { stop: 'idle' }, when: [[(input, { time }) => time > 3, 'idle']] },
461
+ jump: { after: 0.6, to: 'walk', fade: 0.05 },
462
+ },
463
+ })
464
+ hero.state(t) // 'walk'
465
+ hero.log(t) // [{ at, from, to }, ...]: drawing a frame only searches this
466
+ const clip = hero.blend({ idle: idleClip, walk: walkClip, jump: jumpClip }) // each from its entry, crossfaded
467
+ rig({ bones, animation: layers([{ clip }]) })
468
+ ```
469
+
470
+ - `blendTree(speed, [[0, idle], [1, walk], [3, run]])` mixes clips by one param, or by two with a full grid of keys.
471
+
472
+ ## Audio (motlab.js/addons/audio)
473
+
474
+ Analyse the music once, then drive anything from it. The analysis is plain data, so drawing stays a pure function
475
+ of time.
476
+
477
+ ```js
478
+ const sound = await decodeAudio('./music.mp3') // browser: mono samples plus the AudioBuffer
479
+ const music = analyze(sound.samples, { sampleRate: sound.sampleRate, fps: 30 })
480
+ music.tempo // 120.2
481
+ music.beats // [0.017, 0.505, 1.004, ...] seconds
482
+ music.bars // a guess at bar starts, four beats a bar
483
+ const beat = pulse(music.beats, { attack: 0.02, decay: 0.12 }) // 1 on each beat, falling away
484
+ const bass = levels(music).band('low') // 0..1 per frame; also 'mid', 'high', and rms
485
+ scene({ ..., markers: beatMarkers(music), assets: { audio: { music: './music.mp3' } },
486
+ root: rect({ scale: t => 1 + 0.3 * beat(t), opacity: t => 0.5 + 0.5 * bass(t), ... }) })
487
+ ```
488
+
489
+ - `analyze(samples, { sampleRate, fps, bands, bpm, minBpm, maxBpm, tightness })`: `bands` are `{ name: [lowHz,
490
+ highHz] }`; `bpm` (default 120) is the tempo to prefer when the music reads equally well at half or double speed.
491
+ - `beatClock(music.beats)(t)` gives `{ index, phase }` for motion that loops once a beat.
492
+ - With a cloner, put `timeOffset` before a `transform` that reads `pulse`: each beat then runs across the copies.
493
+
494
+ ## Footage and edits (motlab.js/addons/media, motlab.js/addons/edit)
495
+
496
+ ```js
497
+ const cut = edit({
498
+ fps: 30,
499
+ media: { shot: { duration: 6 } }, // optional: refuses ranges past the media's end
500
+ tracks: [cuts('shot', [[2, 2.6], [0.5, 1.3], [4, 4.6]])], // source [in, out] seconds, back to back
501
+ })
502
+ const tighter = slip(roll(cut, { item: 0, by: 3 }), { item: 2, by: 6 }) // by is in frames
503
+ scene({ duration: tighter.duration, assets: { videos: { shot: './shot.mp4' } }, root: footage(tighter, { scale: 1.5 }) })
504
+ ```
505
+
506
+ - Tracks hold `clip({ media, in, duration, name })` and `gap(duration)` in seconds; the edit rounds them to whole
507
+ frames. `edit.at(t, track)` gives `{ media, source, item, start, local }`, or null in a gap.
508
+ - Operations return a new edit: `split({ at })`, `ripple({ item, edge: 'in' | 'out', by })` (the track gets longer or
509
+ shorter), `roll({ item, by })` (moves the cut after `item`), `slip({ item, by })` (other footage, same place),
510
+ `slide({ item, by })` (moves the clip, its neighbours absorb it).
511
+ - `footage(edit, { track, ...props })` is a video node that follows a track. Several tracks: one footage node each,
512
+ the top track last.
513
+ - `toOTIO(edit, { urls })` and `fromOTIO(json)` read and write OpenTimelineIO JSON, for editors.
514
+ - `demux(bytes)` reads an MP4's tracks and samples (plain or fragmented); `await openVideo(url)` decodes exact frames
515
+ outside a scene: `video.frame(video.frameIndexAt(t))`.
516
+
517
+ ## Games (motlab.js/addons/game, motlab.js/addons/input)
518
+
519
+ A game is a simulation whose input is recorded while someone plays. The recording then replays the round exactly,
520
+ renders it to video with a different camera, and scrubs backwards.
521
+
522
+ ```js
523
+ const rules = {
524
+ init: () => ({ x: 0, y: 0, vy: 0, score: 0 }),
525
+ step: (s, { held, pressed, released }, { dt, tick, emit }) => { // change s in place; plain data only
526
+ if (held.right) s.x += 300 * dt
527
+ if (pressed.jump) { s.vy = -800; emit('jump', { x: s.x }) } // events for sounds and effects
528
+ s.vy += 2000 * dt
529
+ s.y = Math.min(0, s.y + s.vy * dt)
530
+ },
531
+ }
532
+
533
+ // Live: read devices, record each tick at its real time, play with the player.
534
+ const pad = controls({ jump: ['Space', 'KeyW', 'pad:0'], right: ['ArrowRight', 'KeyD', 'pad:axis0+'] })
535
+ let origin = performance.now()
536
+ const record = recorder(tick => pad.readAt(origin + tick * 1000 / 60, origin + (tick - 1) * 1000 / 60))
537
+ const live = game({ ...rules, input: record, hz: 60 })
538
+ const run = player(t => draw(liveScene.evaluate(t)), { duration: 30, loop: false,
539
+ cues: (from, to) => live.events(from, to), onCue: e => playSound(sounds[e.name]) })
540
+ origin = performance.now(); run.play()
541
+
542
+ // Later: the same round from the recording alone, with any camera, any frame, in any order.
543
+ const saved = record.toJSON() // { hz, entries } to keep
544
+ const replay = game({ ...rules, input: fromRecording(saved), hz: 60 })
545
+ ```
546
+
547
+ - A step sees `held` (actions down this tick), `pressed` and `released` (changes since the tick before) and a context
548
+ with `tick`, `t`, `dt` and `emit(name, data)`. `game.at(t)` is the state (mixed between ticks with `lerp`),
549
+ `game.events(from, to)` the events emitted in between, `game.sim` the simulation for `prepare`.
550
+ - Bindings: KeyboardEvent codes (`'Space'`, `'ArrowLeft'`), `'pointer'`, `'pad:0'` (gamepad button), `'pad:axis0+'`
551
+ or `'pad:axis0-'` (an axis past half way) and `'pad:axis0'` (the value). Only active actions appear in the input.
552
+ - `controls().readAt(time, since)` answers from the event log, so slow frames lose no presses and a tap shorter than a
553
+ tick still counts. Gamepads have no events and are read as they are.
554
+ - The recorder reads each tick once, the first time the game steps it; every later read of that tick, a seek
555
+ included, returns the recorded value. That is what makes a live session a pure function of its recording.
556
+ - `player(render, { duration: Infinity, loop: false })` runs an open-ended live game; `cues` and `onCue` fire for
557
+ what forward playback passes (scene.markers.between works too), never on seeks.
558
+
559
+ ## Adapters (motlab.js/adapters/*)
560
+
561
+ Adapters join motlab.js with libraries you install yourself: Rapier, Lottie, Rive, three.js and PixiJS. They are
562
+ optional peer dependencies, and every adapter takes the library as an argument instead of importing it, so your code
563
+ and the adapter share one copy. In a page without a bundler, map the package names with an import map.
564
+
565
+ ```js
566
+ import RAPIER from '@dimforge/rapier2d-deterministic-compat'
567
+ import { rapier } from 'motlab.js/adapters/rapier'
568
+
569
+ await RAPIER.init()
570
+ const world = rapier(RAPIER, {
571
+ build(w, R) { // build in px; lengthUnit (default 100) is px per metre
572
+ w.createCollider(R.ColliderDesc.cuboid(400, 10).setTranslation(400, 500))
573
+ const ball = w.createRigidBody(R.RigidBodyDesc.dynamic().setTranslation(400, 0))
574
+ w.createCollider(R.ColliderDesc.ball(20), ball)
575
+ return { ball } // the bodies to follow, by name
576
+ },
577
+ before({ bodies, tick, t }) {}, // ahead of every step: kinematic targets, forces
578
+ })
579
+ group({ ...world.body('ball') }, [ellipse({ w: 40, h: 40, anchor: [20, 20] })])
580
+ ```
581
+
582
+ - `rapier(RAPIER, { build, before, input, gravity, lengthUnit, hz, start, snapshotEvery, params })` is a simulation
583
+ like `physics()`: `at(t)`, `body(name)`, `instances(names, style)`, `index`, `names`, `hash(tick)`, `sim` and
584
+ `dispose()` (alias `free()`). Any time, in any order, steps from the nearest Rapier snapshot. Use a `-deterministic`
585
+ build for the same numbers on every machine; the `-compat` builds carry their WebAssembly inline and run in Node too.
586
+ - `lottie(lottieWeb, { data })` loads a parsed Lottie JSON with lottie-web's canvas renderer and returns
587
+ `{ duration, frameRate, size, node, dispose }`. `node({ x, y, w, h, time, loop, ... })` is a layer that seeks the
588
+ animation to the frame for its time; without loop the last frame holds.
589
+ - `rive(Rive, { src, wasm, artboard, animation, stateMachine, inputs, hz })` loads a .riv file's bytes with
590
+ `@rive-app/canvas-advanced` and returns `{ size, node, dispose }`. A linear animation is posed by setting its time. A
591
+ state machine steps forward at hz (default 60) from its start, so drawing an earlier time starts it over; `inputs`
592
+ drive its inputs by name, and a trigger fires when its Value turns true. `node({ w, h, fit, alignment, time, ... })`.
593
+ Images and fonts inside the file are decoded before `rive()` resolves, so keep assets in the file. Rive sees a
594
+ clock that stands still, so nothing in it can run on the real clock. `wasm` is where `rive.wasm` is served.
595
+ - `threeLayer({ w, h, renderer, scene, camera, update, ... })` draws a three.js scene as a layer at (0, 0, w, h).
596
+ `update(t)` must pose everything from t, such as `mixer.setTime(t)` for glTF clips. Make the WebGLRenderer with
597
+ `alpha: true`, and make every mesh, material and texture before the layer: three.js names new things with
598
+ `Math.random()`, which throws while a frame is drawn.
599
+ - `pixiLayer({ w, h, renderer, stage, update, ... })` does the same for a PixiJS stage. Make the renderer with
600
+ `autoDetectRenderer({ preference: 'webgl', backgroundAlpha: 0 })` and leave Pixi's ticker out.
601
+ - `threeTexture(THREE, scene, { scale, renderer })` and `pixiTexture(PIXI, scene, options)` go the other way: a motlab
602
+ scene as a texture. Call `at(t)` before the library renders, `await prepare(t)` first for footage, and `dispose()`
603
+ when done.
604
+ - `canvasLayer({ w, h, time, render })` and `sceneCanvas(scene, options)` (with `dispose()`) from
605
+ `motlab.js/adapters/canvas` are the building blocks, for any other library that draws onto a canvas of its own.
606
+ - Layers from adapters are draw nodes: Canvas 2D and WebGL2 draw them, SVG does not.
607
+
608
+ ## Timeline
609
+
610
+ ```js
611
+ const story = timeline()
612
+ .add(logo, { at: 0, dur: 1, hold: 'after' })
613
+ .add(title, { at: '<0.3', dur: 0.8, hold: 'after' }) // 0.3 s after the previous item starts
614
+ .label('cards', '+=0.2') // 0.2 s after the timeline's current end
615
+ .each([cardA, cardB, cardC], { at: 'cards', dur: 1, stagger: 0.12, from: 'start', hold: 'after' })
616
+ ```
617
+
618
+ - Each child sees local time `(t - at) * speed`, so an animation written from 0 can be placed anywhere. Everything
619
+ inside the child, including the nodes a component builds, gets that local time.
620
+ - A child is drawn only during `[at, at + dur)`: not before `at`, not after the end. Use `hold: 'after'` to keep its
621
+ last frame on screen afterwards, `'before'` to show its first frame earlier, or `'both'`. Forgetting
622
+ `hold: 'after'` makes things vanish.
623
+ - `dur` is how long the item is shown; it never stretches the animation (use `speed` for that). It may run past the
624
+ scene's end.
625
+ - Positions: seconds, `'<'` (start of the previous item), `'>'` (its end), `'<0.3'`, `'>-0.2'`, `'+=0.4'`, `'-=0.2'`
626
+ (from the timeline's current end), a label, `'label+=0.2'`. Without `at`, an item goes at the current end. Labels
627
+ take the same positions, so `.label('pills', 2)` puts a label at 2 s.
628
+ - `dur` may be left out, in `add` and in `each`, only for children with their own duration: another timeline, or a
629
+ component instance whose component sets `duration`. Plain nodes need `dur`.
630
+ - `each` options: `stagger` is the gap in seconds between neighbours, and `from` is `'start'` (default), `'end'`,
631
+ `'center'` or an index to start the wave from. Afterwards `'<'` and `'>'` refer to the whole group.
632
+ - Things that run for the whole scene, such as a background or a starfield, need no timeline item: put them in a
633
+ group next to the timeline, as in `root: group({}, [stars, story])`.
634
+ - `stagger(i, { each, from, n })` gives the delay for item i, for your own Values. `from: 'end'` and `'center'` need
635
+ `n`, the number of items.
636
+
637
+ ## Components
638
+
639
+ ```js
640
+ const badge = component({
641
+ name: 'badge',
642
+ params: { label: 'New', color: '#ff5a1f' },
643
+ duration: 1,
644
+ build: p => group({ scale: spring({ duration: 0.6, bounce: 0.4 }), anchor: [80, 30] }, [
645
+ rect({ id: 'bg', w: 160, h: 60, radius: 30, fill: p.color }),
646
+ text({ id: 'label', text: p.label, x: 80, y: 30, align: 'center', baseline: 'middle', fill: '#fff' }),
647
+ ]),
648
+ })
649
+ const a = badge({ id: 'b1', label: 'Fast', x: 200, y: 100 }) // ids inside become 'b1/bg', 'b1/label'
650
+ const dark = badge.variant({ color: '#111' }) // a variant keeps only its changes
651
+ ```
652
+
653
+ Each instance needs an `id`, takes its params plus the common and layer node props, and rejects unknown names.
654
+
655
+ ## Scene
656
+
657
+ ```js
658
+ const s = scene({
659
+ duration: 4, // seconds
660
+ size: [1920, 1080], // logical px
661
+ background: '#101114',
662
+ assets: { fonts: [{ family: 'Inter', src: './Inter.woff2', weight: '100 900' }], images: { logo: './logo.svg' },
663
+ videos: { shot: './shot.mp4' }, audio: { music: './music.mp3' } }, // audio is for players and exporters
664
+ markers: [{ at: 2, name: 'impact', kind: 'cue' }],
665
+ root: story,
666
+ })
667
+ s.evaluate(1.5) // display list: plain data, any t, any order
668
+ s.evaluate(1.5, { overrides: { 'title.y': 300 } })
669
+ s.frameCount(30) // Math.round(duration * fps)
670
+ s.frameTime(45, 30) // 1.5
671
+ s.markers.state('impact', t) // false before 2 s, true after; safe in Values
672
+ s.markers.list // your markers plus every timeline label
673
+ ```
674
+
675
+ ## Checking and drawing
676
+
677
+ ```js
678
+ const result = verify(s, { fps: 30 }) // { ok, frames, mismatches, diffs: [{ t, id, prop, first, second }] }
679
+
680
+ const draw = canvas2d(document.querySelector('canvas'), { scale: 1 })
681
+ await draw.load(s) // sizes the canvas, loads fonts and images; a missing one throws
682
+ draw(s.evaluate(t))
683
+ const pixels = await verifyPixels(s, { fps: 30 }) // browser only: compares pixels in order and shuffled
684
+ ```
685
+
686
+ - Footage decodes ahead of drawing: before drawing a list with video items, `await draw.prepare(list)`. toPNG,
687
+ toPNGSequence, toSpriteSheet and verifyPixels do this for you. Call `draw.dispose()` when tearing down a renderer
688
+ to release video decoders, Blob URLs and WebGL2 resources.
689
+ - `svg(svgElement)` is a renderer with the same `load`, `prepare` and call shape that draws SVG elements; `.toString()` gives the
690
+ markup. Draw nodes throw there.
691
+ - `webgl2(canvas, { scale })` has the same `load`, `prepare` and call shape and draws on the GPU: images, footage,
692
+ layers in every blend mode, mattes, effects, transitions (including GLSL ones), meshes and instances. Shapes and
693
+ text are rasterized by Canvas 2D on the CPU, so frames repeat exactly, and only the area each run covers is
694
+ uploaded. Use it for heavy effects and for thousands of instances, which it draws in one call per item. Its own
695
+ `verifyPixels(s, { fps })` and
696
+ `toPNG(s, t, { scale })` read pixels back from the GPU.
697
+ - Canvas 2D and SVG draw effects and the built-in transitions too, as close matches. GLSL transitions throw there.
698
+ - `await toPNG(s, t, { scale })` gives one frame as a PNG Blob; `for await (const { frame, t, png } of
699
+ toPNGSequence(s, { from, to, fps, scale }))` gives a range one frame at a time.
700
+ - `await toSpriteSheet(s, { from, to, fps: 24, columns, scale, padding, tags })` gives `{ png, json }`: one image plus
701
+ Aseprite-style JSON that `aseprite()` and game engines read. Frames that draw the same display list share a cell,
702
+ and a held run becomes one longer frame, so a cycle on twos needs half the cells. `planSpriteSheet` returns the
703
+ layout and JSON without drawing.
704
+
705
+ ## Playing and animating the page
706
+
707
+ - `player(t => draw(s.evaluate(t)), { duration: s.duration, loop: true, audio })` gives `play()`, `pause()`, `toggle()`,
708
+ `seek(t)`, `destroy()`, `time` and `playing`. `render` may return a Promise (for `draw.prepare(list)`). It draws
709
+ t = 0 at once. The player is the only place that may use `requestAnimationFrame`, because it moves t from outside the
710
+ scene. `audio` (an AudioBuffer, such as `(await decodeAudio(url)).buffer`) plays in step with t.
711
+ - `bind(element, { x, y, rotation, scale, opacity, text, style: { 'background-color': ... }, attr: { r: ... } })`
712
+ returns `(t) => void` that applies the same Values to an HTML or SVG element, writing only what changed. Play it with
713
+ `player(bind(el, props), { duration })`, or call several binds from one player.
714
+
715
+ ## Complete example
716
+
717
+ ```js
718
+ import { scene, timeline, group, rect, text, track, ease, spring, wiggle, rand } from 'motlab.js'
719
+
720
+ const W = 1280
721
+ const H = 720
722
+
723
+ const title = text({
724
+ id: 'title', text: 'Hello', x: W / 2, y: track([[0, 380], [0.8, 340, ease.outCubic]]),
725
+ opacity: track([[0, 0], [0.4, 1]]), font: '800 96px sans-serif', align: 'center', baseline: 'middle', fill: '#fff',
726
+ })
727
+
728
+ const dots = group({}, Array.from({ length: 40 }, (_, i) => rect({
729
+ id: `dot-${i}`, w: 8, h: 8, anchor: [4, 4],
730
+ x: rand.range(0, W, 'dots', i, 'x'),
731
+ y: t => rand.range(0, H, 'dots', i, 'y') + 20 * Math.sin(t * 2 + i),
732
+ fill: rand.pick(['#ff5a1f', '#ffd166'], 'dots', i, 'color'),
733
+ })))
734
+
735
+ const pop = spring({ duration: 0.8, bounce: 0.4 })
736
+ const box = rect({ id: 'box', w: 200, h: 200, radius: 24, anchor: [100, 100], x: W / 2, y: 540,
737
+ scale: pop, rotation: wiggle({ freq: 1, amp: 4, seed: 'box' }), fill: '#ff5a1f' })
738
+
739
+ export const hello = scene({
740
+ duration: 3, size: [W, H], background: '#101114',
741
+ root: timeline()
742
+ .add(dots, { at: 0, dur: 3 })
743
+ .add(title, { at: 0.2, dur: 0.8, hold: 'after' })
744
+ .add(box, { at: '>', dur: pop.duration, hold: 'after' }),
745
+ })
746
+ ```
747
+
748
+ ## Common mistakes
749
+
750
+ - Things disappear after their timeline item ends: add `hold: 'after'`.
751
+ - `Math.random()` in a scene throws: use `rand(seed, index)`.
752
+ - Expecting the ease on the first key to do something: it shapes the segment that ends at its key, so the first key's
753
+ ease is unused.
754
+ - Passing radians to `rotation`: node rotation is degrees. Only `path().arc` and `ellipse` use radians.
755
+ - Dots in ids: `id: 'card.1'` is rejected because overrides use `id.prop`. Use `card-1`.
756
+ - Forgetting that a spring runs 0 to 1: scale it to the range you need.
757
+ - Using a Value's time as scene time inside a timeline: children get local time from their item start.
758
+ - A font family that is neither generic nor in `assets.fonts` throws: declare it, or use `sans-serif`.
759
+ - Expecting a matte node to show: it only cuts the group. Add it to the tree as well if it should be seen.
760
+ - An xsheet column that starts with `.`: there is nothing to hold yet. Start with a drawing or `-`.
761
+ - Giving camera children depth with anything but `z`: the camera reads each child's own `z` prop. Wrap a layer in
762
+ `plane(z, [...])` to keep it at its drawn size.
763
+ - Reusing one Float32Array in an `instances` data function: return a new one each call.
764
+ - Reading the cloner's t in a `transform` value: values get the copy's own time, which `timeOffset` shifts. That is
765
+ what turns one track into a wave.
766
+ - Nesting bone groups and also using `r.bone()`: `bone()` is already the world transform, so place those groups side
767
+ by side in rig space. Use `r.local()` only when the groups nest like the bones.
768
+ - A driver that reads a value which depends on itself, such as a bone's rotation from its own child's angle: the rig
769
+ throws with the loop when built.
770
+ - Blending paths with different commands in keyforms or blend shapes: draw every key shape with the same commands
771
+ in the same order.
772
+ - Keeping state in a closure inside a simulation step: put everything that changes in the state, or snapshots and
773
+ seeking go wrong.
774
+ - Mutating what `sim.at(t)` returns: it may be shared with the next call. Copy it first if you need to change it.
775
+ - An input field that stays true in an inputTrack: it keeps firing `on` each tick. Write a press as one tick.
776
+ - Drawing a list with footage without `await draw.prepare(list)`: drawing is synchronous and throws for a frame that
777
+ has not been decoded.
778
+ - Reading `Math.random` or the clock in a game step: use `rand(seed, tick)`, and take time from the context.
779
+ - Sampling input when frames render instead of with `readAt` at each tick's time: a slow frame then drops presses.
780
+ - Expecting `assets.audio` to be analysed for you: call `analyze` yourself; the scene only records the file so players
781
+ and exporters can play or mix it.
782
+ - Putting `satsuei()` in the effects list without spreading it: it returns a list. Write `effects: [...satsuei()]`.
783
+ - A transition between two small cards without `box`: it then plays across the whole frame. Give the cards' area.
784
+ - A `{ glsl }` transition drawn with Canvas 2D or SVG: it throws. Draw that scene with `webgl2`.
785
+ - Mesh `uvs` in node px: they are image px. `gridMesh` takes a separate `crop` for that reason.
786
+ - Calling `trace` inside a time function: it reads the whole image. Trace once and reuse the result.
787
+ - A fill point that lands on a line: `trace` throws. Pick a point well inside the area, or pass the area's id.
788
+ - Creating three.js objects inside a threeLayer's update: three.js names them with `Math.random()`, which throws.
789
+ Make them once, before the layer, and only move them in update.
790
+ - Driving a Pixi stage with its ticker, or a three.js clip with `mixer.update(delta)`: set state from t instead,
791
+ with `mixer.setTime(t)` for clips.
792
+ - Using a Rapier build without `-deterministic` and expecting other machines to match.
793
+ - Expecting a Rive state machine to seek like a clip: an earlier time replays it from the start, so long state
794
+ machine shots scrubbed backwards cost more.