Back to the coast

Two Oceans Explained

Wind off the land drives dunes into the sea. Waves come the other way and cut them down. Someone walks between the two, towards us, and never arrives. This page describes how that 40 second loop is simulated, lit and drawn, down to the passes of one frame.

Misty coast with turquoise surf on the left, golden dunes on the right and a small figure in a dark coat with footprints behind
Loop
40 s, closes on itself
Coast
480 m, 8 bays of 60 m
Ground
824 × 800 cells of 0.6 m
Sea
360 × 800 cells, live, 120 steps a second
Download
5.8 MB of dunes
Sun
7.5° up, over the sea
Frame
8.5 ms on an M1 Max

What runs when

The work is split by how fast it has to be. Dunes take about a quarter of an hour to compute, so that happens once, in Python. Waves have to answer to the ground they run over, so they are computed live on the GPU. Everything else is made from those two.

WhenWhatWhere
Once, offline9 laps of the dune model; 64 moments of the last one are kept, with how far each piece of ground moves between them; then ridges, and packingsim/shore.py, shoreloop.py, ridges.py, pack.py
Once, at page loadUnpacking the dunes; noise tiles, sand grain, cloud shadows, clouds, far hillsunpack.ts, bake.wgsl
60 times a secondA tick of the sea: two steps of water, one of foam; the ground is made anew for every second tickwater.wgsl
Every frameGround, wind shelter, shadows, bounced light, then surface, walker, air and printnow, light, trace, walker, air, show

It is raw WebGPU inside a small sketch runner. three.js supplies camera matrices and orbit controls only. The dunes are 64 height maps of 704 × 800 16-bit values and 64 maps of 88 × 100 movements, 72.7 MB in memory and 5.8 MB to download.

Why it loops

Nothing is blended to hide a seam. The whole scene obeys one symmetry: after 40 seconds everything is exactly as it was, one bay further along the coast. The eye retreats by one bay in the same time, so the last frame meets the first.

state(x, z, t + T) = state(x, z − D, t)      T = 40 s,  D = 60 m,  coast repeats every 480 m = 8 D
Coast from above, start of the loopA quarter of a loop laterHalf a loop laterThree quarters of a loop later
The same 312 m of coast from above, a quarter of a loop apart. The sea is on the left and the wind blows from the right. Dunes reach the water, stand out as headlands and are cut back.

Every moving thing has to keep that promise, which limits what it may do:

  • Dunes are fed by pulses of sand whose timing has the symmetry. The dunes lose all memory of their start, because sand only ever travels to the sea, and settle into the same rhythm.
  • Swell is seven waves. Each makes m cycles a loop and n along the coast, with ω = 2π (m − n/8) / 40, so a shift of one bay undoes a loop.
  • Textures fixed to the sand repeat every bay. Those that slide (wind ripples on water, mist, cloud shadows) move a whole number of their own periods a loop.
  • The walker’s scarf, coat and steps make whole numbers of cycles.

Because the coast is eight bays long and the loop moves only one, you see eight different stretches before anything repeats along the shore.

Sand, worked out before

The dune model is a simplified continuum dune model, after Kroy, Sauermann and Herrmann. It runs on 704 × 800 cells, 2,240 steps a lap, in five moves.

  1. Shelter. Behind each crest the wind comes loose. The ground is given an envelope that falls 0.14 m for every metre downwind; whatever lies under it feels no wind.
  2. Wind over the hills. The stress on the envelope is worked out in Fourier space: higher on windward slopes and slightly ahead of the crest, which is what makes a dune grow.
  3. Sand in flight. The flux does not jump to what the wind could carry. It approaches it over a saturation length of 2 m.
  4. Slides. Where the ground is steeper than 0.62 (about 32°), it gives way.
  5. The sea. It takes sand within reach of its waves, most at the water’s edge and hardest on what stands furthest out. The slope above then slides after it, which is how a dune gets undercut.
τ(k)   = 1 + |kx|/|k| · (A|kx| + i B kx) · h(k)              A = 4,  B = 2.5
q_s    = τ^1.5 (1 − τ_c/τ) / (1 − τ_c)                        τ_c = 0.5
dq/dx  = (q_s − q) / l_s                                      l_s = 2 m
dh/dt  = −∇·q,   then slides,   then   dh/dt = −eat · reach(h) · (h − floor)

Sand enters far inland, in eleven pulses. Small dunes outrun large ones and merge with them, so the largest are always at the downwind end. With wind off the land, that end is the shore. The tallest reach 18 m.

After nine laps one lap differs from the one before by 2 cm on average. The last laps lean 12% on the lap before them, which settles what is left.

Ridges

The model gives sharp edges but domed tops: behind the edge of a steep face the ground stays nearly level for metres, and low light fades slowly over it. A ridge looks sharp when the light changes right at it. So a last step raises the ground behind the edges of the taller dunes, by up to 1.8 m, and carries each steep face on up at its own slope until the two meet. This part is shaping by hand, and only dunes above about 4 m get it.

Sand, at this moment

Sixty-four moments in 40 seconds is one every 0.6 s, and in that time a dune moves by up to 16 cells. Fading between two keys would make it dissolve and reappear. So the data also holds, for every block of 8 × 8 cells, how far its shape goes before the next key. The GPU pulls both keys towards each other by that much and only then mixes them.

h(x, t) = mix( key_k(x + d·f),  key_k+1(x − d·(1 − f)),  f )
f: how far between the two keys      d: the block’s move

Moves were found offline by trying every half cell from 0 to 16.5, keeping the best match, and fitting a parabola through its neighbours. The result is stored in 8 bits. Dunes are then drawn up to a quarter taller than they were computed (tall = 1.25), which is an artistic choice.

Height of the ground from above
Ground, 824 × 800, 32-bit float. Made from two keys. The figures here are the real GPU textures of one moment (0.72 of the loop), 300 × 300 m, with the eye at the bottom.
How far each block of ground moves
Moves towards the next key, 88 × 100 blocks. Bright ground travels furthest; small dunes are the fastest.
Depth of water, foam and wet sand
Water, 360 × 800, four channels: depth, foam, wet sand, speed. White lines are breakers; the darker rim on the sand is where it is still wet.
Where sand blows off crests and spray off waves
Wind shelter, 412 × 400. Orange: in the lee of a sharp crest, where sand is blown off. Blue: spray carried off breaking waves.
Height up to which each place is in shadow
Shadow height, 824 × 800, two channels: up to what height a place is in shade, and how far away the thing is that shades it. Blue is in shadow, sand is clear of it.
Direct light on the ground
Sunlit, 824 × 800. Direct light on the ground, the source of everything that bounces.
Sky and bounced light on the ground
Bounced light, 412 × 400. Sky seen over the dunes plus warm light off lit faces. Contrast is raised a lot here; the real differences are subtle, and they are what keep shade from looking flat.

73 MB into 6

Sixty-four height maps are 72.1 MB, and their movements another 0.6. Zipping them barely helps: gzip looks for bytes it has seen before, and a smooth slope never has the same height twice. What does repeat is smoothness itself. Nearly everywhere the ground is what its neighbours say it should be; only crests are news.

A wavelet keeps the news

Each map goes through a CDF 9/7 wavelet, the one JPEG 2000 uses for lossy pictures. It splits a map into a half-size smooth copy and three maps of what that copy misses: along the coast, across it, and both. The smooth copy is split again, four times over. Rounded to steps of 2 mm, 86% of all these numbers are zero.

A height map turned into wavelet coefficients: dark nearly everywhere, with bright lines along the dune crests at four sizes
One moment after the wavelet, brightness on a log scale. Top left: the coast at a sixteenth of its size. Every other box is what a size adds. Dark is zero once rounded; what is left is the crests.

A real line across the coast, sea at the left, through the same wavelet, in one dimension. Above, the ground, with the rebuilt one over it. Below, the numbers that are kept, fine sizes first; taller bars are larger, on a log scale. Round them hard and see where it gives first: next to the crests.

What is written

  • The smallest copy, 44 × 50, is kept as what each number adds to its neighbours, left and above.
  • Everything else is divided by 2 mm and rounded, with a slightly wider zero. Signs are folded in (0, −1, 1, −2, 2 become 0, 1, 2, 3, 4) and each number gets a byte. The 1% or so that do not fit follow at the end in three.
  • Each moment is gzipped by itself, about 85 KB, so moments can be unpacked side by side.
  • The movements are kept exactly, gzipped, 0.35 MB.

And unpacked

While the file is arriving, each moment that is complete is handed to one of up to six workers. A worker unzips it with the browser’s own DecompressionStream, fills in the numbers, and runs the wavelet backwards, whole rows at a time. All of it is about 130 lines without a library, and 1.1 s of work on one thread, spread over the workers while you download. The result goes to the GPU as the same 16-bit maps as before, so nothing after it had to change.

WayDownloadFurthest offOn average (rms)

2 mm was chosen with room to spare: against a nearly exact pack the picture differs by 0.03 to 0.05 of 255. Rounding the heights themselves is the wrong loss. It makes tiny terraces, and a low sun shows slope, not height. Two other ways were tried and dropped: half as many moments was wrong by up to 1.6 m where dunes merge, and taking differences from the moment before made files larger, because dunes move up to 16 cells in between.

The sea

Waves are the shallow-water equations: depth and two flows in each cell, 120 steps a second, on the ground of that very moment. Nothing is animated by hand. Breakers stand up, run up the beach, drain off and reflect from dune feet because of the depth they cross.

h_t  + (hu)_x + (hv)_z = 0
(hu)_t + (hu² + ½ g h²)_x + (huv)_z = −g h b_x − friction
  • Scheme. Second order in space with minmod slopes, HLL fluxes, and the hydrostatic reconstruction of Audusse et al. (2004). Still water stays perfectly still over any ground, and no depth goes negative.
  • Waves come in at the far edge, where the water is pulled towards the seven swells over the first 16 m.
  • Ground that moves. When a dune pushes into the sea, the water keeps its own height. Keeping its depth instead would lift the sea up the dune’s face.
  • Films. Below 5 cm, water sinks into the sand. Flow along the shore is damped, because waves trapped there would slosh for minutes and the loop would not close.
  • Foam is carried by the water. It is made where the surface is steeper than about 0.16, where water runs together, and at the tip of the run-up. It dies within seconds, and at once on steep banks, where an advancing dune buries it.

The page’s own scheme in one dimension: the same fluxes, friction, film and foam rules, 300 cells of 0.6 m. Height is drawn several times too tall. The seven swells come in from the left.

Light

Shadows by doubling

The sun stands 7.5° high, so a dune’s shadow can be 150 m long. Marching each place towards the sun takes many samples, and growing steps miss thin crests. Instead, a map holds for each cell the height up to which it is in shade. A pass looks some distance towards the sun, lowers what it finds by the sun’s slope, and keeps the higher. The next pass looks twice as far into the result of the last. Eight passes reach 154 m and miss nothing on the way.

S_0(p) = max( h(p + 0.9 m) − 0.9·r,  h(p + 1.5 m) − 1.5·r )             
S_k(p) = max( S_k−1(p),  S_k−1(p + 0.6·2^k m) − 0.6·2^k·r )        k = 1 … 7
r: how steeply the sun stands, p + a: a place that far towards it

Real ground from the scene, cut along the sun’s direction. The sun is at the right. Turn the passes down to see the shadow grow.

The distance to whatever casts the shadow is carried along, so penumbras widen with it (the sun’s radius is 1.2°). The same map lights the mist, at one lookup a step.

Bounced light

For every second cell, 12 directions are searched at 10 growing distances. Each rise of the horizon is a strip of lit ground that sends light back; above the last one there is sky. While the piece plays, half of the 8 × 8 blocks are done in one frame and half in the next, like a checkerboard. Everything is done on the frame where the loop wraps.

Sky, clouds, relief in shade

The sky is an analytic gradient, warm towards the sun. Light falling into shade is bluer than the sky you see. Cloud shadows are one picture that slides along the coast. In shade, small slopes that lean away from the sun see more open sky, so ripples stay visible there too.

Baked once

Cloud shadows, clouds and far hills never change shape. They slide, or stand still. Working them out from hashes at each step of each ray was most of the early frame time. They are now drawn into textures when the page starts.

Four tiles of noise
Four noises in one texture, of 4 × 16, 11 × 32, 18 × 32 and 31 × 31 cells. The counts let each slide whole turns a loop.
Cloud shadow texture
Cloud shadows: 720 m along the coast by 1,320 m inland, 256 × 256.
Sand grain noise
One of eight layers of sand noise with its slopes, with smaller copies for sand far off.
Silhouettes of far hills
Far hills, 8,192 × 512. Four ridges reduce to one number: how much of the hills’ colour covers the sky.

Finding the surface

Each pixel sends one ray. The ground is a height map, so a ray at height over above it can move forward by over divided by how fast the ground could rise to meet it. The steepest drawn faces reach 1.34 across the coast. Assuming 1.36 everywhere is safe but slow; assuming less lets some rays step inside a dune and draws false dark lines behind crests.

The current march assumes 0.88, which is wrong in places, and repairs the damage. If a step lands inside, the crossing lies between the last point above and this one, and three rounds of false position find it. A final secant step moves the point onto a smooth B-spline of the ground.

Landing inside can be repaired; stepping clean over a thin ridge cannot, as nothing notices. An earlier setting of 0.7 did that to the new ridges. On one picture of 1,210 × 700 rays, against a march with steps of centimetres, it was wrong at 1,142 of them. With 0.88 it is 574, the same as the safe 1.36 (582), in 24 steps a ray instead of 35. What is left grazes a crest by less than a pixel.

A real slice across the coast with a face of slope 1.2. Dots are the ray’s samples. Filled circle: where it ends. Ring: the true surface.

Sand, water, foam

The scene without air
Surface and walker, before any air.
Distance of each pixel
Distance, kept in the alpha channel. The air pass stops at it, and the mix uses it to keep edges clean.
Light scattered by the mist
Mist: light it gives off, at half size.
How much the mist lets through
Seen through: how much of the surface gets past the mist.
Blown sand and spray
Blown sand (amber) and spray (blue), raised in brightness to be seen.
The finished picture
Final: mixed, with glow and tone curve.

Sand

  • Shape. Four sizes of soft swells from 12 m to 0.5 m, with slopes near 1%. At so low a sun a slope of 4% already looks like rock.
  • Ripples run across the wind, 0.7 m and 2.2 m apart, bent by noise and in patches. Each fades once a pixel covers more than about a third of a wave, measured along the actual view, so they do not shimmer.
  • Steep faces carry tongues where sand has slid. Crests are blown smooth.
  • Light uses an Oren–Nayar response, sun times shadow times cloud, plus the bounced-light map.

Water

  • Small waves finer than the grid: five layers of noise, each moving a whole number of cells a loop. What is too fine for a pixel goes into roughness instead.
  • Colour by depth. Pale sand seen through water that removes red first (exp(−d·(1.6, 0.42, 0.40))), plus the water’s own light, turquoise when shallow and blue below about 1.7 m.
  • A net of light on the bottom, from two ridged noises drifting apart.
  • Reflections march 14 growing steps to find dunes, else read the baked sky and hills. Sun glints use a GGX lobe.

Foam

Foam is bubbles: two sizes of Voronoi cells with warped walls. As foam dies the threshold rises, so sheets open into lace and then threads. The mask from the water grid is read from a slightly displaced place so its 0.6 m squares never show, and a thin film frays at the edge.

The walker

They walk towards the eye on a slow sine, x = 8 + 6 sin 2π(u + 0.56), 86 m away, while the coast passes under them at 1.5 m/s. The route was searched for: never under water, feet always in view, close to the waves once, on the dunes for about half of the loop, and never climbing faster than 2.4 m/s. Steps are as long as the ground they cover, and a whole number fit the loop.

The walker close up: hooded coat, red scarf flying to the left
A distance field: squeezed capsules for chest and waist, one per thigh melted into a coat, two-bone joints for limbs, a hood cut open for a face. Feet follow the slope.
The walker seen from the sun, as a distance map
The shadow picture, 128 × 128, from the sun’s side: how near a ray of sunlight passes them, and where. The sand reads soft shadows from it in one lookup.

The body lives in its own small shader, drawn over the surface inside the same render pass and limited to a rectangle around them. While it was part of the surface shader it cost 3.2 ms on every pixel, sand and sky included, and removing any one of its four uses saved almost nothing. A shader that large runs out of registers everywhere. Reflections in water use four plain capsules.

Air

Mist and blown sand are soft, so they are traced at about half of the screen’s own pixels.

  • Blown sand hangs behind sharp crests, where the wind-shelter map says the air is loose, from a metre or so downwind of them. It thins with distance from the crest and streams in gusts. Spray does the same from breaking waves.
  • Mist is an even haze plus drifting banks near the ground. Thirty steps, denser near the eye, each with one shadow and one cloud lookup, so crests throw shafts of shade through it.
  • Dither. Each small pixel starts its steps at a different offset by interleaved gradient noise, which is even over any 3 × 3 pixels.
  • Laid over the surface. A small pixel takes the nearest or the farthest of the pixels it stands for, by turns. The mix then averages nine small pixels, weighting those at the same distance, so a crest keeps its own air.

The print

Glow is the picture halved six times and added back up. Then exposure, a soft vignette, an ACES-like curve and an S for contrast, and a little grain. Stills and films average many rays a pixel with a low-discrepancy jitter; live playback uses one.

One frame, timed

Measured on an M1 Max at 1728 × 1000 points on a 2× screen, traced at 0.7 of full resolution. Times are each pass on its own; together the frame takes 8.5 ms.

PassSizeWhatms

How it got here

StepResolutionms a frame

Two lessons from that list. The softest effect cost the most: cloud shadows, blobs 45 to 110 m wide, took 10.8 ms because they were rebuilt from hashes at every step of the mist and the blown sand. And the cheapest speed-up was to stop drawing what cannot be seen, such as sand detail under the sea.

How it is checked

  • The seam. A film tool renders all 1,200 frames and compares each with the one before. The step from last to first changes 1.05 of 255, against 0.85 and 0.93 for its neighbours, and no frame jumps.
  • The truth. The ray march is compared with an 80-step reference. With 0.7 steps it differed by 0.06 of 255 on average before the ridges were added. Comparing with the previous version instead would have called the correct picture wrong.
  • The clock. Render-pass timestamps on Apple’s GPUs include waiting, so tools/coast-time.mjs records one real frame, stops the page and replays each pass many times. Variants are interleaved over several rounds and the lowest time is kept, because other apps can only add time.

What is not real

  • Dunes here cross tens of metres in seconds. Real ones take months. Wind strength and sand supply were tuned for the picture.
  • Ridges were shaped after the simulation, dunes are drawn a quarter taller, and the walker is 3.6 m tall so they read at 86 m.
  • Water and sand act on each other in one direction live: the sea runs over the dunes, but the erosion it causes was computed beforehand with simpler rules.
  • Foam’s bubble pattern stays in place while its mask moves with the water. Footprints stay sharp on sand that is moving beneath them.
  • Mist is lit once, with no light passed on between drops.

Methods used: Sauermann, Kroy and Herrmann, Continuum saltation model for sand dunes (2001); Kroy, Sauermann and Herrmann, Minimal model for sand dunes (2002); Audusse et al., A fast and stable well-balanced scheme with hydrostatic reconstruction for shallow water flows (2004); Harten, Lax and van Leer (1983) for the fluxes; Oren and Nayar (1994) for sand; Worley (1996) for the cells of foam; Cohen, Daubechies and Feauveau (1992) and Daubechies and Sweldens (1998) for the wavelet and its lifting steps; Jimenez (2014) for interleaved gradient noise; Narkowicz’s fit of the ACES curve.