Algorithmcore
Height field water
Also called Kass-Miller water.
Simulate a water surface as a height grid evolving by a linearized shallow water wave equation with implicit steps, cheap enough for real time.
- Time
- O(c) step
- Space
- O(c) extra
- Where
- c = the number of grid cells (n_x times n_y)
- Model
- Real RAM
- Properties
- conserves volumedeterministicnot exactnot overhanging surfacesunconditionally stable
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Michael Kass, Gavin Miller, 1990
Height field water stores the water surface as one height per cell of a 2D grid, so the water is a sheet with no overhangs and no splashes. The heights move by a linearized form of the shallow water equations, a wave equation whose wave speed is for the water depth . Kass and Miller (1990) made it fast and stable with implicit steps: each step is one tridiagonal solve along each row and one along each column. The step size is then limited by the accuracy that the animation needs, not by stability, and the volume of the water is kept exactly. The method suits ponds, rivers and wakes in real time.
In plain words
The water is a grid of columns, and each column has a height. Where a column is higher than its neighbors, water flows out of it, and where it is lower, water flows in. So a bump in the surface spreads out as waves, and in deep water the waves run faster. Each step works out the new heights of a whole row of columns at once, and then of a whole column of the grid at once. Doing it all at once in this way keeps the method calm even with long steps, and no water is lost or made.
The problem
The input is a grid of by cells of size , the water heights at the current step and at the last step, the depth of each cell, gravity m/s², the step and a damping . The output is the height field at the next step. The equation is
with no flow through the border of the grid. It comes from the shallow water equations when the waves are small, the velocity is small, and the depth above the ground is taken as known in each step. This is one method for fluid simulation for animation.
The algorithm
HEIGHT-FIELD-STEP(h, h⁻, d, Δt)- 1
for each cell k: r_k ← h_k + (1 - τ)(h_k - h⁻_k) - 2
s ← g Δt² / (2 Δx²); for each pair of neighbor cells k, l: e_kl ← s (d_k + d_l), or 0 if d_k = 0 or d_l = 0 - 3
for each row: solve z_k + Σ_l e_kl (z_k - z_l) = r_k over the x neighbors l, by the Thomas algorithm - 4
for each column: solve h'_k + Σ_l e_kl (h'_k - h'_l) = z_k over the y neighbors l, by the Thomas algorithm - 5
return h', h
Line L1 extrapolates the motion of the last step, , with a damping that removes a part of the velocity. Line L2 computes the coupling of each pair of neighbors, the finite difference form of on the face between them. A dry cell, with , has no coupling; this rule of the code keeps the water out of dry cells. Lines L3 and L4 are the implicit part. Together they solve , where and are the 1D operators of the two directions, and this is a split form of the implicit step . Each line of the grid is a tridiagonal system, and the Thomas algorithm solves it in linear time. The matrices are strictly diagonally dominant, so the Thomas algorithm needs no pivoting. In a full run, the depth comes from before each step. This follows the idea of Kass and Miller; the code is not claimed to repeat their exact equations.
Example
Take a 1D channel of 10 m with 400 cells ( m), depth 1 m, no damping, and a Gaussian bump of height 0.01 m and width 0.2 m in the middle, at rest. The bump splits into two waves that run to the left and to the right. The exact speed is m/s. After 1 s, the table gives the measured distance of the right crest from the start and its height. Each of the two waves of the exact linear equation would have the height 0.005 m.
| (s) | Courant number | crest distance (m) | crest height (m) |
|---|---|---|---|
| 0.002 | 0.25 | 3.11 | 0.00355 |
| 0.005 | 0.63 | 3.11 | 0.00269 |
| 0.01 | 1.25 | 3.11 | 0.00206 |
| 0.02 | 2.5 | 3.06 | 0.00153 |
| 0.05 | 6.3 | 2.99 | 0.00101 |
The crest position is read to the nearest cell, 0.025 m. The step stays stable far above a Courant number of 1, where an explicit scheme would blow up. The price is damping and a slower wave at large steps: the implicit step removes energy from the short waves, so the crest gets lower and wider.
Correctness
The scheme approximates the wave equation, and its error depends on and ; this page does not bound it. The tests check these facts, and the proof gives the arguments:
- Thomas. The tridiagonal solves equal Gaussian elimination, checked in exact rational arithmetic.
- Volume. Each of lines L3 and L4 keeps the sum of the heights, for any depths and any . So if and have the same volume, all later steps have it too. The test checks this exactly with fractions.
- Energy. For a constant depth and , the discrete energy with does not increase, for any . So the step is stable for any step size.
- Rest. A flat lake, also with islands of dry ground, stays flat.
The wave speed of the example is a measurement, close to for small steps.
Proof: The line solves, the volume and the energy of the height field stepfull
We use the notation of the page, with exact real arithmetic. For one direction, , where runs over the neighbors of in that direction, , and if or is dry. Lines L3 and L4 solve and . We write .
The line solves
Claim 1. On each line, the matrix of is tridiagonal and strictly diagonally dominant, and the Thomas algorithm of the code computes its solution without a division by 0.
Proof. Row has the diagonal and the entries for its at most two neighbors on the line, so . Write for the entry left of the diagonal and for the one right of it, so . The forward sweep computes and , . By induction , so , so and . The sweep is Gaussian elimination without pivoting: row minus times the reduced row removes the entry left of the diagonal and leaves the pivot . The back substitution then solves the upper bidiagonal system.
Volume
Claim 2. for every , so each of lines L3 and L4 keeps the sum of the values.
Proof. Each unordered pair adds to row and to row , and these cancel because . From , .
Claim 3. If , then , for any depths and any . So the volume of every later step is .
Proof. By line L1, . By Claim 2 for lines L3 and L4, . The next step gets the pair , which again has two equal sums, and induction gives the rest.
Energy
Claim 4. Let every cell have the same depth , and let . Let and . Then , for any .
Proof. and is symmetric, so and are symmetric positive semidefinite. With one depth, for every pair, so and for the 1D matrices and of a line. These commute, and is symmetric positive semidefinite, because the eigenvalues of a Kronecker product are the products of the eigenvalues. So is symmetric positive semidefinite. Lines L3 and L4 give , which is , or
Take the inner product with . The left side is . For a symmetric , . So
bounds and for all steps, so the differences of neighbor heights and the change per step stay bounded for every : this is the unconditional stability of the page. The loss is the damping of the implicit step; it is larger for larger and for short waves, where is large. For a depth that varies, and do not commute in general, is not symmetric, and the proof does not apply.
Rest
Claim 5. Let , let have the same value on all wet cells of each connected wet region, and let the dry cells have any heights. Then .
Proof. Then . For a dry cell, every is 0, so its row is . For a wet cell, its neighbors with are wet and in the same region, so they have the same value of , and satisfies the row. By Claim 1 the system has one solution, so , and in the same way .
Complexity
Each row solve and each column solve is linear in its length, so a step costs time, about a constant number of passes over the grid. The memory is . There is no iteration and no tolerance, so the cost per step is fixed, which suits real time.
Properties
- Unconditional stability. The energy does not grow for any (proved for a constant depth). For a depth that varies, the split operators do not commute, and the energy proof does not apply.
- Exact volume. Each solve keeps the sum of the heights (proved).
- Damping. The implicit step damps the waves, more at large steps and for short waves (measured).
- Wave speed. Waves run faster in deep water and slower in shallow water, so waves bend toward a beach and slow down there. This is a property of the equation.
- Height field. The surface is a function of the position, so there are no breaking waves, overhangs or splashes.
Variants and improvements
- Full shallow water. A solver of the shallow water equations with velocities on a staggered grid adds the flow of the water, not only the waves.
- Explicit steps. An explicit step is simpler and damps the waves less, but it is stable only when is below a limit of order 1.
- No splitting. Solving with conjugate gradients removes the splitting error at a higher cost.
- Ocean waves. For deep open water, Gerstner waves or FFT ocean synthesis give waves with no simulation; a height field adds the local response to objects.
- Coupling to particles. Splashes from a particle system on top of the height field give the motion that a height field cannot hold.
When to use it
Use height field water for ponds, pools, rivers and wakes, where the surface has no overhangs and the cost must be small and fixed. For breaking waves and splashes, use a 3D solver such as FLIP or SPH. For deep ocean waves seen from far away, use FFT ocean synthesis.
Pitfalls
- No damping and long runs. With in line L1, only the implicit damping removes energy, and small waves can run for a long time. A small gives calm water.
- Water flowing into dry cells. Without the rule of line L2 for dry cells, a dry cell next to water gets a coupling, and the heights of its ground pull water into it or out of it. The code sets the coupling to 0, which also stops water from flooding dry land.
- Negative depth. With large waves on a shallow bed, can become negative. The depth must be clamped at 0 before line L2.
- Wrong boundary rows. At the border, line L3 has only one neighbor. Using a coupling to a cell outside the grid adds or removes water.
- One pass only. Only line L3, without line L4, gives waves along the rows only.
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/height-field-water/. The authors are listed in prov/CH9SFZ.jsonl.
"""Height field water: the linearized shallow water wave equation with implicit steps.
The water surface is a grid of heights h[i][j] over cells of size dx. The
wave equation is d^2 h / dt^2 = div(g d grad h), with the water depth d. One
step is
r = h + (1 - damping) (h - h_prev),
(I + A_x) z = r (a tridiagonal solve along each row),
(I + A_y) h_new = z (a tridiagonal solve along each column),
where A_x adds e (z_i - z_k) for each x neighbor k of cell i, with
e = g dt^2 (d_i + d_k) / (2 dx^2), or e = 0 if one of the two cells is dry,
and A_y is the same along y. There is no
flow through the border of the grid (Neumann boundary). The scheme follows
the idea of Kass and Miller (1990): implicit steps with tridiagonal solves
along the rows and the columns. It is not claimed to be their exact equations.
The functions work with float or with fractions.Fraction values.
"""
G = 9.81
def thomas(sub, diag, sup, rhs):
"""Solve a tridiagonal system by the Thomas algorithm.
sub[i] is the entry left of the diagonal in row i (sub[0] is not used),
sup[i] the entry right of it (sup[n-1] is not used). No pivoting: the
matrix must be strictly diagonally dominant or symmetric positive definite.
"""
n = len(diag)
c = [0] * n
d = [0] * n
c[0] = sup[0] / diag[0] if n > 1 else 0
d[0] = rhs[0] / diag[0]
for i in range(1, n):
m = diag[i] - sub[i] * c[i - 1]
c[i] = sup[i] / m if i < n - 1 else 0
d[i] = (rhs[i] - sub[i] * d[i - 1]) / m
x = [0] * n
x[n - 1] = d[n - 1]
for i in range(n - 2, -1, -1):
x[i] = d[i] - c[i] * x[i + 1]
return x
def solve_line(values, depths, s):
"""Solve (I + A) z = values on one line, with e_k = s (depths[k] + depths[k + 1]) between neighbors k and k + 1.
e_k is 0 if one of the two cells is dry (depth 0), so no water flows into
or out of a dry cell. This is a choice of this file.
"""
n = len(values)
zero = 0 * s # a zero of the type of s, so that Fraction input gives Fraction output
e = [s * (depths[k] + depths[k + 1]) if depths[k] > 0 and depths[k + 1] > 0 else zero for k in range(n - 1)]
sub = [zero] + [-x for x in e]
sup = [-x for x in e] + [zero]
diag = [1 + (e[k - 1] if k > 0 else zero) + (e[k] if k < n - 1 else zero) for k in range(n)]
return thomas(sub, diag, sup, values)
def step(h, h_prev, depth, dt, dx, g=G, damping=0):
"""One implicit step. h, h_prev and depth are lists of columns, indexed [i][j]. Returns (h_new, h)."""
nx, ny = len(h), len(h[0])
r = [[h[i][j] + (1 - damping) * (h[i][j] - h_prev[i][j]) for j in range(ny)] for i in range(nx)] # @line L1
s = g * dt * dt / (2 * dx * dx) # @line L2
z = [[0] * ny for _ in range(nx)]
for j in range(ny):
row = solve_line([r[i][j] for i in range(nx)], [depth[i][j] for i in range(nx)], s) # @line L3
for i in range(nx):
z[i][j] = row[i]
h_new = [solve_line(z[i], depth[i], s) for i in range(nx)] # @line L4
return h_new, h # @line L5
def water_depth(h, ground):
"""The depth d = max(h - ground, 0) of each cell."""
return [[max(hv - gv, 0) for hv, gv in zip(hc, gc)] for hc, gc in zip(h, ground)]
def simulate(h, ground, dt, dx, steps, g=G, damping=0):
"""Run steps from rest at h, with the depth from the ground updated before each step. Returns the last h."""
h_prev = [list(col) for col in h]
for _ in range(steps):
h, h_prev = step(h, h_prev, water_depth(h, ground), dt, dx, g, damping)
return h
def volume(h, dx):
"""The water volume above the zero level, dx^2 times the sum of the heights."""
return dx * dx * sum(sum(col) for col in h)
def discrete_energy(h, h_prev, depth, dt, dx, g=G):
"""|h - h_prev|^2 + (<M h, h> + <M h_prev, h_prev>) / 2 with M = A_x + A_y + A_x A_y; see the proof page.
The step does not increase it when the depth is the same in every cell.
"""
nx, ny = len(h), len(h[0])
def apply_a(q, axis):
s = g * dt * dt / (2 * dx * dx)
out = [[0.0] * ny for _ in range(nx)]
for i in range(nx):
for j in range(ny):
acc = 0.0
for di, dj in ((1, 0), (-1, 0)) if axis == 0 else ((0, 1), (0, -1)):
k, l = i + di, j + dj
if 0 <= k < nx and 0 <= l < ny and depth[i][j] > 0 and depth[k][l] > 0:
acc += s * (depth[i][j] + depth[k][l]) * (q[i][j] - q[k][l])
out[i][j] = acc
return out
def m_dot(q):
ax = apply_a(q, 0)
ay = apply_a(q, 1)
axy = apply_a(ay, 0)
return sum(q[i][j] * (ax[i][j] + ay[i][j] + axy[i][j]) for i in range(nx) for j in range(ny))
kinetic = sum((h[i][j] - h_prev[i][j]) ** 2 for i in range(nx) for j in range(ny))
return kinetic + 0.5 * (m_dot(h) + m_dot(h_prev))
test_height_field_water.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/height-field-water/. The authors are listed in prov/CH9SFZ.jsonl.
import math
import random
from fractions import Fraction
import height_field_water as hw
def gauss_solve(a, b):
"""Gaussian elimination with exact Fraction arithmetic and row pivoting."""
n = len(b)
m = [list(row) + [b[i]] for i, row in enumerate(a)]
for c in range(n):
p = next(r for r in range(c, n) if m[r][c] != 0)
m[c], m[p] = m[p], m[c]
for r in range(n):
if r != c and m[r][c] != 0:
f = m[r][c] / m[c][c]
m[r] = [x - f * y for x, y in zip(m[r], m[c])]
return [m[i][n] / m[i][i] for i in range(n)]
def test_thomas_matches_gaussian_elimination() -> None:
rng = random.Random(1)
for n in (1, 2, 3, 7):
sub = [Fraction(rng.randint(-5, 5), rng.randint(1, 5)) for _ in range(n)]
sup = [Fraction(rng.randint(-5, 5), rng.randint(1, 5)) for _ in range(n)]
diag = [abs(sub[i]) + abs(sup[i]) + Fraction(rng.randint(1, 9), rng.randint(1, 3)) for i in range(n)]
rhs = [Fraction(rng.randint(-9, 9), rng.randint(1, 4)) for _ in range(n)]
a = [[Fraction(0)] * n for _ in range(n)]
for i in range(n):
a[i][i] = diag[i]
if i > 0:
a[i][i - 1] = sub[i]
if i < n - 1:
a[i][i + 1] = sup[i]
assert hw.thomas(sub, diag, sup, rhs) == gauss_solve(a, rhs)
def test_volume_is_kept_exactly() -> None:
rng = random.Random(2)
nx, ny = 4, 3
h = [[Fraction(rng.randint(8, 12), 10) for _ in range(ny)] for _ in range(nx)]
h_prev = [[x + Fraction(rng.randint(-2, 2), 100) for x in col] for col in h]
shift = (sum(map(sum, h)) - sum(map(sum, h_prev))) / (nx * ny)
h_prev = [[x + shift for x in col] for col in h_prev]
depth = [[Fraction(rng.randint(0, 10), 10) for _ in range(ny)] for _ in range(nx)]
dx, dt = Fraction(1, 10), Fraction(1, 50)
v0 = hw.volume(h, dx)
assert hw.volume(h_prev, dx) == v0
for _ in range(2):
h, h_prev = hw.step(h, h_prev, depth, dt, dx, Fraction(981, 100), Fraction(1, 10))
assert hw.volume(h, dx) == v0
def bump(nx, ny, dx):
return [[1.0 + 0.05 * math.exp(-(((i - 0.4 * nx) ** 2 + (j - 0.5 * ny) ** 2) * dx * dx / 0.06))
for j in range(ny)] for i in range(nx)]
def test_energy_does_not_increase_for_a_constant_depth() -> None:
nx = ny = 12
dx, dt = 0.1, 0.03
h = bump(nx, ny, dx)
h_prev = [list(col) for col in h]
depth = [[1.0] * ny for _ in range(nx)]
e = hw.discrete_energy(h, h_prev, depth, dt, dx)
e0 = e
for _ in range(25):
h_new, h_prev = hw.step(h, h_prev, depth, dt, dx)
h = h_new
e_new = hw.discrete_energy(h, h_prev, depth, dt, dx)
assert e_new <= e * (1.0 + 1e-12)
e = e_new
assert e < e0
def test_wave_speed_is_close_to_the_shallow_water_speed() -> None:
# A measurement: a bump in a channel of depth 1 m splits into two waves with speed (g d)^(1/2) = 3.13209 m/s.
nx, dx, dt = 400, 0.025, 0.01
xs = [(i + 0.5) * dx for i in range(nx)]
h = [[1.0 + 0.01 * math.exp(-((x - 5.0) / 0.2) ** 2)] for x in xs]
h_prev = [list(col) for col in h]
depth = [[1.0] for _ in xs]
for _ in range(100):
h, h_prev = hw.step(h, h_prev, depth, dt, dx)
peak = max((h[i][0], xs[i]) for i in range(nx) if xs[i] > 5.0)[1]
assert abs(math.sqrt(9.81 * 1.0) - 3.13209) < 1e-5
assert abs((peak - 5.0) - 3.13209) < 0.03 * 3.13209
def test_flat_lake_over_rough_ground_stays_flat() -> None:
rng = random.Random(3)
nx, ny, dx = 8, 6, 0.1
ground = [[rng.uniform(0.0, 1.5) for _ in range(ny)] for _ in range(nx)]
h = [[max(1.0, ground[i][j]) for j in range(ny)] for i in range(nx)]
out = hw.simulate(h, ground, 0.02, dx, 10)
assert max(abs(out[i][j] - h[i][j]) for i in range(nx) for j in range(ny)) < 1e-12
def test_simulate_keeps_the_volume_with_a_changing_depth() -> None:
rng = random.Random(4)
nx, ny, dx = 10, 8, 0.1
ground = [[rng.uniform(0.0, 0.5) for _ in range(ny)] for _ in range(nx)]
h = bump(nx, ny, dx)
out = hw.simulate(h, ground, 0.02, dx, 20, damping=0.05)
assert abs(hw.volume(out, dx) - hw.volume(h, dx)) < 1e-12
History
Kass and Miller (1990) presented this method at SIGGRAPH 90. They linearized the shallow water equations, took implicit steps for stability, and split the 2D solve into tridiagonal solves along the rows and the columns. They also let the depth change with the water and the ground, so that waves slow down near a beach. Height fields of this kind are still a common choice for water surfaces in games.
References
- Michael Kass and Gavin Miller, Rapid, stable fluid dynamics for computer graphics, ACM SIGGRAPH Computer Graphics 24(4), 49-57, 1990, the whole paper (the linearized shallow water equation, the implicit step and the tridiagonal solves)
- Fluid Simulation for Computer Graphics, the chapter on shallow water
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 CH9SFZ Edit this page History Report an error Markdown