Skip to content

feat(fx): incompressible Navier-Stokes solver (fl::FluidSim) as a 2D effect #5337

Closed

Description

@zackees

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 velocity
  • d, d0 — density (the visible "ink")
  • p, div — pressure and divergence scratch

Per frame:

  1. diffuse velocity — Gauss–Seidel relaxation of (I − a∇²)
  2. project — compute divergence, solve the pressure Poisson equation, subtract ∇p
  3. advect velocity by itself — semi-Lagrangian backtrace with bilinear interpolation
  4. project again — the advected field is no longer divergence-free
  5. diffuse + advect density, 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) — float fields. This is the reference implementation and the one that should be validated against the paper first.
  • Fixed-point tier (FluidSimFP) — s16x16 (or s32x16) 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 way FlowField does.

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
  • s16x16 fixed-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 the addLeds chain, but the viewer logs screenMapsCount: 0 and 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

  1. FluidSimFloat reproduces the qualitative behaviour of Stam's reference: injected dye advects, shears into filaments, and forms vortices; no density blow-up over 10 000 frames.
  2. Velocity divergence after projection is below a documented epsilon on a synthetic test field (a unit test, not a screenshot).
  3. The fixed-point tier stays within a documented tolerance of the float tier on the same seed and inputs.
  4. 48×32 runs at ≥ 20 fps on an ESP32-S3 (measured, not estimated).
  5. The wasm example compiles and renders without browser-side errors via --test.
  6. 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-class Fx2d, or stay an example until the fixed-point tier is proven? (Proposal: land float as Fx2d, keep the example as the reference sketch.)
  • Is s16x16 enough range for the pressure field, or does the Poisson solve need s32x16? 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.

Activity

  1. added
    sanitized
    on Nov 21, 2026
  2. zackees commented on Nov 21, 2026

    @zackees
    MemberAuthor

    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:

    • Promotion: should the solver move into src/fl/fx/2d as an Fx2d, 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).
    • Pressure field: s16x16 or s32x16?
    • Vorticity confinement: add it or not?
    • Criterion 4: 48×32 at ≥20 fps needs an ESP32-S3 measurement, and no S3 is on this bench.
  3. StefanPetrick commented on Nov 21, 2026

    @StefanPetrick

    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.

  4. added
    sanitized
    and removed
    sanitized
    on Nov 21, 2026
  5. StefanPetrick commented on Nov 21, 2026

    @StefanPetrick

    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

  6. added
    sanitized
    and removed
    sanitized
    on Nov 21, 2026
  7. StefanPetrick commented on Nov 21, 2026

    @StefanPetrick

    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

    Operation | Default iterations -- | -- Velocity diffusion | 6 Dye diffusion | 6 Pressure projection | 10 Additional vorticity projection | 10

    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.

  8. added
    sanitized
    and removed
    sanitized
    on Nov 21, 2026
  9. zackees commented on Nov 22, 2026

    @zackees
    MemberAuthor

    Closing as delivered. examples/FluidSim shipped in #5336, with smaller default grids for boards without PSRAM in #5354.

    The remaining asks moved to #5418:

    • moving the solver into src/fl/fx/2d;
    • a fixed-point tier (s16x16 vs s32x16 pressure, and whether to add vorticity confinement);
    • a 48×32, at least 20 fps number on an ESP32-S3.

    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.

  10. moved this from Triage to Done in FastLED Trackeron Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    sanitized

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions