@arraypress/effects-astro 0.10.0 → 0.11.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,610 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/voronoi-mesh
3
+ *
4
+ * A Voronoi mesh drawn as thin lines on a ground, in two nested tiers.
5
+ * The macro cells come from one seed per square of a grid (`cells`
6
+ * across), each jittered off the square's centre and orbiting slowly
7
+ * around that rest point. Inside each macro cell a handful of inner seeds
8
+ * (`inner`) sit around its seed and pulse: pushed out together to most of
9
+ * the cell and drawn back in, so the inner lines breathe outward from the
10
+ * seed like an event horizon. The inner tier is a Voronoi among only the
11
+ * inner seeds of the pixel's own macro cell, so its lines stop at the
12
+ * macro borders by construction, as the sketch's clipped polygons did.
13
+ *
14
+ * In a fragment shader: the macro tier is a jittered-grid Voronoi with
15
+ * the exact border distance (the nearest seed in a 3×3 neighbourhood,
16
+ * then the distance to each bisector around it, the two-pass F2−F1 border
17
+ * method), the inner tier the same over its few seeds, and both are drawn
18
+ * as anti-aliased lines of a CSS-px width. The unit is a share of the
19
+ * canvas width, so a card and a hero hold the same cells. Its lattice
20
+ * hash is Dave Hoskins' Hash without Sine (MIT, © 2014 David Hoskins),
21
+ * which brings its input under 1 before it multiplies, so the GPU's 32-bit
22
+ * floats and the JavaScript twins here agree; `meshPolygons` and
23
+ * `meshStill` draw the same frame as real polygons (an SVG), for the still
24
+ * a page shows before the shader starts and without WebGL.
25
+ *
26
+ * A slow driver (`breathe`) speeds the clocks, thickens the lines and
27
+ * lifts the macro tier a little and back, over about half a minute, as
28
+ * the sketch's noise driver did; the clocks are closed-form functions of
29
+ * the seconds, never stepped per frame. A `quiet` area fades the lines
30
+ * behind copy. With prefers-reduced-motion, or `speed: 0`, it is one
31
+ * still frame. Colours mix with the ground in Oklab.
32
+ *
33
+ * After `voronoi_bg`, a Processing sketch shared with the owner
34
+ * (2026-11-20): the two tiers, the orbit, the pulse's shape (a squared
35
+ * sine with a dead zone, the seeds of a cell in phase but for a little
36
+ * jitter), the maroon ground and the line colours are its; here it runs
37
+ * on the GPU instead of clipping polygons on the CPU.
38
+ */
39
+
40
+ import { createStage } from './stage.js';
41
+ import { GLSL_HASH33, hash33 } from './hash-noise.js';
42
+ import { GLSL_OKLAB, mixOklab, parseColor, toHex, toOklab } from './color.js';
43
+ import { GLSL_QUIET, quietUniform } from './glsl.js';
44
+ import { watchColors } from './mount.js';
45
+ import { pickColors } from './palettes.js';
46
+
47
+ /** Hash without Sine (./hash-noise.js), the seeds' hash. */
48
+ export { hash33 };
49
+
50
+ /**
51
+ * @typedef {object} VoronoiMeshConfig
52
+ * @property {string[]} [colors] Two CSS hex colours: the macro lines' and the inner lines'. Default a pale stone and a dusty rose.
53
+ * @property {string} [palette] A shared palette by name (PALETTES; any case), when there are no `colors`: its glint for the macro lines, its first colour for the inner.
54
+ * @property {string} [background='#350f0e'] The ground, a CSS hex colour (opaque, so the canvas covers what is behind it); `transparent` draws the lines alone.
55
+ * @property {number} [cells=9] Macro cells across the width.
56
+ * @property {number} [inner=5] Inner seeds per macro cell, 0–8; 0 for the macro tier alone.
57
+ * @property {number} [width=1] The macro lines' width in CSS px; the inner lines are 0.7 of it.
58
+ * @property {[number, number]} [opacity=[0.4, 0.22]] The macro and inner lines' opacity, each 0–1.
59
+ * @property {number} [pulse=1] How far the inner seeds pulse, 0–1: 1 draws them in to the macro seed and out again, 0 holds them still.
60
+ * @property {number} [spread=0.6] How far out the inner seeds push, a share of a cell.
61
+ * @property {number} [jitter=0.75] How far each macro seed rests off its square's centre, 0–1.
62
+ * @property {number} [orbit=1] How wide the macro seeds orbit, 0–1.
63
+ * @property {number} [breathe=0.35] The slow driver, 0–1: how much it speeds the clocks, thickens the lines and lifts the macro tier.
64
+ * @property {number} [speed=1] Plays every clock faster or slower; 0 for one still frame.
65
+ * @property {[number, number]} [offset=[0, 0]] Where the grid starts, in cells, so two cards differ.
66
+ * @property {{ x?: number, y?: number, radius?: number, depth?: number } | null} [quiet=null]
67
+ * An area kept quiet: centre (0–1 from the top left), radius (share of the height), depth (0–1).
68
+ */
69
+
70
+ /** The settings' defaults, shared by the shader and the JavaScript twins. */
71
+ export const MESH_DEFAULTS = {
72
+ background: '#350f0e',
73
+ cells: 9,
74
+ inner: 5,
75
+ width: 1,
76
+ opacity: /** @type {[number, number]} */ ([0.4, 0.22]),
77
+ pulse: 1,
78
+ spread: 0.6,
79
+ jitter: 0.75,
80
+ orbit: 1,
81
+ breathe: 0.35,
82
+ };
83
+
84
+ /** The sketch's line colours: a pale stone for the macro lines, a dusty rose for the inner. */
85
+ const STONE = ['#c1c2bc', '#a67676'];
86
+
87
+ /** The most inner seeds a cell takes (the shader's loop bound). */
88
+ const MAX_INNER = 8;
89
+ /**
90
+ * The furthest a macro seed rests off its square's centre (along each
91
+ * axis) and the widest it orbits, in cells. Together under half a cell
92
+ * (0.42) along each axis, so every seed stays inside its own square and
93
+ * the nearest is always within the pixel's 3×3 neighbourhood.
94
+ */
95
+ const JITTER_REACH = 0.22;
96
+ const ORBIT_REACH = 0.2;
97
+ /** The orbit's and the pulse's rates, cycles a second (the sketch's). */
98
+ const ORBIT_HZ = 0.03;
99
+ const PULSE_HZ = 0.05;
100
+ /** The pulse's dead zone (a share of its cycle at rest in the middle) and how far a seed's phase strays from its cell's. */
101
+ const DEAD_ZONE = 0.08;
102
+ const PHASE_JITTER = 0.12;
103
+ /** The driver's two slow waves (radians a second) and the second's phase. */
104
+ const W1 = 2 * Math.PI * 0.031;
105
+ const W2 = 2 * Math.PI * 0.013;
106
+ const PHI = 1.3;
107
+ /** How much the driver speeds the clocks (the sketch's), and thickens the lines (gentler than the sketch's 6, for thin card lines). */
108
+ const SPEED_BOOST = 2;
109
+ const WIDTH_BOOST = 1.2;
110
+ /** The inner lines' width, a share of the macro lines'. */
111
+ const INNER_WIDTH = 0.7;
112
+ const TAU = 2 * Math.PI;
113
+
114
+ /**
115
+ * GLSL (ES 1.00): the hash, the seeds and the pulse, the twins of
116
+ * `hash33`, `macroSeed`, `innerSeed` and `pulseWave` below.
117
+ */
118
+ const GLSL_SEEDS = `
119
+ const float TAU = 6.28318530718;
120
+ ${GLSL_HASH33}vec2 macroSeed(vec2 c) {
121
+ vec3 a = hash33(vec3(c, 0.0));
122
+ vec3 b = hash33(vec3(c, 1.0));
123
+ float ph = TAU * (${ORBIT_HZ} * uClock + a.z);
124
+ return c + 0.5 + (a.xy - 0.5) * 2.0 * uJitter + vec2(cos(ph), sin(ph)) * uOrbit * (0.7 + 0.3 * b.x);
125
+ }
126
+ float pulseWave(float t) {
127
+ float u = clamp((t - ${DEAD_ZONE / 2}) / ${1 - DEAD_ZONE}, 0.0, 1.0);
128
+ float s = sin(3.14159265 * u);
129
+ return s * s;
130
+ }
131
+ vec2 innerSeed(vec2 c, vec2 s, vec3 b, float k) {
132
+ vec3 h = hash33(vec3(c, 2.0 + k));
133
+ float ang = TAU * ((k + 0.5 + 0.6 * (h.x - 0.5)) / uInner + b.z);
134
+ float t = fract(${PULSE_HZ} * uClock + b.y + (h.y - 0.5) * ${2 * PHASE_JITTER});
135
+ float r = uSpread * (0.7 + 0.4 * h.z) * (1.0 - uPulse * (1.0 - pulseWave(t)));
136
+ return s + r * vec2(cos(ang), sin(ang));
137
+ }
138
+ `;
139
+
140
+ const FRAG = `
141
+ precision highp float;
142
+ uniform vec2 uRes;
143
+ uniform float uCells;
144
+ uniform vec2 uOffset;
145
+ uniform float uClock;
146
+ uniform float uJitter;
147
+ uniform float uOrbit;
148
+ uniform float uInner;
149
+ uniform float uSpread;
150
+ uniform float uPulse;
151
+ uniform vec2 uWidth;
152
+ uniform vec2 uAlpha;
153
+ uniform vec3 uMacro;
154
+ uniform vec3 uInnerCol;
155
+ uniform vec4 uBg;
156
+ ${GLSL_OKLAB}
157
+ ${GLSL_QUIET}
158
+ ${GLSL_SEEDS}
159
+
160
+ // A line's coverage at d device px from its centre, w device px wide;
161
+ // under a pixel wide it fades rather than thins, so it never breaks up.
162
+ float line(float d, float w) {
163
+ return clamp(0.5 + 0.5 * max(w, 1.0) - d, 0.0, 1.0) * min(w, 1.0);
164
+ }
165
+
166
+ void main() {
167
+ // Counted from the top left, as the still's polygons are.
168
+ vec2 px = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y);
169
+ float unit = uRes.x / uCells;
170
+ vec2 p = px / unit + uOffset;
171
+ vec2 ip = floor(p);
172
+
173
+ // The macro tier: the nearest seed, then the nearest bisector around it.
174
+ float best = 1e9;
175
+ vec2 bc = ip;
176
+ vec2 bs = ip;
177
+ for (int j = -1; j <= 1; j++)
178
+ for (int i = -1; i <= 1; i++) {
179
+ vec2 c = ip + vec2(float(i), float(j));
180
+ vec2 s = macroSeed(c);
181
+ float d = dot(s - p, s - p);
182
+ if (d < best) { best = d; bc = c; bs = s; }
183
+ }
184
+ float edge = 1e9;
185
+ for (int j = -1; j <= 1; j++)
186
+ for (int i = -1; i <= 1; i++) {
187
+ if (i == 0 && j == 0) continue;
188
+ vec2 s = macroSeed(bc + vec2(float(i), float(j)));
189
+ vec2 n = s - bs;
190
+ float l = length(n);
191
+ if (l > 1e-5) edge = min(edge, dot(0.5 * (s + bs) - p, n / l));
192
+ }
193
+
194
+ // The inner tier: the same among only this cell's inner seeds.
195
+ float iedge = 1e9;
196
+ if (uInner > 0.5) {
197
+ vec3 b = hash33(vec3(bc, 1.0));
198
+ float ib = 1e9;
199
+ vec2 iseed = bs;
200
+ float ik = -1.0;
201
+ for (int k = 0; k < ${MAX_INNER}; k++) {
202
+ if (float(k) >= uInner) break;
203
+ vec2 q = innerSeed(bc, bs, b, float(k));
204
+ float d = dot(q - p, q - p);
205
+ if (d < ib) { ib = d; iseed = q; ik = float(k); }
206
+ }
207
+ for (int k = 0; k < ${MAX_INNER}; k++) {
208
+ if (float(k) >= uInner) break;
209
+ if (float(k) == ik) continue;
210
+ vec2 q = innerSeed(bc, bs, b, float(k));
211
+ vec2 n = q - iseed;
212
+ float l = length(n);
213
+ if (l > 1e-5) iedge = min(iedge, dot(0.5 * (q + iseed) - p, n / l));
214
+ }
215
+ }
216
+
217
+ vec2 uv = vec2(px.x - 0.5 * uRes.x, 0.5 * uRes.y - px.y) / uRes.y;
218
+ float hush = mix(1.0 - uQuiet.w, 1.0, quietOpen(uv));
219
+ float am = line(edge * unit, uWidth.x) * uAlpha.x * hush;
220
+ float ai = line(iedge * unit, uWidth.y) * uAlpha.y * hush;
221
+ if (uBg.a > 0.5) {
222
+ // On the ground: inner, then macro over it, mixed in Oklab.
223
+ vec3 lab = mix(mix(uBg.rgb, uInnerCol, ai), uMacro, am);
224
+ gl_FragColor = vec4(fromOklab(lab), 1.0);
225
+ } else {
226
+ // No ground: premultiplied, macro over inner.
227
+ vec3 col = fromOklab(uMacro) * am + fromOklab(uInnerCol) * ai * (1.0 - am);
228
+ gl_FragColor = vec4(col, am + ai * (1.0 - am));
229
+ }
230
+ }
231
+ `;
232
+
233
+ /**
234
+ * The settings over the defaults; a setting left undefined keeps its default.
235
+ *
236
+ * @param {VoronoiMeshConfig} [config] The settings.
237
+ * @returns {typeof MESH_DEFAULTS & VoronoiMeshConfig} Every setting.
238
+ */
239
+ function withDefaults(config = {}) {
240
+ const set = Object.fromEntries(Object.entries(config).filter(([, v]) => v !== undefined));
241
+ return { ...MESH_DEFAULTS, ...set };
242
+ }
243
+
244
+ /**
245
+ * The slow driver at a time: two slow sines, 0 to `breathe`.
246
+ *
247
+ * @param {number} t Seconds (already at the effect's speed).
248
+ * @param {number} [breathe=0.35] How much there is of it, 0–1.
249
+ * @returns {number} 0 to `breathe`.
250
+ */
251
+ export function driveAt(t, breathe = MESH_DEFAULTS.breathe) {
252
+ return breathe * (0.5 + 0.3 * Math.sin(W1 * t) + 0.2 * Math.sin(W2 * t + PHI));
253
+ }
254
+
255
+ /**
256
+ * The seeds' clock at a time: the seconds, run faster while the driver is
257
+ * up. The integral of `1 + 2 · driveAt`, in closed form, so it is the same
258
+ * whatever the frame rate and never stepped.
259
+ *
260
+ * @param {number} t Seconds (already at the effect's speed).
261
+ * @param {number} [breathe=0.35] The driver's amount, 0–1.
262
+ * @returns {number} The clock, in seconds; 0 at 0.
263
+ */
264
+ export function clockAt(t, breathe = MESH_DEFAULTS.breathe) {
265
+ const integral = 0.5 * t + (0.3 * (1 - Math.cos(W1 * t))) / W1 + (0.2 * (Math.cos(PHI) - Math.cos(W2 * t + PHI))) / W2;
266
+ return t + SPEED_BOOST * breathe * integral;
267
+ }
268
+
269
+ /**
270
+ * The pulse's shape over one cycle: at rest through the dead zone around
271
+ * 0, then a squared sine out to 1 halfway and back.
272
+ *
273
+ * @param {number} t Where in the cycle, 0–1.
274
+ * @returns {number} 0–1.
275
+ */
276
+ export function pulseWave(t) {
277
+ const u = Math.min(1, Math.max(0, (t - DEAD_ZONE / 2) / (1 - DEAD_ZONE)));
278
+ const s = Math.sin(Math.PI * u);
279
+ return s * s;
280
+ }
281
+
282
+ /**
283
+ * The settings as the seeds take them, each in cells.
284
+ *
285
+ * @typedef {object} SeedOptions
286
+ * @property {number} jitter The furthest a seed rests off its square's centre.
287
+ * @property {number} orbit The widest it orbits.
288
+ * @property {number} inner Inner seeds per cell.
289
+ * @property {number} spread How far out the inner seeds push.
290
+ * @property {number} pulse How far they pulse, 0–1.
291
+ */
292
+
293
+ /**
294
+ * The settings, with defaults, as the seeds take them.
295
+ *
296
+ * @param {VoronoiMeshConfig} [config] The settings.
297
+ * @returns {SeedOptions} The seeds' options, in cells.
298
+ */
299
+ export function seedOptions(config = {}) {
300
+ const o = withDefaults(config);
301
+ const clamp01 = (/** @type {number} */ n) => Math.min(1, Math.max(0, n));
302
+ return {
303
+ jitter: clamp01(o.jitter) * JITTER_REACH,
304
+ orbit: clamp01(o.orbit) * ORBIT_REACH,
305
+ inner: Math.round(Math.min(MAX_INNER, Math.max(0, o.inner))),
306
+ spread: Math.max(0, o.spread),
307
+ pulse: clamp01(o.pulse),
308
+ };
309
+ }
310
+
311
+ /**
312
+ * A macro seed: the one for the grid square whose corner is (cx, cy),
313
+ * jittered off its centre and orbiting it (the shader's `macroSeed`).
314
+ *
315
+ * @param {number} cx The square's x (an integer, in cells).
316
+ * @param {number} cy The square's y.
317
+ * @param {number} clock The seeds' clock (`clockAt`).
318
+ * @param {SeedOptions} [options] From `seedOptions` (the defaults if none).
319
+ * @returns {[number, number]} The seed, in cells.
320
+ */
321
+ export function macroSeed(cx, cy, clock, options = seedOptions()) {
322
+ const [ax, ay, az] = hash33(cx, cy, 0);
323
+ const [bx] = hash33(cx, cy, 1);
324
+ const ph = TAU * (ORBIT_HZ * clock + az);
325
+ const r = options.orbit * (0.7 + 0.3 * bx);
326
+ return [cx + 0.5 + (ax - 0.5) * 2 * options.jitter + Math.cos(ph) * r, cy + 0.5 + (ay - 0.5) * 2 * options.jitter + Math.sin(ph) * r];
327
+ }
328
+
329
+ /**
330
+ * A macro cell's inner seeds: spread around its seed at even angles (a
331
+ * little jittered), pushed out and drawn back in together by the pulse,
332
+ * each a touch out of phase (the shader's `innerSeed`).
333
+ *
334
+ * @param {number} cx The macro cell's grid square x.
335
+ * @param {number} cy Its y.
336
+ * @param {number} clock The seeds' clock (`clockAt`).
337
+ * @param {SeedOptions} [options] From `seedOptions` (the defaults if none).
338
+ * @returns {[number, number][]} The inner seeds, in cells.
339
+ */
340
+ export function innerSeeds(cx, cy, clock, options = seedOptions()) {
341
+ const [sx, sy] = macroSeed(cx, cy, clock, options);
342
+ const [, by, bz] = hash33(cx, cy, 1);
343
+ return Array.from({ length: options.inner }, (_, k) => {
344
+ const [hx, hy, hz] = hash33(cx, cy, 2 + k);
345
+ const ang = TAU * ((k + 0.5 + 0.6 * (hx - 0.5)) / options.inner + bz);
346
+ const t = PULSE_HZ * clock + by + (hy - 0.5) * 2 * PHASE_JITTER;
347
+ const r = options.spread * (0.7 + 0.4 * hz) * (1 - options.pulse * (1 - pulseWave(t - Math.floor(t))));
348
+ return /** @type {[number, number]} */ ([sx + r * Math.cos(ang), sy + r * Math.sin(ang)]);
349
+ });
350
+ }
351
+
352
+ /**
353
+ * The macro tier at a point, as the shader finds it: the nearest seed in
354
+ * the point's 3×3 neighbourhood, then the distance to the nearest
355
+ * bisector between it and the seeds around it.
356
+ *
357
+ * @param {number} x The point, in cells.
358
+ * @param {number} y The point, in cells.
359
+ * @param {number} clock The seeds' clock (`clockAt`).
360
+ * @param {SeedOptions} [options] From `seedOptions` (the defaults if none).
361
+ * @returns {{ cell: [number, number], seed: [number, number], edge: number }} The nearest seed's square, the seed, and the distance to its cell's border, in cells.
362
+ */
363
+ export function macroAt(x, y, clock, options = seedOptions()) {
364
+ const ix = Math.floor(x);
365
+ const iy = Math.floor(y);
366
+ let best = Infinity;
367
+ /** @type {[number, number]} */
368
+ let cell = [ix, iy];
369
+ /** @type {[number, number]} */
370
+ let seed = [ix, iy];
371
+ for (let j = -1; j <= 1; j++)
372
+ for (let i = -1; i <= 1; i++) {
373
+ const s = macroSeed(ix + i, iy + j, clock, options);
374
+ const d = (s[0] - x) ** 2 + (s[1] - y) ** 2;
375
+ if (d < best) [best, cell, seed] = [d, [ix + i, iy + j], s];
376
+ }
377
+ let edge = Infinity;
378
+ for (let j = -1; j <= 1; j++)
379
+ for (let i = -1; i <= 1; i++) {
380
+ if (i === 0 && j === 0) continue;
381
+ const s = macroSeed(cell[0] + i, cell[1] + j, clock, options);
382
+ const nx = s[0] - seed[0];
383
+ const ny = s[1] - seed[1];
384
+ const l = Math.hypot(nx, ny);
385
+ if (l > 1e-5) edge = Math.min(edge, ((s[0] + seed[0]) / 2 - x) * (nx / l) + ((s[1] + seed[1]) / 2 - y) * (ny / l));
386
+ }
387
+ return { cell, seed, edge };
388
+ }
389
+
390
+ /**
391
+ * Keeps the part of a polygon on `site`'s side of the bisector between
392
+ * `site` and `other` (one Sutherland–Hodgman step, as the sketch clips).
393
+ *
394
+ * @param {[number, number][]} poly The polygon.
395
+ * @param {[number, number]} site The seed whose side is kept.
396
+ * @param {[number, number]} other The other seed.
397
+ * @returns {[number, number][]} The clipped polygon (fewer than three points when nothing is left).
398
+ */
399
+ function clipHalfPlane(poly, site, other) {
400
+ const mx = (site[0] + other[0]) / 2;
401
+ const my = (site[1] + other[1]) / 2;
402
+ const nx = other[0] - site[0];
403
+ const ny = other[1] - site[1];
404
+ if (nx * nx + ny * ny < 1e-12) return poly;
405
+ /** @type {[number, number][]} */
406
+ const out = [];
407
+ for (let i = 0; i < poly.length; i++) {
408
+ const a = poly[i];
409
+ const b = poly[(i + 1) % poly.length];
410
+ const da = (a[0] - mx) * nx + (a[1] - my) * ny;
411
+ const db = (b[0] - mx) * nx + (b[1] - my) * ny;
412
+ if (da <= 0) out.push(a);
413
+ if (da <= 0 !== db <= 0) {
414
+ const t = da / (da - db);
415
+ out.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);
416
+ }
417
+ }
418
+ return out;
419
+ }
420
+
421
+ /**
422
+ * One frame's cells as polygons, in CSS px from the top left: what the
423
+ * shader draws, as the sketch drew it (each cell clipped against its
424
+ * neighbours' bisectors, the inner cells against their macro cell).
425
+ *
426
+ * @param {VoronoiMeshConfig} config The settings (the same as the shader's).
427
+ * @param {number} width The target's width, CSS px.
428
+ * @param {number} height Its height.
429
+ * @param {number} [time=0] Seconds, as the shader's clock (already at its speed).
430
+ * @returns {{ macro: [number, number][][], inner: [number, number][][] }} The macro cells and the inner cells.
431
+ */
432
+ export function meshPolygons(config, width, height, time = 0) {
433
+ const o = withDefaults(config);
434
+ const options = seedOptions(config);
435
+ const clock = clockAt(time, o.breathe);
436
+ const unit = width / o.cells;
437
+ const [ox, oy] = config.offset ?? [0, 0];
438
+ const x0 = ox;
439
+ const y0 = oy;
440
+ const x1 = ox + o.cells;
441
+ const y1 = oy + height / unit;
442
+ /** @type {[number, number][]} */
443
+ const bound = [
444
+ [x0 - 1, y0 - 1],
445
+ [x1 + 1, y0 - 1],
446
+ [x1 + 1, y1 + 1],
447
+ [x0 - 1, y1 + 1],
448
+ ];
449
+ const toPx = (/** @type {[number, number][]} */ poly) => poly.map(([x, y]) => /** @type {[number, number]} */ ([(x - x0) * unit, (y - y0) * unit]));
450
+ /** @type {[number, number][][]} */
451
+ const macro = [];
452
+ /** @type {[number, number][][]} */
453
+ const inner = [];
454
+ for (let cy = Math.floor(y0) - 2; cy <= Math.floor(y1) + 2; cy++)
455
+ for (let cx = Math.floor(x0) - 2; cx <= Math.floor(x1) + 2; cx++) {
456
+ const seed = macroSeed(cx, cy, clock, options);
457
+ let poly = bound;
458
+ for (let j = -2; j <= 2 && poly.length > 2; j++)
459
+ for (let i = -2; i <= 2 && poly.length > 2; i++) if (i || j) poly = clipHalfPlane(poly, seed, macroSeed(cx + i, cy + j, clock, options));
460
+ if (poly.length < 3) continue;
461
+ macro.push(toPx(poly));
462
+ const seeds = innerSeeds(cx, cy, clock, options);
463
+ for (const [k, q] of seeds.entries()) {
464
+ let cell = poly;
465
+ for (const [m, r] of seeds.entries()) if (m !== k && cell.length > 2) cell = clipHalfPlane(cell, q, r);
466
+ if (cell.length > 2) inner.push(toPx(cell));
467
+ }
468
+ }
469
+ return { macro, inner };
470
+ }
471
+
472
+ /**
473
+ * The two line colours as the shader takes them.
474
+ *
475
+ * @param {VoronoiMeshConfig} config The settings.
476
+ * @returns {[string, string]} The macro lines' colour and the inner lines'.
477
+ */
478
+ export function meshColors(config) {
479
+ const colors = pickColors(config, STONE, (palette) => [palette.glint, palette.colors[0]]);
480
+ return [colors[0], colors[1] ?? colors[0]];
481
+ }
482
+
483
+ /**
484
+ * One frame as an SVG, the polygons of `meshPolygons` stroked in the
485
+ * line colours over the ground, with the quiet area as a mask: the still
486
+ * a page shows before the shader starts and without WebGL.
487
+ *
488
+ * @param {VoronoiMeshConfig} config The settings (the same as the shader's).
489
+ * @param {number} width The target's width, CSS px.
490
+ * @param {number} height Its height.
491
+ * @param {number} [time=0] Seconds, as the shader's clock.
492
+ * @returns {string} The SVG's markup.
493
+ */
494
+ export function meshSvg(config, width, height, time = 0) {
495
+ const o = withDefaults(config);
496
+ const { macro, inner } = meshPolygons(config, width, height, time);
497
+ const [macroColor, innerColor] = meshColors(config);
498
+ const drive = driveAt(time, o.breathe);
499
+ const w = o.width * (1 + drive * WIDTH_BOOST);
500
+ const alpha = [Math.min(1, o.opacity[0] * (1 + drive)), o.opacity[1]];
501
+ const r = (/** @type {number} */ n) => Math.round(n * 10) / 10;
502
+ const path = (/** @type {[number, number][][]} */ polys) => polys.map((poly) => `M${poly.map(([x, y]) => `${r(x)} ${r(y)}`).join('L')}Z`).join('');
503
+ const [qx, qy, radius, depth] = quietUniform(config.quiet, width / height);
504
+ let mask = '';
505
+ let use = '';
506
+ if (radius > 0) {
507
+ const stops = [0, 0.06, 0.25, 0.5, 0.75, 1].map((at) => {
508
+ const t = Math.min(1, Math.max(0, (at - 0.06) / 0.94));
509
+ const v = Math.round((1 - depth + depth * t * t * (3 - 2 * t)) * 255);
510
+ return `<stop offset="${at}" stop-color="rgb(${v},${v},${v})"/>`;
511
+ });
512
+ mask = `<radialGradient id="q" gradientUnits="userSpaceOnUse" cx="${r(width / 2 + qx * height)}" cy="${r(height / 2 - qy * height)}" r="${r(radius * height)}">${stops.join('')}</radialGradient><mask id="m"><rect width="${width}" height="${height}" fill="url(#q)"/></mask>`;
513
+ use = ' mask="url(#m)"';
514
+ }
515
+ const opaque = Boolean(o.background) && o.background !== 'transparent';
516
+ const ground = opaque ? `<rect width="${width}" height="${height}" fill="${o.background}"/>` : '';
517
+ /**
518
+ * A tier's stroke: on a ground, the line colour mixed into it in Oklab at
519
+ * the tier's opacity (as the shader mixes) and drawn solid; with none,
520
+ * the colour itself at that opacity.
521
+ *
522
+ * @param {string} color The line colour.
523
+ * @param {number} a The tier's opacity.
524
+ * @returns {string} The path's stroke attributes.
525
+ */
526
+ const stroke = (color, a) =>
527
+ opaque ? `stroke="${toHex(mixOklab(parseColor(o.background), parseColor(color), a))}"` : `stroke="${color}" opacity="${r(a * 100) / 100}"`;
528
+ const lines = [
529
+ inner.length && o.inner > 0 ? `<path d="${path(inner)}" ${stroke(innerColor, alpha[1])} stroke-width="${r(w * INNER_WIDTH * 100) / 100}"/>` : '',
530
+ `<path d="${path(macro)}" ${stroke(macroColor, alpha[0])} stroke-width="${r(w * 100) / 100}"/>`,
531
+ ].join('');
532
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">${mask ? `<defs>${mask}</defs>` : ''}${ground}<g fill="none" stroke-linejoin="round"${use}>${lines}</g></svg>`;
533
+ }
534
+
535
+ /**
536
+ * One frame as a CSS `background`: the SVG of `meshSvg` as a data URL,
537
+ * stretched to the box, over the ground colour. For the element's
538
+ * `background` (or a card's) so the mesh shows before the shader starts
539
+ * and without WebGL. Made for one size: a box of another shape stretches
540
+ * it, so give the box's own size.
541
+ *
542
+ * @param {VoronoiMeshConfig} config The settings (the same as the shader's).
543
+ * @param {number} width The box's width, CSS px.
544
+ * @param {number} height Its height.
545
+ * @param {number} [time=0] Seconds, as the shader's clock.
546
+ * @returns {string} A CSS `background` value.
547
+ */
548
+ export function meshStill(config, width, height, time = 0) {
549
+ const svg = meshSvg(config, width, height, time).replace(/[#%<>"]/g, (c) => encodeURIComponent(c));
550
+ const ground = config.background === 'transparent' ? 'transparent' : config.background ?? MESH_DEFAULTS.background;
551
+ return `url("data:image/svg+xml,${svg}") 0 0 / 100% 100% no-repeat, ${ground}`;
552
+ }
553
+
554
+ /**
555
+ * Starts the mesh on an element: a canvas inside it (its first), filling it.
556
+ *
557
+ * @param {HTMLElement} el The element.
558
+ * @param {VoronoiMeshConfig} config The settings.
559
+ * @returns {() => void} Stops it.
560
+ */
561
+ export function voronoiMesh(el, config) {
562
+ const o = withDefaults(config);
563
+ const options = seedOptions(config);
564
+ const speed = config.speed ?? 1;
565
+ const lab = (/** @type {string} */ c) => toOklab(parseColor(c));
566
+ let [macro, inner] = meshColors(config).map(lab);
567
+ const opaque = Boolean(o.background) && o.background !== 'transparent';
568
+ const bg = opaque ? [...lab(o.background), 1] : [0, 0, 0, 0];
569
+ const start = performance.now();
570
+ let ratio = 1;
571
+
572
+ const { stage, stop } = createStage(el, {
573
+ fragment: FRAG,
574
+ still: speed <= 0,
575
+ setup({ gl, uniform }) {
576
+ gl.uniform1f(uniform('uCells'), Math.max(0.5, o.cells));
577
+ gl.uniform2f(uniform('uOffset'), ...(config.offset ?? [0, 0]));
578
+ gl.uniform1f(uniform('uJitter'), options.jitter);
579
+ gl.uniform1f(uniform('uOrbit'), options.orbit);
580
+ gl.uniform1f(uniform('uInner'), options.inner);
581
+ gl.uniform1f(uniform('uSpread'), options.spread);
582
+ gl.uniform1f(uniform('uPulse'), options.pulse);
583
+ gl.uniform4f(uniform('uBg'), bg[0], bg[1], bg[2], bg[3]);
584
+ },
585
+ resize({ gl, uniform, canvas, ratio: r }) {
586
+ ratio = r;
587
+ gl.uniform4f(uniform('uQuiet'), ...quietUniform(config.quiet, canvas.width / canvas.height));
588
+ },
589
+ uniforms({ gl, uniform }, now) {
590
+ const t = ((now - start) / 1000) * Math.max(0, speed);
591
+ const drive = driveAt(t, o.breathe);
592
+ const w = o.width * (1 + drive * WIDTH_BOOST) * ratio;
593
+ gl.uniform1f(uniform('uClock'), clockAt(t, o.breathe));
594
+ gl.uniform2f(uniform('uWidth'), w, w * INNER_WIDTH);
595
+ gl.uniform2f(uniform('uAlpha'), Math.min(1, o.opacity[0] * (1 + drive)), o.inner > 0 ? o.opacity[1] : 0);
596
+ gl.uniform3f(uniform('uMacro'), macro[0], macro[1], macro[2]);
597
+ gl.uniform3f(uniform('uInnerCol'), inner[0], inner[1], inner[2]);
598
+ },
599
+ });
600
+ if (!stage) return stop;
601
+
602
+ const unwatch = watchColors(el, (next) => {
603
+ [macro, inner] = meshColors({ colors: next.colors }).map(lab);
604
+ if (stage.still) stage.redraw();
605
+ });
606
+ return () => {
607
+ stop();
608
+ unwatch();
609
+ };
610
+ }