@arraypress/effects-astro 0.12.0 → 0.14.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,317 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/fluid-folds
3
+ *
4
+ * Glossy folds of liquid colour on a dark ground: a height field of soft
5
+ * folds, warped by slow noise, lit from one side, so each fold catches a
6
+ * bright, glassy highlight along its crest and falls into shadow behind it.
7
+ * Its colour runs along a ramp of three colours (in Oklab) that drifts
8
+ * across the folds, so a fold turns from deep to hot as it bends. Two
9
+ * styles: `liquid`, folds bending every way like poured enamel, and
10
+ * `dunes`, long folds lying across the frame like silk dunes.
11
+ *
12
+ * Every clock is in seconds and nothing is kept between frames: the height
13
+ * field is a function of where and when, here in GLSL and in plain
14
+ * JavaScript too (`foldHeight`, `foldShade`), so a still and a test see
15
+ * what the shader draws. It is made to sit behind copy: no pointer, and a
16
+ * `quiet` area dims the folds behind a lockup.
17
+ *
18
+ * Opaque: it paints its `background` (default near-black) everywhere.
19
+ * Without WebGL nothing is drawn; with prefers-reduced-motion it is one
20
+ * still frame.
21
+ */
22
+
23
+ import { createStage } from './stage.js';
24
+ import { GLSL_GRADIENT_NOISE, GLSL_HASH33, gnoise } from './hash-noise.js';
25
+ import { GLSL_OKLAB, parseColor, toOklab, toHex, mixOklab } from './color.js';
26
+ import { GLSL_QUIET, quietUniform } from './glsl.js';
27
+ import { watchColors } from './mount.js';
28
+ import { pickColors } from './palettes.js';
29
+
30
+ /**
31
+ * @typedef {'liquid' | 'dunes'} FoldStyle
32
+ *
33
+ * @typedef {object} FluidFoldsConfig
34
+ * @property {string[]} [colors] Three CSS hex colours along the folds: deep, mid and hot. Default cobalt, violet and coral.
35
+ * @property {string} [palette] A shared palette by name (PALETTES; any case), when there are no `colors`.
36
+ * @property {string} [background='#050409'] The ground, painted everywhere (the folds' deepest shadow).
37
+ * @property {FoldStyle} [style='liquid'] Folds bending every way, or long folds lying across the frame.
38
+ * @property {number} [scale=1.6] How many folds across the height.
39
+ * @property {number} [warp=0.9] How far the noise bends the folds.
40
+ * @property {number} [gloss=0.8] How bright and tight the highlight along each crest is; 0 for none.
41
+ * @property {number} [light=-30] Where the light comes from, degrees from straight above (negative from the left).
42
+ * @property {number} [hue=0.5] How fast the colour runs across the folds (higher shows more of the ramp at once).
43
+ * @property {number} [rate=0.03] How fast the folds move, cycles a second.
44
+ * @property {number} [level=0.55] For dunes, where the folds sit, a share of the height from the top (above it, the dark sky).
45
+ * @property {number} [grain=0.03] Fine grain over all of it; 0 for none.
46
+ * @property {number} [seed=0] Where its noise starts, so two cards differ.
47
+ * @property {number} [speed=1] Plays every clock faster or slower; 0 for one still frame.
48
+ * @property {{ x?: number, y?: number, radius?: number, depth?: number } | null} [quiet=null]
49
+ * An area dimmed: centre (0–1 from the top left), radius (share of the height), depth (0–1).
50
+ */
51
+
52
+ /** The styles, in the order the shader numbers them. */
53
+ export const FOLD_STYLES = /** @type {const} */ (['liquid', 'dunes']);
54
+
55
+ /** The settings' defaults, shared by the shader and the JS twin. */
56
+ export const FOLD_DEFAULTS = {
57
+ background: '#050409',
58
+ style: /** @type {FoldStyle} */ ('liquid'),
59
+ scale: 1.6,
60
+ warp: 0.9,
61
+ gloss: 0.8,
62
+ light: -30,
63
+ hue: 0.5,
64
+ rate: 0.03,
65
+ level: 0.55,
66
+ grain: 0.03,
67
+ seed: 0,
68
+ };
69
+
70
+ /** The default colours: cobalt, violet and coral, after the owner's fluid references. */
71
+ const ENAMEL = ['#1638ff', '#7b2cff', '#ff4a3d'];
72
+
73
+ /**
74
+ * GLSL: `float foldHeight(vec2 p, float t)` (heights from the top left)
75
+ * and `float foldHue(vec2 p, float t)`, the same as `foldHeight` and
76
+ * `foldHue` below in JavaScript.
77
+ */
78
+ const GLSL_FOLDS = `
79
+ uniform float uStyle;
80
+ uniform float uScale;
81
+ uniform float uWarp;
82
+ uniform float uRate;
83
+ uniform float uLevel;
84
+ uniform float uHueRate;
85
+ uniform float uSeed;
86
+ float fbm3(vec2 p) {
87
+ return 0.55 * gnoise(p) + 0.3 * gnoise(p * 2.03 + 17.1) + 0.15 * gnoise(p * 4.01 + 41.7);
88
+ }
89
+ float foldHeight(vec2 p, float t) {
90
+ float ph = t * uRate;
91
+ vec2 q = p * uScale + vec2(uSeed, uSeed * 0.7);
92
+ if (uStyle < 0.5) {
93
+ vec2 w = vec2(fbm3(q * 0.8 + vec2(ph, 0.0)), fbm3(q * 0.8 + vec2(5.2, 1.3 - ph))) - 0.5;
94
+ vec2 r = q + uWarp * 2.0 * w;
95
+ return 0.5 + 0.5 * sin(6.2831853 * (fbm3(r) * 2.6 + ph * 0.5));
96
+ }
97
+ vec2 w = vec2(fbm3(vec2(q.x * 0.5 + ph, q.y * 0.3)), 0.0) - 0.5;
98
+ float y = q.y * 2.2 + uWarp * 1.6 * (fbm3(vec2(q.x * 0.7 - ph * 0.6, q.y * 0.6)) - 0.5) + w.x;
99
+ float ridge = 0.5 + 0.5 * sin(6.2831853 * y + 2.0 * sin(q.x * 1.3 + ph * 2.0));
100
+ float sky = smoothstep(uLevel - 0.25, uLevel + 0.1, p.y);
101
+ return ridge * sky;
102
+ }
103
+ float foldHue(vec2 p, float t) {
104
+ return fract(gnoise(p * uHueRate * 1.7 + vec2(uSeed * 1.3 + t * uRate * 0.6, uSeed)) * 1.4 + p.x * 0.18);
105
+ }
106
+ `;
107
+
108
+ const FRAG = `
109
+ precision highp float;
110
+ uniform vec2 uRes;
111
+ uniform float uTime;
112
+ uniform float uGloss;
113
+ uniform vec2 uLight;
114
+ uniform float uGrain;
115
+ uniform vec3 uBg;
116
+ uniform vec3 uRamp[3];
117
+ ${GLSL_OKLAB}
118
+ ${GLSL_QUIET}
119
+ ${GLSL_HASH33}
120
+ ${GLSL_GRADIENT_NOISE}
121
+ ${GLSL_FOLDS}
122
+
123
+ vec3 rampAt(float h) {
124
+ // deep, mid, hot, and round again to deep, so the hue drifts without a seam
125
+ float x = h * 3.0;
126
+ if (x < 1.0) return mix(uRamp[0], uRamp[1], x);
127
+ if (x < 2.0) return mix(uRamp[1], uRamp[2], x - 1.0);
128
+ return mix(uRamp[2], uRamp[0], x - 2.0);
129
+ }
130
+
131
+ void main() {
132
+ vec2 px = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y);
133
+ vec2 p = px / uRes.y;
134
+ float e = 1.5 / uRes.y;
135
+ float h = foldHeight(p, uTime);
136
+ float hx = foldHeight(p + vec2(e, 0.0), uTime);
137
+ float hy = foldHeight(p + vec2(0.0, e), uTime);
138
+ // the surface's slope, in heights of the frame
139
+ vec3 n = normalize(vec3((h - hx) / e * 0.06, (h - hy) / e * 0.06, 1.0));
140
+ vec3 L = normalize(vec3(uLight, 0.9));
141
+ float diff = clamp(dot(n, L), 0.0, 1.0);
142
+ float spec = pow(clamp(dot(n, normalize(L + vec3(0.0, 0.0, 1.0))), 0.0, 1.0), mix(8.0, 60.0, uGloss)) * uGloss;
143
+ float body = smoothstep(0.08, 0.95, h);
144
+
145
+ float hue = foldHue(p, uTime);
146
+ vec3 lab = mix(uBg, rampAt(hue), body * (0.18 + 0.82 * diff));
147
+ vec3 col = fromOklab(lab);
148
+ // an iridescent rim where a fold turns away, in the next colour round the ramp, and the glossy highlight on top
149
+ float rim = pow(clamp(1.0 - n.z, 0.0, 1.0), 1.5) * 2.2;
150
+ col += fromOklab(rampAt(fract(hue + 0.33))) * rim * body * 0.6;
151
+ col += spec * mix(vec3(1.0), fromOklab(rampAt(fract(hue + 0.66))), 0.4) * body * 1.3;
152
+
153
+ vec2 q = vec2(p.x - 0.5 * uRes.x / uRes.y, 0.5 - p.y);
154
+ col *= mix(1.0 - uQuiet.w, 1.0, quietOpen(q));
155
+ col += (hash33(vec3(px, floor(uTime * 24.0))).x - 0.5) * uGrain;
156
+ gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
157
+ }
158
+ `;
159
+
160
+ /**
161
+ * The settings, filled with the defaults, with the style's number.
162
+ *
163
+ * @param {FluidFoldsConfig} config The settings.
164
+ * @returns {typeof FOLD_DEFAULTS & { styleIndex: number, speed: number }} The settings.
165
+ */
166
+ function settings(config) {
167
+ const o = { ...FOLD_DEFAULTS, speed: 1, ...config };
168
+ return { ...o, styleIndex: Math.max(0, FOLD_STYLES.indexOf(o.style)) };
169
+ }
170
+
171
+ /** Three octaves of the shared gradient noise (the shader's `fbm3`). */
172
+ const fbm3 = (/** @type {number} */ x, /** @type {number} */ y) =>
173
+ 0.55 * gnoise(x, y) + 0.3 * gnoise(x * 2.03 + 17.1, y * 2.03 + 17.1) + 0.15 * gnoise(x * 4.01 + 41.7, y * 4.01 + 41.7);
174
+
175
+ /** Hermite smoothing between two edges (GLSL's `smoothstep`). */
176
+ const smooth = (/** @type {number} */ e0, /** @type {number} */ e1, /** @type {number} */ x) => {
177
+ const t = Math.min(1, Math.max(0, (x - e0) / (e1 - e0)));
178
+ return t * t * (3 - 2 * t);
179
+ };
180
+
181
+ /**
182
+ * The folds' height at a point (the shader's `foldHeight`), 0–1: a fold's
183
+ * crest is near 1, the hollow behind it near 0.
184
+ *
185
+ * @param {FluidFoldsConfig} config The settings.
186
+ * @param {number} x Heights from the left.
187
+ * @param {number} y Heights from the top.
188
+ * @param {number} [time=0] Seconds (already at its speed).
189
+ * @returns {number} 0–1.
190
+ */
191
+ export function foldHeight(config, x, y, time = 0) {
192
+ const o = settings(config);
193
+ const ph = time * o.rate;
194
+ const qx = x * o.scale + o.seed;
195
+ const qy = y * o.scale + o.seed * 0.7;
196
+ if (o.styleIndex === 0) {
197
+ const wx = fbm3(qx * 0.8 + ph, qy * 0.8) - 0.5;
198
+ const wy = fbm3(qx * 0.8 + 5.2, qy * 0.8 + 1.3 - ph) - 0.5;
199
+ return 0.5 + 0.5 * Math.sin(2 * Math.PI * (fbm3(qx + o.warp * 2 * wx, qy + o.warp * 2 * wy) * 2.6 + ph * 0.5));
200
+ }
201
+ const w = fbm3(qx * 0.5 + ph, qy * 0.3) - 0.5;
202
+ const yy = qy * 2.2 + o.warp * 1.6 * (fbm3(qx * 0.7 - ph * 0.6, qy * 0.6) - 0.5) + w;
203
+ const ridge = 0.5 + 0.5 * Math.sin(2 * Math.PI * yy + 2 * Math.sin(qx * 1.3 + ph * 2));
204
+ return ridge * smooth(o.level - 0.25, o.level + 0.1, y);
205
+ }
206
+
207
+ /**
208
+ * Where on the colour ramp a point is (the shader's `foldHue`), 0–1 round
209
+ * deep, mid, hot and back to deep.
210
+ *
211
+ * @param {FluidFoldsConfig} config The settings.
212
+ * @param {number} x Heights from the left.
213
+ * @param {number} y Heights from the top.
214
+ * @param {number} [time=0] Seconds (already at its speed).
215
+ * @returns {number} 0–1.
216
+ */
217
+ export function foldHue(config, x, y, time = 0) {
218
+ const o = settings(config);
219
+ const v = gnoise(x * o.hue * 1.7 + o.seed * 1.3 + time * o.rate * 0.6, y * o.hue * 1.7 + o.seed) * 1.4 + x * 0.18;
220
+ return v - Math.floor(v);
221
+ }
222
+
223
+ /**
224
+ * The three colours as the shader takes them (fewer repeat).
225
+ *
226
+ * @param {FluidFoldsConfig} config The settings.
227
+ * @returns {[string, string, string]} Deep, mid and hot.
228
+ */
229
+ export function foldColors(config) {
230
+ const c = pickColors(config, ENAMEL);
231
+ return [c[0], c[Math.min(1, c.length - 1)], c[c.length - 1]];
232
+ }
233
+
234
+ /**
235
+ * A CSS `background` that stands in for the folds before the shader starts
236
+ * and without WebGL: two soft swells of the ramp's colours and a glossy
237
+ * streak across them, on the ground (dunes lie under a dark sky).
238
+ *
239
+ * @param {FluidFoldsConfig} config The settings (`colors`/`palette`, `background`, `style`, `level`).
240
+ * @returns {string} The CSS background.
241
+ */
242
+ export function foldsStill(config) {
243
+ const o = settings(config);
244
+ const [deep, mid, hot] = foldColors(config).map((c) => toHex(parseColor(c)));
245
+ const ground = toHex(parseColor(o.background));
246
+ const dim = (/** @type {string} */ c) => toHex(mixOklab(parseColor(ground), parseColor(c), 0.55));
247
+ if (o.styleIndex === 1) {
248
+ const top = Math.round(o.level * 100);
249
+ return [
250
+ `linear-gradient(172deg, transparent ${top + 8}%, ${dim(hot)}55 ${top + 14}%, transparent ${top + 22}%)`,
251
+ `radial-gradient(120% 60% at 30% 100%, ${dim(mid)} 0%, ${dim(deep)} 40%, transparent 75%)`,
252
+ `linear-gradient(to bottom, ${ground} ${Math.max(0, top - 10)}%, ${dim(deep)} 100%)`,
253
+ ground,
254
+ ].join(', ');
255
+ }
256
+ return [
257
+ `linear-gradient(125deg, transparent 38%, rgba(255,255,255,0.16) 46%, transparent 52%)`,
258
+ `radial-gradient(70% 55% at 22% 78%, ${dim(hot)} 0%, transparent 70%)`,
259
+ `radial-gradient(75% 60% at 78% 24%, ${dim(deep)} 0%, ${dim(mid)}88 35%, transparent 72%)`,
260
+ ground,
261
+ ].join(', ');
262
+ }
263
+
264
+ /**
265
+ * Starts the folds on an element: a canvas inside it (its first), at the
266
+ * stage's capped pixel ratio.
267
+ *
268
+ * @param {HTMLElement} el The element.
269
+ * @param {FluidFoldsConfig} config The settings.
270
+ * @returns {() => void} Stops it.
271
+ */
272
+ export function fluidFolds(el, config) {
273
+ const o = settings(config);
274
+ const lab = (/** @type {string} */ c) => toOklab(parseColor(c));
275
+ let ramp = foldColors(config).map(lab);
276
+ const ground = lab(o.background);
277
+ const a = (o.light * Math.PI) / 180;
278
+ const start = performance.now();
279
+
280
+ const { stage, stop } = createStage(el, {
281
+ fragment: FRAG,
282
+ alpha: false,
283
+ still: o.speed <= 0,
284
+ setup({ gl, uniform }) {
285
+ gl.uniform1f(uniform('uStyle'), o.styleIndex);
286
+ gl.uniform1f(uniform('uScale'), o.scale);
287
+ gl.uniform1f(uniform('uWarp'), o.warp);
288
+ gl.uniform1f(uniform('uRate'), o.rate);
289
+ gl.uniform1f(uniform('uLevel'), o.level);
290
+ gl.uniform1f(uniform('uHueRate'), o.hue);
291
+ gl.uniform1f(uniform('uSeed'), o.seed);
292
+ gl.uniform1f(uniform('uGloss'), o.gloss);
293
+ gl.uniform2f(uniform('uLight'), Math.sin(a), Math.cos(a));
294
+ gl.uniform1f(uniform('uGrain'), o.grain);
295
+ gl.uniform3f(uniform('uBg'), ground[0], ground[1], ground[2]);
296
+ },
297
+ resize({ gl, uniform }) {
298
+ const w = Math.max(1, el.clientWidth);
299
+ const h = Math.max(1, el.clientHeight);
300
+ gl.uniform4f(uniform('uQuiet'), ...quietUniform(config.quiet, w / h));
301
+ },
302
+ uniforms({ gl, uniform }, now) {
303
+ gl.uniform1f(uniform('uTime'), ((now - start) / 1000) * Math.max(0, o.speed));
304
+ gl.uniform3fv(uniform('uRamp[0]'), new Float32Array(ramp.flat()));
305
+ },
306
+ });
307
+ if (!stage) return stop;
308
+
309
+ const unwatch = watchColors(el, (next) => {
310
+ ramp = foldColors({ colors: next.colors }).map(lab);
311
+ if (stage.still) stage.redraw();
312
+ });
313
+ return () => {
314
+ stop();
315
+ unwatch();
316
+ };
317
+ }
@@ -0,0 +1,70 @@
1
+ import type { PaletteName } from './palettes.js';
2
+
3
+ /** The glass: upright flutes, or a wall of square glass blocks. */
4
+ export type BokehGlass = 'reeds' | 'blocks';
5
+
6
+ export interface FlutedBokehConfig {
7
+ /** Two to four CSS hex colours for the lights. Default coral, amber and ice blue. */
8
+ colors?: string[];
9
+ /** A shared palette by name (`PALETTES`, any case), when there are no `colors`. */
10
+ palette?: PaletteName | (string & {});
11
+ /** The ground, painted everywhere. Default '#050608'. */
12
+ background?: string;
13
+ /** Upright flutes, or a wall of square glass blocks. Default 'reeds'. */
14
+ mode?: BokehGlass;
15
+ /** Flutes across the width (blocks across, for `blocks`). Default 28. */
16
+ flutes?: number;
17
+ /** How much of what is behind a flute it shows across its width (lower stretches more). Default 0.3. */
18
+ squeeze?: number;
19
+ /** How far red and blue part at the seams; 0 for none. Default 0.35. */
20
+ dispersion?: number;
21
+ /** How far the light smears upright, a share of the height; 0 for none. Default 0.06. */
22
+ streak?: number;
23
+ /** Lights behind the glass (1–8). Default 5. */
24
+ lights?: number;
25
+ /** The lights' radius, a share of the height. Default 0.22. */
26
+ size?: number;
27
+ /** How bright the lights are. Default 1. */
28
+ glow?: number;
29
+ /** How far the lights wander, a share of the height. Default 0.08. */
30
+ drift?: number;
31
+ /** How fast they wander, cycles a second. Default 0.04. */
32
+ rate?: number;
33
+ /** How strong the seams' highlights and shadows (or the blocks' joints) are; 0 for none. Default 0.3. */
34
+ seams?: number;
35
+ /** Fine grain over all of it; 0 for none. Default 0.04. */
36
+ grain?: number;
37
+ /** Where the lights sit and start wandering, so two cards differ. Default 0. */
38
+ seed?: number;
39
+ /** Plays every clock faster or slower; 0 for one still frame. Default 1. */
40
+ speed?: number;
41
+ /** An area dimmed: centre (0–1 from the top left), radius (share of the height), depth (0–1). */
42
+ quiet?: { x?: number; y?: number; radius?: number; depth?: number } | null;
43
+ }
44
+
45
+ /** The glass, in the order the shader numbers it. */
46
+ export declare const BOKEH_GLASS: readonly ['reeds', 'blocks'];
47
+
48
+ /** The most lights the shader draws. */
49
+ export declare const MAX_LIGHTS: 8;
50
+
51
+ /** The settings' defaults, shared by the shader and the JS twin. */
52
+ export declare const BOKEH_DEFAULTS: Required<Omit<FlutedBokehConfig, 'colors' | 'palette' | 'speed' | 'quiet'>>;
53
+
54
+ /** The lights: where each sits (shares of the width and height), its size (a share of `size`), its colour's index and its phase. */
55
+ export declare function bokehLights(config: FlutedBokehConfig): { x: number; y: number; r: number; color: number; phase: number }[];
56
+
57
+ /** The light behind the glass at a point (shares of the width and height): red, green and blue, 0 and up. */
58
+ export declare function bokehAt(config: FlutedBokehConfig, x: number, y: number, aspect: number, time?: number): [number, number, number];
59
+
60
+ /** Where behind the reeds a point looks: the share of the width it shows, and where in its flute it is (−1 to 1). */
61
+ export declare function reedSample(x: number, flutes: number, squeeze: number): { x: number; local: number };
62
+
63
+ /** The lights' colours as the shader takes them: two to four. */
64
+ export declare function bokehColors(config: FlutedBokehConfig): string[];
65
+
66
+ /** A CSS `background` that stands in for the lights before the shader starts and without WebGL. */
67
+ export declare function bokehStill(config: FlutedBokehConfig, aspect?: number): string;
68
+
69
+ /** Starts the lights and the glass on an element (its first canvas). Returns a function that stops it. */
70
+ export declare function flutedBokeh(el: HTMLElement, config: FlutedBokehConfig): () => void;