Algorithm Search⌘K

Algorithmadvanced

Foster-Metaxas liquid animation

Also called realistic animation of liquids.

Animate liquids by explicit finite differences of the Navier-Stokes equations on a MAC grid, a cell-by-cell pressure iteration and marker particles for the surface.

Time
Θ(m) markersO(g k) pressureO(g k + m) stepΘ(g) velocity
Space
Θ(g + m) extra
Where
g = the number of grid cells; k = the number of pressure sweeps; m = the number of marker particles
Properties
deterministicnot exactexplicitnot unconditionally stable
Origin
Nick Foster, Dimitri Metaxas, 1996

The Foster-Metaxas method (1996) is an early full 3D Navier-Stokes solver for liquids in computer animation. It brought the marker-and-cell method of Harlow and Welch from engineering into graphics. It stores the velocity on a MAC grid, moves it by explicit finite differences, removes the divergence by a cell-by-cell pressure iteration, and tracks the liquid with massless marker particles. Special rules set the velocity at the free surface. The method is explicit, so its time step must stay small. That limit is the main thing that stable fluids removed three years later.

In plain words

The space is cut into a grid of boxes. Small markers float in the liquid and show where it is. A box with markers next to an empty box is on the surface.

Each step does four things. First it changes the speed of the liquid on each box wall: the flow carries speed along, gravity pulls down, pressure pushes from high to low, and friction evens out the speeds. Next it visits each full box in turn and fixes its walls. If more liquid flows out than in, the box lowers its pressure and its walls let less out, and if more flows in, it does the opposite. It repeats the visits until every full box is balanced. Then simple rules set the walls of the surface boxes. Last, each marker moves with the local speed.

The steps must be short, or the numbers grow out of control.

The problem

Animate a liquid with a free surface in a box with walls. The liquid moves by the incompressible Navier-Stokes equations, written with the kinematic pressure pp (pressure divided by density), as in the paper:

∂u∂t=−(u⋅∇)u−∇p+ν∇2u+g,∇⋅u=0.\frac{\partial \mathbf u}{\partial t} = -(\mathbf u \cdot \nabla)\mathbf u - \nabla p + \nu \nabla^2 \mathbf u + \mathbf g, \qquad \nabla \cdot \mathbf u = 0.

Above the liquid is air at a fixed pressure, taken as 0. At each frame the animator needs the shape of the liquid, for rendering. Small details of the flow matter less than a plausible shape, so this is a case of fluid simulation for animation.

The algorithm

The paper's Section 6 lists nine steps: set up the obstacles and the liquid, set the initial pressure and velocity, and then loop over labeling the cells, setting the boundary values, computing the new velocity, iterating the pressure, fixing the surface cells and moving the markers. This page shows the loop in 2D with square cells and free-slip walls, as in the paper's examples. The paper is in 3D with δx\delta x, δy\delta y and δz\delta z allowed to differ, and it also has obstacle cells inside the grid.

  1. FOSTER-METAXAS-STEP(u, v, p, markers, dt)
  2. 1label each cell EMPTY if it has no marker, SURFACE if it has an EMPTY neighbor, else FULL
  3. 2on each u face with a liquid side: u~ <- u + dt (-d(u^2)/dx - d(uv)/dy - dp/dx + nu lap u + g_x)
  4. 3on each v face with a liquid side: v~ <- v + dt (-d(uv)/dx - d(v^2)/dy - dp/dy + nu lap v + g_y)
  5. 4repeat: for each FULL cell c in a fixed order:
  6. 5D <- -(divergence of c); dp <- beta D with beta = beta0 dx^2 / (4 dt)
  7. 6add (dt / dx) dp to the outward velocity of each face of c not on a wall; p_c <- p_c + dp
  8. 7until |divergence| < eps in every FULL cell
  9. 8on each SURFACE cell, set the faces toward EMPTY cells by the free surface rules
  10. 9move each marker: x <- x + dt U(x), with U interpolated from the four nearest faces

Labels (L1). The paper calls this step 3 and adds a fourth label for obstacle cells. A cell with no marker is EMPTY. A cell with a marker next to an EMPTY cell is SURFACE. Every other cell with a marker is FULL.

Velocity (L2, L3). These are equation 2 of the paper: one forward Euler step with central differences, in conservative form (∂u2/∂x\partial u^2 / \partial x instead of u ∂u/∂xu\, \partial u / \partial x). A value that the grid does not store, such as uu at a cell center, is the average of its two neighbors, and the square of a quantity is the square of that average. The pressure of a SURFACE or EMPTY cell is the air pressure 0. At a free-slip wall, the normal velocity is 0, and a tangential velocity outside the wall copies the one inside. The paper also allows no-slip walls, where the outside value is the negative of the inside one.

Pressure (L4 to L7). These are equations 5 to 9. DD is the "missing mass" of the cell. One update moves all open faces of the cell by the same amount, in the direction that cancels the divergence. With β0=1\beta_0 = 1, an interior cell ends exactly balanced, but the update changes the divergence of its neighbors. So the paper sweeps over all FULL cells until the largest divergence is below ε\varepsilon, and it chooses β0\beta_0 in [1,2][1, 2] to speed this up. This is successive over-relaxation on the pressure Poisson equation, and β0\beta_0 is the relaxation factor. The paper reports 3 to 6 sweeps on average in its examples with β0=1.7\beta_0 = 1.7 and ε=0.0001\varepsilon = 0.0001, starting each step from the old pressure.

Surface (L8). These are the rules of Section 3.2.3. A SURFACE cell with one face toward an EMPTY cell sets that face so that the divergence of the cell is 0 (equation 10). With two such faces on different axes, each copies the face opposite it. With three, the face opposite the liquid copies, and the other two keep the value from equation 2, so they follow gravity. In 3D a surface cell has 64 cases. The paper does not state the 2D case of two open faces on the same axis, which is a column one cell wide. The code of this page moves both by the same amount so that the divergence is 0.

Markers (L9). The paper interpolates the velocity at a marker by area weighting of the four nearest values, which is bilinear interpolation, and moves the marker by forward Euler. The markers carry no mass and do not take part in the velocity computation.

Example

One cell update by hand. Take an interior FULL cell with Δx=0.1\Delta x = 0.1 m and Δt=0.01\Delta t = 0.01 s. Its faces have uleft=0.2u_{\text{left}} = 0.2, uright=0.5u_{\text{right}} = 0.5, vbottom=0.1v_{\text{bottom}} = 0.1 and vtop=0v_{\text{top}} = 0, all in m/s. The divergence is (0.5−0.2+0−0.1)/0.1=2(0.5 - 0.2 + 0 - 0.1)/0.1 = 2 per second, so D=−2D = -2. With β0=1\beta_0 = 1, β=0.12/(4⋅0.01)=0.25\beta = 0.1^2 / (4 \cdot 0.01) = 0.25 m²/s, so δp=−0.5\delta p = -0.5 m²/s², and each outward velocity changes by (0.01/0.1)(−0.5)=−0.05(0.01/0.1)(-0.5) = -0.05 m/s:

face left uu right uu bottom vv top vv divergence (1/s) 12∑w2\frac12 \sum w^2
before 0.20 0.50 0.10 0.00 2 0.150
after 0.25 0.45 0.15 -0.05 0 0.145

The cell is balanced, and the energy drops by 0.0050.005, which is F2/(2n)=0.22/8F^2 / (2 n) = 0.2^2 / 8 with the net outflow F=0.2F = 0.2 m/s and n=4n = 4 open faces. With β0=1.7\beta_0 = 1.7 the update overshoots, to a divergence of −1.4-1.4, but over a sweep it moves the error away faster.

The effect of β0\beta_0, measured. A random velocity in a closed box full of liquid, from random.Random(1), Δt=0.01\Delta t = 0.01 s, reduced to ε=10−4\varepsilon = 10^{-4}:

grid β0=1\beta_0 = 1 1.51.5 1.71.7 1.91.9
8 by 8 139 65 47 77
16 by 16 402 155 83 102

The best β0\beta_0 is near 1.7 here, and the count grows with the grid. The paper's small counts probably come from starting each step at the old pressure, where the velocity is already nearly balanced. The still pool below shows the same effect.

A still pool and a dam break, measured. A pool 6 cells deep in a 12 by 12 box, with 4 markers per cell, Δt=0.005\Delta t = 0.005 s and ε=10−8\varepsilon = 10^{-8}, stays at rest for 40 steps: the largest velocity is 2.5×10−102.5 \times 10^{-10} m/s. The first step needs 134 sweeps to build the hydrostatic pressure, and from the third step on no sweep is needed. A column of water 0.25 m wide and 0.5 m tall in a 0.8 m box (16 by 16 cells, 200 markers, Δt=0.004\Delta t = 0.004 s, ε=10−4\varepsilon = 10^{-4}) collapses. Its front moves from 0.25 m to 0.30 m after 20 steps, 0.46 m after 40 steps and 0.66 m after 60 steps. Each step takes 34 to 53 sweeps, and the CFL number stays below 0.25.

Correctness

The claims are about the discrete step. They are proved in proofs/correctness.md.

  1. One cell update. It multiplies the divergence of the cell by 1−β0nc/41 - \beta_0 n_c / 4, where ncn_c is the number of faces not on a wall. It lowers the kinetic energy by F22ncω(2−ω)\frac{F^2}{2 n_c} \omega (2 - \omega), with ω=β0nc/4\omega = \beta_0 n_c / 4, so for β0≤2\beta_0 \le 2 the energy never increases.
  2. The pressure iteration is the projection. For 0<β0<20 < \beta_0 < 2, the sweeps converge linearly to the orthogonal projection of the velocity onto the fields with zero divergence in every FULL cell. That is the same velocity as the projection of the shared helper macgrid.py with FULL cells as FLUID and the other cells as AIR. If each group of FULL cells touches the surface, the pressures are also the same.
  3. Surface rules. A SURFACE cell with one or two faces toward EMPTY cells ends with zero divergence.
  4. Rest. A pool at rest with the hydrostatic pressure stays at rest.
  5. Step limit. In a linear model, the explicit viscous term is stable in 2D only for νΔt/Δx2≤14\nu \Delta t / \Delta x^2 \le \frac14. Central advection with viscosity in 1D is stable if and only if c2≤2r≤1c^2 \le 2r \le 1, and without viscosity it grows a little at every step size.

The tests check each claim: the update formula on every cell of a random field, the match with the helper in a closed box and with a free surface, the surface rules, the hydrostatic pressure, the still pool, the viscous limit through the full code, and the dam break.

Proof: The pressure iteration converges to the discrete projection, and the explicit step has a step limitfull

We use the 2D MAC layout and the line numbers of the page, with square cells of side Δx\Delta x. All statements are in exact arithmetic. As in the paper, pp is the pressure divided by the density. The box walls are free-slip, so the normal velocity on a wall face is 0 and a relax step never changes it. A face of a cell is open if it is not on a wall. For a cell cc, let nc∈{2,3,4}n_c \in \{2, 3, 4\} be its number of open faces, and let Fc=Δx (∇⋅u)cF_c = \Delta x \, (\nabla \cdot \mathbf u)_c be the sum of the outward velocities over its faces. The paper's "missing mass" is Dc=−Fc/ΔxD_c = -F_c / \Delta x (its equation 5). We write E=12∑fwf2E = \frac12 \sum_f w_f^2 for the kinetic energy of a face field ww, per unit mass and cell area.

Lemma 1 (labels, line L1). After line L1, a FULL cell has no EMPTY neighbor in the grid, and a SURFACE cell has at least one. So the open faces of a FULL cell lead to FULL or SURFACE cells.

Proof. Line L1 marks a cell with a marker as SURFACE exactly when a neighbor in the grid has no marker, which is the EMPTY label. □\square

Lemma 2 (one cell update, lines L5 and L6). Let cc be a FULL cell and ωc=β0nc/4\omega_c = \beta_0 n_c / 4. After one update of cc, its divergence is multiplied by 1−ωc1 - \omega_c, and the kinetic energy changes by

ΔE=−Fc22nc ωc(2−ωc).\Delta E = -\frac{F_c^2}{2 n_c}\, \omega_c (2 - \omega_c).

So for 0≤β0≤20 \le \beta_0 \le 2 the energy never increases, and for β0=1\beta_0 = 1 an interior cell (nc=4n_c = 4) ends with zero divergence.

Proof. Line L5 sets δp=βDc\delta p = \beta D_c with β=β0Δx2/(4Δt)\beta = \beta_0 \Delta x^2 / (4 \Delta t), which is equation 7 of the paper for δx=δy=Δx\delta x = \delta y = \Delta x in 2D. Line L6 adds ΔtΔxδp\frac{\Delta t}{\Delta x} \delta p to the outward velocity of each open face (it adds to ui+1,ju_{i+1,j} and subtracts from ui,ju_{i,j}, and the outward direction of the left face is −x-x). That amount is s=ΔtΔx⋅β0Δx24Δt⋅(−FcΔx)=−β04Fcs = \frac{\Delta t}{\Delta x} \cdot \frac{\beta_0 \Delta x^2}{4 \Delta t} \cdot \left(-\frac{F_c}{\Delta x}\right) = -\frac{\beta_0}{4} F_c. The wall faces do not change. So the new sum of outward velocities is Fc+ncs=(1−ωc)FcF_c + n_c s = (1 - \omega_c) F_c. For the energy, let w1,…,wncw_1, \dots, w_{n_c} be the outward velocities of the open faces, with ∑kwk=Fc\sum_k w_k = F_c (the wall faces carry 0). Each becomes wk−ωcFc/ncw_k - \omega_c F_c / n_c, and no other face changes. Then

ΔE=12∑k[(wk−ωcFcnc)2−wk2]=12[−2ωcFc2nc+ωc2Fc2nc],\Delta E = \frac12 \sum_k \left[\left(w_k - \frac{\omega_c F_c}{n_c}\right)^2 - w_k^2\right] = \frac12\left[-\frac{2 \omega_c F_c^2}{n_c} + \frac{\omega_c^2 F_c^2}{n_c}\right],

which is the formula. With nc≤4n_c \le 4 and 0≤β0≤20 \le \beta_0 \le 2 we have 0≤ωc≤20 \le \omega_c \le 2, so ΔE≤0\Delta E \le 0. □\square

The update is a step of successive over-relaxation on the pressure Poisson system, with the factor ωc\omega_c in place of β0\beta_0. For an interior cell the two are the same. Near a wall ωc<β0\omega_c < \beta_0, so a cell with two open faces needs β0=2\beta_0 = 2 to zero its divergence in one update. The paper's range 1≤β0≤21 \le \beta_0 \le 2 keeps every ωc\omega_c in [12,2][\frac12, 2].

Theorem 1 (the pressure iteration is a projection, lines L4 to L7). Let w0w^0 be the face field after lines L2 and L3, and let F\mathcal F be the set of FULL cells. For each c∈Fc \in \mathcal F let gcg_c be the face field that is +1+1 in the outward direction on each open face of cc and 0 elsewhere, so that Fc(w)=⟨gc,w⟩F_c(w) = \langle g_c, w \rangle. Let SS be the span of the gcg_c. If 0<β0<20 < \beta_0 < 2, the sweeps of line L4 converge linearly to

w∗=w0−PSw0,w^\ast = w^0 - P_S w^0,

the orthogonal projection of w0w^0 onto the fields with zero divergence on every FULL cell. This is the field of least kinetic energy among w0+Sw^0 + S, and it is the same field that macgrid.project gives with ρ=1\rho = 1, when FULL cells are FLUID and all other cells are AIR. If every connected group of FULL cells touches a SURFACE cell, the accumulated pressure in the FULL cells also converges to the pressure of the helper.

Proof. By Lemma 2, an update of cc changes ww by a multiple of gcg_c, so every iterate lies in w0+Sw^0 + S. A field ww has zero divergence on all FULL cells exactly when ⟨gc,w⟩=0\langle g_c, w \rangle = 0 for all cc, that is, when w∈S⊥w \in S^\perp. The set (w0+S)∩S⊥(w^0 + S) \cap S^\perp has the single point w∗=w0−PSw0w^\ast = w^0 - P_S w^0, and by the Pythagorean rule it has the least norm in w0+Sw^0 + S.

Let e=w−w∗∈Se = w - w^\ast \in S be the error. Since ⟨gc,w∗⟩=0\langle g_c, w^\ast \rangle = 0 and ∥gc∥2=nc\|g_c\|^2 = n_c, the update of Lemma 2 is w←w−ωc⟨gc,w⟩ncgcw \leftarrow w - \omega_c \frac{\langle g_c, w \rangle}{n_c} g_c, so e←(I−ωcPc)ee \leftarrow (I - \omega_c P_c) e, where PcP_c is the orthogonal projection onto gcg_c. Then ∥(I−ωcPc)e∥2=∥e∥2−ωc(2−ωc)∥Pce∥2\|(I - \omega_c P_c) e\|^2 = \|e\|^2 - \omega_c (2 - \omega_c) \|P_c e\|^2. For 0<β0<20 < \beta_0 < 2 we have 0<ωc<20 < \omega_c < 2, since nc≥2n_c \ge 2 on a grid of at least 2 by 2 cells. Let TT be the product of these maps over one sweep. TT maps SS into SS, and ∥Te∥≤∥e∥\|T e\| \le \|e\|. If ∥Te∥=∥e∥\|T e\| = \|e\|, then each factor keeps the norm, so Pce=0P_c e = 0 at each stage, so no stage changes ee, and ⟨gc,e⟩=0\langle g_c, e \rangle = 0 for all cc. Then e∈S∩S⊥={0}e \in S \cap S^\perp = \{0\}. The unit sphere of the finite-dimensional space SS is compact, so q=max⁡{∥Te∥:e∈S,∥e∥=1}<1q = \max \{\|T e\| : e \in S, \|e\| = 1\} < 1, and ∥ek∥≤qk∥e0∥\|e^k\| \le q^k \|e^0\| after kk sweeps. The divergence of each FULL cell is ⟨gc,ek⟩/Δx\langle g_c, e^k \rangle / \Delta x, so it goes to 0 and line L7 stops after finitely many sweeps for any ε>0\varepsilon > 0.

For the helper, write its projection as w′=w0−ΔtρGpw' = w^0 - \frac{\Delta t}{\rho} G p with ρ=1\rho = 1. On an open face from a FLUID cell cc to a neighbor nn, the outward component of GpG p is (pn−pc)/Δx(p_n - p_c)/\Delta x, with pn=0p_n = 0 for an AIR cell. So w′=w0+ΔtΔx∑cpc gc∈w0+Sw' = w^0 + \frac{\Delta t}{\Delta x} \sum_c p_c\, g_c \in w^0 + S, and the helper proves that w′w' has zero divergence on every FLUID cell, so w′∈S⊥w' \in S^\perp. By Lemma 1 the open faces of a FULL cell go to FULL or SURFACE cells, so the two methods have the same cells, the same faces and the same set SS. Hence w′=w∗w' = w^\ast. Lines L5 and L6 add δp\delta p to pcp_c and move ww by ΔtΔxδp gc\frac{\Delta t}{\Delta x} \delta p \, g_c, so the iterate is w0+ΔtΔx∑cpc gcw^0 + \frac{\Delta t}{\Delta x} \sum_c p_c\, g_c with the accumulated pp, the same form. The Gram matrix ⟨gc,gc′⟩\langle g_c, g_{c'} \rangle is the 5-point matrix of the helper: ncn_c on the diagonal and −1-1 for two FULL neighbors. If each connected group of FULL cells touches a SURFACE cell, that matrix is positive definite, the gcg_c are linearly independent, and the coefficients of w∗w^\ast in this basis are unique. Then the accumulated pp converges to the pressure of the helper. In a closed box the gcg_c of a closed group sum to zero, and the two pressures can differ by a constant on that group. □\square

The tests compare the two methods at ε=10−10\varepsilon = 10^{-10}: the velocities agree to about 10−1110^{-11} in a closed 16 by 16 box and in a 10 by 10 box with a free surface, and the pressures agree to 4.3×10−104.3 \times 10^{-10} in the second case.

Lemma 3 (the free surface rules, line L8). After line L8, a SURFACE cell with one open face toward an EMPTY cell, or with two such faces, has zero divergence. A cell with three such faces has zero divergence along the axis of the closed face only.

Proof. One face (equation 10 of the paper): the rule solves ui+1,j−ui,j+vi,j+1−vi,j=0u_{i+1,j} - u_{i,j} + v_{i,j+1} - v_{i,j} = 0 for the open face. Two faces on different axes: each open face copies the face opposite it, so ui+1,j=ui,ju_{i+1,j} = u_{i,j} and vi,j+1=vi,jv_{i,j+1} = v_{i,j}, and both differences are 0. This is the paper's rule ∂u/∂x=0\partial u / \partial x = 0 and ∂v/∂y=0\partial v / \partial y = 0 separately. Two faces on the same axis, a case the paper does not state: the code sets them to m∓hm \mp h with 2h=−(vi,j+1−vi,j)2h = -(v_{i,j+1} - v_{i,j}), so their difference cancels the other axis. Three faces: the face opposite the closed face copies it, so that axis has zero difference. The other two faces keep the values of equation 2, as in the paper, where they follow the body force. □\square

Lemma 4 (hydrostatic rest, lines L2 and L3). Let all velocities be 0, let the FULL cells fill the rows 0,…,h−10, \dots, h-1 and the SURFACE cells fill row hh, and let pi,j=∣gy∣(h−j)Δxp_{i,j} = |g_y| (h - j) \Delta x in the FULL cells. Then lines L2 to L8 keep every velocity at 0.

Proof. With zero velocity, all advection and viscous terms are 0. On a vv face between two FULL rows, line L3 gives ΔtΔx(pi,j−1−pi,j)+Δt gy=ΔtΔx∣gy∣Δx−Δt∣gy∣=0\frac{\Delta t}{\Delta x} (p_{i,j-1} - p_{i,j}) + \Delta t\, g_y = \frac{\Delta t}{\Delta x} |g_y| \Delta x - \Delta t |g_y| = 0. On the face between row h−1h - 1 and the SURFACE row, the SURFACE cell has p=0p = 0 and the same sum is 0. On a uu face both pressures are equal. So w0w^0 is 0 below row hh. The face between the SURFACE row and the EMPTY row gets Δt gy\Delta t\, g_y. Every FULL cell has zero divergence, so line L7 does no sweep. Each SURFACE cell then has one open face, the top one, and Lemma 3 sets it to vi,h−0=0v_{i,h} - 0 = 0. □\square

The surface pressure is placed at the center of the SURFACE cell. The test of a still pool runs 40 steps and finds velocities below 10−910^{-9}. The paper gives no proof of this property.

Theorem 2 (the explicit step has a limit). The paper states the limit max⁡(uδt/δx,vδt/δy,wδt/δz)<1\max(u \delta t / \delta x, v \delta t / \delta y, w \delta t / \delta z) < 1 of its equation 3. That condition is needed for the markers, but it does not alone make lines L2 and L3 stable. On a periodic grid, linearized about a constant velocity, with c=uΔt/Δxc = u \Delta t / \Delta x and r=νΔt/Δx2r = \nu \Delta t / \Delta x^2:

  1. The viscous term alone, in 2D, is stable if and only if r≤14r \le \frac14.
  2. In 1D, central advection and the viscous term together are stable if and only if c2≤2r≤1c^2 \le 2r \le 1.
  3. With ν=0\nu = 0, central advection is unstable at every Δt>0\Delta t > 0. Over a time TT, the growth factor is at most exp⁡(Tu2Δt/(2Δx2))\exp(T u^2 \Delta t / (2 \Delta x^2)).

Proof. Each part is a von Neumann analysis: a Fourier mode ei(k1a+k2b)e^{\mathrm i (k_1 a + k_2 b)} is multiplied by a factor GG per step, and the step is stable if and only if ∣G∣≤1|G| \le 1 for all modes.

  1. The 5-point update w←w+r(sum of the four neighbors−4w)w \leftarrow w + r(\text{sum of the four neighbors} - 4w) has G=1−4r(sin⁡2θ12+sin⁡2θ22)G = 1 - 4r (\sin^2 \frac{\theta_1}{2} + \sin^2 \frac{\theta_2}{2}), which takes all values in [1−8r,1][1 - 8r, 1]. The least is 1−8r1 - 8r, at the checkerboard θ1=θ2=π\theta_1 = \theta_2 = \pi. So ∣G∣≤1|G| \le 1 if and only if r≤14r \le \frac14.
  2. Central differences give G=1−icsin⁡θ−2r(1−cos⁡θ)G = 1 - \mathrm i c \sin \theta - 2 r (1 - \cos \theta). Put σ=1−cos⁡θ∈[0,2]\sigma = 1 - \cos \theta \in [0, 2], so sin⁡2θ=σ(2−σ)\sin^2 \theta = \sigma (2 - \sigma). Then ∣G∣2=(1−2rσ)2+c2σ(2−σ)|G|^2 = (1 - 2 r \sigma)^2 + c^2 \sigma (2 - \sigma), and
∣G∣2−1=σ[(2c2−4r)+σ(4r2−c2)].|G|^2 - 1 = \sigma \left[(2c^2 - 4r) + \sigma (4 r^2 - c^2)\right].

The bracket is linear in σ\sigma, so it is ≤0\le 0 on [0,2][0, 2] exactly when it is ≤0\le 0 at both ends. As σ→0\sigma \to 0 the condition is c2≤2rc^2 \le 2r, and at σ=2\sigma = 2 it is 4r(2r−1)≤04r(2r - 1) \le 0, that is r≤12r \le \frac12. 3. With r=0r = 0, ∣G∣2=1+c2sin⁡2θ>1|G|^2 = 1 + c^2 \sin^2 \theta > 1 for sin⁡θ≠0\sin \theta \ne 0 and c≠0c \ne 0. After N=T/ΔtN = T / \Delta t steps, ∣G∣N≤(1+c2)N/2≤exp⁡(Nc2/2)=exp⁡(Tu2Δt/(2Δx2))|G|^N \le (1 + c^2)^{N/2} \le \exp(N c^2 / 2) = \exp(T u^2 \Delta t / (2 \Delta x^2)). □\square

So a small step keeps the growth small even without viscosity, and the second condition, Δt≤2ν/u2\Delta t \le 2 \nu / u^2, can be stronger than equation 3 when ν\nu is small. These are statements about a linear model problem; the paper's equation 2 is nonlinear and has walls and a free surface. The test file checks the first claim through the full code on a 10 by 10 box: a checkerboard in uu falls to 0.0020.002 of its size after 30 steps at r=0.2r = 0.2, to 0.350.35 at r=0.25r = 0.25, and grows by a factor of about 10410^4 at r=0.3r = 0.3.

Lemma 5 (markers, line L9). Each marker moves by Δt\Delta t times the bilinear interpolation of the four nearest values of each component, which is the area weighting of the paper. The number of markers does not change, and every marker stays inside the box.

Proof. Line L9 calls the helper's vel_at, which is bilinear sampling, and then clamps each coordinate to [10−6Δx,  nΔx−10−6Δx][10^{-6} \Delta x, \; n \Delta x - 10^{-6} \Delta x]. No marker is created or removed. □\square

The markers do not take part in the velocity computation, as the paper says. They only decide the labels at line L1. So the liquid volume is not conserved exactly: it is the number of cells that hold a marker, and it can change when markers bunch up or spread out.

Complexity

Let gg be the number of cells and mm the number of markers. Labels, the new velocity, the surface rules and the extra velocity layer cost Θ(g)\Theta(g), and the markers cost Θ(m)\Theta(m). One pressure sweep costs Θ(g)\Theta(g), so the iteration costs O(gk)O(g k) for kk sweeps. From a cold start on an NN by NN grid, kk grows with NN, about as N2N^2 for β0=1\beta_0 = 1 and as NN at the best β0\beta_0, which are the rates of Gauss-Seidel and optimal SOR on the Poisson equation. The extra space is Θ(g+m)\Theta(g + m).

The total cost to a fixed time TT is the cost per step times T/ΔtT / \Delta t, and the explicit step bounds Δt\Delta t by both Δx/∣u∣max⁡\Delta x / |\mathbf u|_{\max} and about Δx2/(4ν)\Delta x^2 / (4 \nu). Halving Δx\Delta x in 3D multiplies the cells by 8 and at least halves Δt\Delta t.

Properties

  • Explicit. The velocity step is forward Euler. It needs the CFL limit of the paper's equation 3 and a viscous limit, so it is not unconditionally stable.
  • Exact projection in the limit. The iteration converges to the same divergence-free field as a direct Poisson solve. With a finite ε\varepsilon it stops early, so each FULL cell keeps a divergence up to ε\varepsilon.
  • Less numerical diffusion than semi-Lagrangian advection. Central differences do not smooth the flow the way interpolation does, so small swirls last longer, as long as the step is stable.
  • Volume is not conserved exactly. The liquid is the set of cells with a marker, and that set can grow or shrink as markers spread or bunch.
  • Local and simple. Each part touches a cell and its neighbors only, which made it practical on the hardware of 1996.

Variants and improvements

  • Obstacles, inflow and outflow. The paper's Section 3.2 sets the boundary values for obstacle cells inside the grid, with free-slip or no-slip walls, and for sources and sinks of liquid.
  • Control. Section 7 lets the animator steer the liquid through inflow and outflow and through a time history of pressure applied at the surface.
  • Hot gas. Foster and Metaxas (1997) used the same kind of solver for a hot, turbulent gas.
  • Semi-Lagrangian liquids. Foster and Fedkiw (2001) replaced the explicit advection by the semi-Lagrangian step of stable fluids, and the markers by a level set corrected with particles. This led to the particle level set method.
  • Direct pressure solves. Later solvers replace the sweeps by conjugate gradients or multigrid on the same 5-point system.
  • Particle velocities. PIC and FLIP give the markers a velocity of their own and use them for the advection too.

When to use it

Use it to study the history of liquid animation, or as a small explicit solver where the time step is already small for another reason, such as fast contact or high viscosity in a short shot. Its central differences keep more detail than a first order semi-Lagrangian step at the same grid size.

For most new work, use a semi-Lagrangian or particle-grid solver with a level set or particles for the surface. They allow large steps and give a smoother surface than marker cells.

Pitfalls

  • Too large a step. Equation 3 keeps the CFL number below 1, but the viscous term needs νΔt/Δx2≤14\nu \Delta t / \Delta x^2 \le \frac14 in 2D (and 16\frac16 in 3D), and central advection needs viscosity or a small step. Check all limits each step.
  • Too few sweeps. A loose ε\varepsilon leaves divergence, which shows as liquid that gains or loses volume.
  • β0\beta_0 out of range. For β0>2\beta_0 > 2 an interior cell update can increase the energy, and the iteration can diverge. At β0=2\beta_0 = 2 an interior update only flips the sign of the divergence.
  • The surface pressure. The pressure of a SURFACE cell is the air pressure. A FULL cell next to it sees the surface at the center of the SURFACE cell, half a cell away from where the markers may be.
  • Blocky surface. Marker cells give a surface made of whole cells. Render a smooth surface built from the markers, not the cell labels.
  • Empty faces. Markers near the surface read faces that the solver did not set. Give those faces a value, for example by one layer of extrapolation as the code here does.
  • Run-to-run cost. The number of sweeps depends on the flow, so the cost per frame is not fixed.

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.

foster_metaxas_fluids.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/foster-metaxas-fluids/. The authors are listed in prov/NBGCFG.jsonl.

"""The liquid solver of Foster and Metaxas (1996) in 2D.

Explicit finite differences of the Navier-Stokes equations on a MAC grid, a
cell-by-cell pressure iteration, free surface rules for the surface cells and
massless marker particles that mark where the liquid is. The arrays use the
layout of the shared helper macgrid.py: p[i][j] at the cell centers, u[i][j]
on the left face and v[i][j] on the bottom face of cell (i, j). The domain is
a box with free-slip walls; obstacles inside the box are not handled here.

As in the paper, p is the pressure divided by the density (m^2/s^2), and the
square cells have side dx (the paper allows dx, dy and dz to differ).
"""

import math

import macgrid

EMPTY, SURFACE, FULL = 0, 1, 2


class Liquid:
    """The state of the solver: a macgrid.Grid for u, v and p, the cell contents and the markers."""

    def __init__(self, nx, ny, dx, markers):
        self.g = macgrid.make_grid(nx, ny, dx)
        self.cells = [[EMPTY] * ny for _ in range(nx)]
        self.markers = [[float(x), float(y)] for (x, y) in markers]
        label_cells(self)


def in_grid(liq, i, j):
    return 0 <= i < liq.g.nx and 0 <= j < liq.g.ny


def label_cells(liq):
    """Cells with no marker are EMPTY; a cell with a marker is SURFACE if it has an EMPTY neighbor, else FULL."""
    g = liq.g
    has = [[False] * g.ny for _ in range(g.nx)]
    for (x, y) in liq.markers:
        i = min(max(int(x / g.dx), 0), g.nx - 1)
        j = min(max(int(y / g.dx), 0), g.ny - 1)
        has[i][j] = True
    for i in range(g.nx):
        for j in range(g.ny):
            if not has[i][j]:
                liq.cells[i][j] = EMPTY  # @line L1
                continue
            near_empty = any(in_grid(liq, a, b) and not has[a][b]
                             for (a, b) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)))
            liq.cells[i][j] = SURFACE if near_empty else FULL


def is_liquid(liq, i, j):
    return in_grid(liq, i, j) and liq.cells[i][j] != EMPTY


def pressure(liq, i, j):
    """p of a FULL cell; SURFACE and EMPTY cells have the air pressure 0."""
    return liq.g.p[i][j] if liq.cells[i][j] == FULL else 0.0


def tentative_velocity(liq, dt, gx, gy, nu):
    """Equation 2 of the paper in 2D: one forward Euler step of the momentum equation.

    It is applied on every inner face with a FULL or SURFACE cell on one side.
    Missing values outside the box use the free-slip rule: a tangential
    velocity beyond a wall equals the one inside, and the normal velocity on a
    wall is 0. Returns the new (u, v); the old arrays are only read.
    """
    g = liq.g
    nx, ny, dx = g.nx, g.ny, g.dx
    u, v = g.u, g.v

    def uu(i, j):
        return u[i][min(max(j, 0), ny - 1)]

    def vv(i, j):
        return v[min(max(i, 0), nx - 1)][j]

    def node_uv(i, j):
        """u v at the grid node (i dx, j dx), from the averages of the two nearest values of each."""
        return 0.5 * (uu(i, j - 1) + uu(i, j)) * 0.5 * (vv(i - 1, j) + vv(i, j))

    def uc(i, j):
        return 0.5 * (u[i][j] + u[i + 1][j])

    def vc(i, j):
        return 0.5 * (v[i][j] + v[i][j + 1])

    nu_ = [list(col) for col in u]
    nv_ = [list(col) for col in v]
    s = dt / dx
    for i in range(1, nx):
        for j in range(ny):
            if not (is_liquid(liq, i - 1, j) or is_liquid(liq, i, j)):
                continue
            lap = uu(i + 1, j) + uu(i - 1, j) + uu(i, j + 1) + uu(i, j - 1) - 4.0 * u[i][j]
            nu_[i][j] = u[i][j] + s * (  # @line L2
                (uc(i - 1, j) ** 2 - uc(i, j) ** 2)
                + (node_uv(i, j) - node_uv(i, j + 1))
                + (pressure(liq, i - 1, j) - pressure(liq, i, j))
                + nu * lap / dx) + dt * gx
    for i in range(nx):
        for j in range(1, ny):
            if not (is_liquid(liq, i, j - 1) or is_liquid(liq, i, j)):
                continue
            lap = vv(i + 1, j) + vv(i - 1, j) + v[i][min(j + 1, ny)] + v[i][max(j - 1, 0)] - 4.0 * v[i][j]
            nv_[i][j] = v[i][j] + s * (  # @line L3
                (vc(i, j - 1) ** 2 - vc(i, j) ** 2)
                + (node_uv(i, j) - node_uv(i + 1, j))
                + (pressure(liq, i, j - 1) - pressure(liq, i, j))
                + nu * lap / dx) + dt * gy
    return nu_, nv_


def cell_divergence(liq, i, j):
    g = liq.g
    return (g.u[i + 1][j] - g.u[i][j] + g.v[i][j + 1] - g.v[i][j]) / g.dx


def max_full_divergence(liq):
    """The largest |divergence| over the FULL cells (0.0 if there is none)."""
    g = liq.g
    return max((abs(cell_divergence(liq, i, j)) for i in range(g.nx) for j in range(g.ny)
                if liq.cells[i][j] == FULL), default=0.0)


def relax_cell(liq, i, j, dt, beta0):
    """Equations 5 to 9 for one FULL cell: dp = beta D, then move its open faces and its pressure.

    D is minus the divergence (the paper's "missing mass") and
    beta = beta0 / (2 dt (1/dx^2 + 1/dy^2)) = beta0 dx^2 / (4 dt). The faces on
    the walls of the box keep their zero normal velocity. Returns dp.
    """
    g = liq.g
    d = -cell_divergence(liq, i, j)
    dp = beta0 * g.dx * g.dx / (4.0 * dt) * d  # @line L5
    s = dt / g.dx * dp
    if i + 1 < g.nx:
        g.u[i + 1][j] += s  # @line L6
    if i > 0:
        g.u[i][j] -= s
    if j + 1 < g.ny:
        g.v[i][j + 1] += s
    if j > 0:
        g.v[i][j] -= s
    g.p[i][j] += dp
    return dp


def pressure_iteration(liq, dt, beta0=1.7, eps=1e-4, max_sweeps=10000):
    """Sweep over the FULL cells with relax_cell until every FULL cell has |divergence| < eps.

    Returns the number of sweeps. A sweep visits the cells in the order i, then j.
    """
    g = liq.g
    full = [(i, j) for i in range(g.nx) for j in range(g.ny) if liq.cells[i][j] == FULL]
    sweeps = 0
    while sweeps < max_sweeps and max_full_divergence(liq) >= eps:  # @line L7
        for (i, j) in full:
            relax_cell(liq, i, j, dt, beta0)  # @line L4
        sweeps += 1
    return sweeps


def surface_velocities(liq):
    """Set the faces of each SURFACE cell that face an EMPTY cell (Section 3.2.3 of the paper).

    One open face: it gets the value that makes the divergence of the cell 0
    (equation 10). Two open faces on different axes: each takes the value of
    the face opposite it. Three open faces: the open face opposite the closed
    one takes its value, and the other two keep the result of equation 2. Two
    open faces on the same axis, a case the paper does not state in 2D: both
    move by the same amount in opposite directions so that the divergence is 0.
    Four open faces: no change.
    """
    g = liq.g
    u, v = g.u, g.v
    for i in range(g.nx):
        for j in range(g.ny):
            if liq.cells[i][j] != SURFACE:
                continue

            def opened(a, b):
                return in_grid(liq, a, b) and liq.cells[a][b] == EMPTY

            left, right = opened(i - 1, j), opened(i + 1, j)
            down, up = opened(i, j - 1), opened(i, j + 1)
            n_open = left + right + down + up
            if n_open == 1:
                if right:
                    u[i + 1][j] = u[i][j] - (v[i][j + 1] - v[i][j])  # @line L8
                elif left:
                    u[i][j] = u[i + 1][j] + (v[i][j + 1] - v[i][j])
                elif up:
                    v[i][j + 1] = v[i][j] - (u[i + 1][j] - u[i][j])
                else:
                    v[i][j] = v[i][j + 1] + (u[i + 1][j] - u[i][j])
            elif n_open == 2 and (left or right) and (down or up):
                if right:
                    u[i + 1][j] = u[i][j]
                else:
                    u[i][j] = u[i + 1][j]
                if up:
                    v[i][j + 1] = v[i][j]
                else:
                    v[i][j] = v[i][j + 1]
            elif n_open == 2:
                if left:
                    m, h = 0.5 * (u[i][j] + u[i + 1][j]), -0.5 * (v[i][j + 1] - v[i][j])
                    u[i][j], u[i + 1][j] = m - h, m + h
                else:
                    m, h = 0.5 * (v[i][j] + v[i][j + 1]), -0.5 * (u[i + 1][j] - u[i][j])
                    v[i][j], v[i][j + 1] = m - h, m + h
            elif n_open == 3:
                if not left:
                    u[i + 1][j] = u[i][j]
                elif not right:
                    u[i][j] = u[i + 1][j]
                elif not down:
                    v[i][j + 1] = v[i][j]
                else:
                    v[i][j] = v[i][j + 1]


def extrapolate(liq):
    """Give each inner face with no liquid side the mean of its liquid neighbors of the same component, or 0.

    This is not in the paper; it gives the markers near the surface a velocity
    to sample from the empty side.
    """
    g = liq.g
    u, v = g.u, g.v

    def u_wet(i, j):
        return 1 <= i < g.nx and 0 <= j < g.ny and (is_liquid(liq, i - 1, j) or is_liquid(liq, i, j))

    def v_wet(i, j):
        return 0 <= i < g.nx and 1 <= j < g.ny and (is_liquid(liq, i, j - 1) or is_liquid(liq, i, j))

    nu_ = [list(col) for col in u]
    nv_ = [list(col) for col in v]
    for i in range(1, g.nx):
        for j in range(g.ny):
            if not u_wet(i, j):
                vals = [u[a][b] for (a, b) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)) if u_wet(a, b)]
                nu_[i][j] = sum(vals) / len(vals) if vals else 0.0
    for i in range(g.nx):
        for j in range(1, g.ny):
            if not v_wet(i, j):
                vals = [v[a][b] for (a, b) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)) if v_wet(a, b)]
                nv_[i][j] = sum(vals) / len(vals) if vals else 0.0
    g.u, g.v = nu_, nv_


def move_markers(liq, dt):
    """x <- x + dt U(x) for each marker, with U from area weighting (bilinear) of the four nearest faces.

    A marker that would leave the box is put back just inside it.
    """
    g = liq.g
    lo = 1e-6 * g.dx
    hx, hy = g.nx * g.dx - lo, g.ny * g.dx - lo
    for m in liq.markers:
        ux, uy = macgrid.vel_at(g, m[0], m[1])
        m[0] = min(max(m[0] + dt * ux, lo), hx)  # @line L9
        m[1] = min(max(m[1] + dt * uy, lo), hy)


def cfl_number(liq, dt):
    """max(|u| dt / dx, |v| dt / dx) over all faces; the paper needs it below 1 (its equation 3)."""
    g = liq.g
    m = max(max(abs(t) for col in g.u for t in col), max(abs(t) for col in g.v for t in col))
    return m * dt / g.dx


def step(liq, dt, gx=0.0, gy=-9.81, nu=0.0, beta0=1.7, eps=1e-4):
    """One step of Section 6 of the paper (steps 3 to 8). Returns the number of pressure sweeps."""
    label_cells(liq)
    liq.g.u, liq.g.v = tentative_velocity(liq, dt, gx, gy, nu)
    sweeps = pressure_iteration(liq, dt, beta0, eps)
    surface_velocities(liq)
    extrapolate(liq)
    move_markers(liq, dt)
    return sweeps


def kinetic_energy(liq):
    """(1/2) times the sum of the squares of all face velocities (per unit mass and cell area)."""
    g = liq.g
    return 0.5 * (sum(t * t for col in g.u for t in col) + sum(t * t for col in g.v for t in col))


def isfinite_state(liq):
    g = liq.g
    return all(math.isfinite(t) for q in (g.u, g.v, g.p) for col in q for t in col)
macgrid.py 347 lines
# 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
test_foster_metaxas_fluids.py 177 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/foster-metaxas-fluids/. The authors are listed in prov/NBGCFG.jsonl.

"""Tests of the Foster-Metaxas liquid solver in 2D."""

import random

import macgrid
import foster_metaxas_fluids as fm
from foster_metaxas_fluids import EMPTY, FULL, SURFACE


def box(n, rows, seed=None, dx=None):
    """A liquid with one marker in each cell of the lowest rows rows; random inner velocities if seed is given."""
    dx = dx or 1.0 / n
    liq = fm.Liquid(n, n, dx, [((i + 0.5) * dx, (j + 0.5) * dx) for i in range(n) for j in range(rows)])
    if seed is not None:
        rng = random.Random(seed)
        g = liq.g
        for i in range(1, n):
            for j in range(n):
                g.u[i][j] = rng.uniform(-1.0, 1.0)
        for i in range(n):
            for j in range(1, n):
                g.v[i][j] = rng.uniform(-1.0, 1.0)
    return liq


def face_diff(a, b):
    return max(abs(x - y) for c1, c2 in zip(a, b) for x, y in zip(c1, c2))


def test_labels():
    liq = box(5, 3)
    assert [liq.cells[2][j] for j in range(5)] == [FULL, FULL, SURFACE, EMPTY, EMPTY]
    liq = fm.Liquid(4, 4, 0.25, [(0.6, 0.6)])
    assert liq.cells[2][2] == SURFACE and sum(c.count(EMPTY) for c in liq.cells) == 15


def test_one_cell_update_with_beta0_one_zeroes_its_divergence():
    liq = box(3, 3, seed=1)
    fm.relax_cell(liq, 1, 1, 0.02, 1.0)
    assert abs(fm.cell_divergence(liq, 1, 1)) < 1e-12
    liq = box(3, 3, seed=2)
    d0 = fm.cell_divergence(liq, 0, 1)  # 3 open faces: omega = 3/4
    fm.relax_cell(liq, 0, 1, 0.02, 1.0)
    assert abs(fm.cell_divergence(liq, 0, 1) - 0.25 * d0) < 1e-12


def test_each_cell_update_lowers_kinetic_energy_by_the_formula():
    liq = box(6, 6, seed=3)
    g = liq.g
    for (i, j) in [(i, j) for i in range(6) for j in range(6)] * 2:
        n = sum((i > 0, i < 5, j > 0, j < 5))
        f = g.dx * fm.cell_divergence(liq, i, j)
        w = 1.7 * n / 4.0
        e0 = fm.kinetic_energy(liq)
        fm.relax_cell(liq, i, j, 0.05, 1.7)
        de = fm.kinetic_energy(liq) - e0
        assert de <= 1e-15
        assert abs(de + f * f / (2.0 * n) * w * (2.0 - w)) < 1e-12


def test_pressure_iteration_gives_the_helper_projection_closed_box():
    liq = box(16, 16, seed=4)
    h = macgrid.make_grid(16, 16, 1.0 / 16.0)
    h.u, h.v = macgrid.copy_field(liq.g.u), macgrid.copy_field(liq.g.v)
    e0 = fm.kinetic_energy(liq)
    sweeps = fm.pressure_iteration(liq, 0.01, 1.7, 1e-10)
    macgrid.project(h, 0.01, 1.0)
    assert sweeps > 0 and fm.max_full_divergence(liq) < 1e-10
    assert face_diff(liq.g.u, h.u) < 1e-9 and face_diff(liq.g.v, h.v) < 1e-9
    assert fm.kinetic_energy(liq) <= e0


def test_pressure_iteration_with_a_free_surface_matches_helper():
    liq = box(10, 7, seed=5)
    h = macgrid.make_grid(10, 10, 0.1)
    h.u, h.v = macgrid.copy_field(liq.g.u), macgrid.copy_field(liq.g.v)
    for i in range(10):
        for j in range(10):
            h.label[i][j] = macgrid.FLUID if liq.cells[i][j] == FULL else macgrid.AIR
    fm.pressure_iteration(liq, 0.01, 1.7, 1e-10)
    macgrid.project(h, 0.01, 1.0)
    assert face_diff(liq.g.u, h.u) < 1e-9 and face_diff(liq.g.v, h.v) < 1e-9
    assert max(abs(liq.g.p[i][j] - h.p[i][j]) for i in range(10) for j in range(10)
               if liq.cells[i][j] == FULL) < 1e-8


def test_over_relaxation_needs_fewer_sweeps():
    counts = {}
    for b0 in (1.0, 1.5, 1.7, 1.9):
        counts[b0] = fm.pressure_iteration(box(16, 16, seed=1), 0.01, b0, 1e-4)
    assert counts == {1.0: 402, 1.5: 155, 1.7: 83, 1.9: 102}


def test_surface_rules_give_zero_divergence():
    rng = random.Random(6)
    for marks, cell in (
            ([(1.5, 0.5), (0.5, 0.5), (2.5, 0.5), (1.5, 1.5)], (1, 1)),  # top cell: three open faces
            ([(0.5, 0.5), (1.5, 0.5), (2.5, 0.5), (0.5, 1.5), (1.5, 1.5), (2.5, 1.5)], (1, 1)),  # one open face
            ([(0.5, 0.5), (1.5, 0.5), (0.5, 1.5), (1.5, 1.5)], (1, 1)),  # a corner: two open faces
            ([(0.5, 0.5), (0.5, 1.5), (0.5, 2.5), (1.5, 1.5), (2.5, 0.5), (2.5, 1.5), (2.5, 2.5)], (1, 1))):
        liq = fm.Liquid(4, 4, 1.0, marks)
        g = liq.g
        for i in range(1, 4):
            for j in range(4):
                g.u[i][j] = rng.uniform(-1.0, 1.0)
        for i in range(4):
            for j in range(1, 4):
                g.v[i][j] = rng.uniform(-1.0, 1.0)
        i, j = cell
        assert liq.cells[i][j] == SURFACE
        fm.surface_velocities(liq)
        n_open = sum(liq.cells[a][b] == EMPTY for (a, b) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)))
        if n_open != 3:
            assert abs(fm.cell_divergence(liq, i, j)) < 1e-12


def test_gravity_and_hydrostatic_rest():
    liq = box(6, 4)
    u, v = fm.tentative_velocity(liq, 0.01, 0.0, -9.81, 0.0)
    assert all(abs(v[i][j] + 0.0981) < 1e-15 for i in range(6) for j in range(1, 5))
    assert all(v[i][0] == 0.0 and v[i][6] == 0.0 and v[i][5] == 0.0 for i in range(6))
    for i in range(6):
        for j in range(3):
            liq.g.p[i][j] = 9.81 * (3 - j) * liq.g.dx
    u, v = fm.tentative_velocity(liq, 0.01, 0.0, -9.81, 0.0)
    assert max(abs(t) for col in u for t in col) < 1e-15
    assert max(abs(v[i][j]) for i in range(6) for j in range(4)) < 1e-15  # faces below the SURFACE row
    assert all(abs(v[i][4] + 0.0981) < 1e-15 for i in range(6))  # SURFACE to EMPTY: only gravity


def test_still_pool_stays_still():
    n, dx = 12, 1.0 / 12.0
    marks = [((i + 0.25 + 0.5 * a) * dx, (j + 0.25 + 0.5 * b) * dx)
             for i in range(n) for j in range(6) for a in range(2) for b in range(2)]
    liq = fm.Liquid(n, n, dx, marks)
    for _ in range(40):
        fm.step(liq, 0.005, eps=1e-8)
    assert max(abs(t) for col in liq.g.u + liq.g.v for t in col) < 1e-8
    assert max(abs(m[1] - o[1]) for m, o in zip(liq.markers, marks)) < 1e-9


def test_explicit_viscosity_has_a_step_limit():
    def grow(r):
        liq = box(10, 10)
        g = liq.g
        for i in range(1, 10):
            for j in range(10):
                g.u[i][j] = 1e-3 * (-1) ** (i + j)
        a0 = max(abs(t) for col in g.u for t in col)
        dt = 0.01
        nu = r * g.dx * g.dx / dt
        for _ in range(30):
            g.u, g.v = fm.tentative_velocity(liq, dt, 0.0, 0.0, nu)
        return max(abs(t) for col in g.u for t in col) / a0
    assert grow(0.2) < 0.01
    assert grow(0.25) < 1.0
    assert grow(0.3) > 100.0


def test_dam_break():
    n, dx, dt = 16, 0.05, 0.004
    marks = [((i + 0.25 + 0.5 * a) * dx, (j + 0.25 + 0.5 * b) * dx)
             for i in range(5) for j in range(10) for a in range(2) for b in range(2)]
    liq = fm.Liquid(n, n, dx, marks)
    front = []
    for k in range(60):
        fm.step(liq, dt)
        assert fm.max_full_divergence(liq) < 1e-4
        assert fm.cfl_number(liq, dt) < 1.0
        front.append(max(m[0] for m in liq.markers))
    assert len(liq.markers) == 200 and fm.isfinite_state(liq)
    assert all(0.0 < m[0] < 0.8 and 0.0 < m[1] < 0.8 for m in liq.markers)
    assert front[0] < front[29] < front[59]
    assert abs(front[59] - 0.661) < 0.001

History

Harlow and Welch published the marker-and-cell method in 1965 at Los Alamos, with the staggered grid and marker particles for a free surface. In 1996 Nick Foster and Dimitri Metaxas adapted it for computer animation in "Realistic animation of liquids" (the title of the paper, which is the alias of this page). They added obstacles inside the grid and control by the animator, with examples such as a jet of water and a falling drop. Their 1997 SIGGRAPH paper used a similar solver for hot gas. Stam's stable fluids (1999) removed the explicit step limit, and Foster and Fedkiw (2001) combined that idea with a level set to build the liquid solvers that graphics has used since.

References

  1. Nick Foster and Dimitri Metaxas, Realistic animation of liquids, Graphical Models and Image Processing 58(5), 471-483, 1996, Section 3 (the grid, equations 2 to 10 and the boundary rules), Section 4.1 (markers), Section 6 (the algorithm) and Section 8 (examples)
  2. Francis H. Harlow and J. Eddie Welch, Numerical calculation of time-dependent viscous incompressible flow of fluid with free surface, The Physics of Fluids 8(12), 2182-2189, 1965, the marker-and-cell method: the staggered grid and the marker particles
  3. Nick Foster and Ronald Fedkiw, Practical animation of liquids, SIGGRAPH 2001, 23-30, the later solver with semi-Lagrangian advection and a level set with particles

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.markers
  • a full proof of time.pressure
  • a full proof of time.step
  • a full proof of time.velocity
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example