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,589 +1,589 @@
1
- import { toSVG } from '../core/path.js'
2
- import { layoutText } from './text-layout.js'
3
- import { loadAssets, prepareVideos, videoFrame, videoItems } from './canvas2d.js'
4
- import { STRIDE } from '../core/nodes.js'
5
-
6
- /** @typedef {import('../core/scene.js').Scene} Scene */
7
- /** @typedef {import('../core/scene.js').DisplayItem} DisplayItem */
8
- /** @typedef {import('../core/nodes.js').Gradient} Gradient */
9
- /** @typedef {import('../core/path.js').Path} Path */
10
-
11
- /**
12
- * @typedef {((list: DisplayItem[]) => void) & {
13
- * load: (scene: Scene) => Promise<void>,
14
- * prepare: (list: DisplayItem[]) => Promise<void>,
15
- * toString: () => string,
16
- * dispose: () => void,
17
- * readonly element: SVGSVGElement
18
- * }} SVGRenderer
19
- */
20
-
21
- const NS = 'http://www.w3.org/2000/svg'
22
- const DEG = 180 / Math.PI
23
- const SPACE = /^\s*$/
24
- const NEUTRAL = { x: 0, y: 0, rotation: 0, scale: 1, opacity: 1, fill: undefined }
25
- const ANCHOR = /** @type {Record<string, string>} */ ({ center: 'middle', right: 'end', end: 'end' })
26
- // Sets the alpha to 1 - alpha and the colour to white, which turns an alpha mask inside out.
27
- const INVERT_ALPHA = '0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 -1 1'
28
- let instances = 0
29
-
30
- /** @typedef {import('../core/scene.js').Matrix} Matrix */
31
-
32
- /** @param {number[]} m */
33
- const matrixAttr = m => `matrix(${m.map(v => Math.round(v * 1e6) / 1e6).join(' ')})`
34
-
35
- /** @param {Matrix} p @param {Matrix} q @returns {Matrix} */
36
- const multiply = (p, q) => [
37
- p[0] * q[0] + p[2] * q[1],
38
- p[1] * q[0] + p[3] * q[1],
39
- p[0] * q[2] + p[2] * q[3],
40
- p[1] * q[2] + p[3] * q[3],
41
- p[0] * q[4] + p[2] * q[5] + p[4],
42
- p[1] * q[4] + p[3] * q[5] + p[5],
43
- ]
44
-
45
- /**
46
- * Draws display lists as SVG elements, for crisp vector output and for saving a frame as an SVG file. Draw nodes use
47
- * the canvas API and throw here. Text is placed with canvas font metrics, so it lines up with the Canvas 2D renderer.
48
- * @param {SVGSVGElement} target
49
- * @returns {SVGRenderer}
50
- */
51
- export function svg(target) {
52
- const doc = target.ownerDocument
53
- const prefix = `m${++instances}`
54
- /** @type {Map<string, HTMLImageElement>} */
55
- const images = new Map()
56
- /** @type {Map<string, import('../addons/media.js').Video>} */
57
- const videos = new Map()
58
- // Each decoded frame becomes a PNG blob URL once; dispose() revokes them.
59
- /** @type {WeakMap<ImageBitmap, string>} */
60
- const frameUrls = new WeakMap()
61
- /** @type {Set<string>} */
62
- const blobUrls = new Set()
63
- /** @type {WeakMap<Path, { length: number, d: string }>} */
64
- const pathData = new WeakMap()
65
- const measurer = /** @type {CanvasRenderingContext2D} */ (doc.createElement('canvas').getContext('2d'))
66
- /** @type {Map<string, number>} */
67
- const widths = new Map()
68
- /** @type {Map<string, number>} */
69
- const shifts = new Map()
70
- let size = [0, 0]
71
-
72
- /** @param {string} name @param {Record<string, string | number | undefined>} [attrs] */
73
- function el(name, attrs = {}) {
74
- const node = doc.createElementNS(NS, name)
75
- for (const [key, value] of Object.entries(attrs)) if (value !== undefined) node.setAttribute(key, String(value))
76
- return node
77
- }
78
-
79
- /** @param {Path} path */
80
- function d(path) {
81
- const hit = pathData.get(path)
82
- if (hit && hit.length === path.data.length) return hit.d
83
- const out = toSVG(path)
84
- pathData.set(path, { length: path.data.length, d: out })
85
- return out
86
- }
87
-
88
- /** @param {string} font @param {string} text */
89
- function measure(font, text) {
90
- const key = `${font}\n${text}`
91
- let w = widths.get(key)
92
- if (w === undefined) {
93
- measurer.font = font
94
- w = measurer.measureText(text).width
95
- widths.set(key, w)
96
- }
97
- return w
98
- }
99
-
100
- /**
101
- * How far below the line a canvas textBaseline names the alphabetic baseline lies, so SVG text can sit on the
102
- * alphabetic baseline and still land where canvas puts it. Taken from the font box ascents, because browsers
103
- * disagree on the sign of TextMetrics.alphabeticBaseline.
104
- * @param {string} font @param {string} baseline
105
- */
106
- function baselineShift(font, baseline) {
107
- const key = `${font}\n${baseline}`
108
- let shift = shifts.get(key)
109
- if (shift === undefined) {
110
- measurer.font = font
111
- measurer.textBaseline = 'alphabetic'
112
- const alphabetic = measurer.measureText('Hg').fontBoundingBoxAscent
113
- measurer.textBaseline = /** @type {CanvasTextBaseline} */ (baseline)
114
- shift = alphabetic - measurer.measureText('Hg').fontBoundingBoxAscent
115
- shifts.set(key, shift)
116
- }
117
- return shift
118
- }
119
-
120
- /**
121
- * @param {SVGElement} defs
122
- * @param {() => string} nextId
123
- * @param {string | Gradient | undefined} style
124
- */
125
- function paint(defs, nextId, style) {
126
- if (style === undefined) return 'none'
127
- if (typeof style === 'string') return style
128
- const id = nextId()
129
- const g = style.type === 'linear'
130
- ? el('linearGradient', { id, gradientUnits: 'userSpaceOnUse', x1: style.x0, y1: style.y0, x2: style.x1, y2: style.y1 })
131
- : el('radialGradient', { id, gradientUnits: 'userSpaceOnUse', fx: style.x0, fy: style.y0, fr: style.r0, cx: style.x1, cy: style.y1, r: style.r1 })
132
- for (const [offset, color] of style.stops) g.append(el('stop', { offset: Math.min(1, Math.max(0, offset)), 'stop-color': color }))
133
- defs.append(g)
134
- return `url(#${id})`
135
- }
136
-
137
- /**
138
- * @param {DisplayItem & { type: 'text' }} item
139
- * @param {SVGElement} defs
140
- * @param {() => string} nextId
141
- * @param {string} text
142
- * @param {Record<string, string | number | undefined>} attrs
143
- * @param {string} [fill]
144
- */
145
- function textElement(item, defs, nextId, text, attrs, fill) {
146
- const node = el('text', {
147
- ...attrs,
148
- style: `font: ${item.font ?? '10px sans-serif'}; white-space: pre`,
149
- fill: fill ?? paint(defs, nextId, item.fill),
150
- stroke: item.stroke === undefined ? undefined : paint(defs, nextId, item.stroke),
151
- 'stroke-width': item.stroke === undefined ? undefined : (item.strokeWidth ?? 1),
152
- 'dominant-baseline': 'alphabetic',
153
- })
154
- node.textContent = text
155
- return node
156
- }
157
-
158
- /**
159
- * @param {SVGElement} parent
160
- * @param {DisplayItem[]} list
161
- * @param {SVGElement} defs
162
- * @param {() => string} nextId
163
- */
164
- function draw(parent, list, defs, nextId) {
165
- for (const item of list) {
166
- const blend = item.blend === undefined ? undefined : `mix-blend-mode: ${item.blend === 'add' ? 'plus-lighter' : item.blend}`
167
- if (item.type === 'layer') {
168
- const group = el('g', { opacity: item.opacity, style: `isolation: isolate${blend ? `; ${blend}` : ''}` })
169
- if (item.samples) {
170
- item.samples.forEach((sample, k) => {
171
- const g = el('g', { opacity: 1 / (k + 1) })
172
- draw(g, sample, defs, nextId)
173
- group.append(g)
174
- })
175
- } else draw(group, item.items ?? [], defs, nextId)
176
- if (item.matte) {
177
- const id = nextId()
178
- const mode = item.matte.mode
179
- const mask = el('mask', { id, maskUnits: 'userSpaceOnUse', x: 0, y: 0, width: size[0], height: size[1], style: `mask-type: ${mode === 'luma' ? 'luminance' : 'alpha'}` })
180
- let holder = mask
181
- if (mode !== 'alpha' && mode !== 'luma') {
182
- const filterId = nextId()
183
- const filter = el('filter', { id: filterId, filterUnits: 'userSpaceOnUse', x: 0, y: 0, width: size[0], height: size[1] })
184
- if (mode === 'luma-inverted') filter.append(el('feColorMatrix', { type: 'luminanceToAlpha' }))
185
- filter.append(el('feColorMatrix', { type: 'matrix', values: INVERT_ALPHA }))
186
- defs.append(filter)
187
- holder = el('g', { filter: `url(#${filterId})` })
188
- mask.append(holder)
189
- }
190
- draw(holder, item.matte.items, defs, nextId)
191
- defs.append(mask)
192
- const wrapped = el('g', { mask: `url(#${id})` })
193
- wrapped.append(...group.childNodes)
194
- group.append(wrapped)
195
- }
196
- if (item.effects) {
197
- const filterId = nextId()
198
- defs.append(effectFilter(filterId, item.effects, item.t ?? 0))
199
- const filtered = el('g', { filter: `url(#${filterId})` })
200
- filtered.append(...group.childNodes)
201
- group.append(filtered)
202
- }
203
- parent.append(group)
204
- continue
205
- }
206
- if (item.type === 'transition') {
207
- parent.append(transitionGroup(item, defs, nextId, blend))
208
- continue
209
- }
210
- const transform = matrixAttr(item.matrix)
211
- switch (item.type) {
212
- case 'shape':
213
- parent.append(el('path', {
214
- d: d(item.path),
215
- transform,
216
- fill: paint(defs, nextId, item.fill),
217
- stroke: item.stroke === undefined ? undefined : paint(defs, nextId, item.stroke),
218
- 'stroke-width': item.stroke === undefined ? undefined : (item.strokeWidth ?? 1),
219
- 'stroke-linecap': item.lineCap,
220
- 'stroke-linejoin': item.lineJoin,
221
- 'stroke-miterlimit': item.stroke === undefined ? undefined : 10,
222
- 'stroke-dasharray': item.dash?.length ? item.dash.join(' ') : undefined,
223
- 'stroke-dashoffset': item.dashOffset,
224
- // Canvas applies alpha to fill and stroke separately; whole-element opacity would hide the fill under the stroke.
225
- 'fill-opacity': item.opacity,
226
- 'stroke-opacity': item.opacity,
227
- style: blend,
228
- }))
229
- break
230
- case 'text': {
231
- const font = item.font ?? '10px sans-serif'
232
- const shift = baselineShift(font, item.baseline ?? 'alphabetic')
233
- const common = { 'fill-opacity': item.opacity, 'stroke-opacity': item.opacity }
234
- if (!item.units && item.width === undefined && !item.text.includes('\n')) {
235
- const node = textElement(item, defs, nextId, item.text, { ...common, transform, y: shift, 'text-anchor': ANCHOR[item.align ?? 'start'] ?? 'start' })
236
- if (blend) node.setAttribute('style', `${node.getAttribute('style')}; ${blend}`)
237
- parent.append(node)
238
- break
239
- }
240
- const layout = layoutText(item, text => measure(font, text))
241
- const group = el('g', { transform, style: blend })
242
- if (!item.units) {
243
- for (const line of layout.lines) group.append(textElement(item, defs, nextId, line.text, { ...common, x: line.x, y: line.y + shift }))
244
- } else {
245
- item.units.forEach((unit, i) => {
246
- const box = layout.boxes[i]
247
- const style = item.offsets?.[i] ?? NEUTRAL
248
- if (!box || SPACE.test(unit) || style.opacity <= 0 || style.scale === 0) return
249
- const opacity = item.opacity * style.opacity
250
- const place = `translate(${box.x + box.w / 2 + style.x} ${box.y + style.y}) rotate(${style.rotation}) scale(${style.scale})`
251
- group.append(textElement(item, defs, nextId, unit, { transform: place, x: -box.w / 2, y: shift, 'fill-opacity': opacity, 'stroke-opacity': opacity }, style.fill))
252
- })
253
- }
254
- parent.append(group)
255
- break
256
- }
257
- case 'image': {
258
- const img = images.get(item.src)
259
- if (!img) throw new Error(`svg: image "${item.src}" is not loaded; list it in the scene's assets.images`)
260
- const pixelated = item.smooth === false ? 'pixelated' : undefined
261
- if (item.crop) {
262
- // A nested viewport shows only the cropped part of the source, stretched to w by h.
263
- const [sx, sy, sw, sh] = item.crop
264
- const box = el('svg', { viewBox: `${sx} ${sy} ${sw} ${sh}`, width: item.w ?? sw, height: item.h ?? sh, preserveAspectRatio: 'none' })
265
- box.append(el('image', { href: img.src, width: img.naturalWidth, height: img.naturalHeight, 'image-rendering': pixelated }))
266
- const holder = el('g', { transform, opacity: item.opacity, style: blend })
267
- holder.append(box)
268
- parent.append(holder)
269
- break
270
- }
271
- parent.append(el('image', {
272
- href: img.src,
273
- transform,
274
- width: item.w ?? img.naturalWidth,
275
- height: item.h ?? img.naturalHeight,
276
- preserveAspectRatio: 'none',
277
- 'image-rendering': pixelated,
278
- opacity: item.opacity,
279
- style: blend,
280
- }))
281
- break
282
- }
283
- case 'video': {
284
- const frame = videoFrame(videos, item, 'svg')
285
- const url = frameUrls.get(frame)
286
- if (!url) throw new Error(`svg: a frame of video "${item.src}" is not ready; await prepare(list) before drawing`)
287
- const pixelated = item.smooth === false ? 'pixelated' : undefined
288
- const vw = videos.get(item.src)?.width ?? frame.width
289
- const vh = videos.get(item.src)?.height ?? frame.height
290
- if (item.crop) {
291
- const [sx, sy, sw, sh] = item.crop
292
- const box = el('svg', { viewBox: `${sx} ${sy} ${sw} ${sh}`, width: item.w ?? sw, height: item.h ?? sh, preserveAspectRatio: 'none' })
293
- box.append(el('image', { href: url, width: vw, height: vh, 'image-rendering': pixelated }))
294
- const holder = el('g', { transform, opacity: item.opacity, style: blend })
295
- holder.append(box)
296
- parent.append(holder)
297
- break
298
- }
299
- parent.append(el('image', {
300
- href: url, transform, width: item.w ?? vw, height: item.h ?? vh, preserveAspectRatio: 'none',
301
- 'image-rendering': pixelated, opacity: item.opacity, style: blend,
302
- }))
303
- break
304
- }
305
- case 'mesh': {
306
- const img = images.get(item.src)
307
- if (!img) throw new Error(`svg: image "${item.src}" is not loaded; list it in the scene's assets.images`)
308
- const group = el('g', { transform, opacity: item.opacity, style: blend })
309
- const { points: P, uvs: U, triangles: T } = item
310
- for (let k = 0; k < T.length; k += 3) {
311
- const [i, j, l] = [T[k] * 2, T[k + 1] * 2, T[k + 2] * 2]
312
- const [x0, y0, x1, y1, x2, y2] = [P[i], P[i + 1], P[j], P[j + 1], P[l], P[l + 1]]
313
- const [u0, v0, u1, v1, u2, v2] = [U[i], U[i + 1], U[j], U[j + 1], U[l], U[l + 1]]
314
- const det = (u1 - u0) * (v2 - v0) - (u2 - u0) * (v1 - v0)
315
- if (det === 0) continue
316
- const a = ((x1 - x0) * (v2 - v0) - (x2 - x0) * (v1 - v0)) / det
317
- const b = ((y1 - y0) * (v2 - v0) - (y2 - y0) * (v1 - v0)) / det
318
- const c = ((x2 - x0) * (u1 - u0) - (x1 - x0) * (u2 - u0)) / det
319
- const dd = ((y2 - y0) * (u1 - u0) - (y1 - y0) * (u2 - u0)) / det
320
- const clipId = nextId()
321
- const cx = (x0 + x1 + x2) / 3
322
- const cy = (y0 + y1 + y2) / 3
323
- // Grown by half a unit, as the Canvas 2D renderer does, so neighbouring triangles leave no seam.
324
- const grown = [[x0, y0], [x1, y1], [x2, y2]].map(([x, y]) => {
325
- const len = Math.hypot(x - cx, y - cy) || 1
326
- return `${x + ((x - cx) / len) * 0.5},${y + ((y - cy) / len) * 0.5}`
327
- })
328
- const clip = el('clipPath', { id: clipId })
329
- clip.append(el('polygon', { points: grown.join(' ') }))
330
- defs.append(clip)
331
- const piece = el('g', { 'clip-path': `url(#${clipId})` })
332
- piece.append(el('image', {
333
- href: img.src, width: img.naturalWidth, height: img.naturalHeight,
334
- transform: matrixAttr([a, b, c, dd, x0 - a * u0 - c * v0, y0 - b * u0 - dd * v0]),
335
- 'image-rendering': item.smooth === false ? 'pixelated' : undefined,
336
- }))
337
- group.append(piece)
338
- }
339
- parent.append(group)
340
- break
341
- }
342
- case 'instances': {
343
- const { base, data, colors } = item
344
- if (base.type === 'layer' || base.type === 'instances' || base.type === 'draw' || base.type === 'transition' || base.type === 'mesh') break
345
- /** @type {DisplayItem[]} */
346
- const copies = []
347
- for (let k = 0; k < data.length; k += STRIDE) {
348
- if (!(data[k + 5] > 0)) continue
349
- const angle = (data[k + 2] * Math.PI) / 180
350
- const cos = Math.cos(angle)
351
- const sin = Math.sin(angle)
352
- const copy = /** @type {Matrix} */ ([cos * data[k + 3], sin * data[k + 3], -sin * data[k + 4], cos * data[k + 4], data[k], data[k + 1]])
353
- const colour = data[k + 6]
354
- copies.push({
355
- ...base,
356
- matrix: multiply(multiply(item.matrix, copy), base.matrix),
357
- opacity: item.opacity * base.opacity * data[k + 5],
358
- ...(colour >= 0 ? { fill: colors[colour] } : {}),
359
- })
360
- }
361
- const group = el('g', { style: blend })
362
- draw(group, copies, defs, nextId)
363
- parent.append(group)
364
- break
365
- }
366
- case 'draw':
367
- throw new Error(`svg: node "${item.id}" draws with the canvas API, which SVG cannot run; use the canvas2d renderer`)
368
- }
369
- }
370
- }
371
-
372
- /** @param {DisplayItem[]} list */
373
- function render(list) {
374
- let count = 0
375
- const nextId = () => `${prefix}-${++count}`
376
- const defs = el('defs')
377
- const content = el('g')
378
- draw(content, list, defs, nextId)
379
- target.replaceChildren(defs, content)
380
- }
381
-
382
- /**
383
- * One SVG filter for a layer's effects, applied in order. Para and vignette use a gradient picture of the frame,
384
- * cut to the layer's own alpha.
385
- * @param {string} id @param {import('../core/scene.js').ResolvedEffect[]} effects @param {number} t
386
- */
387
- function effectFilter(id, effects, t) {
388
- const filter = el('filter', { id, filterUnits: 'userSpaceOnUse', x: 0, y: 0, width: size[0], height: size[1], 'color-interpolation-filters': 'sRGB' })
389
- let input = 'SourceGraphic'
390
- effects.forEach((effect, k) => {
391
- const out = `e${k}`
392
- /** @param {string} name @param {Record<string, string | number | undefined>} attrs */
393
- const add = (name, attrs) => {
394
- const node = el(name, attrs)
395
- filter.append(node)
396
- return node
397
- }
398
- /** @param {string} into @param {number} amount Multiplies every channel. */
399
- const scaleAll = (into, amount) => {
400
- const node = add('feComponentTransfer', { in: into, result: `${into}s` })
401
- for (const channel of ['R', 'G', 'B', 'A']) node.append(el(`feFunc${channel}`, { type: 'linear', slope: amount }))
402
- return `${into}s`
403
- }
404
- /** A picture of the whole frame from SVG markup, as filter input. @param {string} markup @param {string} name */
405
- const picture = (markup, name) => {
406
- const svgText = `<svg xmlns="${NS}" width="${size[0]}" height="${size[1]}">${markup}</svg>`
407
- add('feImage', { href: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgText)}`, x: 0, y: 0, width: size[0], height: size[1], preserveAspectRatio: 'none', result: name })
408
- add('feComposite', { in: name, in2: input, operator: 'in', result: `${name}c` })
409
- return `${name}c`
410
- }
411
- switch (effect.type) {
412
- case 'blur':
413
- add('feGaussianBlur', { in: input, stdDeviation: effect.radius, result: out })
414
- break
415
- case 'glow':
416
- case 'diffusion': {
417
- let from = input
418
- if (effect.type === 'glow') {
419
- const th = Math.min(0.99, effect.threshold)
420
- const bright = add('feComponentTransfer', { in: input, result: `${out}b` })
421
- for (const channel of ['R', 'G', 'B']) bright.append(el(`feFunc${channel}`, { type: 'linear', slope: 1 / (1 - th), intercept: -th / (1 - th) }))
422
- from = `${out}b`
423
- }
424
- add('feGaussianBlur', { in: from, stdDeviation: effect.radius, result: `${out}g` })
425
- add('feBlend', { in: scaleAll(`${out}g`, effect.strength), in2: input, mode: 'screen', result: out })
426
- break
427
- }
428
- case 'grain': {
429
- add('feTurbulence', { type: 'fractalNoise', baseFrequency: 1 / Math.max(0.5, effect.size), numOctaves: 1, seed: Math.round(effect.seed * 1000 + t * 1000) % 100000, result: `${out}n` })
430
- add('feColorMatrix', { in: `${out}n`, type: 'saturate', values: 0, result: `${out}m` })
431
- add('feComposite', { in: `${out}m`, in2: input, operator: 'in', result: `${out}k` })
432
- add('feBlend', { in: scaleAll(`${out}k`, Math.min(1, effect.amount * 4)), in2: input, mode: 'overlay', result: out })
433
- break
434
- }
435
- case 'para': {
436
- const a = (effect.angle * Math.PI) / 180
437
- const [x1, y1, x2, y2] = [0.5 - Math.cos(a) / 2, 0.5 - Math.sin(a) / 2, 0.5 + Math.cos(a) / 2, 0.5 + Math.sin(a) / 2]
438
- const markup = `<defs><linearGradient id="g" x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}"><stop offset="0" stop-color="${effect.from}"/><stop offset="1" stop-color="${effect.to}"/></linearGradient></defs><rect width="100%" height="100%" fill="url(#g)"/>`
439
- const cut = picture(markup, `${out}p`)
440
- add('feBlend', { in: scaleAll(cut, effect.opacity), in2: input, mode: effect.blend === 'add' ? 'plus-lighter' : effect.blend, result: out })
441
- break
442
- }
443
- case 'vignette': {
444
- const markup = `<defs><radialGradient id="g" r="${0.5 * Math.SQRT2}"><stop offset="${effect.radius}" stop-color="black" stop-opacity="0"/><stop offset="1" stop-color="black" stop-opacity="${effect.strength}"/></radialGradient></defs><rect width="100%" height="100%" fill="url(#g)"/>`
445
- add('feComposite', { in: picture(markup, `${out}v`), in2: input, operator: 'atop', result: out })
446
- break
447
- }
448
- }
449
- input = out
450
- })
451
- return filter
452
- }
453
-
454
- /**
455
- * A transition as SVG: masks and transforms for the built-in ones; GLSL needs the WebGL2 renderer.
456
- * @param {DisplayItem & { type: 'transition' }} item @param {SVGElement} defs @param {() => string} nextId
457
- * @param {string | undefined} blend
458
- */
459
- function transitionGroup(item, defs, nextId, blend) {
460
- if (typeof item.effect !== 'string') throw new Error(`svg: transition "${item.id}" runs GLSL, which needs the WebGL2 renderer`)
461
- const p = item.progress
462
- const [x, y, w, h] = item.box ?? [0, 0, size[0], size[1]]
463
- const cx = x + w / 2
464
- const cy = y + h / 2
465
- const params = /** @type {Record<string, number>} */ (item.params)
466
- const group = el('g', { opacity: item.opacity, style: `isolation: isolate${blend ? `; ${blend}` : ''}` })
467
- if (item.box) {
468
- const clipId = nextId()
469
- const clip = el('clipPath', { id: clipId, clipPathUnits: 'userSpaceOnUse' })
470
- clip.append(el('rect', { x, y, width: w, height: h }))
471
- defs.append(clip)
472
- group.setAttribute('clip-path', `url(#${clipId})`)
473
- }
474
- const from = el('g', {})
475
- const to = el('g', {})
476
- draw(from, item.from, defs, nextId)
477
- draw(to, item.to, defs, nextId)
478
- /** Shows `to` only where a mask drawn with `paint` is opaque. @param {SVGElement} paint */
479
- const masked = paint => {
480
- const id = nextId()
481
- const mask = el('mask', { id, maskUnits: 'userSpaceOnUse', x, y, width: w, height: h, style: 'mask-type: alpha' })
482
- mask.append(paint)
483
- defs.append(mask)
484
- to.setAttribute('mask', `url(#${id})`)
485
- }
486
- switch (item.effect) {
487
- case 'fade':
488
- case 'zoom': {
489
- const grow = item.effect === 'zoom' ? 1 + (params.strength ?? 0.25) * p : 1
490
- const shrink = item.effect === 'zoom' ? 1 + (params.strength ?? 0.25) * (1 - p) : 1
491
- from.setAttribute('opacity', String(1 - p))
492
- from.setAttribute('transform', matrixAttr([grow, 0, 0, grow, cx * (1 - grow), cy * (1 - grow)]))
493
- to.setAttribute('opacity', String(p))
494
- to.setAttribute('transform', matrixAttr([shrink, 0, 0, shrink, cx * (1 - shrink), cy * (1 - shrink)]))
495
- to.setAttribute('style', 'mix-blend-mode: plus-lighter')
496
- break
497
- }
498
- case 'slide': {
499
- const a = ((params.angle ?? 0) * Math.PI) / 180
500
- from.setAttribute('transform', `translate(${-Math.cos(a) * w * p} ${-Math.sin(a) * h * p})`)
501
- to.setAttribute('transform', `translate(${Math.cos(a) * w * (1 - p)} ${Math.sin(a) * h * (1 - p)})`)
502
- break
503
- }
504
- case 'wipe': {
505
- const a = ((params.angle ?? 0) * Math.PI) / 180
506
- const soft = params.softness ?? 0.1
507
- const edge = p * (1 + soft)
508
- const id = nextId()
509
- const gradient = el('linearGradient', { id, x1: 0.5 - Math.cos(a) / 2, y1: 0.5 - Math.sin(a) / 2, x2: 0.5 + Math.cos(a) / 2, y2: 0.5 + Math.sin(a) / 2 })
510
- gradient.append(el('stop', { offset: Math.min(1, Math.max(0, edge - soft)), 'stop-color': 'black', 'stop-opacity': 1 }))
511
- gradient.append(el('stop', { offset: Math.min(1, Math.max(0, edge)), 'stop-color': 'black', 'stop-opacity': 0 }))
512
- defs.append(gradient)
513
- masked(el('rect', { x, y, width: w, height: h, fill: `url(#${id})` }))
514
- break
515
- }
516
- case 'circle': {
517
- const ox = x + (params.x ?? 0.5) * w
518
- const oy = y + (params.y ?? 0.5) * h
519
- const soft = (params.softness ?? 0.05) * Math.hypot(w, h)
520
- const r = p * (Math.hypot(Math.max(ox - x, x + w - ox), Math.max(oy - y, y + h - oy)) + soft)
521
- const id = nextId()
522
- const gradient = el('radialGradient', { id, gradientUnits: 'userSpaceOnUse', cx: ox, cy: oy, r: Math.max(r, 1e-3) })
523
- gradient.append(el('stop', { offset: Math.max(0, r - soft) / Math.max(r, 1e-3), 'stop-color': 'black', 'stop-opacity': 1 }))
524
- gradient.append(el('stop', { offset: 1, 'stop-color': 'black', 'stop-opacity': 0 }))
525
- defs.append(gradient)
526
- masked(el('rect', { x, y, width: w, height: h, fill: `url(#${id})` }))
527
- break
528
- }
529
- case 'dissolve': {
530
- // Turbulence noise turned into alpha, kept where it falls below progress.
531
- const filterId = nextId()
532
- const filter = el('filter', { id: filterId, filterUnits: 'userSpaceOnUse', x, y, width: w, height: h })
533
- filter.append(el('feTurbulence', { type: 'fractalNoise', baseFrequency: 1 / (params.size ?? 4), numOctaves: 1, seed: 7, result: 'n' }))
534
- filter.append(el('feColorMatrix', { in: 'n', type: 'matrix', values: '0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0', result: 'a' }))
535
- const steps = 32
536
- const table = Array.from({ length: steps }, (_, k) => ((k + 0.5) / steps < 0.3 + p * 0.4 ? 1 : 0)).join(' ')
537
- const transfer = el('feComponentTransfer', { in: 'a' })
538
- transfer.append(el('feFuncA', { type: 'discrete', tableValues: p >= 1 ? '1' : p <= 0 ? '0' : table }))
539
- filter.append(transfer)
540
- defs.append(filter)
541
- masked(el('rect', { x, y, width: w, height: h, fill: 'black', filter: `url(#${filterId})` }))
542
- break
543
- }
544
- }
545
- group.append(from, to)
546
- return group
547
- }
548
-
549
- /** @param {Scene} scene */
550
- async function load(scene) {
551
- size = [scene.size[0], scene.size[1]]
552
- target.setAttribute('viewBox', `0 0 ${size[0]} ${size[1]}`)
553
- if (!target.hasAttribute('width')) target.setAttribute('width', String(size[0]))
554
- if (!target.hasAttribute('height')) target.setAttribute('height', String(size[1]))
555
- await loadAssets(scene, images, videos)
556
- }
557
-
558
- /** @param {DisplayItem[]} list */
559
- async function prepare(list) {
560
- await prepareVideos(videos, list)
561
- for (const item of videoItems(list)) {
562
- const frame = videoFrame(videos, item, 'svg')
563
- if (frameUrls.has(frame)) continue
564
- const canvas = new OffscreenCanvas(frame.width, frame.height)
565
- const c = /** @type {OffscreenCanvasRenderingContext2D} */ (canvas.getContext('2d'))
566
- c.drawImage(frame, 0, 0)
567
- const url = URL.createObjectURL(await canvas.convertToBlob({ type: 'image/png' }))
568
- frameUrls.set(frame, url)
569
- blobUrls.add(url)
570
- }
571
- }
572
-
573
- function dispose() {
574
- for (const url of blobUrls) URL.revokeObjectURL(url)
575
- blobUrls.clear()
576
- widths.clear()
577
- shifts.clear()
578
- images.clear()
579
- videos.clear()
580
- }
581
-
582
- return Object.defineProperties(/** @type {SVGRenderer} */ (/** @type {unknown} */ (render)), {
583
- load: { value: load },
584
- prepare: { value: prepare },
585
- toString: { value: () => new XMLSerializer().serializeToString(target) },
586
- dispose: { value: dispose },
587
- element: { value: target },
588
- })
589
- }
1
+ import { toSVG } from '../core/path.js'
2
+ import { layoutText } from './text-layout.js'
3
+ import { loadAssets, prepareVideos, videoFrame, videoItems } from './canvas2d.js'
4
+ import { STRIDE } from '../core/nodes.js'
5
+
6
+ /** @typedef {import('../core/scene.js').Scene} Scene */
7
+ /** @typedef {import('../core/scene.js').DisplayItem} DisplayItem */
8
+ /** @typedef {import('../core/nodes.js').Gradient} Gradient */
9
+ /** @typedef {import('../core/path.js').Path} Path */
10
+
11
+ /**
12
+ * @typedef {((list: DisplayItem[]) => void) & {
13
+ * load: (scene: Scene) => Promise<void>,
14
+ * prepare: (list: DisplayItem[]) => Promise<void>,
15
+ * toString: () => string,
16
+ * dispose: () => void,
17
+ * readonly element: SVGSVGElement
18
+ * }} SVGRenderer
19
+ */
20
+
21
+ const NS = 'http://www.w3.org/2000/svg'
22
+ const DEG = 180 / Math.PI
23
+ const SPACE = /^\s*$/
24
+ const NEUTRAL = { x: 0, y: 0, rotation: 0, scale: 1, opacity: 1, fill: undefined }
25
+ const ANCHOR = /** @type {Record<string, string>} */ ({ center: 'middle', right: 'end', end: 'end' })
26
+ // Sets the alpha to 1 - alpha and the colour to white, which turns an alpha mask inside out.
27
+ const INVERT_ALPHA = '0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 -1 1'
28
+ let instances = 0
29
+
30
+ /** @typedef {import('../core/scene.js').Matrix} Matrix */
31
+
32
+ /** @param {number[]} m */
33
+ const matrixAttr = m => `matrix(${m.map(v => Math.round(v * 1e6) / 1e6).join(' ')})`
34
+
35
+ /** @param {Matrix} p @param {Matrix} q @returns {Matrix} */
36
+ const multiply = (p, q) => [
37
+ p[0] * q[0] + p[2] * q[1],
38
+ p[1] * q[0] + p[3] * q[1],
39
+ p[0] * q[2] + p[2] * q[3],
40
+ p[1] * q[2] + p[3] * q[3],
41
+ p[0] * q[4] + p[2] * q[5] + p[4],
42
+ p[1] * q[4] + p[3] * q[5] + p[5],
43
+ ]
44
+
45
+ /**
46
+ * Draws display lists as SVG elements, for crisp vector output and for saving a frame as an SVG file. Draw nodes use
47
+ * the canvas API and throw here. Text is placed with canvas font metrics, so it lines up with the Canvas 2D renderer.
48
+ * @param {SVGSVGElement} target
49
+ * @returns {SVGRenderer}
50
+ */
51
+ export function svg(target) {
52
+ const doc = target.ownerDocument
53
+ const prefix = `m${++instances}`
54
+ /** @type {Map<string, HTMLImageElement>} */
55
+ const images = new Map()
56
+ /** @type {Map<string, import('../addons/media.js').Video>} */
57
+ const videos = new Map()
58
+ // Each decoded frame becomes a PNG blob URL once; dispose() revokes them.
59
+ /** @type {WeakMap<ImageBitmap, string>} */
60
+ const frameUrls = new WeakMap()
61
+ /** @type {Set<string>} */
62
+ const blobUrls = new Set()
63
+ /** @type {WeakMap<Path, { length: number, d: string }>} */
64
+ const pathData = new WeakMap()
65
+ const measurer = /** @type {CanvasRenderingContext2D} */ (doc.createElement('canvas').getContext('2d'))
66
+ /** @type {Map<string, number>} */
67
+ const widths = new Map()
68
+ /** @type {Map<string, number>} */
69
+ const shifts = new Map()
70
+ let size = [0, 0]
71
+
72
+ /** @param {string} name @param {Record<string, string | number | undefined>} [attrs] */
73
+ function el(name, attrs = {}) {
74
+ const node = doc.createElementNS(NS, name)
75
+ for (const [key, value] of Object.entries(attrs)) if (value !== undefined) node.setAttribute(key, String(value))
76
+ return node
77
+ }
78
+
79
+ /** @param {Path} path */
80
+ function d(path) {
81
+ const hit = pathData.get(path)
82
+ if (hit && hit.length === path.data.length) return hit.d
83
+ const out = toSVG(path)
84
+ pathData.set(path, { length: path.data.length, d: out })
85
+ return out
86
+ }
87
+
88
+ /** @param {string} font @param {string} text */
89
+ function measure(font, text) {
90
+ const key = `${font}\n${text}`
91
+ let w = widths.get(key)
92
+ if (w === undefined) {
93
+ measurer.font = font
94
+ w = measurer.measureText(text).width
95
+ widths.set(key, w)
96
+ }
97
+ return w
98
+ }
99
+
100
+ /**
101
+ * How far below the line a canvas textBaseline names the alphabetic baseline lies, so SVG text can sit on the
102
+ * alphabetic baseline and still land where canvas puts it. Taken from the font box ascents, because browsers
103
+ * disagree on the sign of TextMetrics.alphabeticBaseline.
104
+ * @param {string} font @param {string} baseline
105
+ */
106
+ function baselineShift(font, baseline) {
107
+ const key = `${font}\n${baseline}`
108
+ let shift = shifts.get(key)
109
+ if (shift === undefined) {
110
+ measurer.font = font
111
+ measurer.textBaseline = 'alphabetic'
112
+ const alphabetic = measurer.measureText('Hg').fontBoundingBoxAscent
113
+ measurer.textBaseline = /** @type {CanvasTextBaseline} */ (baseline)
114
+ shift = alphabetic - measurer.measureText('Hg').fontBoundingBoxAscent
115
+ shifts.set(key, shift)
116
+ }
117
+ return shift
118
+ }
119
+
120
+ /**
121
+ * @param {SVGElement} defs
122
+ * @param {() => string} nextId
123
+ * @param {string | Gradient | undefined} style
124
+ */
125
+ function paint(defs, nextId, style) {
126
+ if (style === undefined) return 'none'
127
+ if (typeof style === 'string') return style
128
+ const id = nextId()
129
+ const g = style.type === 'linear'
130
+ ? el('linearGradient', { id, gradientUnits: 'userSpaceOnUse', x1: style.x0, y1: style.y0, x2: style.x1, y2: style.y1 })
131
+ : el('radialGradient', { id, gradientUnits: 'userSpaceOnUse', fx: style.x0, fy: style.y0, fr: style.r0, cx: style.x1, cy: style.y1, r: style.r1 })
132
+ for (const [offset, color] of style.stops) g.append(el('stop', { offset: Math.min(1, Math.max(0, offset)), 'stop-color': color }))
133
+ defs.append(g)
134
+ return `url(#${id})`
135
+ }
136
+
137
+ /**
138
+ * @param {DisplayItem & { type: 'text' }} item
139
+ * @param {SVGElement} defs
140
+ * @param {() => string} nextId
141
+ * @param {string} text
142
+ * @param {Record<string, string | number | undefined>} attrs
143
+ * @param {string} [fill]
144
+ */
145
+ function textElement(item, defs, nextId, text, attrs, fill) {
146
+ const node = el('text', {
147
+ ...attrs,
148
+ style: `font: ${item.font ?? '10px sans-serif'}; white-space: pre`,
149
+ fill: fill ?? paint(defs, nextId, item.fill),
150
+ stroke: item.stroke === undefined ? undefined : paint(defs, nextId, item.stroke),
151
+ 'stroke-width': item.stroke === undefined ? undefined : (item.strokeWidth ?? 1),
152
+ 'dominant-baseline': 'alphabetic',
153
+ })
154
+ node.textContent = text
155
+ return node
156
+ }
157
+
158
+ /**
159
+ * @param {SVGElement} parent
160
+ * @param {DisplayItem[]} list
161
+ * @param {SVGElement} defs
162
+ * @param {() => string} nextId
163
+ */
164
+ function draw(parent, list, defs, nextId) {
165
+ for (const item of list) {
166
+ const blend = item.blend === undefined ? undefined : `mix-blend-mode: ${item.blend === 'add' ? 'plus-lighter' : item.blend}`
167
+ if (item.type === 'layer') {
168
+ const group = el('g', { opacity: item.opacity, style: `isolation: isolate${blend ? `; ${blend}` : ''}` })
169
+ if (item.samples) {
170
+ item.samples.forEach((sample, k) => {
171
+ const g = el('g', { opacity: 1 / (k + 1) })
172
+ draw(g, sample, defs, nextId)
173
+ group.append(g)
174
+ })
175
+ } else draw(group, item.items ?? [], defs, nextId)
176
+ if (item.matte) {
177
+ const id = nextId()
178
+ const mode = item.matte.mode
179
+ const mask = el('mask', { id, maskUnits: 'userSpaceOnUse', x: 0, y: 0, width: size[0], height: size[1], style: `mask-type: ${mode === 'luma' ? 'luminance' : 'alpha'}` })
180
+ let holder = mask
181
+ if (mode !== 'alpha' && mode !== 'luma') {
182
+ const filterId = nextId()
183
+ const filter = el('filter', { id: filterId, filterUnits: 'userSpaceOnUse', x: 0, y: 0, width: size[0], height: size[1] })
184
+ if (mode === 'luma-inverted') filter.append(el('feColorMatrix', { type: 'luminanceToAlpha' }))
185
+ filter.append(el('feColorMatrix', { type: 'matrix', values: INVERT_ALPHA }))
186
+ defs.append(filter)
187
+ holder = el('g', { filter: `url(#${filterId})` })
188
+ mask.append(holder)
189
+ }
190
+ draw(holder, item.matte.items, defs, nextId)
191
+ defs.append(mask)
192
+ const wrapped = el('g', { mask: `url(#${id})` })
193
+ wrapped.append(...group.childNodes)
194
+ group.append(wrapped)
195
+ }
196
+ if (item.effects) {
197
+ const filterId = nextId()
198
+ defs.append(effectFilter(filterId, item.effects, item.t ?? 0))
199
+ const filtered = el('g', { filter: `url(#${filterId})` })
200
+ filtered.append(...group.childNodes)
201
+ group.append(filtered)
202
+ }
203
+ parent.append(group)
204
+ continue
205
+ }
206
+ if (item.type === 'transition') {
207
+ parent.append(transitionGroup(item, defs, nextId, blend))
208
+ continue
209
+ }
210
+ const transform = matrixAttr(item.matrix)
211
+ switch (item.type) {
212
+ case 'shape':
213
+ parent.append(el('path', {
214
+ d: d(item.path),
215
+ transform,
216
+ fill: paint(defs, nextId, item.fill),
217
+ stroke: item.stroke === undefined ? undefined : paint(defs, nextId, item.stroke),
218
+ 'stroke-width': item.stroke === undefined ? undefined : (item.strokeWidth ?? 1),
219
+ 'stroke-linecap': item.lineCap,
220
+ 'stroke-linejoin': item.lineJoin,
221
+ 'stroke-miterlimit': item.stroke === undefined ? undefined : 10,
222
+ 'stroke-dasharray': item.dash?.length ? item.dash.join(' ') : undefined,
223
+ 'stroke-dashoffset': item.dashOffset,
224
+ // Canvas applies alpha to fill and stroke separately; whole-element opacity would hide the fill under the stroke.
225
+ 'fill-opacity': item.opacity,
226
+ 'stroke-opacity': item.opacity,
227
+ style: blend,
228
+ }))
229
+ break
230
+ case 'text': {
231
+ const font = item.font ?? '10px sans-serif'
232
+ const shift = baselineShift(font, item.baseline ?? 'alphabetic')
233
+ const common = { 'fill-opacity': item.opacity, 'stroke-opacity': item.opacity }
234
+ if (!item.units && item.width === undefined && !item.text.includes('\n')) {
235
+ const node = textElement(item, defs, nextId, item.text, { ...common, transform, y: shift, 'text-anchor': ANCHOR[item.align ?? 'start'] ?? 'start' })
236
+ if (blend) node.setAttribute('style', `${node.getAttribute('style')}; ${blend}`)
237
+ parent.append(node)
238
+ break
239
+ }
240
+ const layout = layoutText(item, text => measure(font, text))
241
+ const group = el('g', { transform, style: blend })
242
+ if (!item.units) {
243
+ for (const line of layout.lines) group.append(textElement(item, defs, nextId, line.text, { ...common, x: line.x, y: line.y + shift }))
244
+ } else {
245
+ item.units.forEach((unit, i) => {
246
+ const box = layout.boxes[i]
247
+ const style = item.offsets?.[i] ?? NEUTRAL
248
+ if (!box || SPACE.test(unit) || style.opacity <= 0 || style.scale === 0) return
249
+ const opacity = item.opacity * style.opacity
250
+ const place = `translate(${box.x + box.w / 2 + style.x} ${box.y + style.y}) rotate(${style.rotation}) scale(${style.scale})`
251
+ group.append(textElement(item, defs, nextId, unit, { transform: place, x: -box.w / 2, y: shift, 'fill-opacity': opacity, 'stroke-opacity': opacity }, style.fill))
252
+ })
253
+ }
254
+ parent.append(group)
255
+ break
256
+ }
257
+ case 'image': {
258
+ const img = images.get(item.src)
259
+ if (!img) throw new Error(`svg: image "${item.src}" is not loaded; list it in the scene's assets.images`)
260
+ const pixelated = item.smooth === false ? 'pixelated' : undefined
261
+ if (item.crop) {
262
+ // A nested viewport shows only the cropped part of the source, stretched to w by h.
263
+ const [sx, sy, sw, sh] = item.crop
264
+ const box = el('svg', { viewBox: `${sx} ${sy} ${sw} ${sh}`, width: item.w ?? sw, height: item.h ?? sh, preserveAspectRatio: 'none' })
265
+ box.append(el('image', { href: img.src, width: img.naturalWidth, height: img.naturalHeight, 'image-rendering': pixelated }))
266
+ const holder = el('g', { transform, opacity: item.opacity, style: blend })
267
+ holder.append(box)
268
+ parent.append(holder)
269
+ break
270
+ }
271
+ parent.append(el('image', {
272
+ href: img.src,
273
+ transform,
274
+ width: item.w ?? img.naturalWidth,
275
+ height: item.h ?? img.naturalHeight,
276
+ preserveAspectRatio: 'none',
277
+ 'image-rendering': pixelated,
278
+ opacity: item.opacity,
279
+ style: blend,
280
+ }))
281
+ break
282
+ }
283
+ case 'video': {
284
+ const frame = videoFrame(videos, item, 'svg')
285
+ const url = frameUrls.get(frame)
286
+ if (!url) throw new Error(`svg: a frame of video "${item.src}" is not ready; await prepare(list) before drawing`)
287
+ const pixelated = item.smooth === false ? 'pixelated' : undefined
288
+ const vw = videos.get(item.src)?.width ?? frame.width
289
+ const vh = videos.get(item.src)?.height ?? frame.height
290
+ if (item.crop) {
291
+ const [sx, sy, sw, sh] = item.crop
292
+ const box = el('svg', { viewBox: `${sx} ${sy} ${sw} ${sh}`, width: item.w ?? sw, height: item.h ?? sh, preserveAspectRatio: 'none' })
293
+ box.append(el('image', { href: url, width: vw, height: vh, 'image-rendering': pixelated }))
294
+ const holder = el('g', { transform, opacity: item.opacity, style: blend })
295
+ holder.append(box)
296
+ parent.append(holder)
297
+ break
298
+ }
299
+ parent.append(el('image', {
300
+ href: url, transform, width: item.w ?? vw, height: item.h ?? vh, preserveAspectRatio: 'none',
301
+ 'image-rendering': pixelated, opacity: item.opacity, style: blend,
302
+ }))
303
+ break
304
+ }
305
+ case 'mesh': {
306
+ const img = images.get(item.src)
307
+ if (!img) throw new Error(`svg: image "${item.src}" is not loaded; list it in the scene's assets.images`)
308
+ const group = el('g', { transform, opacity: item.opacity, style: blend })
309
+ const { points: P, uvs: U, triangles: T } = item
310
+ for (let k = 0; k < T.length; k += 3) {
311
+ const [i, j, l] = [T[k] * 2, T[k + 1] * 2, T[k + 2] * 2]
312
+ const [x0, y0, x1, y1, x2, y2] = [P[i], P[i + 1], P[j], P[j + 1], P[l], P[l + 1]]
313
+ const [u0, v0, u1, v1, u2, v2] = [U[i], U[i + 1], U[j], U[j + 1], U[l], U[l + 1]]
314
+ const det = (u1 - u0) * (v2 - v0) - (u2 - u0) * (v1 - v0)
315
+ if (det === 0) continue
316
+ const a = ((x1 - x0) * (v2 - v0) - (x2 - x0) * (v1 - v0)) / det
317
+ const b = ((y1 - y0) * (v2 - v0) - (y2 - y0) * (v1 - v0)) / det
318
+ const c = ((x2 - x0) * (u1 - u0) - (x1 - x0) * (u2 - u0)) / det
319
+ const dd = ((y2 - y0) * (u1 - u0) - (y1 - y0) * (u2 - u0)) / det
320
+ const clipId = nextId()
321
+ const cx = (x0 + x1 + x2) / 3
322
+ const cy = (y0 + y1 + y2) / 3
323
+ // Grown by half a unit, as the Canvas 2D renderer does, so neighbouring triangles leave no seam.
324
+ const grown = [[x0, y0], [x1, y1], [x2, y2]].map(([x, y]) => {
325
+ const len = Math.hypot(x - cx, y - cy) || 1
326
+ return `${x + ((x - cx) / len) * 0.5},${y + ((y - cy) / len) * 0.5}`
327
+ })
328
+ const clip = el('clipPath', { id: clipId })
329
+ clip.append(el('polygon', { points: grown.join(' ') }))
330
+ defs.append(clip)
331
+ const piece = el('g', { 'clip-path': `url(#${clipId})` })
332
+ piece.append(el('image', {
333
+ href: img.src, width: img.naturalWidth, height: img.naturalHeight,
334
+ transform: matrixAttr([a, b, c, dd, x0 - a * u0 - c * v0, y0 - b * u0 - dd * v0]),
335
+ 'image-rendering': item.smooth === false ? 'pixelated' : undefined,
336
+ }))
337
+ group.append(piece)
338
+ }
339
+ parent.append(group)
340
+ break
341
+ }
342
+ case 'instances': {
343
+ const { base, data, colors } = item
344
+ if (base.type === 'layer' || base.type === 'instances' || base.type === 'draw' || base.type === 'transition' || base.type === 'mesh') break
345
+ /** @type {DisplayItem[]} */
346
+ const copies = []
347
+ for (let k = 0; k < data.length; k += STRIDE) {
348
+ if (!(data[k + 5] > 0)) continue
349
+ const angle = (data[k + 2] * Math.PI) / 180
350
+ const cos = Math.cos(angle)
351
+ const sin = Math.sin(angle)
352
+ const copy = /** @type {Matrix} */ ([cos * data[k + 3], sin * data[k + 3], -sin * data[k + 4], cos * data[k + 4], data[k], data[k + 1]])
353
+ const colour = data[k + 6]
354
+ copies.push({
355
+ ...base,
356
+ matrix: multiply(multiply(item.matrix, copy), base.matrix),
357
+ opacity: item.opacity * base.opacity * data[k + 5],
358
+ ...(colour >= 0 ? { fill: colors[colour] } : {}),
359
+ })
360
+ }
361
+ const group = el('g', { style: blend })
362
+ draw(group, copies, defs, nextId)
363
+ parent.append(group)
364
+ break
365
+ }
366
+ case 'draw':
367
+ throw new Error(`svg: node "${item.id}" draws with the canvas API, which SVG cannot run; use the canvas2d renderer`)
368
+ }
369
+ }
370
+ }
371
+
372
+ /** @param {DisplayItem[]} list */
373
+ function render(list) {
374
+ let count = 0
375
+ const nextId = () => `${prefix}-${++count}`
376
+ const defs = el('defs')
377
+ const content = el('g')
378
+ draw(content, list, defs, nextId)
379
+ target.replaceChildren(defs, content)
380
+ }
381
+
382
+ /**
383
+ * One SVG filter for a layer's effects, applied in order. Para and vignette use a gradient picture of the frame,
384
+ * cut to the layer's own alpha.
385
+ * @param {string} id @param {import('../core/scene.js').ResolvedEffect[]} effects @param {number} t
386
+ */
387
+ function effectFilter(id, effects, t) {
388
+ const filter = el('filter', { id, filterUnits: 'userSpaceOnUse', x: 0, y: 0, width: size[0], height: size[1], 'color-interpolation-filters': 'sRGB' })
389
+ let input = 'SourceGraphic'
390
+ effects.forEach((effect, k) => {
391
+ const out = `e${k}`
392
+ /** @param {string} name @param {Record<string, string | number | undefined>} attrs */
393
+ const add = (name, attrs) => {
394
+ const node = el(name, attrs)
395
+ filter.append(node)
396
+ return node
397
+ }
398
+ /** @param {string} into @param {number} amount Multiplies every channel. */
399
+ const scaleAll = (into, amount) => {
400
+ const node = add('feComponentTransfer', { in: into, result: `${into}s` })
401
+ for (const channel of ['R', 'G', 'B', 'A']) node.append(el(`feFunc${channel}`, { type: 'linear', slope: amount }))
402
+ return `${into}s`
403
+ }
404
+ /** A picture of the whole frame from SVG markup, as filter input. @param {string} markup @param {string} name */
405
+ const picture = (markup, name) => {
406
+ const svgText = `<svg xmlns="${NS}" width="${size[0]}" height="${size[1]}">${markup}</svg>`
407
+ add('feImage', { href: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgText)}`, x: 0, y: 0, width: size[0], height: size[1], preserveAspectRatio: 'none', result: name })
408
+ add('feComposite', { in: name, in2: input, operator: 'in', result: `${name}c` })
409
+ return `${name}c`
410
+ }
411
+ switch (effect.type) {
412
+ case 'blur':
413
+ add('feGaussianBlur', { in: input, stdDeviation: effect.radius, result: out })
414
+ break
415
+ case 'glow':
416
+ case 'diffusion': {
417
+ let from = input
418
+ if (effect.type === 'glow') {
419
+ const th = Math.min(0.99, effect.threshold)
420
+ const bright = add('feComponentTransfer', { in: input, result: `${out}b` })
421
+ for (const channel of ['R', 'G', 'B']) bright.append(el(`feFunc${channel}`, { type: 'linear', slope: 1 / (1 - th), intercept: -th / (1 - th) }))
422
+ from = `${out}b`
423
+ }
424
+ add('feGaussianBlur', { in: from, stdDeviation: effect.radius, result: `${out}g` })
425
+ add('feBlend', { in: scaleAll(`${out}g`, effect.strength), in2: input, mode: 'screen', result: out })
426
+ break
427
+ }
428
+ case 'grain': {
429
+ add('feTurbulence', { type: 'fractalNoise', baseFrequency: 1 / Math.max(0.5, effect.size), numOctaves: 1, seed: Math.round(effect.seed * 1000 + t * 1000) % 100000, result: `${out}n` })
430
+ add('feColorMatrix', { in: `${out}n`, type: 'saturate', values: 0, result: `${out}m` })
431
+ add('feComposite', { in: `${out}m`, in2: input, operator: 'in', result: `${out}k` })
432
+ add('feBlend', { in: scaleAll(`${out}k`, Math.min(1, effect.amount * 4)), in2: input, mode: 'overlay', result: out })
433
+ break
434
+ }
435
+ case 'para': {
436
+ const a = (effect.angle * Math.PI) / 180
437
+ const [x1, y1, x2, y2] = [0.5 - Math.cos(a) / 2, 0.5 - Math.sin(a) / 2, 0.5 + Math.cos(a) / 2, 0.5 + Math.sin(a) / 2]
438
+ const markup = `<defs><linearGradient id="g" x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}"><stop offset="0" stop-color="${effect.from}"/><stop offset="1" stop-color="${effect.to}"/></linearGradient></defs><rect width="100%" height="100%" fill="url(#g)"/>`
439
+ const cut = picture(markup, `${out}p`)
440
+ add('feBlend', { in: scaleAll(cut, effect.opacity), in2: input, mode: effect.blend === 'add' ? 'plus-lighter' : effect.blend, result: out })
441
+ break
442
+ }
443
+ case 'vignette': {
444
+ const markup = `<defs><radialGradient id="g" r="${0.5 * Math.SQRT2}"><stop offset="${effect.radius}" stop-color="black" stop-opacity="0"/><stop offset="1" stop-color="black" stop-opacity="${effect.strength}"/></radialGradient></defs><rect width="100%" height="100%" fill="url(#g)"/>`
445
+ add('feComposite', { in: picture(markup, `${out}v`), in2: input, operator: 'atop', result: out })
446
+ break
447
+ }
448
+ }
449
+ input = out
450
+ })
451
+ return filter
452
+ }
453
+
454
+ /**
455
+ * A transition as SVG: masks and transforms for the built-in ones; GLSL needs the WebGL2 renderer.
456
+ * @param {DisplayItem & { type: 'transition' }} item @param {SVGElement} defs @param {() => string} nextId
457
+ * @param {string | undefined} blend
458
+ */
459
+ function transitionGroup(item, defs, nextId, blend) {
460
+ if (typeof item.effect !== 'string') throw new Error(`svg: transition "${item.id}" runs GLSL, which needs the WebGL2 renderer`)
461
+ const p = item.progress
462
+ const [x, y, w, h] = item.box ?? [0, 0, size[0], size[1]]
463
+ const cx = x + w / 2
464
+ const cy = y + h / 2
465
+ const params = /** @type {Record<string, number>} */ (item.params)
466
+ const group = el('g', { opacity: item.opacity, style: `isolation: isolate${blend ? `; ${blend}` : ''}` })
467
+ if (item.box) {
468
+ const clipId = nextId()
469
+ const clip = el('clipPath', { id: clipId, clipPathUnits: 'userSpaceOnUse' })
470
+ clip.append(el('rect', { x, y, width: w, height: h }))
471
+ defs.append(clip)
472
+ group.setAttribute('clip-path', `url(#${clipId})`)
473
+ }
474
+ const from = el('g', {})
475
+ const to = el('g', {})
476
+ draw(from, item.from, defs, nextId)
477
+ draw(to, item.to, defs, nextId)
478
+ /** Shows `to` only where a mask drawn with `paint` is opaque. @param {SVGElement} paint */
479
+ const masked = paint => {
480
+ const id = nextId()
481
+ const mask = el('mask', { id, maskUnits: 'userSpaceOnUse', x, y, width: w, height: h, style: 'mask-type: alpha' })
482
+ mask.append(paint)
483
+ defs.append(mask)
484
+ to.setAttribute('mask', `url(#${id})`)
485
+ }
486
+ switch (item.effect) {
487
+ case 'fade':
488
+ case 'zoom': {
489
+ const grow = item.effect === 'zoom' ? 1 + (params.strength ?? 0.25) * p : 1
490
+ const shrink = item.effect === 'zoom' ? 1 + (params.strength ?? 0.25) * (1 - p) : 1
491
+ from.setAttribute('opacity', String(1 - p))
492
+ from.setAttribute('transform', matrixAttr([grow, 0, 0, grow, cx * (1 - grow), cy * (1 - grow)]))
493
+ to.setAttribute('opacity', String(p))
494
+ to.setAttribute('transform', matrixAttr([shrink, 0, 0, shrink, cx * (1 - shrink), cy * (1 - shrink)]))
495
+ to.setAttribute('style', 'mix-blend-mode: plus-lighter')
496
+ break
497
+ }
498
+ case 'slide': {
499
+ const a = ((params.angle ?? 0) * Math.PI) / 180
500
+ from.setAttribute('transform', `translate(${-Math.cos(a) * w * p} ${-Math.sin(a) * h * p})`)
501
+ to.setAttribute('transform', `translate(${Math.cos(a) * w * (1 - p)} ${Math.sin(a) * h * (1 - p)})`)
502
+ break
503
+ }
504
+ case 'wipe': {
505
+ const a = ((params.angle ?? 0) * Math.PI) / 180
506
+ const soft = params.softness ?? 0.1
507
+ const edge = p * (1 + soft)
508
+ const id = nextId()
509
+ const gradient = el('linearGradient', { id, x1: 0.5 - Math.cos(a) / 2, y1: 0.5 - Math.sin(a) / 2, x2: 0.5 + Math.cos(a) / 2, y2: 0.5 + Math.sin(a) / 2 })
510
+ gradient.append(el('stop', { offset: Math.min(1, Math.max(0, edge - soft)), 'stop-color': 'black', 'stop-opacity': 1 }))
511
+ gradient.append(el('stop', { offset: Math.min(1, Math.max(0, edge)), 'stop-color': 'black', 'stop-opacity': 0 }))
512
+ defs.append(gradient)
513
+ masked(el('rect', { x, y, width: w, height: h, fill: `url(#${id})` }))
514
+ break
515
+ }
516
+ case 'circle': {
517
+ const ox = x + (params.x ?? 0.5) * w
518
+ const oy = y + (params.y ?? 0.5) * h
519
+ const soft = (params.softness ?? 0.05) * Math.hypot(w, h)
520
+ const r = p * (Math.hypot(Math.max(ox - x, x + w - ox), Math.max(oy - y, y + h - oy)) + soft)
521
+ const id = nextId()
522
+ const gradient = el('radialGradient', { id, gradientUnits: 'userSpaceOnUse', cx: ox, cy: oy, r: Math.max(r, 1e-3) })
523
+ gradient.append(el('stop', { offset: Math.max(0, r - soft) / Math.max(r, 1e-3), 'stop-color': 'black', 'stop-opacity': 1 }))
524
+ gradient.append(el('stop', { offset: 1, 'stop-color': 'black', 'stop-opacity': 0 }))
525
+ defs.append(gradient)
526
+ masked(el('rect', { x, y, width: w, height: h, fill: `url(#${id})` }))
527
+ break
528
+ }
529
+ case 'dissolve': {
530
+ // Turbulence noise turned into alpha, kept where it falls below progress.
531
+ const filterId = nextId()
532
+ const filter = el('filter', { id: filterId, filterUnits: 'userSpaceOnUse', x, y, width: w, height: h })
533
+ filter.append(el('feTurbulence', { type: 'fractalNoise', baseFrequency: 1 / (params.size ?? 4), numOctaves: 1, seed: 7, result: 'n' }))
534
+ filter.append(el('feColorMatrix', { in: 'n', type: 'matrix', values: '0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0', result: 'a' }))
535
+ const steps = 32
536
+ const table = Array.from({ length: steps }, (_, k) => ((k + 0.5) / steps < 0.3 + p * 0.4 ? 1 : 0)).join(' ')
537
+ const transfer = el('feComponentTransfer', { in: 'a' })
538
+ transfer.append(el('feFuncA', { type: 'discrete', tableValues: p >= 1 ? '1' : p <= 0 ? '0' : table }))
539
+ filter.append(transfer)
540
+ defs.append(filter)
541
+ masked(el('rect', { x, y, width: w, height: h, fill: 'black', filter: `url(#${filterId})` }))
542
+ break
543
+ }
544
+ }
545
+ group.append(from, to)
546
+ return group
547
+ }
548
+
549
+ /** @param {Scene} scene */
550
+ async function load(scene) {
551
+ size = [scene.size[0], scene.size[1]]
552
+ target.setAttribute('viewBox', `0 0 ${size[0]} ${size[1]}`)
553
+ if (!target.hasAttribute('width')) target.setAttribute('width', String(size[0]))
554
+ if (!target.hasAttribute('height')) target.setAttribute('height', String(size[1]))
555
+ await loadAssets(scene, images, videos)
556
+ }
557
+
558
+ /** @param {DisplayItem[]} list */
559
+ async function prepare(list) {
560
+ await prepareVideos(videos, list)
561
+ for (const item of videoItems(list)) {
562
+ const frame = videoFrame(videos, item, 'svg')
563
+ if (frameUrls.has(frame)) continue
564
+ const canvas = new OffscreenCanvas(frame.width, frame.height)
565
+ const c = /** @type {OffscreenCanvasRenderingContext2D} */ (canvas.getContext('2d'))
566
+ c.drawImage(frame, 0, 0)
567
+ const url = URL.createObjectURL(await canvas.convertToBlob({ type: 'image/png' }))
568
+ frameUrls.set(frame, url)
569
+ blobUrls.add(url)
570
+ }
571
+ }
572
+
573
+ function dispose() {
574
+ for (const url of blobUrls) URL.revokeObjectURL(url)
575
+ blobUrls.clear()
576
+ widths.clear()
577
+ shifts.clear()
578
+ images.clear()
579
+ videos.clear()
580
+ }
581
+
582
+ return Object.defineProperties(/** @type {SVGRenderer} */ (/** @type {unknown} */ (render)), {
583
+ load: { value: load },
584
+ prepare: { value: prepare },
585
+ toString: { value: () => new XMLSerializer().serializeToString(target) },
586
+ dispose: { value: dispose },
587
+ element: { value: target },
588
+ })
589
+ }