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
- Model
- Real RAM
- Properties
- deterministicnot exactexplicitnot unconditionally stable
- Evidence
- Proof sketchCode in 1 languages
- 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 (pressure divided by density), as in the paper:
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 , and allowed to differ, and it also has obstacle cells inside the grid.
FOSTER-METAXAS-STEP(u, v, p, markers, dt)- 1
label each cell EMPTY if it has no marker, SURFACE if it has an EMPTY neighbor, else FULL - 2
on each u face with a liquid side: u~ <- u + dt (-d(u^2)/dx - d(uv)/dy - dp/dx + nu lap u + g_x) - 3
on each v face with a liquid side: v~ <- v + dt (-d(uv)/dx - d(v^2)/dy - dp/dy + nu lap v + g_y) - 4
repeat: for each FULL cell c in a fixed order: - 5
D <- -(divergence of c); dp <- beta D with beta = beta0 dx^2 / (4 dt) - 6
add (dt / dx) dp to the outward velocity of each face of c not on a wall; p_c <- p_c + dp - 7
until |divergence| < eps in every FULL cell - 8
on each SURFACE cell, set the faces toward EMPTY cells by the free surface rules - 9
move 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 ( instead of ). A value that the grid does not store, such as 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. 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 , 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 , and it chooses in to speed this up. This is successive over-relaxation on the pressure Poisson equation, and is the relaxation factor. The paper reports 3 to 6 sweeps on average in its examples with and , 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 m and s. Its faces have , , and , all in m/s. The divergence is per second, so . With , m²/s, so m²/s², and each outward velocity changes by m/s:
| face | left | right | bottom | top | divergence (1/s) | |
|---|---|---|---|---|---|---|
| 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 , which is with the net outflow m/s and open faces. With the update overshoots, to a divergence of , but over a sweep it moves the error away faster.
The effect of , measured. A random velocity in a closed box full of liquid, from random.Random(1), s, reduced to :
| grid | ||||
|---|---|---|---|---|
| 8 by 8 | 139 | 65 | 47 | 77 |
| 16 by 16 | 402 | 155 | 83 | 102 |
The best 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, s and , stays at rest for 40 steps: the largest velocity is 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, s, ) 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.
- One cell update. It multiplies the divergence of the cell by , where is the number of faces not on a wall. It lowers the kinetic energy by , with , so for the energy never increases.
- The pressure iteration is the projection. For , 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.pywith 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. - Surface rules. A SURFACE cell with one or two faces toward EMPTY cells ends with zero divergence.
- Rest. A pool at rest with the hydrostatic pressure stays at rest.
- Step limit. In a linear model, the explicit viscous term is stable in 2D only for . Central advection with viscosity in 1D is stable if and only if , 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 . All statements are in exact arithmetic. As in the paper, 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 , let be its number of open faces, and let be the sum of the outward velocities over its faces. The paper's "missing mass" is (its equation 5). We write for the kinetic energy of a face field , 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.
Lemma 2 (one cell update, lines L5 and L6). Let be a FULL cell and . After one update of , its divergence is multiplied by , and the kinetic energy changes by
So for the energy never increases, and for an interior cell () ends with zero divergence.
Proof. Line L5 sets with , which is equation 7 of the paper for in 2D. Line L6 adds to the outward velocity of each open face (it adds to and subtracts from , and the outward direction of the left face is ). That amount is . The wall faces do not change. So the new sum of outward velocities is . For the energy, let be the outward velocities of the open faces, with (the wall faces carry 0). Each becomes , and no other face changes. Then
which is the formula. With and we have , so .
The update is a step of successive over-relaxation on the pressure Poisson system, with the factor in place of . For an interior cell the two are the same. Near a wall , so a cell with two open faces needs to zero its divergence in one update. The paper's range keeps every in .
Theorem 1 (the pressure iteration is a projection, lines L4 to L7). Let be the face field after lines L2 and L3, and let be the set of FULL cells. For each let be the face field that is in the outward direction on each open face of and 0 elsewhere, so that . Let be the span of the . If , the sweeps of line L4 converge linearly to
the orthogonal projection of onto the fields with zero divergence on every FULL cell. This is the field of least kinetic energy among , and it is the same field that macgrid.project gives with , 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 changes by a multiple of , so every iterate lies in . A field has zero divergence on all FULL cells exactly when for all , that is, when . The set has the single point , and by the Pythagorean rule it has the least norm in .
Let be the error. Since and , the update of Lemma 2 is , so , where is the orthogonal projection onto . Then . For we have , since on a grid of at least 2 by 2 cells. Let be the product of these maps over one sweep. maps into , and . If , then each factor keeps the norm, so at each stage, so no stage changes , and for all . Then . The unit sphere of the finite-dimensional space is compact, so , and after sweeps. The divergence of each FULL cell is , so it goes to 0 and line L7 stops after finitely many sweeps for any .
For the helper, write its projection as with . On an open face from a FLUID cell to a neighbor , the outward component of is , with for an AIR cell. So , and the helper proves that has zero divergence on every FLUID cell, so . 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 . Hence . Lines L5 and L6 add to and move by , so the iterate is with the accumulated , the same form. The Gram matrix is the 5-point matrix of the helper: on the diagonal and for two FULL neighbors. If each connected group of FULL cells touches a SURFACE cell, that matrix is positive definite, the are linearly independent, and the coefficients of in this basis are unique. Then the accumulated converges to the pressure of the helper. In a closed box the of a closed group sum to zero, and the two pressures can differ by a constant on that group.
The tests compare the two methods at : the velocities agree to about in a closed 16 by 16 box and in a 10 by 10 box with a free surface, and the pressures agree to 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 for the open face. Two faces on different axes: each open face copies the face opposite it, so and , and both differences are 0. This is the paper's rule and separately. Two faces on the same axis, a case the paper does not state: the code sets them to with , 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.
Lemma 4 (hydrostatic rest, lines L2 and L3). Let all velocities be 0, let the FULL cells fill the rows and the SURFACE cells fill row , and let 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 face between two FULL rows, line L3 gives . On the face between row and the SURFACE row, the SURFACE cell has and the same sum is 0. On a face both pressures are equal. So is 0 below row . The face between the SURFACE row and the EMPTY row gets . 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 .
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 . The paper gives no proof of this property.
Theorem 2 (the explicit step has a limit). The paper states the limit 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 and :
- The viscous term alone, in 2D, is stable if and only if .
- In 1D, central advection and the viscous term together are stable if and only if .
- With , central advection is unstable at every . Over a time , the growth factor is at most .
Proof. Each part is a von Neumann analysis: a Fourier mode is multiplied by a factor per step, and the step is stable if and only if for all modes.
- The 5-point update has , which takes all values in . The least is , at the checkerboard . So if and only if .
- Central differences give . Put , so . Then , and
The bracket is linear in , so it is on exactly when it is at both ends. As the condition is , and at it is , that is . 3. With , for and . After steps, .
So a small step keeps the growth small even without viscosity, and the second condition, , can be stronger than equation 3 when 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 falls to of its size after 30 steps at , to at , and grows by a factor of about at .
Lemma 5 (markers, line L9). Each marker moves by 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 . No marker is created or removed.
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 be the number of cells and the number of markers. Labels, the new velocity, the surface rules and the extra velocity layer cost , and the markers cost . One pressure sweep costs , so the iteration costs for sweeps. From a cold start on an by grid, grows with , about as for and as at the best , which are the rates of Gauss-Seidel and optimal SOR on the Poisson equation. The extra space is .
The total cost to a fixed time is the cost per step times , and the explicit step bounds by both and about . Halving in 3D multiplies the cells by 8 and at least halves .
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 it stops early, so each FULL cell keeps a divergence up to .
- 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 in 2D (and in 3D), and central advection needs viscosity or a small step. Check all limits each step.
- Too few sweeps. A loose leaves divergence, which shows as liquid that gains or loses volume.
- out of range. For an interior cell update can increase the energy, and the iteration can diverge. At 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.
# 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
- 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)
- 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
- 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.
| 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 NBGCFG Edit this page History Report an error Markdown