motlab.js 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/README.md +5 -1
- package/llms.txt +794 -794
- package/package.json +107 -107
- package/src/adapters/lottie.js +102 -102
- package/src/adapters/rapier.js +163 -163
- package/src/adapters/rive.js +316 -316
- package/src/addons/deform.js +441 -441
- package/src/addons/physics.js +980 -980
- package/src/core/nodes.js +328 -328
- package/src/core/scene.js +678 -678
- package/src/core/version.js +1 -1
- package/src/renderer/canvas2d.js +950 -950
- package/src/renderer/svg.js +589 -589
- package/src/renderer/webgl2.js +1331 -1331
- package/types/core/version.d.ts +1 -1
package/src/renderer/webgl2.js
CHANGED
|
@@ -1,1331 +1,1331 @@
|
|
|
1
|
-
// Draws display lists with WebGL2. Shapes and text are still rasterized by Canvas 2D on the CPU, in runs whose
|
|
2
|
-
// touched area is uploaded as a texture; the GPU does the rest: images and footage, layers in every blend mode,
|
|
3
|
-
// mattes, motion blur, effects, transitions, meshes and instanced copies.
|
|
4
|
-
import { canvas2d, loadAssets, prepareVideos, videoFrame } from './canvas2d.js'
|
|
5
|
-
import { makeSurface, pngOf, pixelHash, comparePixels } from './pixels.js'
|
|
6
|
-
import { fontSize, layoutText } from './text-layout.js'
|
|
7
|
-
import { STRIDE } from '../core/nodes.js'
|
|
8
|
-
import { hash } from '../core/hash.js'
|
|
9
|
-
import { rand } from '../core/rand.js'
|
|
10
|
-
|
|
11
|
-
/** @typedef {import('../core/scene.js').Scene} Scene */
|
|
12
|
-
/** @typedef {import('../core/scene.js').DisplayItem} DisplayItem */
|
|
13
|
-
/** @typedef {import('../core/scene.js').ResolvedEffect} ResolvedEffect */
|
|
14
|
-
/** @typedef {import('../core/scene.js').Matrix} Matrix */
|
|
15
|
-
/** @typedef {import('../core/path.js').Path} Path */
|
|
16
|
-
/** @typedef {import('../addons/media.js').Video} Video */
|
|
17
|
-
/** @typedef {HTMLCanvasElement | OffscreenCanvas} Surface */
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* @typedef {((list: DisplayItem[]) => void) & {
|
|
21
|
-
* load: (scene: Scene) => Promise<void>,
|
|
22
|
-
* prepare: (list: DisplayItem[]) => Promise<void>,
|
|
23
|
-
* dispose: (options?: { loseContext?: boolean }) => void,
|
|
24
|
-
* readonly canvas: Surface,
|
|
25
|
-
* readonly gl: WebGL2RenderingContext
|
|
26
|
-
* }} WebGL2Renderer
|
|
27
|
-
* Drawing is synchronous, so a list with video items needs `await draw.prepare(list)` first to decode their frames.
|
|
28
|
-
*/
|
|
29
|
-
|
|
30
|
-
/** A texture and the framebuffer that draws into it. @typedef {{ tex: WebGLTexture, fbo: WebGLFramebuffer | null, w: number, h: number }} Target */
|
|
31
|
-
/** Where a list draws. Passes that read the target replace it, so `t` changes as drawing goes on. @typedef {{ t: Target }} Slot */
|
|
32
|
-
/** @typedef {{ program: WebGLProgram, uniforms: Map<string, { loc: WebGLUniformLocation, type: number }>, defaults: Record<string, number | number[]> }} Program */
|
|
33
|
-
/** @typedef {{ tex: WebGLTexture, rect: [number, number, number, number] }} Sprite */
|
|
34
|
-
|
|
35
|
-
// In the order of the shader's blend switch; 'normal' is 0.
|
|
36
|
-
const MODES = [
|
|
37
|
-
'normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light',
|
|
38
|
-
'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity', 'add',
|
|
39
|
-
]
|
|
40
|
-
const MATTES = ['alpha', 'alpha-inverted', 'luma', 'luma-inverted']
|
|
41
|
-
// Blends where drawing a run of items together and compositing the run once equals compositing them one by one.
|
|
42
|
-
const CHAINED = new Set([undefined, 'add', 'screen'])
|
|
43
|
-
// How far glyphs reach above and below the baseline, in font sizes, by textBaseline; generous for accents and descenders.
|
|
44
|
-
const GLYPH_REACH = Object.freeze({
|
|
45
|
-
alphabetic: [-1.3, 0.6], top: [-0.5, 1.6], hanging: [-0.5, 1.6], middle: [-1.1, 1.1], bottom: [-1.6, 0.5], ideographic: [-1.6, 0.5],
|
|
46
|
-
})
|
|
47
|
-
// Bases whose copies are drawn from one cached sprite; text bases are drawn by Canvas 2D.
|
|
48
|
-
const SPRITE_BASES = new Set(['shape', 'image'])
|
|
49
|
-
const SPRITE_PAD = 2
|
|
50
|
-
const SPRITE_CACHE = 24
|
|
51
|
-
// Texture unit for images and sprites, which carry a sampler of their own; passes use units from 0.
|
|
52
|
-
const IMAGE_UNIT = 7
|
|
53
|
-
|
|
54
|
-
const fullVertex = (/** @type {string} */ name) => `#version 300 es
|
|
55
|
-
out vec2 ${name};
|
|
56
|
-
void main() {
|
|
57
|
-
vec2 p = vec2(gl_VertexID & 1, gl_VertexID >> 1) * 4.0 - 1.0;
|
|
58
|
-
${name} = p * 0.5 + 0.5;
|
|
59
|
-
gl_Position = vec4(p, 0.0, 1.0);
|
|
60
|
-
}`
|
|
61
|
-
|
|
62
|
-
const HEAD = `#version 300 es
|
|
63
|
-
precision highp float;
|
|
64
|
-
in vec2 uv;
|
|
65
|
-
out vec4 color;
|
|
66
|
-
`
|
|
67
|
-
|
|
68
|
-
// Premultiplied colours in and out, after the W3C compositing spec: the source over the backdrop, mixed by a mode.
|
|
69
|
-
const BLEND = `
|
|
70
|
-
float lum(vec3 c) { return dot(c, vec3(0.3, 0.59, 0.11)); }
|
|
71
|
-
vec3 clipColor(vec3 c) {
|
|
72
|
-
float l = lum(c);
|
|
73
|
-
float n = min(min(c.r, c.g), c.b);
|
|
74
|
-
float x = max(max(c.r, c.g), c.b);
|
|
75
|
-
if (n < 0.0 && l > n) c = l + (c - l) * l / (l - n);
|
|
76
|
-
if (x > 1.0 && x > l) c = l + (c - l) * (1.0 - l) / (x - l);
|
|
77
|
-
return c;
|
|
78
|
-
}
|
|
79
|
-
vec3 setLum(vec3 c, float l) { return clipColor(c + (l - lum(c))); }
|
|
80
|
-
float sat(vec3 c) { return max(max(c.r, c.g), c.b) - min(min(c.r, c.g), c.b); }
|
|
81
|
-
vec3 setSat(vec3 c, float s) {
|
|
82
|
-
float n = min(min(c.r, c.g), c.b);
|
|
83
|
-
float x = max(max(c.r, c.g), c.b);
|
|
84
|
-
return x > n ? (c - n) * s / (x - n) : vec3(0.0);
|
|
85
|
-
}
|
|
86
|
-
vec3 hardLight(vec3 b, vec3 s) { return mix(2.0 * b * s, 1.0 - 2.0 * (1.0 - b) * (1.0 - s), step(0.5, s)); }
|
|
87
|
-
float dodge(float b, float s) { return b <= 0.0 ? 0.0 : s >= 1.0 ? 1.0 : min(1.0, b / (1.0 - s)); }
|
|
88
|
-
float burn(float b, float s) { return b >= 1.0 ? 1.0 : s <= 0.0 ? 0.0 : 1.0 - min(1.0, (1.0 - b) / s); }
|
|
89
|
-
float softLight(float b, float s) {
|
|
90
|
-
float d = b <= 0.25 ? ((16.0 * b - 12.0) * b + 4.0) * b : sqrt(b);
|
|
91
|
-
return s <= 0.5 ? b - (1.0 - 2.0 * s) * b * (1.0 - b) : b + (2.0 * s - 1.0) * (d - b);
|
|
92
|
-
}
|
|
93
|
-
vec3 mixColor(vec3 b, vec3 s, int mode) {
|
|
94
|
-
switch (mode) {
|
|
95
|
-
case 1: return b * s;
|
|
96
|
-
case 2: return b + s - b * s;
|
|
97
|
-
case 3: return hardLight(s, b);
|
|
98
|
-
case 4: return min(b, s);
|
|
99
|
-
case 5: return max(b, s);
|
|
100
|
-
case 6: return vec3(dodge(b.r, s.r), dodge(b.g, s.g), dodge(b.b, s.b));
|
|
101
|
-
case 7: return vec3(burn(b.r, s.r), burn(b.g, s.g), burn(b.b, s.b));
|
|
102
|
-
case 8: return hardLight(b, s);
|
|
103
|
-
case 9: return vec3(softLight(b.r, s.r), softLight(b.g, s.g), softLight(b.b, s.b));
|
|
104
|
-
case 10: return abs(b - s);
|
|
105
|
-
case 11: return b + s - 2.0 * b * s;
|
|
106
|
-
case 12: return setLum(setSat(s, sat(b)), lum(b));
|
|
107
|
-
case 13: return setLum(setSat(b, sat(s)), lum(b));
|
|
108
|
-
case 14: return setLum(s, lum(b));
|
|
109
|
-
case 15: return setLum(b, lum(s));
|
|
110
|
-
default: return s;
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
vec4 blend(vec4 s, vec4 d, int mode) {
|
|
114
|
-
s = clamp(s, 0.0, 1.0);
|
|
115
|
-
d = clamp(d, 0.0, 1.0);
|
|
116
|
-
if (mode == 16) return min(s + d, 1.0);
|
|
117
|
-
vec3 cs = s.a > 0.0 ? s.rgb / s.a : vec3(0.0);
|
|
118
|
-
vec3 cb = d.a > 0.0 ? d.rgb / d.a : vec3(0.0);
|
|
119
|
-
return vec4(s.rgb * (1.0 - d.a) + d.rgb * (1.0 - s.a) + s.a * d.a * mixColor(cb, cs, mode), s.a + d.a - s.a * d.a);
|
|
120
|
-
}
|
|
121
|
-
`
|
|
122
|
-
|
|
123
|
-
const HASH = `
|
|
124
|
-
uint mixBits(uint x) {
|
|
125
|
-
x ^= x >> 16;
|
|
126
|
-
x *= 0x7feb352du;
|
|
127
|
-
x ^= x >> 15;
|
|
128
|
-
x *= 0x846ca68bu;
|
|
129
|
-
x ^= x >> 16;
|
|
130
|
-
return x;
|
|
131
|
-
}
|
|
132
|
-
`
|
|
133
|
-
|
|
134
|
-
/** Fragment shaders of the full-frame passes, by name. */
|
|
135
|
-
const PASSES = {
|
|
136
|
-
copy: `${HEAD}
|
|
137
|
-
uniform sampler2D src;
|
|
138
|
-
uniform float opacity;
|
|
139
|
-
void main() { color = texture(src, uv) * opacity; }`,
|
|
140
|
-
|
|
141
|
-
blend: `${HEAD}${BLEND}
|
|
142
|
-
uniform sampler2D src, dst;
|
|
143
|
-
uniform float opacity;
|
|
144
|
-
uniform int mode;
|
|
145
|
-
void main() { color = blend(texture(src, uv) * opacity, texture(dst, uv), mode); }`,
|
|
146
|
-
|
|
147
|
-
matte: `${HEAD}
|
|
148
|
-
uniform sampler2D src, mask;
|
|
149
|
-
uniform int mode;
|
|
150
|
-
void main() {
|
|
151
|
-
vec4 m = texture(mask, uv);
|
|
152
|
-
float k = mode < 2 ? m.a : dot(clamp(m.rgb, 0.0, 1.0), vec3(0.2126, 0.7152, 0.0722));
|
|
153
|
-
color = texture(src, uv) * (mode == 1 || mode == 3 ? 1.0 - k : k);
|
|
154
|
-
}`,
|
|
155
|
-
|
|
156
|
-
// One axis of a Gaussian blur; what lies outside the frame counts as transparent, as in Canvas 2D.
|
|
157
|
-
blur: `${HEAD}
|
|
158
|
-
uniform sampler2D src;
|
|
159
|
-
uniform vec2 dir;
|
|
160
|
-
uniform float sigma;
|
|
161
|
-
uniform int radius;
|
|
162
|
-
vec4 tap(vec2 p) { return all(greaterThanEqual(p, vec2(0.0))) && all(lessThanEqual(p, vec2(1.0))) ? texture(src, p) : vec4(0.0); }
|
|
163
|
-
void main() {
|
|
164
|
-
vec4 sum = texture(src, uv);
|
|
165
|
-
float total = 1.0;
|
|
166
|
-
float k = -0.5 / (sigma * sigma);
|
|
167
|
-
for (int i = 1; i <= radius; i++) {
|
|
168
|
-
float w = exp(float(i * i) * k);
|
|
169
|
-
vec2 o = dir * float(i);
|
|
170
|
-
sum += w * (tap(uv + o) + tap(uv - o));
|
|
171
|
-
total += 2.0 * w;
|
|
172
|
-
}
|
|
173
|
-
color = sum / total;
|
|
174
|
-
}`,
|
|
175
|
-
|
|
176
|
-
// Keeps what is brighter than the threshold, scaled by how far above it the pixel is.
|
|
177
|
-
bright: `${HEAD}
|
|
178
|
-
uniform sampler2D src;
|
|
179
|
-
uniform float threshold;
|
|
180
|
-
void main() {
|
|
181
|
-
vec4 c = texture(src, uv);
|
|
182
|
-
float l = c.a > 0.0 ? dot(c.rgb / c.a, vec3(0.2126, 0.7152, 0.0722)) : 0.0;
|
|
183
|
-
color = c * clamp((l - threshold) / max(1.0 - threshold, 1e-4), 0.0, 1.0);
|
|
184
|
-
}`,
|
|
185
|
-
|
|
186
|
-
// Screens the glow on, once per whole unit of strength and once more with what is left.
|
|
187
|
-
screen: `${HEAD}
|
|
188
|
-
uniform sampler2D src, glow;
|
|
189
|
-
uniform float strength;
|
|
190
|
-
void main() {
|
|
191
|
-
vec4 c = clamp(texture(src, uv), 0.0, 1.0);
|
|
192
|
-
vec4 g = clamp(texture(glow, uv), 0.0, 1.0);
|
|
193
|
-
for (float left = min(strength, 8.0); left > 0.0; left -= 1.0) {
|
|
194
|
-
vec4 s = g * min(left, 1.0);
|
|
195
|
-
c = s + c - s * c;
|
|
196
|
-
}
|
|
197
|
-
color = c;
|
|
198
|
-
}`,
|
|
199
|
-
|
|
200
|
-
grain: `${HEAD}${HASH}
|
|
201
|
-
uniform sampler2D src;
|
|
202
|
-
uniform float amount, size;
|
|
203
|
-
uniform uint key;
|
|
204
|
-
void main() {
|
|
205
|
-
vec4 c = texture(src, uv);
|
|
206
|
-
uvec2 cell = uvec2(floor(gl_FragCoord.xy / size));
|
|
207
|
-
float n = float(mixBits(cell.x ^ mixBits(cell.y ^ key))) / 4294967295.0;
|
|
208
|
-
vec3 b = c.a > 0.0 ? clamp(c.rgb / c.a, 0.0, 1.0) : vec3(0.0);
|
|
209
|
-
vec3 o = mix(2.0 * b * n, 1.0 - 2.0 * (1.0 - b) * (1.0 - n), step(0.5, b));
|
|
210
|
-
color = vec4(mix(b, o, min(1.0, amount * 4.0)) * c.a, c.a);
|
|
211
|
-
}`,
|
|
212
|
-
|
|
213
|
-
// A gradient across the frame, inside the layer's own shape, blended on with a mode.
|
|
214
|
-
para: `${HEAD}${BLEND}
|
|
215
|
-
uniform sampler2D src;
|
|
216
|
-
uniform vec4 colorFrom, colorTo;
|
|
217
|
-
uniform vec2 size;
|
|
218
|
-
uniform float angle, opacity;
|
|
219
|
-
uniform int mode;
|
|
220
|
-
void main() {
|
|
221
|
-
vec4 c = texture(src, uv);
|
|
222
|
-
vec2 q = vec2(uv.x, 1.0 - uv.y) * size;
|
|
223
|
-
float s = clamp(dot(q - size * 0.5, vec2(cos(angle), sin(angle))) / length(size) + 0.5, 0.0, 1.0);
|
|
224
|
-
color = blend(mix(colorFrom, colorTo, s) * c.a * opacity, c, mode);
|
|
225
|
-
}`,
|
|
226
|
-
|
|
227
|
-
vignette: `${HEAD}
|
|
228
|
-
uniform sampler2D src;
|
|
229
|
-
uniform vec2 size;
|
|
230
|
-
uniform float strength, radius;
|
|
231
|
-
void main() {
|
|
232
|
-
vec4 c = texture(src, uv);
|
|
233
|
-
float r = length(size) * 0.5;
|
|
234
|
-
float k = strength * clamp((length((uv - 0.5) * size) - r * radius) / max(r - r * radius, 1e-4), 0.0, 1.0);
|
|
235
|
-
color = vec4(c.rgb * (1.0 - k), c.a);
|
|
236
|
-
}`,
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
const MESH_VERTEX = `#version 300 es
|
|
240
|
-
layout(location = 0) in vec2 point;
|
|
241
|
-
layout(location = 1) in vec2 texel;
|
|
242
|
-
uniform mat3 matrix;
|
|
243
|
-
uniform vec2 imageSize;
|
|
244
|
-
out vec2 uv;
|
|
245
|
-
void main() {
|
|
246
|
-
uv = texel / imageSize;
|
|
247
|
-
gl_Position = vec4((matrix * vec3(point, 1.0)).xy, 0.0, 1.0);
|
|
248
|
-
}`
|
|
249
|
-
|
|
250
|
-
const MESH_FRAGMENT = `${HEAD}
|
|
251
|
-
uniform sampler2D image;
|
|
252
|
-
uniform float opacity;
|
|
253
|
-
void main() { color = texture(image, uv) * opacity; }`
|
|
254
|
-
|
|
255
|
-
// Each copy is its STRIDE numbers: x, y, rotation, scale x, scale y, opacity, colour index.
|
|
256
|
-
const INSTANCE_VERTEX = `#version 300 es
|
|
257
|
-
layout(location = 0) in vec2 corner;
|
|
258
|
-
layout(location = 1) in vec4 copyA;
|
|
259
|
-
layout(location = 2) in vec3 copyB;
|
|
260
|
-
uniform mat3 item;
|
|
261
|
-
uniform mat3 base;
|
|
262
|
-
uniform float opacity;
|
|
263
|
-
out vec2 uv;
|
|
264
|
-
out float alpha;
|
|
265
|
-
flat out float layer;
|
|
266
|
-
void main() {
|
|
267
|
-
vec2 p = (base * vec3(corner, 1.0)).xy;
|
|
268
|
-
float r = radians(copyA.z);
|
|
269
|
-
float c = cos(r);
|
|
270
|
-
float s = sin(r);
|
|
271
|
-
p = vec2(c * copyA.w * p.x - s * copyB.x * p.y, s * copyA.w * p.x + c * copyB.x * p.y) + copyA.xy;
|
|
272
|
-
gl_Position = copyB.y > 0.0 ? vec4((item * vec3(p, 1.0)).xy, 0.0, 1.0) : vec4(2.0, 2.0, 2.0, 1.0);
|
|
273
|
-
uv = corner;
|
|
274
|
-
alpha = opacity * copyB.y;
|
|
275
|
-
layer = copyB.z >= 0.0 ? copyB.z + 1.0 : 0.0;
|
|
276
|
-
}`
|
|
277
|
-
|
|
278
|
-
const INSTANCE_FRAGMENT = `#version 300 es
|
|
279
|
-
precision highp float;
|
|
280
|
-
precision highp sampler2DArray;
|
|
281
|
-
uniform sampler2DArray sprites;
|
|
282
|
-
in vec2 uv;
|
|
283
|
-
in float alpha;
|
|
284
|
-
flat in float layer;
|
|
285
|
-
out vec4 color;
|
|
286
|
-
void main() { color = texture(sprites, vec3(uv, layer)) * alpha; }`
|
|
287
|
-
|
|
288
|
-
// The gl-transitions interface: transition(uv) mixes getFromColor and getToColor by progress, ratio is width over
|
|
289
|
-
// height, and uv spans the box (or the frame). viewSize, the area in scene px, is extra; `// = 90.0` after a uniform
|
|
290
|
-
// sets its default.
|
|
291
|
-
const TRANSITION_HEAD = `#version 300 es
|
|
292
|
-
precision highp float;
|
|
293
|
-
in vec2 mlUv;
|
|
294
|
-
out vec4 mlColor;
|
|
295
|
-
uniform sampler2D mlFrom, mlTo;
|
|
296
|
-
uniform vec4 mlBox;
|
|
297
|
-
uniform float progress, ratio;
|
|
298
|
-
uniform vec2 viewSize;
|
|
299
|
-
bool mlInside(vec2 p) { return all(greaterThanEqual(p, vec2(0.0))) && all(lessThanEqual(p, vec2(1.0))); }
|
|
300
|
-
vec4 getFromColor(vec2 p) { return mlInside(p) ? texture(mlFrom, mlBox.xy + p * mlBox.zw) : vec4(0.0); }
|
|
301
|
-
vec4 getToColor(vec2 p) { return mlInside(p) ? texture(mlTo, mlBox.xy + p * mlBox.zw) : vec4(0.0); }
|
|
302
|
-
`
|
|
303
|
-
const TRANSITION_MAIN = `
|
|
304
|
-
void main() {
|
|
305
|
-
vec2 p = (mlUv - mlBox.xy) / mlBox.zw;
|
|
306
|
-
mlColor = mlInside(p) ? transition(p) : vec4(0.0);
|
|
307
|
-
}`
|
|
308
|
-
|
|
309
|
-
/** The built-in transitions, matching the Canvas 2D and SVG renderers. */
|
|
310
|
-
const BUILT_IN = {
|
|
311
|
-
fade: `vec4 transition(vec2 uv) { return mix(getFromColor(uv), getToColor(uv), progress); }`,
|
|
312
|
-
|
|
313
|
-
wipe: `uniform float angle; // = 0.0
|
|
314
|
-
uniform float softness; // = 0.1
|
|
315
|
-
vec4 transition(vec2 uv) {
|
|
316
|
-
vec2 dir = vec2(cos(radians(angle)), sin(radians(angle)));
|
|
317
|
-
vec2 p = (vec2(uv.x, 1.0 - uv.y) - 0.5) * viewSize;
|
|
318
|
-
float s = dot(p, dir) / dot(abs(dir), viewSize) + 0.5;
|
|
319
|
-
float edge = progress * (1.0 + softness);
|
|
320
|
-
float m = softness > 0.0 ? clamp((edge - s) / softness, 0.0, 1.0) : step(s, edge);
|
|
321
|
-
vec4 t = getToColor(uv) * m;
|
|
322
|
-
return t + getFromColor(uv) * (1.0 - t.a);
|
|
323
|
-
}`,
|
|
324
|
-
|
|
325
|
-
slide: `uniform float angle; // = 0.0
|
|
326
|
-
vec4 transition(vec2 uv) {
|
|
327
|
-
vec2 d = vec2(cos(radians(angle)), -sin(radians(angle)));
|
|
328
|
-
vec4 t = getToColor(uv - d * (1.0 - progress));
|
|
329
|
-
return t + getFromColor(uv + d * progress) * (1.0 - t.a);
|
|
330
|
-
}`,
|
|
331
|
-
|
|
332
|
-
circle: `uniform float x; // = 0.5
|
|
333
|
-
uniform float y; // = 0.5
|
|
334
|
-
uniform float softness; // = 0.05
|
|
335
|
-
vec4 transition(vec2 uv) {
|
|
336
|
-
vec2 c = vec2(x, y) * viewSize;
|
|
337
|
-
vec2 p = vec2(uv.x, 1.0 - uv.y) * viewSize;
|
|
338
|
-
float soft = softness * length(viewSize);
|
|
339
|
-
float r = progress * (length(max(c, viewSize - c)) + soft);
|
|
340
|
-
float inner = max(0.0, r - soft);
|
|
341
|
-
float outer = max(r, 1e-3);
|
|
342
|
-
vec4 t = getToColor(uv) * clamp((outer - distance(p, c)) / max(outer - inner, 1e-3), 0.0, 1.0);
|
|
343
|
-
return t + getFromColor(uv) * (1.0 - t.a);
|
|
344
|
-
}`,
|
|
345
|
-
|
|
346
|
-
zoom: `uniform float strength; // = 0.25
|
|
347
|
-
vec4 transition(vec2 uv) {
|
|
348
|
-
vec2 from = 0.5 + (uv - 0.5) / (1.0 + strength * progress);
|
|
349
|
-
vec2 to = 0.5 + (uv - 0.5) / (1.0 + strength * (1.0 - progress));
|
|
350
|
-
return getFromColor(from) * (1.0 - progress) + getToColor(to) * progress;
|
|
351
|
-
}`,
|
|
352
|
-
|
|
353
|
-
dissolve: `uniform float size; // = 4.0
|
|
354
|
-
${HASH}
|
|
355
|
-
vec4 transition(vec2 uv) {
|
|
356
|
-
uvec2 cell = uvec2(floor(vec2(uv.x, 1.0 - uv.y) * viewSize / max(size, 1e-3)));
|
|
357
|
-
float n = float(mixBits(cell.x ^ mixBits(cell.y + 0x9e3779b9u))) / 4294967296.0;
|
|
358
|
-
vec4 t = n < progress ? getToColor(uv) : vec4(0.0);
|
|
359
|
-
return t + getFromColor(uv) * (1.0 - t.a);
|
|
360
|
-
}`,
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
const DEFAULT_UNIFORM = /uniform\s+(\w+)\s+(\w+)\s*;\s*\/\/\s*=\s*([^\n]+)/g
|
|
364
|
-
|
|
365
|
-
/**
|
|
366
|
-
* Defaults written as `// = value` after uniform declarations.
|
|
367
|
-
* @param {string} source
|
|
368
|
-
* @returns {Record<string, number | number[]>}
|
|
369
|
-
*/
|
|
370
|
-
function uniformDefaults(source) {
|
|
371
|
-
/** @type {Record<string, number | number[]>} */
|
|
372
|
-
const out = {}
|
|
373
|
-
for (const [, type, name, text] of source.matchAll(DEFAULT_UNIFORM)) {
|
|
374
|
-
const numbers = (text.match(/-?\d*\.?\d+(?:e[-+]?\d+)?|true|false/gi) ?? []).map(v => (v === 'true' ? 1 : v === 'false' ? 0 : Number(v)))
|
|
375
|
-
const size = Number(/(\d)$/.exec(type)?.[1] ?? 1)
|
|
376
|
-
if (numbers.length === 0) continue
|
|
377
|
-
out[name] = size === 1 ? numbers[0] : numbers.length === 1 ? Array(size).fill(numbers[0]) : numbers.slice(0, size)
|
|
378
|
-
}
|
|
379
|
-
return out
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
/**
|
|
383
|
-
* The bounds of a path's points and control points, which hold the whole curve.
|
|
384
|
-
* @param {Path} path
|
|
385
|
-
* @returns {[number, number, number, number] | null}
|
|
386
|
-
*/
|
|
387
|
-
function pathBounds(path) {
|
|
388
|
-
let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity]
|
|
389
|
-
const add = (/** @type {number} */ x, /** @type {number} */ y) => {
|
|
390
|
-
x0 = Math.min(x0, x)
|
|
391
|
-
y0 = Math.min(y0, y)
|
|
392
|
-
x1 = Math.max(x1, x)
|
|
393
|
-
y1 = Math.max(y1, y)
|
|
394
|
-
}
|
|
395
|
-
const round = (/** @type {number} */ x, /** @type {number} */ y, /** @type {number} */ r) => {
|
|
396
|
-
add(x - r, y - r)
|
|
397
|
-
add(x + r, y + r)
|
|
398
|
-
}
|
|
399
|
-
path.replay({
|
|
400
|
-
moveTo: add,
|
|
401
|
-
lineTo: add,
|
|
402
|
-
bezierCurveTo: (ax, ay, bx, by, x, y) => (add(ax, ay), add(bx, by), add(x, y)),
|
|
403
|
-
quadraticCurveTo: (ax, ay, x, y) => (add(ax, ay), add(x, y)),
|
|
404
|
-
arc: (x, y, r) => round(x, y, r),
|
|
405
|
-
arcTo: (ax, ay, bx, by) => (add(ax, ay), add(bx, by)),
|
|
406
|
-
ellipse: (x, y, rx, ry) => round(x, y, Math.max(rx, ry)),
|
|
407
|
-
rect: (x, y, w, h) => (add(x, y), add(x + w, y + h)),
|
|
408
|
-
roundRect: (x, y, w, h) => (add(x, y), add(x + w, y + h)),
|
|
409
|
-
closePath: () => {},
|
|
410
|
-
})
|
|
411
|
-
return x0 <= x1 ? [x0, y0, x1, y1] : null
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
/** How much a matrix stretches its longest axis. @param {Matrix} m */
|
|
415
|
-
const stretch = m => Math.max(Math.hypot(m[0], m[1]), Math.hypot(m[2], m[3]))
|
|
416
|
-
|
|
417
|
-
/**
|
|
418
|
-
* Draws display lists with WebGL2, with the same contract as canvas2d: `await draw.load(scene)` once, then
|
|
419
|
-
* `draw(scene.evaluate(t))` per frame. It also runs GLSL transitions, which the other renderers cannot.
|
|
420
|
-
* @param {Surface} canvas
|
|
421
|
-
* @param {{ scale?: number, preserveDrawingBuffer?: boolean }} [options] preserveDrawingBuffer keeps the last frame
|
|
422
|
-
* readable after the browser has shown it, for code that reads pixels or exports later.
|
|
423
|
-
* @returns {WebGL2Renderer}
|
|
424
|
-
*/
|
|
425
|
-
export function webgl2(canvas, { scale = 1, preserveDrawingBuffer = false } = {}) {
|
|
426
|
-
const context = /** @type {WebGL2RenderingContext | null} */ (canvas.getContext('webgl2', {
|
|
427
|
-
alpha: true, premultipliedAlpha: true, antialias: false, depth: false, stencil: false, preserveDrawingBuffer,
|
|
428
|
-
}))
|
|
429
|
-
if (!context) throw new Error('webgl2: this canvas cannot give a WebGL2 context')
|
|
430
|
-
const gl = context
|
|
431
|
-
|
|
432
|
-
/** @type {Map<string, any>} */
|
|
433
|
-
const images = new Map()
|
|
434
|
-
/** @type {Map<string, Video>} */
|
|
435
|
-
const videos = new Map()
|
|
436
|
-
const assets = { images, videos }
|
|
437
|
-
const vectorCanvas = makeSurface(1, 1)
|
|
438
|
-
// On the CPU: Chrome's GPU Canvas 2D does not always rasterize the same path the same way, and frames must repeat.
|
|
439
|
-
const vector = canvas2d(vectorCanvas, { scale, assets, willReadFrequently: true })
|
|
440
|
-
const spriteCanvas = makeSurface(1, 1)
|
|
441
|
-
// Sprites are drawn rarely, so on the CPU, where the same base always gives the same pixels.
|
|
442
|
-
const spriteRender = canvas2d(spriteCanvas, { assets, willReadFrequently: true })
|
|
443
|
-
const probe = /** @type {OffscreenCanvasRenderingContext2D} */ (makeSurface(1, 1).getContext('2d', { willReadFrequently: true }))
|
|
444
|
-
|
|
445
|
-
// Half float layers where the GPU can draw into them; 8 bits per channel otherwise.
|
|
446
|
-
const format = gl.getExtension('EXT_color_buffer_float') ? gl.RGBA16F : gl.RGBA8
|
|
447
|
-
const maxTexture = /** @type {number} */ (gl.getParameter(gl.MAX_TEXTURE_SIZE))
|
|
448
|
-
const maxArrayLayers = /** @type {number} */ (gl.getParameter(gl.MAX_ARRAY_TEXTURE_LAYERS))
|
|
449
|
-
let width = 0
|
|
450
|
-
let height = 0
|
|
451
|
-
/** @type {[number, number]} */
|
|
452
|
-
let sceneSize = [canvas.width / scale, canvas.height / scale]
|
|
453
|
-
/** @type {Target | null} */
|
|
454
|
-
let upload = null
|
|
455
|
-
|
|
456
|
-
const smooth = /** @type {WebGLSampler} */ (gl.createSampler())
|
|
457
|
-
gl.samplerParameteri(smooth, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR)
|
|
458
|
-
gl.samplerParameteri(smooth, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
|
|
459
|
-
const sharp = /** @type {WebGLSampler} */ (gl.createSampler())
|
|
460
|
-
gl.samplerParameteri(sharp, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
|
|
461
|
-
gl.samplerParameteri(sharp, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
|
|
462
|
-
for (const s of [smooth, sharp]) {
|
|
463
|
-
gl.samplerParameteri(s, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
|
|
464
|
-
gl.samplerParameteri(s, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
const FIXED = {
|
|
468
|
-
normal: [gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA],
|
|
469
|
-
add: [gl.ONE, gl.ONE, gl.ONE, gl.ONE],
|
|
470
|
-
screen: [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA],
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
/** @param {string} vertex @param {string} fragment @param {string} what @returns {Program} */
|
|
474
|
-
function compile(vertex, fragment, what) {
|
|
475
|
-
const program = /** @type {WebGLProgram} */ (gl.createProgram())
|
|
476
|
-
const shaders = [[gl.VERTEX_SHADER, vertex], [gl.FRAGMENT_SHADER, fragment]].map(([type, source]) => {
|
|
477
|
-
const shader = /** @type {WebGLShader} */ (gl.createShader(/** @type {number} */ (type)))
|
|
478
|
-
gl.shaderSource(shader, /** @type {string} */ (source))
|
|
479
|
-
gl.compileShader(shader)
|
|
480
|
-
gl.attachShader(program, shader)
|
|
481
|
-
return shader
|
|
482
|
-
})
|
|
483
|
-
gl.linkProgram(program)
|
|
484
|
-
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
|
|
485
|
-
const log = shaders.map(s => gl.getShaderInfoLog(s)).filter(Boolean).join('\n') || gl.getProgramInfoLog(program)
|
|
486
|
-
throw new Error(`webgl2: ${what} did not compile: ${log}`)
|
|
487
|
-
}
|
|
488
|
-
for (const shader of shaders) gl.deleteShader(shader)
|
|
489
|
-
/** @type {Program['uniforms']} */
|
|
490
|
-
const uniforms = new Map()
|
|
491
|
-
const count = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS)
|
|
492
|
-
for (let i = 0; i < count; i++) {
|
|
493
|
-
const info = /** @type {WebGLActiveInfo} */ (gl.getActiveUniform(program, i))
|
|
494
|
-
const loc = gl.getUniformLocation(program, info.name)
|
|
495
|
-
if (loc) uniforms.set(info.name, { loc, type: info.type })
|
|
496
|
-
}
|
|
497
|
-
return { program, uniforms, defaults: uniformDefaults(fragment) }
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
/** @type {Map<string, Program>} */
|
|
501
|
-
const programs = new Map()
|
|
502
|
-
/** @param {keyof typeof PASSES | 'mesh' | 'instances'} name */
|
|
503
|
-
function shader(name) {
|
|
504
|
-
let p = programs.get(name)
|
|
505
|
-
if (!p) {
|
|
506
|
-
if (name === 'mesh') p = compile(MESH_VERTEX, MESH_FRAGMENT, 'the mesh shader')
|
|
507
|
-
else if (name === 'instances') p = compile(INSTANCE_VERTEX, INSTANCE_FRAGMENT, 'the instances shader')
|
|
508
|
-
else p = compile(fullVertex('uv'), PASSES[name], `the ${name} pass`)
|
|
509
|
-
programs.set(name, p)
|
|
510
|
-
}
|
|
511
|
-
return p
|
|
512
|
-
}
|
|
513
|
-
|
|
514
|
-
/** @type {Map<string, Program>} */
|
|
515
|
-
const transitions = new Map()
|
|
516
|
-
/** @param {DisplayItem & { type: 'transition' }} item */
|
|
517
|
-
function transitionProgram(item) {
|
|
518
|
-
const source = typeof item.effect === 'string' ? BUILT_IN[/** @type {keyof typeof BUILT_IN} */ (item.effect)] : item.effect.glsl
|
|
519
|
-
let p = transitions.get(source)
|
|
520
|
-
if (!p) {
|
|
521
|
-
p = compile(fullVertex('mlUv'), `${TRANSITION_HEAD}${source}\n${TRANSITION_MAIN}`, `transition "${item.id}"`)
|
|
522
|
-
transitions.set(source, p)
|
|
523
|
-
}
|
|
524
|
-
return p
|
|
525
|
-
}
|
|
526
|
-
|
|
527
|
-
/**
|
|
528
|
-
* Sets uniforms by their GLSL type; a Target binds to the next texture unit. Names the program lacks are skipped.
|
|
529
|
-
* @param {Program} p @param {Record<string, unknown>} values
|
|
530
|
-
*/
|
|
531
|
-
function use(p, values) {
|
|
532
|
-
gl.useProgram(p.program)
|
|
533
|
-
let unit = 0
|
|
534
|
-
for (const [name, value] of Object.entries(values)) {
|
|
535
|
-
const u = p.uniforms.get(name)
|
|
536
|
-
if (!u) continue
|
|
537
|
-
if (value !== null && typeof value === 'object' && 'tex' in value) {
|
|
538
|
-
gl.activeTexture(gl.TEXTURE0 + unit)
|
|
539
|
-
gl.bindTexture(gl.TEXTURE_2D, /** @type {Target} */ (value).tex)
|
|
540
|
-
gl.uniform1i(u.loc, unit++)
|
|
541
|
-
continue
|
|
542
|
-
}
|
|
543
|
-
const v = /** @type {any} */ (value)
|
|
544
|
-
switch (u.type) {
|
|
545
|
-
case gl.FLOAT: gl.uniform1f(u.loc, v); break
|
|
546
|
-
case gl.FLOAT_VEC2: gl.uniform2fv(u.loc, v); break
|
|
547
|
-
case gl.FLOAT_VEC3: gl.uniform3fv(u.loc, v); break
|
|
548
|
-
case gl.FLOAT_VEC4: gl.uniform4fv(u.loc, v); break
|
|
549
|
-
case gl.FLOAT_MAT3: gl.uniformMatrix3fv(u.loc, false, v); break
|
|
550
|
-
case gl.UNSIGNED_INT: gl.uniform1ui(u.loc, v); break
|
|
551
|
-
case gl.INT_VEC2: case gl.BOOL_VEC2: gl.uniform2iv(u.loc, v); break
|
|
552
|
-
case gl.INT_VEC3: case gl.BOOL_VEC3: gl.uniform3iv(u.loc, v); break
|
|
553
|
-
case gl.INT_VEC4: case gl.BOOL_VEC4: gl.uniform4iv(u.loc, v); break
|
|
554
|
-
default: gl.uniform1i(u.loc, Number(v))
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
// Targets are pooled per size and reused across frames.
|
|
560
|
-
|
|
561
|
-
/** @type {Map<string, Target[]>} */
|
|
562
|
-
const pool = new Map()
|
|
563
|
-
|
|
564
|
-
/** @param {number} w @param {number} h @returns {Target} */
|
|
565
|
-
function makeTarget(w, h) {
|
|
566
|
-
const tex = /** @type {WebGLTexture} */ (gl.createTexture())
|
|
567
|
-
gl.bindTexture(gl.TEXTURE_2D, tex)
|
|
568
|
-
gl.texStorage2D(gl.TEXTURE_2D, 1, format, w, h)
|
|
569
|
-
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
|
|
570
|
-
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
|
|
571
|
-
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
|
|
572
|
-
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
|
|
573
|
-
const fbo = gl.createFramebuffer()
|
|
574
|
-
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo)
|
|
575
|
-
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0)
|
|
576
|
-
return { tex, fbo, w, h }
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
function acquire(w = width, h = height) {
|
|
580
|
-
return pool.get(`${w}x${h}`)?.pop() ?? makeTarget(w, h)
|
|
581
|
-
}
|
|
582
|
-
|
|
583
|
-
/** @param {Target} t */
|
|
584
|
-
function release(t) {
|
|
585
|
-
const key = `${t.w}x${t.h}`
|
|
586
|
-
const list = pool.get(key)
|
|
587
|
-
if (list) list.push(t)
|
|
588
|
-
else pool.set(key, [t])
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
function cleared() {
|
|
592
|
-
const t = acquire()
|
|
593
|
-
gl.bindFramebuffer(gl.FRAMEBUFFER, t.fbo)
|
|
594
|
-
gl.viewport(0, 0, t.w, t.h)
|
|
595
|
-
gl.clearColor(0, 0, 0, 0)
|
|
596
|
-
gl.clear(gl.COLOR_BUFFER_BIT)
|
|
597
|
-
return t
|
|
598
|
-
}
|
|
599
|
-
|
|
600
|
-
/** Runs a full-frame pass into `out`. @param {Program} p @param {Target} out @param {Record<string, unknown>} values */
|
|
601
|
-
function pass(p, out, values) {
|
|
602
|
-
gl.bindFramebuffer(gl.FRAMEBUFFER, out.fbo)
|
|
603
|
-
gl.viewport(0, 0, out.w, out.h)
|
|
604
|
-
gl.disable(gl.BLEND)
|
|
605
|
-
use(p, values)
|
|
606
|
-
gl.drawArrays(gl.TRIANGLES, 0, 3)
|
|
607
|
-
}
|
|
608
|
-
|
|
609
|
-
/** Replaces a slot's target by a pass that reads it as `src`. @param {Slot} slot @param {Program} p @param {Record<string, unknown>} values */
|
|
610
|
-
function replace(slot, p, values) {
|
|
611
|
-
const out = acquire(slot.t.w, slot.t.h)
|
|
612
|
-
pass(p, out, { src: slot.t, ...values })
|
|
613
|
-
release(slot.t)
|
|
614
|
-
slot.t = out
|
|
615
|
-
}
|
|
616
|
-
|
|
617
|
-
/**
|
|
618
|
-
* Lays a texture over a slot with an opacity and a blend mode: by the GPU's blend unit where the mode allows it,
|
|
619
|
-
* else by a pass that reads both.
|
|
620
|
-
* @param {Slot} slot @param {Target} src @param {number} opacity @param {string | undefined} blend
|
|
621
|
-
*/
|
|
622
|
-
function composite(slot, src, opacity, blend) {
|
|
623
|
-
const fixed = FIXED[/** @type {keyof typeof FIXED} */ (blend ?? 'normal')]
|
|
624
|
-
if (!fixed) {
|
|
625
|
-
const out = acquire(slot.t.w, slot.t.h)
|
|
626
|
-
pass(shader('blend'), out, { src, dst: slot.t, opacity, mode: MODES.indexOf(blend ?? 'normal') })
|
|
627
|
-
release(slot.t)
|
|
628
|
-
slot.t = out
|
|
629
|
-
return
|
|
630
|
-
}
|
|
631
|
-
gl.bindFramebuffer(gl.FRAMEBUFFER, slot.t.fbo)
|
|
632
|
-
gl.viewport(0, 0, slot.t.w, slot.t.h)
|
|
633
|
-
gl.enable(gl.BLEND)
|
|
634
|
-
gl.blendFuncSeparate(fixed[0], fixed[1], fixed[2], fixed[3])
|
|
635
|
-
use(shader('copy'), { src, opacity })
|
|
636
|
-
gl.drawArrays(gl.TRIANGLES, 0, 3)
|
|
637
|
-
gl.disable(gl.BLEND)
|
|
638
|
-
}
|
|
639
|
-
|
|
640
|
-
/**
|
|
641
|
-
* Runs geometry that draws premultiplied colour over a slot, in a blend mode.
|
|
642
|
-
* @param {Slot} slot @param {string | undefined} blend @param {() => void} draw
|
|
643
|
-
*/
|
|
644
|
-
function drawBlended(slot, blend, draw) {
|
|
645
|
-
const fixed = FIXED[/** @type {keyof typeof FIXED} */ (blend ?? 'normal')]
|
|
646
|
-
const into = fixed ? slot.t : cleared()
|
|
647
|
-
const [s, d, sa, da] = fixed ?? FIXED.normal
|
|
648
|
-
gl.bindFramebuffer(gl.FRAMEBUFFER, into.fbo)
|
|
649
|
-
gl.viewport(0, 0, into.w, into.h)
|
|
650
|
-
gl.enable(gl.BLEND)
|
|
651
|
-
gl.blendFuncSeparate(s, d, sa, da)
|
|
652
|
-
draw()
|
|
653
|
-
gl.disable(gl.BLEND)
|
|
654
|
-
if (!fixed) {
|
|
655
|
-
composite(slot, into, 1, blend)
|
|
656
|
-
release(into)
|
|
657
|
-
}
|
|
658
|
-
}
|
|
659
|
-
|
|
660
|
-
/** The scene px to clip space transform for a display item's matrix. @param {Matrix} m */
|
|
661
|
-
function clipMatrix(m) {
|
|
662
|
-
const sx = (2 * scale) / width
|
|
663
|
-
const sy = (-2 * scale) / height
|
|
664
|
-
return new Float32Array([m[0] * sx, m[1] * sy, 0, m[2] * sx, m[3] * sy, 0, m[4] * sx - 1, m[5] * sy + 1, 1])
|
|
665
|
-
}
|
|
666
|
-
|
|
667
|
-
/** @param {DisplayItem[]} list @param {Slot} slot */
|
|
668
|
-
function drawList(list, slot) {
|
|
669
|
-
/** @type {DisplayItem[]} */
|
|
670
|
-
let run = []
|
|
671
|
-
const flush = () => {
|
|
672
|
-
if (run.length === 0) return
|
|
673
|
-
const blend = run[0].blend
|
|
674
|
-
// A shader blend writes the whole target, so only a blend the GPU does by itself can be limited to an area.
|
|
675
|
-
const area = FIXED[/** @type {keyof typeof FIXED} */ (blend ?? 'normal')] ? runArea(run) : null
|
|
676
|
-
vector(run)
|
|
677
|
-
run = []
|
|
678
|
-
const up = /** @type {Target} */ (upload)
|
|
679
|
-
gl.bindTexture(gl.TEXTURE_2D, up.tex)
|
|
680
|
-
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true)
|
|
681
|
-
if (!area) {
|
|
682
|
-
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, vectorCanvas)
|
|
683
|
-
composite(slot, up, 1, blend)
|
|
684
|
-
return
|
|
685
|
-
}
|
|
686
|
-
const [x, y, w, h] = area
|
|
687
|
-
if (w === 0 || h === 0) return
|
|
688
|
-
// GL rows run up from the bottom; with FLIP_Y the source is flipped first, so rows are skipped from its bottom.
|
|
689
|
-
const glY = height - y - h
|
|
690
|
-
gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, x)
|
|
691
|
-
gl.pixelStorei(gl.UNPACK_SKIP_ROWS, glY)
|
|
692
|
-
gl.texSubImage2D(gl.TEXTURE_2D, 0, x, glY, w, h, gl.RGBA, gl.UNSIGNED_BYTE, vectorCanvas)
|
|
693
|
-
gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, 0)
|
|
694
|
-
gl.pixelStorei(gl.UNPACK_SKIP_ROWS, 0)
|
|
695
|
-
// The rest of the upload texture still holds earlier runs, so the composite is held to this area.
|
|
696
|
-
gl.enable(gl.SCISSOR_TEST)
|
|
697
|
-
gl.scissor(x, glY, w, h)
|
|
698
|
-
composite(slot, up, 1, blend)
|
|
699
|
-
gl.disable(gl.SCISSOR_TEST)
|
|
700
|
-
}
|
|
701
|
-
for (const item of list) {
|
|
702
|
-
switch (item.type) {
|
|
703
|
-
case 'layer':
|
|
704
|
-
flush()
|
|
705
|
-
drawLayer(item, slot)
|
|
706
|
-
break
|
|
707
|
-
case 'transition':
|
|
708
|
-
flush()
|
|
709
|
-
drawTransition(item, slot)
|
|
710
|
-
break
|
|
711
|
-
case 'mesh':
|
|
712
|
-
flush()
|
|
713
|
-
drawMesh(item, slot)
|
|
714
|
-
break
|
|
715
|
-
case 'image':
|
|
716
|
-
case 'video':
|
|
717
|
-
flush()
|
|
718
|
-
drawPicture(item, slot)
|
|
719
|
-
break
|
|
720
|
-
case 'instances':
|
|
721
|
-
if (SPRITE_BASES.has(item.base.type)) {
|
|
722
|
-
flush()
|
|
723
|
-
drawInstances(item, slot)
|
|
724
|
-
break
|
|
725
|
-
}
|
|
726
|
-
// Falls through: copies of text are drawn by Canvas 2D.
|
|
727
|
-
default: {
|
|
728
|
-
const last = run[run.length - 1]
|
|
729
|
-
if (last && (last.blend !== item.blend || !CHAINED.has(item.blend))) flush()
|
|
730
|
-
run.push(item)
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
}
|
|
734
|
-
flush()
|
|
735
|
-
}
|
|
736
|
-
|
|
737
|
-
/**
|
|
738
|
-
* The canvas px a run of shapes and text can touch, as [x, y, w, h] from the top left, or null when that is not
|
|
739
|
-
* known and the whole frame goes up. Text gets room for any glyph and strokes for a miter join.
|
|
740
|
-
* @param {DisplayItem[]} items
|
|
741
|
-
* @returns {[number, number, number, number] | null}
|
|
742
|
-
*/
|
|
743
|
-
function runArea(items) {
|
|
744
|
-
let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity]
|
|
745
|
-
for (const item of items) {
|
|
746
|
-
if (item.type !== 'shape' && item.type !== 'text') return null
|
|
747
|
-
const box = item.type === 'shape' ? localBounds(item) : textBounds(item)
|
|
748
|
-
if (!box) return null
|
|
749
|
-
const m = item.matrix
|
|
750
|
-
for (const [x, y] of [[box[0], box[1]], [box[2], box[1]], [box[0], box[3]], [box[2], box[3]]]) {
|
|
751
|
-
const px = (m[0] * x + m[2] * y + m[4]) * scale
|
|
752
|
-
const py = (m[1] * x + m[3] * y + m[5]) * scale
|
|
753
|
-
x0 = Math.min(x0, px)
|
|
754
|
-
y0 = Math.min(y0, py)
|
|
755
|
-
x1 = Math.max(x1, px)
|
|
756
|
-
y1 = Math.max(y1, py)
|
|
757
|
-
}
|
|
758
|
-
}
|
|
759
|
-
// Two px of slack for antialiasing.
|
|
760
|
-
const left = Math.max(0, Math.floor(x0) - 2)
|
|
761
|
-
const top = Math.max(0, Math.floor(y0) - 2)
|
|
762
|
-
const right = Math.min(width, Math.ceil(x1) + 2)
|
|
763
|
-
const bottom = Math.min(height, Math.ceil(y1) + 2)
|
|
764
|
-
return right > left && bottom > top ? [left, top, right - left, bottom - top] : [0, 0, 0, 0]
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
/**
|
|
768
|
-
* A text item's box in its own space, laid out as canvas2d lays it out. Each unit moved by per-letter animation
|
|
769
|
-
* gets a circle that holds it at any rotation.
|
|
770
|
-
* @param {DisplayItem & { type: 'text' }} item
|
|
771
|
-
* @returns {[number, number, number, number]}
|
|
772
|
-
*/
|
|
773
|
-
function textBounds(item) {
|
|
774
|
-
probe.font = item.font ?? '10px sans-serif'
|
|
775
|
-
const size = fontSize(item.font)
|
|
776
|
-
const layout = layoutText(item, text => probe.measureText(text).width)
|
|
777
|
-
const [up, down] = GLYPH_REACH[/** @type {keyof typeof GLYPH_REACH} */ (item.baseline ?? 'alphabetic')] ?? GLYPH_REACH.alphabetic
|
|
778
|
-
const side = size / 2 + (item.stroke === undefined ? 0 : (item.strokeWidth ?? 1) * 5)
|
|
779
|
-
let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity]
|
|
780
|
-
/** @param {number} a @param {number} b @param {number} c @param {number} d */
|
|
781
|
-
const add = (a, b, c, d) => {
|
|
782
|
-
x0 = Math.min(x0, a)
|
|
783
|
-
y0 = Math.min(y0, b)
|
|
784
|
-
x1 = Math.max(x1, c)
|
|
785
|
-
y1 = Math.max(y1, d)
|
|
786
|
-
}
|
|
787
|
-
if (!item.units) {
|
|
788
|
-
for (const line of layout.lines) add(line.x - side, line.y + up * size - side, line.x + line.width + side, line.y + down * size + side)
|
|
789
|
-
} else {
|
|
790
|
-
layout.boxes.forEach((box, i) => {
|
|
791
|
-
if (!box) return
|
|
792
|
-
const style = item.offsets?.[i]
|
|
793
|
-
const cx = box.x + box.w / 2 + (style?.x ?? 0)
|
|
794
|
-
const cy = box.y + (style?.y ?? 0)
|
|
795
|
-
const r = Math.hypot(box.w / 2 + side, Math.max(-up, down) * size + side) * Math.abs(style?.scale ?? 1)
|
|
796
|
-
add(cx - r, cy - r, cx + r, cy + r)
|
|
797
|
-
})
|
|
798
|
-
}
|
|
799
|
-
return x0 === Infinity ? [0, 0, 0, 0] : [x0, y0, x1, y1]
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
/** @param {DisplayItem & { type: 'layer' }} layer @param {Slot} slot */
|
|
803
|
-
function drawLayer(layer, slot) {
|
|
804
|
-
const content = { t: cleared() }
|
|
805
|
-
if (layer.samples) {
|
|
806
|
-
// The mean of the samples, each added at 1 / n.
|
|
807
|
-
const n = layer.samples.length
|
|
808
|
-
for (const list of layer.samples) {
|
|
809
|
-
const sample = { t: cleared() }
|
|
810
|
-
drawList(list, sample)
|
|
811
|
-
gl.bindFramebuffer(gl.FRAMEBUFFER, content.t.fbo)
|
|
812
|
-
gl.viewport(0, 0, width, height)
|
|
813
|
-
gl.enable(gl.BLEND)
|
|
814
|
-
gl.blendFunc(gl.ONE, gl.ONE)
|
|
815
|
-
use(shader('copy'), { src: sample.t, opacity: 1 / n })
|
|
816
|
-
gl.drawArrays(gl.TRIANGLES, 0, 3)
|
|
817
|
-
gl.disable(gl.BLEND)
|
|
818
|
-
release(sample.t)
|
|
819
|
-
}
|
|
820
|
-
} else drawList(layer.items ?? [], content)
|
|
821
|
-
if (layer.matte) {
|
|
822
|
-
const mask = { t: cleared() }
|
|
823
|
-
drawList(layer.matte.items, mask)
|
|
824
|
-
replace(content, shader('matte'), { mask: mask.t, mode: MATTES.indexOf(layer.matte.mode) })
|
|
825
|
-
release(mask.t)
|
|
826
|
-
}
|
|
827
|
-
for (const effect of layer.effects ?? []) applyEffect(content, effect, layer.t ?? 0)
|
|
828
|
-
composite(slot, content.t, layer.opacity, layer.blend)
|
|
829
|
-
release(content.t)
|
|
830
|
-
}
|
|
831
|
-
|
|
832
|
-
/**
|
|
833
|
-
* A Gaussian blur of `sigma` canvas px into a new target. The image is halved until the blur is at most 3 px wide
|
|
834
|
-
* at that size, so a wide blur costs about as little as a narrow one.
|
|
835
|
-
* @param {Target} src @param {number} sigma
|
|
836
|
-
*/
|
|
837
|
-
function blurred(src, sigma) {
|
|
838
|
-
const out = acquire(src.w, src.h)
|
|
839
|
-
if (!(sigma > 0)) {
|
|
840
|
-
pass(shader('copy'), out, { src, opacity: 1 })
|
|
841
|
-
return out
|
|
842
|
-
}
|
|
843
|
-
/** @type {Target[]} */
|
|
844
|
-
const chain = []
|
|
845
|
-
let cur = src
|
|
846
|
-
// Each halving is a 2 by 2 box, which blurs a little by itself: 0.25 texel² at the size it reads.
|
|
847
|
-
let boxVariance = 0
|
|
848
|
-
while (sigma * (cur.w / src.w) > 3 && cur.w > 8 && cur.h > 8) {
|
|
849
|
-
const half = acquire(Math.ceil(cur.w / 2), Math.ceil(cur.h / 2))
|
|
850
|
-
pass(shader('copy'), half, { src: cur, opacity: 1 })
|
|
851
|
-
boxVariance += 0.25 * (src.w / cur.w) ** 2
|
|
852
|
-
chain.push(half)
|
|
853
|
-
cur = half
|
|
854
|
-
}
|
|
855
|
-
const rest = Math.sqrt(Math.max(0, sigma * sigma - boxVariance))
|
|
856
|
-
const across = acquire(cur.w, cur.h)
|
|
857
|
-
const sx = Math.max(rest * (cur.w / src.w), 1e-3)
|
|
858
|
-
const sy = Math.max(rest * (cur.h / src.h), 1e-3)
|
|
859
|
-
pass(shader('blur'), across, { src: cur, dir: [1 / cur.w, 0], sigma: sx, radius: Math.min(64, Math.ceil(sx * 3)) })
|
|
860
|
-
const down = chain.length > 0 ? cur : out
|
|
861
|
-
pass(shader('blur'), down, { src: across, dir: [0, 1 / cur.h], sigma: sy, radius: Math.min(64, Math.ceil(sy * 3)) })
|
|
862
|
-
release(across)
|
|
863
|
-
if (down !== out) pass(shader('copy'), out, { src: down, opacity: 1 })
|
|
864
|
-
for (const t of chain) release(t)
|
|
865
|
-
return out
|
|
866
|
-
}
|
|
867
|
-
|
|
868
|
-
/** @type {Map<string, number[]>} */
|
|
869
|
-
const colours = new Map()
|
|
870
|
-
/** A CSS colour as premultiplied RGBA from 0 to 1, read back from a pixel so any CSS colour works. @param {string} css */
|
|
871
|
-
function rgba(css) {
|
|
872
|
-
let c = colours.get(css)
|
|
873
|
-
if (c) return c
|
|
874
|
-
if (colours.size > 256) colours.clear()
|
|
875
|
-
probe.clearRect(0, 0, 1, 1)
|
|
876
|
-
probe.fillStyle = 'rgba(0, 0, 0, 0)'
|
|
877
|
-
probe.fillStyle = css
|
|
878
|
-
probe.fillRect(0, 0, 1, 1)
|
|
879
|
-
const [r, g, b, a] = probe.getImageData(0, 0, 1, 1).data
|
|
880
|
-
c = [(r / 255) * (a / 255), (g / 255) * (a / 255), (b / 255) * (a / 255), a / 255]
|
|
881
|
-
colours.set(css, c)
|
|
882
|
-
return c
|
|
883
|
-
}
|
|
884
|
-
|
|
885
|
-
/** @param {Slot} content @param {ResolvedEffect} effect @param {number} t */
|
|
886
|
-
function applyEffect(content, effect, t) {
|
|
887
|
-
const size = [width, height]
|
|
888
|
-
switch (effect.type) {
|
|
889
|
-
case 'blur': {
|
|
890
|
-
const b = blurred(content.t, effect.radius * scale)
|
|
891
|
-
release(content.t)
|
|
892
|
-
content.t = b
|
|
893
|
-
break
|
|
894
|
-
}
|
|
895
|
-
case 'glow':
|
|
896
|
-
case 'diffusion': {
|
|
897
|
-
let source = content.t
|
|
898
|
-
if (effect.type === 'glow') {
|
|
899
|
-
source = acquire()
|
|
900
|
-
pass(shader('bright'), source, { src: content.t, threshold: effect.threshold })
|
|
901
|
-
}
|
|
902
|
-
const glow = blurred(source, effect.radius * scale)
|
|
903
|
-
if (source !== content.t) release(source)
|
|
904
|
-
replace(content, shader('screen'), { glow, strength: effect.strength })
|
|
905
|
-
release(glow)
|
|
906
|
-
break
|
|
907
|
-
}
|
|
908
|
-
case 'grain':
|
|
909
|
-
replace(content, shader('grain'), {
|
|
910
|
-
amount: effect.amount,
|
|
911
|
-
size: Math.max(1, effect.size * scale),
|
|
912
|
-
key: Math.floor(rand('grain', effect.seed, Math.round(t * 1000)) * 4294967296) >>> 0,
|
|
913
|
-
})
|
|
914
|
-
break
|
|
915
|
-
case 'para':
|
|
916
|
-
replace(content, shader('para'), {
|
|
917
|
-
colorFrom: rgba(effect.from),
|
|
918
|
-
colorTo: rgba(effect.to),
|
|
919
|
-
size,
|
|
920
|
-
angle: (effect.angle * Math.PI) / 180,
|
|
921
|
-
opacity: effect.opacity,
|
|
922
|
-
mode: Math.max(0, MODES.indexOf(effect.blend)),
|
|
923
|
-
})
|
|
924
|
-
break
|
|
925
|
-
case 'vignette':
|
|
926
|
-
replace(content, shader('vignette'), { size, strength: effect.strength, radius: effect.radius })
|
|
927
|
-
break
|
|
928
|
-
}
|
|
929
|
-
}
|
|
930
|
-
|
|
931
|
-
/** @param {DisplayItem & { type: 'transition' }} item @param {Slot} slot */
|
|
932
|
-
function drawTransition(item, slot) {
|
|
933
|
-
const from = { t: cleared() }
|
|
934
|
-
const to = { t: cleared() }
|
|
935
|
-
drawList(item.from, from)
|
|
936
|
-
drawList(item.to, to)
|
|
937
|
-
const p = transitionProgram(item)
|
|
938
|
-
const [x, y, w, h] = item.box ?? [0, 0, sceneSize[0], sceneSize[1]]
|
|
939
|
-
const out = acquire()
|
|
940
|
-
pass(p, out, {
|
|
941
|
-
...p.defaults,
|
|
942
|
-
...item.params,
|
|
943
|
-
mlFrom: from.t,
|
|
944
|
-
mlTo: to.t,
|
|
945
|
-
mlBox: [(x * scale) / width, 1 - ((y + h) * scale) / height, (w * scale) / width, (h * scale) / height],
|
|
946
|
-
progress: item.progress,
|
|
947
|
-
ratio: w / h,
|
|
948
|
-
viewSize: [w, h],
|
|
949
|
-
})
|
|
950
|
-
release(from.t)
|
|
951
|
-
release(to.t)
|
|
952
|
-
composite(slot, out, item.opacity, item.blend)
|
|
953
|
-
release(out)
|
|
954
|
-
}
|
|
955
|
-
|
|
956
|
-
// Meshes and instances read their numbers through scratch arrays that only grow.
|
|
957
|
-
let scratch = new Float32Array(0)
|
|
958
|
-
/** @param {ArrayLike<number>} values */
|
|
959
|
-
function floats(values) {
|
|
960
|
-
if (values instanceof Float32Array) return values
|
|
961
|
-
if (scratch.length < values.length) scratch = new Float32Array(Math.max(values.length, scratch.length * 2))
|
|
962
|
-
const view = scratch.subarray(0, values.length)
|
|
963
|
-
view.set(values)
|
|
964
|
-
return view
|
|
965
|
-
}
|
|
966
|
-
|
|
967
|
-
const meshVao = gl.createVertexArray()
|
|
968
|
-
const pointBuffer = /** @type {WebGLBuffer} */ (gl.createBuffer())
|
|
969
|
-
const quadUvBuffer = /** @type {WebGLBuffer} */ (gl.createBuffer())
|
|
970
|
-
/** @type {WeakMap<object, WebGLBuffer>} */
|
|
971
|
-
const uvBuffers = new WeakMap()
|
|
972
|
-
/** @typedef {{ buffer: WebGLBuffer, count: number, type: number }} Index */
|
|
973
|
-
/** @type {WeakMap<object, Index>} */
|
|
974
|
-
const indexBuffers = new WeakMap()
|
|
975
|
-
/** @type {WebGLBuffer[]} */
|
|
976
|
-
const ownedBuffers = [pointBuffer, quadUvBuffer]
|
|
977
|
-
/** @type {Map<string, { tex: WebGLTexture, source: any }>} */
|
|
978
|
-
const textures = new Map()
|
|
979
|
-
|
|
980
|
-
/** @param {ArrayLike<number>} triangles @returns {Index} */
|
|
981
|
-
function indexFor(triangles) {
|
|
982
|
-
let index = indexBuffers.get(triangles)
|
|
983
|
-
if (!index) {
|
|
984
|
-
const big = Array.prototype.some.call(triangles, (/** @type {number} */ i) => i > 65535)
|
|
985
|
-
const buffer = /** @type {WebGLBuffer} */ (gl.createBuffer())
|
|
986
|
-
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer)
|
|
987
|
-
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, big ? Uint32Array.from(triangles) : Uint16Array.from(triangles), gl.STATIC_DRAW)
|
|
988
|
-
index = { buffer, count: triangles.length, type: big ? gl.UNSIGNED_INT : gl.UNSIGNED_SHORT }
|
|
989
|
-
indexBuffers.set(triangles, index)
|
|
990
|
-
ownedBuffers.push(buffer)
|
|
991
|
-
}
|
|
992
|
-
return index
|
|
993
|
-
}
|
|
994
|
-
const QUAD = [0, 1, 2, 2, 1, 3]
|
|
995
|
-
|
|
996
|
-
/**
|
|
997
|
-
* A texture of an image or a decoded video frame, with mipmaps for smooth shrinking. It is uploaded again only
|
|
998
|
-
* when the source under `key` changes, as a video's frame does.
|
|
999
|
-
* @param {string} key @param {any} source
|
|
1000
|
-
*/
|
|
1001
|
-
function textureOf(key, source) {
|
|
1002
|
-
const hit = textures.get(key)
|
|
1003
|
-
if (hit && hit.source === source) return { tex: hit.tex, w: source.width, h: source.height }
|
|
1004
|
-
const tex = hit?.tex ?? /** @type {WebGLTexture} */ (gl.createTexture())
|
|
1005
|
-
gl.bindTexture(gl.TEXTURE_2D, tex)
|
|
1006
|
-
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false)
|
|
1007
|
-
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, source)
|
|
1008
|
-
gl.generateMipmap(gl.TEXTURE_2D)
|
|
1009
|
-
textures.set(key, { tex, source })
|
|
1010
|
-
return { tex, w: source.width, h: source.height }
|
|
1011
|
-
}
|
|
1012
|
-
|
|
1013
|
-
/** @param {string} src */
|
|
1014
|
-
function imageTexture(src) {
|
|
1015
|
-
const image = images.get(src)
|
|
1016
|
-
if (!image) throw new Error(`webgl2: image "${src}" is not loaded; list it in the scene's assets.images`)
|
|
1017
|
-
return textureOf(`image:${src}`, image)
|
|
1018
|
-
}
|
|
1019
|
-
|
|
1020
|
-
/**
|
|
1021
|
-
* Textured triangles in an item's space: points as x, y pairs, uvs as the matching texture px.
|
|
1022
|
-
* @param {Slot} slot
|
|
1023
|
-
* @param {{ matrix: Matrix, opacity: number, blend?: string, smooth?: false }} item
|
|
1024
|
-
* @param {{ tex: WebGLTexture, w: number, h: number }} texture
|
|
1025
|
-
* @param {ArrayLike<number>} points @param {WebGLBuffer} uvs @param {Index} index
|
|
1026
|
-
*/
|
|
1027
|
-
function drawTriangles(slot, item, texture, points, uvs, index) {
|
|
1028
|
-
gl.bindVertexArray(meshVao)
|
|
1029
|
-
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index.buffer)
|
|
1030
|
-
gl.bindBuffer(gl.ARRAY_BUFFER, pointBuffer)
|
|
1031
|
-
gl.bufferData(gl.ARRAY_BUFFER, floats(points), gl.STREAM_DRAW)
|
|
1032
|
-
gl.enableVertexAttribArray(0)
|
|
1033
|
-
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0)
|
|
1034
|
-
gl.bindBuffer(gl.ARRAY_BUFFER, uvs)
|
|
1035
|
-
gl.enableVertexAttribArray(1)
|
|
1036
|
-
gl.vertexAttribPointer(1, 2, gl.FLOAT, false, 0, 0)
|
|
1037
|
-
gl.bindVertexArray(null)
|
|
1038
|
-
drawBlended(slot, item.blend, () => {
|
|
1039
|
-
gl.activeTexture(gl.TEXTURE0 + IMAGE_UNIT)
|
|
1040
|
-
gl.bindTexture(gl.TEXTURE_2D, texture.tex)
|
|
1041
|
-
gl.bindSampler(IMAGE_UNIT, item.smooth === false ? sharp : smooth)
|
|
1042
|
-
use(shader('mesh'), { matrix: clipMatrix(item.matrix), imageSize: [texture.w, texture.h], opacity: item.opacity, image: IMAGE_UNIT })
|
|
1043
|
-
gl.bindVertexArray(meshVao)
|
|
1044
|
-
gl.drawElements(gl.TRIANGLES, index.count, index.type, 0)
|
|
1045
|
-
gl.bindVertexArray(null)
|
|
1046
|
-
})
|
|
1047
|
-
}
|
|
1048
|
-
|
|
1049
|
-
/** @param {DisplayItem & { type: 'mesh' }} item @param {Slot} slot */
|
|
1050
|
-
function drawMesh(item, slot) {
|
|
1051
|
-
const texture = imageTexture(item.src)
|
|
1052
|
-
let uvs = uvBuffers.get(item.uvs)
|
|
1053
|
-
if (!uvs) {
|
|
1054
|
-
uvs = /** @type {WebGLBuffer} */ (gl.createBuffer())
|
|
1055
|
-
gl.bindBuffer(gl.ARRAY_BUFFER, uvs)
|
|
1056
|
-
gl.bufferData(gl.ARRAY_BUFFER, floats(item.uvs), gl.STATIC_DRAW)
|
|
1057
|
-
uvBuffers.set(item.uvs, uvs)
|
|
1058
|
-
ownedBuffers.push(uvs)
|
|
1059
|
-
}
|
|
1060
|
-
drawTriangles(slot, item, texture, item.points, uvs, indexFor(item.triangles))
|
|
1061
|
-
}
|
|
1062
|
-
|
|
1063
|
-
/**
|
|
1064
|
-
* An image or video frame as one quad, on the GPU rather than through Canvas 2D, whose image scaling can differ
|
|
1065
|
-
* from one draw to the next.
|
|
1066
|
-
* @param {DisplayItem & { type: 'image' | 'video' }} item @param {Slot} slot
|
|
1067
|
-
*/
|
|
1068
|
-
function drawPicture(item, slot) {
|
|
1069
|
-
const texture = item.type === 'image' ? imageTexture(item.src) : textureOf(`video:${item.src}`, videoFrame(videos, item, 'webgl2'))
|
|
1070
|
-
const [sx, sy, sw, sh] = item.crop ?? [0, 0, texture.w, texture.h]
|
|
1071
|
-
const w = item.w ?? sw
|
|
1072
|
-
const h = item.h ?? sh
|
|
1073
|
-
gl.bindBuffer(gl.ARRAY_BUFFER, quadUvBuffer)
|
|
1074
|
-
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([sx, sy, sx + sw, sy, sx, sy + sh, sx + sw, sy + sh]), gl.STREAM_DRAW)
|
|
1075
|
-
drawTriangles(slot, item, texture, [0, 0, w, 0, 0, h, w, h], quadUvBuffer, indexFor(QUAD))
|
|
1076
|
-
}
|
|
1077
|
-
|
|
1078
|
-
const instanceVao = gl.createVertexArray()
|
|
1079
|
-
const instanceBuffer = /** @type {WebGLBuffer} */ (gl.createBuffer())
|
|
1080
|
-
const quadCornerBuffer = /** @type {WebGLBuffer} */ (gl.createBuffer())
|
|
1081
|
-
ownedBuffers.push(instanceBuffer, quadCornerBuffer)
|
|
1082
|
-
gl.bindVertexArray(instanceVao)
|
|
1083
|
-
gl.bindBuffer(gl.ARRAY_BUFFER, quadCornerBuffer)
|
|
1084
|
-
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]), gl.STATIC_DRAW)
|
|
1085
|
-
gl.enableVertexAttribArray(0)
|
|
1086
|
-
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0)
|
|
1087
|
-
gl.bindBuffer(gl.ARRAY_BUFFER, instanceBuffer)
|
|
1088
|
-
gl.enableVertexAttribArray(1)
|
|
1089
|
-
gl.vertexAttribPointer(1, 4, gl.FLOAT, false, STRIDE * 4, 0)
|
|
1090
|
-
gl.vertexAttribDivisor(1, 1)
|
|
1091
|
-
gl.enableVertexAttribArray(2)
|
|
1092
|
-
gl.vertexAttribPointer(2, 3, gl.FLOAT, false, STRIDE * 4, 16)
|
|
1093
|
-
gl.vertexAttribDivisor(2, 1)
|
|
1094
|
-
gl.bindVertexArray(null)
|
|
1095
|
-
|
|
1096
|
-
/** @type {Map<string, Sprite>} */
|
|
1097
|
-
const sprites = new Map()
|
|
1098
|
-
|
|
1099
|
-
/**
|
|
1100
|
-
* The base's local bounds: a shape's path grown by its stroke, or an image's size.
|
|
1101
|
-
* @param {DisplayItem} base
|
|
1102
|
-
* @returns {[number, number, number, number] | null}
|
|
1103
|
-
*/
|
|
1104
|
-
function localBounds(base) {
|
|
1105
|
-
if (base.type === 'image') {
|
|
1106
|
-
const img = images.get(base.src)
|
|
1107
|
-
if (!img) throw new Error(`webgl2: image "${base.src}" is not loaded; list it in the scene's assets.images`)
|
|
1108
|
-
return [0, 0, base.w ?? base.crop?.[2] ?? img.width, base.h ?? base.crop?.[3] ?? img.height]
|
|
1109
|
-
}
|
|
1110
|
-
if (base.type !== 'shape' || (base.fill === undefined && base.stroke === undefined)) return null
|
|
1111
|
-
const box = pathBounds(base.path)
|
|
1112
|
-
if (!box || base.stroke === undefined) return box
|
|
1113
|
-
// A miter join can reach out half the miter limit (10) times the line width.
|
|
1114
|
-
const grow = ((base.strokeWidth ?? 1) / 2) * ((base.lineJoin ?? 'miter') === 'miter' ? 10 : 1)
|
|
1115
|
-
return [box[0] - grow, box[1] - grow, box[2] + grow, box[3] + grow]
|
|
1116
|
-
}
|
|
1117
|
-
|
|
1118
|
-
/**
|
|
1119
|
-
* The base drawn once per colour into the layers of a texture array, at the next power of two of `reach` canvas
|
|
1120
|
-
* px per unit, so a copy that grows does not redraw the sprite every frame.
|
|
1121
|
-
* @param {DisplayItem} base @param {string[]} colors @param {number} reach
|
|
1122
|
-
* @returns {Sprite | null}
|
|
1123
|
-
*/
|
|
1124
|
-
function spriteFor(base, colors, reach) {
|
|
1125
|
-
if (!(reach > 0)) return null
|
|
1126
|
-
const box = localBounds(base)
|
|
1127
|
-
if (!box) return null
|
|
1128
|
-
const w = Math.max(box[2] - box[0], 1e-6)
|
|
1129
|
-
const h = Math.max(box[3] - box[1], 1e-6)
|
|
1130
|
-
const k = Math.min(2 ** Math.ceil(Math.log2(reach)), (Math.min(maxTexture, 2048) - 2 * SPRITE_PAD) / Math.max(w, h))
|
|
1131
|
-
if (!(k > 0)) return null
|
|
1132
|
-
const layers = base.type === 'image' ? 1 : colors.length + 1
|
|
1133
|
-
if (layers > maxArrayLayers) {
|
|
1134
|
-
throw new RangeError(`webgl2: instances needs ${layers} colour layers, above this GPU's limit of ${maxArrayLayers}`)
|
|
1135
|
-
}
|
|
1136
|
-
const key = `${hash({ ...base, id: '', matrix: null, opacity: 1, blend: undefined })}:${layers > 1 ? colors.join('|') : ''}:${k}`
|
|
1137
|
-
const hit = sprites.get(key)
|
|
1138
|
-
if (hit) {
|
|
1139
|
-
sprites.delete(key)
|
|
1140
|
-
sprites.set(key, hit)
|
|
1141
|
-
return hit
|
|
1142
|
-
}
|
|
1143
|
-
const cw = Math.ceil(w * k) + 2 * SPRITE_PAD
|
|
1144
|
-
const ch = Math.ceil(h * k) + 2 * SPRITE_PAD
|
|
1145
|
-
spriteCanvas.width = cw
|
|
1146
|
-
spriteCanvas.height = ch
|
|
1147
|
-
const tex = /** @type {WebGLTexture} */ (gl.createTexture())
|
|
1148
|
-
gl.bindTexture(gl.TEXTURE_2D_ARRAY, tex)
|
|
1149
|
-
gl.texStorage3D(gl.TEXTURE_2D_ARRAY, Math.floor(Math.log2(Math.max(cw, ch))) + 1, gl.RGBA8, cw, ch, layers)
|
|
1150
|
-
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false)
|
|
1151
|
-
/** @type {Matrix} */
|
|
1152
|
-
const matrix = [k, 0, 0, k, SPRITE_PAD - box[0] * k, SPRITE_PAD - box[1] * k]
|
|
1153
|
-
for (let layer = 0; layer < layers; layer++) {
|
|
1154
|
-
const fill = layer === 0 ? {} : { fill: colors[layer - 1] }
|
|
1155
|
-
spriteRender([/** @type {DisplayItem} */ ({ ...base, ...fill, matrix, opacity: 1, blend: undefined })])
|
|
1156
|
-
gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, 0, 0, layer, cw, ch, 1, gl.RGBA, gl.UNSIGNED_BYTE, spriteCanvas)
|
|
1157
|
-
}
|
|
1158
|
-
gl.generateMipmap(gl.TEXTURE_2D_ARRAY)
|
|
1159
|
-
/** @type {Sprite} */
|
|
1160
|
-
const sprite = { tex, rect: [box[0] - SPRITE_PAD / k, box[1] - SPRITE_PAD / k, cw / k, ch / k] }
|
|
1161
|
-
sprites.set(key, sprite)
|
|
1162
|
-
if (sprites.size > SPRITE_CACHE) {
|
|
1163
|
-
const [oldest, old] = sprites.entries().next().value ?? []
|
|
1164
|
-
if (oldest !== undefined && old) {
|
|
1165
|
-
gl.deleteTexture(old.tex)
|
|
1166
|
-
sprites.delete(oldest)
|
|
1167
|
-
}
|
|
1168
|
-
}
|
|
1169
|
-
return sprite
|
|
1170
|
-
}
|
|
1171
|
-
|
|
1172
|
-
/** @param {DisplayItem & { type: 'instances' }} item @param {Slot} slot */
|
|
1173
|
-
function drawInstances(item, slot) {
|
|
1174
|
-
const { base, data, colors } = item
|
|
1175
|
-
const count = Math.floor(data.length / STRIDE)
|
|
1176
|
-
let most = 0
|
|
1177
|
-
for (let k = 0; k < count * STRIDE; k += STRIDE) {
|
|
1178
|
-
if (data[k + 5] > 0) most = Math.max(most, Math.abs(data[k + 3]), Math.abs(data[k + 4]))
|
|
1179
|
-
}
|
|
1180
|
-
if (most === 0 || base.type === 'layer' || base.type === 'transition') return
|
|
1181
|
-
const sprite = spriteFor(base, colors, scale * stretch(item.matrix) * most * stretch(base.matrix))
|
|
1182
|
-
if (!sprite) return
|
|
1183
|
-
const [rx, ry, rw, rh] = sprite.rect
|
|
1184
|
-
const b = base.matrix
|
|
1185
|
-
const baseMatrix = new Float32Array([b[0] * rw, b[1] * rw, 0, b[2] * rh, b[3] * rh, 0, b[0] * rx + b[2] * ry + b[4], b[1] * rx + b[3] * ry + b[5], 1])
|
|
1186
|
-
gl.bindBuffer(gl.ARRAY_BUFFER, instanceBuffer)
|
|
1187
|
-
gl.bufferData(gl.ARRAY_BUFFER, floats(data.subarray(0, count * STRIDE)), gl.STREAM_DRAW)
|
|
1188
|
-
drawBlended(slot, item.blend, () => {
|
|
1189
|
-
gl.activeTexture(gl.TEXTURE0 + IMAGE_UNIT)
|
|
1190
|
-
gl.bindTexture(gl.TEXTURE_2D_ARRAY, sprite.tex)
|
|
1191
|
-
gl.bindSampler(IMAGE_UNIT, base.type === 'image' && base.smooth === false ? sharp : smooth)
|
|
1192
|
-
use(shader('instances'), { item: clipMatrix(item.matrix), base: baseMatrix, opacity: item.opacity * base.opacity, sprites: IMAGE_UNIT })
|
|
1193
|
-
gl.bindVertexArray(instanceVao)
|
|
1194
|
-
gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, count)
|
|
1195
|
-
gl.bindVertexArray(null)
|
|
1196
|
-
})
|
|
1197
|
-
}
|
|
1198
|
-
|
|
1199
|
-
/** Matches the GPU targets and the Canvas 2D surface to the canvas, if it changed size. */
|
|
1200
|
-
function fit() {
|
|
1201
|
-
if (canvas.width === width && canvas.height === height && upload) return
|
|
1202
|
-
width = canvas.width
|
|
1203
|
-
height = canvas.height
|
|
1204
|
-
sceneSize = [width / scale, height / scale]
|
|
1205
|
-
for (const list of pool.values()) {
|
|
1206
|
-
for (const t of list) {
|
|
1207
|
-
gl.deleteTexture(t.tex)
|
|
1208
|
-
gl.deleteFramebuffer(t.fbo)
|
|
1209
|
-
}
|
|
1210
|
-
}
|
|
1211
|
-
pool.clear()
|
|
1212
|
-
if (upload) gl.deleteTexture(upload.tex)
|
|
1213
|
-
const tex = /** @type {WebGLTexture} */ (gl.createTexture())
|
|
1214
|
-
gl.bindTexture(gl.TEXTURE_2D, tex)
|
|
1215
|
-
gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA8, width, height)
|
|
1216
|
-
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
|
|
1217
|
-
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
|
|
1218
|
-
upload = { tex, fbo: null, w: width, h: height }
|
|
1219
|
-
vectorCanvas.width = width
|
|
1220
|
-
vectorCanvas.height = height
|
|
1221
|
-
}
|
|
1222
|
-
|
|
1223
|
-
/** @param {DisplayItem[]} list */
|
|
1224
|
-
function render(list) {
|
|
1225
|
-
fit()
|
|
1226
|
-
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true)
|
|
1227
|
-
const frame = { t: cleared() }
|
|
1228
|
-
drawList(list, frame)
|
|
1229
|
-
gl.bindFramebuffer(gl.FRAMEBUFFER, null)
|
|
1230
|
-
gl.viewport(0, 0, width, height)
|
|
1231
|
-
gl.disable(gl.BLEND)
|
|
1232
|
-
use(shader('copy'), { src: frame.t, opacity: 1 })
|
|
1233
|
-
gl.drawArrays(gl.TRIANGLES, 0, 3)
|
|
1234
|
-
release(frame.t)
|
|
1235
|
-
}
|
|
1236
|
-
|
|
1237
|
-
/** @param {Scene} scene */
|
|
1238
|
-
async function load(scene) {
|
|
1239
|
-
canvas.width = Math.round(scene.size[0] * scale)
|
|
1240
|
-
canvas.height = Math.round(scene.size[1] * scale)
|
|
1241
|
-
sceneSize = [scene.size[0], scene.size[1]]
|
|
1242
|
-
fit()
|
|
1243
|
-
await loadAssets(scene, images, videos)
|
|
1244
|
-
}
|
|
1245
|
-
|
|
1246
|
-
/** @param {{ loseContext?: boolean }} [options] */
|
|
1247
|
-
function dispose({ loseContext = false } = {}) {
|
|
1248
|
-
for (const list of pool.values()) {
|
|
1249
|
-
for (const t of list) {
|
|
1250
|
-
gl.deleteTexture(t.tex)
|
|
1251
|
-
gl.deleteFramebuffer(t.fbo)
|
|
1252
|
-
}
|
|
1253
|
-
}
|
|
1254
|
-
pool.clear()
|
|
1255
|
-
if (upload) {
|
|
1256
|
-
gl.deleteTexture(upload.tex)
|
|
1257
|
-
upload = null
|
|
1258
|
-
}
|
|
1259
|
-
for (const s of sprites.values()) gl.deleteTexture(s.tex)
|
|
1260
|
-
sprites.clear()
|
|
1261
|
-
for (const entry of textures.values()) gl.deleteTexture(entry.tex)
|
|
1262
|
-
textures.clear()
|
|
1263
|
-
for (const p of programs.values()) gl.deleteProgram(p.program)
|
|
1264
|
-
programs.clear()
|
|
1265
|
-
for (const p of transitions.values()) gl.deleteProgram(p.program)
|
|
1266
|
-
transitions.clear()
|
|
1267
|
-
for (const b of ownedBuffers) gl.deleteBuffer(b)
|
|
1268
|
-
ownedBuffers.length = 0
|
|
1269
|
-
gl.deleteVertexArray(meshVao)
|
|
1270
|
-
gl.deleteVertexArray(instanceVao)
|
|
1271
|
-
gl.deleteSampler(smooth)
|
|
1272
|
-
gl.deleteSampler(sharp)
|
|
1273
|
-
colours.clear()
|
|
1274
|
-
images.clear()
|
|
1275
|
-
videos.clear()
|
|
1276
|
-
vector.dispose()
|
|
1277
|
-
spriteRender.dispose()
|
|
1278
|
-
if (loseContext) gl.getExtension('WEBGL_lose_context')?.loseContext()
|
|
1279
|
-
}
|
|
1280
|
-
|
|
1281
|
-
return Object.defineProperties(/** @type {WebGL2Renderer} */ (/** @type {unknown} */ (render)), {
|
|
1282
|
-
load: { value: load },
|
|
1283
|
-
prepare: { value: (/** @type {DisplayItem[]} */ list) => prepareVideos(videos, list) },
|
|
1284
|
-
dispose: { value: dispose },
|
|
1285
|
-
canvas: { value: canvas },
|
|
1286
|
-
gl: { value: gl },
|
|
1287
|
-
})
|
|
1288
|
-
}
|
|
1289
|
-
|
|
1290
|
-
/** @param {WebGL2Renderer} render @param {DisplayItem[]} list */
|
|
1291
|
-
async function drawReady(render, list) {
|
|
1292
|
-
await render.prepare(list)
|
|
1293
|
-
render(list)
|
|
1294
|
-
}
|
|
1295
|
-
|
|
1296
|
-
/**
|
|
1297
|
-
* One frame as a PNG, drawn with WebGL2 on a canvas of its own.
|
|
1298
|
-
* @param {Scene} scene @param {number} t @param {{ scale?: number }} [options]
|
|
1299
|
-
* @returns {Promise<Blob>}
|
|
1300
|
-
*/
|
|
1301
|
-
export async function toPNG(scene, t, { scale = 1 } = {}) {
|
|
1302
|
-
const render = webgl2(makeSurface(1, 1), { scale, preserveDrawingBuffer: true })
|
|
1303
|
-
try {
|
|
1304
|
-
await render.load(scene)
|
|
1305
|
-
await drawReady(render, scene.evaluate(t))
|
|
1306
|
-
return await pngOf(render.canvas)
|
|
1307
|
-
} finally {
|
|
1308
|
-
render.dispose({ loseContext: true })
|
|
1309
|
-
}
|
|
1310
|
-
}
|
|
1311
|
-
|
|
1312
|
-
/**
|
|
1313
|
-
* Like verify, but compares the pixels WebGL2 draws: every frame in order, then in a shuffled order twice each.
|
|
1314
|
-
* @param {Scene} scene
|
|
1315
|
-
* @param {{ fps?: number, seed?: string | number, scale?: number }} [options]
|
|
1316
|
-
*/
|
|
1317
|
-
export async function verifyPixels(scene, { fps = 30, seed = 'verify', scale = 1 } = {}) {
|
|
1318
|
-
const render = webgl2(makeSurface(1, 1), { scale, preserveDrawingBuffer: true })
|
|
1319
|
-
try {
|
|
1320
|
-
await render.load(scene)
|
|
1321
|
-
const { gl, canvas } = render
|
|
1322
|
-
const pixels = new Uint8Array(canvas.width * canvas.height * 4)
|
|
1323
|
-
return await comparePixels(scene, async t => {
|
|
1324
|
-
await drawReady(render, scene.evaluate(t))
|
|
1325
|
-
gl.readPixels(0, 0, canvas.width, canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels)
|
|
1326
|
-
return pixelHash(pixels)
|
|
1327
|
-
}, { fps, seed })
|
|
1328
|
-
} finally {
|
|
1329
|
-
render.dispose({ loseContext: true })
|
|
1330
|
-
}
|
|
1331
|
-
}
|
|
1
|
+
// Draws display lists with WebGL2. Shapes and text are still rasterized by Canvas 2D on the CPU, in runs whose
|
|
2
|
+
// touched area is uploaded as a texture; the GPU does the rest: images and footage, layers in every blend mode,
|
|
3
|
+
// mattes, motion blur, effects, transitions, meshes and instanced copies.
|
|
4
|
+
import { canvas2d, loadAssets, prepareVideos, videoFrame } from './canvas2d.js'
|
|
5
|
+
import { makeSurface, pngOf, pixelHash, comparePixels } from './pixels.js'
|
|
6
|
+
import { fontSize, layoutText } from './text-layout.js'
|
|
7
|
+
import { STRIDE } from '../core/nodes.js'
|
|
8
|
+
import { hash } from '../core/hash.js'
|
|
9
|
+
import { rand } from '../core/rand.js'
|
|
10
|
+
|
|
11
|
+
/** @typedef {import('../core/scene.js').Scene} Scene */
|
|
12
|
+
/** @typedef {import('../core/scene.js').DisplayItem} DisplayItem */
|
|
13
|
+
/** @typedef {import('../core/scene.js').ResolvedEffect} ResolvedEffect */
|
|
14
|
+
/** @typedef {import('../core/scene.js').Matrix} Matrix */
|
|
15
|
+
/** @typedef {import('../core/path.js').Path} Path */
|
|
16
|
+
/** @typedef {import('../addons/media.js').Video} Video */
|
|
17
|
+
/** @typedef {HTMLCanvasElement | OffscreenCanvas} Surface */
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @typedef {((list: DisplayItem[]) => void) & {
|
|
21
|
+
* load: (scene: Scene) => Promise<void>,
|
|
22
|
+
* prepare: (list: DisplayItem[]) => Promise<void>,
|
|
23
|
+
* dispose: (options?: { loseContext?: boolean }) => void,
|
|
24
|
+
* readonly canvas: Surface,
|
|
25
|
+
* readonly gl: WebGL2RenderingContext
|
|
26
|
+
* }} WebGL2Renderer
|
|
27
|
+
* Drawing is synchronous, so a list with video items needs `await draw.prepare(list)` first to decode their frames.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/** A texture and the framebuffer that draws into it. @typedef {{ tex: WebGLTexture, fbo: WebGLFramebuffer | null, w: number, h: number }} Target */
|
|
31
|
+
/** Where a list draws. Passes that read the target replace it, so `t` changes as drawing goes on. @typedef {{ t: Target }} Slot */
|
|
32
|
+
/** @typedef {{ program: WebGLProgram, uniforms: Map<string, { loc: WebGLUniformLocation, type: number }>, defaults: Record<string, number | number[]> }} Program */
|
|
33
|
+
/** @typedef {{ tex: WebGLTexture, rect: [number, number, number, number] }} Sprite */
|
|
34
|
+
|
|
35
|
+
// In the order of the shader's blend switch; 'normal' is 0.
|
|
36
|
+
const MODES = [
|
|
37
|
+
'normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light',
|
|
38
|
+
'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity', 'add',
|
|
39
|
+
]
|
|
40
|
+
const MATTES = ['alpha', 'alpha-inverted', 'luma', 'luma-inverted']
|
|
41
|
+
// Blends where drawing a run of items together and compositing the run once equals compositing them one by one.
|
|
42
|
+
const CHAINED = new Set([undefined, 'add', 'screen'])
|
|
43
|
+
// How far glyphs reach above and below the baseline, in font sizes, by textBaseline; generous for accents and descenders.
|
|
44
|
+
const GLYPH_REACH = Object.freeze({
|
|
45
|
+
alphabetic: [-1.3, 0.6], top: [-0.5, 1.6], hanging: [-0.5, 1.6], middle: [-1.1, 1.1], bottom: [-1.6, 0.5], ideographic: [-1.6, 0.5],
|
|
46
|
+
})
|
|
47
|
+
// Bases whose copies are drawn from one cached sprite; text bases are drawn by Canvas 2D.
|
|
48
|
+
const SPRITE_BASES = new Set(['shape', 'image'])
|
|
49
|
+
const SPRITE_PAD = 2
|
|
50
|
+
const SPRITE_CACHE = 24
|
|
51
|
+
// Texture unit for images and sprites, which carry a sampler of their own; passes use units from 0.
|
|
52
|
+
const IMAGE_UNIT = 7
|
|
53
|
+
|
|
54
|
+
const fullVertex = (/** @type {string} */ name) => `#version 300 es
|
|
55
|
+
out vec2 ${name};
|
|
56
|
+
void main() {
|
|
57
|
+
vec2 p = vec2(gl_VertexID & 1, gl_VertexID >> 1) * 4.0 - 1.0;
|
|
58
|
+
${name} = p * 0.5 + 0.5;
|
|
59
|
+
gl_Position = vec4(p, 0.0, 1.0);
|
|
60
|
+
}`
|
|
61
|
+
|
|
62
|
+
const HEAD = `#version 300 es
|
|
63
|
+
precision highp float;
|
|
64
|
+
in vec2 uv;
|
|
65
|
+
out vec4 color;
|
|
66
|
+
`
|
|
67
|
+
|
|
68
|
+
// Premultiplied colours in and out, after the W3C compositing spec: the source over the backdrop, mixed by a mode.
|
|
69
|
+
const BLEND = `
|
|
70
|
+
float lum(vec3 c) { return dot(c, vec3(0.3, 0.59, 0.11)); }
|
|
71
|
+
vec3 clipColor(vec3 c) {
|
|
72
|
+
float l = lum(c);
|
|
73
|
+
float n = min(min(c.r, c.g), c.b);
|
|
74
|
+
float x = max(max(c.r, c.g), c.b);
|
|
75
|
+
if (n < 0.0 && l > n) c = l + (c - l) * l / (l - n);
|
|
76
|
+
if (x > 1.0 && x > l) c = l + (c - l) * (1.0 - l) / (x - l);
|
|
77
|
+
return c;
|
|
78
|
+
}
|
|
79
|
+
vec3 setLum(vec3 c, float l) { return clipColor(c + (l - lum(c))); }
|
|
80
|
+
float sat(vec3 c) { return max(max(c.r, c.g), c.b) - min(min(c.r, c.g), c.b); }
|
|
81
|
+
vec3 setSat(vec3 c, float s) {
|
|
82
|
+
float n = min(min(c.r, c.g), c.b);
|
|
83
|
+
float x = max(max(c.r, c.g), c.b);
|
|
84
|
+
return x > n ? (c - n) * s / (x - n) : vec3(0.0);
|
|
85
|
+
}
|
|
86
|
+
vec3 hardLight(vec3 b, vec3 s) { return mix(2.0 * b * s, 1.0 - 2.0 * (1.0 - b) * (1.0 - s), step(0.5, s)); }
|
|
87
|
+
float dodge(float b, float s) { return b <= 0.0 ? 0.0 : s >= 1.0 ? 1.0 : min(1.0, b / (1.0 - s)); }
|
|
88
|
+
float burn(float b, float s) { return b >= 1.0 ? 1.0 : s <= 0.0 ? 0.0 : 1.0 - min(1.0, (1.0 - b) / s); }
|
|
89
|
+
float softLight(float b, float s) {
|
|
90
|
+
float d = b <= 0.25 ? ((16.0 * b - 12.0) * b + 4.0) * b : sqrt(b);
|
|
91
|
+
return s <= 0.5 ? b - (1.0 - 2.0 * s) * b * (1.0 - b) : b + (2.0 * s - 1.0) * (d - b);
|
|
92
|
+
}
|
|
93
|
+
vec3 mixColor(vec3 b, vec3 s, int mode) {
|
|
94
|
+
switch (mode) {
|
|
95
|
+
case 1: return b * s;
|
|
96
|
+
case 2: return b + s - b * s;
|
|
97
|
+
case 3: return hardLight(s, b);
|
|
98
|
+
case 4: return min(b, s);
|
|
99
|
+
case 5: return max(b, s);
|
|
100
|
+
case 6: return vec3(dodge(b.r, s.r), dodge(b.g, s.g), dodge(b.b, s.b));
|
|
101
|
+
case 7: return vec3(burn(b.r, s.r), burn(b.g, s.g), burn(b.b, s.b));
|
|
102
|
+
case 8: return hardLight(b, s);
|
|
103
|
+
case 9: return vec3(softLight(b.r, s.r), softLight(b.g, s.g), softLight(b.b, s.b));
|
|
104
|
+
case 10: return abs(b - s);
|
|
105
|
+
case 11: return b + s - 2.0 * b * s;
|
|
106
|
+
case 12: return setLum(setSat(s, sat(b)), lum(b));
|
|
107
|
+
case 13: return setLum(setSat(b, sat(s)), lum(b));
|
|
108
|
+
case 14: return setLum(s, lum(b));
|
|
109
|
+
case 15: return setLum(b, lum(s));
|
|
110
|
+
default: return s;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
vec4 blend(vec4 s, vec4 d, int mode) {
|
|
114
|
+
s = clamp(s, 0.0, 1.0);
|
|
115
|
+
d = clamp(d, 0.0, 1.0);
|
|
116
|
+
if (mode == 16) return min(s + d, 1.0);
|
|
117
|
+
vec3 cs = s.a > 0.0 ? s.rgb / s.a : vec3(0.0);
|
|
118
|
+
vec3 cb = d.a > 0.0 ? d.rgb / d.a : vec3(0.0);
|
|
119
|
+
return vec4(s.rgb * (1.0 - d.a) + d.rgb * (1.0 - s.a) + s.a * d.a * mixColor(cb, cs, mode), s.a + d.a - s.a * d.a);
|
|
120
|
+
}
|
|
121
|
+
`
|
|
122
|
+
|
|
123
|
+
const HASH = `
|
|
124
|
+
uint mixBits(uint x) {
|
|
125
|
+
x ^= x >> 16;
|
|
126
|
+
x *= 0x7feb352du;
|
|
127
|
+
x ^= x >> 15;
|
|
128
|
+
x *= 0x846ca68bu;
|
|
129
|
+
x ^= x >> 16;
|
|
130
|
+
return x;
|
|
131
|
+
}
|
|
132
|
+
`
|
|
133
|
+
|
|
134
|
+
/** Fragment shaders of the full-frame passes, by name. */
|
|
135
|
+
const PASSES = {
|
|
136
|
+
copy: `${HEAD}
|
|
137
|
+
uniform sampler2D src;
|
|
138
|
+
uniform float opacity;
|
|
139
|
+
void main() { color = texture(src, uv) * opacity; }`,
|
|
140
|
+
|
|
141
|
+
blend: `${HEAD}${BLEND}
|
|
142
|
+
uniform sampler2D src, dst;
|
|
143
|
+
uniform float opacity;
|
|
144
|
+
uniform int mode;
|
|
145
|
+
void main() { color = blend(texture(src, uv) * opacity, texture(dst, uv), mode); }`,
|
|
146
|
+
|
|
147
|
+
matte: `${HEAD}
|
|
148
|
+
uniform sampler2D src, mask;
|
|
149
|
+
uniform int mode;
|
|
150
|
+
void main() {
|
|
151
|
+
vec4 m = texture(mask, uv);
|
|
152
|
+
float k = mode < 2 ? m.a : dot(clamp(m.rgb, 0.0, 1.0), vec3(0.2126, 0.7152, 0.0722));
|
|
153
|
+
color = texture(src, uv) * (mode == 1 || mode == 3 ? 1.0 - k : k);
|
|
154
|
+
}`,
|
|
155
|
+
|
|
156
|
+
// One axis of a Gaussian blur; what lies outside the frame counts as transparent, as in Canvas 2D.
|
|
157
|
+
blur: `${HEAD}
|
|
158
|
+
uniform sampler2D src;
|
|
159
|
+
uniform vec2 dir;
|
|
160
|
+
uniform float sigma;
|
|
161
|
+
uniform int radius;
|
|
162
|
+
vec4 tap(vec2 p) { return all(greaterThanEqual(p, vec2(0.0))) && all(lessThanEqual(p, vec2(1.0))) ? texture(src, p) : vec4(0.0); }
|
|
163
|
+
void main() {
|
|
164
|
+
vec4 sum = texture(src, uv);
|
|
165
|
+
float total = 1.0;
|
|
166
|
+
float k = -0.5 / (sigma * sigma);
|
|
167
|
+
for (int i = 1; i <= radius; i++) {
|
|
168
|
+
float w = exp(float(i * i) * k);
|
|
169
|
+
vec2 o = dir * float(i);
|
|
170
|
+
sum += w * (tap(uv + o) + tap(uv - o));
|
|
171
|
+
total += 2.0 * w;
|
|
172
|
+
}
|
|
173
|
+
color = sum / total;
|
|
174
|
+
}`,
|
|
175
|
+
|
|
176
|
+
// Keeps what is brighter than the threshold, scaled by how far above it the pixel is.
|
|
177
|
+
bright: `${HEAD}
|
|
178
|
+
uniform sampler2D src;
|
|
179
|
+
uniform float threshold;
|
|
180
|
+
void main() {
|
|
181
|
+
vec4 c = texture(src, uv);
|
|
182
|
+
float l = c.a > 0.0 ? dot(c.rgb / c.a, vec3(0.2126, 0.7152, 0.0722)) : 0.0;
|
|
183
|
+
color = c * clamp((l - threshold) / max(1.0 - threshold, 1e-4), 0.0, 1.0);
|
|
184
|
+
}`,
|
|
185
|
+
|
|
186
|
+
// Screens the glow on, once per whole unit of strength and once more with what is left.
|
|
187
|
+
screen: `${HEAD}
|
|
188
|
+
uniform sampler2D src, glow;
|
|
189
|
+
uniform float strength;
|
|
190
|
+
void main() {
|
|
191
|
+
vec4 c = clamp(texture(src, uv), 0.0, 1.0);
|
|
192
|
+
vec4 g = clamp(texture(glow, uv), 0.0, 1.0);
|
|
193
|
+
for (float left = min(strength, 8.0); left > 0.0; left -= 1.0) {
|
|
194
|
+
vec4 s = g * min(left, 1.0);
|
|
195
|
+
c = s + c - s * c;
|
|
196
|
+
}
|
|
197
|
+
color = c;
|
|
198
|
+
}`,
|
|
199
|
+
|
|
200
|
+
grain: `${HEAD}${HASH}
|
|
201
|
+
uniform sampler2D src;
|
|
202
|
+
uniform float amount, size;
|
|
203
|
+
uniform uint key;
|
|
204
|
+
void main() {
|
|
205
|
+
vec4 c = texture(src, uv);
|
|
206
|
+
uvec2 cell = uvec2(floor(gl_FragCoord.xy / size));
|
|
207
|
+
float n = float(mixBits(cell.x ^ mixBits(cell.y ^ key))) / 4294967295.0;
|
|
208
|
+
vec3 b = c.a > 0.0 ? clamp(c.rgb / c.a, 0.0, 1.0) : vec3(0.0);
|
|
209
|
+
vec3 o = mix(2.0 * b * n, 1.0 - 2.0 * (1.0 - b) * (1.0 - n), step(0.5, b));
|
|
210
|
+
color = vec4(mix(b, o, min(1.0, amount * 4.0)) * c.a, c.a);
|
|
211
|
+
}`,
|
|
212
|
+
|
|
213
|
+
// A gradient across the frame, inside the layer's own shape, blended on with a mode.
|
|
214
|
+
para: `${HEAD}${BLEND}
|
|
215
|
+
uniform sampler2D src;
|
|
216
|
+
uniform vec4 colorFrom, colorTo;
|
|
217
|
+
uniform vec2 size;
|
|
218
|
+
uniform float angle, opacity;
|
|
219
|
+
uniform int mode;
|
|
220
|
+
void main() {
|
|
221
|
+
vec4 c = texture(src, uv);
|
|
222
|
+
vec2 q = vec2(uv.x, 1.0 - uv.y) * size;
|
|
223
|
+
float s = clamp(dot(q - size * 0.5, vec2(cos(angle), sin(angle))) / length(size) + 0.5, 0.0, 1.0);
|
|
224
|
+
color = blend(mix(colorFrom, colorTo, s) * c.a * opacity, c, mode);
|
|
225
|
+
}`,
|
|
226
|
+
|
|
227
|
+
vignette: `${HEAD}
|
|
228
|
+
uniform sampler2D src;
|
|
229
|
+
uniform vec2 size;
|
|
230
|
+
uniform float strength, radius;
|
|
231
|
+
void main() {
|
|
232
|
+
vec4 c = texture(src, uv);
|
|
233
|
+
float r = length(size) * 0.5;
|
|
234
|
+
float k = strength * clamp((length((uv - 0.5) * size) - r * radius) / max(r - r * radius, 1e-4), 0.0, 1.0);
|
|
235
|
+
color = vec4(c.rgb * (1.0 - k), c.a);
|
|
236
|
+
}`,
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const MESH_VERTEX = `#version 300 es
|
|
240
|
+
layout(location = 0) in vec2 point;
|
|
241
|
+
layout(location = 1) in vec2 texel;
|
|
242
|
+
uniform mat3 matrix;
|
|
243
|
+
uniform vec2 imageSize;
|
|
244
|
+
out vec2 uv;
|
|
245
|
+
void main() {
|
|
246
|
+
uv = texel / imageSize;
|
|
247
|
+
gl_Position = vec4((matrix * vec3(point, 1.0)).xy, 0.0, 1.0);
|
|
248
|
+
}`
|
|
249
|
+
|
|
250
|
+
const MESH_FRAGMENT = `${HEAD}
|
|
251
|
+
uniform sampler2D image;
|
|
252
|
+
uniform float opacity;
|
|
253
|
+
void main() { color = texture(image, uv) * opacity; }`
|
|
254
|
+
|
|
255
|
+
// Each copy is its STRIDE numbers: x, y, rotation, scale x, scale y, opacity, colour index.
|
|
256
|
+
const INSTANCE_VERTEX = `#version 300 es
|
|
257
|
+
layout(location = 0) in vec2 corner;
|
|
258
|
+
layout(location = 1) in vec4 copyA;
|
|
259
|
+
layout(location = 2) in vec3 copyB;
|
|
260
|
+
uniform mat3 item;
|
|
261
|
+
uniform mat3 base;
|
|
262
|
+
uniform float opacity;
|
|
263
|
+
out vec2 uv;
|
|
264
|
+
out float alpha;
|
|
265
|
+
flat out float layer;
|
|
266
|
+
void main() {
|
|
267
|
+
vec2 p = (base * vec3(corner, 1.0)).xy;
|
|
268
|
+
float r = radians(copyA.z);
|
|
269
|
+
float c = cos(r);
|
|
270
|
+
float s = sin(r);
|
|
271
|
+
p = vec2(c * copyA.w * p.x - s * copyB.x * p.y, s * copyA.w * p.x + c * copyB.x * p.y) + copyA.xy;
|
|
272
|
+
gl_Position = copyB.y > 0.0 ? vec4((item * vec3(p, 1.0)).xy, 0.0, 1.0) : vec4(2.0, 2.0, 2.0, 1.0);
|
|
273
|
+
uv = corner;
|
|
274
|
+
alpha = opacity * copyB.y;
|
|
275
|
+
layer = copyB.z >= 0.0 ? copyB.z + 1.0 : 0.0;
|
|
276
|
+
}`
|
|
277
|
+
|
|
278
|
+
const INSTANCE_FRAGMENT = `#version 300 es
|
|
279
|
+
precision highp float;
|
|
280
|
+
precision highp sampler2DArray;
|
|
281
|
+
uniform sampler2DArray sprites;
|
|
282
|
+
in vec2 uv;
|
|
283
|
+
in float alpha;
|
|
284
|
+
flat in float layer;
|
|
285
|
+
out vec4 color;
|
|
286
|
+
void main() { color = texture(sprites, vec3(uv, layer)) * alpha; }`
|
|
287
|
+
|
|
288
|
+
// The gl-transitions interface: transition(uv) mixes getFromColor and getToColor by progress, ratio is width over
|
|
289
|
+
// height, and uv spans the box (or the frame). viewSize, the area in scene px, is extra; `// = 90.0` after a uniform
|
|
290
|
+
// sets its default.
|
|
291
|
+
const TRANSITION_HEAD = `#version 300 es
|
|
292
|
+
precision highp float;
|
|
293
|
+
in vec2 mlUv;
|
|
294
|
+
out vec4 mlColor;
|
|
295
|
+
uniform sampler2D mlFrom, mlTo;
|
|
296
|
+
uniform vec4 mlBox;
|
|
297
|
+
uniform float progress, ratio;
|
|
298
|
+
uniform vec2 viewSize;
|
|
299
|
+
bool mlInside(vec2 p) { return all(greaterThanEqual(p, vec2(0.0))) && all(lessThanEqual(p, vec2(1.0))); }
|
|
300
|
+
vec4 getFromColor(vec2 p) { return mlInside(p) ? texture(mlFrom, mlBox.xy + p * mlBox.zw) : vec4(0.0); }
|
|
301
|
+
vec4 getToColor(vec2 p) { return mlInside(p) ? texture(mlTo, mlBox.xy + p * mlBox.zw) : vec4(0.0); }
|
|
302
|
+
`
|
|
303
|
+
const TRANSITION_MAIN = `
|
|
304
|
+
void main() {
|
|
305
|
+
vec2 p = (mlUv - mlBox.xy) / mlBox.zw;
|
|
306
|
+
mlColor = mlInside(p) ? transition(p) : vec4(0.0);
|
|
307
|
+
}`
|
|
308
|
+
|
|
309
|
+
/** The built-in transitions, matching the Canvas 2D and SVG renderers. */
|
|
310
|
+
const BUILT_IN = {
|
|
311
|
+
fade: `vec4 transition(vec2 uv) { return mix(getFromColor(uv), getToColor(uv), progress); }`,
|
|
312
|
+
|
|
313
|
+
wipe: `uniform float angle; // = 0.0
|
|
314
|
+
uniform float softness; // = 0.1
|
|
315
|
+
vec4 transition(vec2 uv) {
|
|
316
|
+
vec2 dir = vec2(cos(radians(angle)), sin(radians(angle)));
|
|
317
|
+
vec2 p = (vec2(uv.x, 1.0 - uv.y) - 0.5) * viewSize;
|
|
318
|
+
float s = dot(p, dir) / dot(abs(dir), viewSize) + 0.5;
|
|
319
|
+
float edge = progress * (1.0 + softness);
|
|
320
|
+
float m = softness > 0.0 ? clamp((edge - s) / softness, 0.0, 1.0) : step(s, edge);
|
|
321
|
+
vec4 t = getToColor(uv) * m;
|
|
322
|
+
return t + getFromColor(uv) * (1.0 - t.a);
|
|
323
|
+
}`,
|
|
324
|
+
|
|
325
|
+
slide: `uniform float angle; // = 0.0
|
|
326
|
+
vec4 transition(vec2 uv) {
|
|
327
|
+
vec2 d = vec2(cos(radians(angle)), -sin(radians(angle)));
|
|
328
|
+
vec4 t = getToColor(uv - d * (1.0 - progress));
|
|
329
|
+
return t + getFromColor(uv + d * progress) * (1.0 - t.a);
|
|
330
|
+
}`,
|
|
331
|
+
|
|
332
|
+
circle: `uniform float x; // = 0.5
|
|
333
|
+
uniform float y; // = 0.5
|
|
334
|
+
uniform float softness; // = 0.05
|
|
335
|
+
vec4 transition(vec2 uv) {
|
|
336
|
+
vec2 c = vec2(x, y) * viewSize;
|
|
337
|
+
vec2 p = vec2(uv.x, 1.0 - uv.y) * viewSize;
|
|
338
|
+
float soft = softness * length(viewSize);
|
|
339
|
+
float r = progress * (length(max(c, viewSize - c)) + soft);
|
|
340
|
+
float inner = max(0.0, r - soft);
|
|
341
|
+
float outer = max(r, 1e-3);
|
|
342
|
+
vec4 t = getToColor(uv) * clamp((outer - distance(p, c)) / max(outer - inner, 1e-3), 0.0, 1.0);
|
|
343
|
+
return t + getFromColor(uv) * (1.0 - t.a);
|
|
344
|
+
}`,
|
|
345
|
+
|
|
346
|
+
zoom: `uniform float strength; // = 0.25
|
|
347
|
+
vec4 transition(vec2 uv) {
|
|
348
|
+
vec2 from = 0.5 + (uv - 0.5) / (1.0 + strength * progress);
|
|
349
|
+
vec2 to = 0.5 + (uv - 0.5) / (1.0 + strength * (1.0 - progress));
|
|
350
|
+
return getFromColor(from) * (1.0 - progress) + getToColor(to) * progress;
|
|
351
|
+
}`,
|
|
352
|
+
|
|
353
|
+
dissolve: `uniform float size; // = 4.0
|
|
354
|
+
${HASH}
|
|
355
|
+
vec4 transition(vec2 uv) {
|
|
356
|
+
uvec2 cell = uvec2(floor(vec2(uv.x, 1.0 - uv.y) * viewSize / max(size, 1e-3)));
|
|
357
|
+
float n = float(mixBits(cell.x ^ mixBits(cell.y + 0x9e3779b9u))) / 4294967296.0;
|
|
358
|
+
vec4 t = n < progress ? getToColor(uv) : vec4(0.0);
|
|
359
|
+
return t + getFromColor(uv) * (1.0 - t.a);
|
|
360
|
+
}`,
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const DEFAULT_UNIFORM = /uniform\s+(\w+)\s+(\w+)\s*;\s*\/\/\s*=\s*([^\n]+)/g
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Defaults written as `// = value` after uniform declarations.
|
|
367
|
+
* @param {string} source
|
|
368
|
+
* @returns {Record<string, number | number[]>}
|
|
369
|
+
*/
|
|
370
|
+
function uniformDefaults(source) {
|
|
371
|
+
/** @type {Record<string, number | number[]>} */
|
|
372
|
+
const out = {}
|
|
373
|
+
for (const [, type, name, text] of source.matchAll(DEFAULT_UNIFORM)) {
|
|
374
|
+
const numbers = (text.match(/-?\d*\.?\d+(?:e[-+]?\d+)?|true|false/gi) ?? []).map(v => (v === 'true' ? 1 : v === 'false' ? 0 : Number(v)))
|
|
375
|
+
const size = Number(/(\d)$/.exec(type)?.[1] ?? 1)
|
|
376
|
+
if (numbers.length === 0) continue
|
|
377
|
+
out[name] = size === 1 ? numbers[0] : numbers.length === 1 ? Array(size).fill(numbers[0]) : numbers.slice(0, size)
|
|
378
|
+
}
|
|
379
|
+
return out
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* The bounds of a path's points and control points, which hold the whole curve.
|
|
384
|
+
* @param {Path} path
|
|
385
|
+
* @returns {[number, number, number, number] | null}
|
|
386
|
+
*/
|
|
387
|
+
function pathBounds(path) {
|
|
388
|
+
let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity]
|
|
389
|
+
const add = (/** @type {number} */ x, /** @type {number} */ y) => {
|
|
390
|
+
x0 = Math.min(x0, x)
|
|
391
|
+
y0 = Math.min(y0, y)
|
|
392
|
+
x1 = Math.max(x1, x)
|
|
393
|
+
y1 = Math.max(y1, y)
|
|
394
|
+
}
|
|
395
|
+
const round = (/** @type {number} */ x, /** @type {number} */ y, /** @type {number} */ r) => {
|
|
396
|
+
add(x - r, y - r)
|
|
397
|
+
add(x + r, y + r)
|
|
398
|
+
}
|
|
399
|
+
path.replay({
|
|
400
|
+
moveTo: add,
|
|
401
|
+
lineTo: add,
|
|
402
|
+
bezierCurveTo: (ax, ay, bx, by, x, y) => (add(ax, ay), add(bx, by), add(x, y)),
|
|
403
|
+
quadraticCurveTo: (ax, ay, x, y) => (add(ax, ay), add(x, y)),
|
|
404
|
+
arc: (x, y, r) => round(x, y, r),
|
|
405
|
+
arcTo: (ax, ay, bx, by) => (add(ax, ay), add(bx, by)),
|
|
406
|
+
ellipse: (x, y, rx, ry) => round(x, y, Math.max(rx, ry)),
|
|
407
|
+
rect: (x, y, w, h) => (add(x, y), add(x + w, y + h)),
|
|
408
|
+
roundRect: (x, y, w, h) => (add(x, y), add(x + w, y + h)),
|
|
409
|
+
closePath: () => {},
|
|
410
|
+
})
|
|
411
|
+
return x0 <= x1 ? [x0, y0, x1, y1] : null
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** How much a matrix stretches its longest axis. @param {Matrix} m */
|
|
415
|
+
const stretch = m => Math.max(Math.hypot(m[0], m[1]), Math.hypot(m[2], m[3]))
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Draws display lists with WebGL2, with the same contract as canvas2d: `await draw.load(scene)` once, then
|
|
419
|
+
* `draw(scene.evaluate(t))` per frame. It also runs GLSL transitions, which the other renderers cannot.
|
|
420
|
+
* @param {Surface} canvas
|
|
421
|
+
* @param {{ scale?: number, preserveDrawingBuffer?: boolean }} [options] preserveDrawingBuffer keeps the last frame
|
|
422
|
+
* readable after the browser has shown it, for code that reads pixels or exports later.
|
|
423
|
+
* @returns {WebGL2Renderer}
|
|
424
|
+
*/
|
|
425
|
+
export function webgl2(canvas, { scale = 1, preserveDrawingBuffer = false } = {}) {
|
|
426
|
+
const context = /** @type {WebGL2RenderingContext | null} */ (canvas.getContext('webgl2', {
|
|
427
|
+
alpha: true, premultipliedAlpha: true, antialias: false, depth: false, stencil: false, preserveDrawingBuffer,
|
|
428
|
+
}))
|
|
429
|
+
if (!context) throw new Error('webgl2: this canvas cannot give a WebGL2 context')
|
|
430
|
+
const gl = context
|
|
431
|
+
|
|
432
|
+
/** @type {Map<string, any>} */
|
|
433
|
+
const images = new Map()
|
|
434
|
+
/** @type {Map<string, Video>} */
|
|
435
|
+
const videos = new Map()
|
|
436
|
+
const assets = { images, videos }
|
|
437
|
+
const vectorCanvas = makeSurface(1, 1)
|
|
438
|
+
// On the CPU: Chrome's GPU Canvas 2D does not always rasterize the same path the same way, and frames must repeat.
|
|
439
|
+
const vector = canvas2d(vectorCanvas, { scale, assets, willReadFrequently: true })
|
|
440
|
+
const spriteCanvas = makeSurface(1, 1)
|
|
441
|
+
// Sprites are drawn rarely, so on the CPU, where the same base always gives the same pixels.
|
|
442
|
+
const spriteRender = canvas2d(spriteCanvas, { assets, willReadFrequently: true })
|
|
443
|
+
const probe = /** @type {OffscreenCanvasRenderingContext2D} */ (makeSurface(1, 1).getContext('2d', { willReadFrequently: true }))
|
|
444
|
+
|
|
445
|
+
// Half float layers where the GPU can draw into them; 8 bits per channel otherwise.
|
|
446
|
+
const format = gl.getExtension('EXT_color_buffer_float') ? gl.RGBA16F : gl.RGBA8
|
|
447
|
+
const maxTexture = /** @type {number} */ (gl.getParameter(gl.MAX_TEXTURE_SIZE))
|
|
448
|
+
const maxArrayLayers = /** @type {number} */ (gl.getParameter(gl.MAX_ARRAY_TEXTURE_LAYERS))
|
|
449
|
+
let width = 0
|
|
450
|
+
let height = 0
|
|
451
|
+
/** @type {[number, number]} */
|
|
452
|
+
let sceneSize = [canvas.width / scale, canvas.height / scale]
|
|
453
|
+
/** @type {Target | null} */
|
|
454
|
+
let upload = null
|
|
455
|
+
|
|
456
|
+
const smooth = /** @type {WebGLSampler} */ (gl.createSampler())
|
|
457
|
+
gl.samplerParameteri(smooth, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR)
|
|
458
|
+
gl.samplerParameteri(smooth, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
|
|
459
|
+
const sharp = /** @type {WebGLSampler} */ (gl.createSampler())
|
|
460
|
+
gl.samplerParameteri(sharp, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
|
|
461
|
+
gl.samplerParameteri(sharp, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
|
|
462
|
+
for (const s of [smooth, sharp]) {
|
|
463
|
+
gl.samplerParameteri(s, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
|
|
464
|
+
gl.samplerParameteri(s, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const FIXED = {
|
|
468
|
+
normal: [gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA],
|
|
469
|
+
add: [gl.ONE, gl.ONE, gl.ONE, gl.ONE],
|
|
470
|
+
screen: [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA],
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** @param {string} vertex @param {string} fragment @param {string} what @returns {Program} */
|
|
474
|
+
function compile(vertex, fragment, what) {
|
|
475
|
+
const program = /** @type {WebGLProgram} */ (gl.createProgram())
|
|
476
|
+
const shaders = [[gl.VERTEX_SHADER, vertex], [gl.FRAGMENT_SHADER, fragment]].map(([type, source]) => {
|
|
477
|
+
const shader = /** @type {WebGLShader} */ (gl.createShader(/** @type {number} */ (type)))
|
|
478
|
+
gl.shaderSource(shader, /** @type {string} */ (source))
|
|
479
|
+
gl.compileShader(shader)
|
|
480
|
+
gl.attachShader(program, shader)
|
|
481
|
+
return shader
|
|
482
|
+
})
|
|
483
|
+
gl.linkProgram(program)
|
|
484
|
+
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
|
|
485
|
+
const log = shaders.map(s => gl.getShaderInfoLog(s)).filter(Boolean).join('\n') || gl.getProgramInfoLog(program)
|
|
486
|
+
throw new Error(`webgl2: ${what} did not compile: ${log}`)
|
|
487
|
+
}
|
|
488
|
+
for (const shader of shaders) gl.deleteShader(shader)
|
|
489
|
+
/** @type {Program['uniforms']} */
|
|
490
|
+
const uniforms = new Map()
|
|
491
|
+
const count = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS)
|
|
492
|
+
for (let i = 0; i < count; i++) {
|
|
493
|
+
const info = /** @type {WebGLActiveInfo} */ (gl.getActiveUniform(program, i))
|
|
494
|
+
const loc = gl.getUniformLocation(program, info.name)
|
|
495
|
+
if (loc) uniforms.set(info.name, { loc, type: info.type })
|
|
496
|
+
}
|
|
497
|
+
return { program, uniforms, defaults: uniformDefaults(fragment) }
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** @type {Map<string, Program>} */
|
|
501
|
+
const programs = new Map()
|
|
502
|
+
/** @param {keyof typeof PASSES | 'mesh' | 'instances'} name */
|
|
503
|
+
function shader(name) {
|
|
504
|
+
let p = programs.get(name)
|
|
505
|
+
if (!p) {
|
|
506
|
+
if (name === 'mesh') p = compile(MESH_VERTEX, MESH_FRAGMENT, 'the mesh shader')
|
|
507
|
+
else if (name === 'instances') p = compile(INSTANCE_VERTEX, INSTANCE_FRAGMENT, 'the instances shader')
|
|
508
|
+
else p = compile(fullVertex('uv'), PASSES[name], `the ${name} pass`)
|
|
509
|
+
programs.set(name, p)
|
|
510
|
+
}
|
|
511
|
+
return p
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/** @type {Map<string, Program>} */
|
|
515
|
+
const transitions = new Map()
|
|
516
|
+
/** @param {DisplayItem & { type: 'transition' }} item */
|
|
517
|
+
function transitionProgram(item) {
|
|
518
|
+
const source = typeof item.effect === 'string' ? BUILT_IN[/** @type {keyof typeof BUILT_IN} */ (item.effect)] : item.effect.glsl
|
|
519
|
+
let p = transitions.get(source)
|
|
520
|
+
if (!p) {
|
|
521
|
+
p = compile(fullVertex('mlUv'), `${TRANSITION_HEAD}${source}\n${TRANSITION_MAIN}`, `transition "${item.id}"`)
|
|
522
|
+
transitions.set(source, p)
|
|
523
|
+
}
|
|
524
|
+
return p
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* Sets uniforms by their GLSL type; a Target binds to the next texture unit. Names the program lacks are skipped.
|
|
529
|
+
* @param {Program} p @param {Record<string, unknown>} values
|
|
530
|
+
*/
|
|
531
|
+
function use(p, values) {
|
|
532
|
+
gl.useProgram(p.program)
|
|
533
|
+
let unit = 0
|
|
534
|
+
for (const [name, value] of Object.entries(values)) {
|
|
535
|
+
const u = p.uniforms.get(name)
|
|
536
|
+
if (!u) continue
|
|
537
|
+
if (value !== null && typeof value === 'object' && 'tex' in value) {
|
|
538
|
+
gl.activeTexture(gl.TEXTURE0 + unit)
|
|
539
|
+
gl.bindTexture(gl.TEXTURE_2D, /** @type {Target} */ (value).tex)
|
|
540
|
+
gl.uniform1i(u.loc, unit++)
|
|
541
|
+
continue
|
|
542
|
+
}
|
|
543
|
+
const v = /** @type {any} */ (value)
|
|
544
|
+
switch (u.type) {
|
|
545
|
+
case gl.FLOAT: gl.uniform1f(u.loc, v); break
|
|
546
|
+
case gl.FLOAT_VEC2: gl.uniform2fv(u.loc, v); break
|
|
547
|
+
case gl.FLOAT_VEC3: gl.uniform3fv(u.loc, v); break
|
|
548
|
+
case gl.FLOAT_VEC4: gl.uniform4fv(u.loc, v); break
|
|
549
|
+
case gl.FLOAT_MAT3: gl.uniformMatrix3fv(u.loc, false, v); break
|
|
550
|
+
case gl.UNSIGNED_INT: gl.uniform1ui(u.loc, v); break
|
|
551
|
+
case gl.INT_VEC2: case gl.BOOL_VEC2: gl.uniform2iv(u.loc, v); break
|
|
552
|
+
case gl.INT_VEC3: case gl.BOOL_VEC3: gl.uniform3iv(u.loc, v); break
|
|
553
|
+
case gl.INT_VEC4: case gl.BOOL_VEC4: gl.uniform4iv(u.loc, v); break
|
|
554
|
+
default: gl.uniform1i(u.loc, Number(v))
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// Targets are pooled per size and reused across frames.
|
|
560
|
+
|
|
561
|
+
/** @type {Map<string, Target[]>} */
|
|
562
|
+
const pool = new Map()
|
|
563
|
+
|
|
564
|
+
/** @param {number} w @param {number} h @returns {Target} */
|
|
565
|
+
function makeTarget(w, h) {
|
|
566
|
+
const tex = /** @type {WebGLTexture} */ (gl.createTexture())
|
|
567
|
+
gl.bindTexture(gl.TEXTURE_2D, tex)
|
|
568
|
+
gl.texStorage2D(gl.TEXTURE_2D, 1, format, w, h)
|
|
569
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
|
|
570
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
|
|
571
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
|
|
572
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
|
|
573
|
+
const fbo = gl.createFramebuffer()
|
|
574
|
+
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo)
|
|
575
|
+
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0)
|
|
576
|
+
return { tex, fbo, w, h }
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function acquire(w = width, h = height) {
|
|
580
|
+
return pool.get(`${w}x${h}`)?.pop() ?? makeTarget(w, h)
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/** @param {Target} t */
|
|
584
|
+
function release(t) {
|
|
585
|
+
const key = `${t.w}x${t.h}`
|
|
586
|
+
const list = pool.get(key)
|
|
587
|
+
if (list) list.push(t)
|
|
588
|
+
else pool.set(key, [t])
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
function cleared() {
|
|
592
|
+
const t = acquire()
|
|
593
|
+
gl.bindFramebuffer(gl.FRAMEBUFFER, t.fbo)
|
|
594
|
+
gl.viewport(0, 0, t.w, t.h)
|
|
595
|
+
gl.clearColor(0, 0, 0, 0)
|
|
596
|
+
gl.clear(gl.COLOR_BUFFER_BIT)
|
|
597
|
+
return t
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/** Runs a full-frame pass into `out`. @param {Program} p @param {Target} out @param {Record<string, unknown>} values */
|
|
601
|
+
function pass(p, out, values) {
|
|
602
|
+
gl.bindFramebuffer(gl.FRAMEBUFFER, out.fbo)
|
|
603
|
+
gl.viewport(0, 0, out.w, out.h)
|
|
604
|
+
gl.disable(gl.BLEND)
|
|
605
|
+
use(p, values)
|
|
606
|
+
gl.drawArrays(gl.TRIANGLES, 0, 3)
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/** Replaces a slot's target by a pass that reads it as `src`. @param {Slot} slot @param {Program} p @param {Record<string, unknown>} values */
|
|
610
|
+
function replace(slot, p, values) {
|
|
611
|
+
const out = acquire(slot.t.w, slot.t.h)
|
|
612
|
+
pass(p, out, { src: slot.t, ...values })
|
|
613
|
+
release(slot.t)
|
|
614
|
+
slot.t = out
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* Lays a texture over a slot with an opacity and a blend mode: by the GPU's blend unit where the mode allows it,
|
|
619
|
+
* else by a pass that reads both.
|
|
620
|
+
* @param {Slot} slot @param {Target} src @param {number} opacity @param {string | undefined} blend
|
|
621
|
+
*/
|
|
622
|
+
function composite(slot, src, opacity, blend) {
|
|
623
|
+
const fixed = FIXED[/** @type {keyof typeof FIXED} */ (blend ?? 'normal')]
|
|
624
|
+
if (!fixed) {
|
|
625
|
+
const out = acquire(slot.t.w, slot.t.h)
|
|
626
|
+
pass(shader('blend'), out, { src, dst: slot.t, opacity, mode: MODES.indexOf(blend ?? 'normal') })
|
|
627
|
+
release(slot.t)
|
|
628
|
+
slot.t = out
|
|
629
|
+
return
|
|
630
|
+
}
|
|
631
|
+
gl.bindFramebuffer(gl.FRAMEBUFFER, slot.t.fbo)
|
|
632
|
+
gl.viewport(0, 0, slot.t.w, slot.t.h)
|
|
633
|
+
gl.enable(gl.BLEND)
|
|
634
|
+
gl.blendFuncSeparate(fixed[0], fixed[1], fixed[2], fixed[3])
|
|
635
|
+
use(shader('copy'), { src, opacity })
|
|
636
|
+
gl.drawArrays(gl.TRIANGLES, 0, 3)
|
|
637
|
+
gl.disable(gl.BLEND)
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* Runs geometry that draws premultiplied colour over a slot, in a blend mode.
|
|
642
|
+
* @param {Slot} slot @param {string | undefined} blend @param {() => void} draw
|
|
643
|
+
*/
|
|
644
|
+
function drawBlended(slot, blend, draw) {
|
|
645
|
+
const fixed = FIXED[/** @type {keyof typeof FIXED} */ (blend ?? 'normal')]
|
|
646
|
+
const into = fixed ? slot.t : cleared()
|
|
647
|
+
const [s, d, sa, da] = fixed ?? FIXED.normal
|
|
648
|
+
gl.bindFramebuffer(gl.FRAMEBUFFER, into.fbo)
|
|
649
|
+
gl.viewport(0, 0, into.w, into.h)
|
|
650
|
+
gl.enable(gl.BLEND)
|
|
651
|
+
gl.blendFuncSeparate(s, d, sa, da)
|
|
652
|
+
draw()
|
|
653
|
+
gl.disable(gl.BLEND)
|
|
654
|
+
if (!fixed) {
|
|
655
|
+
composite(slot, into, 1, blend)
|
|
656
|
+
release(into)
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/** The scene px to clip space transform for a display item's matrix. @param {Matrix} m */
|
|
661
|
+
function clipMatrix(m) {
|
|
662
|
+
const sx = (2 * scale) / width
|
|
663
|
+
const sy = (-2 * scale) / height
|
|
664
|
+
return new Float32Array([m[0] * sx, m[1] * sy, 0, m[2] * sx, m[3] * sy, 0, m[4] * sx - 1, m[5] * sy + 1, 1])
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/** @param {DisplayItem[]} list @param {Slot} slot */
|
|
668
|
+
function drawList(list, slot) {
|
|
669
|
+
/** @type {DisplayItem[]} */
|
|
670
|
+
let run = []
|
|
671
|
+
const flush = () => {
|
|
672
|
+
if (run.length === 0) return
|
|
673
|
+
const blend = run[0].blend
|
|
674
|
+
// A shader blend writes the whole target, so only a blend the GPU does by itself can be limited to an area.
|
|
675
|
+
const area = FIXED[/** @type {keyof typeof FIXED} */ (blend ?? 'normal')] ? runArea(run) : null
|
|
676
|
+
vector(run)
|
|
677
|
+
run = []
|
|
678
|
+
const up = /** @type {Target} */ (upload)
|
|
679
|
+
gl.bindTexture(gl.TEXTURE_2D, up.tex)
|
|
680
|
+
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true)
|
|
681
|
+
if (!area) {
|
|
682
|
+
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, vectorCanvas)
|
|
683
|
+
composite(slot, up, 1, blend)
|
|
684
|
+
return
|
|
685
|
+
}
|
|
686
|
+
const [x, y, w, h] = area
|
|
687
|
+
if (w === 0 || h === 0) return
|
|
688
|
+
// GL rows run up from the bottom; with FLIP_Y the source is flipped first, so rows are skipped from its bottom.
|
|
689
|
+
const glY = height - y - h
|
|
690
|
+
gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, x)
|
|
691
|
+
gl.pixelStorei(gl.UNPACK_SKIP_ROWS, glY)
|
|
692
|
+
gl.texSubImage2D(gl.TEXTURE_2D, 0, x, glY, w, h, gl.RGBA, gl.UNSIGNED_BYTE, vectorCanvas)
|
|
693
|
+
gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, 0)
|
|
694
|
+
gl.pixelStorei(gl.UNPACK_SKIP_ROWS, 0)
|
|
695
|
+
// The rest of the upload texture still holds earlier runs, so the composite is held to this area.
|
|
696
|
+
gl.enable(gl.SCISSOR_TEST)
|
|
697
|
+
gl.scissor(x, glY, w, h)
|
|
698
|
+
composite(slot, up, 1, blend)
|
|
699
|
+
gl.disable(gl.SCISSOR_TEST)
|
|
700
|
+
}
|
|
701
|
+
for (const item of list) {
|
|
702
|
+
switch (item.type) {
|
|
703
|
+
case 'layer':
|
|
704
|
+
flush()
|
|
705
|
+
drawLayer(item, slot)
|
|
706
|
+
break
|
|
707
|
+
case 'transition':
|
|
708
|
+
flush()
|
|
709
|
+
drawTransition(item, slot)
|
|
710
|
+
break
|
|
711
|
+
case 'mesh':
|
|
712
|
+
flush()
|
|
713
|
+
drawMesh(item, slot)
|
|
714
|
+
break
|
|
715
|
+
case 'image':
|
|
716
|
+
case 'video':
|
|
717
|
+
flush()
|
|
718
|
+
drawPicture(item, slot)
|
|
719
|
+
break
|
|
720
|
+
case 'instances':
|
|
721
|
+
if (SPRITE_BASES.has(item.base.type)) {
|
|
722
|
+
flush()
|
|
723
|
+
drawInstances(item, slot)
|
|
724
|
+
break
|
|
725
|
+
}
|
|
726
|
+
// Falls through: copies of text are drawn by Canvas 2D.
|
|
727
|
+
default: {
|
|
728
|
+
const last = run[run.length - 1]
|
|
729
|
+
if (last && (last.blend !== item.blend || !CHAINED.has(item.blend))) flush()
|
|
730
|
+
run.push(item)
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
flush()
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/**
|
|
738
|
+
* The canvas px a run of shapes and text can touch, as [x, y, w, h] from the top left, or null when that is not
|
|
739
|
+
* known and the whole frame goes up. Text gets room for any glyph and strokes for a miter join.
|
|
740
|
+
* @param {DisplayItem[]} items
|
|
741
|
+
* @returns {[number, number, number, number] | null}
|
|
742
|
+
*/
|
|
743
|
+
function runArea(items) {
|
|
744
|
+
let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity]
|
|
745
|
+
for (const item of items) {
|
|
746
|
+
if (item.type !== 'shape' && item.type !== 'text') return null
|
|
747
|
+
const box = item.type === 'shape' ? localBounds(item) : textBounds(item)
|
|
748
|
+
if (!box) return null
|
|
749
|
+
const m = item.matrix
|
|
750
|
+
for (const [x, y] of [[box[0], box[1]], [box[2], box[1]], [box[0], box[3]], [box[2], box[3]]]) {
|
|
751
|
+
const px = (m[0] * x + m[2] * y + m[4]) * scale
|
|
752
|
+
const py = (m[1] * x + m[3] * y + m[5]) * scale
|
|
753
|
+
x0 = Math.min(x0, px)
|
|
754
|
+
y0 = Math.min(y0, py)
|
|
755
|
+
x1 = Math.max(x1, px)
|
|
756
|
+
y1 = Math.max(y1, py)
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
// Two px of slack for antialiasing.
|
|
760
|
+
const left = Math.max(0, Math.floor(x0) - 2)
|
|
761
|
+
const top = Math.max(0, Math.floor(y0) - 2)
|
|
762
|
+
const right = Math.min(width, Math.ceil(x1) + 2)
|
|
763
|
+
const bottom = Math.min(height, Math.ceil(y1) + 2)
|
|
764
|
+
return right > left && bottom > top ? [left, top, right - left, bottom - top] : [0, 0, 0, 0]
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/**
|
|
768
|
+
* A text item's box in its own space, laid out as canvas2d lays it out. Each unit moved by per-letter animation
|
|
769
|
+
* gets a circle that holds it at any rotation.
|
|
770
|
+
* @param {DisplayItem & { type: 'text' }} item
|
|
771
|
+
* @returns {[number, number, number, number]}
|
|
772
|
+
*/
|
|
773
|
+
function textBounds(item) {
|
|
774
|
+
probe.font = item.font ?? '10px sans-serif'
|
|
775
|
+
const size = fontSize(item.font)
|
|
776
|
+
const layout = layoutText(item, text => probe.measureText(text).width)
|
|
777
|
+
const [up, down] = GLYPH_REACH[/** @type {keyof typeof GLYPH_REACH} */ (item.baseline ?? 'alphabetic')] ?? GLYPH_REACH.alphabetic
|
|
778
|
+
const side = size / 2 + (item.stroke === undefined ? 0 : (item.strokeWidth ?? 1) * 5)
|
|
779
|
+
let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity]
|
|
780
|
+
/** @param {number} a @param {number} b @param {number} c @param {number} d */
|
|
781
|
+
const add = (a, b, c, d) => {
|
|
782
|
+
x0 = Math.min(x0, a)
|
|
783
|
+
y0 = Math.min(y0, b)
|
|
784
|
+
x1 = Math.max(x1, c)
|
|
785
|
+
y1 = Math.max(y1, d)
|
|
786
|
+
}
|
|
787
|
+
if (!item.units) {
|
|
788
|
+
for (const line of layout.lines) add(line.x - side, line.y + up * size - side, line.x + line.width + side, line.y + down * size + side)
|
|
789
|
+
} else {
|
|
790
|
+
layout.boxes.forEach((box, i) => {
|
|
791
|
+
if (!box) return
|
|
792
|
+
const style = item.offsets?.[i]
|
|
793
|
+
const cx = box.x + box.w / 2 + (style?.x ?? 0)
|
|
794
|
+
const cy = box.y + (style?.y ?? 0)
|
|
795
|
+
const r = Math.hypot(box.w / 2 + side, Math.max(-up, down) * size + side) * Math.abs(style?.scale ?? 1)
|
|
796
|
+
add(cx - r, cy - r, cx + r, cy + r)
|
|
797
|
+
})
|
|
798
|
+
}
|
|
799
|
+
return x0 === Infinity ? [0, 0, 0, 0] : [x0, y0, x1, y1]
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/** @param {DisplayItem & { type: 'layer' }} layer @param {Slot} slot */
|
|
803
|
+
function drawLayer(layer, slot) {
|
|
804
|
+
const content = { t: cleared() }
|
|
805
|
+
if (layer.samples) {
|
|
806
|
+
// The mean of the samples, each added at 1 / n.
|
|
807
|
+
const n = layer.samples.length
|
|
808
|
+
for (const list of layer.samples) {
|
|
809
|
+
const sample = { t: cleared() }
|
|
810
|
+
drawList(list, sample)
|
|
811
|
+
gl.bindFramebuffer(gl.FRAMEBUFFER, content.t.fbo)
|
|
812
|
+
gl.viewport(0, 0, width, height)
|
|
813
|
+
gl.enable(gl.BLEND)
|
|
814
|
+
gl.blendFunc(gl.ONE, gl.ONE)
|
|
815
|
+
use(shader('copy'), { src: sample.t, opacity: 1 / n })
|
|
816
|
+
gl.drawArrays(gl.TRIANGLES, 0, 3)
|
|
817
|
+
gl.disable(gl.BLEND)
|
|
818
|
+
release(sample.t)
|
|
819
|
+
}
|
|
820
|
+
} else drawList(layer.items ?? [], content)
|
|
821
|
+
if (layer.matte) {
|
|
822
|
+
const mask = { t: cleared() }
|
|
823
|
+
drawList(layer.matte.items, mask)
|
|
824
|
+
replace(content, shader('matte'), { mask: mask.t, mode: MATTES.indexOf(layer.matte.mode) })
|
|
825
|
+
release(mask.t)
|
|
826
|
+
}
|
|
827
|
+
for (const effect of layer.effects ?? []) applyEffect(content, effect, layer.t ?? 0)
|
|
828
|
+
composite(slot, content.t, layer.opacity, layer.blend)
|
|
829
|
+
release(content.t)
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
/**
|
|
833
|
+
* A Gaussian blur of `sigma` canvas px into a new target. The image is halved until the blur is at most 3 px wide
|
|
834
|
+
* at that size, so a wide blur costs about as little as a narrow one.
|
|
835
|
+
* @param {Target} src @param {number} sigma
|
|
836
|
+
*/
|
|
837
|
+
function blurred(src, sigma) {
|
|
838
|
+
const out = acquire(src.w, src.h)
|
|
839
|
+
if (!(sigma > 0)) {
|
|
840
|
+
pass(shader('copy'), out, { src, opacity: 1 })
|
|
841
|
+
return out
|
|
842
|
+
}
|
|
843
|
+
/** @type {Target[]} */
|
|
844
|
+
const chain = []
|
|
845
|
+
let cur = src
|
|
846
|
+
// Each halving is a 2 by 2 box, which blurs a little by itself: 0.25 texel² at the size it reads.
|
|
847
|
+
let boxVariance = 0
|
|
848
|
+
while (sigma * (cur.w / src.w) > 3 && cur.w > 8 && cur.h > 8) {
|
|
849
|
+
const half = acquire(Math.ceil(cur.w / 2), Math.ceil(cur.h / 2))
|
|
850
|
+
pass(shader('copy'), half, { src: cur, opacity: 1 })
|
|
851
|
+
boxVariance += 0.25 * (src.w / cur.w) ** 2
|
|
852
|
+
chain.push(half)
|
|
853
|
+
cur = half
|
|
854
|
+
}
|
|
855
|
+
const rest = Math.sqrt(Math.max(0, sigma * sigma - boxVariance))
|
|
856
|
+
const across = acquire(cur.w, cur.h)
|
|
857
|
+
const sx = Math.max(rest * (cur.w / src.w), 1e-3)
|
|
858
|
+
const sy = Math.max(rest * (cur.h / src.h), 1e-3)
|
|
859
|
+
pass(shader('blur'), across, { src: cur, dir: [1 / cur.w, 0], sigma: sx, radius: Math.min(64, Math.ceil(sx * 3)) })
|
|
860
|
+
const down = chain.length > 0 ? cur : out
|
|
861
|
+
pass(shader('blur'), down, { src: across, dir: [0, 1 / cur.h], sigma: sy, radius: Math.min(64, Math.ceil(sy * 3)) })
|
|
862
|
+
release(across)
|
|
863
|
+
if (down !== out) pass(shader('copy'), out, { src: down, opacity: 1 })
|
|
864
|
+
for (const t of chain) release(t)
|
|
865
|
+
return out
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
/** @type {Map<string, number[]>} */
|
|
869
|
+
const colours = new Map()
|
|
870
|
+
/** A CSS colour as premultiplied RGBA from 0 to 1, read back from a pixel so any CSS colour works. @param {string} css */
|
|
871
|
+
function rgba(css) {
|
|
872
|
+
let c = colours.get(css)
|
|
873
|
+
if (c) return c
|
|
874
|
+
if (colours.size > 256) colours.clear()
|
|
875
|
+
probe.clearRect(0, 0, 1, 1)
|
|
876
|
+
probe.fillStyle = 'rgba(0, 0, 0, 0)'
|
|
877
|
+
probe.fillStyle = css
|
|
878
|
+
probe.fillRect(0, 0, 1, 1)
|
|
879
|
+
const [r, g, b, a] = probe.getImageData(0, 0, 1, 1).data
|
|
880
|
+
c = [(r / 255) * (a / 255), (g / 255) * (a / 255), (b / 255) * (a / 255), a / 255]
|
|
881
|
+
colours.set(css, c)
|
|
882
|
+
return c
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
/** @param {Slot} content @param {ResolvedEffect} effect @param {number} t */
|
|
886
|
+
function applyEffect(content, effect, t) {
|
|
887
|
+
const size = [width, height]
|
|
888
|
+
switch (effect.type) {
|
|
889
|
+
case 'blur': {
|
|
890
|
+
const b = blurred(content.t, effect.radius * scale)
|
|
891
|
+
release(content.t)
|
|
892
|
+
content.t = b
|
|
893
|
+
break
|
|
894
|
+
}
|
|
895
|
+
case 'glow':
|
|
896
|
+
case 'diffusion': {
|
|
897
|
+
let source = content.t
|
|
898
|
+
if (effect.type === 'glow') {
|
|
899
|
+
source = acquire()
|
|
900
|
+
pass(shader('bright'), source, { src: content.t, threshold: effect.threshold })
|
|
901
|
+
}
|
|
902
|
+
const glow = blurred(source, effect.radius * scale)
|
|
903
|
+
if (source !== content.t) release(source)
|
|
904
|
+
replace(content, shader('screen'), { glow, strength: effect.strength })
|
|
905
|
+
release(glow)
|
|
906
|
+
break
|
|
907
|
+
}
|
|
908
|
+
case 'grain':
|
|
909
|
+
replace(content, shader('grain'), {
|
|
910
|
+
amount: effect.amount,
|
|
911
|
+
size: Math.max(1, effect.size * scale),
|
|
912
|
+
key: Math.floor(rand('grain', effect.seed, Math.round(t * 1000)) * 4294967296) >>> 0,
|
|
913
|
+
})
|
|
914
|
+
break
|
|
915
|
+
case 'para':
|
|
916
|
+
replace(content, shader('para'), {
|
|
917
|
+
colorFrom: rgba(effect.from),
|
|
918
|
+
colorTo: rgba(effect.to),
|
|
919
|
+
size,
|
|
920
|
+
angle: (effect.angle * Math.PI) / 180,
|
|
921
|
+
opacity: effect.opacity,
|
|
922
|
+
mode: Math.max(0, MODES.indexOf(effect.blend)),
|
|
923
|
+
})
|
|
924
|
+
break
|
|
925
|
+
case 'vignette':
|
|
926
|
+
replace(content, shader('vignette'), { size, strength: effect.strength, radius: effect.radius })
|
|
927
|
+
break
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
/** @param {DisplayItem & { type: 'transition' }} item @param {Slot} slot */
|
|
932
|
+
function drawTransition(item, slot) {
|
|
933
|
+
const from = { t: cleared() }
|
|
934
|
+
const to = { t: cleared() }
|
|
935
|
+
drawList(item.from, from)
|
|
936
|
+
drawList(item.to, to)
|
|
937
|
+
const p = transitionProgram(item)
|
|
938
|
+
const [x, y, w, h] = item.box ?? [0, 0, sceneSize[0], sceneSize[1]]
|
|
939
|
+
const out = acquire()
|
|
940
|
+
pass(p, out, {
|
|
941
|
+
...p.defaults,
|
|
942
|
+
...item.params,
|
|
943
|
+
mlFrom: from.t,
|
|
944
|
+
mlTo: to.t,
|
|
945
|
+
mlBox: [(x * scale) / width, 1 - ((y + h) * scale) / height, (w * scale) / width, (h * scale) / height],
|
|
946
|
+
progress: item.progress,
|
|
947
|
+
ratio: w / h,
|
|
948
|
+
viewSize: [w, h],
|
|
949
|
+
})
|
|
950
|
+
release(from.t)
|
|
951
|
+
release(to.t)
|
|
952
|
+
composite(slot, out, item.opacity, item.blend)
|
|
953
|
+
release(out)
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
// Meshes and instances read their numbers through scratch arrays that only grow.
|
|
957
|
+
let scratch = new Float32Array(0)
|
|
958
|
+
/** @param {ArrayLike<number>} values */
|
|
959
|
+
function floats(values) {
|
|
960
|
+
if (values instanceof Float32Array) return values
|
|
961
|
+
if (scratch.length < values.length) scratch = new Float32Array(Math.max(values.length, scratch.length * 2))
|
|
962
|
+
const view = scratch.subarray(0, values.length)
|
|
963
|
+
view.set(values)
|
|
964
|
+
return view
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
const meshVao = gl.createVertexArray()
|
|
968
|
+
const pointBuffer = /** @type {WebGLBuffer} */ (gl.createBuffer())
|
|
969
|
+
const quadUvBuffer = /** @type {WebGLBuffer} */ (gl.createBuffer())
|
|
970
|
+
/** @type {WeakMap<object, WebGLBuffer>} */
|
|
971
|
+
const uvBuffers = new WeakMap()
|
|
972
|
+
/** @typedef {{ buffer: WebGLBuffer, count: number, type: number }} Index */
|
|
973
|
+
/** @type {WeakMap<object, Index>} */
|
|
974
|
+
const indexBuffers = new WeakMap()
|
|
975
|
+
/** @type {WebGLBuffer[]} */
|
|
976
|
+
const ownedBuffers = [pointBuffer, quadUvBuffer]
|
|
977
|
+
/** @type {Map<string, { tex: WebGLTexture, source: any }>} */
|
|
978
|
+
const textures = new Map()
|
|
979
|
+
|
|
980
|
+
/** @param {ArrayLike<number>} triangles @returns {Index} */
|
|
981
|
+
function indexFor(triangles) {
|
|
982
|
+
let index = indexBuffers.get(triangles)
|
|
983
|
+
if (!index) {
|
|
984
|
+
const big = Array.prototype.some.call(triangles, (/** @type {number} */ i) => i > 65535)
|
|
985
|
+
const buffer = /** @type {WebGLBuffer} */ (gl.createBuffer())
|
|
986
|
+
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer)
|
|
987
|
+
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, big ? Uint32Array.from(triangles) : Uint16Array.from(triangles), gl.STATIC_DRAW)
|
|
988
|
+
index = { buffer, count: triangles.length, type: big ? gl.UNSIGNED_INT : gl.UNSIGNED_SHORT }
|
|
989
|
+
indexBuffers.set(triangles, index)
|
|
990
|
+
ownedBuffers.push(buffer)
|
|
991
|
+
}
|
|
992
|
+
return index
|
|
993
|
+
}
|
|
994
|
+
const QUAD = [0, 1, 2, 2, 1, 3]
|
|
995
|
+
|
|
996
|
+
/**
|
|
997
|
+
* A texture of an image or a decoded video frame, with mipmaps for smooth shrinking. It is uploaded again only
|
|
998
|
+
* when the source under `key` changes, as a video's frame does.
|
|
999
|
+
* @param {string} key @param {any} source
|
|
1000
|
+
*/
|
|
1001
|
+
function textureOf(key, source) {
|
|
1002
|
+
const hit = textures.get(key)
|
|
1003
|
+
if (hit && hit.source === source) return { tex: hit.tex, w: source.width, h: source.height }
|
|
1004
|
+
const tex = hit?.tex ?? /** @type {WebGLTexture} */ (gl.createTexture())
|
|
1005
|
+
gl.bindTexture(gl.TEXTURE_2D, tex)
|
|
1006
|
+
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false)
|
|
1007
|
+
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, source)
|
|
1008
|
+
gl.generateMipmap(gl.TEXTURE_2D)
|
|
1009
|
+
textures.set(key, { tex, source })
|
|
1010
|
+
return { tex, w: source.width, h: source.height }
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
/** @param {string} src */
|
|
1014
|
+
function imageTexture(src) {
|
|
1015
|
+
const image = images.get(src)
|
|
1016
|
+
if (!image) throw new Error(`webgl2: image "${src}" is not loaded; list it in the scene's assets.images`)
|
|
1017
|
+
return textureOf(`image:${src}`, image)
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
/**
|
|
1021
|
+
* Textured triangles in an item's space: points as x, y pairs, uvs as the matching texture px.
|
|
1022
|
+
* @param {Slot} slot
|
|
1023
|
+
* @param {{ matrix: Matrix, opacity: number, blend?: string, smooth?: false }} item
|
|
1024
|
+
* @param {{ tex: WebGLTexture, w: number, h: number }} texture
|
|
1025
|
+
* @param {ArrayLike<number>} points @param {WebGLBuffer} uvs @param {Index} index
|
|
1026
|
+
*/
|
|
1027
|
+
function drawTriangles(slot, item, texture, points, uvs, index) {
|
|
1028
|
+
gl.bindVertexArray(meshVao)
|
|
1029
|
+
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index.buffer)
|
|
1030
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, pointBuffer)
|
|
1031
|
+
gl.bufferData(gl.ARRAY_BUFFER, floats(points), gl.STREAM_DRAW)
|
|
1032
|
+
gl.enableVertexAttribArray(0)
|
|
1033
|
+
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0)
|
|
1034
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, uvs)
|
|
1035
|
+
gl.enableVertexAttribArray(1)
|
|
1036
|
+
gl.vertexAttribPointer(1, 2, gl.FLOAT, false, 0, 0)
|
|
1037
|
+
gl.bindVertexArray(null)
|
|
1038
|
+
drawBlended(slot, item.blend, () => {
|
|
1039
|
+
gl.activeTexture(gl.TEXTURE0 + IMAGE_UNIT)
|
|
1040
|
+
gl.bindTexture(gl.TEXTURE_2D, texture.tex)
|
|
1041
|
+
gl.bindSampler(IMAGE_UNIT, item.smooth === false ? sharp : smooth)
|
|
1042
|
+
use(shader('mesh'), { matrix: clipMatrix(item.matrix), imageSize: [texture.w, texture.h], opacity: item.opacity, image: IMAGE_UNIT })
|
|
1043
|
+
gl.bindVertexArray(meshVao)
|
|
1044
|
+
gl.drawElements(gl.TRIANGLES, index.count, index.type, 0)
|
|
1045
|
+
gl.bindVertexArray(null)
|
|
1046
|
+
})
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
/** @param {DisplayItem & { type: 'mesh' }} item @param {Slot} slot */
|
|
1050
|
+
function drawMesh(item, slot) {
|
|
1051
|
+
const texture = imageTexture(item.src)
|
|
1052
|
+
let uvs = uvBuffers.get(item.uvs)
|
|
1053
|
+
if (!uvs) {
|
|
1054
|
+
uvs = /** @type {WebGLBuffer} */ (gl.createBuffer())
|
|
1055
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, uvs)
|
|
1056
|
+
gl.bufferData(gl.ARRAY_BUFFER, floats(item.uvs), gl.STATIC_DRAW)
|
|
1057
|
+
uvBuffers.set(item.uvs, uvs)
|
|
1058
|
+
ownedBuffers.push(uvs)
|
|
1059
|
+
}
|
|
1060
|
+
drawTriangles(slot, item, texture, item.points, uvs, indexFor(item.triangles))
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
/**
|
|
1064
|
+
* An image or video frame as one quad, on the GPU rather than through Canvas 2D, whose image scaling can differ
|
|
1065
|
+
* from one draw to the next.
|
|
1066
|
+
* @param {DisplayItem & { type: 'image' | 'video' }} item @param {Slot} slot
|
|
1067
|
+
*/
|
|
1068
|
+
function drawPicture(item, slot) {
|
|
1069
|
+
const texture = item.type === 'image' ? imageTexture(item.src) : textureOf(`video:${item.src}`, videoFrame(videos, item, 'webgl2'))
|
|
1070
|
+
const [sx, sy, sw, sh] = item.crop ?? [0, 0, texture.w, texture.h]
|
|
1071
|
+
const w = item.w ?? sw
|
|
1072
|
+
const h = item.h ?? sh
|
|
1073
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, quadUvBuffer)
|
|
1074
|
+
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([sx, sy, sx + sw, sy, sx, sy + sh, sx + sw, sy + sh]), gl.STREAM_DRAW)
|
|
1075
|
+
drawTriangles(slot, item, texture, [0, 0, w, 0, 0, h, w, h], quadUvBuffer, indexFor(QUAD))
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
const instanceVao = gl.createVertexArray()
|
|
1079
|
+
const instanceBuffer = /** @type {WebGLBuffer} */ (gl.createBuffer())
|
|
1080
|
+
const quadCornerBuffer = /** @type {WebGLBuffer} */ (gl.createBuffer())
|
|
1081
|
+
ownedBuffers.push(instanceBuffer, quadCornerBuffer)
|
|
1082
|
+
gl.bindVertexArray(instanceVao)
|
|
1083
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, quadCornerBuffer)
|
|
1084
|
+
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]), gl.STATIC_DRAW)
|
|
1085
|
+
gl.enableVertexAttribArray(0)
|
|
1086
|
+
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0)
|
|
1087
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, instanceBuffer)
|
|
1088
|
+
gl.enableVertexAttribArray(1)
|
|
1089
|
+
gl.vertexAttribPointer(1, 4, gl.FLOAT, false, STRIDE * 4, 0)
|
|
1090
|
+
gl.vertexAttribDivisor(1, 1)
|
|
1091
|
+
gl.enableVertexAttribArray(2)
|
|
1092
|
+
gl.vertexAttribPointer(2, 3, gl.FLOAT, false, STRIDE * 4, 16)
|
|
1093
|
+
gl.vertexAttribDivisor(2, 1)
|
|
1094
|
+
gl.bindVertexArray(null)
|
|
1095
|
+
|
|
1096
|
+
/** @type {Map<string, Sprite>} */
|
|
1097
|
+
const sprites = new Map()
|
|
1098
|
+
|
|
1099
|
+
/**
|
|
1100
|
+
* The base's local bounds: a shape's path grown by its stroke, or an image's size.
|
|
1101
|
+
* @param {DisplayItem} base
|
|
1102
|
+
* @returns {[number, number, number, number] | null}
|
|
1103
|
+
*/
|
|
1104
|
+
function localBounds(base) {
|
|
1105
|
+
if (base.type === 'image') {
|
|
1106
|
+
const img = images.get(base.src)
|
|
1107
|
+
if (!img) throw new Error(`webgl2: image "${base.src}" is not loaded; list it in the scene's assets.images`)
|
|
1108
|
+
return [0, 0, base.w ?? base.crop?.[2] ?? img.width, base.h ?? base.crop?.[3] ?? img.height]
|
|
1109
|
+
}
|
|
1110
|
+
if (base.type !== 'shape' || (base.fill === undefined && base.stroke === undefined)) return null
|
|
1111
|
+
const box = pathBounds(base.path)
|
|
1112
|
+
if (!box || base.stroke === undefined) return box
|
|
1113
|
+
// A miter join can reach out half the miter limit (10) times the line width.
|
|
1114
|
+
const grow = ((base.strokeWidth ?? 1) / 2) * ((base.lineJoin ?? 'miter') === 'miter' ? 10 : 1)
|
|
1115
|
+
return [box[0] - grow, box[1] - grow, box[2] + grow, box[3] + grow]
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
/**
|
|
1119
|
+
* The base drawn once per colour into the layers of a texture array, at the next power of two of `reach` canvas
|
|
1120
|
+
* px per unit, so a copy that grows does not redraw the sprite every frame.
|
|
1121
|
+
* @param {DisplayItem} base @param {string[]} colors @param {number} reach
|
|
1122
|
+
* @returns {Sprite | null}
|
|
1123
|
+
*/
|
|
1124
|
+
function spriteFor(base, colors, reach) {
|
|
1125
|
+
if (!(reach > 0)) return null
|
|
1126
|
+
const box = localBounds(base)
|
|
1127
|
+
if (!box) return null
|
|
1128
|
+
const w = Math.max(box[2] - box[0], 1e-6)
|
|
1129
|
+
const h = Math.max(box[3] - box[1], 1e-6)
|
|
1130
|
+
const k = Math.min(2 ** Math.ceil(Math.log2(reach)), (Math.min(maxTexture, 2048) - 2 * SPRITE_PAD) / Math.max(w, h))
|
|
1131
|
+
if (!(k > 0)) return null
|
|
1132
|
+
const layers = base.type === 'image' ? 1 : colors.length + 1
|
|
1133
|
+
if (layers > maxArrayLayers) {
|
|
1134
|
+
throw new RangeError(`webgl2: instances needs ${layers} colour layers, above this GPU's limit of ${maxArrayLayers}`)
|
|
1135
|
+
}
|
|
1136
|
+
const key = `${hash({ ...base, id: '', matrix: null, opacity: 1, blend: undefined })}:${layers > 1 ? colors.join('|') : ''}:${k}`
|
|
1137
|
+
const hit = sprites.get(key)
|
|
1138
|
+
if (hit) {
|
|
1139
|
+
sprites.delete(key)
|
|
1140
|
+
sprites.set(key, hit)
|
|
1141
|
+
return hit
|
|
1142
|
+
}
|
|
1143
|
+
const cw = Math.ceil(w * k) + 2 * SPRITE_PAD
|
|
1144
|
+
const ch = Math.ceil(h * k) + 2 * SPRITE_PAD
|
|
1145
|
+
spriteCanvas.width = cw
|
|
1146
|
+
spriteCanvas.height = ch
|
|
1147
|
+
const tex = /** @type {WebGLTexture} */ (gl.createTexture())
|
|
1148
|
+
gl.bindTexture(gl.TEXTURE_2D_ARRAY, tex)
|
|
1149
|
+
gl.texStorage3D(gl.TEXTURE_2D_ARRAY, Math.floor(Math.log2(Math.max(cw, ch))) + 1, gl.RGBA8, cw, ch, layers)
|
|
1150
|
+
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false)
|
|
1151
|
+
/** @type {Matrix} */
|
|
1152
|
+
const matrix = [k, 0, 0, k, SPRITE_PAD - box[0] * k, SPRITE_PAD - box[1] * k]
|
|
1153
|
+
for (let layer = 0; layer < layers; layer++) {
|
|
1154
|
+
const fill = layer === 0 ? {} : { fill: colors[layer - 1] }
|
|
1155
|
+
spriteRender([/** @type {DisplayItem} */ ({ ...base, ...fill, matrix, opacity: 1, blend: undefined })])
|
|
1156
|
+
gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, 0, 0, layer, cw, ch, 1, gl.RGBA, gl.UNSIGNED_BYTE, spriteCanvas)
|
|
1157
|
+
}
|
|
1158
|
+
gl.generateMipmap(gl.TEXTURE_2D_ARRAY)
|
|
1159
|
+
/** @type {Sprite} */
|
|
1160
|
+
const sprite = { tex, rect: [box[0] - SPRITE_PAD / k, box[1] - SPRITE_PAD / k, cw / k, ch / k] }
|
|
1161
|
+
sprites.set(key, sprite)
|
|
1162
|
+
if (sprites.size > SPRITE_CACHE) {
|
|
1163
|
+
const [oldest, old] = sprites.entries().next().value ?? []
|
|
1164
|
+
if (oldest !== undefined && old) {
|
|
1165
|
+
gl.deleteTexture(old.tex)
|
|
1166
|
+
sprites.delete(oldest)
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
return sprite
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
/** @param {DisplayItem & { type: 'instances' }} item @param {Slot} slot */
|
|
1173
|
+
function drawInstances(item, slot) {
|
|
1174
|
+
const { base, data, colors } = item
|
|
1175
|
+
const count = Math.floor(data.length / STRIDE)
|
|
1176
|
+
let most = 0
|
|
1177
|
+
for (let k = 0; k < count * STRIDE; k += STRIDE) {
|
|
1178
|
+
if (data[k + 5] > 0) most = Math.max(most, Math.abs(data[k + 3]), Math.abs(data[k + 4]))
|
|
1179
|
+
}
|
|
1180
|
+
if (most === 0 || base.type === 'layer' || base.type === 'transition') return
|
|
1181
|
+
const sprite = spriteFor(base, colors, scale * stretch(item.matrix) * most * stretch(base.matrix))
|
|
1182
|
+
if (!sprite) return
|
|
1183
|
+
const [rx, ry, rw, rh] = sprite.rect
|
|
1184
|
+
const b = base.matrix
|
|
1185
|
+
const baseMatrix = new Float32Array([b[0] * rw, b[1] * rw, 0, b[2] * rh, b[3] * rh, 0, b[0] * rx + b[2] * ry + b[4], b[1] * rx + b[3] * ry + b[5], 1])
|
|
1186
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, instanceBuffer)
|
|
1187
|
+
gl.bufferData(gl.ARRAY_BUFFER, floats(data.subarray(0, count * STRIDE)), gl.STREAM_DRAW)
|
|
1188
|
+
drawBlended(slot, item.blend, () => {
|
|
1189
|
+
gl.activeTexture(gl.TEXTURE0 + IMAGE_UNIT)
|
|
1190
|
+
gl.bindTexture(gl.TEXTURE_2D_ARRAY, sprite.tex)
|
|
1191
|
+
gl.bindSampler(IMAGE_UNIT, base.type === 'image' && base.smooth === false ? sharp : smooth)
|
|
1192
|
+
use(shader('instances'), { item: clipMatrix(item.matrix), base: baseMatrix, opacity: item.opacity * base.opacity, sprites: IMAGE_UNIT })
|
|
1193
|
+
gl.bindVertexArray(instanceVao)
|
|
1194
|
+
gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, count)
|
|
1195
|
+
gl.bindVertexArray(null)
|
|
1196
|
+
})
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
/** Matches the GPU targets and the Canvas 2D surface to the canvas, if it changed size. */
|
|
1200
|
+
function fit() {
|
|
1201
|
+
if (canvas.width === width && canvas.height === height && upload) return
|
|
1202
|
+
width = canvas.width
|
|
1203
|
+
height = canvas.height
|
|
1204
|
+
sceneSize = [width / scale, height / scale]
|
|
1205
|
+
for (const list of pool.values()) {
|
|
1206
|
+
for (const t of list) {
|
|
1207
|
+
gl.deleteTexture(t.tex)
|
|
1208
|
+
gl.deleteFramebuffer(t.fbo)
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
pool.clear()
|
|
1212
|
+
if (upload) gl.deleteTexture(upload.tex)
|
|
1213
|
+
const tex = /** @type {WebGLTexture} */ (gl.createTexture())
|
|
1214
|
+
gl.bindTexture(gl.TEXTURE_2D, tex)
|
|
1215
|
+
gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA8, width, height)
|
|
1216
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
|
|
1217
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
|
|
1218
|
+
upload = { tex, fbo: null, w: width, h: height }
|
|
1219
|
+
vectorCanvas.width = width
|
|
1220
|
+
vectorCanvas.height = height
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
/** @param {DisplayItem[]} list */
|
|
1224
|
+
function render(list) {
|
|
1225
|
+
fit()
|
|
1226
|
+
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true)
|
|
1227
|
+
const frame = { t: cleared() }
|
|
1228
|
+
drawList(list, frame)
|
|
1229
|
+
gl.bindFramebuffer(gl.FRAMEBUFFER, null)
|
|
1230
|
+
gl.viewport(0, 0, width, height)
|
|
1231
|
+
gl.disable(gl.BLEND)
|
|
1232
|
+
use(shader('copy'), { src: frame.t, opacity: 1 })
|
|
1233
|
+
gl.drawArrays(gl.TRIANGLES, 0, 3)
|
|
1234
|
+
release(frame.t)
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
/** @param {Scene} scene */
|
|
1238
|
+
async function load(scene) {
|
|
1239
|
+
canvas.width = Math.round(scene.size[0] * scale)
|
|
1240
|
+
canvas.height = Math.round(scene.size[1] * scale)
|
|
1241
|
+
sceneSize = [scene.size[0], scene.size[1]]
|
|
1242
|
+
fit()
|
|
1243
|
+
await loadAssets(scene, images, videos)
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
/** @param {{ loseContext?: boolean }} [options] */
|
|
1247
|
+
function dispose({ loseContext = false } = {}) {
|
|
1248
|
+
for (const list of pool.values()) {
|
|
1249
|
+
for (const t of list) {
|
|
1250
|
+
gl.deleteTexture(t.tex)
|
|
1251
|
+
gl.deleteFramebuffer(t.fbo)
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
pool.clear()
|
|
1255
|
+
if (upload) {
|
|
1256
|
+
gl.deleteTexture(upload.tex)
|
|
1257
|
+
upload = null
|
|
1258
|
+
}
|
|
1259
|
+
for (const s of sprites.values()) gl.deleteTexture(s.tex)
|
|
1260
|
+
sprites.clear()
|
|
1261
|
+
for (const entry of textures.values()) gl.deleteTexture(entry.tex)
|
|
1262
|
+
textures.clear()
|
|
1263
|
+
for (const p of programs.values()) gl.deleteProgram(p.program)
|
|
1264
|
+
programs.clear()
|
|
1265
|
+
for (const p of transitions.values()) gl.deleteProgram(p.program)
|
|
1266
|
+
transitions.clear()
|
|
1267
|
+
for (const b of ownedBuffers) gl.deleteBuffer(b)
|
|
1268
|
+
ownedBuffers.length = 0
|
|
1269
|
+
gl.deleteVertexArray(meshVao)
|
|
1270
|
+
gl.deleteVertexArray(instanceVao)
|
|
1271
|
+
gl.deleteSampler(smooth)
|
|
1272
|
+
gl.deleteSampler(sharp)
|
|
1273
|
+
colours.clear()
|
|
1274
|
+
images.clear()
|
|
1275
|
+
videos.clear()
|
|
1276
|
+
vector.dispose()
|
|
1277
|
+
spriteRender.dispose()
|
|
1278
|
+
if (loseContext) gl.getExtension('WEBGL_lose_context')?.loseContext()
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
return Object.defineProperties(/** @type {WebGL2Renderer} */ (/** @type {unknown} */ (render)), {
|
|
1282
|
+
load: { value: load },
|
|
1283
|
+
prepare: { value: (/** @type {DisplayItem[]} */ list) => prepareVideos(videos, list) },
|
|
1284
|
+
dispose: { value: dispose },
|
|
1285
|
+
canvas: { value: canvas },
|
|
1286
|
+
gl: { value: gl },
|
|
1287
|
+
})
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
/** @param {WebGL2Renderer} render @param {DisplayItem[]} list */
|
|
1291
|
+
async function drawReady(render, list) {
|
|
1292
|
+
await render.prepare(list)
|
|
1293
|
+
render(list)
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
/**
|
|
1297
|
+
* One frame as a PNG, drawn with WebGL2 on a canvas of its own.
|
|
1298
|
+
* @param {Scene} scene @param {number} t @param {{ scale?: number }} [options]
|
|
1299
|
+
* @returns {Promise<Blob>}
|
|
1300
|
+
*/
|
|
1301
|
+
export async function toPNG(scene, t, { scale = 1 } = {}) {
|
|
1302
|
+
const render = webgl2(makeSurface(1, 1), { scale, preserveDrawingBuffer: true })
|
|
1303
|
+
try {
|
|
1304
|
+
await render.load(scene)
|
|
1305
|
+
await drawReady(render, scene.evaluate(t))
|
|
1306
|
+
return await pngOf(render.canvas)
|
|
1307
|
+
} finally {
|
|
1308
|
+
render.dispose({ loseContext: true })
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
/**
|
|
1313
|
+
* Like verify, but compares the pixels WebGL2 draws: every frame in order, then in a shuffled order twice each.
|
|
1314
|
+
* @param {Scene} scene
|
|
1315
|
+
* @param {{ fps?: number, seed?: string | number, scale?: number }} [options]
|
|
1316
|
+
*/
|
|
1317
|
+
export async function verifyPixels(scene, { fps = 30, seed = 'verify', scale = 1 } = {}) {
|
|
1318
|
+
const render = webgl2(makeSurface(1, 1), { scale, preserveDrawingBuffer: true })
|
|
1319
|
+
try {
|
|
1320
|
+
await render.load(scene)
|
|
1321
|
+
const { gl, canvas } = render
|
|
1322
|
+
const pixels = new Uint8Array(canvas.width * canvas.height * 4)
|
|
1323
|
+
return await comparePixels(scene, async t => {
|
|
1324
|
+
await drawReady(render, scene.evaluate(t))
|
|
1325
|
+
gl.readPixels(0, 0, canvas.width, canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels)
|
|
1326
|
+
return pixelHash(pixels)
|
|
1327
|
+
}, { fps, seed })
|
|
1328
|
+
} finally {
|
|
1329
|
+
render.dispose({ loseContext: true })
|
|
1330
|
+
}
|
|
1331
|
+
}
|