Loading…
← All components

Background · Smoke

Fluid Smoke Drift

Drifting smoke and mist, fully procedural: your cursor pushes the volutes apart and leaves a swirling wake that closes up organically.

<FluidSmokeDrift />Live

Customize

Background#05060a
Primary#c3cadb
Accent#7c6cff

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

$ npx deepui-cli add fluid-smoke-drift
01

Install

The 3D packages this component is built on.

$ npm install three @react-three/fiber && npm install -D @types/three
02

Add the component

One self-contained file: create components/FluidSmokeDrift.tsx and paste it in.

components/FluidSmokeDrift.tsx
1"use client";
2
3import { useEffect, useMemo, useRef, useState, type RefObject } from "react";
4import * as THREE from "three";
5import { Canvas, useFrame, useThree } from "@react-three/fiber";
6
7/**
8 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep
9 * their own tailored scenes).
10 *
11 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its
12 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):
13 *
14 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }
15 *
16 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,
17 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are
18 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.
19 */
20
21/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */
22export type TiltAxis = "both" | "x-only" | "y-only" | "none";
23
24/** 1. Cursor: how the pointer pulls, pushes and drags the object. */
25interface CursorProps {
26 /** Reach of the pointer's influence, in the component's own space: CSS pixels for pixel-laid-out widgets, world units for 3D scenes (each component says which). Default 220 (px). */
27 cursorRadius?: number;
28 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */
29 cursorForce?: number;
30 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */
31 magneticStrength?: number;
32 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */
33 cursorDamping?: number;
34}
35
36/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */
37interface TiltProps {
38 /** Largest lean towards the pointer, in degrees. Default 15. */
39 maxTiltAngle?: number;
40 /** Axes that follow the pointer. Default "both". */
41 tiltAxis?: TiltAxis;
42 /** Lean away from the pointer instead of towards it. Default false. */
43 invertTilt?: boolean;
44 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */
45 parallaxOffset?: number;
46}
47
48/** 3. Text and 3D typography, for components that draw a label. */
49interface Text3DProps {
50 /** The label drawn by the component. */
51 text?: string;
52 /** Scale of the lettering. Default 1. */
53 fontSize?: number;
54 /** Extrusion depth of 3D letters. Default 0.2. */
55 textDepth?: number;
56 /** Bevelled, light-catching edges on 3D letters. Default true. */
57 bevelEnabled?: boolean;
58 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */
59 fontUrl?: string;
60}
61
62/** 4. Rendering, materials and glow. */
63interface MaterialProps {
64 /** Main color of the object. Default "#6366f1". */
65 primaryColor?: string;
66 /** Color of the glow. Default "#00f0ff". */
67 emissiveColor?: string;
68 /** Strength of the glow, 0 (none) to 3. Default 1. */
69 emissiveIntensity?: number;
70 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */
71 roughness?: number;
72 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */
73 metalness?: number;
74 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */
75 transmission?: number;
76 /** Technical wireframe rendering. Default false. */
77 wireframe?: boolean;
78}
79
80/** 5. Particles, idle motion and shader animation. */
81interface MotionProps {
82 /** Number of instanced elements. Default depends on the component. */
83 particleCount?: number;
84 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */
85 autoRotateSpeed?: number;
86 /** Pulses or ripples per second. Default 1. */
87 pulseRate?: number;
88 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */
89 displacementScale?: number;
90}
91
92/** 6. Environment and camera. */
93interface EnvironmentProps {
94 /** Camera field of view, in degrees. Default depends on the component. */
95 cameraFov?: number;
96 /** Color of the depth fog. Default "#0a0a0a". */
97 fogColor?: string;
98 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */
99 fogDensity?: number;
100}
101
102/** 7. Performance and accessibility. */
103interface PerformanceProps {
104 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */
105 lowPowerMode?: boolean;
106 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */
107 respectReducedMotion?: boolean;
108 /** Stop the render loop while the component is scrolled out of view. Default true. */
109 pauseWhenOffscreen?: boolean;
110}
111
112/** Every group at once. Components extend only the groups they apply (see the top of this file). */
113interface Base3DComponentProps
114 extends CursorProps,
115 TiltProps,
116 Text3DProps,
117 MaterialProps,
118 MotionProps,
119 EnvironmentProps,
120 PerformanceProps {}
121
122type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;
123
124/** The values a prop takes when it is left out. A component may override one, and then documents it. */
125const DEFAULT_3D_PROPS: Defaults = {
126 cursorRadius: 220,
127 cursorForce: 1,
128 magneticStrength: 0,
129 cursorDamping: 0.1,
130 maxTiltAngle: 15,
131 tiltAxis: "both",
132 invertTilt: false,
133 parallaxOffset: 1,
134 fontSize: 1,
135 textDepth: 0.2,
136 bevelEnabled: true,
137 primaryColor: "#6366f1",
138 emissiveColor: "#00f0ff",
139 emissiveIntensity: 1,
140 roughness: 0.3,
141 metalness: 0.5,
142 transmission: 0,
143 wireframe: false,
144 autoRotateSpeed: 0,
145 pulseRate: 1,
146 displacementScale: 1,
147 fogColor: "#0a0a0a",
148 fogDensity: 0,
149 lowPowerMode: false,
150 respectReducedMotion: true,
151 pauseWhenOffscreen: true,
152};
153
154/**
155 * The shared behaviour behind the props of ./types: pointer inertia, tilt, magnetic pull, idle spin,
156 * the OS "reduce motion" setting and the off-screen pause. Inlined into each component's bundle.
157 */
158
159/** True while the OS asks for reduced motion; follows the setting live. */
160function usePrefersReducedMotion(): boolean {
161 const [reduced, setReduced] = useState(false);
162 useEffect(() => {
163 const query = window.matchMedia("(prefers-reduced-motion: reduce)");
164 const sync = () => setReduced(query.matches);
165 sync();
166 query.addEventListener("change", sync);
167 return () => query.removeEventListener("change", sync);
168 }, []);
169 return reduced;
170}
171
172/**
173 * The <Canvas> frameloop for `pauseWhenOffscreen`: "never" while the element is out of view. Put the ref
174 * on the element that wraps the canvas (outside it: this hook runs in the component, not in the scene).
175 */
176function useOffscreenFrameloop(ref: RefObject<HTMLElement | null>, pauseWhenOffscreen: boolean = DEFAULT_3D_PROPS.pauseWhenOffscreen): "always" | "never" {
177 // In view at first: some WebGL backends show an opaque canvas if it is paused before its first frame
178 const [inView, setInView] = useState(true);
179 useEffect(() => {
180 const el = ref.current;
181 if (!el || !pauseWhenOffscreen) return undefined;
182 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));
183 observer.observe(el);
184 return () => observer.disconnect();
185 }, [ref, pauseWhenOffscreen]);
186 return !pauseWhenOffscreen || inView ? "always" : "never";
187}
188
189// A GPU stable-fluids solver (Jos Stam's method, as popularised by Pavel Dobryakov's WebGL fluid):
190// semi-Lagrangian advection, vorticity confinement, a Jacobi pressure solve. Shared by FluidChromaWarp,
191// FluidSmokeDrift and FluidChromaCursor; each of them only adds its own splats and its own display.
192
193const baseVertex = /* glsl */ `
194uniform vec2 uTexel;
195varying vec2 vUv;
196varying vec2 vL;
197varying vec2 vR;
198varying vec2 vT;
199varying vec2 vB;
200void main() {
201 vUv = uv;
202 vL = uv - vec2(uTexel.x, 0.0);
203 vR = uv + vec2(uTexel.x, 0.0);
204 vT = uv + vec2(0.0, uTexel.y);
205 vB = uv - vec2(0.0, uTexel.y);
206 gl_Position = vec4(position.xy, 0.0, 1.0);
207}
208`;
209
210const splatFragment = /* glsl */ `
211uniform sampler2D uTarget;
212uniform float uAspect;
213uniform vec3 uColor;
214uniform vec2 uPoint;
215uniform float uRadius;
216varying vec2 vUv;
217void main() {
218 vec2 p = vUv - uPoint;
219 p.x *= uAspect;
220 vec3 splat = exp(-dot(p, p) / uRadius) * uColor;
221 gl_FragColor = vec4(texture2D(uTarget, vUv).xyz + splat, 1.0);
222}
223`;
224
225const advectFragment = /* glsl */ `
226uniform sampler2D uVelocity;
227uniform sampler2D uSource;
228uniform vec2 uTexel;
229uniform float uDt;
230uniform float uDissipation;
231uniform float uTopSink;
232varying vec2 vUv;
233void main() {
234 vec2 coord = vUv - uDt * texture2D(uVelocity, vUv).xy * uTexel;
235 // The top band drains (rising smoke leaves the frame instead of piling up against the edge)
236 float sink = uTopSink * smoothstep(0.7, 1.0, vUv.y);
237 gl_FragColor = texture2D(uSource, coord) / (1.0 + (uDissipation + sink) * uDt);
238}
239`;
240
241const curlFragment = /* glsl */ `
242uniform sampler2D uVelocity;
243varying vec2 vUv; varying vec2 vL; varying vec2 vR; varying vec2 vT; varying vec2 vB;
244void main() {
245 float l = texture2D(uVelocity, vL).y;
246 float r = texture2D(uVelocity, vR).y;
247 float t = texture2D(uVelocity, vT).x;
248 float b = texture2D(uVelocity, vB).x;
249 gl_FragColor = vec4(0.5 * (r - l - t + b), 0.0, 0.0, 1.0);
250}
251`;
252
253// Vorticity confinement (keeps the small eddies alive), the surface's own slow swirl (curl noise), and
254// buoyancy: dye denser than nothing rises (smoke), in proportion to its red channel
255const forcesFragment = /* glsl */ `
256uniform sampler2D uVelocity;
257uniform sampler2D uCurl;
258uniform sampler2D uDye;
259uniform float uCurlStrength;
260uniform float uDt;
261uniform float uTime;
262uniform float uTurbulence;
263uniform float uNoiseScale;
264uniform float uBuoyancy;
265varying vec2 vUv; varying vec2 vL; varying vec2 vR; varying vec2 vT; varying vec2 vB;
266vec2 hash(vec2 p) { p = vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3))); return -1.0 + 2.0 * fract(sin(p) * 43758.5453); }
267float noise(vec2 p) {
268 vec2 i = floor(p); vec2 f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f);
269 return mix(mix(dot(hash(i), f), dot(hash(i + vec2(1, 0)), f - vec2(1, 0)), u.x),
270 mix(dot(hash(i + vec2(0, 1)), f - vec2(0, 1)), dot(hash(i + vec2(1, 1)), f - vec2(1, 1)), u.x), u.y);
271}
272void main() {
273 float l = texture2D(uCurl, vL).x;
274 float r = texture2D(uCurl, vR).x;
275 float t = texture2D(uCurl, vT).x;
276 float b = texture2D(uCurl, vB).x;
277 float c = texture2D(uCurl, vUv).x;
278 vec2 force = 0.5 * vec2(abs(t) - abs(b), abs(r) - abs(l));
279 force /= length(force) + 1e-4;
280 force *= uCurlStrength * c;
281 force.y *= -1.0;
282 // Curl of a drifting noise field: divergence-free, it stirs without pumping
283 vec2 q = vUv * uNoiseScale + vec2(uTime * 0.05, -uTime * 0.04);
284 float e = 0.01;
285 float n1 = noise(q + vec2(0.0, e)), n2 = noise(q - vec2(0.0, e));
286 float n3 = noise(q + vec2(e, 0.0)), n4 = noise(q - vec2(e, 0.0));
287 vec2 swirl = vec2(n1 - n2, -(n3 - n4)) / (2.0 * e);
288 float density = texture2D(uDye, vUv).r;
289 vec2 v = texture2D(uVelocity, vUv).xy + (force + swirl * uTurbulence * 6.0 + vec2(0.0, density * uBuoyancy)) * uDt;
290 gl_FragColor = vec4(clamp(v, -1000.0, 1000.0), 0.0, 1.0);
291}
292`;
293
294const divergenceFragment = /* glsl */ `
295uniform sampler2D uVelocity;
296varying vec2 vUv; varying vec2 vL; varying vec2 vR; varying vec2 vT; varying vec2 vB;
297void main() {
298 float l = texture2D(uVelocity, vL).x;
299 float r = texture2D(uVelocity, vR).x;
300 float t = texture2D(uVelocity, vT).y;
301 float b = texture2D(uVelocity, vB).y;
302 vec2 c = texture2D(uVelocity, vUv).xy;
303 if (vL.x < 0.0) l = -c.x;
304 if (vR.x > 1.0) r = -c.x;
305 if (vT.y > 1.0) t = -c.y;
306 if (vB.y < 0.0) b = -c.y;
307 gl_FragColor = vec4(0.5 * (r - l + t - b), 0.0, 0.0, 1.0);
308}
309`;
310
311const pressureFragment = /* glsl */ `
312uniform sampler2D uPressure;
313uniform sampler2D uDivergence;
314varying vec2 vUv; varying vec2 vL; varying vec2 vR; varying vec2 vT; varying vec2 vB;
315void main() {
316 float l = texture2D(uPressure, vL).x;
317 float r = texture2D(uPressure, vR).x;
318 float t = texture2D(uPressure, vT).x;
319 float b = texture2D(uPressure, vB).x;
320 float d = texture2D(uDivergence, vUv).x;
321 gl_FragColor = vec4((l + r + b + t - d) * 0.25, 0.0, 0.0, 1.0);
322}
323`;
324
325const gradientFragment = /* glsl */ `
326uniform sampler2D uPressure;
327uniform sampler2D uVelocity;
328varying vec2 vUv; varying vec2 vL; varying vec2 vR; varying vec2 vT; varying vec2 vB;
329void main() {
330 float l = texture2D(uPressure, vL).x;
331 float r = texture2D(uPressure, vR).x;
332 float t = texture2D(uPressure, vT).x;
333 float b = texture2D(uPressure, vB).x;
334 vec2 v = texture2D(uVelocity, vUv).xy - vec2(r - l, t - b);
335 gl_FragColor = vec4(v, 0.0, 1.0);
336}
337`;
338
339const scaleFragment = /* glsl */ `
340uniform sampler2D uSource;
341uniform float uValue;
342varying vec2 vUv;
343void main() { gl_FragColor = uValue * texture2D(uSource, vUv); }
344`;
345
346interface DoubleTarget {
347 read: THREE.WebGLRenderTarget;
348 write: THREE.WebGLRenderTarget;
349 swap: () => void;
350 dispose: () => void;
351}
352
353function createTarget(w: number, h: number) {
354 return new THREE.WebGLRenderTarget(w, h, {
355 type: THREE.HalfFloatType,
356 format: THREE.RGBAFormat,
357 minFilter: THREE.LinearFilter,
358 magFilter: THREE.LinearFilter,
359 wrapS: THREE.ClampToEdgeWrapping,
360 wrapT: THREE.ClampToEdgeWrapping,
361 depthBuffer: false,
362 });
363}
364
365function createDouble(w: number, h: number): DoubleTarget {
366 const t: DoubleTarget = {
367 read: createTarget(w, h),
368 write: createTarget(w, h),
369 swap() {
370 const r = t.read;
371 t.read = t.write;
372 t.write = r;
373 },
374 dispose() {
375 t.read.dispose();
376 t.write.dispose();
377 },
378 };
379 return t;
380}
381
382/** A material for one solver pass, or for a component's own display pass. */
383function fluidPass(fragmentShader: string, uniforms: Record<string, THREE.IUniform>, options: Partial<THREE.ShaderMaterialParameters> = {}) {
384 return new THREE.ShaderMaterial({
385 vertexShader: baseVertex,
386 fragmentShader,
387 uniforms: { uTexel: { value: new THREE.Vector2() }, ...uniforms },
388 depthTest: false,
389 depthWrite: false,
390 ...options,
391 });
392}
393
394interface FluidResolution {
395 /** Velocity / pressure grid, on the short side of the canvas. */
396 sim: number;
397 /** Dye (color) grid, on the short side of the canvas. */
398 dye: number;
399 /** Jacobi iterations of the pressure solve. */
400 iterations: number;
401}
402
403interface FluidStep {
404 dt: number;
405 time: number;
406 /** How fast the motion dies out (per second). */
407 velocityDissipation: number;
408 /** How fast the dye fades (per second). */
409 dyeDissipation: number;
410 /** Vorticity confinement strength. Default 24. */
411 curl?: number;
412 /** Strength of the idle curl-noise swirl. Default 0. */
413 turbulence?: number;
414 /** Size of the idle swirls: noise cells across the canvas. Default 3. */
415 noiseScale?: number;
416 /** Upward force per unit of dye (red channel). Default 0. */
417 buoyancy?: number;
418 /** Extra dye fading (per second) in the top 30% of the canvas, strongest at the edge. Default 0. */
419 topSink?: number;
420}
421
422interface SplatColor {
423 r: number;
424 g: number;
425 b: number;
426}
427
428/** The fluid's state on the GPU and the passes that move it forward. Created and disposed by useFluidSolver. */
429class FluidSolver {
430 readonly aspect: number;
431 readonly simTexel: THREE.Vector2;
432 readonly dyeTexel: THREE.Vector2;
433 private readonly gl: THREE.WebGLRenderer;
434 private readonly iterations: number;
435 private readonly velocity: DoubleTarget;
436 private readonly dye: DoubleTarget;
437 private readonly pressure: DoubleTarget;
438 private readonly divergence: THREE.WebGLRenderTarget;
439 private readonly curl: THREE.WebGLRenderTarget;
440 private readonly passes;
441 private readonly geometry = new THREE.PlaneGeometry(2, 2);
442 private readonly mesh: THREE.Mesh;
443 private readonly scene = new THREE.Scene();
444 private readonly camera = new THREE.Camera();
445
446 constructor(gl: THREE.WebGLRenderer, width: number, height: number, resolution: FluidResolution) {
447 this.gl = gl;
448 this.iterations = resolution.iterations;
449 this.aspect = Math.max(width, 1) / Math.max(height, 1);
450 const grid = (n: number) => [Math.round(n * Math.max(this.aspect, 1)), Math.round(n / Math.min(this.aspect, 1))] as const;
451 const [simW, simH] = grid(resolution.sim);
452 const [dyeW, dyeH] = grid(resolution.dye);
453 this.simTexel = new THREE.Vector2(1 / simW, 1 / simH);
454 this.dyeTexel = new THREE.Vector2(1 / dyeW, 1 / dyeH);
455 this.velocity = createDouble(simW, simH);
456 this.dye = createDouble(dyeW, dyeH);
457 this.pressure = createDouble(simW, simH);
458 this.divergence = createTarget(simW, simH);
459 this.curl = createTarget(simW, simH);
460 this.passes = {
461 splat: fluidPass(splatFragment, { uTarget: { value: null }, uAspect: { value: 1 }, uColor: { value: new THREE.Vector3() }, uPoint: { value: new THREE.Vector2() }, uRadius: { value: 0.001 } }),
462 advect: fluidPass(advectFragment, { uVelocity: { value: null }, uSource: { value: null }, uDt: { value: 0 }, uDissipation: { value: 0 }, uTopSink: { value: 0 } }),
463 curl: fluidPass(curlFragment, { uVelocity: { value: null } }),
464 forces: fluidPass(forcesFragment, {
465 uVelocity: { value: null },
466 uCurl: { value: null },
467 uDye: { value: null },
468 uCurlStrength: { value: 24 },
469 uDt: { value: 0 },
470 uTime: { value: 0 },
471 uTurbulence: { value: 0 },
472 uNoiseScale: { value: 3 },
473 uBuoyancy: { value: 0 },
474 }),
475 divergence: fluidPass(divergenceFragment, { uVelocity: { value: null } }),
476 pressure: fluidPass(pressureFragment, { uPressure: { value: null }, uDivergence: { value: null } }),
477 gradient: fluidPass(gradientFragment, { uPressure: { value: null }, uVelocity: { value: null } }),
478 scale: fluidPass(scaleFragment, { uSource: { value: null }, uValue: { value: 0.8 } }),
479 };
480 this.mesh = new THREE.Mesh(this.geometry, this.passes.scale);
481 this.mesh.frustumCulled = false;
482 this.scene.add(this.mesh);
483 }
484
485 get dyeTexture() {
486 return this.dye.read.texture;
487 }
488
489 get velocityTexture() {
490 return this.velocity.read.texture;
491 }
492
493 /** Draws a full-screen pass into `target` (null: the canvas). */
494 render(material: THREE.ShaderMaterial, target: THREE.WebGLRenderTarget | null, texel: THREE.Vector2 = this.dyeTexel) {
495 const texelUniform = material.uniforms.uTexel as THREE.IUniform<THREE.Vector2> | undefined;
496 texelUniform?.value.copy(texel);
497 this.mesh.material = material;
498 this.gl.setRenderTarget(target);
499 this.gl.render(this.scene, this.camera);
500 }
501
502 /**
503 * Adds force (dx, dy, in sim pixels per second) and dye at (x, y) in 0..1 canvas space. `radius`:
504 * 0.1 (a needle) to 1 (a hand). A null color only pushes.
505 */
506 splat(x: number, y: number, dx: number, dy: number, color: SplatColor | null, strength: number, radius: number) {
507 const s = this.passes.splat;
508 const u = s.uniforms;
509 u.uAspect.value = this.aspect;
510 (u.uPoint.value as THREE.Vector2).set(x, y);
511 u.uRadius.value = (0.0006 + radius * radius * 0.012) * (this.aspect > 1 ? 1 : 1 / this.aspect);
512 u.uTarget.value = this.velocity.read.texture;
513 (u.uColor.value as THREE.Vector3).set(dx, dy, 0);
514 this.render(s, this.velocity.write, this.simTexel);
515 this.velocity.swap();
516 if (!color || strength <= 0) return;
517 u.uTarget.value = this.dye.read.texture;
518 (u.uColor.value as THREE.Vector3).set(color.r * strength, color.g * strength, color.b * strength);
519 this.render(s, this.dye.write, this.dyeTexel);
520 this.dye.swap();
521 }
522
523 /** Moves the fluid forward by `step.dt` seconds. */
524 step(step: FluidStep) {
525 const { velocity, dye, pressure, divergence, curl, passes } = this;
526 passes.curl.uniforms.uVelocity.value = velocity.read.texture;
527 this.render(passes.curl, curl, this.simTexel);
528
529 const f = passes.forces.uniforms;
530 f.uVelocity.value = velocity.read.texture;
531 f.uCurl.value = curl.texture;
532 f.uDye.value = dye.read.texture;
533 f.uCurlStrength.value = step.curl ?? 24;
534 f.uDt.value = step.dt;
535 f.uTime.value = step.time;
536 f.uTurbulence.value = step.turbulence ?? 0;
537 f.uNoiseScale.value = step.noiseScale ?? 3;
538 f.uBuoyancy.value = step.buoyancy ?? 0;
539 this.render(passes.forces, velocity.write, this.simTexel);
540 velocity.swap();
541
542 passes.divergence.uniforms.uVelocity.value = velocity.read.texture;
543 this.render(passes.divergence, divergence, this.simTexel);
544
545 passes.scale.uniforms.uSource.value = pressure.read.texture;
546 passes.scale.uniforms.uValue.value = 0.8;
547 this.render(passes.scale, pressure.write, this.simTexel);
548 pressure.swap();
549 passes.pressure.uniforms.uDivergence.value = divergence.texture;
550 for (let i = 0; i < this.iterations; i++) {
551 passes.pressure.uniforms.uPressure.value = pressure.read.texture;
552 this.render(passes.pressure, pressure.write, this.simTexel);
553 pressure.swap();
554 }
555
556 passes.gradient.uniforms.uPressure.value = pressure.read.texture;
557 passes.gradient.uniforms.uVelocity.value = velocity.read.texture;
558 this.render(passes.gradient, velocity.write, this.simTexel);
559 velocity.swap();
560
561 const a = passes.advect.uniforms;
562 a.uDt.value = step.dt;
563 a.uVelocity.value = velocity.read.texture;
564 a.uSource.value = velocity.read.texture;
565 a.uDissipation.value = step.velocityDissipation;
566 a.uTopSink.value = 0;
567 this.render(passes.advect, velocity.write, this.simTexel);
568 velocity.swap();
569
570 a.uVelocity.value = velocity.read.texture;
571 a.uSource.value = dye.read.texture;
572 a.uDissipation.value = step.dyeDissipation;
573 a.uTopSink.value = step.topSink ?? 0;
574 this.render(passes.advect, dye.write, this.simTexel);
575 dye.swap();
576 }
577
578 dispose() {
579 this.velocity.dispose();
580 this.dye.dispose();
581 this.pressure.dispose();
582 this.divergence.dispose();
583 this.curl.dispose();
584 Object.values(this.passes).forEach((m) => m.dispose());
585 this.geometry.dispose();
586 }
587}
588
589/**
590 * The solver for the current canvas. Rebuilt when the canvas is resized (the fluid restarts: rare,
591 * and cheaper than resampling it) and disposed on unmount.
592 */
593function useFluidSolver(resolution: FluidResolution) {
594 const gl = useThree((state) => state.gl);
595 const width = useThree((state) => state.size.width);
596 const height = useThree((state) => state.size.height);
597 const { sim, dye, iterations } = resolution;
598 const solver = useMemo(() => new FluidSolver(gl, width, height, { sim, dye, iterations }), [gl, width, height, sim, dye, iterations]);
599 useEffect(() => () => solver.dispose(), [solver]);
600 return solver;
601}
602
603/**
604 * Props shared by the procedural backgrounds (FluidSmokeDrift, FerrofluidTopography, …). Every one of
605 * them is a single shader: no image, no video, no external asset. Changing a prop live never recompiles
606 * the shader: colors, speed and scale are uniforms.
607 */
608interface DeepBackgroundProps extends Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode" | "respectReducedMotion"> {
609 /** React to the pointer. false removes the listeners and lets every cursor force ease back to 0. Default true. */
610 interactive?: boolean;
611 /** Palette: [background, primary, accent]. The accent falls back to the component's own. */
612 colors?: [string, string, string?];
613 /** Animation speed multiplier; changing it live never makes the animation jump. Default 1. */
614 speed?: number;
615 /** Size of the patterns, grain or cells: 2 makes them twice as large. Default 1. */
616 scale?: number;
617 /** Extra classes for the container (absolutely positioned, filling its parent). */
618 className?: string;
619}
620
621type BackgroundPalette = readonly [string, string, string];
622
623const DEEP_BACKGROUND_DEFAULTS = {
624 interactive: true,
625 speed: 1,
626 scale: 1,
627} as const;
628
629/** The cursor as the shaders see it. Read inside useFrame: pointer moves never re-render React. */
630interface PointerPhysics {
631 /** Smoothed position in the canvas, 0..1 (y up). */
632 position: THREE.Vector2;
633 /** Smoothed velocity, in canvas units (0..1) per second. */
634 velocity: THREE.Vector2;
635 /** 0..1: eases to 1 while the pointer is over the canvas (and `interactive`), back to 0 otherwise. */
636 strength: number;
637 /** 0..1: eases to 1 while a button or a finger is down. */
638 press: number;
639}
640
641interface RawPointer {
642 x: number;
643 y: number;
644 inside: boolean;
645 down: boolean;
646 seen: boolean;
647}
648
649const FOLLOW = 14; // damp rate of the position
650
651const VELOCITY_FOLLOW = 8;
652
653const STRENGTH_FOLLOW = 3.5; // forces fade in and out over ~half a second
654
655/**
656 * Pointer physics shared by the procedural backgrounds: smoothed position, smoothed velocity and an
657 * eased presence. The canvas has `pointer-events: none` (the page above it stays clickable), so the
658 * pointer is read from window listeners. With `interactive` false there is no listener at all and
659 * every force eases back to 0, leaving the autonomous animation alone.
660 */
661function usePointerPhysics(interactive: boolean): RefObject<PointerPhysics> {
662 const gl = useThree((state) => state.gl);
663 const raw = useRef<RawPointer>({ x: 0.5, y: 0.5, inside: false, down: false, seen: false });
664 const physics = useRef<PointerPhysics>({ position: new THREE.Vector2(0.5, 0.5), velocity: new THREE.Vector2(), strength: 0, press: 0 });
665 const previous = useRef(new THREE.Vector2(0.5, 0.5));
666
667 useEffect(() => {
668 const p = raw.current;
669 if (!interactive) {
670 p.inside = false;
671 p.down = false;
672 return undefined;
673 }
674 const el = gl.domElement;
675 const move = (event: PointerEvent) => {
676 const rect = el.getBoundingClientRect();
677 if (!rect.width || !rect.height) return;
678 p.x = (event.clientX - rect.left) / rect.width;
679 p.y = 1 - (event.clientY - rect.top) / rect.height;
680 p.inside = p.x >= 0 && p.x <= 1 && p.y >= 0 && p.y <= 1;
681 if (!p.seen) {
682 // First contact: start from the pointer instead of sweeping in from the center
683 p.seen = true;
684 physics.current.position.set(p.x, p.y);
685 previous.current.set(p.x, p.y);
686 }
687 };
688 const down = (event: PointerEvent) => {
689 move(event);
690 p.down = true;
691 };
692 const up = () => {
693 p.down = false;
694 };
695 const leave = () => {
696 p.inside = false;
697 p.down = false;
698 };
699 window.addEventListener("pointermove", move, { passive: true });
700 window.addEventListener("pointerdown", down, { passive: true });
701 window.addEventListener("pointerup", up, { passive: true });
702 window.addEventListener("pointercancel", leave, { passive: true });
703 document.documentElement.addEventListener("pointerleave", leave);
704 window.addEventListener("blur", leave);
705 return () => {
706 window.removeEventListener("pointermove", move);
707 window.removeEventListener("pointerdown", down);
708 window.removeEventListener("pointerup", up);
709 window.removeEventListener("pointercancel", leave);
710 document.documentElement.removeEventListener("pointerleave", leave);
711 window.removeEventListener("blur", leave);
712 };
713 }, [gl, interactive]);
714
715 useFrame((_, delta) => {
716 const dt = Math.min(delta, 1 / 20);
717 const p = raw.current;
718 const s = physics.current;
719 const damp = THREE.MathUtils.damp;
720 s.position.set(damp(s.position.x, p.x, FOLLOW, dt), damp(s.position.y, p.y, FOLLOW, dt));
721 const vx = dt > 0 ? (s.position.x - previous.current.x) / dt : 0;
722 const vy = dt > 0 ? (s.position.y - previous.current.y) / dt : 0;
723 previous.current.copy(s.position);
724 const active = interactive && p.inside;
725 s.velocity.set(damp(s.velocity.x, active ? vx : 0, VELOCITY_FOLLOW, dt), damp(s.velocity.y, active ? vy : 0, VELOCITY_FOLLOW, dt));
726 s.strength = damp(s.strength, active ? 1 : 0, STRENGTH_FOLLOW, dt);
727 s.press = damp(s.press, active && p.down ? 1 : 0, STRENGTH_FOLLOW * 2, dt);
728 });
729
730 return physics;
731}
732
733export type { DeepBackgroundProps };
734
735const COLORS: BackgroundPalette = ["#050608", "#c9cfdb", "#7c6cff"];
736const PLUMES = 4;
737const WARM_UP_STEPS = 150; // the screen is already full of smoke on the first frame
738const STEP = 1 / 60;
739
740// Volumetric look from a 2D density field: the smoke is lit from above, and light reaching a point
741// crosses the smoke between it and the light (a short march towards the light: self-shadowing). Thin
742// edges scatter more light than dense cores. Fast-moving smoke, stirred by the cursor, catches the accent.
743const displayFragment = /* glsl */ `
744uniform sampler2D uDye;
745uniform sampler2D uVelocity;
746uniform vec3 uBackground;
747uniform vec3 uSmoke;
748uniform vec3 uAccent;
749uniform vec2 uLight;
750varying vec2 vUv;
751
752float density(vec2 uv) { return texture2D(uDye, uv).r; }
753
754float hash(vec2 p) {
755 vec3 p3 = fract(vec3(p.xyx) * 0.1031);
756 p3 += dot(p3, p3.yzx + 33.33);
757 return fract((p3.x + p3.y) * p3.z);
758}
759
760void main() {
761 float d = max(density(vUv), 0.0);
762 // Jittered start: the march would otherwise print its 6 steps as stripes
763 float jitter = hash(gl_FragCoord.xy);
764 float shadow = 0.0;
765 for (int i = 0; i < 6; i++) shadow += max(density(vUv + uLight * (float(i) + jitter)), 0.0);
766 float light = exp(-shadow * 0.5);
767 float alpha = 1.0 - exp(-d * 1.7);
768
769 vec3 smoke = uSmoke * (0.18 + 0.9 * light);
770 float edge = smoothstep(0.02, 0.25, d) * (1.0 - smoothstep(0.25, 1.1, d));
771 smoke += uSmoke * edge * light * 0.28;
772 float speed = length(texture2D(uVelocity, vUv).xy);
773 smoke = mix(smoke, uAccent * (0.4 + 0.8 * light), clamp(speed / 700.0, 0.0, 1.0) * 0.45);
774
775 vec3 color = mix(uBackground, smoke, alpha);
776 // A faint glow where the smoke is born
777 color += uAccent * 0.05 * exp(-vUv.y * 5.0) * (0.4 + 0.6 * alpha);
778 vec2 c = vUv - 0.5;
779 color *= 1.0 - 0.45 * dot(c, c);
780 color += (hash(gl_FragCoord.xy) - 0.5) / 255.0;
781 gl_FragColor = vec4(max(color, 0.0), 1.0);
782 #include <colorspace_fragment>
783}
784`;
785
786interface SmokeProps {
787 palette: BackgroundPalette;
788 interactive: boolean;
789 speed: number;
790 scale: number;
791 still: boolean;
792 resolution: FluidResolution;
793}
794
795function Smoke({ palette, interactive, speed, scale, still, resolution }: SmokeProps) {
796 const physics = usePointerPhysics(interactive);
797 const solver = useFluidSolver(resolution);
798 const state = useRef({ time: 0, warmed: false });
799
800 const display = useMemo(
801 () =>
802 fluidPass(displayFragment, {
803 uDye: { value: null },
804 uVelocity: { value: null },
805 uBackground: { value: new THREE.Color() },
806 uSmoke: { value: new THREE.Color() },
807 uAccent: { value: new THREE.Color() },
808 uLight: { value: new THREE.Vector2() },
809 }),
810 []
811 );
812 useEffect(() => () => display.dispose(), [display]);
813
814 const [background, smoke, accent] = palette;
815 useEffect(() => {
816 (display.uniforms.uBackground.value as THREE.Color).set(background);
817 (display.uniforms.uSmoke.value as THREE.Color).set(smoke);
818 (display.uniforms.uAccent.value as THREE.Color).set(accent);
819 }, [display, background, smoke, accent]);
820
821 // A new solver (first mount, resize) starts empty: warm it up again
822 useEffect(() => {
823 state.current.warmed = false;
824 }, [solver]);
825
826 const density = useMemo(() => ({ r: 1, g: 1, b: 1 }), []);
827
828 // Continuous emission: plumes along the bottom edge, wandering slowly, puffing irregularly
829 const emit = (time: number, dt: number) => {
830 const s = Math.max(0.3, scale);
831 for (let i = 0; i < PLUMES; i++) {
832 const x = (i + 0.5) / PLUMES + 0.09 * Math.sin(time * 0.21 + i * 2.1) + 0.04 * Math.sin(time * 0.53 + i * 4.7);
833 const puff = 0.55 + 0.45 * Math.sin(time * (0.9 + i * 0.17) + i * 1.3);
834 const sway = 140 * Math.sin(time * 0.7 + i * 3.3);
835 solver.splat(x, -0.03, sway, 520 + 220 * puff, density, 0.14 * puff * dt * 60, 0.2 * s);
836 }
837 };
838
839 const advance = (dt: number) => {
840 const st = state.current;
841 st.time += dt;
842 emit(st.time, dt);
843 solver.step({
844 dt,
845 time: st.time,
846 velocityDissipation: 0.15,
847 dyeDissipation: 0.24,
848 curl: 32,
849 turbulence: 0.6,
850 noiseScale: 3.2 / Math.max(0.3, scale),
851 buoyancy: 420,
852 topSink: 2.5,
853 });
854 };
855
856 useFrame((frame, delta) => {
857 const st = state.current;
858 if (!st.warmed) {
859 st.warmed = true;
860 for (let i = 0; i < WARM_UP_STEPS; i++) advance(STEP);
861 }
862
863 // Simulation time for this frame: `speed` scales it, so a slow speed is a smooth slow motion (one
864 // small step every frame), never a stutter, and changing it live makes nothing jump
865 const simDt = still ? 0 : Math.min(delta, 1 / 30) * Math.max(speed, 0);
866
867 // The cursor pushes the smoke aside (force only, no smoke of its own): its wake swirls and closes.
868 // Its push is measured in simulation time too, or it would pile up while the smoke is slowed down
869 const p = physics.current;
870 if (p.strength > 0.02 && simDt > 0) {
871 const v = p.velocity;
872 const force = 160 * p.strength * simDt * 60;
873 if (Math.hypot(v.x, v.y) > 0.01) solver.splat(p.position.x, p.position.y, v.x * force, v.y * force, null, 0, 0.42 * Math.max(0.3, scale));
874 }
875
876 if (simDt > 1e-5) {
877 // Fast speeds are split into steps of at most 1/30 s: the solver stays accurate
878 const steps = Math.ceil(simDt / (1 / 30));
879 for (let i = 0; i < steps; i++) advance(simDt / steps);
880 }
881
882 const u = display.uniforms;
883 u.uDye.value = solver.dyeTexture;
884 u.uVelocity.value = solver.velocityTexture;
885 (u.uLight.value as THREE.Vector2).set(-0.004 / solver.aspect, 0.012);
886 solver.render(display, null);
887 frame.gl.setRenderTarget(null);
888 }, 1);
889
890 return null;
891}
892
893/**
894 * Drifting smoke, simulated: plumes rise from the bottom edge, curl and spread (stable fluids with
895 * buoyancy and vorticity confinement), lit from above with self-shadowing. Moving the pointer through
896 * it pushes the volutes apart; its swirling wake closes up on its own. 100% procedural.
897 */
898export default function FluidSmokeDrift({
899 interactive = DEEP_BACKGROUND_DEFAULTS.interactive,
900 colors,
901 speed = DEEP_BACKGROUND_DEFAULTS.speed,
902 scale = DEEP_BACKGROUND_DEFAULTS.scale,
903 className = "",
904 pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen,
905 lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode,
906 respectReducedMotion = DEFAULT_3D_PROPS.respectReducedMotion,
907}: DeepBackgroundProps) {
908 const container = useRef<HTMLDivElement>(null);
909 const frameloop = useOffscreenFrameloop(container, pauseWhenOffscreen);
910 const reduced = usePrefersReducedMotion();
911 const palette: BackgroundPalette = [colors?.[0] ?? COLORS[0], colors?.[1] ?? COLORS[1], colors?.[2] ?? COLORS[2]];
912 const resolution = useMemo<FluidResolution>(() => (lowPowerMode ? { sim: 72, dye: 288, iterations: 12 } : { sim: 128, dye: 512, iterations: 20 }), [lowPowerMode]);
913
914 return (
915 <div ref={container} className={`pointer-events-none absolute inset-0 overflow-hidden ${className}`} style={{ background: palette[0] }} aria-hidden="true">
916 <Canvas dpr={lowPowerMode ? 1 : [1, 1.5]} frameloop={frameloop} gl={{ antialias: false, alpha: false, powerPreference: "high-performance" }} style={{ pointerEvents: "none" }}>
917 <Smoke palette={palette} interactive={interactive} speed={speed} scale={scale} still={respectReducedMotion && reduced} resolution={resolution} />
918 </Canvas>
919 </div>
920 );
921}
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import FluidSmokeDrift from "@/components/FluidSmokeDrift";
2
3export default function Section() {
4 return (
5 // The component fills this box: give it a position and a height
6 <div style={{ position: "relative", width: "100%", height: "100vh" }}>
7 <FluidSmokeDrift
8 speed={1}
9 scale={1}
10 background="#05060a"
11 primary="#c3cadb"
12 accent="#7c6cff"
13 interactive
14 />
15 </div>
16 );
17}
Next componentFerrofluid Topography→