motlab.js 0.1.0 → 0.1.1
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/CHANGELOG.md +9 -0
- package/README.md +5 -1
- package/llms.txt +794 -794
- package/package.json +107 -107
- package/src/adapters/lottie.js +102 -102
- package/src/adapters/rapier.js +163 -163
- package/src/adapters/rive.js +316 -316
- package/src/addons/deform.js +441 -441
- package/src/addons/physics.js +980 -980
- package/src/core/nodes.js +328 -328
- package/src/core/scene.js +678 -678
- package/src/core/version.js +1 -1
- package/src/renderer/canvas2d.js +950 -950
- package/src/renderer/svg.js +589 -589
- package/src/renderer/webgl2.js +1331 -1331
- package/types/core/version.d.ts +1 -1
package/src/adapters/rive.js
CHANGED
|
@@ -1,316 +1,316 @@
|
|
|
1
|
-
// Rive files inside a motlab scene, drawn by Rive's canvas runtime (@rive-app/canvas-advanced). A linear animation is
|
|
2
|
-
// a seek: its time is set from t. A state machine only moves forward, so it steps at a fixed rate from its start, and
|
|
3
|
-
// drawing an earlier moment starts it over; each tick is the same whichever way it was reached.
|
|
4
|
-
import { canvasLayer } from './canvas.js'
|
|
5
|
-
import { at } from '../core/math.js'
|
|
6
|
-
import { makeSurface } from '../renderer/pixels.js'
|
|
7
|
-
import { withClock } from '../core/guard.js'
|
|
8
|
-
|
|
9
|
-
/** @typedef {import('@rive-app/canvas-advanced').RiveCanvas} RiveCanvas */
|
|
10
|
-
/** @typedef {import('@rive-app/canvas-advanced').Artboard} Artboard */
|
|
11
|
-
/** @typedef {import('@rive-app/canvas-advanced').File} RiveFile */
|
|
12
|
-
/** @typedef {import('@rive-app/canvas-advanced').SMIInput} SMIInput */
|
|
13
|
-
/** @typedef {typeof import('@rive-app/canvas-advanced').default} RiveFactory */
|
|
14
|
-
/** @typedef {import('../core/nodes.js').CommonProps} CommonProps */
|
|
15
|
-
/** @typedef {import('../core/nodes.js').Node} Node */
|
|
16
|
-
/**
|
|
17
|
-
* @template T
|
|
18
|
-
* @typedef {import('../core/math.js').Value<T>} Value
|
|
19
|
-
*/
|
|
20
|
-
/** @typedef {'fill' | 'contain' | 'cover' | 'fitWidth' | 'fitHeight' | 'none' | 'scaleDown'} Fit */
|
|
21
|
-
/**
|
|
22
|
-
* @typedef {'topLeft' | 'topCenter' | 'topRight' | 'centerLeft' | 'center' | 'centerRight' | 'bottomLeft' |
|
|
23
|
-
* 'bottomCenter' | 'bottomRight'} Alignment
|
|
24
|
-
*/
|
|
25
|
-
|
|
26
|
-
// Rive reads the clock when it makes a state machine and when it draws, and what it draws depends on the time between
|
|
27
|
-
// draws. Every call into Rive sees the clock stand still at this moment, so a pose looks the same however it was reached.
|
|
28
|
-
const STILL = 0
|
|
29
|
-
|
|
30
|
-
const TICK_EPSILON = 1e-9
|
|
31
|
-
/** @type {Fit[]} */
|
|
32
|
-
const FITS = ['fill', 'contain', 'cover', 'fitWidth', 'fitHeight', 'none', 'scaleDown']
|
|
33
|
-
|
|
34
|
-
/** Runtimes by factory and wasm address, so files share one WebAssembly instance. @type {WeakMap<RiveFactory, Map<string, Promise<RiveCanvas>>>} */
|
|
35
|
-
const runtimes = new WeakMap()
|
|
36
|
-
|
|
37
|
-
/** @param {RiveFactory} Rive @param {string | undefined} wasm */
|
|
38
|
-
function runtimeFor(Rive, wasm) {
|
|
39
|
-
let byWasm = runtimes.get(Rive)
|
|
40
|
-
if (!byWasm) runtimes.set(Rive, (byWasm = new Map()))
|
|
41
|
-
const key = wasm ?? ''
|
|
42
|
-
let runtime = byWasm.get(key)
|
|
43
|
-
if (!runtime) byWasm.set(key, (runtime = Rive(wasm ? { locateFile: () => wasm } : undefined)))
|
|
44
|
-
return runtime
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* The time to set on a linear animation `seconds` into playing it, from its start: one-shot animations hold their
|
|
49
|
-
* end, loops wrap, and ping-pong runs back and forth.
|
|
50
|
-
* @param {number} seconds @param {number} duration @param {number} loopValue 0 one-shot, 1 loop, 2 ping-pong.
|
|
51
|
-
*/
|
|
52
|
-
export function animationTime(seconds, duration, loopValue) {
|
|
53
|
-
const s = Math.max(0, seconds)
|
|
54
|
-
if (!(duration > 0)) return 0
|
|
55
|
-
if (loopValue === 1) return s % duration
|
|
56
|
-
if (loopValue === 2) {
|
|
57
|
-
const k = s % (2 * duration)
|
|
58
|
-
return k <= duration ? k : 2 * duration - k
|
|
59
|
-
}
|
|
60
|
-
return Math.min(s, duration)
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* Loads a .riv file and waits until the images and fonts inside it are decoded. Left to the runtime they decode in
|
|
65
|
-
* the background, and the first frames drawn would show without them.
|
|
66
|
-
* @param {RiveCanvas} runtime @param {Uint8Array} bytes
|
|
67
|
-
* @returns {Promise<RiveFile>}
|
|
68
|
-
*/
|
|
69
|
-
async function loadFile(runtime, bytes) {
|
|
70
|
-
/** @type {Promise<void>[]} */
|
|
71
|
-
const decoding = []
|
|
72
|
-
const loader = new runtime.CustomFileAssetLoader({
|
|
73
|
-
/** @param {any} asset @param {Uint8Array} contents */
|
|
74
|
-
loadContents(asset, contents) {
|
|
75
|
-
// An asset kept outside the file arrives without bytes; the runtime fetches it, which cannot be waited for.
|
|
76
|
-
if (!contents || contents.length === 0) return false
|
|
77
|
-
if (asset.isImage) {
|
|
78
|
-
decoding.push(new Promise(done => runtime.decodeImage(contents, image => {
|
|
79
|
-
asset.setRenderImage(image)
|
|
80
|
-
image.unref()
|
|
81
|
-
done()
|
|
82
|
-
})))
|
|
83
|
-
return true
|
|
84
|
-
}
|
|
85
|
-
if (asset.isFont) {
|
|
86
|
-
decoding.push(new Promise(done => runtime.decodeFont(contents, font => {
|
|
87
|
-
asset.setFont(font)
|
|
88
|
-
font.unref()
|
|
89
|
-
done()
|
|
90
|
-
})))
|
|
91
|
-
return true
|
|
92
|
-
}
|
|
93
|
-
return false
|
|
94
|
-
},
|
|
95
|
-
})
|
|
96
|
-
const file = await runtime.load(bytes, loader)
|
|
97
|
-
await Promise.all(decoding)
|
|
98
|
-
return file
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* Loads a Rive file to place in scenes. Each node() gets its own artboard, so copies can show different moments.
|
|
103
|
-
* @param {RiveFactory | { default: RiveFactory }} Rive @rive-app/canvas-advanced: its default export, or the whole
|
|
104
|
-
* module.
|
|
105
|
-
* @param {{ src: ArrayBuffer | Uint8Array, wasm?: string, artboard?: string, animation?: string,
|
|
106
|
-
* stateMachine?: string, inputs?: Record<string, Value<number | boolean>>, hz?: number }} options
|
|
107
|
-
* src is the .riv file's bytes; wasm is where rive.wasm is served (by default Rive's CDN). Name an animation or a
|
|
108
|
-
* state machine; with neither, the artboard's first state machine plays, or its first animation. inputs drive the
|
|
109
|
-
* state machine's inputs by name: numbers and booleans are set every tick, and a trigger fires when its Value turns
|
|
110
|
-
* true. hz (default 60) is the state machine's tick rate.
|
|
111
|
-
* @returns {Promise<{ size: [number, number],
|
|
112
|
-
* node: (props?: CommonProps & { w?: number, h?: number, time?: Value<number>, fit?: Fit, alignment?: Alignment }) => Node,
|
|
113
|
-
* dispose: () => void }>}
|
|
114
|
-
* size is the artboard's. A node is w by h px (default: the artboard's size) and plays from its local time, or from
|
|
115
|
-
* `time`; fit (default 'contain') and alignment (default 'center') place the artboard in it.
|
|
116
|
-
*/
|
|
117
|
-
export async function rive(Rive, { src, wasm, artboard, animation, stateMachine, inputs = {}, hz = 60 }) {
|
|
118
|
-
const factory = typeof Rive === 'function' ? Rive : Rive?.default
|
|
119
|
-
if (typeof factory !== 'function') throw new TypeError('rive: pass @rive-app/canvas-advanced, as in import Rive from \'@rive-app/canvas-advanced\'')
|
|
120
|
-
if (!(src instanceof ArrayBuffer || src instanceof Uint8Array)) throw new TypeError('rive: src must be the .riv file\'s bytes, an ArrayBuffer or Uint8Array')
|
|
121
|
-
if (animation !== undefined && stateMachine !== undefined) throw new TypeError('rive: name an animation or a state machine, not both')
|
|
122
|
-
if (!(hz > 0) || hz === Infinity) throw new RangeError(`rive: hz must be a positive number, got ${hz}`)
|
|
123
|
-
const runtime = await runtimeFor(factory, wasm)
|
|
124
|
-
const file = await loadFile(runtime, src instanceof Uint8Array ? src : new Uint8Array(src))
|
|
125
|
-
|
|
126
|
-
/** @returns {Artboard} */
|
|
127
|
-
const board = () => {
|
|
128
|
-
const made = artboard === undefined ? file.defaultArtboard() : file.artboardByName(artboard)
|
|
129
|
-
if (!made) throw new RangeError(`rive: no artboard "${artboard}"`)
|
|
130
|
-
return made
|
|
131
|
-
}
|
|
132
|
-
const probe = board()
|
|
133
|
-
const box = probe.bounds
|
|
134
|
-
/** @type {[number, number]} */
|
|
135
|
-
const size = [box.maxX - box.minX, box.maxY - box.minY]
|
|
136
|
-
const machine = stateMachine ?? (animation === undefined && probe.stateMachineCount() > 0 ? probe.stateMachineByIndex(0).name : undefined)
|
|
137
|
-
const clip = machine === undefined ? animation ?? (probe.animationCount() > 0 ? probe.animationByIndex(0).name : undefined) : undefined
|
|
138
|
-
if (machine === undefined && clip === undefined) throw new RangeError('rive: the artboard has no animation or state machine to play')
|
|
139
|
-
if (machine !== undefined && !probe.stateMachineByName(machine)) throw new RangeError(`rive: no state machine "${machine}"`)
|
|
140
|
-
if (clip !== undefined && !probe.animationByName(clip)) throw new RangeError(`rive: no animation "${clip}"`)
|
|
141
|
-
if (clip !== undefined && Object.keys(inputs).length > 0) throw new TypeError('rive: inputs drive a state machine, and this node plays an animation')
|
|
142
|
-
probe.delete()
|
|
143
|
-
|
|
144
|
-
/** @type {(() => void)[]} */
|
|
145
|
-
const cleanups = []
|
|
146
|
-
let disposed = false
|
|
147
|
-
|
|
148
|
-
return {
|
|
149
|
-
size,
|
|
150
|
-
dispose() {
|
|
151
|
-
if (disposed) return
|
|
152
|
-
disposed = true
|
|
153
|
-
for (const fn of cleanups) fn()
|
|
154
|
-
cleanups.length = 0
|
|
155
|
-
file.unref?.()
|
|
156
|
-
},
|
|
157
|
-
node({ w = size[0], h = size[1], fit = 'contain', alignment = 'center', ...props } = {}) {
|
|
158
|
-
if (!FITS.includes(fit)) throw new RangeError(`rive: fit must be one of ${FITS.join(', ')}`)
|
|
159
|
-
const canvas = makeSurface(Math.round(w), Math.round(h))
|
|
160
|
-
// A context made for reading back is drawn on the CPU, which gives the same pixels on every draw; Chrome's GPU
|
|
161
|
-
// Canvas 2D does not always. Rive then draws into this same context.
|
|
162
|
-
const context = /** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d', { willReadFrequently: true }))
|
|
163
|
-
const renderer = runtime.makeRenderer(canvas)
|
|
164
|
-
/** Draws an artboard over the whole canvas. @param {Artboard} shown */
|
|
165
|
-
const paint = shown => withClock(() => {
|
|
166
|
-
renderer.clear()
|
|
167
|
-
renderer.save()
|
|
168
|
-
renderer.align(runtime.Fit[fit], runtime.Alignment[alignment], { minX: 0, minY: 0, maxX: canvas.width, maxY: canvas.height }, shown.bounds)
|
|
169
|
-
shown.draw(renderer)
|
|
170
|
-
renderer.restore()
|
|
171
|
-
// Canvas renderers queue their drawing until this flush.
|
|
172
|
-
runtime.resolveAnimationFrame()
|
|
173
|
-
}, STILL)
|
|
174
|
-
const player = machine === undefined ? linear(runtime, board, /** @type {string} */ (clip)) : stepped(runtime, board, machine, inputs, hz)
|
|
175
|
-
cleanups.push(() => {
|
|
176
|
-
player.dispose()
|
|
177
|
-
renderer.delete?.()
|
|
178
|
-
})
|
|
179
|
-
return canvasLayer({
|
|
180
|
-
...props,
|
|
181
|
-
w,
|
|
182
|
-
h,
|
|
183
|
-
render(t, width, height) {
|
|
184
|
-
if (disposed) throw new Error('rive: this file has been disposed')
|
|
185
|
-
if (canvas.width !== width || canvas.height !== height) {
|
|
186
|
-
canvas.width = width
|
|
187
|
-
canvas.height = height
|
|
188
|
-
}
|
|
189
|
-
const shown = player.at(t)
|
|
190
|
-
// At some poses a first draw still shows parts of the pose drawn before it, until something reads the canvas
|
|
191
|
-
// back. Reading one pixel and drawing again gives the pose alone, whether it was reached in order or by a seek.
|
|
192
|
-
paint(shown)
|
|
193
|
-
context.getImageData(0, 0, 1, 1)
|
|
194
|
-
paint(shown)
|
|
195
|
-
return canvas
|
|
196
|
-
},
|
|
197
|
-
})
|
|
198
|
-
},
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
/**
|
|
203
|
-
* A linear animation's timing, as the runtime gives it on the animation rather than its instance: lengths are in
|
|
204
|
-
* frames, and a work area, when enabled, trims the animation.
|
|
205
|
-
* @typedef {{ duration: number, fps: number, loopValue: number, speed: number, enableWorkArea: boolean,
|
|
206
|
-
* workStart: number, workEnd: number }} Timing
|
|
207
|
-
*/
|
|
208
|
-
|
|
209
|
-
/**
|
|
210
|
-
* A linear animation posed at any time by setting its time. A negative speed plays it backwards.
|
|
211
|
-
* @param {RiveCanvas} runtime @param {() => Artboard} board @param {string} name
|
|
212
|
-
* @returns {{ at: (t: number) => Artboard, dispose: () => void }}
|
|
213
|
-
*/
|
|
214
|
-
function linear(runtime, board, name) {
|
|
215
|
-
const artboard = board()
|
|
216
|
-
const clip = artboard.animationByName(name)
|
|
217
|
-
const timing = /** @type {Timing} */ (/** @type {unknown} */ (clip))
|
|
218
|
-
const instance = withClock(() => new runtime.LinearAnimationInstance(clip, artboard), STILL)
|
|
219
|
-
// A new instance starts at the start of its work area.
|
|
220
|
-
const begin = instance.time
|
|
221
|
-
const seconds = (timing.enableWorkArea ? timing.workEnd - timing.workStart : timing.duration) / timing.fps
|
|
222
|
-
const speed = timing.speed || 1
|
|
223
|
-
return {
|
|
224
|
-
at(t) {
|
|
225
|
-
const k = animationTime(t * Math.abs(speed), seconds, timing.loopValue)
|
|
226
|
-
withClock(() => {
|
|
227
|
-
instance.time = begin + (speed < 0 ? seconds - k : k)
|
|
228
|
-
instance.apply(1)
|
|
229
|
-
artboard.advance(0)
|
|
230
|
-
}, STILL)
|
|
231
|
-
return artboard
|
|
232
|
-
},
|
|
233
|
-
dispose() {
|
|
234
|
-
instance.delete?.()
|
|
235
|
-
artboard.delete?.()
|
|
236
|
-
},
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
/**
|
|
241
|
-
* A state machine stepped at hz from its start. Tick n is reached by stepping forward from the last tick drawn, or
|
|
242
|
-
* from a fresh artboard when n lies before it.
|
|
243
|
-
* @param {RiveCanvas} runtime @param {() => Artboard} board @param {string} name
|
|
244
|
-
* @param {Record<string, Value<number | boolean>>} inputs @param {number} hz
|
|
245
|
-
* @returns {{ at: (t: number) => Artboard, dispose: () => void }}
|
|
246
|
-
*/
|
|
247
|
-
function stepped(runtime, board, name, inputs, hz) {
|
|
248
|
-
const dt = 1 / hz
|
|
249
|
-
/** @type {{ artboard: Artboard, machine: import('@rive-app/canvas-advanced').StateMachineInstance, tick: number,
|
|
250
|
-
* bound: [SMIInput, Value<number | boolean>, boolean][] } | null} */
|
|
251
|
-
let run = null
|
|
252
|
-
|
|
253
|
-
/** Sets the inputs for the tick that starts at time `t`. @param {number} t */
|
|
254
|
-
const feed = t => {
|
|
255
|
-
if (!run) return
|
|
256
|
-
for (const entry of run.bound) {
|
|
257
|
-
const [input, value, was] = entry
|
|
258
|
-
const now = at(value, t)
|
|
259
|
-
if (input.type === runtime.SMIInput.trigger) {
|
|
260
|
-
if (now && !was) input.asTrigger().fire()
|
|
261
|
-
entry[2] = Boolean(now)
|
|
262
|
-
} else if (input.type === runtime.SMIInput.bool) input.asBool().value = Boolean(now)
|
|
263
|
-
else input.asNumber().value = Number(now)
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
const restart = () => {
|
|
268
|
-
if (run) {
|
|
269
|
-
run.machine.delete()
|
|
270
|
-
run.artboard.delete()
|
|
271
|
-
}
|
|
272
|
-
const artboard = board()
|
|
273
|
-
const machine = withClock(() => new runtime.StateMachineInstance(artboard.stateMachineByName(name), artboard), STILL)
|
|
274
|
-
/** @type {Map<string, SMIInput>} */
|
|
275
|
-
const byName = new Map()
|
|
276
|
-
for (let i = 0; i < machine.inputCount(); i++) byName.set(machine.input(i).name, machine.input(i))
|
|
277
|
-
run = {
|
|
278
|
-
artboard,
|
|
279
|
-
machine,
|
|
280
|
-
tick: 0,
|
|
281
|
-
bound: Object.entries(inputs).map(([key, value]) => {
|
|
282
|
-
const input = byName.get(key)
|
|
283
|
-
if (!input) throw new RangeError(`rive: state machine "${name}" has no input "${key}". Inputs are ${[...byName.keys()].join(', ')}`)
|
|
284
|
-
return /** @type {[SMIInput, Value<number | boolean>, boolean]} */ ([input, value, false])
|
|
285
|
-
}),
|
|
286
|
-
}
|
|
287
|
-
feed(0)
|
|
288
|
-
withClock(() => {
|
|
289
|
-
machine.advance(0)
|
|
290
|
-
artboard.advance(0)
|
|
291
|
-
}, STILL)
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
return {
|
|
295
|
-
at(t) {
|
|
296
|
-
const target = Math.floor(Math.max(0, t) * hz + TICK_EPSILON)
|
|
297
|
-
if (!run || target < run.tick) restart()
|
|
298
|
-
const live = /** @type {NonNullable<typeof run>} */ (run)
|
|
299
|
-
while (live.tick < target) {
|
|
300
|
-
if (live.tick > 0) feed(live.tick * dt)
|
|
301
|
-
withClock(() => {
|
|
302
|
-
live.machine.advance(dt)
|
|
303
|
-
live.artboard.advance(dt)
|
|
304
|
-
}, STILL)
|
|
305
|
-
live.tick++
|
|
306
|
-
}
|
|
307
|
-
return live.artboard
|
|
308
|
-
},
|
|
309
|
-
dispose() {
|
|
310
|
-
if (!run) return
|
|
311
|
-
run.machine.delete?.()
|
|
312
|
-
run.artboard.delete?.()
|
|
313
|
-
run = null
|
|
314
|
-
},
|
|
315
|
-
}
|
|
316
|
-
}
|
|
1
|
+
// Rive files inside a motlab scene, drawn by Rive's canvas runtime (@rive-app/canvas-advanced). A linear animation is
|
|
2
|
+
// a seek: its time is set from t. A state machine only moves forward, so it steps at a fixed rate from its start, and
|
|
3
|
+
// drawing an earlier moment starts it over; each tick is the same whichever way it was reached.
|
|
4
|
+
import { canvasLayer } from './canvas.js'
|
|
5
|
+
import { at } from '../core/math.js'
|
|
6
|
+
import { makeSurface } from '../renderer/pixels.js'
|
|
7
|
+
import { withClock } from '../core/guard.js'
|
|
8
|
+
|
|
9
|
+
/** @typedef {import('@rive-app/canvas-advanced').RiveCanvas} RiveCanvas */
|
|
10
|
+
/** @typedef {import('@rive-app/canvas-advanced').Artboard} Artboard */
|
|
11
|
+
/** @typedef {import('@rive-app/canvas-advanced').File} RiveFile */
|
|
12
|
+
/** @typedef {import('@rive-app/canvas-advanced').SMIInput} SMIInput */
|
|
13
|
+
/** @typedef {typeof import('@rive-app/canvas-advanced').default} RiveFactory */
|
|
14
|
+
/** @typedef {import('../core/nodes.js').CommonProps} CommonProps */
|
|
15
|
+
/** @typedef {import('../core/nodes.js').Node} Node */
|
|
16
|
+
/**
|
|
17
|
+
* @template T
|
|
18
|
+
* @typedef {import('../core/math.js').Value<T>} Value
|
|
19
|
+
*/
|
|
20
|
+
/** @typedef {'fill' | 'contain' | 'cover' | 'fitWidth' | 'fitHeight' | 'none' | 'scaleDown'} Fit */
|
|
21
|
+
/**
|
|
22
|
+
* @typedef {'topLeft' | 'topCenter' | 'topRight' | 'centerLeft' | 'center' | 'centerRight' | 'bottomLeft' |
|
|
23
|
+
* 'bottomCenter' | 'bottomRight'} Alignment
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
// Rive reads the clock when it makes a state machine and when it draws, and what it draws depends on the time between
|
|
27
|
+
// draws. Every call into Rive sees the clock stand still at this moment, so a pose looks the same however it was reached.
|
|
28
|
+
const STILL = 0
|
|
29
|
+
|
|
30
|
+
const TICK_EPSILON = 1e-9
|
|
31
|
+
/** @type {Fit[]} */
|
|
32
|
+
const FITS = ['fill', 'contain', 'cover', 'fitWidth', 'fitHeight', 'none', 'scaleDown']
|
|
33
|
+
|
|
34
|
+
/** Runtimes by factory and wasm address, so files share one WebAssembly instance. @type {WeakMap<RiveFactory, Map<string, Promise<RiveCanvas>>>} */
|
|
35
|
+
const runtimes = new WeakMap()
|
|
36
|
+
|
|
37
|
+
/** @param {RiveFactory} Rive @param {string | undefined} wasm */
|
|
38
|
+
function runtimeFor(Rive, wasm) {
|
|
39
|
+
let byWasm = runtimes.get(Rive)
|
|
40
|
+
if (!byWasm) runtimes.set(Rive, (byWasm = new Map()))
|
|
41
|
+
const key = wasm ?? ''
|
|
42
|
+
let runtime = byWasm.get(key)
|
|
43
|
+
if (!runtime) byWasm.set(key, (runtime = Rive(wasm ? { locateFile: () => wasm } : undefined)))
|
|
44
|
+
return runtime
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The time to set on a linear animation `seconds` into playing it, from its start: one-shot animations hold their
|
|
49
|
+
* end, loops wrap, and ping-pong runs back and forth.
|
|
50
|
+
* @param {number} seconds @param {number} duration @param {number} loopValue 0 one-shot, 1 loop, 2 ping-pong.
|
|
51
|
+
*/
|
|
52
|
+
export function animationTime(seconds, duration, loopValue) {
|
|
53
|
+
const s = Math.max(0, seconds)
|
|
54
|
+
if (!(duration > 0)) return 0
|
|
55
|
+
if (loopValue === 1) return s % duration
|
|
56
|
+
if (loopValue === 2) {
|
|
57
|
+
const k = s % (2 * duration)
|
|
58
|
+
return k <= duration ? k : 2 * duration - k
|
|
59
|
+
}
|
|
60
|
+
return Math.min(s, duration)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Loads a .riv file and waits until the images and fonts inside it are decoded. Left to the runtime they decode in
|
|
65
|
+
* the background, and the first frames drawn would show without them.
|
|
66
|
+
* @param {RiveCanvas} runtime @param {Uint8Array} bytes
|
|
67
|
+
* @returns {Promise<RiveFile>}
|
|
68
|
+
*/
|
|
69
|
+
async function loadFile(runtime, bytes) {
|
|
70
|
+
/** @type {Promise<void>[]} */
|
|
71
|
+
const decoding = []
|
|
72
|
+
const loader = new runtime.CustomFileAssetLoader({
|
|
73
|
+
/** @param {any} asset @param {Uint8Array} contents */
|
|
74
|
+
loadContents(asset, contents) {
|
|
75
|
+
// An asset kept outside the file arrives without bytes; the runtime fetches it, which cannot be waited for.
|
|
76
|
+
if (!contents || contents.length === 0) return false
|
|
77
|
+
if (asset.isImage) {
|
|
78
|
+
decoding.push(new Promise(done => runtime.decodeImage(contents, image => {
|
|
79
|
+
asset.setRenderImage(image)
|
|
80
|
+
image.unref()
|
|
81
|
+
done()
|
|
82
|
+
})))
|
|
83
|
+
return true
|
|
84
|
+
}
|
|
85
|
+
if (asset.isFont) {
|
|
86
|
+
decoding.push(new Promise(done => runtime.decodeFont(contents, font => {
|
|
87
|
+
asset.setFont(font)
|
|
88
|
+
font.unref()
|
|
89
|
+
done()
|
|
90
|
+
})))
|
|
91
|
+
return true
|
|
92
|
+
}
|
|
93
|
+
return false
|
|
94
|
+
},
|
|
95
|
+
})
|
|
96
|
+
const file = await runtime.load(bytes, loader)
|
|
97
|
+
await Promise.all(decoding)
|
|
98
|
+
return file
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Loads a Rive file to place in scenes. Each node() gets its own artboard, so copies can show different moments.
|
|
103
|
+
* @param {RiveFactory | { default: RiveFactory }} Rive @rive-app/canvas-advanced: its default export, or the whole
|
|
104
|
+
* module.
|
|
105
|
+
* @param {{ src: ArrayBuffer | Uint8Array, wasm?: string, artboard?: string, animation?: string,
|
|
106
|
+
* stateMachine?: string, inputs?: Record<string, Value<number | boolean>>, hz?: number }} options
|
|
107
|
+
* src is the .riv file's bytes; wasm is where rive.wasm is served (by default Rive's CDN). Name an animation or a
|
|
108
|
+
* state machine; with neither, the artboard's first state machine plays, or its first animation. inputs drive the
|
|
109
|
+
* state machine's inputs by name: numbers and booleans are set every tick, and a trigger fires when its Value turns
|
|
110
|
+
* true. hz (default 60) is the state machine's tick rate.
|
|
111
|
+
* @returns {Promise<{ size: [number, number],
|
|
112
|
+
* node: (props?: CommonProps & { w?: number, h?: number, time?: Value<number>, fit?: Fit, alignment?: Alignment }) => Node,
|
|
113
|
+
* dispose: () => void }>}
|
|
114
|
+
* size is the artboard's. A node is w by h px (default: the artboard's size) and plays from its local time, or from
|
|
115
|
+
* `time`; fit (default 'contain') and alignment (default 'center') place the artboard in it.
|
|
116
|
+
*/
|
|
117
|
+
export async function rive(Rive, { src, wasm, artboard, animation, stateMachine, inputs = {}, hz = 60 }) {
|
|
118
|
+
const factory = typeof Rive === 'function' ? Rive : Rive?.default
|
|
119
|
+
if (typeof factory !== 'function') throw new TypeError('rive: pass @rive-app/canvas-advanced, as in import Rive from \'@rive-app/canvas-advanced\'')
|
|
120
|
+
if (!(src instanceof ArrayBuffer || src instanceof Uint8Array)) throw new TypeError('rive: src must be the .riv file\'s bytes, an ArrayBuffer or Uint8Array')
|
|
121
|
+
if (animation !== undefined && stateMachine !== undefined) throw new TypeError('rive: name an animation or a state machine, not both')
|
|
122
|
+
if (!(hz > 0) || hz === Infinity) throw new RangeError(`rive: hz must be a positive number, got ${hz}`)
|
|
123
|
+
const runtime = await runtimeFor(factory, wasm)
|
|
124
|
+
const file = await loadFile(runtime, src instanceof Uint8Array ? src : new Uint8Array(src))
|
|
125
|
+
|
|
126
|
+
/** @returns {Artboard} */
|
|
127
|
+
const board = () => {
|
|
128
|
+
const made = artboard === undefined ? file.defaultArtboard() : file.artboardByName(artboard)
|
|
129
|
+
if (!made) throw new RangeError(`rive: no artboard "${artboard}"`)
|
|
130
|
+
return made
|
|
131
|
+
}
|
|
132
|
+
const probe = board()
|
|
133
|
+
const box = probe.bounds
|
|
134
|
+
/** @type {[number, number]} */
|
|
135
|
+
const size = [box.maxX - box.minX, box.maxY - box.minY]
|
|
136
|
+
const machine = stateMachine ?? (animation === undefined && probe.stateMachineCount() > 0 ? probe.stateMachineByIndex(0).name : undefined)
|
|
137
|
+
const clip = machine === undefined ? animation ?? (probe.animationCount() > 0 ? probe.animationByIndex(0).name : undefined) : undefined
|
|
138
|
+
if (machine === undefined && clip === undefined) throw new RangeError('rive: the artboard has no animation or state machine to play')
|
|
139
|
+
if (machine !== undefined && !probe.stateMachineByName(machine)) throw new RangeError(`rive: no state machine "${machine}"`)
|
|
140
|
+
if (clip !== undefined && !probe.animationByName(clip)) throw new RangeError(`rive: no animation "${clip}"`)
|
|
141
|
+
if (clip !== undefined && Object.keys(inputs).length > 0) throw new TypeError('rive: inputs drive a state machine, and this node plays an animation')
|
|
142
|
+
probe.delete()
|
|
143
|
+
|
|
144
|
+
/** @type {(() => void)[]} */
|
|
145
|
+
const cleanups = []
|
|
146
|
+
let disposed = false
|
|
147
|
+
|
|
148
|
+
return {
|
|
149
|
+
size,
|
|
150
|
+
dispose() {
|
|
151
|
+
if (disposed) return
|
|
152
|
+
disposed = true
|
|
153
|
+
for (const fn of cleanups) fn()
|
|
154
|
+
cleanups.length = 0
|
|
155
|
+
file.unref?.()
|
|
156
|
+
},
|
|
157
|
+
node({ w = size[0], h = size[1], fit = 'contain', alignment = 'center', ...props } = {}) {
|
|
158
|
+
if (!FITS.includes(fit)) throw new RangeError(`rive: fit must be one of ${FITS.join(', ')}`)
|
|
159
|
+
const canvas = makeSurface(Math.round(w), Math.round(h))
|
|
160
|
+
// A context made for reading back is drawn on the CPU, which gives the same pixels on every draw; Chrome's GPU
|
|
161
|
+
// Canvas 2D does not always. Rive then draws into this same context.
|
|
162
|
+
const context = /** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d', { willReadFrequently: true }))
|
|
163
|
+
const renderer = runtime.makeRenderer(canvas)
|
|
164
|
+
/** Draws an artboard over the whole canvas. @param {Artboard} shown */
|
|
165
|
+
const paint = shown => withClock(() => {
|
|
166
|
+
renderer.clear()
|
|
167
|
+
renderer.save()
|
|
168
|
+
renderer.align(runtime.Fit[fit], runtime.Alignment[alignment], { minX: 0, minY: 0, maxX: canvas.width, maxY: canvas.height }, shown.bounds)
|
|
169
|
+
shown.draw(renderer)
|
|
170
|
+
renderer.restore()
|
|
171
|
+
// Canvas renderers queue their drawing until this flush.
|
|
172
|
+
runtime.resolveAnimationFrame()
|
|
173
|
+
}, STILL)
|
|
174
|
+
const player = machine === undefined ? linear(runtime, board, /** @type {string} */ (clip)) : stepped(runtime, board, machine, inputs, hz)
|
|
175
|
+
cleanups.push(() => {
|
|
176
|
+
player.dispose()
|
|
177
|
+
renderer.delete?.()
|
|
178
|
+
})
|
|
179
|
+
return canvasLayer({
|
|
180
|
+
...props,
|
|
181
|
+
w,
|
|
182
|
+
h,
|
|
183
|
+
render(t, width, height) {
|
|
184
|
+
if (disposed) throw new Error('rive: this file has been disposed')
|
|
185
|
+
if (canvas.width !== width || canvas.height !== height) {
|
|
186
|
+
canvas.width = width
|
|
187
|
+
canvas.height = height
|
|
188
|
+
}
|
|
189
|
+
const shown = player.at(t)
|
|
190
|
+
// At some poses a first draw still shows parts of the pose drawn before it, until something reads the canvas
|
|
191
|
+
// back. Reading one pixel and drawing again gives the pose alone, whether it was reached in order or by a seek.
|
|
192
|
+
paint(shown)
|
|
193
|
+
context.getImageData(0, 0, 1, 1)
|
|
194
|
+
paint(shown)
|
|
195
|
+
return canvas
|
|
196
|
+
},
|
|
197
|
+
})
|
|
198
|
+
},
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* A linear animation's timing, as the runtime gives it on the animation rather than its instance: lengths are in
|
|
204
|
+
* frames, and a work area, when enabled, trims the animation.
|
|
205
|
+
* @typedef {{ duration: number, fps: number, loopValue: number, speed: number, enableWorkArea: boolean,
|
|
206
|
+
* workStart: number, workEnd: number }} Timing
|
|
207
|
+
*/
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* A linear animation posed at any time by setting its time. A negative speed plays it backwards.
|
|
211
|
+
* @param {RiveCanvas} runtime @param {() => Artboard} board @param {string} name
|
|
212
|
+
* @returns {{ at: (t: number) => Artboard, dispose: () => void }}
|
|
213
|
+
*/
|
|
214
|
+
function linear(runtime, board, name) {
|
|
215
|
+
const artboard = board()
|
|
216
|
+
const clip = artboard.animationByName(name)
|
|
217
|
+
const timing = /** @type {Timing} */ (/** @type {unknown} */ (clip))
|
|
218
|
+
const instance = withClock(() => new runtime.LinearAnimationInstance(clip, artboard), STILL)
|
|
219
|
+
// A new instance starts at the start of its work area.
|
|
220
|
+
const begin = instance.time
|
|
221
|
+
const seconds = (timing.enableWorkArea ? timing.workEnd - timing.workStart : timing.duration) / timing.fps
|
|
222
|
+
const speed = timing.speed || 1
|
|
223
|
+
return {
|
|
224
|
+
at(t) {
|
|
225
|
+
const k = animationTime(t * Math.abs(speed), seconds, timing.loopValue)
|
|
226
|
+
withClock(() => {
|
|
227
|
+
instance.time = begin + (speed < 0 ? seconds - k : k)
|
|
228
|
+
instance.apply(1)
|
|
229
|
+
artboard.advance(0)
|
|
230
|
+
}, STILL)
|
|
231
|
+
return artboard
|
|
232
|
+
},
|
|
233
|
+
dispose() {
|
|
234
|
+
instance.delete?.()
|
|
235
|
+
artboard.delete?.()
|
|
236
|
+
},
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* A state machine stepped at hz from its start. Tick n is reached by stepping forward from the last tick drawn, or
|
|
242
|
+
* from a fresh artboard when n lies before it.
|
|
243
|
+
* @param {RiveCanvas} runtime @param {() => Artboard} board @param {string} name
|
|
244
|
+
* @param {Record<string, Value<number | boolean>>} inputs @param {number} hz
|
|
245
|
+
* @returns {{ at: (t: number) => Artboard, dispose: () => void }}
|
|
246
|
+
*/
|
|
247
|
+
function stepped(runtime, board, name, inputs, hz) {
|
|
248
|
+
const dt = 1 / hz
|
|
249
|
+
/** @type {{ artboard: Artboard, machine: import('@rive-app/canvas-advanced').StateMachineInstance, tick: number,
|
|
250
|
+
* bound: [SMIInput, Value<number | boolean>, boolean][] } | null} */
|
|
251
|
+
let run = null
|
|
252
|
+
|
|
253
|
+
/** Sets the inputs for the tick that starts at time `t`. @param {number} t */
|
|
254
|
+
const feed = t => {
|
|
255
|
+
if (!run) return
|
|
256
|
+
for (const entry of run.bound) {
|
|
257
|
+
const [input, value, was] = entry
|
|
258
|
+
const now = at(value, t)
|
|
259
|
+
if (input.type === runtime.SMIInput.trigger) {
|
|
260
|
+
if (now && !was) input.asTrigger().fire()
|
|
261
|
+
entry[2] = Boolean(now)
|
|
262
|
+
} else if (input.type === runtime.SMIInput.bool) input.asBool().value = Boolean(now)
|
|
263
|
+
else input.asNumber().value = Number(now)
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const restart = () => {
|
|
268
|
+
if (run) {
|
|
269
|
+
run.machine.delete()
|
|
270
|
+
run.artboard.delete()
|
|
271
|
+
}
|
|
272
|
+
const artboard = board()
|
|
273
|
+
const machine = withClock(() => new runtime.StateMachineInstance(artboard.stateMachineByName(name), artboard), STILL)
|
|
274
|
+
/** @type {Map<string, SMIInput>} */
|
|
275
|
+
const byName = new Map()
|
|
276
|
+
for (let i = 0; i < machine.inputCount(); i++) byName.set(machine.input(i).name, machine.input(i))
|
|
277
|
+
run = {
|
|
278
|
+
artboard,
|
|
279
|
+
machine,
|
|
280
|
+
tick: 0,
|
|
281
|
+
bound: Object.entries(inputs).map(([key, value]) => {
|
|
282
|
+
const input = byName.get(key)
|
|
283
|
+
if (!input) throw new RangeError(`rive: state machine "${name}" has no input "${key}". Inputs are ${[...byName.keys()].join(', ')}`)
|
|
284
|
+
return /** @type {[SMIInput, Value<number | boolean>, boolean]} */ ([input, value, false])
|
|
285
|
+
}),
|
|
286
|
+
}
|
|
287
|
+
feed(0)
|
|
288
|
+
withClock(() => {
|
|
289
|
+
machine.advance(0)
|
|
290
|
+
artboard.advance(0)
|
|
291
|
+
}, STILL)
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
return {
|
|
295
|
+
at(t) {
|
|
296
|
+
const target = Math.floor(Math.max(0, t) * hz + TICK_EPSILON)
|
|
297
|
+
if (!run || target < run.tick) restart()
|
|
298
|
+
const live = /** @type {NonNullable<typeof run>} */ (run)
|
|
299
|
+
while (live.tick < target) {
|
|
300
|
+
if (live.tick > 0) feed(live.tick * dt)
|
|
301
|
+
withClock(() => {
|
|
302
|
+
live.machine.advance(dt)
|
|
303
|
+
live.artboard.advance(dt)
|
|
304
|
+
}, STILL)
|
|
305
|
+
live.tick++
|
|
306
|
+
}
|
|
307
|
+
return live.artboard
|
|
308
|
+
},
|
|
309
|
+
dispose() {
|
|
310
|
+
if (!run) return
|
|
311
|
+
run.machine.delete?.()
|
|
312
|
+
run.artboard.delete?.()
|
|
313
|
+
run = null
|
|
314
|
+
},
|
|
315
|
+
}
|
|
316
|
+
}
|