@crossworks/share-ui 0.300.143 → 0.400.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.
@@ -0,0 +1,783 @@
1
+ import { parseColor, rgbToOklab, type Lab, type Rgb } from './color';
2
+ import {
3
+ DRIFT_MAX_COLORS,
4
+ DRIFT_STYLE_RESOLUTION,
5
+ mulberry32,
6
+ normalizeDriftOptions,
7
+ type DriftColor,
8
+ type DriftOptions,
9
+ type DriftStyle,
10
+ } from './options';
11
+ import { COMPOSITE_SHADER, VERTEX_SHADER, fieldShader } from './shaders';
12
+
13
+ /**
14
+ * Drift — an animated gradient background engine. Framework-free on purpose:
15
+ * the React shell and a plain-script page (the /s reader) drive the same code.
16
+ *
17
+ * Where the frame budget goes, and where it does not:
18
+ *
19
+ * - No geometry. One fullscreen triangle per pass; every style is a pure
20
+ * function of (position, time). Neat displaces a 240×240 mesh per frame.
21
+ * - The field is computed at `resolution` × CSS size (0.2–0.35 by style:
22
+ * 8–25× fewer pixels) into a half-float texture where available, filtered up,
23
+ * then dithered at output size — no banding, no visible softness, because
24
+ * a gradient has no detail to lose.
25
+ * - The output canvas is capped at `maxDpr` (1): retina buys nothing for a
26
+ * filter-up and costs 4× the fill.
27
+ * - A `low-power` opaque context: laptops stay on the integrated GPU, and the
28
+ * compositor skips alpha blending the layer.
29
+ * - Frames only while they can be seen: off-screen (IntersectionObserver),
30
+ * hidden tab, speed 0 and prefers-reduced-motion all stop the loop
31
+ * entirely — a still background renders exactly once per change.
32
+ * - Frame cap (30 by default) and adaptive resolution when frames run late.
33
+ * - Option changes are uniform writes, never a context rebuild; a style
34
+ * switch compiles once and is cached. `destroy` releases the context
35
+ * immediately rather than waiting for GC (browsers cap live contexts).
36
+ */
37
+
38
+ export type DriftStats = {
39
+ /** Rendered frames per second over the last second. */
40
+ fps: number;
41
+ /** Field texture size, px. */
42
+ fieldWidth: number;
43
+ fieldHeight: number;
44
+ /** Output canvas size, px. */
45
+ outputWidth: number;
46
+ outputHeight: number;
47
+ /** Current effective resolution after adaptive drops. */
48
+ resolution: number;
49
+ /** Whether the field texture is half-float (band-free) or 8-bit. */
50
+ halfFloat: boolean;
51
+ /** Whether the loop is currently scheduling frames. */
52
+ animating: boolean;
53
+ };
54
+
55
+ export type DriftHandle = {
56
+ /** Merge new options. Cheap: uniforms only, or one cached program swap. */
57
+ update: (next: Partial<DriftOptions>) => void;
58
+ /** Draw one frame now — e.g. after the page's theme changed while still. */
59
+ redraw: () => void;
60
+ pause: () => void;
61
+ resume: () => void;
62
+ destroy: () => void;
63
+ stats: () => DriftStats;
64
+ };
65
+
66
+ type Gl = WebGLRenderingContext | WebGL2RenderingContext;
67
+
68
+ type FieldProgram = {
69
+ program: WebGLProgram;
70
+ u: Record<string, WebGLUniformLocation | null>;
71
+ };
72
+
73
+ const FIELD_UNIFORMS = [
74
+ 'u_res',
75
+ 'u_time',
76
+ 'u_scale',
77
+ 'u_warp',
78
+ 'u_soft',
79
+ 'u_light',
80
+ 'u_sat',
81
+ 'u_rot',
82
+ 'u_ptr',
83
+ 'u_bg',
84
+ 'u_col',
85
+ 'u_w',
86
+ 'u_stop',
87
+ 'u_ph',
88
+ ] as const;
89
+
90
+ const COMPOSITE_UNIFORMS = [
91
+ 'u_tex',
92
+ 'u_out',
93
+ 'u_px',
94
+ 'u_grain',
95
+ 'u_gseed',
96
+ 'u_vig',
97
+ 'u_bgs',
98
+ ] as const;
99
+
100
+ /** Longest side of the field texture. Past this nothing improves. */
101
+ const FIELD_MAX = 1024;
102
+
103
+ function compile(gl: Gl, type: number, source: string): WebGLShader | null {
104
+ const shader = gl.createShader(type);
105
+ if (!shader) return null;
106
+ gl.shaderSource(shader, source);
107
+ gl.compileShader(shader);
108
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS) && !gl.isContextLost()) {
109
+ console.error('[drift] shader:', gl.getShaderInfoLog(shader));
110
+ gl.deleteShader(shader);
111
+ return null;
112
+ }
113
+ return shader;
114
+ }
115
+
116
+ function link(gl: Gl, fragment: string): WebGLProgram | null {
117
+ const vs = compile(gl, gl.VERTEX_SHADER, VERTEX_SHADER);
118
+ const fs = compile(gl, gl.FRAGMENT_SHADER, fragment);
119
+ if (!vs || !fs) return null;
120
+ const program = gl.createProgram();
121
+ if (!program) return null;
122
+ gl.attachShader(program, vs);
123
+ gl.attachShader(program, fs);
124
+ gl.bindAttribLocation(program, 0, 'a_pos');
125
+ gl.linkProgram(program);
126
+ gl.deleteShader(vs);
127
+ gl.deleteShader(fs);
128
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS) && !gl.isContextLost()) {
129
+ console.error('[drift] link:', gl.getProgramInfoLog(program));
130
+ gl.deleteProgram(program);
131
+ return null;
132
+ }
133
+ return program;
134
+ }
135
+
136
+ function locate<T extends string>(gl: Gl, program: WebGLProgram, names: readonly T[]) {
137
+ const out = {} as Record<T, WebGLUniformLocation | null>;
138
+ for (const name of names) {
139
+ // Arrays are addressed by their first element.
140
+ out[name] =
141
+ gl.getUniformLocation(program, name) ?? gl.getUniformLocation(program, `${name}[0]`);
142
+ }
143
+ return out;
144
+ }
145
+
146
+ /** Everything the field shader needs that only changes with the options. */
147
+ type Derived = {
148
+ bg: Lab;
149
+ bgSrgb: [number, number, number];
150
+ col: Float32Array; // 6 × vec3
151
+ w: Float32Array; // 6
152
+ stop: Float32Array; // 6
153
+ ph: Float32Array; // 6 × vec4
154
+ timeOffset: number;
155
+ grainSeed: number;
156
+ /** False when the ground or every colour failed to parse: paint NOTHING
157
+ * (the element's own surface shows) rather than a guessed palette. */
158
+ paintable: boolean;
159
+ };
160
+
161
+ function derive(o: DriftOptions): Derived {
162
+ const fallback: Rgb = [0, 0, 0];
163
+ const bgParsed = parseColor(o.background);
164
+ const bgRgb = bgParsed ?? fallback;
165
+ const entries = o.colors
166
+ .map((c) => (typeof c === 'string' ? { color: c } : c) as DriftColor)
167
+ .map((c) => ({ rgb: parseColor(c.color), weight: Math.max(0, Math.min(2, c.weight ?? 1)) }))
168
+ .filter((c): c is { rgb: Rgb; weight: number } => c.rgb !== null);
169
+
170
+ const col = new Float32Array(DRIFT_MAX_COLORS * 3);
171
+ const w = new Float32Array(DRIFT_MAX_COLORS);
172
+ const stop = new Float32Array(DRIFT_MAX_COLORS);
173
+ const ph = new Float32Array(DRIFT_MAX_COLORS * 4);
174
+
175
+ // Band centres along 0..1 from cumulative weight: a heavier colour claims a
176
+ // wider band (silk, marble), a thicker layer (dunes), a wider lane (aurora).
177
+ const total = entries.reduce((s, e) => s + e.weight, 0) || 1;
178
+ let cum = 0;
179
+ entries.forEach((e, i) => {
180
+ const lab = rgbToOklab(e.rgb);
181
+ col.set(lab, i * 3);
182
+ w[i] = e.weight;
183
+ stop[i] = (cum + e.weight / 2) / total;
184
+ cum += e.weight;
185
+ });
186
+
187
+ // Seeded phases. xy is a home position spread around a jittered ring so the
188
+ // mesh never clumps; zw are rates/phases in 0..1.
189
+ const rnd = mulberry32(o.seed);
190
+ const n = Math.max(1, entries.length);
191
+ const turn = rnd() * Math.PI * 2;
192
+ for (let i = 0; i < DRIFT_MAX_COLORS; i++) {
193
+ const a = turn + (i / n) * Math.PI * 2 + (rnd() - 0.5) * 0.9;
194
+ const r = 0.35 + rnd() * 0.5;
195
+ ph.set([Math.cos(a) * r, Math.sin(a) * r, rnd(), rnd()], i * 4);
196
+ }
197
+
198
+ return {
199
+ bg: rgbToOklab(bgRgb),
200
+ bgSrgb: [bgRgb[0] / 255, bgRgb[1] / 255, bgRgb[2] / 255],
201
+ col,
202
+ w,
203
+ stop,
204
+ ph,
205
+ timeOffset: rnd() * 200,
206
+ grainSeed: Math.floor(rnd() * 1000),
207
+ paintable: bgParsed !== null && entries.length > 0,
208
+ };
209
+ }
210
+
211
+ /** A frame gap longer than this is the main thread or the tab, not the GPU. */
212
+ const JANK_GAP_MS = 100;
213
+ /** On-time measurement windows (45 frames each) before the field grows back. */
214
+ const GROW_BACK_WINDOWS = 4;
215
+ /** Engine seconds per half-period of the time fold (fp32 keeps ~0.5 ms here). */
216
+ export const TIME_FOLD = 4096;
217
+
218
+ /** Engine time folded into 0..TIME_FOLD as a triangle wave: continuous, so
219
+ * no frame ever jumps, and bounded, so the shader's fp32 clock stays exact. */
220
+ export function foldTime(t: number): number {
221
+ const p = t % (TIME_FOLD * 2);
222
+ return p <= TIME_FOLD ? p : TIME_FOLD * 2 - p;
223
+ }
224
+
225
+ /**
226
+ * Start a Drift background on `canvas` (sized by CSS — it fills whatever box
227
+ * it is given). Returns null when WebGL is unavailable; the element's own
228
+ * background colour is the designed fallback.
229
+ */
230
+ export function createDrift(
231
+ canvas: HTMLCanvasElement,
232
+ initial: Partial<DriftOptions>,
233
+ ): DriftHandle | null {
234
+ let opts = normalizeDriftOptions(initial);
235
+ let derived = derive(opts);
236
+
237
+ const attrs: WebGLContextAttributes = {
238
+ alpha: false,
239
+ antialias: false,
240
+ depth: false,
241
+ stencil: false,
242
+ premultipliedAlpha: false,
243
+ preserveDrawingBuffer: false,
244
+ powerPreference: 'low-power',
245
+ };
246
+ const gl: Gl | null =
247
+ (canvas.getContext('webgl2', attrs) as WebGL2RenderingContext | null) ??
248
+ (canvas.getContext('webgl', attrs) as WebGLRenderingContext | null);
249
+ if (!gl) return null;
250
+ const isGl2 =
251
+ typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
252
+
253
+ // ---- GL resources (rebuilt on context restore) -------------------------
254
+ let vbo: WebGLBuffer | null = null;
255
+ let fieldTex: WebGLTexture | null = null;
256
+ let fbo: WebGLFramebuffer | null = null;
257
+ let composite: FieldProgram | null = null;
258
+ const programs = new Map<DriftStyle, FieldProgram | null>();
259
+ let halfFloat = false;
260
+ let texType: number = gl.UNSIGNED_BYTE;
261
+ let texInternal: number = gl.RGBA;
262
+
263
+ function pickTextureFormat() {
264
+ halfFloat = false;
265
+ texType = gl!.UNSIGNED_BYTE;
266
+ texInternal = gl!.RGBA;
267
+ if (isGl2) {
268
+ const g2 = gl as WebGL2RenderingContext;
269
+ if (
270
+ g2.getExtension('EXT_color_buffer_float') ||
271
+ g2.getExtension('EXT_color_buffer_half_float')
272
+ ) {
273
+ halfFloat = true;
274
+ texType = g2.HALF_FLOAT;
275
+ texInternal = g2.RGBA16F;
276
+ }
277
+ } else {
278
+ const hf = gl!.getExtension('OES_texture_half_float');
279
+ const lin = gl!.getExtension('OES_texture_half_float_linear');
280
+ const cb = gl!.getExtension('EXT_color_buffer_half_float');
281
+ if (hf && lin && cb) {
282
+ halfFloat = true;
283
+ texType = hf.HALF_FLOAT_OES;
284
+ }
285
+ }
286
+ }
287
+
288
+ function program(style: DriftStyle): FieldProgram | null {
289
+ if (programs.has(style)) return programs.get(style) ?? null;
290
+ const p = link(gl!, fieldShader(style));
291
+ const entry = p ? { program: p, u: locate(gl!, p, FIELD_UNIFORMS) } : null;
292
+ programs.set(style, entry);
293
+ return entry;
294
+ }
295
+
296
+ function initGl(): boolean {
297
+ pickTextureFormat();
298
+ vbo = gl!.createBuffer();
299
+ gl!.bindBuffer(gl!.ARRAY_BUFFER, vbo);
300
+ gl!.bufferData(gl!.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl!.STATIC_DRAW);
301
+ gl!.enableVertexAttribArray(0);
302
+ gl!.vertexAttribPointer(0, 2, gl!.FLOAT, false, 0, 0);
303
+ const cp = link(gl!, COMPOSITE_SHADER);
304
+ if (!cp) return false;
305
+ composite = { program: cp, u: locate(gl!, cp, COMPOSITE_UNIFORMS) };
306
+ fieldTex = gl!.createTexture();
307
+ fbo = gl!.createFramebuffer();
308
+ programs.clear();
309
+ fieldW = 0; // force a texture allocation on next resize
310
+ return program(opts.style) !== null;
311
+ }
312
+
313
+ function freeGl() {
314
+ for (const p of programs.values()) if (p) gl!.deleteProgram(p.program);
315
+ programs.clear();
316
+ if (composite) gl!.deleteProgram(composite.program);
317
+ if (vbo) gl!.deleteBuffer(vbo);
318
+ if (fieldTex) gl!.deleteTexture(fieldTex);
319
+ if (fbo) gl!.deleteFramebuffer(fbo);
320
+ composite = null;
321
+ vbo = fieldTex = fbo = null;
322
+ }
323
+
324
+ // ---- sizing --------------------------------------------------------------
325
+ // Hidden BEFORE the size read below: that read forces a style pass, so the
326
+ // first frame's opacity change has a computed 0 to transition from.
327
+ if (opts.fadeIn > 0) {
328
+ canvas.style.opacity = '0';
329
+ canvas.style.transition = `opacity ${opts.fadeIn}ms ease-out`;
330
+ }
331
+ let cssW = canvas.clientWidth;
332
+ let cssH = canvas.clientHeight;
333
+ // Nothing is drawn until the box has a real size: a zero-size first layout
334
+ // would otherwise paint a 1×1 frame and fade in one flat colour.
335
+ const hasSize = () => cssW > 0 && cssH > 0;
336
+ let fieldW = 0;
337
+ let fieldH = 0;
338
+ let adaptiveScale = 1;
339
+
340
+ function allocField(w: number, h: number) {
341
+ gl!.bindTexture(gl!.TEXTURE_2D, fieldTex);
342
+ gl!.texParameteri(gl!.TEXTURE_2D, gl!.TEXTURE_MIN_FILTER, gl!.LINEAR);
343
+ gl!.texParameteri(gl!.TEXTURE_2D, gl!.TEXTURE_MAG_FILTER, gl!.LINEAR);
344
+ gl!.texParameteri(gl!.TEXTURE_2D, gl!.TEXTURE_WRAP_S, gl!.CLAMP_TO_EDGE);
345
+ gl!.texParameteri(gl!.TEXTURE_2D, gl!.TEXTURE_WRAP_T, gl!.CLAMP_TO_EDGE);
346
+ gl!.texImage2D(gl!.TEXTURE_2D, 0, texInternal, w, h, 0, gl!.RGBA, texType, null);
347
+ gl!.bindFramebuffer(gl!.FRAMEBUFFER, fbo);
348
+ gl!.framebufferTexture2D(gl!.FRAMEBUFFER, gl!.COLOR_ATTACHMENT0, gl!.TEXTURE_2D, fieldTex, 0);
349
+ if (halfFloat && gl!.checkFramebufferStatus(gl!.FRAMEBUFFER) !== gl!.FRAMEBUFFER_COMPLETE) {
350
+ // Advertised but not renderable on this driver: fall back to 8-bit
351
+ // (the composite dither still hides the steps).
352
+ halfFloat = false;
353
+ texType = gl!.UNSIGNED_BYTE;
354
+ texInternal = gl!.RGBA;
355
+ gl!.texImage2D(gl!.TEXTURE_2D, 0, gl!.RGBA, w, h, 0, gl!.RGBA, gl!.UNSIGNED_BYTE, null);
356
+ }
357
+ gl!.bindFramebuffer(gl!.FRAMEBUFFER, null);
358
+ }
359
+
360
+ const baseResolution = () => opts.resolution || DRIFT_STYLE_RESOLUTION[opts.style];
361
+
362
+ function applySize() {
363
+ const dpr = Math.min(window.devicePixelRatio || 1, opts.maxDpr);
364
+ const outW = Math.max(1, Math.round(cssW * dpr));
365
+ const outH = Math.max(1, Math.round(cssH * dpr));
366
+ if (canvas.width !== outW || canvas.height !== outH) {
367
+ canvas.width = outW;
368
+ canvas.height = outH;
369
+ }
370
+ const res = baseResolution() * adaptiveScale;
371
+ let w = Math.max(8, Math.round(cssW * res));
372
+ let h = Math.max(8, Math.round(cssH * res));
373
+ const over = Math.max(w, h) / FIELD_MAX;
374
+ if (over > 1) {
375
+ w = Math.round(w / over);
376
+ h = Math.round(h / over);
377
+ }
378
+ if (w !== fieldW || h !== fieldH) {
379
+ fieldW = w;
380
+ fieldH = h;
381
+ allocField(w, h);
382
+ }
383
+ }
384
+
385
+ // ---- drawing -------------------------------------------------------------
386
+ // Engine time, folded before it reaches the shader: u_time is fp32 on the
387
+ // GPU, and an ever-growing clock loses the precision the small offsets need
388
+ // (a visible stutter after a day or two in a desktop shell). A triangle
389
+ // fold keeps every frame continuous with the last (the motion reverses,
390
+ // slowly, once every TIME_FOLD seconds of engine time), unlike a modulo,
391
+ // which would jump.
392
+ let time = 0;
393
+ let ptrX = 0.5;
394
+ let ptrY = 0.5;
395
+ let ptrStrength = 0;
396
+ let ptrTargetX = 0.5;
397
+ let ptrTargetY = 0.5;
398
+ let ptrInside = false;
399
+ let ptrClientX = Number.NaN;
400
+ let ptrClientY = 0;
401
+
402
+ /** Resolve the last pointer position against the canvas — once per frame,
403
+ * not once per pointermove (which can fire 120+ times a second, each a
404
+ * layout read). */
405
+ let ptrRect: DOMRect | null = null;
406
+ function resolvePointer() {
407
+ if (Number.isNaN(ptrClientX)) return;
408
+ // The box is read once and re-read only when it can have moved (resize,
409
+ // scroll), never per frame.
410
+ ptrRect ??= canvas.getBoundingClientRect();
411
+ const r = ptrRect;
412
+ if (r.width === 0 || r.height === 0) return;
413
+ const x = (ptrClientX - r.left) / r.width;
414
+ const y = 1 - (ptrClientY - r.top) / r.height;
415
+ ptrInside = x >= 0 && x <= 1 && y >= 0 && y <= 1;
416
+ ptrTargetX = Math.min(1, Math.max(0, x));
417
+ ptrTargetY = Math.min(1, Math.max(0, y));
418
+ }
419
+
420
+ function draw() {
421
+ if (gl!.isContextLost() || !composite || !hasSize()) return;
422
+ if (!derived.paintable) {
423
+ // Nothing to paint: stay invisible so the surface underneath shows (an
424
+ // opaque context that never drew would otherwise show black).
425
+ shown = false;
426
+ canvas.style.opacity = '0';
427
+ return;
428
+ }
429
+ applySize();
430
+ const fp = program(opts.style);
431
+ if (!fp) return;
432
+ const d = derived;
433
+ const u = fp.u;
434
+
435
+ // Pass 1: the field, small.
436
+ gl!.bindFramebuffer(gl!.FRAMEBUFFER, fbo);
437
+ gl!.viewport(0, 0, fieldW, fieldH);
438
+ gl!.useProgram(fp.program);
439
+ const rad = (opts.angle * Math.PI) / 180;
440
+ gl!.uniform2f(u.u_res!, fieldW, fieldH);
441
+ gl!.uniform1f(u.u_time!, foldTime(time) + d.timeOffset);
442
+ gl!.uniform1f(u.u_scale!, opts.scale);
443
+ gl!.uniform1f(u.u_warp!, opts.warp);
444
+ gl!.uniform1f(u.u_soft!, opts.softness);
445
+ gl!.uniform1f(u.u_light!, opts.lighting);
446
+ gl!.uniform1f(u.u_sat!, opts.saturation);
447
+ gl!.uniform2f(u.u_rot!, Math.cos(rad), Math.sin(rad));
448
+ gl!.uniform3f(u.u_ptr!, ptrX, ptrY, pointerOn() ? ptrStrength * opts.pointer : 0);
449
+ gl!.uniform3f(u.u_bg!, d.bg[0], d.bg[1], d.bg[2]);
450
+ gl!.uniform3fv(u.u_col!, d.col);
451
+ gl!.uniform1fv(u.u_w!, d.w);
452
+ gl!.uniform1fv(u.u_stop!, d.stop);
453
+ gl!.uniform4fv(u.u_ph!, d.ph);
454
+ gl!.drawArrays(gl!.TRIANGLES, 0, 3);
455
+
456
+ // Pass 2: filter up, vignette, grain, dither.
457
+ gl!.bindFramebuffer(gl!.FRAMEBUFFER, null);
458
+ gl!.viewport(0, 0, canvas.width, canvas.height);
459
+ const c = composite;
460
+ gl!.useProgram(c.program);
461
+ gl!.activeTexture(gl!.TEXTURE0);
462
+ gl!.bindTexture(gl!.TEXTURE_2D, fieldTex);
463
+ gl!.uniform1i(c.u.u_tex!, 0);
464
+ gl!.uniform2f(c.u.u_out!, canvas.width, canvas.height);
465
+ gl!.uniform1f(c.u.u_px!, Math.max(1, canvas.width / Math.max(1, cssW)));
466
+ gl!.uniform1f(c.u.u_grain!, opts.grain);
467
+ gl!.uniform1f(c.u.u_gseed!, d.grainSeed);
468
+ gl!.uniform1f(c.u.u_vig!, opts.vignette);
469
+ gl!.uniform3f(c.u.u_bgs!, d.bgSrgb[0], d.bgSrgb[1], d.bgSrgb[2]);
470
+ gl!.drawArrays(gl!.TRIANGLES, 0, 3);
471
+
472
+ if (!shown) {
473
+ shown = true;
474
+ canvas.style.opacity = '1';
475
+ }
476
+ }
477
+
478
+ // ---- scheduling ----------------------------------------------------------
479
+ let raf = 0;
480
+ let timer = 0;
481
+ let last = 0;
482
+ let lastDrawn = 0;
483
+ let paused = false;
484
+ let destroyed = false;
485
+ let onScreen = true;
486
+ let shown = false;
487
+ let fps = 0;
488
+ let fpsWindowStart = 0;
489
+ let fpsWindowFrames = 0;
490
+ const lateSamples: number[] = [];
491
+ const reducedQuery =
492
+ typeof window.matchMedia === 'function'
493
+ ? window.matchMedia('(prefers-reduced-motion: reduce)')
494
+ : null;
495
+
496
+ const reduced = () => opts.respectReducedMotion && reducedQuery?.matches === true;
497
+ const moving = () => opts.speed > 0 && !reduced();
498
+ // Pointer lean is motion too: reduced motion switches it off.
499
+ const pointerOn = () => opts.pointer > 0 && !reduced();
500
+ const pointerSettling = () =>
501
+ pointerOn() &&
502
+ (Math.abs(ptrTargetX - ptrX) > 1e-3 ||
503
+ Math.abs(ptrTargetY - ptrY) > 1e-3 ||
504
+ Math.abs((ptrInside ? 1 : 0) - ptrStrength) > 1e-3);
505
+ const canRun = () =>
506
+ !paused &&
507
+ !destroyed &&
508
+ onScreen &&
509
+ document.visibilityState !== 'hidden' &&
510
+ !gl!.isContextLost();
511
+
512
+ const armed = () => raf !== 0 || timer !== 0;
513
+
514
+ function cancel() {
515
+ if (raf) cancelAnimationFrame(raf);
516
+ if (timer) clearTimeout(timer);
517
+ raf = timer = 0;
518
+ }
519
+
520
+ /** The loop stopped (still, paused, hidden, off-screen, no size): the next
521
+ * start measures afresh, so a stop is never read as one long late frame. */
522
+ function stopTiming() {
523
+ last = 0;
524
+ lastDrawn = 0;
525
+ lateSamples.length = 0;
526
+ }
527
+
528
+ function schedule() {
529
+ if (armed() || !canRun()) return;
530
+ raf = requestAnimationFrame(tick);
531
+ }
532
+
533
+ /** The next frame at the cap's next slot: sleep on a timer until just
534
+ * before it, then take the display's frame. A capped loop never wakes at
535
+ * the display rate only to skip. */
536
+ function scheduleAt(dueIn: number) {
537
+ if (armed()) return;
538
+ if (dueIn > 4) {
539
+ timer = window.setTimeout(() => {
540
+ timer = 0;
541
+ if (canRun()) raf = requestAnimationFrame(tick);
542
+ else stopTiming();
543
+ }, dueIn - 3);
544
+ } else {
545
+ raf = requestAnimationFrame(tick);
546
+ }
547
+ }
548
+
549
+ function tick(now: number) {
550
+ raf = 0;
551
+ if (!canRun()) {
552
+ stopTiming();
553
+ return;
554
+ }
555
+ // A zero-size box (collapsed, display:none) has nothing to draw: stop
556
+ // rather than spin; the ResizeObserver restarts the loop.
557
+ if (!hasSize()) {
558
+ stopTiming();
559
+ return;
560
+ }
561
+ const animating = moving() || pointerSettling();
562
+ const minGap = 1000 / opts.maxFps;
563
+ if (animating && lastDrawn && now - lastDrawn < minGap - 2) {
564
+ scheduleAt(minGap - (now - lastDrawn));
565
+ return;
566
+ }
567
+ // Cap the step so a long pause (hidden tab, off-screen) resumes in place
568
+ // instead of lurching forward.
569
+ const dt = last ? Math.min((now - last) / 1000, 0.1) : 0;
570
+ last = now;
571
+ if (moving()) time += dt * opts.speed;
572
+ if (pointerOn()) {
573
+ resolvePointer();
574
+ const k = Math.min(1, dt * 5);
575
+ ptrX += (ptrTargetX - ptrX) * k;
576
+ ptrY += (ptrTargetY - ptrY) * k;
577
+ ptrStrength += ((ptrInside ? 1 : 0) - ptrStrength) * k;
578
+ }
579
+ if (animating && opts.adaptive && lastDrawn) adapt(now - lastDrawn, minGap);
580
+ lastDrawn = now;
581
+ draw();
582
+ countFps(now);
583
+ if (moving() || pointerSettling()) scheduleAt(minGap - (performance.now() - now));
584
+ else stopTiming();
585
+ }
586
+
587
+ function countFps(now: number) {
588
+ if (!fpsWindowStart) fpsWindowStart = now;
589
+ fpsWindowFrames++;
590
+ if (now - fpsWindowStart >= 1000) {
591
+ fps = Math.round((fpsWindowFrames * 1000) / (now - fpsWindowStart));
592
+ fpsWindowStart = now;
593
+ fpsWindowFrames = 0;
594
+ }
595
+ }
596
+
597
+ /** A window of frames consistently late shrinks the field; several on-time
598
+ * windows in a row grow it back a step, so a busy spell does not cost the
599
+ * quality for good. Gaps over ~100 ms are not GPU slowness (a long task on
600
+ * the main thread, a GC, a stalled tab) and are not counted at all. */
601
+ let onTimeWindows = 0;
602
+ function adapt(gap: number, target: number) {
603
+ if (gap > JANK_GAP_MS) return;
604
+ lateSamples.push(gap);
605
+ if (lateSamples.length < 45) return;
606
+ lateSamples.sort((a, b) => a - b);
607
+ const median = lateSamples[Math.floor(lateSamples.length / 2)] ?? 0;
608
+ lateSamples.length = 0;
609
+ // Late against the cap AND against a 60Hz display's natural cadence.
610
+ const budget = Math.max(target, 16.7);
611
+ if (median > budget * 1.4) {
612
+ onTimeWindows = 0;
613
+ if (baseResolution() * adaptiveScale > 0.12) adaptiveScale *= 0.8;
614
+ } else if (median <= budget * 1.1 && adaptiveScale < 1) {
615
+ onTimeWindows++;
616
+ if (onTimeWindows >= GROW_BACK_WINDOWS) {
617
+ onTimeWindows = 0;
618
+ adaptiveScale = Math.min(1, adaptiveScale / 0.8);
619
+ }
620
+ } else {
621
+ onTimeWindows = 0;
622
+ }
623
+ }
624
+
625
+ /** Paint now if nothing is scheduled (a still background after a change). */
626
+ function redraw() {
627
+ if (!canRun()) return;
628
+ if (raf) return; // the running loop will pick it up
629
+ // A loop asleep until its next slot: take the frame now instead.
630
+ if (timer) {
631
+ clearTimeout(timer);
632
+ timer = 0;
633
+ }
634
+ raf = requestAnimationFrame(tick);
635
+ }
636
+
637
+ // ---- observers -----------------------------------------------------------
638
+ const resizeObserver =
639
+ typeof ResizeObserver !== 'undefined'
640
+ ? new ResizeObserver((entries) => {
641
+ const box = entries[0]?.contentRect;
642
+ if (!box) return;
643
+ cssW = box.width;
644
+ cssH = box.height;
645
+ ptrRect = null;
646
+ redraw();
647
+ })
648
+ : null;
649
+ resizeObserver?.observe(canvas);
650
+
651
+ const intersection =
652
+ typeof IntersectionObserver !== 'undefined'
653
+ ? new IntersectionObserver((entries) => {
654
+ onScreen = entries[0]?.isIntersecting ?? true;
655
+ if (onScreen) schedule();
656
+ })
657
+ : null;
658
+ intersection?.observe(canvas);
659
+
660
+ const onVisibility = () => {
661
+ if (document.visibilityState !== 'hidden') schedule();
662
+ };
663
+ document.addEventListener('visibilitychange', onVisibility);
664
+
665
+ const onReducedChange = () => {
666
+ bindPointer();
667
+ redraw();
668
+ };
669
+ reducedQuery?.addEventListener?.('change', onReducedChange);
670
+
671
+ const onPointerMove = (e: PointerEvent) => {
672
+ ptrClientX = e.clientX;
673
+ ptrClientY = e.clientY;
674
+ // A first move after a still period needs a frame to start settling.
675
+ if (!raf) {
676
+ resolvePointer();
677
+ redraw();
678
+ }
679
+ };
680
+ const onLayoutMove = () => {
681
+ ptrRect = null;
682
+ };
683
+ const onPointerLeave = () => {
684
+ ptrClientX = Number.NaN;
685
+ ptrInside = false;
686
+ redraw();
687
+ };
688
+ let pointerBound = false;
689
+ function bindPointer() {
690
+ const want = pointerOn() && !destroyed;
691
+ if (want === pointerBound) return;
692
+ pointerBound = want;
693
+ if (want) {
694
+ ptrRect = null;
695
+ window.addEventListener('pointermove', onPointerMove, { passive: true });
696
+ window.addEventListener('scroll', onLayoutMove, { passive: true, capture: true });
697
+ window.addEventListener('resize', onLayoutMove, { passive: true });
698
+ document.documentElement.addEventListener('pointerleave', onPointerLeave);
699
+ } else {
700
+ window.removeEventListener('pointermove', onPointerMove);
701
+ window.removeEventListener('scroll', onLayoutMove, { capture: true });
702
+ window.removeEventListener('resize', onLayoutMove);
703
+ document.documentElement.removeEventListener('pointerleave', onPointerLeave);
704
+ }
705
+ }
706
+
707
+ const onLost = (e: Event) => {
708
+ e.preventDefault(); // ask for a restore
709
+ cancel();
710
+ stopTiming();
711
+ };
712
+ const onRestored = () => {
713
+ if (destroyed) return;
714
+ initGl();
715
+ redraw();
716
+ };
717
+ canvas.addEventListener('webglcontextlost', onLost);
718
+ canvas.addEventListener('webglcontextrestored', onRestored);
719
+
720
+ function destroy() {
721
+ if (destroyed) return;
722
+ destroyed = true;
723
+ cancel();
724
+ resizeObserver?.disconnect();
725
+ intersection?.disconnect();
726
+ document.removeEventListener('visibilitychange', onVisibility);
727
+ reducedQuery?.removeEventListener?.('change', onReducedChange);
728
+ bindPointer();
729
+ canvas.removeEventListener('webglcontextlost', onLost);
730
+ canvas.removeEventListener('webglcontextrestored', onRestored);
731
+ freeGl();
732
+ // Free the context now — browsers cap live contexts (~16) and only
733
+ // reclaim abandoned ones at GC.
734
+ gl!.getExtension('WEBGL_lose_context')?.loseContext();
735
+ }
736
+
737
+ // ---- start ---------------------------------------------------------------
738
+ if (!initGl()) {
739
+ // A shader that will not compile here: release the observers, listeners
740
+ // and context too, not just the GL objects.
741
+ destroy();
742
+ return null;
743
+ }
744
+ bindPointer();
745
+ redraw();
746
+
747
+ return {
748
+ update(next) {
749
+ const prev = opts;
750
+ opts = normalizeDriftOptions({ ...opts, ...next });
751
+ if (next.colors !== undefined || next.background !== undefined || next.seed !== undefined) {
752
+ derived = derive(opts);
753
+ }
754
+ if (prev.resolution !== opts.resolution || prev.style !== opts.style) {
755
+ adaptiveScale = 1;
756
+ onTimeWindows = 0;
757
+ }
758
+ bindPointer();
759
+ redraw();
760
+ },
761
+ redraw,
762
+ pause() {
763
+ paused = true;
764
+ cancel();
765
+ stopTiming();
766
+ },
767
+ resume() {
768
+ paused = false;
769
+ redraw();
770
+ },
771
+ destroy,
772
+ stats: () => ({
773
+ fps: armed() ? fps : 0,
774
+ fieldWidth: fieldW,
775
+ fieldHeight: fieldH,
776
+ outputWidth: canvas.width,
777
+ outputHeight: canvas.height,
778
+ resolution: baseResolution() * adaptiveScale,
779
+ halfFloat,
780
+ animating: armed(),
781
+ }),
782
+ };
783
+ }