@elementalfx/fluid 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,775 @@
1
+ // packages/fluid/src/options.ts
2
+ var base = {
3
+ mode: null,
4
+ colors: "rainbow",
5
+ brightness: 0.2,
6
+ dyeDissipation: 1,
7
+ velocityDissipation: 0.2,
8
+ pressure: 0.8,
9
+ curl: 30,
10
+ splatRadius: 0.25,
11
+ splatForce: 6e3,
12
+ ambient: null,
13
+ shading: 1,
14
+ opacity: 1,
15
+ quality: "auto",
16
+ interactive: true,
17
+ zIndex: 2147483e3,
18
+ respectReducedMotion: true,
19
+ pauseOffscreen: true,
20
+ maxPixelRatio: 2
21
+ };
22
+ var presets = {
23
+ ink: {},
24
+ smoke: {
25
+ colors: ["#ffffff"],
26
+ brightness: 0.09,
27
+ dyeDissipation: 1.4,
28
+ velocityDissipation: 0.5,
29
+ curl: 18,
30
+ splatRadius: 0.18,
31
+ shading: 0.6
32
+ },
33
+ neon: {
34
+ colors: ["#18e7ff", "#ff2bd6", "#7dff5a", "#ffd400", "#8a5cff"],
35
+ brightness: 0.22,
36
+ dyeDissipation: 1.1,
37
+ curl: 45,
38
+ shading: 0.3
39
+ }
40
+ };
41
+ var tiers = [
42
+ { name: "low", sim: 64, dye: 256, iterations: 10 },
43
+ { name: "medium", sim: 96, dye: 512, iterations: 16 },
44
+ { name: "high", sim: 128, dye: 1024, iterations: 20 }
45
+ ];
46
+ function resolveOptions(options) {
47
+ const preset = options.preset && presets[options.preset] ? options.preset : "ink";
48
+ const merged = { ...base, ...presets[preset] };
49
+ for (const [key, value] of Object.entries(options)) if (value !== void 0) merged[key] = value;
50
+ merged.preset = preset;
51
+ return merged;
52
+ }
53
+
54
+ // packages/fluid/src/fluid.ts
55
+ import { EffectRuntime, createRandom, isBrowser, noise3, pixelRatio, resolveElement } from "@elementalfx/core";
56
+ import {
57
+ FULLSCREEN_VERTEX,
58
+ PingPong,
59
+ RenderTarget,
60
+ createFullscreenDraw,
61
+ createProgram,
62
+ getWebGL2,
63
+ isWebGL2Supported,
64
+ simulationFormat,
65
+ watchContextLoss
66
+ } from "@elementalfx/gl";
67
+
68
+ // packages/fluid/src/shaders.ts
69
+ var HEADER = `#version 300 es
70
+ precision highp float;
71
+ precision highp sampler2D;
72
+ in vec2 vUv;
73
+ out vec4 outColor;
74
+ uniform vec2 uTexel;
75
+ `;
76
+ var NEIGHBOURS = `
77
+ vec2 uvL() { return vUv - vec2(uTexel.x, 0.0); }
78
+ vec2 uvR() { return vUv + vec2(uTexel.x, 0.0); }
79
+ vec2 uvB() { return vUv - vec2(0.0, uTexel.y); }
80
+ vec2 uvT() { return vUv + vec2(0.0, uTexel.y); }
81
+ `;
82
+ var ADVECT = `${HEADER}
83
+ uniform sampler2D uVelocity;
84
+ uniform sampler2D uSource;
85
+ uniform float uDt;
86
+ uniform float uDissipation;
87
+ void main() {
88
+ vec2 back = vUv - uDt * texture(uVelocity, vUv).xy * uTexel;
89
+ outColor = texture(uSource, back) / (1.0 + uDissipation * uDt);
90
+ }`;
91
+ var DIVERGENCE = `${HEADER}${NEIGHBOURS}
92
+ uniform sampler2D uVelocity;
93
+ void main() {
94
+ vec2 c = texture(uVelocity, vUv).xy;
95
+ float l = texture(uVelocity, uvL()).x;
96
+ float r = texture(uVelocity, uvR()).x;
97
+ float b = texture(uVelocity, uvB()).y;
98
+ float t = texture(uVelocity, uvT()).y;
99
+ // Solid walls: mirror the normal component at the boundary.
100
+ if (uvL().x < 0.0) l = -c.x;
101
+ if (uvR().x > 1.0) r = -c.x;
102
+ if (uvB().y < 0.0) b = -c.y;
103
+ if (uvT().y > 1.0) t = -c.y;
104
+ outColor = vec4(0.5 * (r - l + t - b), 0.0, 0.0, 1.0);
105
+ }`;
106
+ var CURL = `${HEADER}${NEIGHBOURS}
107
+ uniform sampler2D uVelocity;
108
+ void main() {
109
+ float l = texture(uVelocity, uvL()).y;
110
+ float r = texture(uVelocity, uvR()).y;
111
+ float b = texture(uVelocity, uvB()).x;
112
+ float t = texture(uVelocity, uvT()).x;
113
+ outColor = vec4(0.5 * (r - l - t + b), 0.0, 0.0, 1.0);
114
+ }`;
115
+ var VORTICITY = `${HEADER}${NEIGHBOURS}
116
+ uniform sampler2D uVelocity;
117
+ uniform sampler2D uCurl;
118
+ uniform float uCurlStrength;
119
+ uniform float uDt;
120
+ void main() {
121
+ float l = texture(uCurl, uvL()).x;
122
+ float r = texture(uCurl, uvR()).x;
123
+ float b = texture(uCurl, uvB()).x;
124
+ float t = texture(uCurl, uvT()).x;
125
+ float c = texture(uCurl, vUv).x;
126
+ vec2 force = 0.5 * vec2(abs(t) - abs(b), abs(r) - abs(l));
127
+ force /= length(force) + 1e-4;
128
+ force *= uCurlStrength * c;
129
+ force.y = -force.y;
130
+ vec2 velocity = texture(uVelocity, vUv).xy + force * uDt;
131
+ outColor = vec4(clamp(velocity, -1000.0, 1000.0), 0.0, 1.0);
132
+ }`;
133
+ var SCALE = `${HEADER}
134
+ uniform sampler2D uSource;
135
+ uniform float uValue;
136
+ void main() {
137
+ outColor = texture(uSource, vUv) * uValue;
138
+ }`;
139
+ var PRESSURE = `${HEADER}${NEIGHBOURS}
140
+ uniform sampler2D uPressure;
141
+ uniform sampler2D uDivergence;
142
+ void main() {
143
+ float l = texture(uPressure, uvL()).x;
144
+ float r = texture(uPressure, uvR()).x;
145
+ float b = texture(uPressure, uvB()).x;
146
+ float t = texture(uPressure, uvT()).x;
147
+ float divergence = texture(uDivergence, vUv).x;
148
+ outColor = vec4((l + r + b + t - divergence) * 0.25, 0.0, 0.0, 1.0);
149
+ }`;
150
+ var GRADIENT_SUBTRACT = `${HEADER}${NEIGHBOURS}
151
+ uniform sampler2D uPressure;
152
+ uniform sampler2D uVelocity;
153
+ void main() {
154
+ float l = texture(uPressure, uvL()).x;
155
+ float r = texture(uPressure, uvR()).x;
156
+ float b = texture(uPressure, uvB()).x;
157
+ float t = texture(uPressure, uvT()).x;
158
+ vec2 velocity = texture(uVelocity, vUv).xy - 0.5 * vec2(r - l, t - b);
159
+ outColor = vec4(velocity, 0.0, 1.0);
160
+ }`;
161
+ var SPLAT = `${HEADER}
162
+ uniform sampler2D uTarget;
163
+ uniform float uAspect;
164
+ uniform vec3 uValue;
165
+ uniform vec2 uPoint;
166
+ uniform float uRadius;
167
+ void main() {
168
+ vec2 p = vUv - uPoint;
169
+ p.x *= uAspect;
170
+ vec3 base = texture(uTarget, vUv).xyz;
171
+ outColor = vec4(base + exp(-dot(p, p) / uRadius) * uValue, 1.0);
172
+ }`;
173
+ var DISPLAY = `${HEADER}${NEIGHBOURS}
174
+ uniform sampler2D uDye;
175
+ uniform float uOpacity;
176
+ uniform float uShading;
177
+ void main() {
178
+ vec3 color = texture(uDye, vUv).rgb;
179
+ if (uShading > 0.0) {
180
+ float dx = length(texture(uDye, uvR()).rgb) - length(texture(uDye, uvL()).rgb);
181
+ float dy = length(texture(uDye, uvT()).rgb) - length(texture(uDye, uvB()).rgb);
182
+ vec3 n = normalize(vec3(dx, dy, length(uTexel)));
183
+ float diffuse = clamp(dot(n, vec3(0.0, 0.0, 1.0)) + 0.7, 0.7, 1.0);
184
+ color *= mix(1.0, diffuse, uShading);
185
+ }
186
+ float alpha = clamp(max(color.r, max(color.g, color.b)), 0.0, 1.0) * uOpacity;
187
+ // Premultiplied output: dye adds light where it's dense and fades to clear.
188
+ outColor = vec4(min(color, vec3(1.0)) * uOpacity, alpha);
189
+ }`;
190
+
191
+ // packages/fluid/src/fluid.ts
192
+ function createFluid(target = "body", options = {}) {
193
+ let element = isBrowser ? resolveElement(target) : target;
194
+ if (isBrowser && element === document.documentElement) element = document.body;
195
+ return new FluidEffect(element, options);
196
+ }
197
+ var FluidEffect = class {
198
+ constructor(element, options) {
199
+ this.settled = false;
200
+ this.runtime = null;
201
+ this.canvas = null;
202
+ this.state = null;
203
+ this.mounted = false;
204
+ this.destroyed = false;
205
+ this.cleanups = [];
206
+ this.restoreStyles = [];
207
+ this.random = createRandom(Math.floor(Math.random() * 2 ** 31));
208
+ this.tierIndex = 2;
209
+ this.width = 1;
210
+ this.height = 1;
211
+ this.idleTime = 0;
212
+ this.clock = 0;
213
+ this.wanderers = [];
214
+ this.frameTimes = [];
215
+ this.qualityCooldown = 3;
216
+ this.pointers = /* @__PURE__ */ new Map();
217
+ this.resizeQueued = false;
218
+ // ------------------------------------------------------------------ input
219
+ this.pointerCleanup = null;
220
+ this.element = element;
221
+ this.userOptions = { ...options };
222
+ this.options = resolveOptions(this.userOptions);
223
+ this.ready = new Promise((resolve) => this.resolveReady = resolve);
224
+ if (!isBrowser || !isWebGL2Supported()) {
225
+ this.settle(false);
226
+ return;
227
+ }
228
+ this.tierIndex = this.initialTier();
229
+ this.runtime = new EffectRuntime({
230
+ element,
231
+ frame: (dt) => this.frame(dt),
232
+ pauseOffscreen: this.options.pauseOffscreen,
233
+ respectReducedMotion: this.options.respectReducedMotion,
234
+ onReducedMotionChange: (reduce) => reduce ? this.unmount() : this.mount()
235
+ });
236
+ if (this.runtime.reducedMotion) this.settle(false);
237
+ else this.mount();
238
+ }
239
+ get mode() {
240
+ return this.options.mode ?? (isBrowser && this.element === document.body ? "cursor" : "background");
241
+ }
242
+ get quality() {
243
+ return tiers[this.tierIndex].name;
244
+ }
245
+ get ambient() {
246
+ return this.options.ambient ?? (this.mode === "background" ? 1 : 0);
247
+ }
248
+ // ---------------------------------------------------------------- public API
249
+ splat(x, y, dx, dy, color) {
250
+ this.splatScaled(x, y, dx, dy, color ? hexToRgb(color) : this.nextColor(), 1, 1);
251
+ }
252
+ splatScaled(x, y, dx, dy, rgb, dyeScale, radiusScale) {
253
+ const state = this.state;
254
+ if (!state) return;
255
+ const scale = this.options.brightness * dyeScale;
256
+ this.applySplat(state, x / this.width, 1 - y / this.height, dx / this.width, -dy / this.height, [rgb[0] * scale, rgb[1] * scale, rgb[2] * scale], radiusScale);
257
+ this.idleTime = 0;
258
+ this.runtime?.wake();
259
+ }
260
+ burst(count = 6, at) {
261
+ for (let i = 0; i < count; i++) {
262
+ const x = at ? at.x + (this.random() - 0.5) * 40 : this.random() * this.width;
263
+ const y = at ? at.y + (this.random() - 0.5) * 40 : this.random() * this.height;
264
+ const angle = this.random() * Math.PI * 2;
265
+ const speed = (0.6 + this.random() * 0.8) * Math.min(this.width, this.height) * 0.35;
266
+ this.splat(x, y, Math.cos(angle) * speed, Math.sin(angle) * speed);
267
+ }
268
+ }
269
+ set(options) {
270
+ if (this.destroyed) return;
271
+ const previous = this.options;
272
+ this.userOptions = { ...this.userOptions, ...options };
273
+ this.options = resolveOptions(this.userOptions);
274
+ if (previous.respectReducedMotion !== this.options.respectReducedMotion) {
275
+ this.runtime?.setRespectReducedMotion(this.options.respectReducedMotion);
276
+ }
277
+ if (previous.quality !== this.options.quality) {
278
+ this.tierIndex = this.initialTier();
279
+ if (this.state) this.allocate(this.state);
280
+ }
281
+ const remount = previous.mode !== this.options.mode || previous.zIndex !== this.options.zIndex || previous.maxPixelRatio !== this.options.maxPixelRatio;
282
+ if (remount && this.mounted) {
283
+ this.unmount();
284
+ this.mount();
285
+ return;
286
+ }
287
+ if (previous.interactive !== this.options.interactive) this.bindPointer();
288
+ this.idleTime = 0;
289
+ this.runtime?.wake();
290
+ }
291
+ clear() {
292
+ if (!this.state) return;
293
+ this.state.velocity.clear();
294
+ this.state.dye.clear();
295
+ this.state.pressure.clear();
296
+ this.display();
297
+ }
298
+ pause() {
299
+ this.runtime?.pause();
300
+ }
301
+ play() {
302
+ this.idleTime = 0;
303
+ this.runtime?.play();
304
+ this.runtime?.wake();
305
+ }
306
+ destroy() {
307
+ if (this.destroyed) return;
308
+ this.unmount();
309
+ this.destroyed = true;
310
+ this.runtime?.destroy();
311
+ this.runtime = null;
312
+ this.settle(false);
313
+ }
314
+ // ------------------------------------------------------------- mount/unmount
315
+ mount() {
316
+ if (this.mounted || this.destroyed || this.runtime?.reducedMotion) return;
317
+ const canvas = document.createElement("canvas");
318
+ canvas.setAttribute("aria-hidden", "true");
319
+ canvas.dataset.fx = "fluid";
320
+ const s = canvas.style;
321
+ s.left = "0";
322
+ s.top = "0";
323
+ s.width = "100%";
324
+ s.height = "100%";
325
+ s.display = "block";
326
+ s.pointerEvents = "none";
327
+ if (this.mode === "cursor") {
328
+ s.position = "fixed";
329
+ s.zIndex = String(this.options.zIndex);
330
+ document.body.append(canvas);
331
+ } else {
332
+ const computed = getComputedStyle(this.element);
333
+ if (computed.position === "static") this.stash("position", "relative");
334
+ if (computed.zIndex === "auto") this.stash("z-index", "0");
335
+ s.position = "absolute";
336
+ s.zIndex = "-1";
337
+ s.borderRadius = computed.borderRadius;
338
+ this.element.prepend(canvas);
339
+ }
340
+ this.canvas = canvas;
341
+ this.state = this.createGL();
342
+ if (!this.state) {
343
+ canvas.remove();
344
+ this.canvas = null;
345
+ for (const restore of this.restoreStyles.splice(0).reverse()) restore();
346
+ this.settle(false);
347
+ return;
348
+ }
349
+ this.mounted = true;
350
+ this.cleanups.push(
351
+ watchContextLoss(
352
+ canvas,
353
+ () => {
354
+ this.state = null;
355
+ },
356
+ () => {
357
+ this.state = this.createGL();
358
+ this.runtime?.wake();
359
+ }
360
+ )
361
+ );
362
+ const resize = () => {
363
+ this.resizeQueued = true;
364
+ this.runtime?.wake();
365
+ };
366
+ const observer = new ResizeObserver(resize);
367
+ observer.observe(this.mode === "cursor" ? document.documentElement : this.element);
368
+ window.addEventListener("resize", resize);
369
+ this.cleanups.push(() => {
370
+ observer.disconnect();
371
+ window.removeEventListener("resize", resize);
372
+ });
373
+ this.bindPointer();
374
+ this.measure();
375
+ if (this.mode === "background") this.burst(5);
376
+ this.display();
377
+ this.idleTime = 0;
378
+ this.runtime?.wake();
379
+ this.settle(true);
380
+ }
381
+ unmount() {
382
+ if (!this.mounted) return;
383
+ this.mounted = false;
384
+ for (const cleanup of this.cleanups.splice(0)) cleanup();
385
+ this.releaseGL();
386
+ this.canvas?.remove();
387
+ this.canvas = null;
388
+ this.pointers.clear();
389
+ for (const restore of this.restoreStyles.splice(0).reverse()) restore();
390
+ }
391
+ stash(property, value) {
392
+ const element = this.element;
393
+ const previous = element.style.getPropertyValue(property);
394
+ element.style.setProperty(property, value);
395
+ this.restoreStyles.push(() => {
396
+ if (previous) element.style.setProperty(property, previous);
397
+ else element.style.removeProperty(property);
398
+ });
399
+ }
400
+ measure() {
401
+ if (!this.canvas || !this.state) return;
402
+ const rect = this.canvas.getBoundingClientRect();
403
+ this.width = Math.max(1, rect.width);
404
+ this.height = Math.max(1, rect.height);
405
+ const dpr = pixelRatio(this.options.maxPixelRatio);
406
+ this.canvas.width = Math.max(1, Math.round(this.width * dpr));
407
+ this.canvas.height = Math.max(1, Math.round(this.height * dpr));
408
+ this.allocate(this.state);
409
+ this.resizeQueued = false;
410
+ }
411
+ // ------------------------------------------------------------------- WebGL
412
+ createGL() {
413
+ const canvas = this.canvas;
414
+ if (!canvas) return null;
415
+ const gl = getWebGL2(canvas, { powerPreference: "low-power" });
416
+ if (!gl) return null;
417
+ try {
418
+ const format = simulationFormat(gl, { precision: "half" });
419
+ if (format.packed) {
420
+ console.warn("[elementalfx] fluid: this GPU cannot render to float textures, so the fluid is off.");
421
+ gl.getExtension("WEBGL_lose_context")?.loseContext();
422
+ return null;
423
+ }
424
+ const make = (source) => createProgram(gl, FULLSCREEN_VERTEX, source);
425
+ const programs = {
426
+ advect: make(ADVECT),
427
+ divergence: make(DIVERGENCE),
428
+ curl: make(CURL),
429
+ vorticity: make(VORTICITY),
430
+ scale: make(SCALE),
431
+ pressure: make(PRESSURE),
432
+ gradient: make(GRADIENT_SUBTRACT),
433
+ splat: make(SPLAT),
434
+ display: make(DISPLAY)
435
+ };
436
+ const state = {
437
+ gl,
438
+ format,
439
+ programs,
440
+ quad: createFullscreenDraw(gl),
441
+ simSize: [0, 0],
442
+ dyeSize: [0, 0]
443
+ };
444
+ this.allocate(state);
445
+ return state;
446
+ } catch (error) {
447
+ console.warn("[elementalfx] fluid: WebGL setup failed.", error);
448
+ gl.getExtension("WEBGL_lose_context")?.loseContext();
449
+ return null;
450
+ }
451
+ }
452
+ /** (Re)creates simulation textures for the current size and quality tier. */
453
+ allocate(state) {
454
+ const tier = tiers[this.tierIndex];
455
+ const sim = gridSize(tier.sim, this.width, this.height);
456
+ const dye = gridSize(tier.dye, this.width, this.height);
457
+ const { gl, format } = state;
458
+ if (state.simSize[0] !== sim[0] || state.simSize[1] !== sim[1]) {
459
+ state.velocity?.delete();
460
+ state.pressure?.delete();
461
+ state.divergence?.delete();
462
+ state.curl?.delete();
463
+ state.velocity = new PingPong(gl, sim[0], sim[1], format);
464
+ state.pressure = new PingPong(gl, sim[0], sim[1], format);
465
+ state.divergence = new RenderTarget(gl, sim[0], sim[1], format);
466
+ state.curl = new RenderTarget(gl, sim[0], sim[1], format);
467
+ state.simSize = sim;
468
+ }
469
+ if (state.dyeSize[0] !== dye[0] || state.dyeSize[1] !== dye[1]) {
470
+ state.dye?.delete();
471
+ state.dye = new PingPong(gl, dye[0], dye[1], format);
472
+ state.dyeSize = dye;
473
+ }
474
+ }
475
+ releaseGL() {
476
+ const state = this.state;
477
+ this.state = null;
478
+ if (!state) return;
479
+ const { gl } = state;
480
+ if (!gl.isContextLost()) {
481
+ for (const program of Object.values(state.programs)) program.delete();
482
+ state.quad.delete();
483
+ state.velocity.delete();
484
+ state.dye.delete();
485
+ state.pressure.delete();
486
+ state.divergence.delete();
487
+ state.curl.delete();
488
+ }
489
+ gl.getExtension("WEBGL_lose_context")?.loseContext();
490
+ }
491
+ /** Runs one pass: binds textures to units in order, sets uniforms, draws into `target`. */
492
+ pass(state, program, target, textures, uniforms) {
493
+ const { gl } = state;
494
+ program.use();
495
+ let unit = 0;
496
+ for (const [name, texture] of Object.entries(textures)) {
497
+ gl.activeTexture(gl.TEXTURE0 + unit);
498
+ gl.bindTexture(gl.TEXTURE_2D, texture);
499
+ const location = program.uniforms[name];
500
+ if (location) gl.uniform1i(location, unit);
501
+ unit++;
502
+ }
503
+ uniforms(program.uniforms);
504
+ if (target) target.bind();
505
+ else {
506
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
507
+ gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
508
+ }
509
+ state.quad.draw();
510
+ }
511
+ applySplat(state, u, v, du, dv, color, radiusScale = 1) {
512
+ const { gl } = state;
513
+ gl.disable(gl.BLEND);
514
+ const aspect = this.width / this.height;
515
+ const radius = this.options.splatRadius / 100 * (aspect > 1 ? aspect : 1) * radiusScale;
516
+ const force = this.options.splatForce;
517
+ const p = state.programs.splat;
518
+ this.pass(state, p, state.velocity.write, { uTarget: state.velocity.read.texture }, (uni) => {
519
+ gl.uniform1f(uni.uAspect, aspect);
520
+ gl.uniform2f(uni.uPoint, u, v);
521
+ gl.uniform3f(uni.uValue, du * force, dv * force, 0);
522
+ gl.uniform1f(uni.uRadius, radius);
523
+ });
524
+ state.velocity.swap();
525
+ this.pass(state, p, state.dye.write, { uTarget: state.dye.read.texture }, (uni) => {
526
+ gl.uniform1f(uni.uAspect, aspect);
527
+ gl.uniform2f(uni.uPoint, u, v);
528
+ gl.uniform3f(uni.uValue, color[0], color[1], color[2]);
529
+ gl.uniform1f(uni.uRadius, radius);
530
+ });
531
+ state.dye.swap();
532
+ }
533
+ step(state, dt) {
534
+ const { gl, programs } = state;
535
+ const tier = tiers[this.tierIndex];
536
+ const simTexel = [1 / state.simSize[0], 1 / state.simSize[1]];
537
+ const o = this.options;
538
+ gl.disable(gl.BLEND);
539
+ const texel = (u, t = simTexel) => {
540
+ if (u.uTexel) gl.uniform2f(u.uTexel, t[0], t[1]);
541
+ };
542
+ this.pass(state, programs.curl, state.curl, { uVelocity: state.velocity.read.texture }, (u) => texel(u));
543
+ this.pass(state, programs.vorticity, state.velocity.write, { uVelocity: state.velocity.read.texture, uCurl: state.curl.texture }, (u) => {
544
+ texel(u);
545
+ gl.uniform1f(u.uCurlStrength, o.curl);
546
+ gl.uniform1f(u.uDt, dt);
547
+ });
548
+ state.velocity.swap();
549
+ this.pass(state, programs.divergence, state.divergence, { uVelocity: state.velocity.read.texture }, (u) => texel(u));
550
+ this.pass(state, programs.scale, state.pressure.write, { uSource: state.pressure.read.texture }, (u) => {
551
+ texel(u);
552
+ gl.uniform1f(u.uValue, Math.max(0, Math.min(1, o.pressure)));
553
+ });
554
+ state.pressure.swap();
555
+ for (let i = 0; i < tier.iterations; i++) {
556
+ this.pass(state, programs.pressure, state.pressure.write, { uPressure: state.pressure.read.texture, uDivergence: state.divergence.texture }, (u) => texel(u));
557
+ state.pressure.swap();
558
+ }
559
+ this.pass(state, programs.gradient, state.velocity.write, { uPressure: state.pressure.read.texture, uVelocity: state.velocity.read.texture }, (u) => texel(u));
560
+ state.velocity.swap();
561
+ this.pass(state, programs.advect, state.velocity.write, { uVelocity: state.velocity.read.texture, uSource: state.velocity.read.texture }, (u) => {
562
+ texel(u);
563
+ gl.uniform1f(u.uDt, dt);
564
+ gl.uniform1f(u.uDissipation, o.velocityDissipation);
565
+ });
566
+ state.velocity.swap();
567
+ this.pass(state, programs.advect, state.dye.write, { uVelocity: state.velocity.read.texture, uSource: state.dye.read.texture }, (u) => {
568
+ texel(u);
569
+ gl.uniform1f(u.uDt, dt);
570
+ gl.uniform1f(u.uDissipation, o.dyeDissipation);
571
+ });
572
+ state.dye.swap();
573
+ }
574
+ display() {
575
+ const state = this.state;
576
+ if (!state) return;
577
+ const { gl } = state;
578
+ gl.disable(gl.BLEND);
579
+ this.pass(state, state.programs.display, null, { uDye: state.dye.read.texture }, (u) => {
580
+ gl.uniform2f(u.uTexel, 1 / state.dyeSize[0], 1 / state.dyeSize[1]);
581
+ gl.uniform1f(u.uOpacity, Math.max(0, Math.min(1, this.options.opacity)));
582
+ gl.uniform1f(u.uShading, Math.max(0, Math.min(1, this.options.shading)));
583
+ });
584
+ }
585
+ // ------------------------------------------------------------------- frame
586
+ frame(dt) {
587
+ const state = this.state;
588
+ if (!state || state.gl.isContextLost()) return;
589
+ if (this.resizeQueued) this.measure();
590
+ this.adaptQuality(dt);
591
+ const ambient = this.ambient;
592
+ this.updateWanderers(dt, Math.round(ambient));
593
+ for (const pointer of this.pointers.values()) pointer.colorAge += dt;
594
+ this.step(state, Math.min(dt, 1 / 30));
595
+ this.display();
596
+ this.idleTime += dt;
597
+ const settleTime = Math.max(4, 7 / Math.max(0.1, this.options.dyeDissipation));
598
+ if (ambient <= 0 && this.idleTime > settleTime) {
599
+ this.clear();
600
+ this.runtime?.sleep();
601
+ }
602
+ }
603
+ /**
604
+ * Invisible strokes that drift around the area like a slow cursor, so a
605
+ * background keeps flowing without anyone touching it.
606
+ */
607
+ updateWanderers(dt, count) {
608
+ while (this.wanderers.length < count) {
609
+ this.wanderers.push({
610
+ x: this.random() * this.width,
611
+ y: this.random() * this.height,
612
+ heading: this.random() * Math.PI * 2,
613
+ seed: this.random() * 100,
614
+ color: this.nextColor(),
615
+ colorAge: 0
616
+ });
617
+ }
618
+ this.wanderers.length = Math.max(0, count);
619
+ this.clock += dt;
620
+ const speed = Math.min(this.width, this.height) * 0.55;
621
+ for (const w of this.wanderers) {
622
+ w.heading += noise3(this.clock * 0.35, w.seed, 0) * dt * 3.2;
623
+ const margin = Math.min(this.width, this.height) * 0.22;
624
+ const edge = Math.min(w.x, w.y, this.width - w.x, this.height - w.y);
625
+ if (edge < margin) {
626
+ const toCenter = Math.atan2(this.height / 2 - w.y, this.width / 2 - w.x);
627
+ w.heading += Math.sin(toCenter - w.heading) * dt * 7 * (1 - edge / margin);
628
+ }
629
+ const dx = Math.cos(w.heading) * speed * dt;
630
+ const dy = Math.sin(w.heading) * speed * dt;
631
+ w.x += dx;
632
+ w.y += dy;
633
+ if (w.x < 0 || w.x > this.width) {
634
+ w.heading = Math.PI - w.heading;
635
+ w.x = Math.max(0, Math.min(this.width, w.x));
636
+ }
637
+ if (w.y < 0 || w.y > this.height) {
638
+ w.heading = -w.heading;
639
+ w.y = Math.max(0, Math.min(this.height, w.y));
640
+ }
641
+ w.colorAge += dt;
642
+ if (w.colorAge > 2.5) {
643
+ w.color = this.nextColor();
644
+ w.colorAge = 0;
645
+ }
646
+ this.splatScaled(w.x, w.y, dx, dy, w.color, 0.22, 0.45);
647
+ }
648
+ }
649
+ /** In 'auto' quality, steps down a tier when frames stay slower than ~40 fps. */
650
+ adaptQuality(dt) {
651
+ if (this.options.quality !== "auto" || this.tierIndex === 0) return;
652
+ this.qualityCooldown -= dt;
653
+ this.frameTimes.push(dt);
654
+ if (this.frameTimes.length > 90) this.frameTimes.shift();
655
+ if (this.qualityCooldown > 0 || this.frameTimes.length < 90) return;
656
+ const average = this.frameTimes.reduce((sum, t) => sum + t, 0) / this.frameTimes.length;
657
+ if (average > 1 / 40) {
658
+ this.tierIndex--;
659
+ this.frameTimes = [];
660
+ this.qualityCooldown = 3;
661
+ if (this.state) this.allocate(this.state);
662
+ }
663
+ }
664
+ initialTier() {
665
+ const quality = this.options.quality;
666
+ if (quality !== "auto") return tiers.findIndex((tier) => tier.name === quality);
667
+ const coarse = isBrowser && typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches;
668
+ return coarse ? 1 : 2;
669
+ }
670
+ bindPointer() {
671
+ this.pointerCleanup?.();
672
+ this.pointerCleanup = null;
673
+ if (!this.options.interactive || !this.mounted) return;
674
+ const target = this.mode === "cursor" ? window : this.element;
675
+ const local = (event) => {
676
+ const rect = this.canvas.getBoundingClientRect();
677
+ return { x: event.clientX - rect.left, y: event.clientY - rect.top };
678
+ };
679
+ const move = (event) => {
680
+ const e = event;
681
+ const point = local(e);
682
+ const pointer = this.pointers.get(e.pointerId);
683
+ if (!pointer) {
684
+ this.pointers.set(e.pointerId, { ...point, color: this.nextColor(), colorAge: 0 });
685
+ return;
686
+ }
687
+ const dx = point.x - pointer.x;
688
+ const dy = point.y - pointer.y;
689
+ pointer.x = point.x;
690
+ pointer.y = point.y;
691
+ if (dx === 0 && dy === 0) return;
692
+ if (pointer.colorAge > 0.6) {
693
+ pointer.color = this.nextColor();
694
+ pointer.colorAge = 0;
695
+ }
696
+ this.splatScaled(point.x, point.y, dx, dy, pointer.color, 1, 1);
697
+ };
698
+ const down = (event) => {
699
+ const e = event;
700
+ const point = local(e);
701
+ this.pointers.set(e.pointerId, { ...point, color: this.nextColor(), colorAge: 0 });
702
+ this.burst(3, point);
703
+ };
704
+ const up = (event) => {
705
+ const e = event;
706
+ if (e.pointerType !== "mouse") this.pointers.delete(e.pointerId);
707
+ };
708
+ target.addEventListener("pointermove", move, { passive: true });
709
+ target.addEventListener("pointerdown", down, { passive: true });
710
+ target.addEventListener("pointerup", up, { passive: true });
711
+ target.addEventListener("pointercancel", up, { passive: true });
712
+ this.pointerCleanup = () => {
713
+ target.removeEventListener("pointermove", move);
714
+ target.removeEventListener("pointerdown", down);
715
+ target.removeEventListener("pointerup", up);
716
+ target.removeEventListener("pointercancel", up);
717
+ };
718
+ this.cleanups.push(() => {
719
+ this.pointerCleanup?.();
720
+ this.pointerCleanup = null;
721
+ });
722
+ }
723
+ nextColor() {
724
+ const colors = this.options.colors;
725
+ if (colors === "rainbow" || colors.length === 0) return hsvToRgb(this.random(), 1, 1);
726
+ return hexToRgb(colors[Math.floor(this.random() * colors.length)]);
727
+ }
728
+ settle(ok) {
729
+ if (this.settled) return;
730
+ this.settled = true;
731
+ this.resolveReady(ok);
732
+ }
733
+ };
734
+ function gridSize(resolution, width, height) {
735
+ const aspect = width / height;
736
+ const short = Math.round(resolution);
737
+ const long = Math.round(resolution * (aspect >= 1 ? aspect : 1 / aspect));
738
+ return aspect >= 1 ? [long, short] : [short, long];
739
+ }
740
+ function hexToRgb(hex) {
741
+ let value = hex.trim().replace("#", "");
742
+ if (value.length === 3) value = value.replace(/./g, (c) => c + c);
743
+ const n = Number.parseInt(value, 16);
744
+ if (value.length !== 6 || Number.isNaN(n)) return [1, 1, 1];
745
+ return [(n >> 16 & 255) / 255, (n >> 8 & 255) / 255, (n & 255) / 255];
746
+ }
747
+ function hsvToRgb(h, s, v) {
748
+ const i = Math.floor(h * 6);
749
+ const f = h * 6 - i;
750
+ const p = v * (1 - s);
751
+ const q = v * (1 - f * s);
752
+ const t = v * (1 - (1 - f) * s);
753
+ switch (i % 6) {
754
+ case 0:
755
+ return [v, t, p];
756
+ case 1:
757
+ return [q, v, p];
758
+ case 2:
759
+ return [p, v, t];
760
+ case 3:
761
+ return [p, q, v];
762
+ case 4:
763
+ return [t, p, v];
764
+ default:
765
+ return [v, p, q];
766
+ }
767
+ }
768
+
769
+ export {
770
+ presets,
771
+ tiers,
772
+ resolveOptions,
773
+ createFluid
774
+ };
775
+ //# sourceMappingURL=chunk-FAVDIVND.js.map