Algorithmcore
Stable fluids
Also called Stam stable fluids.
Advance a grid fluid by semi-Lagrangian advection, implicit diffusion and pressure projection. It is stable for any time step, but first order and dissipative, so stable is not accurate.
- Time
- Θ(g) advectO(g k) diffuse · project · step
- Space
- Θ(g) extra
- Where
- g = the number of grid cells; k = the number of conjugate gradient iterations of a solve
- Model
- Real RAM
- Properties
- not conservativedeterministicnot exactunconditionally stable
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jos Stam, 1999
Stable fluids is the grid fluid solver of Jos Stam (1999). Each time step adds the forces, moves the velocity along itself by semi-Lagrangian advection, diffuses it by an implicit step, and projects it onto the divergence-free fields. None of the four parts has a limit on the time step, so the solver does not blow up at any . That made interactive fluids possible and made the method the base of most grid solvers for smoke and fire in animation. The price is accuracy: the advection is first order and smooths the flow, so a stable step is not an accurate step.
In plain words
Each frame, the solver does four things to the velocity on a grid.
First it adds the pushes, such as gravity or a fan. Then it moves the flow along itself. For each grid point it asks where the fluid there came from, walks back along the flow, and reads the old value at that spot by mixing the four nearest grid values. A mix of old values can never be larger than the largest old value, so nothing can grow without limit, whatever the step size.
Next it spreads the velocity a little to model friction inside the fluid. It solves for the spread state at the end of the step, which also cannot grow.
Last it removes the part of the flow that would squeeze or stretch the fluid, so the fluid keeps its volume. Smoke and other quantities then ride along on the new flow.
The problem
Given a velocity field on a grid, a density , a viscosity , a force field and a time step , compute the velocity at the next step for the incompressible Navier-Stokes equations
and move the passive scalars (smoke density, temperature) by . The goal of fluid simulation for animation is plausible motion at the step that the frame rate or the artist sets, without a limit from the grid. The output must stay bounded and divergence free for any .
The algorithm
The step splits the equation into four parts and solves each part by a method that is stable on its own. The order is the one of Stam's paper: force, advect, diffuse, project. This page uses the MAC grid layout, with on the vertical faces, on the horizontal faces and and the scalars at the cell centers, as Fedkiw, Stam and Jensen (2001) did for smoke. Stam's 1999 paper stored all components at the cell centers and solved the projection with the fast Fourier transform on a periodic domain, or with a fast Poisson solver for fixed walls.
STABLE-FLUIDS-STEP(u, v, s, dt)- 1
add dt f(x) to the velocity at each face center x - 2
for each sample point x of u, v: x_b <- x - dt U(x - (dt/2) U(x)) ▷ RK2 backtrace - 3
new value at x <- bilinear sample of the old field at x_b, clamped to the grid - 4
for each of u and v: solve (I + alpha L) w = (advected field), alpha = nu dt / dx^2 - 5
set the normal velocity to 0 on each face with a SOLID side - 6
build A p = b on the FLUID cells, b = -(rho dx / dt) (net outflow of the cell) - 7
solve A p = b by conjugate gradients; on a closed region remove the mean of b, then of p - 8
on each open face: u <- u - dt / (rho dx) (pressure difference across the face) - 9
for each scalar s: advect by L2 and L3, diffuse with kappa by L4, then s <- s / (1 + dt a_s)
Forces (L1). This is one forward Euler step of . With a bounded force it adds at most to each face. Buoyancy and vorticity confinement enter here.
Advection (L2, L3). The term says that velocity is carried along by the flow. Along a path with , the value stays the same, which is the method of characteristics. So the new value at a sample point is the old value at the point that reaches it after . Line L2 finds that point by one midpoint step backward in time; line L3 reads the old field there by bilinear interpolation. Each component uses its own sample points and offsets. The old velocity moves itself: all backtraces use the field from before the advection. This is the semi-Lagrangian method: the grid stays fixed (Eulerian), and each value is found by a Lagrangian trace.
Diffusion (L4). This is one backward Euler step of the heat equation for each component, with the 5-point graph Laplacian of the array. The matrix is symmetric positive definite, and conjugate gradients solve it. Smoke usually uses and skips the step, because the advection already smooths more than the physical viscosity of air.
Projection (L5 to L8). Line L5 closes the walls. Lines L6 and L7 solve the pressure Poisson equation, and line L8 subtracts the pressure gradient, so every FLUID cell has zero net outflow. This is the Chorin projection, and the field that results is the divergence-free part of the Helmholtz-Hodge decomposition of the discrete field. The MAC grid page derives the matrix; the slug file writes it out again.
Scalars (L9). A scalar moves with the new velocity by the same advection, diffuses with the coefficient , and fades by , which is backward Euler for as in Stam's paper.
Example
One advection step by hand. Take a row of five cells with m, a constant velocity m/s and s, so the CFL number is . The scalar is . Positions below are in cell index units. The foot of cell is cells to the left, halfway between cells and , so the new value is :
| cell | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| before | 0 | 0 | 1 | 0 | 0 |
| foot of the backtrace | -1.5 (clamped to 0) | -0.5 (clamped to 0) | 0.5 | 1.5 | 2.5 |
| after | 0 | 0 | 0 | 0.5 | 0.5 |
The exact solution moves the spike to the position , between two cells. The grid cannot hold it there, so the spike splits into two halves. No value is larger than 1 and no value is negative, at any step size. The same mixing at every step is the numerical diffusion of the method.
One diffusion step by hand. Two cells with and . The system is , so . The sum stays 1, the values stay in , and the sum of squares drops from 1 to . As grows, tends to , never past it.
First order, measured. A Gaussian bump with m moves by m with m/s at the CFL number on grids of 8, 16 and 32 cells over 1 m. The largest errors are , and . The error halves when the grid spacing halves: the observed order between 16 and 32 cells is . The proof page gives the bound for 32 cells, where is the fractional part of the CFL number and bounds the second derivative.
A large step, measured. On a 16 by 16 box with m, a random divergence-free velocity from random.Random(11) (largest face speed m/s) and a square of smoke, ten steps with s, a CFL number of 5, run without trouble. After each step the largest divergence is below (it is at the end). The kinetic energy drops at every step, from J to J after one step and to J after ten, per unit depth with . The smoke stays in , but its total grows from 16 to 16.84, because semi-Lagrangian advection does not conserve mass. The run is stable and also very wrong: an inviscid fluid in a closed box keeps its energy.
Correctness
The claims are about the discrete step. They are proved in proofs/correctness.md.
- Advection. Each new value is a convex combination of four old values, for any velocity and any . A constant field stays the same, and the values stay between the old minimum and maximum.
- Diffusion. The backward Euler step keeps the sum of the array, keeps the values between the old minimum and maximum, and does not increase the sum of squares, for any .
- Projection. After lines L5 to L8, every FLUID cell has zero divergence, and the kinetic energy has not increased. The projection is orthogonal in the inner product .
- One step. With no force, the velocity after a step is bounded by a bound that depends on the old velocity and the number of faces, but not on or . Each scalar stays inside its old range times .
- Order. For a constant velocity and a smooth field, the advection error after a fixed time is at a fixed CFL number. The leading error is a diffusion term. Away from a whole number of cells per step, the method is first order in space and time.
The tests check the advection, the interpolation and the projection of the slug file against the shared helper macgrid.py on the same input. They also check diffusion against a dense solve and its sum, bound and energy properties, the measured order, and the bounded run at a CFL number of 5.
Proof: Each part of the stable fluids step is stable for any time step, and the advection is first orderfull
We use the MAC layout and the line numbers of the page. All statements are in exact arithmetic. A cell outside the grid is SOLID, and the walls are fixed. A face field is a value on each face, and is the largest . "Stable for any " means here that the output of a part is bounded by its input in a stated norm, with a bound that does not depend on , or .
Lemma 1 (advection, lines L2 and L3). For any velocity field, any and any field , each value of ADVECT is a convex combination of at most four values of . So a constant field stays the same, and at every sample point.
Proof. Line L2 gives some point , whatever the velocity and . Line L3 clamps the point to the box of the sample points and returns over four samples, with weights , , and , where . The weights are nonnegative and sum to 1. A convex combination of equal values is that value, and it lies between the least and the largest of its terms.
The lemma holds for and separately, so and do not increase in the advection of the velocity. It does not say that the sum of is kept: semi-Lagrangian advection is not conservative.
Lemma 2 (diffusion, line L4). Let be the graph Laplacian of the array, over the neighbors inside the array, and . Then is symmetric positive definite, and the solution of satisfies
- ,
- for all ,
- .
Proof. is symmetric, and over the neighbor pairs, so for . For claim 1, the column sums of are zero, so . For claim 2, let be an index with the largest . Then each term is , so , and . The lower bound follows in the same way at the smallest . For claim 3, the eigenvalues of are with an orthonormal eigenbasis, so the eigenvalues of are , and .
This is backward Euler on the heat equation with the 5-point Laplacian. The bounds hold for any , so the step size has no limit. As , tends to the mean of on each connected array, which is the correct limit of the heat equation and also shows how much a large step can smooth.
Lemma 3 (projection, lines L5 to L8). Let be the face field after line L5, so that on every face with a SOLID side. Let solve with and from line L6, and let be the field after line L8. Then has zero divergence on every FLUID cell, and .
Proof. Call a face open if no side is SOLID and at least one side is FLUID. For a cell field with on AIR cells, let on open faces, between the cells of larger and smaller index, and on the other faces. Let be the net outflow of cell divided by . Line L8 is .
Zero divergence. For a FLUID cell , each face is open or has a SOLID side. On an open face toward the neighbor , the outward flux of is , with for an AIR cell. So , which is how line L6 counts the diagonal and the off-diagonal entries. Line L6 sets . Then .
The system is solvable. is symmetric positive semidefinite, and its null space is spanned by the indicators of the connected FLUID regions with no AIR neighbor (the proof is on the MAC grid page). On such a closed region, the sum of is the net flow through its solid faces, which is zero after line L5, so is orthogonal to the null space. Line L7 removes the mean of on each closed region, which changes nothing in exact arithmetic, and the mean of , which picks one of the solutions.
Energy. Let be a face field with on every face with a SOLID side, and . Write and give each term to its cell. The terms of an AIR cell are zero, and the faces of a FLUID cell that are not open carry , so . With , the right side is zero, so and are orthogonal, and .
Lemma 4 (dissipation of a scalar, line L9). For and , is backward Euler for , and the factor is in .
Proof. Backward Euler gives , so , and .
Theorem 1 (stability of one step). With no force, for any , , and :
- Each value of a scalar field after the step lies in , where is the field before the step and .
- The velocity after the step has zero divergence on the FLUID cells, and , where is the number of faces.
Proof. Claim 1 follows from Lemma 1, Lemma 2 (claim 2) and Lemma 4, applied in this order. For claim 2, Lemma 1 bounds each component after advection by its old maximum, Lemma 2 does not increase the maximum, so after line L4 . Line L5 only sets values to zero, and Lemma 3 does not increase and gives zero divergence.
The bound in claim 2 does not depend on or . That is the sense of "stable for any time step" in Stam's paper: advection takes values only from inside the old field, and the other parts are implicit or are projections. We do not claim that the velocity stays bounded uniformly over many steps with a constant independent of . Lemma 1 bounds the advection in the maximum norm and Lemma 3 bounds the projection in the energy norm, and the two norms differ by up to the factor . The test file measures the energy over ten steps at a CFL number of 5 and finds that it decreases at every step.
Theorem 2 (first order advection). On an infinite or periodic 1D grid of spacing , let the velocity be a constant , let with an integer and , and let be a smooth function with . After steps of lines L2 and L3, with , the error at every sample point is at most
At a fixed CFL number with , the error is : the method is first order.
Proof. With a constant velocity, both stages of the RK2 backtrace use , so line L2 is exact: the foot of sample is , at the distance from and from . Line L3 is linear interpolation between these two samples. For a smooth , the error of linear interpolation at a point between two nodes at distances and is at most ; here . Let be the error at step against the exact solution , which has the same bound on its second derivative. One step gives , where is the interpolation and . is a convex combination, so , and . With this is the bound.
The leading term of the local error is , a diffusion term. So on a bump the bound is close to the actual error: the method smooths with an effective viscosity . For the step moves the field by whole cells and is exact. The test file moves a Gaussian bump with () by at . For the bound is , and the measured error is . The order between and is 1.00.
The theorem is for the interior of the domain. At an inflow border, line L3 clamps the foot to the last sample, which is a first order boundary condition.
Complexity
Let be the number of cells. Lines L1 to L3, L5, L8 and the scalar advection cost : each face or cell does a constant amount of work, and the backtrace and the sample cost each. The extra space is for the new fields and the solver vectors.
The linear solves dominate. A conjugate gradient iteration costs on a 5-point matrix, so each solve costs . For the pressure on an by grid, for a fixed reduction of the error, because the condition number of grows as ; multigrid brings the solve to . For the diffusion, the condition number of is at most , so the solve is cheap when is small and approaches the cost of a Poisson solve when is large. Stam's periodic version replaces both solves by FFTs, which cost .
Properties
- No step limit. The CFL condition does not limit , because the backtrace may cross many cells. Large steps lose accuracy, not stability. Many solvers still keep the CFL number at a few cells per step, as a rule of thumb for accuracy.
- Dissipative. Linear interpolation smooths the field at every step, with an effective viscosity of order . Smoke loses its small swirls, and the total kinetic energy decays even with . Vorticity confinement, BFECC and the unconditionally stable MacCormack method are the usual repairs.
- Not conservative. The sum of an advected scalar is not kept. Smoke mass and liquid volume drift over time.
- First order. The splitting is first order in time, and the advection is first order at a fixed CFL number.
- Simple and robust. Every part is either a convex combination or a symmetric positive (semi)definite solve.
Variants and improvements
- Collocated grid with FFT. Stam's original form, with all components at the cell centers and the diffusion and the projection done in Fourier space on a periodic domain, where both are diagonal.
- A version for games. Stam later published a short version for games (2003) that relaxes the linear systems with a fixed number of Gauss-Seidel sweeps. It is cheaper and less accurate than a converged solve.
- Staggered grid. The MAC layout of this page (Fedkiw, Stam and Jensen 2001), which avoids the checkerboard modes of the collocated projection.
- Less dissipation. Higher order interpolation (monotone cubic), BFECC, the unconditionally stable MacCormack method, and particle methods such as FLIP and APIC that do not interpolate the velocity at every step.
- Liquids. Add a free surface tracked by a level set or particles, AIR cells with and the ghost fluid method at the surface.
- Better splitting. Advection-reflection methods reflect the velocity at the half step instead of only projecting it. They lose less energy, at the cost of a second projection.
When to use it
Use stable fluids for smoke, fire, dust and other gases in animation and games, where the step is set by the frame rate and the look matters more than the accuracy. It is also the base for liquid solvers and the grid stage of particle-grid hybrids. It is easy to write, easy to run on a GPU, and robust.
Do not use it where accuracy matters: in engineering flow, for drag or heat transfer, or where mass must be conserved. Use a conservative finite volume method with a step inside the CFL limit there. For thin liquid sheets, splashes and small features, the numerical diffusion is too strong; use particles.
Pitfalls
- Stable is not accurate. A step at a CFL number of 5 runs, but it can lose most of the kinetic energy in a few steps, as the measured run shows. Pick for accuracy, not only for stability.
- Advecting in place. The backtraces must use the velocity from before the step. Writing the new values into the same arrays during the sweep mixes old and new values.
- Half-cell offsets. On a MAC grid, , and the scalars have different sample points. Trace from the sample point of each component and sample with its offsets.
- Boundaries. A backtrace that leaves the domain must read a boundary value. Clamping returns the nearest sample, which is right for a wall and wrong for an inflow with a given value.
- The order of the steps. Advect with a divergence-free field. A force added after the projection is not projected and adds divergence to the next advection.
- Diffusing walls. The diffusion of this page treats the border of each array with a zero normal derivative. A no-slip wall needs zero velocity at the wall in the diffusion step, not only in the projection.
- The singular pressure system. A closed box has a free constant in . Remove the mean of before conjugate gradients, or the solve stalls.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""A 2D MAC grid with sampling, divergence, pressure projection and advection.
This file is copied byte for byte into each impl/python folder that needs it.
Do not edit a copy. The reference is in
graphics-and-signals/fluid-animation/mac-grid/impl/python/.
Layout (the MAC layout of Harlow and Welch 1965, as in Bridson 2015):
- The grid has nx by ny cells of size dx. i is the x index, j is the y index.
- p[i][j] is at ((i + 1/2) dx, (j + 1/2) dx), for i < nx and j < ny.
- u[i][j] is at (i dx, (j + 1/2) dx), for i = 0..nx and j < ny.
- v[i][j] is at ((i + 1/2) dx, j dx), for i < nx and j = 0..ny.
- label[i][j] is FLUID, SOLID or AIR. A cell outside the grid counts as
SOLID, so the border of the grid is a fixed wall.
Units are SI. In 2D a density rho is in kg/m^2 if you read the grid as a
sheet, or in kg/m^3 per unit depth; the code does not care.
"""
import math
from collections import deque
FLUID, SOLID, AIR = 0, 1, 2
class Grid:
"""The arrays of a MAC grid. All arrays are lists of lists indexed [i][j]."""
def __init__(self, nx, ny, dx):
if nx < 1 or ny < 1 or dx <= 0:
raise ValueError("need nx >= 1, ny >= 1 and dx > 0")
self.nx = nx
self.ny = ny
self.dx = float(dx)
self.p = zeros(nx, ny)
self.u = zeros(nx + 1, ny)
self.v = zeros(nx, ny + 1)
self.label = [[FLUID] * ny for _ in range(nx)]
def make_grid(nx, ny, dx):
"""A grid of nx by ny FLUID cells of size dx, with p, u and v set to zero."""
return Grid(nx, ny, dx)
def zeros(a, b):
"""An a by b list of lists of 0.0."""
return [[0.0] * b for _ in range(a)]
def copy_field(q):
"""A deep copy of a 2D field."""
return [list(col) for col in q]
def cell_label(g, i, j):
"""The label of cell (i, j). A cell outside the grid is SOLID."""
if 0 <= i < g.nx and 0 <= j < g.ny:
return g.label[i][j]
return SOLID
def cell_center(g, i, j):
"""The position ((i + 1/2) dx, (j + 1/2) dx) of the center of cell (i, j)."""
return ((i + 0.5) * g.dx, (j + 0.5) * g.dx)
def sample(q, x, y, dx, ox, oy):
"""Bilinear sample at (x, y) of a field whose value q[a][b] is at ((a + ox) dx, (b + oy) dx).
A point outside the sample positions is clamped to the nearest one, so the
result is always a convex combination of at most four values of q.
"""
na, nb = len(q), len(q[0])
fx = x / dx - ox
fy = y / dx - oy
fx = min(max(fx, 0.0), float(na - 1))
fy = min(max(fy, 0.0), float(nb - 1))
a0 = min(int(math.floor(fx)), na - 2) if na > 1 else 0
b0 = min(int(math.floor(fy)), nb - 2) if nb > 1 else 0
a1 = a0 + 1 if na > 1 else a0
b1 = b0 + 1 if nb > 1 else b0
s = fx - a0
t = fy - b0
return ((1.0 - s) * ((1.0 - t) * q[a0][b0] + t * q[a0][b1])
+ s * ((1.0 - t) * q[a1][b0] + t * q[a1][b1]))
def u_at(g, x, y):
"""The x velocity at (x, y), by bilinear sampling of u."""
return sample(g.u, x, y, g.dx, 0.0, 0.5)
def v_at(g, x, y):
"""The y velocity at (x, y), by bilinear sampling of v."""
return sample(g.v, x, y, g.dx, 0.5, 0.0)
def vel_at(g, x, y):
"""The velocity (u, v) at (x, y)."""
return (u_at(g, x, y), v_at(g, x, y))
def center_at(g, q, x, y):
"""Bilinear sample at (x, y) of a cell centered field q (same layout as p)."""
return sample(q, x, y, g.dx, 0.5, 0.5)
def divergence(g):
"""The discrete divergence (u[i+1][j] - u[i][j] + v[i][j+1] - v[i][j]) / dx of every cell."""
d = zeros(g.nx, g.ny)
for i in range(g.nx):
ui, ui1 = g.u[i], g.u[i + 1]
vi = g.v[i]
for j in range(g.ny):
d[i][j] = (ui1[j] - ui[j] + vi[j + 1] - vi[j]) / g.dx
return d
def max_fluid_divergence(g):
"""The largest |divergence| over the FLUID cells (0.0 if there is none)."""
d = divergence(g)
m = 0.0
for i in range(g.nx):
for j in range(g.ny):
if g.label[i][j] == FLUID:
m = max(m, abs(d[i][j]))
return m
def is_solid_u_face(g, i, j):
"""True if the u face (i, j), between cells (i - 1, j) and (i, j), touches a SOLID cell."""
return cell_label(g, i - 1, j) == SOLID or cell_label(g, i, j) == SOLID
def is_solid_v_face(g, i, j):
"""True if the v face (i, j), between cells (i, j - 1) and (i, j), touches a SOLID cell."""
return cell_label(g, i, j - 1) == SOLID or cell_label(g, i, j) == SOLID
def set_solid_boundaries(g, solid_velocity=None):
"""Set the normal velocity on every face that touches a SOLID cell.
A face on the border of the grid is a fixed wall and gets 0. A face inside
the grid that touches a SOLID cell gets the normal component of
solid_velocity(x, y) at the face center, or 0 if solid_velocity is None.
"""
dx = g.dx
for i in range(g.nx + 1):
for j in range(g.ny):
if is_solid_u_face(g, i, j):
if i == 0 or i == g.nx or solid_velocity is None:
g.u[i][j] = 0.0
else:
g.u[i][j] = float(solid_velocity(i * dx, (j + 0.5) * dx)[0])
for i in range(g.nx):
for j in range(g.ny + 1):
if is_solid_v_face(g, i, j):
if j == 0 or j == g.ny or solid_velocity is None:
g.v[i][j] = 0.0
else:
g.v[i][j] = float(solid_velocity((i + 0.5) * dx, j * dx)[1])
def _fluid_system(g, dt, rho):
"""Index the FLUID cells and build the 5-point Laplacian and the right side.
Returns (cells, diag, nbrs, b, has_air) where cells[k] = (i, j), diag[k] is
the number of neighbors that are not SOLID, nbrs[k] lists the indices of the
FLUID neighbors, and b[k] = -(rho dx / dt) (u[i+1][j] - u[i][j] + v[i][j+1] - v[i][j]).
has_air[k] is True if the cell has an AIR neighbor.
"""
idx = {}
cells = []
for i in range(g.nx):
for j in range(g.ny):
if g.label[i][j] == FLUID:
idx[(i, j)] = len(cells)
cells.append((i, j))
diag, nbrs, b, has_air = [], [], [], []
scale = -rho * g.dx / dt
for (i, j) in cells:
dcount = 0
nb = []
air = False
for (a, c) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
lab = cell_label(g, a, c)
if lab == SOLID:
continue
dcount += 1
if lab == FLUID:
nb.append(idx[(a, c)])
else:
air = True
diag.append(dcount)
nbrs.append(nb)
has_air.append(air)
b.append(scale * (g.u[i + 1][j] - g.u[i][j] + g.v[i][j + 1] - g.v[i][j]))
return cells, diag, nbrs, b, has_air
def _components(nbrs):
"""The connected components of the FLUID cells, as lists of indices."""
n = len(nbrs)
comp = [-1] * n
out = []
for s in range(n):
if comp[s] >= 0:
continue
comp[s] = len(out)
members = [s]
queue = deque([s])
while queue:
k = queue.popleft()
for m in nbrs[k]:
if comp[m] < 0:
comp[m] = comp[s]
members.append(m)
queue.append(m)
out.append(members)
return out
def _apply(diag, nbrs, x):
return [diag[k] * x[k] - sum(x[m] for m in nbrs[k]) for k in range(len(x))]
def pressure_solve(g, dt, rho, tol=1e-12, max_iter=None):
"""Solve the pressure Poisson equation by conjugate gradients and store p in g.p.
The system is A p = b on the FLUID cells, with the 5-point Laplacian A
(Neumann at SOLID faces, p = 0 in AIR cells) and
b = -(rho dx^2 / dt) times the divergence. A connected group of FLUID cells
with no AIR neighbor has a singular block: the mean of b is removed on it
before the solve (the compatibility condition) and the mean of p is removed
after it. CG stops when max |r| <= tol * max |b|. Returns the number of
iterations. p is 0 in SOLID and AIR cells.
"""
cells, diag, nbrs, b, has_air = _fluid_system(g, dt, rho)
n = len(cells)
g.p = zeros(g.nx, g.ny)
if n == 0:
return 0
closed = [c for c in _components(nbrs) if not any(has_air[k] for k in c)]
for c in closed:
mean = sum(b[k] for k in c) / len(c)
for k in c:
b[k] -= mean
bmax = max(abs(t) for t in b)
x = [0.0] * n
it = 0
if bmax > 0.0:
if max_iter is None:
max_iter = max(100, 4 * n)
r = list(b)
d = list(r)
rr = sum(t * t for t in r)
while it < max_iter and max(abs(t) for t in r) > tol * bmax:
q = _apply(diag, nbrs, d)
dq = sum(d[k] * q[k] for k in range(n))
if dq <= 0.0:
break
alpha = rr / dq
for k in range(n):
x[k] += alpha * d[k]
r[k] -= alpha * q[k]
rr_new = sum(t * t for t in r)
beta = rr_new / rr
rr = rr_new
for k in range(n):
d[k] = r[k] + beta * d[k]
it += 1
for c in closed:
mean = sum(x[k] for k in c) / len(c)
for k in c:
x[k] -= mean
for k, (i, j) in enumerate(cells):
g.p[i][j] = x[k]
return it
def subtract_pressure_gradient(g, dt, rho):
"""u[i][j] -= dt / (rho dx) (p[i][j] - p[i-1][j]), and the same for v.
Only faces with a FLUID cell on at least one side and no SOLID cell are
changed. The pressure of an AIR cell is 0.
"""
s = dt / (rho * g.dx)
for i in range(1, g.nx):
for j in range(g.ny):
a, c = g.label[i - 1][j], g.label[i][j]
if a == SOLID or c == SOLID or (a != FLUID and c != FLUID):
continue
g.u[i][j] -= s * (g.p[i][j] - g.p[i - 1][j])
for i in range(g.nx):
for j in range(1, g.ny):
a, c = g.label[i][j - 1], g.label[i][j]
if a == SOLID or c == SOLID or (a != FLUID and c != FLUID):
continue
g.v[i][j] -= s * (g.p[i][j] - g.p[i][j - 1])
def project(g, dt, rho, tol=1e-12, solid_velocity=None):
"""Make the velocity divergence free in the FLUID cells. Returns the CG iteration count."""
set_solid_boundaries(g, solid_velocity)
it = pressure_solve(g, dt, rho, tol)
subtract_pressure_gradient(g, dt, rho)
return it
def backtrace(g, x, y, dt):
"""The start point of the path that ends at (x, y) after time dt, by an RK2 (midpoint) step.
A negative dt traces forward in time.
"""
u1, v1 = vel_at(g, x, y)
xm, ym = x - 0.5 * dt * u1, y - 0.5 * dt * v1
u2, v2 = vel_at(g, xm, ym)
return (x - dt * u2, y - dt * v2)
def advect(g, q, dt, ox=0.5, oy=0.5):
"""Semi-Lagrangian advection of the field q by the velocity of g, for time dt.
q[a][b] is at ((a + ox) dx, (b + oy) dx): the default is a cell centered
field; use (0, 0.5) for u and (0.5, 0) for v. Each new value is the bilinear
sample of q at the RK2 backtrace of its sample point. Returns a new field.
"""
dx = g.dx
out = zeros(len(q), len(q[0]))
for a in range(len(q)):
for b in range(len(q[0])):
xb, yb = backtrace(g, (a + ox) * dx, (b + oy) * dx, dt)
out[a][b] = sample(q, xb, yb, dx, ox, oy)
return out
def advect_velocity(g, dt):
"""Advect u and v by the velocity of g. Returns (new_u, new_v); g is not changed."""
return advect(g, g.u, dt, 0.0, 0.5), advect(g, g.v, dt, 0.5, 0.0)
def kinetic_energy(g, rho):
"""(1/2) rho dx^2 times the sum of u^2 and v^2 over all faces (per unit depth in 2D)."""
s = sum(t * t for col in g.u for t in col) + sum(t * t for col in g.v for t in col)
return 0.5 * rho * g.dx * g.dx * s
stable_fluids.py 300 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stable-fluids/. The authors are listed in prov/4DDRB0.jsonl.
"""Stable fluids (Stam 1999) on a 2D MAC grid.
One step adds the forces, advects by the semi-Lagrangian method, diffuses by
backward Euler and projects the velocity onto the divergence-free fields. All
four parts are written out here. The grid object and its layout come from the
shared helper macgrid.py: p[i][j] at ((i + 1/2) dx, (j + 1/2) dx), u[i][j] at
(i dx, (j + 1/2) dx) and v[i][j] at ((i + 1/2) dx, j dx). Stam used a cell
centered grid; this file uses the MAC layout of Fedkiw, Stam and Jensen 2001.
Each part is stable for any time step. The step is first order in time and
dissipative, so a large step is stable but not accurate.
"""
import math
from collections import deque
from macgrid import FLUID, SOLID
def label_at(g, i, j):
"""The label of cell (i, j); a cell outside the grid is SOLID."""
if 0 <= i < g.nx and 0 <= j < g.ny:
return g.label[i][j]
return SOLID
# ---- forces ----
def add_force(g, dt, force):
"""u <- u + dt f_x and v <- v + dt f_y at each face center; force(x, y) returns (f_x, f_y) in m/s^2."""
dx = g.dx
for i in range(g.nx + 1):
for j in range(g.ny):
g.u[i][j] += dt * force(i * dx, (j + 0.5) * dx)[0] # @line L1
for i in range(g.nx):
for j in range(g.ny + 1):
g.v[i][j] += dt * force((i + 0.5) * dx, j * dx)[1]
# ---- advection ----
def interp(q, x, y, dx, ox, oy):
"""Bilinear interpolation at (x, y) of q, where q[a][b] is at ((a + ox) dx, (b + oy) dx).
A point outside the box of the sample points is clamped to it.
"""
na, nb = len(q), len(q[0])
fx = min(max(x / dx - ox, 0.0), float(na - 1))
fy = min(max(y / dx - oy, 0.0), float(nb - 1))
a0 = min(int(math.floor(fx)), na - 2) if na > 1 else 0
b0 = min(int(math.floor(fy)), nb - 2) if nb > 1 else 0
a1 = a0 + 1 if na > 1 else a0
b1 = b0 + 1 if nb > 1 else b0
s = fx - a0
t = fy - b0
return ((1.0 - s) * ((1.0 - t) * q[a0][b0] + t * q[a0][b1]) # @line L3
+ s * ((1.0 - t) * q[a1][b0] + t * q[a1][b1]))
def velocity(g, x, y):
"""The velocity (u, v) at (x, y), from the face values of g."""
return (interp(g.u, x, y, g.dx, 0.0, 0.5), interp(g.v, x, y, g.dx, 0.5, 0.0))
def trace_back(g, x, y, dt):
"""The point that reaches (x, y) after time dt along the velocity of g, by one midpoint (RK2) step."""
u1, v1 = velocity(g, x, y)
u2, v2 = velocity(g, x - 0.5 * dt * u1, y - 0.5 * dt * v1)
return (x - dt * u2, y - dt * v2) # @line L2
def advect(g, q, dt, ox=0.5, oy=0.5):
"""Semi-Lagrangian advection of q, whose samples have offsets (ox, oy), by the velocity of g.
Returns a new field. Each new value is the old field interpolated at the
backtrace of its own sample point, so it lies between the smallest and the
largest of the four old values used.
"""
dx = g.dx
out = [[0.0] * len(q[0]) for _ in range(len(q))]
for a in range(len(q)):
for b in range(len(q[0])):
xb, yb = trace_back(g, (a + ox) * dx, (b + oy) * dx, dt)
out[a][b] = interp(q, xb, yb, dx, ox, oy)
return out
def advect_velocity(g, dt):
"""Advect u and v by the velocity of g (the old velocity moves itself). Returns (u, v)."""
return advect(g, g.u, dt, 0.0, 0.5), advect(g, g.v, dt, 0.5, 0.0)
# ---- conjugate gradients ----
def cg(apply, b, tol=1e-12, max_iter=None):
"""Solve M x = b for a symmetric positive (semi)definite M given as apply(x) = M x.
Starts from x = 0 and stops when max |r| <= tol * max |b|. Returns (x, iterations).
"""
n = len(b)
x = [0.0] * n
bmax = max((abs(t) for t in b), default=0.0)
if bmax == 0.0:
return x, 0
if max_iter is None:
max_iter = max(100, 4 * n)
r = list(b)
d = list(r)
rr = sum(t * t for t in r)
it = 0
while it < max_iter and max(abs(t) for t in r) > tol * bmax:
q = apply(d)
dq = sum(d[k] * q[k] for k in range(n))
if dq <= 0.0:
break
alpha = rr / dq
for k in range(n):
x[k] += alpha * d[k]
r[k] -= alpha * q[k]
rr_new = sum(t * t for t in r)
beta = rr_new / rr
rr = rr_new
for k in range(n):
d[k] = r[k] + beta * d[k]
it += 1
return x, it
# ---- diffusion ----
def diffuse(q, alpha, tol=1e-12):
"""One backward Euler step of the heat equation on the array q: solve (I + alpha L) w = q.
L is the graph Laplacian of the array (5 points, a missing neighbor at the
border of the array is left out, which is a zero normal derivative), and
alpha = nu dt / dx^2. Returns (w, iterations).
"""
na, nb = len(q), len(q[0])
if alpha == 0.0:
return [list(col) for col in q], 0
nbrs = []
for a in range(na):
for b in range(nb):
nbrs.append([a2 * nb + b2 for (a2, b2) in ((a - 1, b), (a + 1, b), (a, b - 1), (a, b + 1))
if 0 <= a2 < na and 0 <= b2 < nb])
def apply(x):
return [x[k] + alpha * (len(nbrs[k]) * x[k] - sum(x[m] for m in nbrs[k])) for k in range(len(x))]
flat = [q[a][b] for a in range(na) for b in range(nb)]
w, it = cg(apply, flat, tol) # @line L4
return [[w[a * nb + b] for b in range(nb)] for a in range(na)], it
# ---- projection ----
def set_walls(g):
"""Set the normal velocity to zero on every face with a SOLID cell on one side (fixed walls)."""
for i in range(g.nx + 1):
for j in range(g.ny):
if label_at(g, i - 1, j) == SOLID or label_at(g, i, j) == SOLID:
g.u[i][j] = 0.0 # @line L5
for i in range(g.nx):
for j in range(g.ny + 1):
if label_at(g, i, j - 1) == SOLID or label_at(g, i, j) == SOLID:
g.v[i][j] = 0.0
def pressure_system(g, dt, rho):
"""The pressure equations A p = b over the FLUID cells.
Returns (cells, diag, nbrs, b, open_cell). Row k has diag[k] = the number of
neighbors that are not SOLID and -1 for each FLUID neighbor in nbrs[k];
b[k] = -(rho dx / dt) times the net outflow of the cell. open_cell[k] is True
if the cell has an AIR neighbor, where p = 0.
"""
index = {}
cells = []
for i in range(g.nx):
for j in range(g.ny):
if g.label[i][j] == FLUID:
index[(i, j)] = len(cells)
cells.append((i, j))
diag, nbrs, b, open_cell = [], [], [], []
for (i, j) in cells:
count, nb, air = 0, [], False
for (a, c) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
lab = label_at(g, a, c)
if lab == SOLID:
continue
count += 1 # @line L6
if lab == FLUID:
nb.append(index[(a, c)])
else:
air = True
diag.append(count)
nbrs.append(nb)
open_cell.append(air)
b.append(-rho * g.dx / dt * (g.u[i + 1][j] - g.u[i][j] + g.v[i][j + 1] - g.v[i][j]))
return cells, diag, nbrs, b, open_cell
def closed_regions(nbrs, open_cell):
"""The connected groups of FLUID cells with no AIR neighbor, as lists of row indices."""
n = len(nbrs)
seen = [False] * n
out = []
for s in range(n):
if seen[s]:
continue
seen[s] = True
group, queue = [s], deque([s])
while queue:
k = queue.popleft()
for m in nbrs[k]:
if not seen[m]:
seen[m] = True
group.append(m)
queue.append(m)
if not any(open_cell[k] for k in group):
out.append(group)
return out
def solve_pressure(g, dt, rho, tol=1e-12):
"""Solve A p = b by conjugate gradients and store p in g.p (0 outside the FLUID cells). Returns the iterations."""
cells, diag, nbrs, b, open_cell = pressure_system(g, dt, rho)
g.p = [[0.0] * g.ny for _ in range(g.nx)]
if not cells:
return 0
closed = closed_regions(nbrs, open_cell)
for group in closed:
mean = sum(b[k] for k in group) / len(group)
for k in group:
b[k] -= mean
def apply(x):
return [diag[k] * x[k] - sum(x[m] for m in nbrs[k]) for k in range(len(x))]
x, it = cg(apply, b, tol) # @line L7
for group in closed:
mean = sum(x[k] for k in group) / len(group)
for k in group:
x[k] -= mean
for k, (i, j) in enumerate(cells):
g.p[i][j] = x[k]
return it
def subtract_gradient(g, dt, rho):
"""u -= dt / (rho dx) times the pressure difference on each face with no SOLID side and a FLUID side."""
s = dt / (rho * g.dx)
for i in range(1, g.nx):
for j in range(g.ny):
a, c = g.label[i - 1][j], g.label[i][j]
if a != SOLID and c != SOLID and (a == FLUID or c == FLUID):
g.u[i][j] -= s * (g.p[i][j] - g.p[i - 1][j]) # @line L8
for i in range(g.nx):
for j in range(1, g.ny):
a, c = g.label[i][j - 1], g.label[i][j]
if a != SOLID and c != SOLID and (a == FLUID or c == FLUID):
g.v[i][j] -= s * (g.p[i][j] - g.p[i][j - 1])
def project(g, dt, rho, tol=1e-12):
"""Make the velocity of g divergence free on the FLUID cells. Returns the CG iterations."""
set_walls(g)
it = solve_pressure(g, dt, rho, tol)
subtract_gradient(g, dt, rho)
return it
# ---- one step ----
def step(g, dt, rho, nu=0.0, force=None, scalars=(), kappa=0.0, decay=0.0):
"""One stable fluids step of length dt. Changes g and returns the new scalar fields as a list.
nu is the kinematic viscosity (m^2/s), kappa the diffusion coefficient of
the scalars and decay the rate a_s (1/s) of their dissipation. The scalars
are cell centered and move with the new velocity.
"""
if force is not None:
add_force(g, dt, force)
g.u, g.v = advect_velocity(g, dt)
if nu > 0.0:
alpha = nu * dt / (g.dx * g.dx)
g.u = diffuse(g.u, alpha)[0]
g.v = diffuse(g.v, alpha)[0]
project(g, dt, rho)
out = []
for s in scalars:
s = advect(g, s, dt)
if kappa > 0.0:
s = diffuse(s, kappa * dt / (g.dx * g.dx))[0]
f = 1.0 / (1.0 + dt * decay)
out.append([[f * t for t in col] for col in s]) # @line L9
return out
test_stable_fluids.py 202 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stable-fluids/. The authors are listed in prov/4DDRB0.jsonl.
"""Tests of the stable fluids step and of its parts against the shared helper."""
import math
import random
import macgrid
from macgrid import AIR, SOLID
import stable_fluids as sf
def random_grid(nx, ny, dx, seed):
rng = random.Random(seed)
g = macgrid.make_grid(nx, ny, dx)
for col in g.u:
for j in range(ny):
col[j] = rng.uniform(-1.0, 1.0)
for col in g.v:
for j in range(ny + 1):
col[j] = rng.uniform(-1.0, 1.0)
return g, rng
def copy_grid(g):
h = macgrid.make_grid(g.nx, g.ny, g.dx)
h.u = macgrid.copy_field(g.u)
h.v = macgrid.copy_field(g.v)
h.label = [list(col) for col in g.label]
return h
def dense_solve(a, b):
n = len(b)
m = [list(row) + [b[k]] for k, row in enumerate(a)]
for c in range(n):
piv = max(range(c, n), key=lambda r: abs(m[r][c]))
m[c], m[piv] = m[piv], m[c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
m[r] = [x - f * y for x, y in zip(m[r], m[c])]
x = [0.0] * n
for c in range(n - 1, -1, -1):
x[c] = (m[c][n] - sum(m[c][k] * x[k] for k in range(c + 1, n))) / m[c][c]
return x
def max_abs(*fields):
return max(abs(t) for q in fields for col in q for t in col)
# ---- the parts against the helper ----
def test_interp_and_advect_match_helper():
g, rng = random_grid(10, 8, 0.125, 1)
macgrid.project(g, 0.1, 1.0)
for _ in range(200):
x, y = rng.uniform(-0.2, 1.4), rng.uniform(-0.2, 1.2)
assert abs(sf.velocity(g, x, y)[0] - macgrid.u_at(g, x, y)) < 1e-14
assert abs(sf.velocity(g, x, y)[1] - macgrid.v_at(g, x, y)) < 1e-14
assert sf.trace_back(g, x, y, 0.3) == macgrid.backtrace(g, x, y, 0.3)
q = [[rng.uniform(0.0, 2.0) for _ in range(8)] for _ in range(10)]
a1, a2 = sf.advect(g, q, 0.4), macgrid.advect(g, q, 0.4)
assert max(abs(a1[i][j] - a2[i][j]) for i in range(10) for j in range(8)) < 1e-14
u1, v1 = sf.advect_velocity(g, 0.4)
u2, v2 = macgrid.advect_velocity(g, 0.4)
assert u1 == u2 and v1 == v2
def test_project_matches_helper_with_air_and_solid():
g, _ = random_grid(12, 10, 0.1, 2)
for i in range(12):
for j in range(7, 10):
g.label[i][j] = AIR
g.label[5][3] = SOLID
g.label[6][3] = SOLID
h = copy_grid(g)
sf.project(g, 0.05, 1000.0)
macgrid.project(h, 0.05, 1000.0)
pmax = max_abs(h.p)
assert max(abs(g.p[i][j] - h.p[i][j]) for i in range(12) for j in range(10)) < 1e-9 * pmax
assert max(abs(g.u[i][j] - h.u[i][j]) for i in range(13) for j in range(10)) < 1e-9
assert max(abs(g.v[i][j] - h.v[i][j]) for i in range(12) for j in range(11)) < 1e-9
assert macgrid.max_fluid_divergence(g) < 1e-8
def test_project_closed_box_32():
g, _ = random_grid(32, 32, 1.0 / 32.0, 3)
sf.set_walls(g)
e0 = macgrid.kinetic_energy(g, 1000.0)
it = sf.project(g, 1.0 / 60.0, 1000.0)
assert it > 0
assert macgrid.max_fluid_divergence(g) < 1e-8
assert macgrid.kinetic_energy(g, 1000.0) <= e0
assert abs(sum(map(sum, g.p))) < 1e-9 * 1024 * max_abs(g.p)
# ---- diffusion ----
def test_diffuse_matches_dense_solve_and_keeps_sum_and_bounds():
rng = random.Random(4)
na, nb, alpha = 5, 4, 2.5
q = [[rng.uniform(-1.0, 3.0) for _ in range(nb)] for _ in range(na)]
w, it = sf.diffuse(q, alpha)
assert it > 0
n = na * nb
a = [[0.0] * n for _ in range(n)]
for i in range(na):
for j in range(nb):
k = i * nb + j
a[k][k] = 1.0
for (i2, j2) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
if 0 <= i2 < na and 0 <= j2 < nb:
a[k][k] += alpha
a[k][i2 * nb + j2] -= alpha
x = dense_solve(a, [q[i][j] for i in range(na) for j in range(nb)])
assert max(abs(w[i][j] - x[i * nb + j]) for i in range(na) for j in range(nb)) < 1e-10
assert abs(sum(map(sum, w)) - sum(map(sum, q))) < 1e-10
lo, hi = min(map(min, q)), max(map(max, q))
assert all(lo - 1e-12 <= t <= hi + 1e-12 for col in w for t in col)
assert sum(t * t for col in w for t in col) <= sum(t * t for col in q for t in col)
def test_diffuse_large_step_is_bounded_and_flattens():
q = [[1.0 if (i + j) % 2 == 0 else 0.0 for j in range(8)] for i in range(8)]
w, _ = sf.diffuse(q, 1000.0)
assert all(abs(t - 0.5) < 1e-3 for col in w for t in col)
w0, it = sf.diffuse(q, 0.0)
assert w0 == q and it == 0
# ---- advection order and stability ----
def bump_error(nx, cfl=2.5, x0=0.34375, dist=0.3125, sigma=0.1):
"""Max error after moving a Gaussian bump by dist with u = 1, at the CFL number cfl."""
g = macgrid.make_grid(nx, 2, 1.0 / nx)
for col in g.u:
col[0] = col[1] = 1.0
def f(x):
return math.exp(-(x - x0) ** 2 / (2.0 * sigma * sigma))
s = [[f((a + 0.5) * g.dx)] * 2 for a in range(nx)]
steps = round(dist / (cfl * g.dx))
for _ in range(steps):
s = sf.advect(g, s, dist / steps)
return max(abs(s[a][0] - f((a + 0.5) * g.dx - dist)) for a in range(nx))
def test_advection_is_first_order_at_fixed_cfl():
e8, e16, e32 = bump_error(8), bump_error(16), bump_error(32)
assert e8 > e16 > e32
order = math.log2(e16 / e32)
assert 0.8 < order < 1.2
assert 0.04 < e32 < 0.05
def test_constant_field_and_maximum_principle():
g, rng = random_grid(12, 12, 1.0 / 12.0, 5)
sf.project(g, 0.1, 1.0)
const = [[2.5] * 12 for _ in range(12)]
assert all(abs(t - 2.5) < 1e-14 for col in sf.advect(g, const, 0.7) for t in col)
q = [[rng.uniform(0.0, 1.0) for _ in range(12)] for _ in range(12)]
out = sf.advect(g, q, 0.7)
assert 0.0 <= min(map(min, out)) and max(map(max, out)) <= 1.0
def test_large_step_stays_bounded():
g, _ = random_grid(16, 16, 1.0 / 16.0, 11)
sf.project(g, 0.01, 1.0)
umax = max_abs(g.u, g.v)
dt = 5.0 * g.dx / umax
s = [[1.0 if 4 <= a < 8 and 4 <= b < 8 else 0.0 for b in range(16)] for a in range(16)]
e = [macgrid.kinetic_energy(g, 1.0)]
for _ in range(10):
s = sf.step(g, dt, 1.0, scalars=[s])[0]
e.append(macgrid.kinetic_energy(g, 1.0))
assert macgrid.max_fluid_divergence(g) < 1e-8
assert all(math.isfinite(t) for t in e)
assert all(e[k + 1] <= e[k] for k in range(10))
assert e[10] < 0.02 * e[0]
assert 0.0 <= min(map(min, s)) and max(map(max, s)) <= 1.0
# ---- the full step ----
def test_step_with_force_viscosity_and_decay():
g = macgrid.make_grid(12, 12, 1.0 / 12.0)
s = [[1.0 if 5 <= a < 7 and 1 <= b < 3 else 0.0 for b in range(12)] for a in range(12)]
def lift(x, y):
return (0.0, 4.0 if 0.4 < x < 0.6 and y < 0.4 else 0.0)
for _ in range(5):
s = sf.step(g, 0.02, 1.0, nu=1e-3, force=lift, scalars=[s], kappa=1e-4, decay=0.5)[0]
assert macgrid.max_fluid_divergence(g) < 1e-8
assert max_abs(g.v) > 0.0
assert all(t == 0.0 for t in g.v[3][:1] + g.v[3][12:])
assert 0.0 <= min(map(min, s)) and max(map(max, s)) <= 1.0
s1 = sf.step(macgrid.make_grid(4, 4, 0.25), 0.1, 1.0, scalars=[[[1.0] * 4 for _ in range(4)]], decay=2.0)[0]
assert all(abs(t - 1.0 / 1.2) < 1e-15 for col in s1 for t in col)
History
Jos Stam presented stable fluids at SIGGRAPH 1999. Earlier animation solvers, such as the one of Foster and Metaxas (1996), were explicit and had to keep the step small. Stam made the advection semi-Lagrangian, a method known from weather prediction, made the diffusion implicit, and kept Chorin's projection. He showed that no part limits the step. In 2001, Fedkiw, Stam and Jensen moved the method to the staggered grid, added vorticity confinement, and used it for smoke. Later work kept the structure of the step and replaced the parts: higher order advection, particle velocities, and faster pressure solvers.
References
- Jos Stam, Stable fluids, Proceedings of SIGGRAPH 99, 121-128, 1999, the solver (add force, advect, diffuse, project), the stability argument, and the FFT solve on a periodic domain
- Ronald Fedkiw, Jos Stam and Henrik Wann Jensen, Visual simulation of smoke, SIGGRAPH 2001, 15-22, Section 4, the semi-Lagrangian solver on the staggered grid
- Robert Bridson, Fluid Simulation for Computer Graphics, second edition, CRC Press, 2015, the chapters Advection Algorithms and Making Fluids Incompressible
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 4DDRB0 Edit this page History Report an error Markdown