Algorithm Search⌘K

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)
Properties
conserves volumedeterministicnot exactnot overhanging surfacesunconditionally stable
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 (gd)1/2(g d)^{1/2} for the water depth dd. 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 nxn_x by nyn_y cells of size Δx\Delta x, the water heights hh at the current step and h−h^- at the last step, the depth dd of each cell, gravity g=9.81g = 9.81 m/s², the step Δt\Delta t and a damping τ∈[0,1]\tau \in [0, 1]. The output is the height field at the next step. The equation is

∂2h∂t2=∇⋅(g d ∇h),\frac{\partial^2 h}{\partial t^2} = \nabla\cdot(g\,d\,\nabla h),

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 d=h−bd = h - b above the ground bb is taken as known in each step. This is one method for fluid simulation for animation.

The algorithm

  1. HEIGHT-FIELD-STEP(h, h⁻, d, Δt)
  2. 1for each cell k: r_k ← h_k + (1 - τ)(h_k - h⁻_k)
  3. 2s ← 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
  4. 3for each row: solve z_k + Σ_l e_kl (z_k - z_l) = r_k over the x neighbors l, by the Thomas algorithm
  5. 4for each column: solve h'_k + Σ_l e_kl (h'_k - h'_l) = z_k over the y neighbors l, by the Thomas algorithm
  6. 5return h', h

Line L1 extrapolates the motion of the last step, h+(h−h−)h + (h - h^-), with a damping τ\tau that removes a part of the velocity. Line L2 computes the coupling of each pair of neighbors, the finite difference form of g dg\,d on the face between them. A dry cell, with d=0d = 0, 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 (I+Ax)(I+Ay)h′=r(I + A_x)(I + A_y)h' = r, where AxA_x and AyA_y are the 1D operators of the two directions, and this is a split form of the implicit step (I+Ax+Ay)h′=r(I + A_x + A_y)h' = r. 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 d=max⁡(h−b,0)d = \max(h - b, 0) 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 (Δx=0.025\Delta x = 0.025 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 (gd)1/2=3.13209(g d)^{1/2} = 3.13209 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.

Δt\Delta t (s) Courant number cΔt/Δxc\Delta t/\Delta x 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 Δt\Delta t and Δx\Delta x; 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 τ\tau. So if hh and h−h^- have the same volume, all later steps have it too. The test checks this exactly with fractions.
  • Energy. For a constant depth and τ=0\tau = 0, the discrete energy ∣h′−h∣2+12(⟨Mh′,h′⟩+⟨Mh,h⟩)|h' - h|^2 + \frac12(\langle Mh', h'\rangle + \langle Mh, h\rangle) with M=Ax+Ay+AxAyM = A_x + A_y + A_x A_y does not increase, for any Δt\Delta t. 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 (gd)1/2(g d)^{1/2} 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, (Aq)k=∑lekl(qk−ql)(A q)_k = \sum_l e_{kl}(q_k - q_l), where ll runs over the neighbors of kk in that direction, ekl=elk≥0e_{kl} = e_{lk} \ge 0, and ekl=0e_{kl} = 0 if kk or ll is dry. Lines L3 and L4 solve (I+Ax)z=r(I + A_x)z = r and (I+Ay)h′=z(I + A_y)h' = z. We write ⟨p,q⟩=∑kpkqk\langle p, q\rangle = \sum_k p_k q_k.

The line solves

Claim 1. On each line, the matrix of I+AI + A is tridiagonal and strictly diagonally dominant, and the Thomas algorithm of the code computes its solution without a division by 0.

Proof. Row kk has the diagonal ak=1+∑lekla_k = 1 + \sum_l e_{kl} and the entries −ekl-e_{kl} for its at most two neighbors on the line, so ∣ak∣=1+∑lekl>∑lekl|a_k| = 1 + \sum_l e_{kl} > \sum_l e_{kl}. Write bkb_k for the entry left of the diagonal and ckc_k for the one right of it, so ∣ak∣>∣bk∣+∣ck∣|a_k| > |b_k| + |c_k|. The forward sweep computes γ0=c0/a0\gamma_0 = c_0/a_0 and μk=ak−bkγk−1\mu_k = a_k - b_k\gamma_{k-1}, γk=ck/μk\gamma_k = c_k/\mu_k. By induction ∣γk−1∣<1|\gamma_{k-1}| < 1, so ∣μk∣≥∣ak∣−∣bk∣>∣ck∣≥0|\mu_k| \ge |a_k| - |b_k| > |c_k| \ge 0, so μk≠0\mu_k \ne 0 and ∣γk∣<1|\gamma_k| < 1. The sweep is Gaussian elimination without pivoting: row kk minus bk/μk−1b_k/\mu_{k-1} times the reduced row k−1k-1 removes the entry left of the diagonal and leaves the pivot μk\mu_k. The back substitution then solves the upper bidiagonal system. □\square

Volume

Claim 2. ∑k(Aq)k=0\sum_k (Aq)_k = 0 for every qq, so each of lines L3 and L4 keeps the sum of the values.

Proof. Each unordered pair {k,l}\{k, l\} adds ekl(qk−ql)e_{kl}(q_k - q_l) to row kk and elk(ql−qk)e_{lk}(q_l - q_k) to row ll, and these cancel because ekl=elke_{kl} = e_{lk}. From (I+A)z=r(I + A)z = r, ∑kzk=∑krk−∑k(Az)k=∑krk\sum_k z_k = \sum_k r_k - \sum_k (Az)_k = \sum_k r_k. □\square

Claim 3. If ∑khk=∑khk−=V\sum_k h_k = \sum_k h^-_k = V, then ∑khk′=V\sum_k h'_k = V, for any depths and any τ\tau. So the volume of every later step is VΔx2V\Delta x^2.

Proof. By line L1, ∑krk=V+(1−τ)(V−V)=V\sum_k r_k = V + (1 - \tau)(V - V) = V. By Claim 2 for lines L3 and L4, ∑khk′=V\sum_k h'_k = V. The next step gets the pair (h′,h)(h', h), which again has two equal sums, and induction gives the rest. □\square

Energy

Claim 4. Let every cell have the same depth d>0d > 0, and let τ=0\tau = 0. Let M=Ax+Ay+AxAyM = A_x + A_y + A_x A_y and E(p,q)=∣p−q∣2+12(⟨Mp,p⟩+⟨Mq,q⟩)E(p, q) = |p - q|^2 + \frac12(\langle Mp, p\rangle + \langle Mq, q\rangle). Then E(h′,h)≤E(h,h−)E(h', h) \le E(h, h^-), for any Δt\Delta t.

Proof. ⟨Aq,q⟩=∑{k,l}ekl(qk−ql)2≥0\langle A q, q\rangle = \sum_{\{k, l\}} e_{kl}(q_k - q_l)^2 \ge 0 and AA is symmetric, so AxA_x and AyA_y are symmetric positive semidefinite. With one depth, ekl=2sde_{kl} = 2sd for every pair, so Ax=Lx⊗IA_x = L_x\otimes I and Ay=I⊗LyA_y = I\otimes L_y for the 1D matrices LxL_x and LyL_y of a line. These commute, and AxAy=Lx⊗LyA_x A_y = L_x\otimes L_y is symmetric positive semidefinite, because the eigenvalues of a Kronecker product are the products of the eigenvalues. So MM is symmetric positive semidefinite. Lines L3 and L4 give (I+Ax)(I+Ay)h′=r(I + A_x)(I + A_y)h' = r, which is (I+M)h′=2h−h−(I + M)h' = 2h - h^-, or

(h′−h)−(h−h−)=−Mh′.(h' - h) - (h - h^-) = -Mh'.

Take the inner product with (h′−h)+(h−h−)=h′−h−(h' - h) + (h - h^-) = h' - h^-. The left side is ∣h′−h∣2−∣h−h−∣2|h' - h|^2 - |h - h^-|^2. For a symmetric MM, ⟨Mh′,h′−h−⟩=12(⟨Mh′,h′⟩−⟨Mh−,h−⟩)+12⟨M(h′−h−),h′−h−⟩\langle Mh', h' - h^-\rangle = \frac12(\langle Mh', h'\rangle - \langle Mh^-, h^-\rangle) + \frac12\langle M(h' - h^-), h' - h^-\rangle. So

E(h′,h)−E(h,h−)=∣h′−h∣2−∣h−h−∣2+12⟨Mh′,h′⟩−12⟨Mh−,h−⟩=−12⟨M(h′−h−),h′−h−⟩≤0.□E(h', h) - E(h, h^-) = |h' - h|^2 - |h - h^-|^2 + \tfrac12\langle Mh', h'\rangle - \tfrac12\langle Mh^-, h^-\rangle = -\tfrac12\langle M(h' - h^-), h' - h^-\rangle \le 0. \qquad\square

EE bounds ∣h′−h∣2|h' - h|^2 and ⟨Mh,h⟩\langle Mh, h\rangle for all steps, so the differences of neighbor heights and the change per step stay bounded for every Δt\Delta t: this is the unconditional stability of the page. The loss 12⟨M(h′−h−),h′−h−⟩\frac12\langle M(h' - h^-), h' - h^-\rangle is the damping of the implicit step; it is larger for larger Δt\Delta t and for short waves, where MM is large. For a depth that varies, AxA_x and AyA_y do not commute in general, MM is not symmetric, and the proof does not apply.

Rest

Claim 5. Let h=h−h = h^-, let hh have the same value on all wet cells of each connected wet region, and let the dry cells have any heights. Then h′=hh' = h.

Proof. Then r=hr = h. For a dry cell, every ekle_{kl} is 0, so its row is zk=rkz_k = r_k. For a wet cell, its neighbors with ekl>0e_{kl} > 0 are wet and in the same region, so they have the same value of rr, and z=rz = r satisfies the row. By Claim 1 the system has one solution, so z=rz = r, and in the same way h′=z=hh' = z = h. ■\blacksquare

Complexity

Each row solve and each column solve is linear in its length, so a step costs O(nxny)O(n_x n_y) time, about a constant number of passes over the grid. The memory is O(nxny)O(n_x n_y). 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 Δt\Delta t (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 cΔt/Δxc\Delta t/\Delta x is below a limit of order 1.
  • No splitting. Solving (I+Ax+Ay)h′=r(I + A_x + A_y)h' = r 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 τ=0\tau = 0 in line L1, only the implicit damping removes energy, and small waves can run for a long time. A small τ\tau 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, h−bh - b 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.

height_field_water.pyI0RawGitHub
# 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

  1. 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)
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.step
  • 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
  • at least three sources
  • a scene preset for the example