Algorithmcore
Tessendorf FFT ocean synthesis
Also called FFT ocean waves, statistical ocean wave synthesis.
Fill a frequency grid with random amplitudes from an ocean spectrum such as Phillips, advance phases by the dispersion relation, and invert by FFT.
- Time
- O(N^2 log N) frameO(N^2) setup
- Space
- O(N^2) extra
- Where
- N = the number of grid points along one side of the patch
- Model
- Real RAM
- Properties
- deterministicnot exactnot needs simulationperiodicreal output
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jerry Tessendorf, Gary Mastin, Peter Watterberg, John Mareda, 2001
FFT ocean synthesis makes an animated patch of deep ocean as a sum of many thousands of sine waves, one for each point of a frequency grid. Each wave gets a random amplitude whose size comes from an ocean wave spectrum, often the Phillips spectrum, and a speed from the deep water dispersion relation . One inverse fast Fourier transform per frame then gives the heights at all grid points in time. Mastin, Watterberg and Mareda (1987) used this idea for images of the sea, and Tessendorf (2001) made it a standard method for ocean surfaces in film and games, with the motion in time and a horizontal "choppy" displacement. There is no simulation: each frame comes from a closed formula, and the patch repeats in space, so it tiles.
In plain words
The sea far from the coast looks like many waves of different lengths that run in different directions and pass through each other. Long waves run faster than short ones. The method picks a large set of wave lengths and directions on a regular grid, gives each one a random size, with more size for the waves that the wind makes most, and lets each wave run at its own speed. To find the height of the water at every point of the grid, it adds up all the waves, and the fast Fourier transform does this sum for all points at once. A small sideways push of each point makes the crests sharper.
The problem
The input is the patch size (m), the grid size (a power of 2), the wind direction and speed (m/s), a spectrum scale , gravity m/s², a random seed, the frame times and a choppiness . The output, for each frame, is the height and the horizontal displacement at the grid points , . The wave vectors are for the signed indices , and
The initial amplitudes are with independent standard normal . The Phillips spectrum, in the form of Tessendorf, is
The dispersion relation is the law for small waves on deep water. The Phillips spectrum is a fit, not a law: it approximates the spectrum of a wind sea in deep water, with the fall of the equilibrium range of Phillips (1958) at short waves, a cut at waves longer than about , the largest waves that a steady wind of speed can raise, and a factor that removes waves that run across the wind. This is one method for fluid simulation for animation.
The algorithm
FFT-OCEAN(L, N, ŵ, V, A, seed, times, λ)- 1
for each k on the grid: h₀(k) ← (ξ_r + i ξ_i)(P(k)/2)^½, with ξ from the seeded generator - 2
for each frame time t - 3
for each k: H(k, t) ← h₀(k) e^{iω(k)t} + conj(h₀(-k)) e^{-iω(k)t} - 4
h ← inverse 2D FFT of H - 5
D ← inverse 2D FFT of -i λ (k/|k|) H - 6
output the points x + D with the heights h
Line L1 runs once. It draws two normal numbers for each grid point, so a fixed seed gives the same ocean each time. The code sets to 0 on the row and the column of the index , where and fall on the same grid point; this keeps the displacement of line L5 real, and it is a choice of this code. Line L3 moves each wave forward in time: the factor turns its phase at the rate of the dispersion relation, and the second term is the partner wave that makes . That symmetry makes the height real. Line L4 is the inverse 2D DFT, done by a 1D FFT on each row and then on each column, with no factor . Line L5 is optional: it moves each point toward the crests and away from the troughs, which makes the crests sharp and the troughs flat, as a Gerstner wave does. The code writes its own radix-2 FFT, and the test compares it with a direct sum.
Example
Take m, m/s (so m), the wind along , , seed 3, and . For each , the table gives the largest imaginary part of the computed height, the largest difference from a direct evaluation of the sum, the measured root mean square height, the expected value from the proof, and the time of one height field in this pure Python code.
| max (m) | max difference from the direct sum (m) | measured RMS height (m) | expected RMS height (m) | FFT time (s) | direct sum time (s) | |
|---|---|---|---|---|---|---|
| 8 | 3.5e-16 | 1.3e-15 | 0.535 | 0.475 | 0.0001 | 0.002 |
| 16 | 3.7e-16 | 2.2e-15 | 0.533 | 0.504 | 0.0005 | 0.029 |
| 32 | 3.6e-16 | 4.0e-15 | 0.622 | 0.510 | 0.002 | 0.88 |
| 64 | 7.3e-16 | not run | 0.769 | 0.512 | 0.014 | not run |
The imaginary part is rounding only, and the FFT gives the same heights as the direct sum. The measured RMS height of one random ocean differs from the expected value because a few long waves near the peak of the spectrum carry most of the energy. The direct sum costs terms, so it is several hundred times slower at .
One wave of wavelength 10 m has rad/m, rad/s, the period s and the phase speed m/s. On this patch it is the wave of index 10, and it needs .
Correctness
The proof shows these facts in exact arithmetic, and the tests check them:
- FFT. The radix-2 FFT of the code equals the DFT.
- Real height. for every and , so the inverse DFT is real. With the Nyquist row and column set to 0, the displacement is real too.
- The sum. At the grid points, the inverse 2D DFT of line L4 equals the sum with the signed wave vectors.
- One wave. A single gives the height , a cosine wave that runs at the speed .
- Statistics. The mean height is 0, and the expected square height is at every point and every time.
Whether the result looks like a real sea is not a claim of this page; it depends on the spectrum.
Proof: The FFT, the real height and the statistics of FFT ocean synthesisfull
We use the notation of the page, with exact arithmetic. The grid indices are with a power of 2, and the signed index is for and otherwise, so . The wave vector of is , and means the index . For every index pair except the Nyquist row and column ( or ), . On the Nyquist row and column the code sets , so there by line L3. The grid points are .
The FFT
Claim 1. For a power of 2, fft(a) returns with , and with for the inverse.
Proof. For the code returns . For , split the sum into the even and odd : and for , where and are the DFTs of length of the even and odd entries, because and . The bit reversal puts the even entries in the first half and the odd entries in the second half, each half again in bit reversed order. By induction on the length, after the passes with block sizes up to , the two halves hold and . The last pass, with block size , computes with for , which is the split above.
The 2D transform of the code applies Claim 1 to each row and then to each column, which is the 2D DFT because the 2D kernel is the product of two 1D kernels.
The height is real
Claim 2. for every index and every .
Proof. depends on only, and on every index. So , and . These are equal.
Claim 3. At the grid points, the inverse 2D DFT of line L4 equals , and this value is real.
Proof. because and , so the sum is the inverse DFT of Claim 1 with no factor. For its conjugate, . Put and , a bijection of the indices: by Claim 2 the term becomes , so .
Claim 4. The displacement of line L5 is real.
Proof. Let for and . Off the Nyquist row and column, , so by Claim 2. On the Nyquist row and column, , so at both and . So has the symmetry of Claim 2 in each component, and the argument of Claim 3 makes its inverse DFT real.
One wave
Claim 5. If is 0 except at one index off the Nyquist row and column with , then , a cosine wave that runs in the direction at the speed .
Proof. Only and are not 0. With , the sum is , which is twice the real part. The phase is constant on points that move with the velocity .
In the same way, each gives a wave in the direction , and each term gives one in the direction .
Statistics
Claim 6. The mean of over the grid points is 0, and for every grid point and every , and , summed over the indices off the Nyquist row and column.
Proof. , so and ; the mean over the grid is , since for . The values are independent for different indices, with , and . So . Since is real, . If , and depend on disjoint sets of independent values with mean 0, so . If , , because and are independent with mean 0 and is even. If , then and . So only the terms remain, and they give , with no dependence on or .
The peak of the spectrum
Claim 7. Along the wind (), is largest at .
Proof. With , , whose derivative is positive for and negative after.
Complexity
Line L1 costs once. Each frame costs for line L3 and for each 2D FFT of lines L4 and L5: row transforms and column transforms of length . The memory is . A direct sum would cost per frame. The FFTs are the main cost, and they run well on a GPU.
Properties
- Periodic. The height is periodic with the period in and in , because every wave vector is a multiple of (proved). The patch tiles with no seam, but the repetition can show from far away.
- No simulation. Each frame comes from and alone, so any frame can be made at once, in any order (proved from the formula).
- Dispersion. Each wave runs at the deep water phase speed , so long waves overtake short ones (a law of the model).
- Stationary statistics. The expected square height does not depend on (proved). One random ocean still changes its RMS height a little in time (measured).
- Both directions. , so the code makes as many waves that run against the wind as with it (proved from the formula).
- Peak. Along the wind, is largest at , the wavelength , which is 90.6 m for m/s (proved).
Variants and improvements
- Other spectra. Measured ocean spectra such as JONSWAP or Pierson-Moskowitz in place of Phillips give other shapes of the sea. Each is a fit to measurements.
- Finite depth. for the depth slows the long waves. The code has this as an option of its dispersion function.
- Looping in time. Rounding each to a multiple of makes the animation repeat with the period .
- Small wave cut. A factor removes waves much shorter than ; the code has it as the option
small. - One direction. Setting for removes the waves that run against the wind.
- Cascades. Several patches of different sizes, added together, hide the repetition of one patch.
- Normals and foam. The slope is one more inverse FFT of . The Jacobian of falls below 0 where the choppy surface folds, which is a common place to put foam.
When to use it
Use FFT ocean synthesis for open deep water seen from a ship, a plane or a shore far away, where the waves are not affected by objects. For a few wave trains with direct control, Gerstner waves are simpler. For water that reacts to objects or to a coast, use height field water or the shallow water equations, maybe on top of this method.
Pitfalls
- Height not real. If line L3 uses only , without the partner term, is not Hermitian and the inverse FFT has a large imaginary part.
- Wrong wave vectors. The FFT stores the negative frequencies in the upper half of the indices. Using the index in place of for in lines L1 and L3 gives wrong speeds and wrong directions.
- The Nyquist row. At the index , and are the same grid point, and the factor of line L5 is not odd there, so the displacement gets an imaginary part. Set to 0 there, as the code does.
- Scale of the FFT. Some FFT libraries divide the inverse by . Then the amplitudes in line L1 must be multiplied by , or the waves are far too small.
- Too much chop. A large in line L5 folds the surface over itself near the crests.
- Patch size and wind speed do not match. The longest wave on the patch is and the shortest is . If the peak wavelength of line L1 is longer than , the main waves of the spectrum are not on the grid.
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/fft-ocean-synthesis/. The authors are listed in prov/6YE8FD.jsonl.
"""FFT ocean synthesis in the style of Tessendorf (2001), on an N by N grid.
The patch has the side length L (m) and is periodic. The wave vector of the
index (n, m) is k = (2 pi n' / L, 2 pi m' / L), where n' = n for n < N/2 and
n' = n - N otherwise (the order of the FFT). The height is
h(x, t) = sum_k H(k, t) exp(i k . x),
H(k, t) = h0(k) exp(i w(k) t) + conj(h0(-k)) exp(-i w(k) t),
with the deep water dispersion w(k) = (g |k|)^(1/2) and the initial
amplitudes h0(k) = (xi_r + i xi_i) (P(k) / 2)^(1/2) from two standard normal
numbers and the Phillips spectrum P. Because H(-k) = conj(H(k)), the height is
real. The sum has no factor 1/N^2, as in the notes of Tessendorf.
This file sets h0 to 0 on the Nyquist row and column (n = N/2 or m = N/2),
so that the choppy displacement is real too. This is a choice of this file.
"""
import cmath
import math
G = 9.81
def fft(a, inverse=False):
"""The radix-2 DFT of a list of complex numbers whose length is a power of 2.
Forward: A_k = sum_n a_n exp(-2 pi i n k / N). Inverse: the same with
exp(+2 pi i n k / N), with no factor 1/N. Returns a new list.
"""
n = len(a)
if n & (n - 1):
raise ValueError("the length must be a power of 2")
out = list(a)
j = 0
for i in range(1, n):
bit = n >> 1
while j & bit:
j ^= bit
bit >>= 1
j |= bit
if i < j:
out[i], out[j] = out[j], out[i]
sign = 1.0 if inverse else -1.0
size = 2
while size <= n:
w_step = cmath.exp(sign * 2j * math.pi / size)
half = size // 2
for start in range(0, n, size):
w = 1.0 + 0.0j
for k in range(start, start + half):
t = w * out[k + half]
out[k + half] = out[k] - t
out[k] = out[k] + t
w *= w_step
size *= 2
return out
def fft2(grid, inverse=False):
"""The 2D DFT of an N by N list of lists, by 1D transforms of the rows and then of the columns."""
rows = [fft(row, inverse) for row in grid]
cols = [fft([rows[i][j] for i in range(len(rows))], inverse) for j in range(len(rows[0]))]
return [[cols[j][i] for j in range(len(cols))] for i in range(len(rows))]
def wave_index(n, size):
"""The signed index n' of the FFT order."""
return n if n < size // 2 else n - size
def wave_vector(n, m, size, length):
return (2.0 * math.pi * wave_index(n, size) / length, 2.0 * math.pi * wave_index(m, size) / length)
def dispersion(k, g=G, depth=None):
"""The angular frequency w of a wave with the wave number k: (g k)^(1/2) in deep water, (g k tanh(k d))^(1/2) at depth d."""
if depth is None:
return math.sqrt(g * k)
return math.sqrt(g * k * math.tanh(k * depth))
def phillips(kx, ky, amplitude, wind, speed, g=G, small=0.0):
"""The Phillips spectrum A exp(-1 / (k L)^2) / k^4 |k_hat . w_hat|^2, with L = V^2 / g.
wind is the wind direction (any length), speed the wind speed V (m/s).
small > 0 multiplies by exp(-k^2 small^2) to remove waves much shorter than small.
P(0) = 0.
"""
k2 = kx * kx + ky * ky
if k2 == 0.0:
return 0.0
big_l = speed * speed / g
wn = math.hypot(wind[0], wind[1])
cos = (kx * wind[0] + ky * wind[1]) / (math.sqrt(k2) * wn)
return amplitude * math.exp(-1.0 / (k2 * big_l * big_l)) / (k2 * k2) * cos * cos * math.exp(-k2 * small * small)
def initial_amplitudes(rng, size, length, amplitude, wind, speed, g=G, small=0.0):
"""h0(k) = (xi_r + i xi_i) (P(k) / 2)^(1/2) for each index, with standard normal xi from rng.gauss."""
h0 = [[0j] * size for _ in range(size)]
for n in range(size):
for m in range(size):
xr, xi = rng.gauss(0.0, 1.0), rng.gauss(0.0, 1.0)
if n == size // 2 or m == size // 2:
continue
kx, ky = wave_vector(n, m, size, length)
p = phillips(kx, ky, amplitude, wind, speed, g, small)
h0[n][m] = complex(xr, xi) * math.sqrt(p / 2.0)
return h0
def spectrum_at(h0, size, length, t, g=G):
"""H(k, t) = h0(k) exp(i w t) + conj(h0(-k)) exp(-i w t) for each index."""
out = [[0j] * size for _ in range(size)]
for n in range(size):
for m in range(size):
kx, ky = wave_vector(n, m, size, length)
w = dispersion(math.hypot(kx, ky), g)
e = cmath.exp(1j * w * t)
out[n][m] = h0[n][m] * e + h0[(-n) % size][(-m) % size].conjugate() * e.conjugate()
return out
def height_field(h0, size, length, t, g=G):
"""The complex heights at the grid points x = (a L / N, b L / N). The imaginary part is 0 up to rounding."""
spec = spectrum_at(h0, size, length, t, g) # @line L3
return fft2(spec, inverse=True) # @line L4
def choppy_displacement(h0, size, length, t, lam=1.0, g=G):
"""The horizontal displacement D(x) = sum_k -i lam (k / |k|) H(k, t) exp(i k . x), as two complex grids."""
spec = spectrum_at(h0, size, length, t, g)
sx = [[0j] * size for _ in range(size)]
sy = [[0j] * size for _ in range(size)]
for n in range(size):
for m in range(size):
kx, ky = wave_vector(n, m, size, length)
k = math.hypot(kx, ky)
if k > 0.0:
sx[n][m] = -1j * lam * kx / k * spec[n][m]
sy[n][m] = -1j * lam * ky / k * spec[n][m]
return fft2(sx, inverse=True), fft2(sy, inverse=True) # @line L5
def synthesize(rng, size, length, amplitude, wind, speed, times, lam=1.0, g=G):
"""The ocean patch at each time in times: a list of (height, dx, dy) real grids."""
h0 = initial_amplitudes(rng, size, length, amplitude, wind, speed, g) # @line L1
frames = []
for t in times: # @line L2
h = height_field(h0, size, length, t, g)
dx, dy = choppy_displacement(h0, size, length, t, lam, g)
frames.append(([[z.real for z in row] for row in h], [[z.real for z in row] for row in dx],
[[z.real for z in row] for row in dy])) # @line L6
return frames
test_fft_ocean_synthesis.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fft-ocean-synthesis/. The authors are listed in prov/6YE8FD.jsonl.
import cmath
import math
import random
import unittest
import fft_ocean_synthesis as fo
SIZE = 16
LENGTH = 100.0
WIND = (1.0, 0.5)
SPEED = 10.0
AMP = 1e-3
def direct_dft(a, inverse=False):
n = len(a)
s = 1.0 if inverse else -1.0
return [sum(a[j] * cmath.exp(s * 2j * math.pi * j * k / n) for j in range(n)) for k in range(n)]
def direct_height(spec, size, length, x, y):
total = 0j
for n in range(size):
for m in range(size):
kx, ky = fo.wave_vector(n, m, size, length)
total += spec[n][m] * cmath.exp(1j * (kx * x + ky * y))
return total
class TestFFT(unittest.TestCase):
def test_fft_equals_direct_dft(self):
rng = random.Random(1)
for n in (1, 2, 4, 8, 32):
a = [complex(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)]
for inverse in (False, True):
fast = fo.fft(a, inverse)
slow = direct_dft(a, inverse)
self.assertLess(max(abs(p - q) for p, q in zip(fast, slow)), 1e-12)
self.assertEqual([abs(z) for z in fo.fft([1, 0, 0, 0])], [1.0] * 4)
def test_fft_round_trip(self):
rng = random.Random(2)
a = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(64)]
back = [z / 64 for z in fo.fft(fo.fft(a), inverse=True)]
self.assertLess(max(abs(p - q) for p, q in zip(a, back)), 1e-12)
def test_bad_length(self):
with self.assertRaises(ValueError):
fo.fft([0j] * 6)
class TestOcean(unittest.TestCase):
def setUp(self):
self.h0 = fo.initial_amplitudes(random.Random(7), SIZE, LENGTH, AMP, WIND, SPEED)
def test_dispersion_check_values(self):
k = 2 * math.pi / 10.0
w = fo.dispersion(k, 9.81)
self.assertAlmostEqual(k, 0.628319, places=6)
self.assertAlmostEqual(w, 2.482701, places=6)
self.assertAlmostEqual(2 * math.pi / w, 2.530786, places=6)
self.assertAlmostEqual(w / k, 3.951342, places=6)
self.assertAlmostEqual(fo.dispersion(k, 9.81, depth=1000.0), w, places=12)
self.assertLess(fo.dispersion(k, 9.81, depth=1.0), w)
def test_spectrum_is_hermitian(self):
for t in (0.0, 1.3, 17.0):
spec = fo.spectrum_at(self.h0, SIZE, LENGTH, t)
for n in range(SIZE):
for m in range(SIZE):
other = spec[(-n) % SIZE][(-m) % SIZE].conjugate()
self.assertLess(abs(spec[n][m] - other), 1e-15 + 1e-12 * abs(spec[n][m]))
def test_height_is_real_and_equals_direct_sum(self):
for t in (0.0, 2.5):
spec = fo.spectrum_at(self.h0, SIZE, LENGTH, t)
h = fo.height_field(self.h0, SIZE, LENGTH, t)
self.assertGreater(max(abs(z.real) for row in h for z in row), 0.05)
self.assertLess(max(abs(z.imag) for row in h for z in row), 1e-12)
for a in range(SIZE):
for b in range(SIZE):
x, y = a * LENGTH / SIZE, b * LENGTH / SIZE
self.assertLess(abs(h[a][b] - direct_height(spec, SIZE, LENGTH, x, y)), 1e-12)
def test_choppy_displacement_is_real(self):
dx, dy = fo.choppy_displacement(self.h0, SIZE, LENGTH, 3.0, lam=0.8)
self.assertLess(max(abs(z.imag) for g in (dx, dy) for row in g for z in row), 1e-12)
self.assertGreater(max(abs(z.real) for row in dx for z in row), 0.01)
def test_single_mode_is_a_moving_cosine(self):
n, m = 3, 1
a = complex(0.2, -0.1)
h0 = [[0j] * SIZE for _ in range(SIZE)]
h0[n][m] = a
kx, ky = fo.wave_vector(n, m, SIZE, LENGTH)
w = fo.dispersion(math.hypot(kx, ky))
for t in (0.0, 0.7, 4.0):
h = fo.height_field(h0, SIZE, LENGTH, t)
for i in range(SIZE):
for j in range(SIZE):
x, y = i * LENGTH / SIZE, j * LENGTH / SIZE
want = 2 * (a * cmath.exp(1j * (kx * x + ky * y + w * t))).real
self.assertAlmostEqual(h[i][j].real, want, places=12)
def test_phillips(self):
self.assertEqual(fo.phillips(0.0, 0.0, 1.0, WIND, SPEED), 0.0)
self.assertAlmostEqual(fo.phillips(-0.5, 1.0, 1.0, WIND, SPEED), 0.0, places=15)
p = fo.phillips(0.3, 0.1, 1.0, WIND, SPEED)
self.assertAlmostEqual(p, fo.phillips(-0.3, -0.1, 1.0, WIND, SPEED), places=15)
self.assertLess(fo.phillips(0.3, 0.1, 1.0, WIND, SPEED, small=1.0), p)
def test_seed_and_frames(self):
f1 = fo.synthesize(random.Random(5), 8, 50.0, AMP, WIND, SPEED, [0.0, 1.0])
f2 = fo.synthesize(random.Random(5), 8, 50.0, AMP, WIND, SPEED, [0.0, 1.0])
self.assertEqual(f1, f2)
self.assertEqual(len(f1), 2)
mean = sum(sum(row) for row in f1[1][0]) / 64
self.assertLess(abs(mean), 1e-12)
if __name__ == "__main__":
unittest.main()
History
Mastin, Watterberg and Mareda (1987) made images of the sea by filtering white noise with an ocean wave spectrum and then inverting it with an FFT. Tessendorf wrote the method in the form used today in his SIGGRAPH course notes "Simulating Ocean Water", with the Phillips spectrum, the time evolution by the dispersion relation and the choppy displacement. The notes appeared in several versions; this page cites the 2001 version. The method is now a common way to make ocean surfaces in films and games.
References
- Simulating Ocean Water, the sections on the statistical wave model, the Phillips spectrum, the time evolution and choppy waves
- Gary Mastin, Peter Watterberg and John Mareda, Fourier synthesis of ocean scenes, IEEE Computer Graphics and Applications 7(3), 16-23, 1987, the whole paper (white noise filtered by an ocean wave spectrum and inverted by FFT)
- O. M. Phillips, The equilibrium range in the spectrum of wind-generated waves, Journal of Fluid Mechanics 4(4), 426-434, 1958, the equilibrium range of the spectrum (general locator)
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 6YE8FD Edit this page History Report an error Markdown