Repository navigation
Description
feat(fx): incompressible Navier-Stokes solver (fl::FluidSim) as a 2D effect
Motivation
Stefan Petrick (author of AnimARTrix) posted "FastFluid Update — Behind the Scenes of a Realtime Fluid Solver" to r/FastLED and a companion thread in r/WLED. He is running a numerical Navier–Stokes solver on LED matrices — a 64×64 grid in his demos, and in the WLED thread he reports an unoptimized prototype hitting ~30 fps on a 48×32 WS2812 matrix on a bare ESP32-S3.
This is a different class of effect from anything we ship today:
fl::FlowField(src/fl/fx/2d/flowfield.h) is noise advection. It transports color along a Perlin-noise vector field. There is no velocity field that responds to itself, no pressure solve, and therefore no incompressibility — smoke never "sloshes", it just follows the noise.- A real solver has a velocity field that is advected by itself, diffused, and then projected onto its divergence-free component by solving a Poisson equation for pressure. That projection step is what produces vortices, shear layers, and the lava-lamp look in Stefan's clips. It cannot be faked with a noise field.
The reference algorithm is Jos Stam, Stable Fluids (SIGGRAPH 1999), the paper Stefan links in the WLED thread: https://pages.cs.wisc.edu/~chaol/data/cs777/stam-stable_fluids.pdf.
What exists today
| Piece | Where | Status |
|---|---|---|
| Noise-advection flow field | src/fl/fx/2d/flowfield.h / .cpp.hpp |
ships in 3.10.10; float + fixed-point variants |
| Wave PDE | src/fl/fx/2d/wave.h |
ships; 2D wave equation |
| Stam solver | — | missing |
Nothing in the tree does a linear solve or a pressure projection. The closest existing machinery is the fixed-point math in src/fl/math/fixed_point/ (s16x16) and the fl::vector/XYMap plumbing that FlowField already uses.
Proposed design
Add fl::FluidSim as an Fx2d (src/fl/fx/2d/fluid.h + fluid.cpp.hpp), following the existing FlowField layout so it drops into FxEngine and the wasm UI with no new glue.
Fields (padded grid, (W+2)*(H+2) cells, boundary ring at 0 and W+1/H+1):
u,v— velocity,u0,v0— previous velocityd,d0— density (the visible "ink")p,div— pressure and divergence scratch
Per frame:
diffusevelocity — Gauss–Seidel relaxation of(I − a∇²)project— compute divergence, solve the pressure Poisson equation, subtract∇padvectvelocity by itself — semi-Lagrangian backtrace with bilinear interpolationprojectagain — the advected field is no longer divergence-freediffuse+advectdensity, then apply dissipation
Injectors: Gaussian splats. A splat is an exp(-r²/radius²) weight over a bounding box, adding force (fx, fy) to velocity and a density amount to d. Three splats whose angles are noise-modulated reproduce Stefan's "jets shaping themselves" behaviour without keyframes.
Frame-rate independence: everything that advances the simulation must be scaled by dt — the splat impulse (force is an acceleration, so dt multiplies it, exactly as Stam's add_source does), the density injection rate, the dye injection interval, and the density dissipation (dissipate^(dt*60), so a documented "fraction surviving one 60 fps frame" gives the same smoke lifetime at any frame rate). Getting this wrong makes the sim run visibly faster on a 60 fps part than on a 20 fps one, which would invalidate the fps comparison in criterion 4.
Boundary conditions: b=1 mirrors horizontal velocity, b=2 mirrors vertical velocity (negated), b=0 is a plain Neumann mirror for density and pressure. Corners average their two neighbours.
Two compute tiers
Mirror the FlowField split so 8-bit parts stay viable:
- Float tier (
FluidSimFloat) —floatfields. This is the reference implementation and the one that should be validated against the paper first. - Fixed-point tier (
FluidSimFP) —s16x16(ors32x16) fields. Gauss–Seidel is well conditioned for this: the iteration count is small and the values stay bounded, so Q16.16 should hold. Validate against the float tier with a tolerance, the same wayFlowFielddoes.
Memory budget
8 × (W+2)(H+2) × sizeof(cell), i.e. the padded grid, not the display grid:
| Grid | cells | float (32-bit) | Q16.16 (32-bit) |
|---|---|---|---|
| 32×32 | 1 156 | 36.1 KiB | 36.1 KiB |
| 48×32 | 1 700 | 53.1 KiB | 53.1 KiB |
| 64×64 | 4 356 | 136.1 KiB | 136.1 KiB |
At 64×64 this is PSRAM-class. The example should carry @filter: (memory is large) and default to 32×32 or 48×32 on non-PSRAM parts. A 16-bit fixed-point tier would halve these to 18.1 / 26.6 / 68.1 KiB if s16x16 precision turns out to be sufficient.
Cost
Per frame at 64×64 with 12 Gauss–Seidel iterations the solver does roughly 12 × 8 × 4096 ≈ 400 K cell updates, plus two advection passes. On top of that come the splat injections: each splat is a Gaussian weight over a 3-sigma bounding box, so that is 3 force box passes per frame plus a density pass at 5 Hz — bounded, but not free, and on a small grid it is a large share of the total. That is the number to measure on real hardware — Stefan's ~30 fps at 48×32 on an S3 is the target to beat or match. Candidate optimizations if we miss it:
- fewer iterations (8 is usually visually indistinguishable for smoke)
- restrict the projection to every other frame
s16x16fixed-point tier- ESP32-S3 SIMD for the inner Gauss–Seidel loop (Stefan notes the S3 vector unit is worth trying; another commenter found it did not help a particle system, so measure before committing)
Prototype
A working prototype sketch is up in draft PR #5336: examples/FluidSim/FluidSim.ino, the float-tier solver with the injector setup and UI. It compiles and renders through the CLI wasm compiler and is the base for the promotion work below.
Dev harness
Develop against the FastLED CLI wasm compiler, which renders the sketch in a real browser and can capture deterministic frames:
fastled examples/FluidSim --fastled-path <path-to-fastled> \
--test --test-screenshot frame.png --test-wait-secs 2 --test-timeout-secs 120--test-interval-secs + --test-count capture a time series, which is what a fluid sim needs — a single frame cannot show whether the solver is actually moving and divergence-free. --check renders one frame and fails on browser-side errors, so it works as a cheap CI gate.
Two harness caveats found while developing the prototype:
- The sketch calls
setScreenMap(xyMap)on theaddLedschain, but the viewer logsscreenMapsCount: 0and falls back to an auto-detected grid. It looks right for a single square matrix, but the SERPENTINE mapping is never exercised, so a green wasm render does not prove the screen-map wiring. Worth a separate CLI bug. - Screenshots are tone-mapped, so they cannot show whether density is bounded. The prototype prints
fluid peak=<value>once a second to the viewer log; a 14 s run held peak density between 0.13 and 0.26 with no growth trend, which is the evidence for criterion 1, not the pictures.
Acceptance criteria
FluidSimFloatreproduces the qualitative behaviour of Stam's reference: injected dye advects, shears into filaments, and forms vortices; no density blow-up over 10 000 frames.- Velocity divergence after projection is below a documented epsilon on a synthetic test field (a unit test, not a screenshot).
- The fixed-point tier stays within a documented tolerance of the float tier on the same seed and inputs.
- 48×32 runs at ≥ 20 fps on an ESP32-S3 (measured, not estimated).
- The wasm example compiles and renders without browser-side errors via
--test. - Memory at the default grid is documented per tier. Partially done: the example carries
@filter: (memory is large)and the grid is overridable at compile time (-DFLUID_GRID=32), but the default is still 64×64 — a reduced default for non-PSRAM parts is not implemented yet.
Open questions
- Should the solver live in
src/fl/fx/2d/as a first-classFx2d, or stay an example until the fixed-point tier is proven? (Proposal: land float asFx2d, keep the example as the reference sketch.) - Is
s16x16enough range for the pressure field, or does the Poisson solve needs32x16? The pressure values are the largest intermediate in the pipeline. - Do we want a vorticity-confinement term? Stefan's clips show a lot of small-scale swirl; confinement is the standard trick to keep it without raising the grid resolution. It is cheap (one extra pass) but adds a tuning parameter.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
zackees commentedon Nov 21, 2026
Criterion 6 (a reduced default grid for non-PSRAM parts) is in #5354: 48×32 (53.1 KiB) unless the board is wasm, host or PSRAM, plus a memory table per grid.
The rest needs a maintainer decision or hardware we don't have here, so I'm leaving it open:
src/fl/fx/2das anFx2d, or stay an example until a fixed-point tier is proven? This also blocks criteria 2 (divergence unit test) and 3 (fixed vs float tolerance).s16x16ors32x16?fix(examples): FluidSim defaults to 48x32 on non-PSRAM boards (FastLE…
StefanPetrick commentedon Nov 21, 2026
The link to the Stable Fluids paper seems broken. This one works: https://www.josstam.com/_files/ugd/cf1fd6_898fe9b63df946689101b8d074f8efba.pdf
All LED demos we showed are based on this C port from Jeff: https://github.com/4wheeljive/FastFluid/tree/main
It contains already some optimisations.
Realistically the whole thing would need a browser UI to unlock its full potential, there are just so many parameters to play with.
Also the gaussian splat injection is visually top notch, but expensive and maybe overkill.
Here is my latest prototype Python code: https://gist.github.com/StefanPetrick/0fda5997e3af3d369b0bfa78520af3a4
It shows different injection methods, styles & logics; color schemes; resolutions; and a handy color post-processing.
It might be useful to just play with it and get an intuition for the possibilities.
Don't be distracted by the swirl section - it is basically FlowFields on top of the fluidsim - meaning it adds a random velocity field to the calculated one in order to add some chaotic motion and make the whole thing look more alive and unpredictable but still very fluid like.
StefanPetrick commentedon Nov 21, 2026
Here a quick interactive demo of the different emitter logics: The capital letters (Mode A-H) correspond to the different emitter modes in the Python code.
FluidEmitter_Studio(1).html
StefanPetrick commentedon Nov 21, 2026
This are the optimisations we found already:
FastFluid — Optimizations over Stam's Stable Fluids
Based on the current C++ implementation:
Numerical optimizations
Independent iteration counts: 6 iterations for diffusion, 10 for pressure projection by default. Both are adjustable from 2 to 30 at runtime.
In-place Gauss–Seidel solver: Faster convergence per iteration than Jacobi, without an additional iteration buffer. (The code incorrectly labels it Jacobi.)
Approximate pressure projection: Fixed iteration budget instead of solving to full convergence.
Conditional diffusion: Skip diffusion entirely when its effective coefficient is negligible (≤ 10⁻⁸).
First-order backtracing: Simple Euler backtracing instead of Stam's RK2 or adaptive particle tracing.
Combined velocity advection: Shared backtrace and bilinear interpolation weights for both velocity components.
Combined RGB advection: Shared backtrace and interpolation weights for all three dye channels.
Conditional vorticity confinement: Skip curl computation and the additional pressure projection when disabled.
Simplified boundary conditions: Edge clamping and zero normal velocity.
Simplified obstacle handling: Local velocity clamping instead of an obstacle-aware pressure solver.
Memory and CPU optimizations
Static, contiguous, row-major float32 grids.
No additional ghost-cell padding.
Aggressive scratch-buffer reuse across simulation and rendering.
Precomputed reciprocals instead of repeated divisions.
Fused loops for velocity and dye dissipation.
Direct, localized force and dye injection.
Fast approximate power and lookup-table trigonometric functions.
Compiler optimizations (
-O3, fast math).Pressure solver specifically
Pressure projection runs twice per timestep, or three times with vorticity confinement enabled.
The key design decision is to spend computational effort where it matters most for visual quality, rather than pursuing numerical accuracy everywhere.
zackees commentedon Nov 22, 2026
Closing as delivered.
examples/FluidSimshipped in #5336, with smaller default grids for boards without PSRAM in #5354.The remaining asks moved to #5418:
src/fl/fx/2d;Thanks to Stefan for the working Stam paper link, the FastFluid C port and the list of optimisations. They're the starting point for #5418.