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.
@@ -1,950 +1,950 @@
1
- import { guarded, context } from '../core/guard.js'
2
- import { rand } from '../core/rand.js'
3
- import { layoutText } from './text-layout.js'
4
- import { STRIDE } from '../core/nodes.js'
5
- import { hash } from '../core/hash.js'
6
- import { openVideo } from '../addons/media.js'
7
- import { makeSurface, pngOf, pixelHash, comparePixels } from './pixels.js'
8
-
9
- /** @typedef {import('../core/scene.js').Scene} Scene */
10
- /** @typedef {import('../core/scene.js').DisplayItem} DisplayItem */
11
- /** @typedef {import('../core/nodes.js').Gradient} Gradient */
12
- /** @typedef {import('../core/path.js').Path} Path */
13
- /** @typedef {CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D} Context */
14
- /** @typedef {HTMLCanvasElement | OffscreenCanvas} Surface */
15
-
16
- /** @typedef {import('../addons/media.js').Video} Video */
17
-
18
- /**
19
- * @typedef {((list: DisplayItem[]) => void) & {
20
- * load: (scene: Scene) => Promise<void>,
21
- * prepare: (list: DisplayItem[]) => Promise<void>,
22
- * dispose: () => void,
23
- * readonly canvas: Surface,
24
- * readonly context: Context
25
- * }} Canvas2DRenderer
26
- * Drawing is synchronous, so a list with video items needs `await draw.prepare(list)` first to decode their frames.
27
- */
28
-
29
- const NO_DASH = /** @type {number[]} */ ([])
30
- const DEG = Math.PI / 180
31
- const DEFAULT_FONT = '10px sans-serif'
32
- const SPACE = /^\s*$/
33
- const NEUTRAL = { x: 0, y: 0, rotation: 0, scale: 1, opacity: 1, fill: undefined }
34
- /** @type {Record<string, GlobalCompositeOperation>} */
35
- const BLEND = { normal: 'source-over', add: 'lighter' }
36
-
37
- /** @param {string | undefined} blend */
38
- const composite = blend => (blend === undefined ? 'source-over' : (BLEND[blend] ?? /** @type {GlobalCompositeOperation} */ (blend)))
39
-
40
- /**
41
- * Draws display lists with the Canvas 2D API. Call `await draw.load(scene)` once to size the canvas and load the
42
- * scene's fonts and images, then `draw(scene.evaluate(t))` for each frame. Works on an HTMLCanvasElement or, in a
43
- * worker, an OffscreenCanvas.
44
- * @param {Surface} canvas
45
- * @param {{ scale?: number, willReadFrequently?: boolean, assets?: { images: Map<string, any>, videos: Map<string, Video> } }} [options]
46
- * scale draws at a multiple of the scene's size, for sharper output. willReadFrequently keeps the canvas on the CPU,
47
- * for code that reads pixels back. assets shares images and footage another renderer already loaded.
48
- * @returns {Canvas2DRenderer}
49
- */
50
- export function canvas2d(canvas, { scale = 1, willReadFrequently = false, assets } = {}) {
51
- const ctx = /** @type {Context | null} */ (canvas.getContext('2d', { willReadFrequently }))
52
- if (!ctx) throw new Error('canvas2d: this canvas cannot give a 2D context')
53
- const main = ctx
54
- /** @type {Map<string, CanvasImageSource & { width: number, height: number }>} */
55
- const images = assets?.images ?? new Map()
56
- /** @type {Map<string, Video>} */
57
- const videos = assets?.videos ?? new Map()
58
- // A Path2D per path, rebuilt only when commands were added since.
59
- /** @type {WeakMap<Path, { length: number, path2d: Path2D }>} */
60
- const built = new WeakMap()
61
- /** @type {WeakMap<Context, WeakMap<Gradient, CanvasGradient>>} */
62
- const gradients = new WeakMap()
63
- /** @type {Map<string, number>} */
64
- const widths = new Map()
65
- // Offscreen surfaces for layers: three per nesting level (content, matte, one motion blur sample).
66
- /** @type {{ canvas: Surface, ctx: Context }[]} */
67
- const surfaces = []
68
-
69
- /** @param {number} i */
70
- function surface(i) {
71
- let s = surfaces[i]
72
- if (!s || s.canvas.width !== canvas.width || s.canvas.height !== canvas.height) {
73
- const c = makeSurface(canvas.width, canvas.height)
74
- s = { canvas: c, ctx: /** @type {Context} */ (c.getContext('2d', { willReadFrequently })) }
75
- surfaces[i] = s
76
- }
77
- s.ctx.setTransform(1, 0, 0, 1, 0, 0)
78
- s.ctx.globalAlpha = 1
79
- s.ctx.globalCompositeOperation = 'source-over'
80
- s.ctx.clearRect(0, 0, canvas.width, canvas.height)
81
- return s
82
- }
83
-
84
- /** @param {Path} path */
85
- function path2d(path) {
86
- const hit = built.get(path)
87
- if (hit && hit.length === path.data.length) return hit.path2d
88
- const p = new Path2D()
89
- path.replay(p)
90
- built.set(path, { length: path.data.length, path2d: p })
91
- return p
92
- }
93
-
94
- /** @param {Context} c @param {string | Gradient} style */
95
- function paint(c, style) {
96
- if (typeof style === 'string') return style
97
- let cache = gradients.get(c)
98
- if (!cache) gradients.set(c, (cache = new WeakMap()))
99
- let g = cache.get(style)
100
- if (!g) {
101
- g = style.type === 'linear'
102
- ? c.createLinearGradient(style.x0, style.y0, style.x1, style.y1)
103
- : c.createRadialGradient(style.x0, style.y0, style.r0, style.x1, style.y1, style.r1)
104
- for (const [offset, color] of style.stops) g.addColorStop(Math.min(1, Math.max(0, offset)), color)
105
- cache.set(style, g)
106
- }
107
- return g
108
- }
109
-
110
- /** @param {Context} c @param {string} text */
111
- function measure(c, text) {
112
- const key = `${c.font}\n${text}`
113
- let w = widths.get(key)
114
- if (w === undefined) {
115
- if (widths.size > 5000) widths.clear()
116
- w = c.measureText(text).width
117
- widths.set(key, w)
118
- }
119
- return w
120
- }
121
-
122
- /**
123
- * @param {Context} c
124
- * @param {DisplayItem & { type: 'text' }} item
125
- * @param {string} text
126
- * @param {number} x
127
- * @param {number} y
128
- * @param {string} [fill]
129
- */
130
- function fillStroke(c, item, text, x, y, fill) {
131
- if (item.fill !== undefined || fill !== undefined) {
132
- c.fillStyle = paint(c, fill ?? /** @type {string | Gradient} */ (item.fill))
133
- c.fillText(text, x, y)
134
- }
135
- if (item.stroke !== undefined) {
136
- c.strokeStyle = paint(c, item.stroke)
137
- c.lineWidth = item.strokeWidth ?? 1
138
- c.setLineDash(NO_DASH)
139
- c.strokeText(text, x, y)
140
- }
141
- }
142
-
143
- /** @param {Context} c @param {DisplayItem & { type: 'text' }} item */
144
- function drawText(c, item) {
145
- c.font = item.font ?? DEFAULT_FONT
146
- c.textBaseline = /** @type {CanvasTextBaseline} */ (item.baseline ?? 'alphabetic')
147
- if (!item.units && item.width === undefined && !item.text.includes('\n')) {
148
- c.textAlign = /** @type {CanvasTextAlign} */ (item.align ?? 'start')
149
- fillStroke(c, item, item.text, 0, 0)
150
- return
151
- }
152
- c.textAlign = 'left'
153
- const layout = layoutText(item, text => measure(c, text))
154
- if (!item.units) {
155
- for (const line of layout.lines) fillStroke(c, item, line.text, line.x, line.y)
156
- return
157
- }
158
- const base = c.getTransform()
159
- const alpha = c.globalAlpha
160
- item.units.forEach((unit, i) => {
161
- const box = layout.boxes[i]
162
- const style = item.offsets?.[i] ?? NEUTRAL
163
- if (!box || SPACE.test(unit) || style.opacity <= 0 || style.scale === 0) return
164
- c.setTransform(base)
165
- c.translate(box.x + box.w / 2 + style.x, box.y + style.y)
166
- if (style.rotation) c.rotate(style.rotation * DEG)
167
- if (style.scale !== 1) c.scale(style.scale, style.scale)
168
- c.globalAlpha = alpha * style.opacity
169
- fillStroke(c, item, unit, -box.w / 2, 0, style.fill)
170
- })
171
- c.setTransform(base)
172
- c.globalAlpha = alpha
173
- }
174
-
175
- /** @param {Context} c @param {DisplayItem & { type: 'layer' }} layer @param {number} depth */
176
- function drawLayer(c, layer, depth) {
177
- const content = surface(depth * 3)
178
- if (layer.samples) {
179
- // A running average: sample k is laid over the mean of the earlier ones with weight 1 / (k + 1).
180
- layer.samples.forEach((list, k) => {
181
- const sample = surface(depth * 3 + 2)
182
- drawItems(sample.ctx, list, depth + 1)
183
- content.ctx.setTransform(1, 0, 0, 1, 0, 0)
184
- content.ctx.globalCompositeOperation = 'source-over'
185
- content.ctx.globalAlpha = 1 / (k + 1)
186
- content.ctx.drawImage(sample.canvas, 0, 0)
187
- })
188
- } else {
189
- drawItems(content.ctx, layer.items ?? [], depth + 1)
190
- }
191
- if (layer.matte) {
192
- const mask = surface(depth * 3 + 1)
193
- drawItems(mask.ctx, layer.matte.items, depth + 1)
194
- const mode = layer.matte.mode
195
- if (mode === 'luma' || mode === 'luma-inverted') {
196
- const image = mask.ctx.getImageData(0, 0, canvas.width, canvas.height)
197
- const d = image.data
198
- for (let i = 0; i < d.length; i += 4) {
199
- const luma = ((0.2126 * d[i] + 0.7152 * d[i + 1] + 0.0722 * d[i + 2]) * d[i + 3]) / 255
200
- d[i + 3] = mode === 'luma' ? luma : 255 - luma
201
- }
202
- mask.ctx.putImageData(image, 0, 0)
203
- }
204
- content.ctx.setTransform(1, 0, 0, 1, 0, 0)
205
- content.ctx.globalAlpha = 1
206
- content.ctx.globalCompositeOperation = mode === 'alpha-inverted' ? 'destination-out' : 'destination-in'
207
- content.ctx.drawImage(mask.canvas, 0, 0)
208
- }
209
- if (layer.effects) for (const effect of layer.effects) applyEffect(content, effect, layer.t ?? 0, depth)
210
- c.setTransform(1, 0, 0, 1, 0, 0)
211
- c.globalAlpha = layer.opacity
212
- c.globalCompositeOperation = composite(layer.blend)
213
- c.drawImage(content.canvas, 0, 0)
214
- }
215
-
216
- /**
217
- * One effect on a layer's surface, as close to the WebGL2 renderer as Canvas 2D allows: blur and the glows use the
218
- * canvas blur filter, and the glow's threshold is approximated with a contrast filter.
219
- * @param {{ canvas: Surface, ctx: Context }} target @param {import('../core/scene.js').ResolvedEffect} effect
220
- * @param {number} t @param {number} depth
221
- */
222
- function applyEffect(target, effect, t, depth) {
223
- const temp = surface(depth * 3 + 1)
224
- const tc = temp.ctx
225
- const w = canvas.width
226
- const h = canvas.height
227
- const put = (/** @type {GlobalCompositeOperation} */ op, /** @type {number} */ alpha) => {
228
- target.ctx.setTransform(1, 0, 0, 1, 0, 0)
229
- target.ctx.globalCompositeOperation = op
230
- target.ctx.globalAlpha = alpha
231
- target.ctx.drawImage(temp.canvas, 0, 0)
232
- target.ctx.globalCompositeOperation = 'source-over'
233
- target.ctx.globalAlpha = 1
234
- }
235
- // Paints a full-frame fill into temp, cut to the layer's own shape.
236
- const masked = (/** @type {string | CanvasGradient | CanvasPattern} */ fill) => {
237
- tc.fillStyle = fill
238
- tc.fillRect(0, 0, w, h)
239
- tc.globalCompositeOperation = 'destination-in'
240
- tc.drawImage(target.canvas, 0, 0)
241
- tc.globalCompositeOperation = 'source-over'
242
- }
243
- switch (effect.type) {
244
- case 'blur':
245
- tc.filter = `blur(${effect.radius * scale}px)`
246
- tc.drawImage(target.canvas, 0, 0)
247
- tc.filter = 'none'
248
- target.ctx.clearRect(0, 0, w, h)
249
- put('source-over', 1)
250
- break
251
- case 'glow':
252
- case 'diffusion': {
253
- const contrast = effect.type === 'glow' ? `contrast(${1 + 2 * effect.threshold}) brightness(${1 - effect.threshold / 2}) ` : ''
254
- tc.filter = `${contrast}blur(${effect.radius * scale}px)`
255
- tc.drawImage(target.canvas, 0, 0)
256
- tc.filter = 'none'
257
- for (let left = effect.strength; left > 0; left -= 1) put('screen', Math.min(1, left))
258
- break
259
- }
260
- case 'grain': {
261
- masked(/** @type {CanvasPattern} */ (tc.createPattern(noiseTile(effect.seed, t, Math.max(1, effect.size * scale)), 'repeat')))
262
- put('overlay', Math.min(1, effect.amount * 4))
263
- break
264
- }
265
- case 'para': {
266
- const a = (effect.angle * Math.PI) / 180
267
- const r = Math.hypot(w, h) / 2
268
- const g = tc.createLinearGradient(w / 2 - Math.cos(a) * r, h / 2 - Math.sin(a) * r, w / 2 + Math.cos(a) * r, h / 2 + Math.sin(a) * r)
269
- g.addColorStop(0, effect.from)
270
- g.addColorStop(1, effect.to)
271
- masked(g)
272
- put(composite(effect.blend), effect.opacity)
273
- break
274
- }
275
- case 'vignette': {
276
- const r = Math.hypot(w, h) / 2
277
- const g = tc.createRadialGradient(w / 2, h / 2, r * effect.radius, w / 2, h / 2, r)
278
- g.addColorStop(0, 'rgba(0, 0, 0, 0)')
279
- g.addColorStop(1, `rgba(0, 0, 0, ${effect.strength})`)
280
- masked(g)
281
- put('source-atop', 1)
282
- break
283
- }
284
- }
285
- }
286
-
287
- /**
288
- * Mixes two lists by a built-in transition, across the item's box or the whole frame; GLSL transitions need the
289
- * WebGL2 renderer.
290
- * @param {Context} c @param {DisplayItem & { type: 'transition' }} item @param {number} depth
291
- */
292
- function drawTransition(c, item, depth) {
293
- if (typeof item.effect !== 'string') throw new Error(`canvas2d: transition "${item.id}" runs GLSL, which needs the WebGL2 renderer`)
294
- const from = surface(depth * 3)
295
- const to = surface(depth * 3 + 2)
296
- drawItems(from.ctx, item.from, depth + 1)
297
- drawItems(to.ctx, item.to, depth + 1)
298
- const p = item.progress
299
- const [x, y, w, h] = item.box ? item.box.map(v => v * scale) : [0, 0, canvas.width, canvas.height]
300
- const cx = x + w / 2
301
- const cy = y + h / 2
302
- const params = /** @type {Record<string, number>} */ (item.params)
303
- const mix = surface(depth * 3 + 1)
304
- const m = mix.ctx
305
- // Cuts `to` down to where it shows, by an alpha mask painted with destination-in.
306
- const reveal = (/** @type {string | CanvasGradient} */ fill) => {
307
- to.ctx.setTransform(1, 0, 0, 1, 0, 0)
308
- to.ctx.globalCompositeOperation = 'destination-in'
309
- to.ctx.fillStyle = fill
310
- to.ctx.fillRect(0, 0, canvas.width, canvas.height)
311
- to.ctx.globalCompositeOperation = 'source-over'
312
- }
313
- switch (item.effect) {
314
- case 'fade':
315
- m.globalAlpha = 1 - p
316
- m.drawImage(from.canvas, 0, 0)
317
- m.globalAlpha = p
318
- m.globalCompositeOperation = 'lighter'
319
- m.drawImage(to.canvas, 0, 0)
320
- break
321
- case 'wipe': {
322
- const a = ((params.angle ?? 0) * Math.PI) / 180
323
- const soft = params.softness ?? 0.1
324
- const reach = (Math.abs(Math.cos(a)) * w + Math.abs(Math.sin(a)) * h) / 2
325
- const [dx, dy] = [Math.cos(a) * reach, Math.sin(a) * reach]
326
- const g = m.createLinearGradient(cx - dx, cy - dy, cx + dx, cy + dy)
327
- const edge = p * (1 + soft)
328
- g.addColorStop(Math.min(1, Math.max(0, edge - soft)), 'rgba(0, 0, 0, 1)')
329
- g.addColorStop(Math.min(1, Math.max(0, edge)), 'rgba(0, 0, 0, 0)')
330
- reveal(g)
331
- m.drawImage(from.canvas, 0, 0)
332
- m.drawImage(to.canvas, 0, 0)
333
- break
334
- }
335
- case 'slide': {
336
- const a = ((params.angle ?? 0) * Math.PI) / 180
337
- const [dx, dy] = [Math.cos(a) * w, Math.sin(a) * h]
338
- m.drawImage(from.canvas, -dx * p, -dy * p)
339
- m.drawImage(to.canvas, dx * (1 - p), dy * (1 - p))
340
- break
341
- }
342
- case 'circle': {
343
- const ox = x + (params.x ?? 0.5) * w
344
- const oy = y + (params.y ?? 0.5) * h
345
- const soft = (params.softness ?? 0.05) * Math.hypot(w, h)
346
- const r = p * (Math.hypot(Math.max(ox - x, x + w - ox), Math.max(oy - y, y + h - oy)) + soft)
347
- const g = m.createRadialGradient(ox, oy, Math.max(0, r - soft), ox, oy, Math.max(r, 1e-3))
348
- g.addColorStop(0, 'rgba(0, 0, 0, 1)')
349
- g.addColorStop(1, 'rgba(0, 0, 0, 0)')
350
- reveal(g)
351
- m.drawImage(from.canvas, 0, 0)
352
- m.drawImage(to.canvas, 0, 0)
353
- break
354
- }
355
- case 'zoom': {
356
- const grow = 1 + (params.strength ?? 0.25) * p
357
- m.globalAlpha = 1 - p
358
- m.setTransform(grow, 0, 0, grow, cx * (1 - grow), cy * (1 - grow))
359
- m.drawImage(from.canvas, 0, 0)
360
- const shrink = 1 + (params.strength ?? 0.25) * (1 - p)
361
- m.globalAlpha = p
362
- m.globalCompositeOperation = 'lighter'
363
- m.setTransform(shrink, 0, 0, shrink, cx * (1 - shrink), cy * (1 - shrink))
364
- m.drawImage(to.canvas, 0, 0)
365
- break
366
- }
367
- case 'dissolve': {
368
- const size = Math.max(1, Math.round((params.size ?? 4) * scale))
369
- const tile = dissolveMask(p, size, w, h)
370
- to.ctx.setTransform(1, 0, 0, 1, 0, 0)
371
- to.ctx.globalCompositeOperation = 'destination-in'
372
- to.ctx.imageSmoothingEnabled = false
373
- to.ctx.drawImage(tile, x, y, tile.width * size, tile.height * size)
374
- to.ctx.globalCompositeOperation = 'source-over'
375
- m.drawImage(from.canvas, 0, 0)
376
- m.drawImage(to.canvas, 0, 0)
377
- break
378
- }
379
- }
380
- c.save()
381
- c.setTransform(1, 0, 0, 1, 0, 0)
382
- if (item.box) {
383
- c.beginPath()
384
- c.rect(x, y, w, h)
385
- c.clip()
386
- }
387
- c.globalAlpha = item.opacity
388
- c.globalCompositeOperation = composite(item.blend)
389
- c.drawImage(mix.canvas, 0, 0)
390
- c.restore()
391
- }
392
-
393
- /**
394
- * An image through a triangle mesh: each triangle is clipped and the image mapped onto it by the affine transform
395
- * that carries its uv corners to its points. Triangles grow by half a pixel so no seams show between them.
396
- * @param {Context} c @param {DisplayItem & { type: 'mesh' }} item
397
- */
398
- function drawMesh(c, item) {
399
- const img = images.get(item.src)
400
- if (!img) throw new Error(`canvas2d: image "${item.src}" is not loaded; list it in the scene's assets.images`)
401
- const { points: P, uvs: U, triangles: T } = item
402
- const base = c.getTransform()
403
- c.imageSmoothingEnabled = item.smooth !== false
404
- for (let k = 0; k < T.length; k += 3) {
405
- const [i, j, l] = [T[k] * 2, T[k + 1] * 2, T[k + 2] * 2]
406
- const [x0, y0, x1, y1, x2, y2] = [P[i], P[i + 1], P[j], P[j + 1], P[l], P[l + 1]]
407
- const [u0, v0, u1, v1, u2, v2] = [U[i], U[i + 1], U[j], U[j + 1], U[l], U[l + 1]]
408
- const det = (u1 - u0) * (v2 - v0) - (u2 - u0) * (v1 - v0)
409
- if (det === 0) continue
410
- // The affine map with (u, v) to (x, y) at all three corners.
411
- const a = ((x1 - x0) * (v2 - v0) - (x2 - x0) * (v1 - v0)) / det
412
- const b = ((y1 - y0) * (v2 - v0) - (y2 - y0) * (v1 - v0)) / det
413
- const cc = ((x2 - x0) * (u1 - u0) - (x1 - x0) * (u2 - u0)) / det
414
- const d = ((y2 - y0) * (u1 - u0) - (y1 - y0) * (u2 - u0)) / det
415
- const e = x0 - a * u0 - cc * v0
416
- const f = y0 - b * u0 - d * v0
417
- const cx = (x0 + x1 + x2) / 3
418
- const cy = (y0 + y1 + y2) / 3
419
- /** @param {number} x @param {number} y @returns {[number, number]} */
420
- const grow = (x, y) => {
421
- const dx = x - cx
422
- const dy = y - cy
423
- const len = Math.hypot(dx, dy) || 1
424
- return [x + (dx / len) * (0.5 / scale), y + (dy / len) * (0.5 / scale)]
425
- }
426
- c.save()
427
- c.beginPath()
428
- c.moveTo(...grow(x0, y0))
429
- c.lineTo(...grow(x1, y1))
430
- c.lineTo(...grow(x2, y2))
431
- c.closePath()
432
- c.clip()
433
- c.transform(a, b, cc, d, e, f)
434
- c.drawImage(img, 0, 0)
435
- c.restore()
436
- c.setTransform(base)
437
- }
438
- }
439
-
440
- /**
441
- * Draws a shape, text or image with the transform already set. `fill` replaces the item's own, for instances.
442
- * @param {Context} c @param {DisplayItem} item @param {string | undefined} fill
443
- */
444
- function drawLeaf(c, item, fill) {
445
- switch (item.type) {
446
- case 'shape': {
447
- const p = path2d(item.path)
448
- const fillStyle = fill ?? item.fill
449
- if (fillStyle !== undefined) {
450
- c.fillStyle = paint(c, fillStyle)
451
- c.fill(p)
452
- }
453
- if (item.stroke !== undefined) {
454
- c.strokeStyle = paint(c, item.stroke)
455
- c.lineWidth = item.strokeWidth ?? 1
456
- c.lineCap = /** @type {CanvasLineCap} */ (item.lineCap ?? 'butt')
457
- c.lineJoin = /** @type {CanvasLineJoin} */ (item.lineJoin ?? 'miter')
458
- c.setLineDash(item.dash ?? NO_DASH)
459
- c.lineDashOffset = item.dashOffset ?? 0
460
- c.stroke(p)
461
- }
462
- break
463
- }
464
- case 'text':
465
- drawText(c, fill === undefined ? item : { ...item, fill })
466
- break
467
- case 'image': {
468
- const img = images.get(item.src)
469
- if (!img) throw new Error(`canvas2d: image "${item.src}" is not loaded; list it in the scene's assets.images`)
470
- c.imageSmoothingEnabled = item.smooth !== false
471
- if (item.crop) {
472
- const [sx, sy, sw, sh] = item.crop
473
- c.drawImage(img, sx, sy, sw, sh, 0, 0, item.w ?? sw, item.h ?? sh)
474
- } else c.drawImage(img, 0, 0, item.w ?? img.width, item.h ?? img.height)
475
- break
476
- }
477
- case 'video': {
478
- const frame = videoFrame(videos, item, 'canvas2d')
479
- c.imageSmoothingEnabled = item.smooth !== false
480
- if (item.crop) {
481
- const [sx, sy, sw, sh] = item.crop
482
- c.drawImage(frame, sx, sy, sw, sh, 0, 0, item.w ?? sw, item.h ?? sh)
483
- } else c.drawImage(frame, 0, 0, item.w ?? frame.width, item.h ?? frame.height)
484
- break
485
- }
486
- }
487
- }
488
-
489
- /**
490
- * Each copy's transform is the item's, then the copy's own (x, y, rotation, scale), then the base's.
491
- * @param {Context} c @param {DisplayItem & { type: 'instances' }} item
492
- */
493
- function drawInstances(c, item) {
494
- const { base, data, colors } = item
495
- if (base.type === 'layer' || base.type === 'instances' || base.type === 'draw' || base.type === 'transition' || base.type === 'mesh') return
496
- const [m0, m1, m2, m3, m4, m5] = item.matrix
497
- const [b0, b1, b2, b3, b4, b5] = base.matrix
498
- for (let k = 0; k < data.length; k += STRIDE) {
499
- const opacity = data[k + 5]
500
- if (!(opacity > 0)) continue
501
- const angle = data[k + 2] * DEG
502
- const cos = angle === 0 ? 1 : Math.cos(angle)
503
- const sin = angle === 0 ? 0 : Math.sin(angle)
504
- const l0 = cos * data[k + 3]
505
- const l1 = sin * data[k + 3]
506
- const l2 = -sin * data[k + 4]
507
- const l3 = cos * data[k + 4]
508
- const l4 = data[k]
509
- const l5 = data[k + 1]
510
- // item × copy
511
- const a0 = m0 * l0 + m2 * l1
512
- const a1 = m1 * l0 + m3 * l1
513
- const a2 = m0 * l2 + m2 * l3
514
- const a3 = m1 * l2 + m3 * l3
515
- const a4 = m0 * l4 + m2 * l5 + m4
516
- const a5 = m1 * l4 + m3 * l5 + m5
517
- // (item × copy) × base
518
- c.setTransform(
519
- (a0 * b0 + a2 * b1) * scale,
520
- (a1 * b0 + a3 * b1) * scale,
521
- (a0 * b2 + a2 * b3) * scale,
522
- (a1 * b2 + a3 * b3) * scale,
523
- (a0 * b4 + a2 * b5 + a4) * scale,
524
- (a1 * b4 + a3 * b5 + a5) * scale,
525
- )
526
- c.globalAlpha = item.opacity * base.opacity * opacity
527
- const colour = data[k + 6]
528
- drawLeaf(c, base, colour >= 0 ? colors[colour] : undefined)
529
- }
530
- }
531
-
532
- /** @param {Context} c @param {DisplayItem[]} list @param {number} depth */
533
- function drawItems(c, list, depth) {
534
- for (const item of list) {
535
- if (item.type === 'layer') {
536
- drawLayer(c, item, depth)
537
- continue
538
- }
539
- if (item.type === 'transition') {
540
- drawTransition(c, item, depth)
541
- continue
542
- }
543
- const m = item.matrix
544
- c.setTransform(m[0] * scale, m[1] * scale, m[2] * scale, m[3] * scale, m[4] * scale, m[5] * scale)
545
- c.globalAlpha = item.opacity
546
- c.globalCompositeOperation = composite(item.blend)
547
- switch (item.type) {
548
- case 'shape':
549
- case 'text':
550
- case 'image':
551
- case 'video':
552
- drawLeaf(c, item, undefined)
553
- break
554
- case 'mesh':
555
- drawMesh(c, item)
556
- break
557
- case 'instances':
558
- drawInstances(c, item)
559
- break
560
- case 'draw':
561
- c.save()
562
- c.imageSmoothingEnabled = true
563
- try {
564
- guarded(() => {
565
- context.node = item.id
566
- context.t = item.t
567
- item.draw(c, item.t)
568
- })
569
- } finally {
570
- c.restore()
571
- }
572
- break
573
- }
574
- }
575
- }
576
-
577
- /** @param {DisplayItem[]} list */
578
- function render(list) {
579
- main.setTransform(1, 0, 0, 1, 0, 0)
580
- main.globalAlpha = 1
581
- main.globalCompositeOperation = 'source-over'
582
- main.clearRect(0, 0, canvas.width, canvas.height)
583
- drawItems(main, list, 0)
584
- }
585
-
586
- /** @param {Scene} scene */
587
- async function load(scene) {
588
- canvas.width = Math.round(scene.size[0] * scale)
589
- canvas.height = Math.round(scene.size[1] * scale)
590
- await loadAssets(scene, images, videos)
591
- }
592
-
593
- function dispose() {
594
- surfaces.length = 0
595
- widths.clear()
596
- if (!assets) {
597
- images.clear()
598
- videos.clear()
599
- }
600
- }
601
-
602
- return Object.defineProperties(/** @type {Canvas2DRenderer} */ (/** @type {unknown} */ (render)), {
603
- load: { value: load },
604
- prepare: { value: (/** @type {DisplayItem[]} */ list) => prepareVideos(videos, list) },
605
- dispose: { value: dispose },
606
- canvas: { value: canvas },
607
- context: { value: ctx },
608
- })
609
- }
610
-
611
- // Footage is opened once per URL and shared, so every renderer reuses the frames already decoded.
612
- /** @type {Map<string, Promise<Video>>} */
613
- const openedVideos = new Map()
614
-
615
- /**
616
- * Loads a scene's fonts into the document (or worker), its images into `images` and its footage into `videos`. A
617
- * missing file throws, naming it.
618
- * @param {Scene} scene
619
- * @param {Map<string, any>} images
620
- * @param {Map<string, Video>} [videos]
621
- */
622
- export async function loadAssets(scene, images, videos) {
623
- const g = /** @type {any} */ (globalThis)
624
- const base = g.document?.baseURI ?? g.location?.href
625
- const fontSet = g.document?.fonts ?? g.fonts
626
- const { fonts = [], images: sources = {}, videos: footage = {} } = scene.assets
627
- await Promise.all([
628
- ...Object.entries(footage).map(async ([key, src]) => {
629
- const url = new URL(src, base).href
630
- let opening = openedVideos.get(url)
631
- if (!opening) {
632
- opening = openVideo(url)
633
- openedVideos.set(url, opening)
634
- opening.catch(() => openedVideos.delete(url))
635
- }
636
- try {
637
- videos?.set(key, await opening)
638
- } catch (error) {
639
- throw new Error(`video "${key}" could not be opened from ${src}: ${error instanceof Error ? error.message : error}`)
640
- }
641
- }),
642
- ...fonts.map(async ({ family, src, weight, style }) => {
643
- const face = new FontFace(family, `url(${new URL(src, base).href})`, { weight, style })
644
- try {
645
- await face.load()
646
- } catch (error) {
647
- throw new Error(`font "${family}" could not be loaded from ${src}: ${error instanceof Error ? error.message : error}`)
648
- }
649
- fontSet.add(face)
650
- }),
651
- ...Object.entries(sources).map(async ([key, src]) => {
652
- try {
653
- images.set(key, await loadImage(new URL(src, base).href))
654
- } catch (error) {
655
- throw new Error(`image "${key}" could not be loaded from ${src}: ${error instanceof Error ? error.message : error}`)
656
- }
657
- }),
658
- ])
659
- }
660
-
661
- /**
662
- * An <img> where there is a document, because it also decodes SVG; createImageBitmap in workers.
663
- * @param {string} url
664
- * @returns {Promise<CanvasImageSource & { width: number, height: number }>}
665
- */
666
- async function loadImage(url) {
667
- if (typeof Image !== 'undefined') {
668
- const img = new Image()
669
- img.src = url
670
- await img.decode()
671
- return img
672
- }
673
- const response = await fetch(url)
674
- if (!response.ok) throw new Error(`HTTP ${response.status}`)
675
- return createImageBitmap(await response.blob())
676
- }
677
-
678
- /** @type {Map<string, OffscreenCanvas | HTMLCanvasElement>} */
679
- const noiseTiles = new Map()
680
-
681
- /**
682
- * A grey noise tile for grain, the same for the same seed and moment: each frame of grain differs, but redrawing a
683
- * frame gives the same grain.
684
- * @param {number} seed @param {number} t @param {number} size Pixels per grain.
685
- */
686
- function noiseTile(seed, t, size) {
687
- const key = `${seed}:${Math.round(t * 1000)}:${size}`
688
- let tile = noiseTiles.get(key)
689
- if (tile) return tile
690
- if (noiseTiles.size > 64) noiseTiles.clear()
691
- const n = 128
692
- tile = makeSurface(Math.round(n * size), Math.round(n * size))
693
- const small = makeSurface(n, n)
694
- const sc = /** @type {Context} */ (small.getContext('2d'))
695
- const image = sc.createImageData(n, n)
696
- for (let i = 0; i < n * n; i++) {
697
- const v = Math.round(rand('grain', seed, Math.round(t * 1000), i) * 255)
698
- image.data.set([v, v, v, 255], i * 4)
699
- }
700
- sc.putImageData(image, 0, 0)
701
- const tc = /** @type {Context} */ (tile.getContext('2d'))
702
- tc.imageSmoothingEnabled = false
703
- tc.drawImage(small, 0, 0, tile.width, tile.height)
704
- noiseTiles.set(key, tile)
705
- return tile
706
- }
707
-
708
- /** @type {Map<string, Float32Array>} */
709
- const dissolveNoise = new Map()
710
- /** @type {{ canvas: Surface, ctx: Context, image: ImageData } | null} */
711
- let dissolveScratch = null
712
-
713
- /**
714
- * An alpha mask for a dissolve: a fixed field of random values per block, shown where they fall below progress.
715
- * @param {number} p @param {number} size @param {number} w @param {number} h
716
- */
717
- function dissolveMask(p, size, w, h) {
718
- const cols = Math.ceil(w / size)
719
- const rows = Math.ceil(h / size)
720
- const key = `${cols}x${rows}`
721
- let field = dissolveNoise.get(key)
722
- if (!field) {
723
- if (dissolveNoise.size > 32) dissolveNoise.clear()
724
- dissolveNoise.set(key, (field = Float32Array.from({ length: cols * rows }, (_, i) => rand('dissolve', i))))
725
- }
726
- if (!dissolveScratch || dissolveScratch.canvas.width !== cols || dissolveScratch.canvas.height !== rows) {
727
- const canvas = makeSurface(cols, rows)
728
- const ctx = /** @type {Context} */ (canvas.getContext('2d'))
729
- dissolveScratch = { canvas, ctx, image: ctx.createImageData(cols, rows) }
730
- }
731
- const { canvas, ctx, image } = dissolveScratch
732
- for (let i = 0; i < field.length; i++) image.data[i * 4 + 3] = field[i] < p ? 255 : 0
733
- ctx.putImageData(image, 0, 0)
734
- return canvas
735
- }
736
-
737
- /**
738
- * Every video item in a display list, layers included.
739
- * @param {DisplayItem[]} list
740
- * @param {(DisplayItem & { type: 'video' })[]} [out]
741
- */
742
- export function videoItems(list, out = []) {
743
- for (const item of list) {
744
- if (item.type === 'video') out.push(item)
745
- else if (item.type === 'layer') {
746
- if (item.items) videoItems(item.items, out)
747
- for (const sample of item.samples ?? []) videoItems(sample, out)
748
- if (item.matte) videoItems(item.matte.items, out)
749
- } else if (item.type === 'transition') {
750
- videoItems(item.from, out)
751
- videoItems(item.to, out)
752
- }
753
- }
754
- return out
755
- }
756
-
757
- /**
758
- * Decodes the frames a display list shows.
759
- * @param {Map<string, Video>} videos @param {DisplayItem[]} list
760
- */
761
- export async function prepareVideos(videos, list) {
762
- const items = videoItems(list)
763
- if (items.length === 0) return
764
- await Promise.all(items.map(item => {
765
- const video = videos.get(item.src)
766
- if (!video) throw new Error(`video "${item.src}" is not loaded; list it in the scene's assets.videos`)
767
- return video.frame(video.frameIndexAt(item.time))
768
- }))
769
- }
770
-
771
- /**
772
- * The decoded frame a video item shows; it must have been prepared.
773
- * @param {Map<string, Video>} videos @param {DisplayItem & { type: 'video' }} item @param {string} who
774
- */
775
- export function videoFrame(videos, item, who) {
776
- const video = videos.get(item.src)
777
- if (!video) throw new Error(`${who}: video "${item.src}" is not loaded; list it in the scene's assets.videos`)
778
- const index = video.frameIndexAt(item.time)
779
- const frame = video.cached(index)
780
- if (!frame) throw new Error(`${who}: frame ${index} of video "${item.src}" is not decoded yet; await prepare(list) before drawing`)
781
- return frame
782
- }
783
-
784
- /**
785
- * Prepares and draws one display list.
786
- * @param {Canvas2DRenderer} render @param {DisplayItem[]} list
787
- */
788
- async function drawReady(render, list) {
789
- await render.prepare(list)
790
- render(list)
791
- }
792
-
793
- /**
794
- * One frame as a PNG, drawn on a canvas of its own.
795
- * @param {Scene} scene
796
- * @param {number} t
797
- * @param {{ scale?: number }} [options]
798
- * @returns {Promise<Blob>}
799
- */
800
- export async function toPNG(scene, t, { scale = 1 } = {}) {
801
- const render = canvas2d(makeSurface(1, 1), { scale })
802
- try {
803
- await render.load(scene)
804
- await drawReady(render, scene.evaluate(t))
805
- return await pngOf(render.canvas)
806
- } finally {
807
- render.dispose()
808
- }
809
- }
810
-
811
- /**
812
- * Every frame from `from` to `to` as PNGs, one at a time, so long ranges never sit in memory together.
813
- * @param {Scene} scene
814
- * @param {{ from?: number, to?: number, fps?: number, scale?: number }} [options]
815
- * @returns {AsyncGenerator<{ frame: number, t: number, png: Blob }>}
816
- */
817
- export async function* toPNGSequence(scene, { from = 0, to = scene.duration, fps = 30, scale = 1 } = {}) {
818
- const render = canvas2d(makeSurface(1, 1), { scale })
819
- try {
820
- await render.load(scene)
821
- for (let frame = Math.ceil(from * fps - 1e-9); frame / fps < to - 1e-9; frame++) {
822
- const t = scene.frameTime(frame, fps)
823
- await drawReady(render, scene.evaluate(t))
824
- yield { frame, t, png: await pngOf(render.canvas) }
825
- }
826
- } finally {
827
- render.dispose()
828
- }
829
- }
830
-
831
- /**
832
- * @typedef {object} SpriteSheetPlan
833
- * @property {number[]} cells The time drawn into each cell, left to right and top to bottom.
834
- * @property {{ x: number, y: number, w: number, h: number }[]} rects Where each cell sits in the sheet, in px.
835
- * @property {[number, number]} size The whole sheet in px.
836
- * @property {object} json Aseprite's sprite sheet JSON (array form), which cel's aseprite() and game engines read.
837
- */
838
-
839
- /**
840
- * Works out a sprite sheet without drawing it: which frames get a cell, where the cells go, and the JSON. With dedupe
841
- * (the default) a frame whose display list matches an earlier one reuses its cell, and a run of matching frames
842
- * becomes one frame that shows longer, so a cycle animated on twos needs half the cells.
843
- * @param {Scene} scene
844
- * @param {{ from?: number, to?: number, fps?: number, columns?: number, scale?: number, padding?: number,
845
- * dedupe?: boolean, image?: string, tags?: { name: string, from: number, to: number, direction?: string }[] }} [options]
846
- * fps defaults to 24; columns to a near-square layout; padding is px between cells; image is the PNG's file name
847
- * written into the JSON; tag times are seconds.
848
- * @returns {SpriteSheetPlan}
849
- */
850
- export function planSpriteSheet(scene, {
851
- from = 0, to = scene.duration, fps = 24, columns, scale = 1, padding = 0, dedupe = true, image = 'sheet.png', tags = [],
852
- } = {}) {
853
- const w = Math.round(scene.size[0] * scale)
854
- const h = Math.round(scene.size[1] * scale)
855
- /** @type {number[]} */
856
- const cells = []
857
- /** @type {Map<string, number>} */
858
- const seen = new Map()
859
- /** @type {{ cell: number, start: number, frames: number }[]} */
860
- const runs = []
861
- const first = Math.ceil(from * fps - 1e-9)
862
- for (let frame = first; frame / fps < to - 1e-9; frame++) {
863
- const t = scene.frameTime(frame, fps)
864
- const key = dedupe ? hash(scene.evaluate(t)) : String(frame)
865
- let cell = seen.get(key)
866
- if (cell === undefined) {
867
- cell = cells.length
868
- cells.push(t)
869
- seen.set(key, cell)
870
- }
871
- const last = runs[runs.length - 1]
872
- if (dedupe && last && last.cell === cell) last.frames++
873
- else runs.push({ cell, start: frame - first, frames: 1 })
874
- }
875
- if (cells.length === 0) throw new RangeError(`planSpriteSheet: no frames between ${from} and ${to} s`)
876
- const across = columns ?? Math.ceil(Math.sqrt(cells.length))
877
- if (!(Number.isInteger(across) && across > 0)) throw new RangeError(`planSpriteSheet: columns must be a whole number above 0, got ${columns}`)
878
- const down = Math.ceil(cells.length / across)
879
- const rects = cells.map((_, i) => ({ x: (i % across) * (w + padding), y: Math.floor(i / across) * (h + padding), w, h }))
880
- /** @type {[number, number]} */
881
- const size = [Math.min(across, cells.length) * (w + padding) - padding, down * (h + padding) - padding]
882
- // Rounding each run's end rather than its length keeps the total exact to the millisecond.
883
- const ms = (/** @type {number} */ frames) => Math.round((frames * 1000) / fps)
884
- const frames = runs.map((run, i) => ({
885
- filename: `frame ${i}`,
886
- frame: rects[run.cell],
887
- rotated: false,
888
- trimmed: false,
889
- spriteSourceSize: { x: 0, y: 0, w, h },
890
- sourceSize: { w, h },
891
- duration: ms(run.start + run.frames) - ms(run.start),
892
- }))
893
- /** @param {number} t */
894
- const runAt = t => {
895
- const frame = Math.floor(t * fps + 1e-9) - first
896
- const index = runs.findIndex(run => frame < run.start + run.frames)
897
- return index === -1 ? runs.length - 1 : index
898
- }
899
- const frameTags = tags.map(tag => ({ name: tag.name, from: runAt(tag.from), to: runAt(tag.to), direction: tag.direction ?? 'forward' }))
900
- const json = {
901
- frames,
902
- meta: { app: 'motlab.js', image, format: 'RGBA8888', size: { w: size[0], h: size[1] }, scale: String(scale), frameTags },
903
- }
904
- return { cells, rects, size, json }
905
- }
906
-
907
- /**
908
- * Draws a sprite sheet as planSpriteSheet lays it out: one PNG plus Aseprite-style JSON, from a whole scene or a
909
- * component placed in one.
910
- * @param {Scene} scene
911
- * @param {Parameters<typeof planSpriteSheet>[1]} [options]
912
- * @returns {Promise<{ png: Blob, json: object }>}
913
- */
914
- export async function toSpriteSheet(scene, options = {}) {
915
- const plan = planSpriteSheet(scene, options)
916
- const render = canvas2d(makeSurface(1, 1), { scale: options.scale ?? 1 })
917
- try {
918
- await render.load(scene)
919
- const sheet = makeSurface(plan.size[0], plan.size[1])
920
- const c = /** @type {Context} */ (sheet.getContext('2d'))
921
- for (const [i, t] of plan.cells.entries()) {
922
- await drawReady(render, scene.evaluate(t))
923
- c.drawImage(render.canvas, plan.rects[i].x, plan.rects[i].y)
924
- }
925
- return { png: await pngOf(sheet), json: plan.json }
926
- } finally {
927
- render.dispose()
928
- }
929
- }
930
-
931
- /**
932
- * Like verify, but compares pixels: draws every frame in order, then in a shuffled order twice each, and lists the
933
- * times whose pixels changed. It draws on a canvas of its own that stays on the CPU, because Chrome moves a canvas
934
- * from the GPU to the CPU after a few pixel reads and the two smooth edges slightly differently.
935
- * @param {Scene} scene
936
- * @param {{ fps?: number, seed?: string | number, scale?: number }} [options]
937
- */
938
- export async function verifyPixels(scene, { fps = 30, seed = 'verify', scale = 1 } = {}) {
939
- const render = canvas2d(makeSurface(1, 1), { scale, willReadFrequently: true })
940
- try {
941
- await render.load(scene)
942
- const { canvas, context: c } = render
943
- return await comparePixels(scene, async t => {
944
- await drawReady(render, scene.evaluate(t))
945
- return pixelHash(c.getImageData(0, 0, canvas.width, canvas.height).data)
946
- }, { fps, seed })
947
- } finally {
948
- render.dispose()
949
- }
950
- }
1
+ import { guarded, context } from '../core/guard.js'
2
+ import { rand } from '../core/rand.js'
3
+ import { layoutText } from './text-layout.js'
4
+ import { STRIDE } from '../core/nodes.js'
5
+ import { hash } from '../core/hash.js'
6
+ import { openVideo } from '../addons/media.js'
7
+ import { makeSurface, pngOf, pixelHash, comparePixels } from './pixels.js'
8
+
9
+ /** @typedef {import('../core/scene.js').Scene} Scene */
10
+ /** @typedef {import('../core/scene.js').DisplayItem} DisplayItem */
11
+ /** @typedef {import('../core/nodes.js').Gradient} Gradient */
12
+ /** @typedef {import('../core/path.js').Path} Path */
13
+ /** @typedef {CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D} Context */
14
+ /** @typedef {HTMLCanvasElement | OffscreenCanvas} Surface */
15
+
16
+ /** @typedef {import('../addons/media.js').Video} Video */
17
+
18
+ /**
19
+ * @typedef {((list: DisplayItem[]) => void) & {
20
+ * load: (scene: Scene) => Promise<void>,
21
+ * prepare: (list: DisplayItem[]) => Promise<void>,
22
+ * dispose: () => void,
23
+ * readonly canvas: Surface,
24
+ * readonly context: Context
25
+ * }} Canvas2DRenderer
26
+ * Drawing is synchronous, so a list with video items needs `await draw.prepare(list)` first to decode their frames.
27
+ */
28
+
29
+ const NO_DASH = /** @type {number[]} */ ([])
30
+ const DEG = Math.PI / 180
31
+ const DEFAULT_FONT = '10px sans-serif'
32
+ const SPACE = /^\s*$/
33
+ const NEUTRAL = { x: 0, y: 0, rotation: 0, scale: 1, opacity: 1, fill: undefined }
34
+ /** @type {Record<string, GlobalCompositeOperation>} */
35
+ const BLEND = { normal: 'source-over', add: 'lighter' }
36
+
37
+ /** @param {string | undefined} blend */
38
+ const composite = blend => (blend === undefined ? 'source-over' : (BLEND[blend] ?? /** @type {GlobalCompositeOperation} */ (blend)))
39
+
40
+ /**
41
+ * Draws display lists with the Canvas 2D API. Call `await draw.load(scene)` once to size the canvas and load the
42
+ * scene's fonts and images, then `draw(scene.evaluate(t))` for each frame. Works on an HTMLCanvasElement or, in a
43
+ * worker, an OffscreenCanvas.
44
+ * @param {Surface} canvas
45
+ * @param {{ scale?: number, willReadFrequently?: boolean, assets?: { images: Map<string, any>, videos: Map<string, Video> } }} [options]
46
+ * scale draws at a multiple of the scene's size, for sharper output. willReadFrequently keeps the canvas on the CPU,
47
+ * for code that reads pixels back. assets shares images and footage another renderer already loaded.
48
+ * @returns {Canvas2DRenderer}
49
+ */
50
+ export function canvas2d(canvas, { scale = 1, willReadFrequently = false, assets } = {}) {
51
+ const ctx = /** @type {Context | null} */ (canvas.getContext('2d', { willReadFrequently }))
52
+ if (!ctx) throw new Error('canvas2d: this canvas cannot give a 2D context')
53
+ const main = ctx
54
+ /** @type {Map<string, CanvasImageSource & { width: number, height: number }>} */
55
+ const images = assets?.images ?? new Map()
56
+ /** @type {Map<string, Video>} */
57
+ const videos = assets?.videos ?? new Map()
58
+ // A Path2D per path, rebuilt only when commands were added since.
59
+ /** @type {WeakMap<Path, { length: number, path2d: Path2D }>} */
60
+ const built = new WeakMap()
61
+ /** @type {WeakMap<Context, WeakMap<Gradient, CanvasGradient>>} */
62
+ const gradients = new WeakMap()
63
+ /** @type {Map<string, number>} */
64
+ const widths = new Map()
65
+ // Offscreen surfaces for layers: three per nesting level (content, matte, one motion blur sample).
66
+ /** @type {{ canvas: Surface, ctx: Context }[]} */
67
+ const surfaces = []
68
+
69
+ /** @param {number} i */
70
+ function surface(i) {
71
+ let s = surfaces[i]
72
+ if (!s || s.canvas.width !== canvas.width || s.canvas.height !== canvas.height) {
73
+ const c = makeSurface(canvas.width, canvas.height)
74
+ s = { canvas: c, ctx: /** @type {Context} */ (c.getContext('2d', { willReadFrequently })) }
75
+ surfaces[i] = s
76
+ }
77
+ s.ctx.setTransform(1, 0, 0, 1, 0, 0)
78
+ s.ctx.globalAlpha = 1
79
+ s.ctx.globalCompositeOperation = 'source-over'
80
+ s.ctx.clearRect(0, 0, canvas.width, canvas.height)
81
+ return s
82
+ }
83
+
84
+ /** @param {Path} path */
85
+ function path2d(path) {
86
+ const hit = built.get(path)
87
+ if (hit && hit.length === path.data.length) return hit.path2d
88
+ const p = new Path2D()
89
+ path.replay(p)
90
+ built.set(path, { length: path.data.length, path2d: p })
91
+ return p
92
+ }
93
+
94
+ /** @param {Context} c @param {string | Gradient} style */
95
+ function paint(c, style) {
96
+ if (typeof style === 'string') return style
97
+ let cache = gradients.get(c)
98
+ if (!cache) gradients.set(c, (cache = new WeakMap()))
99
+ let g = cache.get(style)
100
+ if (!g) {
101
+ g = style.type === 'linear'
102
+ ? c.createLinearGradient(style.x0, style.y0, style.x1, style.y1)
103
+ : c.createRadialGradient(style.x0, style.y0, style.r0, style.x1, style.y1, style.r1)
104
+ for (const [offset, color] of style.stops) g.addColorStop(Math.min(1, Math.max(0, offset)), color)
105
+ cache.set(style, g)
106
+ }
107
+ return g
108
+ }
109
+
110
+ /** @param {Context} c @param {string} text */
111
+ function measure(c, text) {
112
+ const key = `${c.font}\n${text}`
113
+ let w = widths.get(key)
114
+ if (w === undefined) {
115
+ if (widths.size > 5000) widths.clear()
116
+ w = c.measureText(text).width
117
+ widths.set(key, w)
118
+ }
119
+ return w
120
+ }
121
+
122
+ /**
123
+ * @param {Context} c
124
+ * @param {DisplayItem & { type: 'text' }} item
125
+ * @param {string} text
126
+ * @param {number} x
127
+ * @param {number} y
128
+ * @param {string} [fill]
129
+ */
130
+ function fillStroke(c, item, text, x, y, fill) {
131
+ if (item.fill !== undefined || fill !== undefined) {
132
+ c.fillStyle = paint(c, fill ?? /** @type {string | Gradient} */ (item.fill))
133
+ c.fillText(text, x, y)
134
+ }
135
+ if (item.stroke !== undefined) {
136
+ c.strokeStyle = paint(c, item.stroke)
137
+ c.lineWidth = item.strokeWidth ?? 1
138
+ c.setLineDash(NO_DASH)
139
+ c.strokeText(text, x, y)
140
+ }
141
+ }
142
+
143
+ /** @param {Context} c @param {DisplayItem & { type: 'text' }} item */
144
+ function drawText(c, item) {
145
+ c.font = item.font ?? DEFAULT_FONT
146
+ c.textBaseline = /** @type {CanvasTextBaseline} */ (item.baseline ?? 'alphabetic')
147
+ if (!item.units && item.width === undefined && !item.text.includes('\n')) {
148
+ c.textAlign = /** @type {CanvasTextAlign} */ (item.align ?? 'start')
149
+ fillStroke(c, item, item.text, 0, 0)
150
+ return
151
+ }
152
+ c.textAlign = 'left'
153
+ const layout = layoutText(item, text => measure(c, text))
154
+ if (!item.units) {
155
+ for (const line of layout.lines) fillStroke(c, item, line.text, line.x, line.y)
156
+ return
157
+ }
158
+ const base = c.getTransform()
159
+ const alpha = c.globalAlpha
160
+ item.units.forEach((unit, i) => {
161
+ const box = layout.boxes[i]
162
+ const style = item.offsets?.[i] ?? NEUTRAL
163
+ if (!box || SPACE.test(unit) || style.opacity <= 0 || style.scale === 0) return
164
+ c.setTransform(base)
165
+ c.translate(box.x + box.w / 2 + style.x, box.y + style.y)
166
+ if (style.rotation) c.rotate(style.rotation * DEG)
167
+ if (style.scale !== 1) c.scale(style.scale, style.scale)
168
+ c.globalAlpha = alpha * style.opacity
169
+ fillStroke(c, item, unit, -box.w / 2, 0, style.fill)
170
+ })
171
+ c.setTransform(base)
172
+ c.globalAlpha = alpha
173
+ }
174
+
175
+ /** @param {Context} c @param {DisplayItem & { type: 'layer' }} layer @param {number} depth */
176
+ function drawLayer(c, layer, depth) {
177
+ const content = surface(depth * 3)
178
+ if (layer.samples) {
179
+ // A running average: sample k is laid over the mean of the earlier ones with weight 1 / (k + 1).
180
+ layer.samples.forEach((list, k) => {
181
+ const sample = surface(depth * 3 + 2)
182
+ drawItems(sample.ctx, list, depth + 1)
183
+ content.ctx.setTransform(1, 0, 0, 1, 0, 0)
184
+ content.ctx.globalCompositeOperation = 'source-over'
185
+ content.ctx.globalAlpha = 1 / (k + 1)
186
+ content.ctx.drawImage(sample.canvas, 0, 0)
187
+ })
188
+ } else {
189
+ drawItems(content.ctx, layer.items ?? [], depth + 1)
190
+ }
191
+ if (layer.matte) {
192
+ const mask = surface(depth * 3 + 1)
193
+ drawItems(mask.ctx, layer.matte.items, depth + 1)
194
+ const mode = layer.matte.mode
195
+ if (mode === 'luma' || mode === 'luma-inverted') {
196
+ const image = mask.ctx.getImageData(0, 0, canvas.width, canvas.height)
197
+ const d = image.data
198
+ for (let i = 0; i < d.length; i += 4) {
199
+ const luma = ((0.2126 * d[i] + 0.7152 * d[i + 1] + 0.0722 * d[i + 2]) * d[i + 3]) / 255
200
+ d[i + 3] = mode === 'luma' ? luma : 255 - luma
201
+ }
202
+ mask.ctx.putImageData(image, 0, 0)
203
+ }
204
+ content.ctx.setTransform(1, 0, 0, 1, 0, 0)
205
+ content.ctx.globalAlpha = 1
206
+ content.ctx.globalCompositeOperation = mode === 'alpha-inverted' ? 'destination-out' : 'destination-in'
207
+ content.ctx.drawImage(mask.canvas, 0, 0)
208
+ }
209
+ if (layer.effects) for (const effect of layer.effects) applyEffect(content, effect, layer.t ?? 0, depth)
210
+ c.setTransform(1, 0, 0, 1, 0, 0)
211
+ c.globalAlpha = layer.opacity
212
+ c.globalCompositeOperation = composite(layer.blend)
213
+ c.drawImage(content.canvas, 0, 0)
214
+ }
215
+
216
+ /**
217
+ * One effect on a layer's surface, as close to the WebGL2 renderer as Canvas 2D allows: blur and the glows use the
218
+ * canvas blur filter, and the glow's threshold is approximated with a contrast filter.
219
+ * @param {{ canvas: Surface, ctx: Context }} target @param {import('../core/scene.js').ResolvedEffect} effect
220
+ * @param {number} t @param {number} depth
221
+ */
222
+ function applyEffect(target, effect, t, depth) {
223
+ const temp = surface(depth * 3 + 1)
224
+ const tc = temp.ctx
225
+ const w = canvas.width
226
+ const h = canvas.height
227
+ const put = (/** @type {GlobalCompositeOperation} */ op, /** @type {number} */ alpha) => {
228
+ target.ctx.setTransform(1, 0, 0, 1, 0, 0)
229
+ target.ctx.globalCompositeOperation = op
230
+ target.ctx.globalAlpha = alpha
231
+ target.ctx.drawImage(temp.canvas, 0, 0)
232
+ target.ctx.globalCompositeOperation = 'source-over'
233
+ target.ctx.globalAlpha = 1
234
+ }
235
+ // Paints a full-frame fill into temp, cut to the layer's own shape.
236
+ const masked = (/** @type {string | CanvasGradient | CanvasPattern} */ fill) => {
237
+ tc.fillStyle = fill
238
+ tc.fillRect(0, 0, w, h)
239
+ tc.globalCompositeOperation = 'destination-in'
240
+ tc.drawImage(target.canvas, 0, 0)
241
+ tc.globalCompositeOperation = 'source-over'
242
+ }
243
+ switch (effect.type) {
244
+ case 'blur':
245
+ tc.filter = `blur(${effect.radius * scale}px)`
246
+ tc.drawImage(target.canvas, 0, 0)
247
+ tc.filter = 'none'
248
+ target.ctx.clearRect(0, 0, w, h)
249
+ put('source-over', 1)
250
+ break
251
+ case 'glow':
252
+ case 'diffusion': {
253
+ const contrast = effect.type === 'glow' ? `contrast(${1 + 2 * effect.threshold}) brightness(${1 - effect.threshold / 2}) ` : ''
254
+ tc.filter = `${contrast}blur(${effect.radius * scale}px)`
255
+ tc.drawImage(target.canvas, 0, 0)
256
+ tc.filter = 'none'
257
+ for (let left = effect.strength; left > 0; left -= 1) put('screen', Math.min(1, left))
258
+ break
259
+ }
260
+ case 'grain': {
261
+ masked(/** @type {CanvasPattern} */ (tc.createPattern(noiseTile(effect.seed, t, Math.max(1, effect.size * scale)), 'repeat')))
262
+ put('overlay', Math.min(1, effect.amount * 4))
263
+ break
264
+ }
265
+ case 'para': {
266
+ const a = (effect.angle * Math.PI) / 180
267
+ const r = Math.hypot(w, h) / 2
268
+ const g = tc.createLinearGradient(w / 2 - Math.cos(a) * r, h / 2 - Math.sin(a) * r, w / 2 + Math.cos(a) * r, h / 2 + Math.sin(a) * r)
269
+ g.addColorStop(0, effect.from)
270
+ g.addColorStop(1, effect.to)
271
+ masked(g)
272
+ put(composite(effect.blend), effect.opacity)
273
+ break
274
+ }
275
+ case 'vignette': {
276
+ const r = Math.hypot(w, h) / 2
277
+ const g = tc.createRadialGradient(w / 2, h / 2, r * effect.radius, w / 2, h / 2, r)
278
+ g.addColorStop(0, 'rgba(0, 0, 0, 0)')
279
+ g.addColorStop(1, `rgba(0, 0, 0, ${effect.strength})`)
280
+ masked(g)
281
+ put('source-atop', 1)
282
+ break
283
+ }
284
+ }
285
+ }
286
+
287
+ /**
288
+ * Mixes two lists by a built-in transition, across the item's box or the whole frame; GLSL transitions need the
289
+ * WebGL2 renderer.
290
+ * @param {Context} c @param {DisplayItem & { type: 'transition' }} item @param {number} depth
291
+ */
292
+ function drawTransition(c, item, depth) {
293
+ if (typeof item.effect !== 'string') throw new Error(`canvas2d: transition "${item.id}" runs GLSL, which needs the WebGL2 renderer`)
294
+ const from = surface(depth * 3)
295
+ const to = surface(depth * 3 + 2)
296
+ drawItems(from.ctx, item.from, depth + 1)
297
+ drawItems(to.ctx, item.to, depth + 1)
298
+ const p = item.progress
299
+ const [x, y, w, h] = item.box ? item.box.map(v => v * scale) : [0, 0, canvas.width, canvas.height]
300
+ const cx = x + w / 2
301
+ const cy = y + h / 2
302
+ const params = /** @type {Record<string, number>} */ (item.params)
303
+ const mix = surface(depth * 3 + 1)
304
+ const m = mix.ctx
305
+ // Cuts `to` down to where it shows, by an alpha mask painted with destination-in.
306
+ const reveal = (/** @type {string | CanvasGradient} */ fill) => {
307
+ to.ctx.setTransform(1, 0, 0, 1, 0, 0)
308
+ to.ctx.globalCompositeOperation = 'destination-in'
309
+ to.ctx.fillStyle = fill
310
+ to.ctx.fillRect(0, 0, canvas.width, canvas.height)
311
+ to.ctx.globalCompositeOperation = 'source-over'
312
+ }
313
+ switch (item.effect) {
314
+ case 'fade':
315
+ m.globalAlpha = 1 - p
316
+ m.drawImage(from.canvas, 0, 0)
317
+ m.globalAlpha = p
318
+ m.globalCompositeOperation = 'lighter'
319
+ m.drawImage(to.canvas, 0, 0)
320
+ break
321
+ case 'wipe': {
322
+ const a = ((params.angle ?? 0) * Math.PI) / 180
323
+ const soft = params.softness ?? 0.1
324
+ const reach = (Math.abs(Math.cos(a)) * w + Math.abs(Math.sin(a)) * h) / 2
325
+ const [dx, dy] = [Math.cos(a) * reach, Math.sin(a) * reach]
326
+ const g = m.createLinearGradient(cx - dx, cy - dy, cx + dx, cy + dy)
327
+ const edge = p * (1 + soft)
328
+ g.addColorStop(Math.min(1, Math.max(0, edge - soft)), 'rgba(0, 0, 0, 1)')
329
+ g.addColorStop(Math.min(1, Math.max(0, edge)), 'rgba(0, 0, 0, 0)')
330
+ reveal(g)
331
+ m.drawImage(from.canvas, 0, 0)
332
+ m.drawImage(to.canvas, 0, 0)
333
+ break
334
+ }
335
+ case 'slide': {
336
+ const a = ((params.angle ?? 0) * Math.PI) / 180
337
+ const [dx, dy] = [Math.cos(a) * w, Math.sin(a) * h]
338
+ m.drawImage(from.canvas, -dx * p, -dy * p)
339
+ m.drawImage(to.canvas, dx * (1 - p), dy * (1 - p))
340
+ break
341
+ }
342
+ case 'circle': {
343
+ const ox = x + (params.x ?? 0.5) * w
344
+ const oy = y + (params.y ?? 0.5) * h
345
+ const soft = (params.softness ?? 0.05) * Math.hypot(w, h)
346
+ const r = p * (Math.hypot(Math.max(ox - x, x + w - ox), Math.max(oy - y, y + h - oy)) + soft)
347
+ const g = m.createRadialGradient(ox, oy, Math.max(0, r - soft), ox, oy, Math.max(r, 1e-3))
348
+ g.addColorStop(0, 'rgba(0, 0, 0, 1)')
349
+ g.addColorStop(1, 'rgba(0, 0, 0, 0)')
350
+ reveal(g)
351
+ m.drawImage(from.canvas, 0, 0)
352
+ m.drawImage(to.canvas, 0, 0)
353
+ break
354
+ }
355
+ case 'zoom': {
356
+ const grow = 1 + (params.strength ?? 0.25) * p
357
+ m.globalAlpha = 1 - p
358
+ m.setTransform(grow, 0, 0, grow, cx * (1 - grow), cy * (1 - grow))
359
+ m.drawImage(from.canvas, 0, 0)
360
+ const shrink = 1 + (params.strength ?? 0.25) * (1 - p)
361
+ m.globalAlpha = p
362
+ m.globalCompositeOperation = 'lighter'
363
+ m.setTransform(shrink, 0, 0, shrink, cx * (1 - shrink), cy * (1 - shrink))
364
+ m.drawImage(to.canvas, 0, 0)
365
+ break
366
+ }
367
+ case 'dissolve': {
368
+ const size = Math.max(1, Math.round((params.size ?? 4) * scale))
369
+ const tile = dissolveMask(p, size, w, h)
370
+ to.ctx.setTransform(1, 0, 0, 1, 0, 0)
371
+ to.ctx.globalCompositeOperation = 'destination-in'
372
+ to.ctx.imageSmoothingEnabled = false
373
+ to.ctx.drawImage(tile, x, y, tile.width * size, tile.height * size)
374
+ to.ctx.globalCompositeOperation = 'source-over'
375
+ m.drawImage(from.canvas, 0, 0)
376
+ m.drawImage(to.canvas, 0, 0)
377
+ break
378
+ }
379
+ }
380
+ c.save()
381
+ c.setTransform(1, 0, 0, 1, 0, 0)
382
+ if (item.box) {
383
+ c.beginPath()
384
+ c.rect(x, y, w, h)
385
+ c.clip()
386
+ }
387
+ c.globalAlpha = item.opacity
388
+ c.globalCompositeOperation = composite(item.blend)
389
+ c.drawImage(mix.canvas, 0, 0)
390
+ c.restore()
391
+ }
392
+
393
+ /**
394
+ * An image through a triangle mesh: each triangle is clipped and the image mapped onto it by the affine transform
395
+ * that carries its uv corners to its points. Triangles grow by half a pixel so no seams show between them.
396
+ * @param {Context} c @param {DisplayItem & { type: 'mesh' }} item
397
+ */
398
+ function drawMesh(c, item) {
399
+ const img = images.get(item.src)
400
+ if (!img) throw new Error(`canvas2d: image "${item.src}" is not loaded; list it in the scene's assets.images`)
401
+ const { points: P, uvs: U, triangles: T } = item
402
+ const base = c.getTransform()
403
+ c.imageSmoothingEnabled = item.smooth !== false
404
+ for (let k = 0; k < T.length; k += 3) {
405
+ const [i, j, l] = [T[k] * 2, T[k + 1] * 2, T[k + 2] * 2]
406
+ const [x0, y0, x1, y1, x2, y2] = [P[i], P[i + 1], P[j], P[j + 1], P[l], P[l + 1]]
407
+ const [u0, v0, u1, v1, u2, v2] = [U[i], U[i + 1], U[j], U[j + 1], U[l], U[l + 1]]
408
+ const det = (u1 - u0) * (v2 - v0) - (u2 - u0) * (v1 - v0)
409
+ if (det === 0) continue
410
+ // The affine map with (u, v) to (x, y) at all three corners.
411
+ const a = ((x1 - x0) * (v2 - v0) - (x2 - x0) * (v1 - v0)) / det
412
+ const b = ((y1 - y0) * (v2 - v0) - (y2 - y0) * (v1 - v0)) / det
413
+ const cc = ((x2 - x0) * (u1 - u0) - (x1 - x0) * (u2 - u0)) / det
414
+ const d = ((y2 - y0) * (u1 - u0) - (y1 - y0) * (u2 - u0)) / det
415
+ const e = x0 - a * u0 - cc * v0
416
+ const f = y0 - b * u0 - d * v0
417
+ const cx = (x0 + x1 + x2) / 3
418
+ const cy = (y0 + y1 + y2) / 3
419
+ /** @param {number} x @param {number} y @returns {[number, number]} */
420
+ const grow = (x, y) => {
421
+ const dx = x - cx
422
+ const dy = y - cy
423
+ const len = Math.hypot(dx, dy) || 1
424
+ return [x + (dx / len) * (0.5 / scale), y + (dy / len) * (0.5 / scale)]
425
+ }
426
+ c.save()
427
+ c.beginPath()
428
+ c.moveTo(...grow(x0, y0))
429
+ c.lineTo(...grow(x1, y1))
430
+ c.lineTo(...grow(x2, y2))
431
+ c.closePath()
432
+ c.clip()
433
+ c.transform(a, b, cc, d, e, f)
434
+ c.drawImage(img, 0, 0)
435
+ c.restore()
436
+ c.setTransform(base)
437
+ }
438
+ }
439
+
440
+ /**
441
+ * Draws a shape, text or image with the transform already set. `fill` replaces the item's own, for instances.
442
+ * @param {Context} c @param {DisplayItem} item @param {string | undefined} fill
443
+ */
444
+ function drawLeaf(c, item, fill) {
445
+ switch (item.type) {
446
+ case 'shape': {
447
+ const p = path2d(item.path)
448
+ const fillStyle = fill ?? item.fill
449
+ if (fillStyle !== undefined) {
450
+ c.fillStyle = paint(c, fillStyle)
451
+ c.fill(p)
452
+ }
453
+ if (item.stroke !== undefined) {
454
+ c.strokeStyle = paint(c, item.stroke)
455
+ c.lineWidth = item.strokeWidth ?? 1
456
+ c.lineCap = /** @type {CanvasLineCap} */ (item.lineCap ?? 'butt')
457
+ c.lineJoin = /** @type {CanvasLineJoin} */ (item.lineJoin ?? 'miter')
458
+ c.setLineDash(item.dash ?? NO_DASH)
459
+ c.lineDashOffset = item.dashOffset ?? 0
460
+ c.stroke(p)
461
+ }
462
+ break
463
+ }
464
+ case 'text':
465
+ drawText(c, fill === undefined ? item : { ...item, fill })
466
+ break
467
+ case 'image': {
468
+ const img = images.get(item.src)
469
+ if (!img) throw new Error(`canvas2d: image "${item.src}" is not loaded; list it in the scene's assets.images`)
470
+ c.imageSmoothingEnabled = item.smooth !== false
471
+ if (item.crop) {
472
+ const [sx, sy, sw, sh] = item.crop
473
+ c.drawImage(img, sx, sy, sw, sh, 0, 0, item.w ?? sw, item.h ?? sh)
474
+ } else c.drawImage(img, 0, 0, item.w ?? img.width, item.h ?? img.height)
475
+ break
476
+ }
477
+ case 'video': {
478
+ const frame = videoFrame(videos, item, 'canvas2d')
479
+ c.imageSmoothingEnabled = item.smooth !== false
480
+ if (item.crop) {
481
+ const [sx, sy, sw, sh] = item.crop
482
+ c.drawImage(frame, sx, sy, sw, sh, 0, 0, item.w ?? sw, item.h ?? sh)
483
+ } else c.drawImage(frame, 0, 0, item.w ?? frame.width, item.h ?? frame.height)
484
+ break
485
+ }
486
+ }
487
+ }
488
+
489
+ /**
490
+ * Each copy's transform is the item's, then the copy's own (x, y, rotation, scale), then the base's.
491
+ * @param {Context} c @param {DisplayItem & { type: 'instances' }} item
492
+ */
493
+ function drawInstances(c, item) {
494
+ const { base, data, colors } = item
495
+ if (base.type === 'layer' || base.type === 'instances' || base.type === 'draw' || base.type === 'transition' || base.type === 'mesh') return
496
+ const [m0, m1, m2, m3, m4, m5] = item.matrix
497
+ const [b0, b1, b2, b3, b4, b5] = base.matrix
498
+ for (let k = 0; k < data.length; k += STRIDE) {
499
+ const opacity = data[k + 5]
500
+ if (!(opacity > 0)) continue
501
+ const angle = data[k + 2] * DEG
502
+ const cos = angle === 0 ? 1 : Math.cos(angle)
503
+ const sin = angle === 0 ? 0 : Math.sin(angle)
504
+ const l0 = cos * data[k + 3]
505
+ const l1 = sin * data[k + 3]
506
+ const l2 = -sin * data[k + 4]
507
+ const l3 = cos * data[k + 4]
508
+ const l4 = data[k]
509
+ const l5 = data[k + 1]
510
+ // item × copy
511
+ const a0 = m0 * l0 + m2 * l1
512
+ const a1 = m1 * l0 + m3 * l1
513
+ const a2 = m0 * l2 + m2 * l3
514
+ const a3 = m1 * l2 + m3 * l3
515
+ const a4 = m0 * l4 + m2 * l5 + m4
516
+ const a5 = m1 * l4 + m3 * l5 + m5
517
+ // (item × copy) × base
518
+ c.setTransform(
519
+ (a0 * b0 + a2 * b1) * scale,
520
+ (a1 * b0 + a3 * b1) * scale,
521
+ (a0 * b2 + a2 * b3) * scale,
522
+ (a1 * b2 + a3 * b3) * scale,
523
+ (a0 * b4 + a2 * b5 + a4) * scale,
524
+ (a1 * b4 + a3 * b5 + a5) * scale,
525
+ )
526
+ c.globalAlpha = item.opacity * base.opacity * opacity
527
+ const colour = data[k + 6]
528
+ drawLeaf(c, base, colour >= 0 ? colors[colour] : undefined)
529
+ }
530
+ }
531
+
532
+ /** @param {Context} c @param {DisplayItem[]} list @param {number} depth */
533
+ function drawItems(c, list, depth) {
534
+ for (const item of list) {
535
+ if (item.type === 'layer') {
536
+ drawLayer(c, item, depth)
537
+ continue
538
+ }
539
+ if (item.type === 'transition') {
540
+ drawTransition(c, item, depth)
541
+ continue
542
+ }
543
+ const m = item.matrix
544
+ c.setTransform(m[0] * scale, m[1] * scale, m[2] * scale, m[3] * scale, m[4] * scale, m[5] * scale)
545
+ c.globalAlpha = item.opacity
546
+ c.globalCompositeOperation = composite(item.blend)
547
+ switch (item.type) {
548
+ case 'shape':
549
+ case 'text':
550
+ case 'image':
551
+ case 'video':
552
+ drawLeaf(c, item, undefined)
553
+ break
554
+ case 'mesh':
555
+ drawMesh(c, item)
556
+ break
557
+ case 'instances':
558
+ drawInstances(c, item)
559
+ break
560
+ case 'draw':
561
+ c.save()
562
+ c.imageSmoothingEnabled = true
563
+ try {
564
+ guarded(() => {
565
+ context.node = item.id
566
+ context.t = item.t
567
+ item.draw(c, item.t)
568
+ })
569
+ } finally {
570
+ c.restore()
571
+ }
572
+ break
573
+ }
574
+ }
575
+ }
576
+
577
+ /** @param {DisplayItem[]} list */
578
+ function render(list) {
579
+ main.setTransform(1, 0, 0, 1, 0, 0)
580
+ main.globalAlpha = 1
581
+ main.globalCompositeOperation = 'source-over'
582
+ main.clearRect(0, 0, canvas.width, canvas.height)
583
+ drawItems(main, list, 0)
584
+ }
585
+
586
+ /** @param {Scene} scene */
587
+ async function load(scene) {
588
+ canvas.width = Math.round(scene.size[0] * scale)
589
+ canvas.height = Math.round(scene.size[1] * scale)
590
+ await loadAssets(scene, images, videos)
591
+ }
592
+
593
+ function dispose() {
594
+ surfaces.length = 0
595
+ widths.clear()
596
+ if (!assets) {
597
+ images.clear()
598
+ videos.clear()
599
+ }
600
+ }
601
+
602
+ return Object.defineProperties(/** @type {Canvas2DRenderer} */ (/** @type {unknown} */ (render)), {
603
+ load: { value: load },
604
+ prepare: { value: (/** @type {DisplayItem[]} */ list) => prepareVideos(videos, list) },
605
+ dispose: { value: dispose },
606
+ canvas: { value: canvas },
607
+ context: { value: ctx },
608
+ })
609
+ }
610
+
611
+ // Footage is opened once per URL and shared, so every renderer reuses the frames already decoded.
612
+ /** @type {Map<string, Promise<Video>>} */
613
+ const openedVideos = new Map()
614
+
615
+ /**
616
+ * Loads a scene's fonts into the document (or worker), its images into `images` and its footage into `videos`. A
617
+ * missing file throws, naming it.
618
+ * @param {Scene} scene
619
+ * @param {Map<string, any>} images
620
+ * @param {Map<string, Video>} [videos]
621
+ */
622
+ export async function loadAssets(scene, images, videos) {
623
+ const g = /** @type {any} */ (globalThis)
624
+ const base = g.document?.baseURI ?? g.location?.href
625
+ const fontSet = g.document?.fonts ?? g.fonts
626
+ const { fonts = [], images: sources = {}, videos: footage = {} } = scene.assets
627
+ await Promise.all([
628
+ ...Object.entries(footage).map(async ([key, src]) => {
629
+ const url = new URL(src, base).href
630
+ let opening = openedVideos.get(url)
631
+ if (!opening) {
632
+ opening = openVideo(url)
633
+ openedVideos.set(url, opening)
634
+ opening.catch(() => openedVideos.delete(url))
635
+ }
636
+ try {
637
+ videos?.set(key, await opening)
638
+ } catch (error) {
639
+ throw new Error(`video "${key}" could not be opened from ${src}: ${error instanceof Error ? error.message : error}`)
640
+ }
641
+ }),
642
+ ...fonts.map(async ({ family, src, weight, style }) => {
643
+ const face = new FontFace(family, `url(${new URL(src, base).href})`, { weight, style })
644
+ try {
645
+ await face.load()
646
+ } catch (error) {
647
+ throw new Error(`font "${family}" could not be loaded from ${src}: ${error instanceof Error ? error.message : error}`)
648
+ }
649
+ fontSet.add(face)
650
+ }),
651
+ ...Object.entries(sources).map(async ([key, src]) => {
652
+ try {
653
+ images.set(key, await loadImage(new URL(src, base).href))
654
+ } catch (error) {
655
+ throw new Error(`image "${key}" could not be loaded from ${src}: ${error instanceof Error ? error.message : error}`)
656
+ }
657
+ }),
658
+ ])
659
+ }
660
+
661
+ /**
662
+ * An <img> where there is a document, because it also decodes SVG; createImageBitmap in workers.
663
+ * @param {string} url
664
+ * @returns {Promise<CanvasImageSource & { width: number, height: number }>}
665
+ */
666
+ async function loadImage(url) {
667
+ if (typeof Image !== 'undefined') {
668
+ const img = new Image()
669
+ img.src = url
670
+ await img.decode()
671
+ return img
672
+ }
673
+ const response = await fetch(url)
674
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
675
+ return createImageBitmap(await response.blob())
676
+ }
677
+
678
+ /** @type {Map<string, OffscreenCanvas | HTMLCanvasElement>} */
679
+ const noiseTiles = new Map()
680
+
681
+ /**
682
+ * A grey noise tile for grain, the same for the same seed and moment: each frame of grain differs, but redrawing a
683
+ * frame gives the same grain.
684
+ * @param {number} seed @param {number} t @param {number} size Pixels per grain.
685
+ */
686
+ function noiseTile(seed, t, size) {
687
+ const key = `${seed}:${Math.round(t * 1000)}:${size}`
688
+ let tile = noiseTiles.get(key)
689
+ if (tile) return tile
690
+ if (noiseTiles.size > 64) noiseTiles.clear()
691
+ const n = 128
692
+ tile = makeSurface(Math.round(n * size), Math.round(n * size))
693
+ const small = makeSurface(n, n)
694
+ const sc = /** @type {Context} */ (small.getContext('2d'))
695
+ const image = sc.createImageData(n, n)
696
+ for (let i = 0; i < n * n; i++) {
697
+ const v = Math.round(rand('grain', seed, Math.round(t * 1000), i) * 255)
698
+ image.data.set([v, v, v, 255], i * 4)
699
+ }
700
+ sc.putImageData(image, 0, 0)
701
+ const tc = /** @type {Context} */ (tile.getContext('2d'))
702
+ tc.imageSmoothingEnabled = false
703
+ tc.drawImage(small, 0, 0, tile.width, tile.height)
704
+ noiseTiles.set(key, tile)
705
+ return tile
706
+ }
707
+
708
+ /** @type {Map<string, Float32Array>} */
709
+ const dissolveNoise = new Map()
710
+ /** @type {{ canvas: Surface, ctx: Context, image: ImageData } | null} */
711
+ let dissolveScratch = null
712
+
713
+ /**
714
+ * An alpha mask for a dissolve: a fixed field of random values per block, shown where they fall below progress.
715
+ * @param {number} p @param {number} size @param {number} w @param {number} h
716
+ */
717
+ function dissolveMask(p, size, w, h) {
718
+ const cols = Math.ceil(w / size)
719
+ const rows = Math.ceil(h / size)
720
+ const key = `${cols}x${rows}`
721
+ let field = dissolveNoise.get(key)
722
+ if (!field) {
723
+ if (dissolveNoise.size > 32) dissolveNoise.clear()
724
+ dissolveNoise.set(key, (field = Float32Array.from({ length: cols * rows }, (_, i) => rand('dissolve', i))))
725
+ }
726
+ if (!dissolveScratch || dissolveScratch.canvas.width !== cols || dissolveScratch.canvas.height !== rows) {
727
+ const canvas = makeSurface(cols, rows)
728
+ const ctx = /** @type {Context} */ (canvas.getContext('2d'))
729
+ dissolveScratch = { canvas, ctx, image: ctx.createImageData(cols, rows) }
730
+ }
731
+ const { canvas, ctx, image } = dissolveScratch
732
+ for (let i = 0; i < field.length; i++) image.data[i * 4 + 3] = field[i] < p ? 255 : 0
733
+ ctx.putImageData(image, 0, 0)
734
+ return canvas
735
+ }
736
+
737
+ /**
738
+ * Every video item in a display list, layers included.
739
+ * @param {DisplayItem[]} list
740
+ * @param {(DisplayItem & { type: 'video' })[]} [out]
741
+ */
742
+ export function videoItems(list, out = []) {
743
+ for (const item of list) {
744
+ if (item.type === 'video') out.push(item)
745
+ else if (item.type === 'layer') {
746
+ if (item.items) videoItems(item.items, out)
747
+ for (const sample of item.samples ?? []) videoItems(sample, out)
748
+ if (item.matte) videoItems(item.matte.items, out)
749
+ } else if (item.type === 'transition') {
750
+ videoItems(item.from, out)
751
+ videoItems(item.to, out)
752
+ }
753
+ }
754
+ return out
755
+ }
756
+
757
+ /**
758
+ * Decodes the frames a display list shows.
759
+ * @param {Map<string, Video>} videos @param {DisplayItem[]} list
760
+ */
761
+ export async function prepareVideos(videos, list) {
762
+ const items = videoItems(list)
763
+ if (items.length === 0) return
764
+ await Promise.all(items.map(item => {
765
+ const video = videos.get(item.src)
766
+ if (!video) throw new Error(`video "${item.src}" is not loaded; list it in the scene's assets.videos`)
767
+ return video.frame(video.frameIndexAt(item.time))
768
+ }))
769
+ }
770
+
771
+ /**
772
+ * The decoded frame a video item shows; it must have been prepared.
773
+ * @param {Map<string, Video>} videos @param {DisplayItem & { type: 'video' }} item @param {string} who
774
+ */
775
+ export function videoFrame(videos, item, who) {
776
+ const video = videos.get(item.src)
777
+ if (!video) throw new Error(`${who}: video "${item.src}" is not loaded; list it in the scene's assets.videos`)
778
+ const index = video.frameIndexAt(item.time)
779
+ const frame = video.cached(index)
780
+ if (!frame) throw new Error(`${who}: frame ${index} of video "${item.src}" is not decoded yet; await prepare(list) before drawing`)
781
+ return frame
782
+ }
783
+
784
+ /**
785
+ * Prepares and draws one display list.
786
+ * @param {Canvas2DRenderer} render @param {DisplayItem[]} list
787
+ */
788
+ async function drawReady(render, list) {
789
+ await render.prepare(list)
790
+ render(list)
791
+ }
792
+
793
+ /**
794
+ * One frame as a PNG, drawn on a canvas of its own.
795
+ * @param {Scene} scene
796
+ * @param {number} t
797
+ * @param {{ scale?: number }} [options]
798
+ * @returns {Promise<Blob>}
799
+ */
800
+ export async function toPNG(scene, t, { scale = 1 } = {}) {
801
+ const render = canvas2d(makeSurface(1, 1), { scale })
802
+ try {
803
+ await render.load(scene)
804
+ await drawReady(render, scene.evaluate(t))
805
+ return await pngOf(render.canvas)
806
+ } finally {
807
+ render.dispose()
808
+ }
809
+ }
810
+
811
+ /**
812
+ * Every frame from `from` to `to` as PNGs, one at a time, so long ranges never sit in memory together.
813
+ * @param {Scene} scene
814
+ * @param {{ from?: number, to?: number, fps?: number, scale?: number }} [options]
815
+ * @returns {AsyncGenerator<{ frame: number, t: number, png: Blob }>}
816
+ */
817
+ export async function* toPNGSequence(scene, { from = 0, to = scene.duration, fps = 30, scale = 1 } = {}) {
818
+ const render = canvas2d(makeSurface(1, 1), { scale })
819
+ try {
820
+ await render.load(scene)
821
+ for (let frame = Math.ceil(from * fps - 1e-9); frame / fps < to - 1e-9; frame++) {
822
+ const t = scene.frameTime(frame, fps)
823
+ await drawReady(render, scene.evaluate(t))
824
+ yield { frame, t, png: await pngOf(render.canvas) }
825
+ }
826
+ } finally {
827
+ render.dispose()
828
+ }
829
+ }
830
+
831
+ /**
832
+ * @typedef {object} SpriteSheetPlan
833
+ * @property {number[]} cells The time drawn into each cell, left to right and top to bottom.
834
+ * @property {{ x: number, y: number, w: number, h: number }[]} rects Where each cell sits in the sheet, in px.
835
+ * @property {[number, number]} size The whole sheet in px.
836
+ * @property {object} json Aseprite's sprite sheet JSON (array form), which cel's aseprite() and game engines read.
837
+ */
838
+
839
+ /**
840
+ * Works out a sprite sheet without drawing it: which frames get a cell, where the cells go, and the JSON. With dedupe
841
+ * (the default) a frame whose display list matches an earlier one reuses its cell, and a run of matching frames
842
+ * becomes one frame that shows longer, so a cycle animated on twos needs half the cells.
843
+ * @param {Scene} scene
844
+ * @param {{ from?: number, to?: number, fps?: number, columns?: number, scale?: number, padding?: number,
845
+ * dedupe?: boolean, image?: string, tags?: { name: string, from: number, to: number, direction?: string }[] }} [options]
846
+ * fps defaults to 24; columns to a near-square layout; padding is px between cells; image is the PNG's file name
847
+ * written into the JSON; tag times are seconds.
848
+ * @returns {SpriteSheetPlan}
849
+ */
850
+ export function planSpriteSheet(scene, {
851
+ from = 0, to = scene.duration, fps = 24, columns, scale = 1, padding = 0, dedupe = true, image = 'sheet.png', tags = [],
852
+ } = {}) {
853
+ const w = Math.round(scene.size[0] * scale)
854
+ const h = Math.round(scene.size[1] * scale)
855
+ /** @type {number[]} */
856
+ const cells = []
857
+ /** @type {Map<string, number>} */
858
+ const seen = new Map()
859
+ /** @type {{ cell: number, start: number, frames: number }[]} */
860
+ const runs = []
861
+ const first = Math.ceil(from * fps - 1e-9)
862
+ for (let frame = first; frame / fps < to - 1e-9; frame++) {
863
+ const t = scene.frameTime(frame, fps)
864
+ const key = dedupe ? hash(scene.evaluate(t)) : String(frame)
865
+ let cell = seen.get(key)
866
+ if (cell === undefined) {
867
+ cell = cells.length
868
+ cells.push(t)
869
+ seen.set(key, cell)
870
+ }
871
+ const last = runs[runs.length - 1]
872
+ if (dedupe && last && last.cell === cell) last.frames++
873
+ else runs.push({ cell, start: frame - first, frames: 1 })
874
+ }
875
+ if (cells.length === 0) throw new RangeError(`planSpriteSheet: no frames between ${from} and ${to} s`)
876
+ const across = columns ?? Math.ceil(Math.sqrt(cells.length))
877
+ if (!(Number.isInteger(across) && across > 0)) throw new RangeError(`planSpriteSheet: columns must be a whole number above 0, got ${columns}`)
878
+ const down = Math.ceil(cells.length / across)
879
+ const rects = cells.map((_, i) => ({ x: (i % across) * (w + padding), y: Math.floor(i / across) * (h + padding), w, h }))
880
+ /** @type {[number, number]} */
881
+ const size = [Math.min(across, cells.length) * (w + padding) - padding, down * (h + padding) - padding]
882
+ // Rounding each run's end rather than its length keeps the total exact to the millisecond.
883
+ const ms = (/** @type {number} */ frames) => Math.round((frames * 1000) / fps)
884
+ const frames = runs.map((run, i) => ({
885
+ filename: `frame ${i}`,
886
+ frame: rects[run.cell],
887
+ rotated: false,
888
+ trimmed: false,
889
+ spriteSourceSize: { x: 0, y: 0, w, h },
890
+ sourceSize: { w, h },
891
+ duration: ms(run.start + run.frames) - ms(run.start),
892
+ }))
893
+ /** @param {number} t */
894
+ const runAt = t => {
895
+ const frame = Math.floor(t * fps + 1e-9) - first
896
+ const index = runs.findIndex(run => frame < run.start + run.frames)
897
+ return index === -1 ? runs.length - 1 : index
898
+ }
899
+ const frameTags = tags.map(tag => ({ name: tag.name, from: runAt(tag.from), to: runAt(tag.to), direction: tag.direction ?? 'forward' }))
900
+ const json = {
901
+ frames,
902
+ meta: { app: 'motlab.js', image, format: 'RGBA8888', size: { w: size[0], h: size[1] }, scale: String(scale), frameTags },
903
+ }
904
+ return { cells, rects, size, json }
905
+ }
906
+
907
+ /**
908
+ * Draws a sprite sheet as planSpriteSheet lays it out: one PNG plus Aseprite-style JSON, from a whole scene or a
909
+ * component placed in one.
910
+ * @param {Scene} scene
911
+ * @param {Parameters<typeof planSpriteSheet>[1]} [options]
912
+ * @returns {Promise<{ png: Blob, json: object }>}
913
+ */
914
+ export async function toSpriteSheet(scene, options = {}) {
915
+ const plan = planSpriteSheet(scene, options)
916
+ const render = canvas2d(makeSurface(1, 1), { scale: options.scale ?? 1 })
917
+ try {
918
+ await render.load(scene)
919
+ const sheet = makeSurface(plan.size[0], plan.size[1])
920
+ const c = /** @type {Context} */ (sheet.getContext('2d'))
921
+ for (const [i, t] of plan.cells.entries()) {
922
+ await drawReady(render, scene.evaluate(t))
923
+ c.drawImage(render.canvas, plan.rects[i].x, plan.rects[i].y)
924
+ }
925
+ return { png: await pngOf(sheet), json: plan.json }
926
+ } finally {
927
+ render.dispose()
928
+ }
929
+ }
930
+
931
+ /**
932
+ * Like verify, but compares pixels: draws every frame in order, then in a shuffled order twice each, and lists the
933
+ * times whose pixels changed. It draws on a canvas of its own that stays on the CPU, because Chrome moves a canvas
934
+ * from the GPU to the CPU after a few pixel reads and the two smooth edges slightly differently.
935
+ * @param {Scene} scene
936
+ * @param {{ fps?: number, seed?: string | number, scale?: number }} [options]
937
+ */
938
+ export async function verifyPixels(scene, { fps = 30, seed = 'verify', scale = 1 } = {}) {
939
+ const render = canvas2d(makeSurface(1, 1), { scale, willReadFrequently: true })
940
+ try {
941
+ await render.load(scene)
942
+ const { canvas, context: c } = render
943
+ return await comparePixels(scene, async t => {
944
+ await drawReady(render, scene.evaluate(t))
945
+ return pixelHash(c.getImageData(0, 0, canvas.width, canvas.height).data)
946
+ }, { fps, seed })
947
+ } finally {
948
+ render.dispose()
949
+ }
950
+ }