@arraypress/effects-astro 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,351 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/photo-bokeh
3
+ *
4
+ * A photo seen through a lens racking its focus: the plane of focus sweeps
5
+ * slowly from near to far and back, so one part of the picture sharpens while
6
+ * the rest melts into soft blur, and out-of-focus lights (soft filled glows,
7
+ * round or six-bladed, tinted from the photo's highlights and brighter where
8
+ * they cross them) drift slowly upward through it. Made for flowers and close
9
+ * portraits behind a mark: no pointer, the copy sharp in front.
10
+ *
11
+ * There is no depth map, so the depth is a guess from the picture itself:
12
+ * its blurred brightness and colour (the bright, saturated subject nearer)
13
+ * and where it sits (lower nearer), so the blur follows the picture's forms
14
+ * rather than lying flat over it. The blur is a golden-angle disc of taps
15
+ * read from the photo's mipmaps, so a wide blur stays smooth and cheap.
16
+ *
17
+ * The focus and the lights are here in plain JavaScript too (`focusAt`,
18
+ * `blurAt`, `discAt`). Transparent until the photo has loaded (the element's
19
+ * own still shows), then opaque; with prefers-reduced-motion (or `speed: 0`)
20
+ * one still frame. Without WebGL nothing is drawn.
21
+ */
22
+
23
+ import { createStage } from './stage.js';
24
+ import { GLSL_HASH33 } from './hash-noise.js';
25
+ import { GLSL_QUIET, quietUniform } from './glsl.js';
26
+ import { loadImage, imageTexture, coverScale, GLSL_COVER } from './image.js';
27
+
28
+ /**
29
+ * @typedef {'round' | 'blades'} BokehShape
30
+ *
31
+ * @typedef {object} PhotoBokehConfig
32
+ * @property {string} src The photo (same origin, or served for CORS).
33
+ * @property {number} [blur=0.03] The widest blur, a share of the height.
34
+ * @property {number} [rate=0.06] How fast the focus racks, cycles a second.
35
+ * @property {number} [near=0.55] How much the depth guess leans on the picture (its brightness and colour) against its height in the frame, 0–1.
36
+ * @property {number} [discs=6] Out-of-focus lights drifting through it, up to 12; 0 for none.
37
+ * @property {number} [size=0.11] Their radius, a share of the height.
38
+ * @property {number} [glow=0.35] How bright they are.
39
+ * @property {BokehShape} [shape='round'] Round lights, or six-bladed ones.
40
+ * @property {number} [drift=0.02] How fast they rise, heights a second.
41
+ * @property {number} [vignette=0.35] Darkening toward the edges; 0 for none.
42
+ * @property {number} [grain=0.04] Fine grain over all of it; 0 for none.
43
+ * @property {number} [seed=0] Where the focus and the lights start, so two cards differ.
44
+ * @property {number} [speed=1] Plays every clock faster or slower; 0 for one still frame.
45
+ * @property {{ x?: number, y?: number, radius?: number, depth?: number } | null} [quiet=null]
46
+ * An area dimmed a little for copy: centre (0–1 from the top left), radius (share of the height), depth (0–1).
47
+ */
48
+
49
+ /** The settings' defaults, shared by the shader and the JS twin. */
50
+ export const BOKEH_DEFAULTS = {
51
+ blur: 0.03,
52
+ rate: 0.06,
53
+ near: 0.55,
54
+ discs: 6,
55
+ size: 0.11,
56
+ glow: 0.35,
57
+ shape: /** @type {BokehShape} */ ('round'),
58
+ drift: 0.02,
59
+ vignette: 0.35,
60
+ grain: 0.04,
61
+ seed: 0,
62
+ };
63
+
64
+ /** The most lights the shader draws. */
65
+ export const MAX_DISCS = 12;
66
+
67
+ /**
68
+ * The settings, filled with the defaults.
69
+ *
70
+ * @param {Partial<PhotoBokehConfig>} config The settings.
71
+ * @returns {typeof BOKEH_DEFAULTS & { speed: number }} The settings.
72
+ */
73
+ const settings = (config) => ({ ...BOKEH_DEFAULTS, speed: 1, ...config });
74
+
75
+ /**
76
+ * Where the plane of focus is: a depth from 0 (far) to 1 (near), sweeping back and forth.
77
+ *
78
+ * @param {Partial<PhotoBokehConfig>} config The settings.
79
+ * @param {number} t Seconds (already at its speed).
80
+ * @returns {number} The depth in focus.
81
+ */
82
+ export function focusAt(config, t) {
83
+ const o = settings(config);
84
+ return 0.5 + 0.45 * Math.sin(2 * Math.PI * t * o.rate + o.seed * 1.7);
85
+ }
86
+
87
+ /**
88
+ * How soft a point is: nothing at the plane of focus, the widest blur well away from it.
89
+ *
90
+ * @param {Partial<PhotoBokehConfig>} config The settings.
91
+ * @param {number} depth The point's depth, 0 (far) to 1 (near).
92
+ * @param {number} t Seconds.
93
+ * @returns {number} The blur's radius, a share of the height.
94
+ */
95
+ export function blurAt(config, depth, t) {
96
+ const o = settings(config);
97
+ const d = Math.abs(depth - focusAt(config, t));
98
+ const k = Math.min(1, Math.max(0, (d - 0.04) / 0.36));
99
+ return o.blur * k * k * (3 - 2 * k);
100
+ }
101
+
102
+ /**
103
+ * Where an out-of-focus light is: rising slowly, swaying, wrapping round from the bottom.
104
+ *
105
+ * @param {Partial<PhotoBokehConfig>} config The settings.
106
+ * @param {number} i Which light.
107
+ * @param {number} t Seconds.
108
+ * @returns {{ x: number, y: number, r: number }} Its centre (0–1 from the top left of the frame) and radius (heights).
109
+ */
110
+ export function discAt(config, i, t) {
111
+ const o = settings(config);
112
+ const h = (n) => {
113
+ const s = Math.sin((i + 1) * 12.9898 + n * 78.233 + o.seed * 3.1) * 43758.5453;
114
+ return s - Math.floor(s);
115
+ };
116
+ const rise = o.drift * (0.6 + h(2) * 0.8);
117
+ const y = 1.15 - ((h(1) * 1.3 + t * rise) % 1.3);
118
+ const x = h(0) + 0.03 * Math.sin(t * 0.4 + i * 1.9);
119
+ return { x, y, r: o.size * (0.6 + h(3) * 0.8) };
120
+ }
121
+
122
+ const FRAG = `
123
+ precision highp float;
124
+ uniform vec2 uRes;
125
+ uniform float uTime;
126
+ uniform sampler2D uPhoto;
127
+ uniform vec2 uScale;
128
+ uniform float uTexH;
129
+ uniform float uReady;
130
+ uniform float uBlur;
131
+ uniform float uRate;
132
+ uniform float uNear;
133
+ uniform float uDiscs;
134
+ uniform float uSize;
135
+ uniform float uGlow;
136
+ uniform float uBlades;
137
+ uniform float uDrift;
138
+ uniform float uVignette;
139
+ uniform float uGrain;
140
+ uniform float uSeed;
141
+ uniform vec3 uTint[4];
142
+ ${GLSL_COVER}
143
+ ${GLSL_QUIET}
144
+ ${GLSL_HASH33}
145
+
146
+ // the photo at a box point (0-1, y down), read at a softness (its mipmap bias)
147
+ vec3 photo(vec2 uv, float bias) {
148
+ vec2 t = coverUv(uv, uScale);
149
+ return texture2D(uPhoto, vec2(t.x, t.y), bias).rgb;
150
+ }
151
+
152
+ // a guess at how near a point is: its blurred brightness and colour (the lit, saturated subject nearer), and its height
153
+ float depthAt(vec2 uv) {
154
+ vec3 c = photo(uv, 5.0);
155
+ float l = dot(c, vec3(0.299, 0.587, 0.114));
156
+ float sat = max(c.r, max(c.g, c.b)) - min(c.r, min(c.g, c.b));
157
+ float picture = clamp(l * 0.85 + sat * 0.6, 0.0, 1.0);
158
+ return clamp(mix(uv.y, picture, uNear), 0.0, 1.0);
159
+ }
160
+
161
+ float hash1(float n) { return fract(sin(n * 12.9898 + uSeed * 3.1) * 43758.5453); }
162
+
163
+ // one out-of-focus light: a soft, filled glow (brightest in its middle, no ring at its edge), round or six-bladed
164
+ float disc(vec2 p, vec2 c, float r) {
165
+ vec2 d = p - c;
166
+ float dist = length(d);
167
+ if (uBlades > 0.5) {
168
+ float a = atan(d.y, d.x);
169
+ float k = 3.14159265 / 6.0;
170
+ dist *= cos(k) / cos(mod(a, 2.0 * k) - k);
171
+ }
172
+ float x = dist / r;
173
+ return exp(-x * x * 1.6) * (1.0 - smoothstep(0.9, 1.3, x));
174
+ }
175
+
176
+ void main() {
177
+ vec2 px = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y);
178
+ vec2 uv = px / uRes;
179
+ float aspect = uRes.x / uRes.y;
180
+ if (uReady < 0.5) { gl_FragColor = vec4(0.0); return; }
181
+
182
+ float focus = 0.5 + 0.45 * sin(6.2831853 * uTime * uRate + uSeed * 1.7);
183
+ float depth = depthAt(uv);
184
+ float k = smoothstep(0.04, 0.4, abs(depth - focus));
185
+ float radius = uBlur * k; // heights
186
+ // a golden-angle disc of taps, read from the mipmap whose texels match their spacing
187
+ vec3 sum = vec3(0.0);
188
+ float bias = clamp(log2(max(radius * uTexH / 3.0, 1.0)), 0.0, 6.0);
189
+ const int TAPS = 20;
190
+ for (int i = 0; i < TAPS; i++) {
191
+ float f = (float(i) + 0.5) / float(TAPS);
192
+ float a = float(i) * 2.39996323;
193
+ vec2 off = vec2(cos(a), sin(a)) * sqrt(f) * radius;
194
+ off.x /= aspect;
195
+ sum += photo(uv + off, bias);
196
+ }
197
+ vec3 col = sum / float(TAPS);
198
+
199
+ // the lights drift through, tinted from the photo's highlights, added like light
200
+ vec2 p = vec2(uv.x * aspect, uv.y);
201
+ vec3 lights = vec3(0.0);
202
+ for (int i = 0; i < ${MAX_DISCS}; i++) {
203
+ if (float(i) >= uDiscs) break;
204
+ float fi = float(i) + 1.0;
205
+ float rise = uDrift * (0.6 + hash1(fi * 7.0 + 2.0) * 0.8);
206
+ float y = 1.15 - mod(hash1(fi * 7.0 + 1.0) * 1.3 + uTime * rise, 1.3);
207
+ float x = hash1(fi * 7.0) + 0.03 * sin(uTime * 0.4 + float(i) * 1.9);
208
+ float r = uSize * (0.6 + hash1(fi * 7.0 + 3.0) * 0.8);
209
+ vec3 tint = uTint[0];
210
+ if (mod(float(i), 4.0) > 0.5) tint = uTint[1];
211
+ if (mod(float(i), 4.0) > 1.5) tint = uTint[2];
212
+ if (mod(float(i), 4.0) > 2.5) tint = uTint[3];
213
+ lights += tint * disc(p, vec2(x * aspect, y), r) * (0.5 + 0.5 * hash1(fi * 7.0 + 5.0));
214
+ }
215
+ // brighter where they pass over the photo's own highlights, as light out of focus would be
216
+ float lum = dot(col, vec3(0.299, 0.587, 0.114));
217
+ col = 1.0 - (1.0 - col) * (1.0 - clamp(lights * uGlow * (0.75 + lum * 1.6), 0.0, 1.0));
218
+
219
+ // a little quieter where the copy sits, darker toward the edges, and grain
220
+ vec2 q = vec2((uv.x - 0.5) * aspect, 0.5 - uv.y);
221
+ col *= mix(1.0 - uQuiet.w * 0.45, 1.0, quietOpen(q));
222
+ float v = length((uv - 0.5) * vec2(aspect, 1.0));
223
+ col *= 1.0 - uVignette * smoothstep(0.35, 0.95, v);
224
+ col += (hash33(vec3(px, floor(uTime * 24.0))).x - 0.5) * uGrain;
225
+ gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
226
+ }
227
+ `;
228
+
229
+ /**
230
+ * A CSS `background` that stands in before the shader starts and without WebGL: the photo itself, covering.
231
+ *
232
+ * @param {Pick<PhotoBokehConfig, 'src'>} config The settings.
233
+ * @returns {string} The CSS background.
234
+ */
235
+ export function photoBokehStill(config) {
236
+ return `center / cover no-repeat url(${JSON.stringify(config.src)})`;
237
+ }
238
+
239
+ /**
240
+ * The photo's brightest, most coloured pixels, for the lights' tints: four, from a small copy of it.
241
+ *
242
+ * @param {ArrayLike<number>} rgba The small copy's pixels, RGBA 0–255.
243
+ * @returns {[number, number, number][]} Four colours, 0–1 (lightened, so a light reads as light).
244
+ */
245
+ export function highlightTints(rgba) {
246
+ const px = [];
247
+ for (let i = 0; i < rgba.length; i += 4) {
248
+ const r = rgba[i] / 255,
249
+ g = rgba[i + 1] / 255,
250
+ b = rgba[i + 2] / 255;
251
+ const l = 0.299 * r + 0.587 * g + 0.114 * b;
252
+ const sat = Math.max(r, g, b) - Math.min(r, g, b);
253
+ px.push({ c: [r, g, b], score: l + sat * 0.6 });
254
+ }
255
+ px.sort((a, b) => b.score - a.score);
256
+ const picks = [];
257
+ for (const p of px) {
258
+ if (picks.length === 4) break;
259
+ if (picks.every((q) => Math.hypot(q[0] - p.c[0], q[1] - p.c[1], q[2] - p.c[2]) > 0.18)) picks.push(p.c);
260
+ }
261
+ while (picks.length < 4) picks.push(picks[0] ?? [1, 0.9, 0.8]);
262
+ return picks.map((c) => /** @type {[number, number, number]} */ (c.map((v) => Math.min(1, v * 0.6 + 0.4))));
263
+ }
264
+
265
+ /**
266
+ * Starts the rack focus on an element: a canvas inside it (its first), the photo loaded from `src`.
267
+ *
268
+ * @param {HTMLElement} el The element.
269
+ * @param {PhotoBokehConfig} config The settings.
270
+ * @returns {() => void} Stops it.
271
+ */
272
+ export function photoBokeh(el, config) {
273
+ const o = settings(config);
274
+ const start = performance.now();
275
+ let ready = false;
276
+ let imageAspect = 1;
277
+ let aspect = 0.8;
278
+ let texH = 512;
279
+ let tints = new Float32Array([1, 0.9, 0.85, 1, 0.8, 0.8, 0.9, 0.9, 1, 1, 1, 1]);
280
+ /** @type {WebGLTexture | null} */
281
+ let texture = null;
282
+
283
+ const { stage, stop } = createStage(el, {
284
+ fragment: FRAG,
285
+ alpha: true,
286
+ still: o.speed <= 0,
287
+ setup({ gl, uniform }) {
288
+ gl.uniform1i(uniform('uPhoto'), 0);
289
+ gl.uniform1f(uniform('uBlur'), o.blur);
290
+ gl.uniform1f(uniform('uRate'), o.rate);
291
+ gl.uniform1f(uniform('uNear'), o.near);
292
+ gl.uniform1f(uniform('uDiscs'), Math.min(MAX_DISCS, Math.max(0, o.discs)));
293
+ gl.uniform1f(uniform('uSize'), o.size);
294
+ gl.uniform1f(uniform('uGlow'), o.glow);
295
+ gl.uniform1f(uniform('uBlades'), o.shape === 'blades' ? 1 : 0);
296
+ gl.uniform1f(uniform('uDrift'), o.drift);
297
+ gl.uniform1f(uniform('uVignette'), o.vignette);
298
+ gl.uniform1f(uniform('uGrain'), o.grain);
299
+ gl.uniform1f(uniform('uSeed'), o.seed);
300
+ return () => gl.deleteTexture(texture);
301
+ },
302
+ resize({ gl, uniform, canvas }) {
303
+ aspect = canvas.width / canvas.height;
304
+ gl.uniform2fv(uniform('uScale'), coverScale(imageAspect, aspect));
305
+ gl.uniform4f(uniform('uQuiet'), ...quietUniform(config.quiet, aspect));
306
+ },
307
+ uniforms({ gl, uniform }, now) {
308
+ gl.uniform1f(uniform('uTime'), ((now - start) / 1000) * Math.max(0, o.speed));
309
+ gl.uniform1f(uniform('uReady'), ready ? 1 : 0);
310
+ gl.uniform1f(uniform('uTexH'), texH);
311
+ gl.uniform3fv(uniform('uTint[0]'), tints);
312
+ if (texture) {
313
+ gl.activeTexture(gl.TEXTURE0);
314
+ gl.bindTexture(gl.TEXTURE_2D, texture);
315
+ }
316
+ },
317
+ });
318
+ if (!stage) return stop;
319
+
320
+ let alive = true;
321
+ loadImage(o.src)
322
+ .then((image) => {
323
+ if (!alive) return;
324
+ const { gl, uniform, program } = stage;
325
+ gl.activeTexture(gl.TEXTURE0);
326
+ texture = imageTexture(gl, image, { mipmap: true });
327
+ imageAspect = image.naturalWidth / image.naturalHeight;
328
+ texH = image.naturalHeight;
329
+ // the lights take the photo's highlights
330
+ const small = document.createElement('canvas');
331
+ small.width = 24;
332
+ small.height = 24;
333
+ const s = small.getContext('2d', { willReadFrequently: true });
334
+ if (s) {
335
+ s.drawImage(image, 0, 0, 24, 24);
336
+ tints = new Float32Array(highlightTints(s.getImageData(0, 0, 24, 24).data).flat());
337
+ }
338
+ gl.useProgram(program);
339
+ gl.uniform2fv(uniform('uScale'), coverScale(imageAspect, aspect));
340
+ ready = true;
341
+ stage.redraw();
342
+ })
343
+ .catch((error) => {
344
+ // the still stays
345
+ console.warn('[effects-astro]', error);
346
+ });
347
+ return () => {
348
+ alive = false;
349
+ stop();
350
+ };
351
+ }
@@ -0,0 +1,25 @@
1
+ /** Turns sharing on (or off) for stages started from now on: they draw in one hidden WebGL context and copy each frame into their own canvas. Off by default. */
2
+ export function shareContexts(on?: boolean): void;
3
+ /** Whether new stages share the one context. */
4
+ export function sharingContexts(): boolean;
5
+ /** The most a side of the hidden canvas grows to. */
6
+ export const HOST_MAX: number;
7
+ /** A tracked view of a context: the state its caller sets and the resources it makes are remembered. */
8
+ export function trackGL(gl: any): {
9
+ gl: any;
10
+ state: object;
11
+ /** The context put back to its defaults. */
12
+ reset(): void;
13
+ /** This view's state laid on again. */
14
+ replay(): void;
15
+ /** This view's resources deleted. */
16
+ dispose(): void;
17
+ };
18
+ /** A stage's place in the shared context, or null without WebGL (or when its canvas has a WebGL context already). */
19
+ export function sharedPlace(canvas: HTMLCanvasElement): {
20
+ gl: any;
21
+ begin(w: number, h: number): void;
22
+ opaque(): void;
23
+ end(w: number, h: number): void;
24
+ dispose(): void;
25
+ } | null;
@@ -0,0 +1,229 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/shared-gl
3
+ *
4
+ * One WebGL context for many effects. A browser keeps about sixteen WebGL
5
+ * contexts and drops the oldest past that, so a wall of thirty live cards,
6
+ * each with its own, can only run half of them. With `shareContexts()` on,
7
+ * every stage (./stage.js) draws in one hidden context instead and copies
8
+ * its frame into its own canvas (a Canvas 2D one) with `drawImage`, so any
9
+ * number can run; only what is on the screen draws.
10
+ *
11
+ * Effects written for a context of their own keep working: each stage gets
12
+ * a tracked view of the shared context (`trackGL`) that remembers the state
13
+ * it set (capabilities, blending, pixel storage, the texture bound to each
14
+ * unit) and the resources it made. Before a stage draws, the context is put
15
+ * back to its defaults and that stage's state laid on again; when the stage
16
+ * stops, its resources are deleted. It is off by default: an effect on its
17
+ * own page keeps a context of its own.
18
+ */
19
+
20
+ import { getContext } from './gl.js';
21
+
22
+ /** Whether new stages share the one context. */
23
+ let sharing = false;
24
+
25
+ /**
26
+ * Turns sharing on (or off) for stages started from now on.
27
+ *
28
+ * @param {boolean} [on=true] Share.
29
+ */
30
+ export function shareContexts(on = true) {
31
+ sharing = on;
32
+ }
33
+
34
+ /** @returns {boolean} Whether new stages share the one context. */
35
+ export const sharingContexts = () => sharing;
36
+
37
+ /** The most a side of the hidden canvas grows to (a card is far smaller). */
38
+ export const HOST_MAX = 4096;
39
+
40
+ /** The capabilities put back to off before each stage draws. */
41
+ const CAPS = ['BLEND', 'DEPTH_TEST', 'CULL_FACE', 'SCISSOR_TEST', 'STENCIL_TEST', 'POLYGON_OFFSET_FILL', 'SAMPLE_ALPHA_TO_COVERAGE'];
42
+
43
+ /** Calls whose last arguments are the state they set (laid on again before a stage draws). */
44
+ const STATE_CALLS = ['blendFunc', 'blendFuncSeparate', 'blendEquation', 'blendEquationSeparate', 'blendColor', 'depthFunc', 'depthMask', 'cullFace', 'frontFace', 'polygonOffset'];
45
+
46
+ /** What a stage's resources are deleted with. */
47
+ const DELETERS = {
48
+ createTexture: 'deleteTexture',
49
+ createBuffer: 'deleteBuffer',
50
+ createFramebuffer: 'deleteFramebuffer',
51
+ createRenderbuffer: 'deleteRenderbuffer',
52
+ createProgram: 'deleteProgram',
53
+ createShader: 'deleteShader',
54
+ createVertexArray: 'deleteVertexArray',
55
+ };
56
+
57
+ /**
58
+ * A tracked view of a context: calls go straight through, but the state the
59
+ * caller sets and the resources it makes are remembered, so its state can be
60
+ * laid on again after another user changed it, and its resources freed.
61
+ *
62
+ * @param {any} gl The real context.
63
+ * @returns {{ gl: any, reset: () => void, replay: () => void, dispose: () => void, state: object }} The view
64
+ * (`gl`), the context put back to its defaults (`reset`), this view's state laid on (`replay`), and its
65
+ * resources deleted (`dispose`).
66
+ */
67
+ export function trackGL(gl) {
68
+ const state = {
69
+ /** @type {Map<number, boolean>} */
70
+ caps: new Map(),
71
+ /** @type {Map<string, any[]>} */
72
+ calls: new Map(),
73
+ /** @type {Map<number, number>} */
74
+ store: new Map(),
75
+ /** @type {Map<number, Map<number, any>>} unit → target → texture */
76
+ units: new Map(),
77
+ active: gl.TEXTURE0,
78
+ /** @type {[string, any][]} */
79
+ made: [],
80
+ };
81
+ /** @type {Map<PropertyKey, Function>} */
82
+ const bound = new Map();
83
+ const wrap = (name, fn) => {
84
+ if (name === 'enable' || name === 'disable')
85
+ return (cap) => {
86
+ state.caps.set(cap, name === 'enable');
87
+ return fn.call(gl, cap);
88
+ };
89
+ if (STATE_CALLS.includes(name))
90
+ return (...args) => {
91
+ state.calls.set(name, args);
92
+ // a blend set one way forgets the other way's
93
+ if (name === 'blendFunc') state.calls.delete('blendFuncSeparate');
94
+ if (name === 'blendFuncSeparate') state.calls.delete('blendFunc');
95
+ if (name === 'blendEquation') state.calls.delete('blendEquationSeparate');
96
+ if (name === 'blendEquationSeparate') state.calls.delete('blendEquation');
97
+ return fn.apply(gl, args);
98
+ };
99
+ if (name === 'pixelStorei')
100
+ return (pname, value) => {
101
+ state.store.set(pname, value);
102
+ return fn.call(gl, pname, value);
103
+ };
104
+ if (name === 'activeTexture')
105
+ return (unit) => {
106
+ state.active = unit;
107
+ return fn.call(gl, unit);
108
+ };
109
+ if (name === 'bindTexture')
110
+ return (target, texture) => {
111
+ if (!state.units.has(state.active)) state.units.set(state.active, new Map());
112
+ state.units.get(state.active).set(target, texture);
113
+ return fn.call(gl, target, texture);
114
+ };
115
+ if (name in DELETERS)
116
+ return (...args) => {
117
+ const made = fn.apply(gl, args);
118
+ if (made) state.made.push([name, made]);
119
+ return made;
120
+ };
121
+ return fn.bind(gl);
122
+ };
123
+ const view = new Proxy(gl, {
124
+ get(target, key) {
125
+ const value = target[key];
126
+ if (typeof value !== 'function') return value;
127
+ if (!bound.has(key)) bound.set(key, wrap(String(key), value));
128
+ return bound.get(key);
129
+ },
130
+ });
131
+ return {
132
+ gl: view,
133
+ state,
134
+ reset() {
135
+ for (const cap of CAPS) if (gl[cap] !== undefined) gl.disable(gl[cap]);
136
+ gl.blendFunc(gl.ONE, gl.ZERO);
137
+ gl.blendEquation(gl.FUNC_ADD);
138
+ gl.depthMask(true);
139
+ gl.colorMask(true, true, true, true);
140
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
141
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
142
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
143
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
144
+ },
145
+ replay() {
146
+ for (const [cap, on] of state.caps) (on ? gl.enable : gl.disable).call(gl, cap);
147
+ for (const [name, args] of state.calls) gl[name](...args);
148
+ for (const [pname, value] of state.store) gl.pixelStorei(pname, value);
149
+ for (const [unit, targets] of state.units) {
150
+ gl.activeTexture(unit);
151
+ for (const [target, texture] of targets) gl.bindTexture(target, texture);
152
+ }
153
+ gl.activeTexture(state.active);
154
+ },
155
+ dispose() {
156
+ for (const [name, made] of state.made.splice(0)) {
157
+ const del = gl[DELETERS[name]];
158
+ if (typeof del === 'function') del.call(gl, made);
159
+ }
160
+ state.units.clear();
161
+ },
162
+ };
163
+ }
164
+
165
+ /** The hidden canvas and its context, made on first use. */
166
+ let host = null;
167
+
168
+ /**
169
+ * The shared context, made on first use (null without WebGL, or once it was lost).
170
+ *
171
+ * @returns {{ canvas: HTMLCanvasElement, gl: any } | null} The hidden canvas and its context.
172
+ */
173
+ function hostContext() {
174
+ if (host) return host.lost ? null : host;
175
+ const canvas = document.createElement('canvas');
176
+ canvas.width = canvas.height = 1;
177
+ const gl = getContext(canvas, { alpha: true, premultipliedAlpha: true, antialias: false });
178
+ if (!gl) return null;
179
+ host = { canvas, gl, lost: false };
180
+ canvas.addEventListener('webglcontextlost', () => {
181
+ if (host) host.lost = true;
182
+ });
183
+ return host;
184
+ }
185
+
186
+ /**
187
+ * A stage's place in the shared context: its tracked view of the context, and
188
+ * the steps around each of its frames (`begin`: the hidden canvas big enough,
189
+ * the context in this stage's state; `end`: the frame copied into the stage's
190
+ * own canvas). Null when there is no WebGL, or the stage's canvas can't take
191
+ * a Canvas 2D context (it has a WebGL one already).
192
+ *
193
+ * @param {HTMLCanvasElement} canvas The stage's own canvas.
194
+ * @returns {{ gl: any, begin: (w: number, h: number) => void, end: (w: number, h: number) => void, opaque: () => void, dispose: () => void } | null} The place.
195
+ */
196
+ export function sharedPlace(canvas) {
197
+ const h = hostContext();
198
+ if (!h) return null;
199
+ const out = canvas.getContext('2d');
200
+ if (!out) return null;
201
+ const view = trackGL(h.gl);
202
+ const { gl } = h;
203
+ return {
204
+ gl: view.gl,
205
+ begin(w, hgt) {
206
+ const W = Math.min(HOST_MAX, Math.max(h.canvas.width, w)),
207
+ H = Math.min(HOST_MAX, Math.max(h.canvas.height, hgt));
208
+ if (W !== h.canvas.width || H !== h.canvas.height) {
209
+ h.canvas.width = W;
210
+ h.canvas.height = H;
211
+ }
212
+ view.reset();
213
+ view.replay();
214
+ },
215
+ /** For an opaque stage: the alpha is 1 and stays 1, whatever the shader writes. */
216
+ opaque() {
217
+ gl.clearColor(0, 0, 0, 1);
218
+ gl.clear(gl.COLOR_BUFFER_BIT);
219
+ gl.colorMask(true, true, true, false);
220
+ },
221
+ end(w, hgt) {
222
+ gl.colorMask(true, true, true, true);
223
+ out.globalCompositeOperation = 'copy';
224
+ // the frame was drawn at the bottom left of the hidden canvas (WebGL's origin)
225
+ out.drawImage(h.canvas, 0, h.canvas.height - hgt, w, hgt, 0, 0, w, hgt);
226
+ },
227
+ dispose: () => view.dispose(),
228
+ };
229
+ }
@@ -14,6 +14,7 @@
14
14
  */
15
15
 
16
16
  import { getContext, createProgram, bindTriangle } from './gl.js';
17
+ import { sharingContexts, sharedPlace } from './shared-gl.js';
17
18
  import { pixelRatio, prefersReducedMotion } from './device.js';
18
19
  import { animate } from './loop.js';
19
20
 
@@ -71,11 +72,16 @@ void main() { gl_Position = vec4(p, 0.0, 1.0); }
71
72
  export function createStage(el, options) {
72
73
  const { fragment, alpha = true, scale = 1, webgl1 = true, adaptive = true, antialias = false } = options;
73
74
  const canvas = el.querySelector('canvas');
74
- const gl = canvas && getContext(canvas, { alpha, premultipliedAlpha: true, antialias }, webgl1);
75
+ // with shareContexts() on (./shared-gl.js), the effect draws in the one shared context and copies each frame into
76
+ // its own canvas; a multisampled effect keeps a context of its own (the shared one isn't)
77
+ const place = canvas && sharingContexts() && !antialias ? sharedPlace(canvas) : null;
78
+ const gl = place ? place.gl : canvas && getContext(canvas, { alpha, premultipliedAlpha: true, antialias }, webgl1);
75
79
  const compiled = gl && createProgram(gl, options.vertex ?? CLIP, fragment);
80
+ /** Gives the context back: a context of its own is lost; a shared place deletes what it made. */
81
+ const giveBack = () => (place ? place.dispose() : gl?.getExtension('WEBGL_lose_context')?.loseContext());
76
82
  if (!canvas || !gl || !compiled) {
77
83
  canvas?.remove();
78
- gl?.getExtension('WEBGL_lose_context')?.loseContext();
84
+ giveBack();
79
85
  return { stage: null, stop: () => {} };
80
86
  }
81
87
  const triangle = bindTriangle(gl);
@@ -122,6 +128,7 @@ export function createStage(el, options) {
122
128
  * @param {number} dt Seconds since the last frame.
123
129
  */
124
130
  const render = (now, dt) => {
131
+ place?.begin(canvas.width, canvas.height);
125
132
  options.update?.(stage, now, dt);
126
133
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);
127
134
  gl.viewport(0, 0, canvas.width, canvas.height);
@@ -132,9 +139,10 @@ export function createStage(el, options) {
132
139
  if (alpha) {
133
140
  gl.clearColor(0, 0, 0, 0);
134
141
  gl.clear(gl.COLOR_BUFFER_BIT);
135
- }
142
+ } else place?.opaque();
136
143
  gl.drawArrays(gl.TRIANGLES, 0, 3);
137
144
  options.after?.(stage, now, dt);
145
+ place?.end(canvas.width, canvas.height);
138
146
  if (adaptive && dt > 0) adapt(dt);
139
147
  };
140
148
 
@@ -149,12 +157,13 @@ export function createStage(el, options) {
149
157
  redraw: () => render(performance.now(), 0),
150
158
  };
151
159
 
160
+ place?.begin(1, 1);
152
161
  gl.useProgram(compiled.program);
153
162
  const cleanup = options.setup?.(stage);
154
163
  if (cleanup === false) {
155
164
  // It cannot run here: the canvas goes, and its GPU context with it.
156
165
  canvas.remove();
157
- gl.getExtension('WEBGL_lose_context')?.loseContext();
166
+ giveBack();
158
167
  return { stage: null, stop: () => {} };
159
168
  }
160
169
  gl.useProgram(compiled.program);
@@ -164,6 +173,7 @@ export function createStage(el, options) {
164
173
  stage.ratio = pixelRatio(scale) * quality.share;
165
174
  canvas.width = Math.max(1, Math.round(el.clientWidth * stage.ratio));
166
175
  canvas.height = Math.max(1, Math.round(el.clientHeight * stage.ratio));
176
+ place?.begin(canvas.width, canvas.height);
167
177
  gl.useProgram(compiled.program);
168
178
  options.resize?.(stage);
169
179
  if (stage.still) stage.redraw();
@@ -180,8 +190,10 @@ export function createStage(el, options) {
180
190
  resizer.disconnect();
181
191
  cleanup?.();
182
192
  // Gone from the page: give the GPU context back now rather than
183
- // whenever it is collected, as a browser keeps only so many.
184
- if (!el.isConnected) gl.getExtension('WEBGL_lose_context')?.loseContext();
193
+ // whenever it is collected, as a browser keeps only so many. A
194
+ // shared place always gives back what it made (the context stays).
195
+ if (place) place.dispose();
196
+ else if (!el.isConnected) gl.getExtension('WEBGL_lose_context')?.loseContext();
185
197
  },
186
198
  };
187
199
  }