How it works
A real combustion simulation runs behind the page: a 455×256 stable-fluids grid carries velocity, temperature and fuel, and the colour you see is the physical blackbody colour of that temperature. Your cursor does not paint fire. It lays a line of fuel on the “ground”, and an igniter that follows your path 0.14 s late sets it alight. The flames grow in your wake and keep burning where you drew for four to five seconds, while the fuel right under a resting pointer waits to catch until you move on.
Pipeline (per frame)
pointer path ring buffer {x, y, t} ─┬─ capsule prev→now (fuel, grip)
└─ capsule at path(t − 0.14 s) (igniter)
live user pointer ──▶ mask m = 0 within ~1 brush radius, 1 beyond 1.6 (none for the ghost torch)
fixed 60 Hz sim step, run once ≥ half a step has built up (1 per frame at 60 Hz, 0–2 otherwise)
│
├─▶ TORCH, BED state RGBA16F 455×256 v ← mix(v, v_ptr, w·grip); T ← max(T, (2·T_ign+.6)·w·m) on fuel
│ + COMBUST bed RGBA32F 455×256 static fuel line, never advected: B += w·deposit·s
│ one MRT pass rel R16F 455×256 lit = max(lit, m·ign(T)); masked hits wait in a pending latch
│ release = k·(B/s)^⅛·lit·m·jets(noise), also into rel
│ s = burn time / 4.2, so a longer burn lays more fuel
│ T, F −= ¼·[1 −4 6 −4 1]/16 in x and y (kills the odd-even mode)
│ F += release·dt; burn = min(F, F·ign(T)·rate·dt)
│ T += burn·heat; T ← T / (1 + (c·T^3/8 + m)·dt)
│ v.y += b·T·dt; v += curl-noise·dt in hot gas; drag, |v| clamp
├─▶ VORTICITY state ω = ∂v/∂x − ∂u/∂y at 9 texels; v += ε·(N × ω)·dt, N over 1.5 texels
├─▶ PRESSURE ×4 pres RG32F 455×256 14 Jacobi sweeps as 2 + 4 + 4 + 4, each pass over a diamond of
│ texels; the first computes div into .y: MAC faces (u left,
│ v bottom), forward differences, − e·burn; warm start 0.85·p
│ walls left/right/bottom; p = 0 in the top ghost row (open top)
│ + state (last pass) v ← mix(v, 4-neighbour mean, .18) − backward-difference ∇p
├─▶ SOOT soot R16F 1280×720 clamped MacCormack by the MAC v, one pass; S += yield·burn·dt
└─▶ STATE state MacCormack for T and F; semi-Lagrangian v, per face
+ EMBERS MRT, sim-sized 4096 embers in the top-left 64×64 block of
RGBA32F (pos, vel) + RGBA16F (life, max life, temp, seed)
┌────────────── render, every display frame, at t_sim + unstepped remainder ──────────────┐
│ SCENE RGBA16F 2560×1440: noise-warped T; colour from a 5-tap Catmull-Rom, edge │
│ from a B-spline through a narrow cut, ridged filaments in the hot cores │
│ → blackbody LUT 256×1 (+ the gas cone from rel), then 4096 instanced │
│ ember streaks (ONE, ONE), carried along their velocity to display time │
│ PRE 13-tap Karis + soft knee → L0 1280×720 RGBA16F │
│ + MRT RG16F 1280×720: the soot's 5-tap blur and T, for the composite │
│ DOWN 13-tap → L1 640×360 │
│ TAIL ×2 L2 = 13-tap of L1; L3–L5 (160×90 … 40×22) as separable Gaussians of L1, │
│ horizontal into strips, then vertical into one atlas │
│ GATHER L1 + .85·tent(L2) + .85²·B(L3) + .85³·B(L4) + .85⁴·B(L5) → 640×360 │
│ COMPOSITE canvas RGBA8: bloom = L0 + .85·tent(GATHER), normalised; flames·(1 − veil) │
│ + bloom + fire-lit smoke → ACES → sRGB → TPDF dither │
│ premultiplied α = 1 − (1 − 0.4·smoke)·(1 − max); smoke × ¼ over the buttons; │
│ UI veil (floor 0.35) only around a real pointer over a button or link │
└─────────────────────────────────────────────────────────────────────────────────────────┘
15 render passes per frame: 8 for a sim step, 7 for rendering (the ember draw shares the scene's)
The ideas that matter
- The fuel lives on the ground, not in the air. If the cursor injected burning gas, the trail would float up and burn out in under a second, like a fireball. Instead the cursor fills a static fuel bed that is never advected. Once a flame heats a fuelled cell past ignition, the cell latches lit and feeds gas into the flow at a rate ∝
B⅛, so a stretch of trail burns near full strength for most of its life and then dies down quickly. Slow noise on that rate splits the line into separate jets, the seeds of distinct tongues. - Burn time stretches the fire instead of thinning it. The bed gets
s = burn time / 4.2times the fuel and the release is rescaled to(B/s)⅛, so a longer burn keeps the same flame height and simply lasts longer. At the default fuel the centre of a stroke burns for about five seconds. The intro’s ghost torch lays only 1.2× the fuel of a real stroke, so your own first stroke looks like the one you just watched. - A delayed igniter, and a torch that never sits in its own fire. A ring buffer of pointer samples lets the igniter heat the path where the cursor was 0.14 s ago, so flames bloom a beat behind it, and when you stop it catches up and lingers for 0.3 s. Within about one brush radius of a real pointer nothing lights or burns: fuel reached there waits in a pending latch and catches the moment the pointer moves off. The trail ends a little short of the cursor with real flames right behind it, instead of a hole cut in the picture. Over a button or link the display adds a soft veil that never goes below 35%, applied to the radiance before the tonemap so dimmed yellow cores shift toward red rather than olive.
- Combustion with tips. Fuel burns where temperature passes a smoothstep ignition,
burn = min(F, F·ign·rate·dt), and the heat it releases lifts the gas through buoyancy. Radiative cooling goes as(T/Tmax)⁴, so the hottest gas loses heat fastest, which ends a tongue in a tip instead of an endless column. Integrated implicitly,T ← T/(1 + c·T³·dt), it is stable at any cooling rate, and a linear entrainment term stops warm gas from glowing on as haze. - Physical colour, in HDR. At startup, JavaScript bakes a 256×1 RGBA16F LUT from Krystek’s approximation of the Planckian locus in CIE 1960 (u, v), through XYZ to linear sRGB, with chromaticity normalised to 1 and radiance ∝ T⁴. Sim temperature maps linearly to Kelvin, so cores run past the top of the ramp into HDR, and a per-channel ACES tonemap turns them white-hot while thin sheets stay saturated orange and red. Plasma keeps the same T⁴ radiance but walks the hue from indigo through violet and orchid to lavender-white, with a higher HDR ceiling so its cores reach the white end.
- Sharp at 1:1: interpolate the colour, smooth the edge. The colour comes from a 5-tap Catmull-Rom lookup, which passes through the sim’s values, so the inside of a tongue keeps its shape. The silhouette comes from a cubic B-spline of the same temperature through a narrow cut (about 870–1220 K on the default ramp), which removes the grid-scale comb an interpolating filter would show at the edge. Inside the hot body only, a fast-rising ridged noise brightens thin filaments; its coordinates are warped by the slow noise layers, because plain ridges nest into a woodgrain. The scene renders at the full 2560×1440 canvas.
- Tongues, not fur. Rising noise displaces the temperature lookup upward rather than multiplying it, which bends the iso-contours into tongues; multiplicative noise only makes furry edges. Velocity stays semi-Lagrangian while temperature, fuel and soot get clamped MacCormack, because undamped MacCormack velocity plus confinement boils at grid scale. Vorticity confinement takes its gradient over 1.5 texels, so it follows eddies a few cells across.
- A gas flame shines from its reaction. Blue flame is soot-free, so most of its light is chemiluminescence from the burning itself (Nguyen et al. 2002), not blackbody glow. The trail is the burner: the bed pass copies its release rate into an R16F target that the scene filters cheaply, and that band, reaching a few cells up, is drawn as a translucent azure cone. The reaction
F·ign(T)·rateinside it runs from cyan to a white-cyan core, and the hot products above are cut hard, so the plume stays nearly transparent instead of glowing as a lavender cloud. - A projection that agrees with itself. The storage is collocated but read as a staggered (MAC) grid: texel (i, j) holds u on its left face and v on its bottom face. Divergence is a forward difference and the gradient a backward one, so together they form exactly the 5-point Laplacian the Jacobi pass solves; with central differences, 2–3-cell compressions escape it and pile up as ripples in dense plumes. Advection samples each component half a cell over and traces each face from its own position. The top texel row is a ghost row with p = 0 whose v is the open top’s outflow, so divergence, pressure and gradient agree at the boundary.
- No washboard in the plume. Where gas rises an even number of cells per step, advection copies each row from a row of the same parity, so a small odd-even difference near the bed would ride up the plume as thin horizontal lines. A ∇⁴ hyperdiffusion on temperature and fuel,
¼·[1 −4 6 −4 1]/16per axis per step, removes that 2-cell mode while 5-cell tongues keep 97% of their amplitude. - Soot becomes smoke where it cools. Burning also makes soot, MacCormack-advected at half display resolution and drawn once the gas has cooled below what reads as flame. It is lit by the bloom texture as a stand-in for firelight, and its ambient light grows faster than the soot as the slider rises, so the top of the range shows grey, fire-lit smoke rather than only a darker veil on a dark page. Over the page’s buttons the smoke fades to a quarter, so heavy smoke reads as a thin haze in front of a white button, not a grey smudge on it.
- Embers without a CPU readback. 4096 GPU particles live in float textures. Each sim step a ring-buffer window of ids respawns at random recent path points, and a candidate is only born where the sim is above ignition, so sparks come from wherever the trail is actually burning. They ride the flow with drag, lift and flutter, cool through the same LUT and are drawn as velocity-stretched streaks into the HDR scene, so they bloom too. Their state sits in the corner of two sim-sized textures, so the state-advection pass steps them as extra MRT outputs instead of spending a pass of its own, and each frame draws them carried along their velocity to the display time, so they still move at the display’s rate.
- Stable bloom. The first 13-tap downsample (Jimenez 2014) Karis-averages its five 2×2 groups by
1/(1+luma)and applies a soft knee, so a single spark or thin tip cannot make the pyramid flicker. Each of the six levels is weighted0.85iand the sum is normalised, so the radius does not change the strength. The default (strength 1.6, threshold 0.3) throws a visible warm halo around the cores. - Fifteen render passes, not forty. On ANGLE/Metal a frame of 16 or more render passes measured about 2 ms more GPU time than the same work in 15, so passes are merged wherever a pass only reads the texel it writes or a few around it. Torch, bed and combustion share one MRT pass. Vorticity computes its own curl. The 14 Jacobi sweeps run 2 + 4 + 4 + 4 per pass, each pass reading the diamond of texels within its sweep count and mirroring it across the walls, which reproduces the walls’
p(−1) = p(0)exactly. The first pass also computes the divergence and the last also applies the gradient. Each MacCormack advection takes one pass, recomputing the forward step at the four texels its reverse step lands between. Stepped from the same random fields, the merged sim matches the old one-job-per-pass layout: torch, bed and combustion bit for bit, the pressure solve to float precision, and vorticity and advection to within the half-float rounding of fields that now stay in registers. The bloom keeps the 13-tap pyramid and its tent upsampling exactly down to L2. L3–L5 come straight from L1 as separable Gaussians and go back up through cubic B-splines, with variances matched to the 13-tap and tent chains they replace. Against the old 11-pass pyramid on the same frames, the bloom differs by 0.4–0.6% on average and at most 1.4%. - Display-independent. The sim takes fixed 60 Hz steps, each run once at least half a step of time has built up, so a 60 Hz screen gets exactly one per frame despite rAF jitter and the fire looks the same at any refresh rate. Rendering happens every display frame at
t_sim + remainder, so on 90–144 Hz screens the flame noise and embers move at the display’s rate (the embers step with the sim and are drawn carried forward by the remainder) while the fluid advances in 60 Hz steps. All noise runs on accumulated sim time, so nothing jumps after an idle stop. - It opens already burning, around the copy. Before its first frame the page simulates 0.4 s of the ghost stroke off-screen, so flames are up at the first paint. The path is measured from the live layout. On a desktop it starts right of the buttons, climbs a gentle S-curve once past the copy column so tongues reach headline height, and comes back along the same line. Where the buttons span the screen, as on phones, it runs below them and then climbs the right edge to the headline, about a second into the intro. The gallery embed sweeps back and forth, rising to mid-height on the right.
Parameters
Presets
All four presets are dark. Fire is emission: additive light reads against a dark page and vanishes on white, where flames look like orange stickers. The light-page story for fire is a different model, burning paper with a char front and an ember rim (the burning-paper candidate in the research notes).
Performance & compatibility
- Measured by the harness: Chrome, ANGLE-Metal, an Apple M5 (10-core GPU), 1280×720 at DPR 2, so a 2560×1440 backing store, during its scripted pointer sweep. Serial, locked, uncontended runs (the library’s GPU lock, so no other harness shared the GPU): the default preset measured a steady 60 fps, GPU 4.65 ms mean and 7.21 ms p95, JS 0.19 ms per frame. Per preset (GPU mean / p95): Campfire 5.13 / 7.67, Blue flame 4.55 / 7.39, Hellfire 3.96 / 6.75, Plasma 4.89 / 7.07 ms. Before the pass merging described above, the same canonical run measured 7.71 / 14.8 ms. The per-frame timer still swings by about 2× within a sweep: it reads around 4 ms for some frames and 7–8 ms for others as the GPU’s clock and the browser’s own GPU work come and go, so p95 sits well above the mean.
- Per-frame cost. With the screen full of fire after a harness-style sweep, timing 20 frames inside one GPU query (median of 7) gives 2.4–2.7 ms per frame across the four presets (Campfire 2.5 ms), against 3.4 ms for the 40-pass version timed the same way. The largest single passes are the full-resolution scene and composite, then the bloom’s first downsample and the soot advection.
- What scales the cost. Pass count first: a 60 Hz frame is 15 render passes, 8 of them the sim step, and a frame that has to run two sim steps to catch up after a long frame takes 23 and pays the extra ~2 ms. Fill comes next. The HDR scene is 3.7 MP at full resolution with 2 early-out taps, 5 Catmull-Rom, 4 B-spline and 4 noise taps per lit pixel, plus 6 taps of the R16F release for the gas cone. The composite reads 7 taps per pixel: scene, bloom L0, 4 for the tent upsample of the gathered levels, and one for the blurred soot and temperature that the bloom’s first pass writes alongside L0. The merged sim passes fetch more texels than one-job passes would (a 4-sweep pressure pass reads 41), which costs far less than the passes they replace. About 63 MB in all: scene 29.5, bloom 16.2 (L0 7.4, the soot/temperature target 3.7, L1 and its gathered sum 3.7, atlas and strips 1.5), sim 7.7 (3.7 of it the RGBA32F bed), embers 5.6 (sim-sized so the advection pass can step them), soot 3.7, LUT and noise 0.3.
- Requirements. WebGL2 with
EXT_color_buffer_floatfor half-float and float render targets. The bed (RGBA32F) and pressure (RG32F) use NEAREST filtering (every pass reads them at texel centres), so they need no float filtering. The merged passes write up to three targets of mixed formats at once (RGBA16F, RGBA32F, R16F). Ember positions use RGBA32F, with an RGBA16F fallback if that cannot be written alongside the state. Nothing blends into a 32-bit target, soEXT_float_blendis not needed. Without WebGL2 the hero stays live and clickable, and a message card explains why the fire is missing. - Mobile. Drag to light a trail. Coarse pointers render at 1.5× DPR (585 px wide on a 390 px phone), with the HDR scene at 0.75× of that, a 160-cell sim and 2304 embers. The harness measured a 60 fps touch drag at 390 px. A real finger gets the same sim mask as a cursor while it rests. The intro runs below the buttons, then climbs the right edge so tongues reach the headline in the first second. All sizes follow the screen’s short side, so the flames keep their proportions in portrait.
- Idle and visibility. The trail eases out over the 1.6 s before the 7 s idle stop, then the sim is cleared. The harness measured the loop idle at 7.10 s with zero frames after. It pauses off-screen and in hidden tabs. The gallery embed runs the ghost torch forever at DPR 1, with a 176-cell sim, 1024 embers, 15% more fuel and buoyancy and a quarter fewer sparks.
- Reduced motion. 2.5 s of the intro stroke are simulated off-screen and shown as one still frame, with a “Play anyway” button. The 0.4 s pre-roll that opens the animated page already burning is skipped here.
- High refresh rates. Rendering runs every display frame, so on 90–144 Hz screens the GPU renders 1.5–2.4× as often as at 60 Hz while the sim step count is unchanged. A frame without a sim step is 7 render passes. The embers are stepped with the sim and drawn carried along their velocity to the display time, so they still move smoothly.
References & credits
- Duc Quang Nguyen, Ronald Fedkiw, Henrik Wann Jensen, “Physically Based Modeling and Animation of Fire”, SIGGRAPH 2002: combustion fields, expansion at the reaction front, blue core, blackbody rendering. cseweb.ucsd.edu/~henrik/papers/fire (paper).
- Ronald Fedkiw, Jos Stam, Henrik Wann Jensen, “Visual Simulation of Smoke”, SIGGRAPH 2001: temperature buoyancy and vorticity confinement. cseweb.ucsd.edu/~henrik/papers/smoke (paper).
- Francis H. Harlow, J. Eddie Welch, “Numerical Calculation of Time-Dependent Viscous Incompressible Flow of Fluid with Free Surface”, Physics of Fluids 8, 1965: the staggered (MAC) grid whose face-centred differences the projection borrows on collocated storage. doi.org/10.1063/1.1761178 (paper).
- Jos Stam, “Stable Fluids”, SIGGRAPH 1999. dgp.toronto.edu/…/ns.pdf. Mark J. Harris, GPU Gems ch. 38: the fragment-shader formulation. developer.nvidia.com/gpugems (book text, free online).
- Andrew Selle et al., “An Unconditionally Stable MacCormack Method”, J. Sci. Comput. 2008: the clamped MacCormack scheme. yingjie.math.gatech.edu/…/SFKLR.pdf. Its GPU form follows Crane, Llamas & Tariq, GPU Gems 3 ch. 30. developer.nvidia.com/gpugems3.
- Robert Bridson, Jim Hourihan, Marcus Nordenstam, “Curl-Noise for Procedural Fluid Flow”, SIGGRAPH 2007: divergence-free turbulence. cs.ubc.ca/~rbridson/… (paper).
- M. Krystek, “An algorithm to calculate correlated colour temperature”, Color Research & Application 10(1), 1985: the rational Planckian-locus approximation used for the LUT, as summarised in Wikipedia: Planckian locus (CC BY-SA text; the formula is mathematics).
- Catmull-Rom filtering in a few bilinear taps: Matt Pettineo (MJP), “Catmull-Rom texture filtering in 9 samples”, gist.github.com/TheRealMJP (MIT), and the 5-tap variant without corner taps from Jorge Jimenez’s “Filmic SMAA” talk, SIGGRAPH 2016 Advances in Real-Time Rendering, advances.realtimerendering.com/s2016 (slides). Written from the published weight formulas; no code copied.
- Jorge Jimenez, “Next Generation Post Processing in Call of Duty: Advanced Warfare”, SIGGRAPH 2014: the 13-tap downsample and Karis-averaged first pass. iryoku.com (slides). The weights were cross-checked against LearnOpenGL’s “Phys. Based Bloom” (learnopengl.com, code CC BY-NC 4.0: read, not copied). Soft-knee curve after keijiro/KinoBloom (github.com/keijiro/KinoBloom, MIT).
- Krzysztof Narkowicz, “ACES Filmic Tone Mapping Curve”, 2016: the fitted tonemap. knarkowicz.wordpress.com (blog; public formula).
- Ken Perlin, “Improving Noise”, SIGGRAPH 2002: the quintic fade in the gradient noise. mrl.cs.nyu.edu/~perlin/paper445.pdf. Hash: Dave Hoskins, “Hash without Sine”, shadertoy.com/view/4djSRW, MIT.
- Pass layout (curl → vorticity → divergence → pressure → gradient → advect): the common WebGL arrangement of Pavel Dobryakov’s WebGL-Fluid-Simulation (MIT), via the Russ Hype Machine reference trail this library is seeded from. No code is copied: this page is written from the papers above. andrewkchan/fire-simulation (no licence, all rights reserved) is compared in the research notes; none of its code is used.
- Research:
research/smoke-fire-ink.md(the fire model and thefire-fusecandidate),research/distortion-glass-post.md(bloom, anti-firefly, tonemap and dither) andresearch/eulerian-fluids.md(MacCormack measurements and the 120 Hz finding), all in this library.