@jsb188/gfx 1.1.2

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.
Files changed (65) hide show
  1. package/README.md +522 -0
  2. package/elements/Shapes.helpers.ts +204 -0
  3. package/elements/Shapes.hooks.ts +171 -0
  4. package/elements/Shapes.tsx +505 -0
  5. package/elements/Shapes.types.ts +81 -0
  6. package/elements/Stack.helpers.ts +42 -0
  7. package/elements/Stack.tsx +143 -0
  8. package/elements/Text.helpers.ts +45 -0
  9. package/elements/Text.hooks.ts +197 -0
  10. package/elements/Text.tsx +98 -0
  11. package/libs/chain.ts +174 -0
  12. package/libs/dotGrid.helpers.ts +53 -0
  13. package/libs/dotGrid.ts +954 -0
  14. package/libs/effects/dotEffects.ts +136 -0
  15. package/libs/effects/effectQuad.ts +146 -0
  16. package/libs/effects/effectRegion.ts +299 -0
  17. package/libs/effects/imageEffects.ts +599 -0
  18. package/libs/effects/index.ts +8 -0
  19. package/libs/effects/ripple.ts +160 -0
  20. package/libs/glsl.ts +134 -0
  21. package/libs/passes.ts +374 -0
  22. package/libs/pointer.ts +151 -0
  23. package/libs/runtime.ts +329 -0
  24. package/libs/texture.ts +160 -0
  25. package/libs/types.ts +94 -0
  26. package/libs/uniforms.ts +32 -0
  27. package/main.ts +4 -0
  28. package/modules/Carousel.helpers.ts +316 -0
  29. package/modules/Carousel.hooks.ts +520 -0
  30. package/modules/Carousel.tsx +631 -0
  31. package/modules/Dots.tsx +269 -0
  32. package/modules/DotsBoard.helpers.ts +388 -0
  33. package/modules/DotsBoard.hooks.ts +144 -0
  34. package/modules/DotsBoard.strings.ts +649 -0
  35. package/modules/DotsBoard.types.ts +240 -0
  36. package/modules/DotsBoardCanvas.hooks.ts +49 -0
  37. package/modules/DotsBoardCanvas.tsx +190 -0
  38. package/modules/DotsBoardElements.tsx +330 -0
  39. package/modules/Gallery.helpers.ts +32 -0
  40. package/modules/Gallery.hooks.ts +149 -0
  41. package/modules/Gallery.tsx +194 -0
  42. package/modules/GfxCanvas.hooks.ts +12 -0
  43. package/modules/GfxCanvas.tsx +189 -0
  44. package/modules/Hero.tsx +90 -0
  45. package/modules/KineticHeader.helpers.ts +44 -0
  46. package/modules/KineticHeader.hooks.ts +206 -0
  47. package/modules/KineticHeader.tsx +305 -0
  48. package/modules/KineticHeader.types.ts +56 -0
  49. package/modules/ScrollSteps.hooks.ts +138 -0
  50. package/modules/ScrollSteps.tsx +98 -0
  51. package/package.json +52 -0
  52. package/scenes/Carousel.ts +277 -0
  53. package/scenes/DotsBoard.helpers.ts +12 -0
  54. package/scenes/DotsBoard.ts +245 -0
  55. package/scenes/Hero.ts +280 -0
  56. package/tsconfig.json +13 -0
  57. package/utils/align.ts +18 -0
  58. package/utils/color.ts +112 -0
  59. package/utils/dotEffectSpecs.ts +79 -0
  60. package/utils/dotGridSpecs.ts +469 -0
  61. package/utils/easing.ts +18 -0
  62. package/utils/imageEffectSpecs.ts +89 -0
  63. package/utils/motion.ts +88 -0
  64. package/utils/random.ts +22 -0
  65. package/utils/strings.ts +116 -0
@@ -0,0 +1,954 @@
1
+ import { Geometry, Mesh, Program } from 'ogl';
2
+ import type { OGLRenderingContext } from 'ogl';
3
+ import { hexToRgb } from '../utils/color.ts';
4
+ import {
5
+ DOT_ROUNDED_SQUARE_CORNER,
6
+ DOT_RING_INNER_RADIUS,
7
+ DOT_GRID_DEFAULTS,
8
+ DOT_SHAPES,
9
+ getDotGridAnchor,
10
+ getDotGridCoverSize,
11
+ isDotGridInteractive,
12
+ resolveDotGridOptions,
13
+ } from '../utils/dotGridSpecs.ts';
14
+ import type { DotGridOptions } from '../utils/dotGridSpecs.ts';
15
+ import { getDotEffectId } from '../utils/dotEffectSpecs.ts';
16
+ import { PassChain, createPassProgram } from './chain.ts';
17
+ import { DOT_CLICK_MAX_EFFECTS, createDotClickEffects } from './dotGrid.helpers.ts';
18
+ import { GLSL_DOT_EFFECTS, createDotEffectUniforms, dotEffectDeclarations, setDotEffectUniforms } from './effects/dotEffects.ts';
19
+ import { GLSL_CONSTANTS, GLSL_COVER_UV, GLSL_HASH2, GLSL_HEADER, fragmentShader } from './glsl.ts';
20
+ import type { ImageTexture } from './texture.ts';
21
+ import type { RGB, SceneSize } from './types.ts';
22
+ import { setVec2 } from './uniforms.ts';
23
+
24
+ /**
25
+ * A grid of evenly spaced dots, one GPU point each, that a moving cursor throws aside and
26
+ * that spring back home with a damped bounce. Each dot's offset and velocity live in one
27
+ * texel of a half-float ping-pong texture (`cols × rows`) that a fullscreen pass advances
28
+ * every frame; the point shader reads its texel by `gl_VertexID`, so no vertex buffer is
29
+ * ever uploaded. A still cursor does nothing: the kick scales with cursor speed. Thrown dots
30
+ * can take a second color, opacity, and size that fade as they settle. An overlay image can
31
+ * replace the flat color: each dot shows the part of the cover-fit image under it, so bigger
32
+ * dots reveal more of it. A reveal amount grows the dots to full coverage, so at 0 the grid
33
+ * reads as a solid image or color, and a pulse makes a random few dots swell and shrink each
34
+ * cycle. A bottom fade turns the dots over the last so many pixels transparent, or into one
35
+ * flat color, toward the bottom edge (thrown or pulsing or not, and the image through them);
36
+ * the filled reveal state has its own bottom fade, which a fade handoff amount crosses over to
37
+ * the dots' once they have shrunk. Output is premultiplied for a transparent canvas.
38
+ */
39
+
40
+ // Per texel: xy = offset from home (CSS px), zw = velocity (px/s). Each frame the cursor
41
+ // kicks dots inside `uRadius` of it away from itself in proportion to its speed (with a
42
+ // per-dot random factor for a scattered look), then a damped spring (ω, ζ) pulls them home.
43
+ // Inside the bottom fade the kick eases off with the dot's depth into it (none on the bottom
44
+ // edge), so the fading dots stay put. Semi-implicit Euler stays stable while ω·dt < 2, so
45
+ // large frames are split into substeps.
46
+ const SPRING_FRAGMENT = fragmentShader(
47
+ `
48
+ uniform vec2 uOrigin;
49
+ uniform float uSpacing;
50
+ uniform vec2 uPointer;
51
+ uniform vec2 uPointerVelocity;
52
+ uniform float uRadius;
53
+ uniform float uStrength;
54
+ uniform float uRandomness;
55
+ uniform float uImpulse;
56
+ uniform float uImpulseRadius;
57
+ uniform float uImpulseStrength;
58
+ uniform float uImpulseRandomness;
59
+ uniform float uImpulseSeed;
60
+ uniform float uOmega;
61
+ uniform float uZeta;
62
+ uniform float uDt;
63
+ uniform int uSteps;
64
+ uniform float uHeight;
65
+ uniform float uFadeBottom;
66
+ /*
67
+ * Vary a kick's strength and angle while preserving its outward (or inward) direction.
68
+ */
69
+ vec2 scatterDotKick(vec2 direction, vec2 variation, float randomness) {
70
+ float angle = variation.y * randomness * 0.8;
71
+ vec2 scattered = direction * cos(angle) + vec2(-direction.y, direction.x) * sin(angle);
72
+ return scattered * (1.0 + variation.x * randomness);
73
+ }
74
+ void main() {
75
+ ivec2 cell = ivec2(gl_FragCoord.xy);
76
+ vec4 state = texelFetch(tInput, cell, 0);
77
+ vec2 offset = state.xy;
78
+ vec2 velocity = state.zw;
79
+ vec2 home = uOrigin + vec2(cell) * uSpacing;
80
+ float speed = length(uPointerVelocity);
81
+ // How far from the bottom fade the dot's home is (1 above it, 0 on the bottom edge).
82
+ float fade = uFadeBottom > 0.0 ? clamp((uHeight - home.y) / uFadeBottom, 0.0, 1.0) : 1.0;
83
+ float random = (0.6 + 0.8 * hash2(vec2(cell)).x) * fade;
84
+ // A click adds one radial impulse; subsequent frames use the same spring as cursor kicks.
85
+ if (uImpulse > 0.0) {
86
+ vec2 away = home + offset - uPointer;
87
+ float dist = length(away);
88
+ if (dist < uImpulseRadius) {
89
+ float falloff = 1.0 - dist / uImpulseRadius;
90
+ vec2 direction = dist > 0.001 ? away / dist : vec2(1.0, 0.0);
91
+ // Seed once per click so the kick varies without adding jitter during the return.
92
+ vec2 variation = hash2(vec2(cell) + uImpulseSeed) * 2.0 - 1.0;
93
+ direction = scatterDotKick(direction, variation, uImpulseRandomness);
94
+ velocity += direction * uImpulseStrength * uImpulseRadius * uOmega * falloff * falloff * random;
95
+ }
96
+ }
97
+ float dt = uDt / float(uSteps);
98
+ // Keep hover variation fixed per dot so continuous cursor movement never rerolls it frame to frame.
99
+ vec2 hoverVariation = hash2(vec2(cell) + 19.0) * 2.0 - 1.0;
100
+ for (int i = 0; i < 8; i++) {
101
+ if (i >= uSteps) break;
102
+ vec2 away = home + offset - uPointer;
103
+ float dist = length(away);
104
+ if (speed > 0.0 && dist < uRadius) {
105
+ float falloff = 1.0 - dist / uRadius;
106
+ vec2 direction = dist > 0.001 ? away / dist : vec2(1.0, 0.0);
107
+ direction = scatterDotKick(direction, hoverVariation, uRandomness);
108
+ velocity += direction * (uStrength * speed * 0.5 * uOmega * falloff * falloff * random) * dt;
109
+ }
110
+ velocity += (-uOmega * uOmega * offset - 2.0 * uZeta * uOmega * velocity) * dt;
111
+ offset += velocity * dt;
112
+ }
113
+ fragColor = vec4(offset, velocity);
114
+ }
115
+ `,
116
+ [GLSL_HASH2],
117
+ );
118
+
119
+ const REST_FRAGMENT = fragmentShader(`
120
+ void main() {
121
+ fragColor = vec4(0.0);
122
+ }
123
+ `);
124
+
125
+ // The resting diameter eases from the cover size to `uDotSize` with `uReveal`; the thrown and
126
+ // pulse scales multiply on top, and the sprite is capped at what the driver allows. Inside
127
+ // the bottom fade the thrown scale is eased off with the dot's depth into it, so the dots
128
+ // that are fading out (or to the fade color) do not swell under the cursor as the others do;
129
+ // the throw itself is unchanged. A pulse
130
+ // cycle is `floor(time / interval)`: hashing the cell with the cycle picks about `chance` of
131
+ // the dots (never the same dot twice in a row) and gives each a random start inside the cycle,
132
+ // so no per-dot state is needed.
133
+ const DOT_GRID_VERTEX = `${GLSL_HEADER}${GLSL_CONSTANTS}
134
+ uniform vec2 uResolution;
135
+ uniform vec2 uViewSize;
136
+ uniform vec2 uViewOrigin;
137
+ uniform float uPixelRatio;
138
+ uniform vec2 uHoverPointer;
139
+ uniform float uHoverRadius;
140
+ uniform float uHoverAmount;
141
+ uniform float uHoverFade;
142
+ uniform float uColumns;
143
+ uniform vec2 uOrigin;
144
+ uniform float uSpacing;
145
+ uniform float uDotSize;
146
+ uniform float uCoverSize;
147
+ uniform float uRevealSize;
148
+ uniform float uReveal;
149
+ uniform float uFadeBottom;
150
+ uniform sampler2D tState;
151
+ uniform float uOmega;
152
+ uniform float uThrowScale;
153
+ uniform float uOpacity;
154
+ uniform float uThrownOpacity;
155
+ uniform float uThrownScale;
156
+ uniform float uMaxPointSize;
157
+ uniform float uTime;
158
+ uniform float uPulseStart;
159
+ uniform float uPulseChance;
160
+ uniform float uPulseInterval;
161
+ uniform float uRestOn;
162
+ uniform float uRestInterval;
163
+ uniform float uRestRandomOrigin;
164
+ uniform float uMotionEnabled;
165
+ uniform vec4 uClicks[${DOT_CLICK_MAX_EFFECTS}];
166
+ uniform float uClickEffects[${DOT_CLICK_MAX_EFFECTS}];
167
+ ${dotEffectDeclarations('uPulse')}
168
+ ${dotEffectDeclarations('uClick')}
169
+ ${dotEffectDeclarations('uRest')}
170
+ out float vHover;
171
+ out float vWeight;
172
+ out float vPulse;
173
+ out float vRest;
174
+ out vec4 vEffectTint;
175
+ out float vClick;
176
+ out float vOpacity;
177
+ out float vRadius;
178
+ out float vPointSize;
179
+ flat out ivec2 vCell;
180
+
181
+ // Integer bit-mixing hash: exact on every GPU, unlike sin-based float hashes whose results drift
182
+ // (and correlate between cycles) once the inputs grow large.
183
+ uint hashUint(uint x) {
184
+ x ^= x >> 16u;
185
+ x *= 0x7feb352du;
186
+ x ^= x >> 15u;
187
+ x *= 0x846ca68bu;
188
+ x ^= x >> 16u;
189
+ return x;
190
+ }
191
+
192
+ float cellRandom(ivec2 cell, int cycle, uint salt) {
193
+ uint seed = uint(cell.x) * 73856093u ^ uint(cell.y) * 19349663u ^ uint(cycle) * 83492791u ^ salt * 2654435761u;
194
+ return float(hashUint(seed)) / 4294967295.0;
195
+ }
196
+
197
+ bool pulsesIn(ivec2 cell, int cycle) {
198
+ return cellRandom(cell, cycle, 1u) < uPulseChance;
199
+ }
200
+
201
+ ${GLSL_DOT_EFFECTS}
202
+
203
+ /*
204
+ * Sample a selected dot's pulse. A stable local origin gives motion effects a small orbit
205
+ * around home; the default swell preserves the original pulse's timing and size exactly.
206
+ */
207
+ DotEffectSample pulseEffect(ivec2 cell, out float seed) {
208
+ seed = 0.0;
209
+ float time = uTime - uPulseStart;
210
+ if (uMotionEnabled < 0.5 || uPulseChance <= 0.0 || uPulseStart < 0.0 || time < 0.0) return noDotEffect();
211
+ int cycle = int(floor(time / uPulseInterval));
212
+ if (!pulsesIn(cell, cycle) || (cycle > 0 && pulsesIn(cell, cycle - 1))) return noDotEffect();
213
+ float start = cellRandom(cell, cycle, 2u) * (uPulseInterval - uPulseDuration);
214
+ float phase = (time - float(cycle) * uPulseInterval - start) / uPulseDuration;
215
+ seed = cellRandom(cell, cycle, 3u);
216
+ int effect = selectDotEffect(uPulseEffect, cellRandom(cell, cycle, 4u));
217
+ vec2 away = effect == 0 ? vec2(0.0) : vec2(cos(seed * PI * 2.0), sin(seed * PI * 2.0)) * uPulseRadius * 0.35;
218
+ return sampleDotEffect(effect, away, phase, seed, uPulseRadius, uPulseWidth, uPulseStrength);
219
+ }
220
+
221
+ /*
222
+ * Animate the resting grid from a fixed or randomly chosen origin. Origin and effect remain
223
+ * stable for the whole cycle, while sparkle timing can differ between individual dots.
224
+ */
225
+ DotEffectSample restEffect(ivec2 cell, vec2 position, out float seed) {
226
+ seed = 0.0;
227
+ float time = uTime - uPulseStart;
228
+ if (uMotionEnabled < 0.5 || uRestOn < 0.5 || uPulseStart < 0.0 || time < 0.0) return noDotEffect();
229
+ int cycle = int(floor(time / uRestInterval));
230
+ float phase = (time - float(cycle) * uRestInterval) / uRestDuration;
231
+ seed = cellRandom(ivec2(0), cycle, 50u);
232
+ vec2 origin = uResolution * 0.5;
233
+ if (uRestRandomOrigin > 0.5) {
234
+ origin = uResolution * (0.15 + 0.7 * vec2(cellRandom(ivec2(0), cycle, 51u), cellRandom(ivec2(0), cycle, 52u)));
235
+ }
236
+ return sampleDotEffect(selectDotEffect(uRestEffect, seed), position - origin, phase, cellRandom(cell, cycle, 53u), uRestRadius, uRestWidth, uRestStrength);
237
+ }
238
+
239
+ /*
240
+ * Sample overlapping clicks; each dot follows the strongest effect so repeated clicks do
241
+ * not stack unbounded movement, scale, or opacity. Effect IDs are chosen only at click time.
242
+ */
243
+ DotEffectSample clickEffect(ivec2 cell, vec2 position, out float seed) {
244
+ seed = 0.0;
245
+ DotEffectSample result = noDotEffect();
246
+ if (uMotionEnabled < 0.5) return result;
247
+ for (int i = 0; i < ${DOT_CLICK_MAX_EFFECTS}; i++) {
248
+ vec4 click = uClicks[i];
249
+ if (click.w < 0.5) continue;
250
+ float phase = (uTime - click.z) / uClickDuration;
251
+ int cycle = int(click.z * 1000.0) + i;
252
+ DotEffectSample candidate = sampleDotEffect(int(uClickEffects[i]), position - click.xy, phase, cellRandom(cell, cycle, 31u), uClickRadius, uClickWidth, uClickStrength);
253
+ if (candidate.amount > result.amount) {
254
+ result = candidate;
255
+ seed = cellRandom(ivec2(i), cycle, 32u);
256
+ }
257
+ }
258
+ return result;
259
+ }
260
+
261
+ void main() {
262
+ // Integer division, exact on every GPU (a float mod/divide can land a row's first dot at the end of the row before).
263
+ int columns = int(uColumns + 0.5);
264
+ ivec2 cell = ivec2(gl_VertexID % columns, gl_VertexID / columns);
265
+ vCell = cell;
266
+ vec4 state = texelFetch(tState, cell, 0);
267
+ vec2 position = uOrigin + vec2(cell) * uSpacing + state.xy;
268
+ // How far the dot has been thrown: the spring's swing amplitude, which decays smoothly
269
+ // instead of dipping every time the dot passes through home.
270
+ float amplitude = length(vec2(length(state.xy), length(state.zw) / uOmega));
271
+ float weight = clamp(amplitude * uThrowScale, 0.0, 1.0);
272
+ vWeight = weight;
273
+ float restSeed;
274
+ float pulseSeed;
275
+ float clickSeed;
276
+ DotEffectSample resting = restEffect(cell, position, restSeed);
277
+ DotEffectSample pulsing = pulseEffect(cell, pulseSeed);
278
+ DotEffectSample clicking = clickEffect(cell, position, clickSeed);
279
+ vRest = resting.amount;
280
+ vPulse = pulsing.amount;
281
+ vClick = clicking.amount;
282
+ vEffectTint = vec4(0.0);
283
+ addDotEffectTint(vEffectTint, resting, uRestColor, uRestColorOn, restSeed);
284
+ addDotEffectTint(vEffectTint, pulsing, uPulseColor, uPulseColorOn, pulseSeed);
285
+ addDotEffectTint(vEffectTint, clicking, uClickColor, uClickColorOn, clickSeed);
286
+ float opacity = mix(mix(uOpacity, uRestOpacity, vRest), uPulseOpacity, vPulse);
287
+ vOpacity = mix(mix(opacity, uThrownOpacity, weight), uClickOpacity, vClick);
288
+ // New movement fades near the bottom along with the cursor's existing size response.
289
+ float fade = uFadeBottom > 0.0 ? clamp((uResolution.y - position.y) / uFadeBottom, 0.0, 1.0) : 1.0;
290
+ position += (resting.offset + pulsing.offset + clicking.offset) * fade;
291
+ float hoverDistance = length(position - uHoverPointer) / max(1.0, uHoverRadius);
292
+ vHover = uHoverAmount * (uHoverFade > 0.5 ? max(0.0, 1.0 - hoverDistance) : (hoverDistance < 1.0 ? 1.0 : 0.0));
293
+ vec2 uv = (position - uViewOrigin) / uViewSize;
294
+ gl_Position = vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0);
295
+ // One device pixel on each side keeps the anti-aliased rim inside the sprite.
296
+ float size = uRevealSize >= 0.0 ? uRevealSize : mix(uCoverSize, uDotSize, uReveal);
297
+ size *= mix(1.0, uThrownScale, weight * fade);
298
+ size *= mix(1.0, uRestScale, vRest) * mix(1.0, uPulseScale, vPulse);
299
+ size = mix(size, uDotSize * uClickScale, vClick);
300
+ vPointSize = min(size * uPixelRatio + 2.0, uMaxPointSize);
301
+ vRadius = (vPointSize - 2.0) * 0.5;
302
+ gl_PointSize = vPointSize;
303
+ }
304
+ `;
305
+
306
+ // The overlay is sampled at the fragment's own screen position, not the dot's center, so
307
+ // a dot is a window onto the cover-fit image and a larger dot shows more of it. The shape is
308
+ // a signed distance from the sprite center (device pixels, negative inside), which gives every
309
+ // shape the same one-pixel anti-aliased rim and lets a pulsing dot morph between its resting
310
+ // shape and the pulse shape by blending the two distances. The bottom fade is also by screen
311
+ // position, so a dot thrown into the fade zone fades with it, to transparent or to the fade
312
+ // color when one is on. While a reveal runs, each dot is clipped to its own grid cell: at cover
313
+ // size the dots overlap along every cell edge, and where a fade makes them translucent the
314
+ // overlaps would blend to a higher alpha than either dot and draw as a grid of seams. Cells
315
+ // tile the area exactly, so the fill stays seamless; the clip is off once kicks can move dots.
316
+ const DOT_GRID_FRAGMENT = `${GLSL_HEADER}
317
+ uniform vec2 uResolution;
318
+ uniform vec2 uViewSize;
319
+ uniform vec2 uViewOrigin;
320
+ uniform float uPixelRatio;
321
+ uniform vec2 uOrigin;
322
+ uniform float uSpacing;
323
+ uniform float uReveal;
324
+ uniform float uFadeHandoff;
325
+ uniform float uFadeBottom;
326
+ uniform float uFadeColorOn;
327
+ uniform vec3 uFadeColor;
328
+ uniform float uBottomTintOn;
329
+ uniform vec2 uBottomTintRange;
330
+ uniform vec4 uBottomTint;
331
+ uniform int uBottomTintMode;
332
+ uniform float uImageFade;
333
+ uniform float uImageFadeColorOn;
334
+ uniform vec3 uImageFadeColor;
335
+ uniform int uShape;
336
+ uniform int uPulseShape;
337
+ uniform int uRestShape;
338
+ uniform int uClickShape;
339
+ uniform float uCorner;
340
+ uniform vec3 uColor;
341
+ uniform float uThrownColorOn;
342
+ uniform vec3 uThrownColor;
343
+ uniform sampler2D tOverlay;
344
+ uniform vec2 uOverlaySize;
345
+ uniform float uOverlayOn;
346
+ uniform float uOverlayZoom;
347
+ uniform vec2 uOverlayRegion;
348
+ uniform vec2 uOverlayOffset;
349
+ uniform float uOverlayFade;
350
+ uniform vec3 uHoverColor;
351
+ in float vHover;
352
+ in float vWeight;
353
+ in float vPulse;
354
+ in float vRest;
355
+ in vec4 vEffectTint;
356
+ in float vClick;
357
+ in float vOpacity;
358
+ in float vRadius;
359
+ in float vPointSize;
360
+ flat in ivec2 vCell;
361
+ out vec4 fragColor;
362
+ ${GLSL_COVER_UV}
363
+
364
+ float shapeDistance(int shape, vec2 p, float r) {
365
+ if (shape == 1 || shape == 3) {
366
+ float corner = r * uCorner;
367
+ vec2 q = abs(p) - (r - corner);
368
+ float outer = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - corner;
369
+ if (shape == 3) {
370
+ // Inset the same outline for a uniform stroke; keep its hole closed at reveal start.
371
+ float inner = -outer - r * (1.0 - ${DOT_RING_INNER_RADIUS});
372
+ return max(outer, mix(-r - 1.0, inner, uReveal));
373
+ }
374
+ return outer;
375
+ }
376
+ if (shape == 2) {
377
+ // A ring's hole opens with the reveal so its filled intro still covers every pixel.
378
+ float inner = mix(-r - 1.0, r * ${DOT_RING_INNER_RADIUS}, uReveal);
379
+ return max(length(p) - r, inner - length(p));
380
+ }
381
+ return length(p) - r;
382
+ }
383
+
384
+ /*
385
+ * Apply thrown and triggered effect tints equally to the base color and the image sample.
386
+ */
387
+ vec3 applyDotTints(vec3 base) {
388
+ vec3 color = mix(base, uThrownColor, vWeight * uThrownColorOn);
389
+ return color * (1.0 - vEffectTint.a) + vEffectTint.rgb;
390
+ }
391
+
392
+ void main() {
393
+ vec2 fragment = vec2(gl_FragCoord.x / uPixelRatio, uViewSize.y - gl_FragCoord.y / uPixelRatio) + uViewOrigin;
394
+ // A zero-sized dot must stay completely invisible, including its anti-aliased rim.
395
+ if (vRadius <= 0.0) discard;
396
+ vec2 p = (gl_PointCoord - 0.5) * vPointSize;
397
+ // The pixel's cell from its own screen position (CSS px, y down like the grid), the same
398
+ // arithmetic for every dot, so exactly one dot claims each pixel however gl_PointCoord rounds.
399
+ if (uReveal < 1.0) {
400
+ if (ivec2(floor((fragment - uOrigin) / uSpacing + 0.5)) != vCell) discard;
401
+ }
402
+ float dist = shapeDistance(uShape, p, vRadius);
403
+ if (vRest > 0.0) dist = mix(dist, shapeDistance(uRestShape, p, vRadius), vRest);
404
+ if (vPulse > 0.0) dist = mix(dist, shapeDistance(uPulseShape, p, vRadius), vPulse);
405
+ if (vClick > 0.0) dist = mix(dist, shapeDistance(uClickShape, p, vRadius), vClick);
406
+ float alpha = clamp(-dist + 0.5, 0.0, 1.0) * vOpacity;
407
+ // Two linear fades along the logical layer's bottom edge, each 0 above its zone
408
+ // and 1 on the edge: the filled state's over uImageFade CSS pixels while the handoff is 0,
409
+ // and the dots' over uFadeBottom once it is 1, crossing over in between.
410
+ float faded = uFadeBottom > 0.0 ? (1.0 - clamp((uResolution.y - fragment.y) / uFadeBottom, 0.0, 1.0)) * uFadeHandoff : 0.0;
411
+ float imageFaded = uImageFade > 0.0 ? (1.0 - clamp((uResolution.y - fragment.y) / uImageFade, 0.0, 1.0)) * (1.0 - uFadeHandoff) : 0.0;
412
+ // To transparent, unless a fade color takes over the color instead.
413
+ alpha *= 1.0 - faded * (1.0 - uFadeColorOn);
414
+ alpha *= 1.0 - imageFaded * (1.0 - uImageFadeColorOn);
415
+ // Sample the board's top image region, independently of the layer and viewport heights.
416
+ vec2 region = uOverlayRegion.y > 0.0 ? uOverlayRegion : uResolution;
417
+ vec2 imagePoint = fragment + uOverlayOffset;
418
+ vec2 imageUv = vec2(imagePoint.x / region.x, 1.0 - imagePoint.y / region.y);
419
+ vec2 overlayUv = (coverUv(imageUv, region, uOverlaySize) - 0.5) / uOverlayZoom + 0.5;
420
+ float imageWeight = imagePoint.y >= 0.0 && imagePoint.y < region.y ? 1.0 : 0.0;
421
+ if (uOverlayFade > 0.0) imageWeight *= clamp((region.y - imagePoint.y) / uOverlayFade, 0.0, 1.0);
422
+ // Fade the image into the active dot color: hover tint under the pointer, base color elsewhere.
423
+ // Full-strength image pixels keep priority, and the fade has no gray-to-hover seam.
424
+ vec3 color = mix(applyDotTints(uColor), uHoverColor, vHover);
425
+ if (uOverlayOn > 0.5 && imageWeight > 0.0) {
426
+ color = mix(color, applyDotTints(texture(tOverlay, overlayUv).rgb), imageWeight);
427
+ }
428
+ color = mix(color, uFadeColor, faded * uFadeColorOn);
429
+ color = mix(color, uImageFadeColor, imageFaded * uImageFadeColorOn);
430
+ // This final color band stays in logical board coordinates as the canvas window scrolls.
431
+ // Premultiplied interpolation preserves RGBA alpha without dimming the footer underneath.
432
+ float bottomDistance = uResolution.y - fragment.y;
433
+ float span = uBottomTintRange.x - uBottomTintRange.y;
434
+ float blend = span > 0.0 ? clamp((uBottomTintRange.x - bottomDistance) / span, 0.0, 1.0) : step(bottomDistance, uBottomTintRange.y);
435
+ vec4 tint = vec4(uBottomTint.rgb * uBottomTint.a, uBottomTint.a);
436
+ if (uBottomTintMode == 2) {
437
+ // Source-colored dots blend with the DOM backdrop through CSS. Effects still shape/move dots.
438
+ fragColor = tint * blend * alpha;
439
+ } else if (uBottomTintMode == 1) {
440
+ fragColor = vec4(color, 1.0) * (1.0 - blend) * alpha;
441
+ } else {
442
+ fragColor = mix(vec4(color, 1.0), tint, blend * uBottomTintOn) * alpha;
443
+ }
444
+ }
445
+ `;
446
+
447
+ const SPRING = {
448
+ // Substep so that ω·dt stays well inside the integrator's stability limit.
449
+ maxOmegaDt: 0.5,
450
+ // Matches the unrolled loop bound in the shader.
451
+ maxSteps: 8,
452
+ // Damping ratio at bounciness 0 (critical) and 1 (lightly damped).
453
+ zetaRange: [1, 0.15] as const,
454
+ // The swing decays as e^(-4t/T); by 1.5 T even a throw of hundreds of pixels is under a
455
+ // quarter pixel from home, so snapping the dots to rest there is invisible.
456
+ settleFactor: 1.5,
457
+ };
458
+
459
+ /*
460
+ * Build the simulation pass, the point program, an attribute-free geometry (WebGL2 draws
461
+ * from `gl_VertexID`), and the helpers that lay the grid out and drive it. The grid anchors a
462
+ * dot per `dots.alignX` / `alignY` (centered by default, like `mask-position: center` does for
463
+ * a CSS tile) and extends one spacing past every edge. Without half-float render targets the
464
+ * cursor kicks are disabled; the other effects still work.
465
+ */
466
+ export function createDotGrid(gl: OGLRenderingContext, initialOptions?: DotGridOptions) {
467
+ let options = resolveDotGridOptions(initialOptions);
468
+ let size: SceneSize = { width: 1, height: 1, pixelRatio: 1 };
469
+ let omega = 1;
470
+ let settleSeconds = 0;
471
+ let dotCount = 0;
472
+ let lastKickAt = Number.NEGATIVE_INFINITY;
473
+ let simulating = false;
474
+ const clicks = createDotClickEffects();
475
+ // Sprites larger than the driver allows would silently clamp, so the dot size is capped.
476
+ const [, maxPointSize] = gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE) as Float32Array;
477
+
478
+ const chain = new PassChain(gl, { halfFloat: true });
479
+ const spring = createPassProgram(gl, SPRING_FRAGMENT, {
480
+ uOrigin: { value: [0, 0] },
481
+ uSpacing: { value: 1 },
482
+ uPointer: { value: [-1e6, -1e6] },
483
+ uPointerVelocity: { value: [0, 0] },
484
+ uRadius: { value: 0 },
485
+ uStrength: { value: 0 },
486
+ uRandomness: { value: 0 },
487
+ uImpulse: { value: 0 },
488
+ uImpulseRadius: { value: 0 },
489
+ uImpulseStrength: { value: 0 },
490
+ uImpulseRandomness: { value: 0 },
491
+ uImpulseSeed: { value: 0 },
492
+ uOmega: { value: 1 },
493
+ uZeta: { value: 1 },
494
+ uDt: { value: 0 },
495
+ uSteps: { value: 1 },
496
+ uHeight: { value: 1 },
497
+ uFadeBottom: { value: 0 },
498
+ });
499
+ const restPass = createPassProgram(gl, REST_FRAGMENT);
500
+ const program = new Program(gl, {
501
+ vertex: DOT_GRID_VERTEX,
502
+ fragment: DOT_GRID_FRAGMENT,
503
+ uniforms: {
504
+ uResolution: { value: [1, 1] },
505
+ uViewSize: { value: [1, 1] },
506
+ uViewOrigin: { value: [0, 0] },
507
+ uPixelRatio: { value: 1 },
508
+ uShape: { value: 0 },
509
+
510
+ uCorner: { value: DOT_ROUNDED_SQUARE_CORNER },
511
+ uHoverPointer: { value: [-1e6, -1e6] },
512
+ uHoverRadius: { value: 0 },
513
+ uHoverAmount: { value: 0 },
514
+ uHoverFade: { value: 1 },
515
+ uHoverColor: { value: [0, 0, 0] },
516
+ uColumns: { value: 1 },
517
+ uOrigin: { value: [0, 0] },
518
+ uSpacing: { value: 1 },
519
+ uDotSize: { value: 1 },
520
+ uCoverSize: { value: 1 },
521
+ uRevealSize: { value: -1 },
522
+ uReveal: { value: 1 },
523
+ uFadeHandoff: { value: 1 },
524
+ uFadeBottom: { value: 0 },
525
+ uFadeColorOn: { value: 0 },
526
+ uFadeColor: { value: [1, 1, 1] },
527
+ uBottomTintOn: { value: 0 },
528
+ uBottomTintMode: { value: 0 },
529
+ uBottomTintRange: { value: [0, 0] },
530
+ uBottomTint: { value: [0, 0, 0, 0] },
531
+ uImageFade: { value: 0 },
532
+ uImageFadeColorOn: { value: 0 },
533
+ uImageFadeColor: { value: [1, 1, 1] },
534
+ tState: { value: chain.output },
535
+ uOmega: { value: 1 },
536
+ uThrowScale: { value: 0 },
537
+ uColor: { value: [1, 1, 1] },
538
+ uOpacity: { value: 1 },
539
+ uThrownColorOn: { value: 0 },
540
+ uThrownColor: { value: [1, 1, 1] },
541
+ uThrownOpacity: { value: 1 },
542
+ uThrownScale: { value: 1 },
543
+ uMaxPointSize: { value: maxPointSize },
544
+ uTime: { value: 0 },
545
+ uPulseStart: { value: -1 },
546
+ uPulseChance: { value: 0 },
547
+ uPulseInterval: { value: 1 },
548
+ ...createDotEffectUniforms('uPulse'),
549
+ ...createDotEffectUniforms('uClick'),
550
+ ...createDotEffectUniforms('uRest'),
551
+ uRestOn: { value: 0 },
552
+ uRestInterval: { value: 1 },
553
+ uRestRandomOrigin: { value: 0 },
554
+ uMotionEnabled: { value: 1 },
555
+ uClicks: { value: clicks.data },
556
+ uClickEffects: { value: clicks.effects },
557
+ // OGL dereferences every sampler on draw, so the slot holds the state texture until an overlay arrives.
558
+ tOverlay: { value: chain.output },
559
+ uOverlaySize: { value: [1, 1] },
560
+ uOverlayOn: { value: 0 },
561
+ uOverlayZoom: { value: 1 },
562
+ uOverlayRegion: { value: [0, 0] },
563
+ uOverlayOffset: { value: [0, 0] },
564
+ uOverlayFade: { value: 0 },
565
+ },
566
+ transparent: true,
567
+ depthTest: false,
568
+ depthWrite: false,
569
+ cullFace: false,
570
+ });
571
+ program.setBlendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
572
+ const geometry = new Geometry(gl);
573
+ const mesh = new Mesh(gl, { geometry, program, mode: gl.POINTS, frustumCulled: false });
574
+
575
+ /*
576
+ * Put every dot back home with no velocity, and stop stepping until the next kick.
577
+ */
578
+ function rest() {
579
+ program.uniforms.tState.value = chain.render([restPass]);
580
+ simulating = false;
581
+ }
582
+
583
+ /*
584
+ * Position the first dot (the last one at or before the canvas start on each axis, walking
585
+ * back from the alignment anchor), count how many cover the canvas plus a one-spacing
586
+ * margin, and give the simulation one texel per dot (which also rests every dot at home).
587
+ */
588
+ function layout() {
589
+ const { width, height, pixelRatio } = size;
590
+ const { spacing, size: dotSize, alignX, alignY } = options.dots;
591
+ const anchorX = getDotGridAnchor(alignX, dotSize, width);
592
+ const anchorY = getDotGridAnchor(alignY, dotSize, height);
593
+ const firstX = anchorX - Math.ceil(anchorX / spacing) * spacing;
594
+ const firstY = anchorY - Math.ceil(anchorY / spacing) * spacing;
595
+ const columns = Math.ceil((width - firstX) / spacing) + 1;
596
+ const rows = Math.ceil((height - firstY) / spacing) + 1;
597
+ const { uniforms } = program;
598
+ setVec2(uniforms.uResolution, width, height);
599
+ setVec2(uniforms.uOrigin, firstX, firstY);
600
+ setVec2(spring.uniforms.uOrigin, firstX, firstY);
601
+ spring.uniforms.uHeight.value = height;
602
+ uniforms.uPixelRatio.value = pixelRatio;
603
+ uniforms.uColumns.value = columns;
604
+ uniforms.uSpacing.value = spacing;
605
+ spring.uniforms.uSpacing.value = spacing;
606
+ uniforms.uDotSize.value = Math.min(dotSize, (maxPointSize - 2) / pixelRatio);
607
+ uniforms.uCoverSize.value = Math.min(getDotGridCoverSize(spacing, options.dots.shape), (maxPointSize - 2) / pixelRatio);
608
+ geometry.setDrawRange(0, columns * rows);
609
+ dotCount = columns * rows;
610
+ applyPulse();
611
+ chain.setSize(columns, rows);
612
+ rest();
613
+ }
614
+
615
+ /*
616
+ * Write the pulse uniforms; the chance is per dot, so it depends on how many dots there are.
617
+ */
618
+ function applyPulse() {
619
+ const { pulse } = options;
620
+ const { uniforms } = program;
621
+ uniforms.uPulseChance.value = pulse && dotCount > 0 ? Math.min(1, pulse.count / dotCount) : 0;
622
+ uniforms.uPulseInterval.value = (pulse?.interval ?? 1000) / 1000;
623
+ setDotEffectUniforms(uniforms, 'uPulse', pulse);
624
+ }
625
+
626
+ /*
627
+ * Write the spring (derived from the bounce settings: the return settles to ~2% in
628
+ * `bounceDuration`, and `bounciness` picks the damping ratio), the colors, and the thrown look.
629
+ * The pulse uniforms depend on the dot count, so `layout` writes those.
630
+ */
631
+ function applyOptions() {
632
+ const { dots, kick, thrown, click } = options;
633
+ const { uniforms } = program;
634
+ const bounce = kick ?? DOT_GRID_DEFAULTS.kick;
635
+ const zeta = SPRING.zetaRange[0] + (SPRING.zetaRange[1] - SPRING.zetaRange[0]) * bounce.bounciness;
636
+ omega = 4 / (zeta * (bounce.bounceDuration / 1000));
637
+ settleSeconds = (bounce.bounceDuration / 1000) * SPRING.settleFactor;
638
+ spring.uniforms.uRadius.value = kick?.radius ?? 0;
639
+ spring.uniforms.uStrength.value = kick?.strength ?? 0;
640
+ spring.uniforms.uRandomness.value = kick?.randomness ?? 0;
641
+ spring.uniforms.uImpulseRadius.value = click?.kickRadius ?? 0;
642
+ spring.uniforms.uImpulseStrength.value = click?.kickStrength ?? 0;
643
+ spring.uniforms.uImpulseRandomness.value = click?.kickRandomness ?? 0;
644
+ spring.uniforms.uOmega.value = omega;
645
+ spring.uniforms.uZeta.value = zeta;
646
+ uniforms.uOmega.value = omega;
647
+ // A dot counts as fully thrown at a quarter of the biggest throw a swipe can give
648
+ // (`radius × strength`); the kick falls off quadratically from the cursor, so most dots
649
+ // swing far less than that and this keeps the thrown look visible across the kicked area.
650
+ const throwDistance = Math.max(
651
+ kick ? kick.radius * Math.abs(kick.strength) : 0,
652
+ click && (click.effect === 'ripple' || click.effect === 'random') ? click.kickRadius * Math.abs(click.kickStrength) : 0,
653
+ );
654
+ uniforms.uThrowScale.value = throwDistance > 0 ? 4 / throwDistance : 0;
655
+ uniforms.uShape.value = DOT_SHAPES.indexOf(dots.shape);
656
+ setDotEffectUniforms(uniforms, 'uClick', click);
657
+ setDotEffectUniforms(uniforms, 'uRest', options.rest);
658
+ uniforms.uRestOn.value = options.rest ? 1 : 0;
659
+ uniforms.uRestInterval.value = (options.rest?.interval ?? 1000) / 1000;
660
+ uniforms.uRestRandomOrigin.value = options.rest?.origin === 'random' ? 1 : 0;
661
+ if (!click) clicks.update(0, 0);
662
+ uniforms.uColor.value = hexToRgb(dots.color, [1, 1, 1]);
663
+ uniforms.uOpacity.value = dots.opacity;
664
+ uniforms.uThrownColorOn.value = thrown?.color ? 1 : 0;
665
+ if (thrown?.color) uniforms.uThrownColor.value = hexToRgb(thrown.color, [1, 1, 1]);
666
+ uniforms.uThrownOpacity.value = thrown?.opacity ?? dots.opacity;
667
+ uniforms.uThrownScale.value = thrown?.scale ?? 1;
668
+ }
669
+
670
+ /*
671
+ * Re-lay the grid for a new canvas size.
672
+ */
673
+ function resize(nextSize: SceneSize) {
674
+ if (size.width === nextSize.width && size.height === nextSize.height && size.pixelRatio === nextSize.pixelRatio) return;
675
+ size = nextSize;
676
+ setViewport(nextSize.width, nextSize.height, 0);
677
+ layout();
678
+ }
679
+
680
+ /*
681
+ * Draw a window of the logical grid without reallocating or resetting its simulation.
682
+ */
683
+ function setViewport(width: number, height: number, top: number) {
684
+ setVec2(program.uniforms.uViewSize, Math.max(1, width), Math.max(1, height));
685
+ setVec2(program.uniforms.uViewOrigin, 0, top);
686
+ }
687
+
688
+ /*
689
+ * Cover-fit the image to a board region, with the layer's offset in that board. The region's
690
+ * bottom blends only the base image color; kicks and click effects retain their strength.
691
+ */
692
+ function setOverlayRegion(width: number, height: number, left: number, top: number, fade: number) {
693
+ setVec2(program.uniforms.uOverlayRegion, Math.max(1, width), Math.max(0, height));
694
+ setVec2(program.uniforms.uOverlayOffset, left, top);
695
+ program.uniforms.uOverlayFade.value = Math.max(0, Math.min(height, fade));
696
+ }
697
+
698
+ /*
699
+ * Apply new options in place; spacing and size change the layout, the rest are uniforms.
700
+ */
701
+ function setOptions(next?: DotGridOptions) {
702
+ options = resolveDotGridOptions(next);
703
+ applyOptions();
704
+ layout();
705
+ }
706
+
707
+ /*
708
+ * Show an image through the dots instead of the flat color (null restores it). Until the
709
+ * image has decoded the dots keep the flat color, so call this again on load.
710
+ */
711
+ function setOverlay(image: ImageTexture | null) {
712
+ const { uniforms } = program;
713
+ const on = !!image?.loaded;
714
+ uniforms.tOverlay.value = on ? image.texture : chain.output;
715
+ uniforms.uOverlaySize.value = on ? image.size : [1, 1];
716
+ uniforms.uOverlayOn.value = on ? 1 : 0;
717
+ }
718
+
719
+ /*
720
+ * Configure the hover tint independently of spring movement and image sampling.
721
+ */
722
+ function setHover(color: RGB | null, radius = 175, fade = true) {
723
+ program.uniforms.uHoverColor.value = color ?? [0, 0, 0];
724
+ program.uniforms.uHoverRadius.value = color ? Math.max(1, radius) : 0;
725
+ program.uniforms.uHoverFade.value = fade ? 1 : 0;
726
+ }
727
+
728
+ /*
729
+ * Move the hover center in logical layer pixels; zero amount hides the tint.
730
+ */
731
+ function setHoverPointer(x: number, y: number, amount: number) {
732
+ setVec2(program.uniforms.uHoverPointer, x, y);
733
+ program.uniforms.uHoverAmount.value = program.uniforms.uHoverRadius.value > 0 ? amount : 0;
734
+ }
735
+
736
+ /*
737
+ * Clock and reduced-motion state for pulse, resting, and click effects, in seconds.
738
+ */
739
+ function setTime(seconds: number, reducedMotion = false) {
740
+ program.uniforms.uTime.value = seconds;
741
+ program.uniforms.uMotionEnabled.value = reducedMotion ? 0 : 1;
742
+ if (reducedMotion && simulating) rest();
743
+ }
744
+
745
+ /*
746
+ * Start a click effect; ripple impulses use the click's own radius and strength.
747
+ */
748
+ function clickAt(x: number, y: number, seconds: number) {
749
+ if (!options.click) return false;
750
+ const effect = clicks.add(x, y, seconds, options.click.effect);
751
+ if (
752
+ effect === getDotEffectId('ripple') &&
753
+ options.click.kickStrength !== 0 &&
754
+ options.click.kickRadius > 0 &&
755
+ chain.halfFloat &&
756
+ program.uniforms.uMotionEnabled.value > 0
757
+ ) {
758
+ const { uniforms } = spring;
759
+ setVec2(uniforms.uPointer, x, y);
760
+ setVec2(uniforms.uPointerVelocity, 0, 0);
761
+ uniforms.uDt.value = 0;
762
+ uniforms.uSteps.value = 1;
763
+ uniforms.uImpulse.value = 1;
764
+ // The shared click timestamp keeps board layers in sync; bound it for shader precision.
765
+ uniforms.uImpulseSeed.value = Math.round(seconds * 1000) % 4096;
766
+ program.uniforms.tState.value = chain.render([spring]);
767
+ uniforms.uImpulse.value = 0;
768
+ lastKickAt = seconds;
769
+ simulating = true;
770
+ }
771
+ return true;
772
+ }
773
+
774
+ /*
775
+ * Expire click effects or clear them for reduced motion; true requests another frame.
776
+ */
777
+ function stepClicks(seconds: number, reducedMotion: boolean) {
778
+ return clicks.update(seconds, reducedMotion ? 0 : (options.click?.duration ?? 0) / 1000);
779
+ }
780
+
781
+ /*
782
+ * When (on the same clock as `setTime`) ambient effects may begin, so the first cycle starts then;
783
+ * null holds the dots still, e.g. until a reveal has finished.
784
+ */
785
+ function setPulseStart(seconds: number | null) {
786
+ program.uniforms.uPulseStart.value = seconds ?? -1;
787
+ }
788
+
789
+ /*
790
+ * Whether dots pulse on their own, which needs continuous frames.
791
+ */
792
+ function isPulsing() {
793
+ return options.pulse !== null && options.pulse.count > 0;
794
+ }
795
+
796
+ /*
797
+ * Whether pulse or resting effects need an ambient animation loop.
798
+ */
799
+ function isAnimating() {
800
+ return isPulsing() || options.rest !== null;
801
+ }
802
+
803
+ /*
804
+ * Scale of the overlay image about the area's center; 1 is the plain cover fit.
805
+ */
806
+ function setOverlayZoom(zoom: number) {
807
+ program.uniforms.uOverlayZoom.value = Math.max(0.01, zoom);
808
+ }
809
+
810
+ /*
811
+ * How far the dots have shrunk from full coverage to their size: 0 fills the area, 1 is
812
+ * the resting grid. Pass an already eased value. An optional diameter overrides the size
813
+ * for an appear animation; use amount 1 to keep holes open and avoid clipping to cells.
814
+ */
815
+ function setReveal(amount: number, diameter?: number) {
816
+ program.uniforms.uReveal.value = Math.min(1, Math.max(0, amount));
817
+ program.uniforms.uRevealSize.value = diameter === undefined ? -1 : Math.max(0, diameter);
818
+ }
819
+
820
+ /*
821
+ * Height in CSS pixels of the fade along the bottom edge; 0 for none. The dots fade to
822
+ * transparent, or to the hex `color` when given (the image through them included), and the
823
+ * cursor kicks and swells them less the deeper into the fade they sit. The filled reveal
824
+ * state is not this fade's: `setFadeHandoff` brings it in, taking over from `setImageFade`.
825
+ */
826
+ function setFadeBottom(height: number, color: string | null = null) {
827
+ program.uniforms.uFadeBottom.value = Math.max(0, height);
828
+ spring.uniforms.uFadeBottom.value = Math.max(0, height);
829
+ program.uniforms.uFadeColorOn.value = color ? 1 : 0;
830
+ if (color) program.uniforms.uFadeColor.value = hexToRgb(color, [1, 1, 1]);
831
+ }
832
+
833
+ /*
834
+ * Blend the final dot color to RGBA between bottom-relative distances, retaining it below
835
+ * the end stop. Unlike reveal fades this never weakens cursor movement or dot scaling.
836
+ */
837
+ function setBottomTint(
838
+ start: number,
839
+ end: number,
840
+ color: [number, number, number, number] | null,
841
+ mode: 'color' | 'normal' | 'blend' = 'color',
842
+ ) {
843
+ program.uniforms.uBottomTintOn.value = color ? 1 : 0;
844
+ program.uniforms.uBottomTintMode.value = color ? (mode === 'blend' ? 2 : mode === 'normal' ? 1 : 0) : 0;
845
+ setVec2(program.uniforms.uBottomTintRange, start, end);
846
+ if (color) program.uniforms.uBottomTint.value = color;
847
+ }
848
+
849
+ /*
850
+ * Height in CSS pixels of the fade along the bottom edge of the filled reveal state (the
851
+ * solid image or color before the dots shrink); 0 for none. To transparent, or to the hex
852
+ * `color` when given. It goes out with `setFadeHandoff` as `setFadeBottom` comes in.
853
+ */
854
+ function setImageFade(height: number, color: string | null = null) {
855
+ program.uniforms.uImageFade.value = Math.max(0, height);
856
+ program.uniforms.uImageFadeColorOn.value = color ? 1 : 0;
857
+ if (color) program.uniforms.uImageFadeColor.value = hexToRgb(color, [1, 1, 1]);
858
+ }
859
+
860
+ /*
861
+ * Which bottom fade is drawn, 0..1: at 0 the filled reveal state's (`setImageFade`) at full
862
+ * strength and none of the dots', at 1 the dots' (`setFadeBottom`) alone, blending in
863
+ * between. Independent of `setReveal`, so a fade can outlast the shrink.
864
+ */
865
+ function setFadeHandoff(amount: number) {
866
+ program.uniforms.uFadeHandoff.value = Math.min(1, Math.max(0, amount));
867
+ }
868
+
869
+ /*
870
+ * Advance the dots one frame. The pointer is in CSS pixels from the canvas's top-left with
871
+ * its velocity in px/s; `active` is whether kicks may land (the pointer is over the area and
872
+ * no reveal is running). Returns whether the dots are still moving and need another frame.
873
+ */
874
+ function step(pointer: [number, number], velocity: [number, number], active: boolean, dt: number, now: number) {
875
+ if (!chain.halfFloat) return false;
876
+ // A zero-length frame (the first after a pause) has nothing to integrate; keep asking for frames.
877
+ if (dt <= 0) return simulating;
878
+ const moving = active && isInteractive() && (velocity[0] !== 0 || velocity[1] !== 0);
879
+ if (moving) {
880
+ lastKickAt = now;
881
+ simulating = true;
882
+ }
883
+ if (!simulating) return false;
884
+ if (now - lastKickAt > settleSeconds) {
885
+ rest();
886
+ return false;
887
+ }
888
+ const { uniforms } = spring;
889
+ setVec2(uniforms.uPointer, pointer[0], pointer[1]);
890
+ setVec2(uniforms.uPointerVelocity, moving ? velocity[0] : 0, moving ? velocity[1] : 0);
891
+ uniforms.uDt.value = dt;
892
+ uniforms.uSteps.value = Math.min(SPRING.maxSteps, Math.max(1, Math.ceil((omega * dt) / SPRING.maxOmegaDt)));
893
+ program.uniforms.tState.value = chain.render([spring]);
894
+ return true;
895
+ }
896
+
897
+ /*
898
+ * Whether the grid reacts to the pointer at all; a static grid needs no `step` calls and no
899
+ * frames on pointer moves.
900
+ */
901
+ function isInteractive() {
902
+ return chain.halfFloat && isDotGridInteractive(options);
903
+ }
904
+
905
+ /*
906
+ * Draw the dots onto the canvas, optionally clearing it to transparent first.
907
+ */
908
+ function draw(clear = false) {
909
+ if (clear) gl.clearColor(0, 0, 0, 0);
910
+ gl.renderer.render({ scene: mesh, clear, sort: false, frustumCull: false, update: false });
911
+ }
912
+
913
+ /*
914
+ * Free the simulation targets, geometry, and programs.
915
+ */
916
+ function dispose() {
917
+ chain.dispose();
918
+ spring.remove();
919
+ restPass.remove();
920
+ geometry.remove();
921
+ program.remove();
922
+ }
923
+
924
+ applyOptions();
925
+
926
+ return {
927
+ mesh,
928
+ resize,
929
+ setOptions,
930
+ setOverlay,
931
+ setOverlayRegion,
932
+ setViewport,
933
+ setOverlayZoom,
934
+ setReveal,
935
+ setFadeBottom,
936
+ setBottomTint,
937
+ setImageFade,
938
+ setFadeHandoff,
939
+ setTime,
940
+ setHover,
941
+ setHoverPointer,
942
+ clickAt,
943
+ stepClicks,
944
+ setPulseStart,
945
+ step,
946
+ isInteractive,
947
+ isPulsing,
948
+ isAnimating,
949
+ draw,
950
+ dispose,
951
+ };
952
+ }
953
+
954
+ export type DotGrid = ReturnType<typeof createDotGrid>;