Three.js Ocean Water Shader (Gerstner Waves)
Open ocean in Three.js with summed Gerstner waves computed on the GPU, analytic normals, Fresnel sky reflection, sun glints, crest foam and fake subsurface light, plus a buoy that rides the same waves.
Key topics: three.js ocean, gerstner waves, water shader, fresnel, wave simulation, glsl
Game Over
What this code does
- Gerstner Waves: surface points move in circles (x and z shift as well as y), giving sharp crests and broad troughs.
- Dispersion: each wave's speed follows deep-water physics, c = √(g/k), so long waves outrun short ones.
- Analytic Normals: tangent and binormal derivatives of the wave sum give exact normals with no extra samples.
- Shading: Schlick Fresnel blends deep water color with reflected sky, and the sun adds a sharp specular glint.
- Foam & SSS: crest steepness drives noisy foam, and back-lit thin crests glow teal.
- Controls: wave count, steepness, wavelength, wind direction, directional spread, foam and water colors.
Related Demos
Continue Learning
JavaScript Implementation
// One Gerstner wave in a vertex shader (sum several with different directions/wavelengths)
const gerstner = `
uniform float uTime;
vec3 gerstner (vec3 p, vec2 dir, float steepness, float wavelength) {
float k = 6.2831853 / wavelength;
float c = sqrt(9.81 / k); // phase speed of deep-water waves
float f = k * (dot(dir, p.xz) - c * uTime);
float a = steepness / k;
return vec3(dir.x * a * cos(f), a * sin(f), dir.y * a * cos(f));
}
void main () {
vec3 p = position;
p += gerstner(position, normalize(vec2(1.0, 0.3)), 0.25, 22.0);
p += gerstner(position, normalize(vec2(-0.4, 1.0)), 0.18, 12.0);
gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);
}`