How it works
A small stable-fluids simulation carries a single channel of ink, and the ink is never drawn as a cloud: only its iso-contours are, as lines that keep the same pixel width however hard the flow stretches them. Because the ink is advected, every contour is a material line, a thread of liquid that moves with the flow. Dragging the cursor combs the threads into long parallel filaments that fold around vortices and nest like suminagashi marbling or a moving topographic map. A click drops ink that pushes the older rings aside, the way a drop spreads on a marbling bath.
Pipeline (per frame)
Sizes at a 2560×1440 backing store (1280×720 CSS px at DPR 2). Steps of ~1/60 s, one per frame at 60 Hz;
on 90–144 Hz displays a frame between steps draws the latest ink back-warped along the last velocity.
pointer ─▶ critically damped spring (ω 32/s) whose target glides to the cursor over each step
└─▶ ink ≤16 erf ridge segments per step, blend ONE,ONE, scissored ─▶ ink R32F 1707×960
click / intro ─▶ drop: C²-footed cone at 0.45·R, blended once + spreading-flow uniforms (≤6 drops)
vel ─▶ curl + rotation weight RG16F ─▶ vorticity confinement (vortex cores only) vel RG16F 228×128
─▶ viscosity (v₀ parked, 10 Jacobi)
─▶ k sub-steps, k = clamp(⌈brush travel / ½σ⌉, 1, 3):
grip (erf-weighted mix toward the brush velocity over 2.5σ, speed soft-capped)
─▶ divergence (free-slip walls) ─▶ red-black SOR ×20 (×8 when k > 1, warm) ─▶ v −= ½∇p
─▶ snapshot ─▶ semi-Lagrangian self-advection by h/k, fade 0.6/s
ink ─▶ MacCormack A back-trace by B-spline(vel) + drop flow ──────────────────▶ hat R32F 1707×960
─▶ MacCormack B hat + β(CFL)·½(φ − fwd), clamp to the 4 source texels,
+ 0.06·∇²hat, fade ──────────────────────────────────────▶ ink R32F 1707×960
(k > 1: both again, scissored to the brush path, tracing through all k snapshots)
(ink is R16F where R32F can't be filtered or blended)
dark grounds only (allocated on first use):
ink ─▶ bloom source: box-filtered line coverage × colour ───────────────────────▶ RGBA16F 640×360
─▶ 4 × 5-tap down (to 40×23) ─▶ 4 × 8-tap tent up, added level by level
ink (+ bloom, + washi paper RGBA8 512² mipmapped, drawn once on a 2D canvas)
─▶ display 2560×1440: [between steps: offset + Jacobian from B-spline(last vel) + drop flow]
f = bands·T(B-spline(ink)); ∇f and Hessian from 7 taps;
contour level of detail (2 candidates/pixel); second-order distance to each level
─▶ 1 px anti-aliased edge; colour by level
paper: fibre-feathered ink + soft line shadow (quadratic model at p − offset, faded by spacing)
night: Tanaka lighting + wire glint + bloom + hue-keeping shoulder; ±1/255 dither
The ideas that matter
- Draw distance, not threshold. With f = ink × bands, the nearest level is n = round(f), and
(f − n)/|∇f|is, to first order, the distance to that contour in pixels. Coverage is a 1 px smoothstep around half the line width, so every line has the same width and edge however far the flow stretches or squeezes the ink. The derivatives come from central differences one ink texel apart rather thanfwidth, which is constant over each 2×2 pixel quad and makes 1 px lines jaggy. This is the distance-normalised anti-aliasing from the metaball and SDF notes, applied to an advected field. - Second order where first order fails. At a saddle, where two lines of one level touch, |∇f| goes to 0 and the first-order distance blows up into speckle. The same taps give the Hessian, so the distance is solved from the local quadratic instead: ½c·s² + |∇f|·s = |f − n| along the gradient, and s = √(2|f − n|/κ) along the eigen-direction that bends toward the level at a critical point. Necks thicken smoothly, and a crest that turns over just short of a level draws nothing.
- fp32 ink for the flat parts. A plateau that sits a few thousandths of a level under a contour is where any distance estimate is most fragile, and fp16's 10-bit mantissa terraces it into grey speckle and ragged line ends. The ink is R32F wherever the GPU can filter and blend it, which costs nothing measurable on an M-series GPU, and R16F elsewhere.
- Contour level of detail, as on a topographic map. Where the flow packs lines closer than their width plus 2 px, every second level thins out and fades, then every fourth, in power-of-two steps from the local line density. Each pixel tests the nearest kept line and the nearest fading one, so neither clips the other, and a fading line stays ink-coloured because it narrows before it turns transparent.
- A seamless ink ridge. Each brush segment deposits the exact integral of a Gaussian dragged along it,
exp(−y²/2σ²)·½[erf(s/σ√2) − erf((s−L)/σ√2)], so consecutive segments add up to one ridge of constant height at any speed or frame rate. Contours magnify any bump in that ridge, so the path is also cut into sub-segments of at most σ/5 along the spring's smooth curve, and the grip uses the same erf weight. - Marbling drops are a flow, not a stamp. A drop lands as a small cone and is grown by an ink-only flow: a uniform dilation inside the current radius R, so its own rings stay evenly spaced, and an area-preserving source (u = R·R′/r) outside, so every older ring moves to r′ = √(r² + R² − R₀²), the classic marbling drop map. Starting at R₀ = 0.45·R keeps the older rings at the rim from being squeezed past what constant-width lines can resolve, and the cone's foot and the inside/outside switch are both smooth, so no ring the rim passes keeps a kink.
- Gentle forcing keeps the lines clean. Contours turn any velocity roughness into visible teeth, so the forcing is shaped rather than strong. The grip mixes toward the brush velocity (never adds to it) over a band 2.5σ wide, with its target speed soft-capped at 2.4 short sides per second, and a fast brush grips and projects in up to three sub-steps instead of one big jump. Vorticity confinement is weighted by how rotation-dominated the flow is, ω²/(ω² + strain²), so it spins up eddies but leaves the shear layers either side of a stroke alone; confining those rolled them into grid-scale chevrons.
- CFL-adaptive MacCormack. Clamped MacCormack keeps slow swirls crisp, but where the ink moves more than about a texel per step its round-trip error estimate goes wrong in the shear, and plain semi-Lagrangian is cleaner there, with blur that is invisible on 50-texel ridges. So the correction fades out between 1 and 3 texels per 1/60 s, normalised per second so every refresh rate gets the same blend, and a small κ = 0.06 Laplacian relaxes the ringing that is left. Both passes trace the velocity through a 4-tap cubic B-spline, because bilinear velocity creases show up in stretched lines.
- Motion-compensated frames on high-refresh displays. The simulation keeps ~1/60 s steps, so on a 120 Hz screen every other frame falls between two steps. That frame samples the latest ink where it will have flowed to,
ink(x + s·v(x)), with v the last velocity plus drop flow and s the time to the latest step, and the offset's Jacobian warps the neighbour taps too, so line width stays exact. A plain mix of the last two ink states would flatten every ridge crest in between, and the smallest loops would pulse at 60 Hz. - A soft shoulder on the ink. Ink is stored linearly, so strokes sum exactly, but it is drawn through T(d) = 2.2(1 − e^(−d/2.2)). Where strokes pile up, the level count saturates instead of packing endless lines together.
- Free extras from the same distance. The paper line shadow is the contour evaluated at p − offset from the same local quadratic (f − ∇f·o + ½oᵀHo), so it costs no extra texture reads. It is wide and faint, and it fades where lines pack closer than a few shadow widths, so dense bundles stay clean paper instead of a grey ribbon. On the dark ground, Gold Leaf lights each line Tanaka-style by whether its slope faces the top-left light, with a tiny glint in the wire's own colour, and the bloom source is the box-filtered line coverage computed directly at quarter resolution, so the glow never aliases.
- Resolution where it counts. Lines are drawn per device pixel from the interpolated field, so the ink only has to resolve the ridges: 960 on the short side looks as clean as 1440 at 3× zoom, for 56% fewer texels in every advection pass. The display reads the ink through the same 4-tap B-spline as the velocity, because bilinear contours of a peak are piecewise straight and the last small loops before a level vanishes looked polygonal.
Parameters
Presets
Performance & compatibility
- Measured by the library harness at a 2560×1440 backing store on an M-series Mac whose GPU was shared with two or three other agents' harness runs throughout, so no idle-machine run was possible. Every run held 60 fps through the pointer sweep, with JS at 0.08–0.15 ms per frame. A full run at the end of this round measured 5.5 ms mean / 8.8 ms p95 GPU time per frame. Across this round's runs the mean ranged from 3.9 to 10.6 ms and the p95 from 6.1 to 18.2 ms; interleaved runs of the previous version under the same load ranged from 5.5 to 17.6 ms mean and 9.9 to 28.4 ms p95, so the spread is contention, not the page.
- The steadier numbers are GPU-timer minima per pass group (best of 60 at 2560×1440, several runs): the display takes 0.72 ms on a frame that lands on a simulation step and 1.15 ms on an in-between frame of a high-refresh display (the motion-compensated warp), and one simulation step takes 0.88 ms with one sub-step and about 1.0 ms with three. Three sub-steps cost about the same as one because each warm-started sub-step runs 8 SOR sweeps instead of 20 and the extra ink trace is scissored to the brush path. The dark presets add the bloom pyramid (one quarter-res pass plus eight tiny ones), allocated only when a dark ground first needs it.
- Cost is dominated by the two MacCormack passes over the ink and the full-resolution display. The ~40 velocity passes run on a 228×128 grid and are cheap, though each adds a little fixed overhead. Brush ink segments are scissored to the stroke, and the drop flow loops only over drops that are still growing.
- Needs WebGL2 with
EXT_color_buffer_float(R16F/RG16F/RGBA16F render targets, 16F blending). The ink uses R32F whenOES_texture_float_linearandEXT_float_blendare also present, and R16F otherwise, which brings back a little speckle on near-flat ink. Without float render targets the page shows the library's fallback card over the poster frame. - Phones (coarse pointer) draw at DPR 1.5, run the ink at 0.7× the canvas (at most 600 on the short side) and run 6 viscosity sweeps instead of 10. At 390 px wide (harness emulation of a DPR 3 touch device) that is a 585×1266 canvas and 410×887 ink, the same ink-to-canvas ratio as desktop, and touch-drag measured 51 fps in the emulation on a desktop GPU. The page has not been tested on real phone hardware. Drag to comb; a short, nearly still tap drops ink. The controls become a bottom sheet, and brush and drop sizes scale with the short side.
- High-refresh displays render every frame. The simulation keeps ~1/60 s steps (shorter steps add MacCormack noise) and runs up to one step ahead of the clock, and a frame between steps draws the latest ink warped back along the last velocity. Physics is in seconds, so 120 Hz does not run fast. Checked with a deterministic replay rendered at 120 and 144 Hz and read back frame by frame: the smallest loops shrink smoothly through the in-between frames, where mixing the last two states made them pulse.
- Pauses keep the drawing. Scrolling the stage away or hiding the tab pauses the loop without clearing anything, and the time away doesn't count toward the fade. The loop stops 7 s after the last input or the end of the intro, once the lines have faded out over the final 1.6 s, so nothing freezes on screen; coming back to an empty stage replays the intro.
- With
prefers-reduced-motionthe intro (seven drops and the comb) is simulated off-screen for 165 steps and shown as one still frame, with a "Play anyway" button. Changing a preset or control re-renders the still.
References & credits
- Jos Stam, "Stable Fluids" (SIGGRAPH 1999): dgp.toronto.edu (paper; all rights reserved, cited only).
- Mark Harris, "Fast Fluid Dynamics Simulation on the GPU", GPU Gems ch. 38: developer.nvidia.com (book text; all rights reserved, cited only).
- Fedkiw, Stam & Jensen, "Visual Simulation of Smoke" (2001), vorticity confinement: stanford.edu (paper; all rights reserved, cited only).
- Selle, Fedkiw, Kim, Liu & Rossignac, "An Unconditionally Stable MacCormack Method" (2008): gatech.edu (paper; all rights reserved, cited only).
- Sigg & Hadwiger, "Fast Third-Order Texture Filtering", GPU Gems 2 ch. 20, the 4-tap B-spline: developer.nvidia.com (book text; all rights reserved, cited only).
- Aubrey Jaffer et al., "Mathematical Marbling", the drop map r′ = √(r² + R²): people.csail.mit.edu/jaffer/Marbling (articles; all rights reserved, cited only).
- Okubo (1970) and Weiss (1991), the rotation-versus-strain criterion that gates the vorticity confinement here (papers; cited only, no URL).
- Kitiro Tanaka, "The relief contour method of representing topography on maps", Geographical Review 40:3 (1950), illuminated contours: doi.org/10.2307/211219 (paper; all rights reserved, cited only).
- Marius Bjørge, "Bandwidth-Efficient Rendering", SIGGRAPH 2015 course "Moving Mobile Graphics", the dual-filter blur behind the bloom pyramid (slides, no stable URL; all rights reserved, cited only).
- Abramowitz & Stegun 7.1.26, the erf approximation (public domain).
- Dave Hoskins, “Hash without Sine”, shadertoy.com/view/4djSRW (MIT): the
hashfunction behind the output dither. - Pavel Dobryakov, WebGL-Fluid-Simulation: github.com (MIT), the WebGL pass layout this family of sims popularised. No code copied.
- This library's research notes (
research/eulerian-fluids.md,research/rd-metaballs-sdf.md) and the reference fluid trail, which supplied grip, per-distance deposit and implicit viscosity. Everything on this page is written from scratch.