Skip to content

About

Zero-dependency real-time 3-cascade FFT ocean simulation for WebGPU and WebGL2

Resources

Stars

24 stars

Watchers

0 watching

Forks

Repository files navigation

Directed Ocean

A zero-dependency, real-time 3-cascade FFT ocean simulation with GPU buoyancy, ballistic barge-slam spray, procedural foam, and coastal shoal shading. Runs natively on WebGPU with an automatic WebGL2 fallback—no build step, bundler, external libraries, or downloaded assets.

Live Demo: directedgames.com/packages/directed-ocean/

Directed Ocean overview at 100 m camera distance, 15 m/s 235° SW wind, 100 m peak wavelength

Wide 100 m view: 15 m/s, 235° SW, 100 m swell Close-up: buoy pitching in the 100 m swell
Wide 100 m ocean view under 15 m/s 235° SW wind and 100 m peak wavelength with buoy Close-up of moored buoy pitching in 15 m/s 235° SW waves

Quick Start (How to Use)

Run locally

Serve the repository root with any static HTTP server:

python3 -m http.server 8000 --bind 127.0.0.1

Then open http://127.0.0.1:8000/ in a WebGPU- or WebGL2-capable browser (Chrome, Edge, Safari, or Firefox). You can also open index.html directly from disk.

Selecting the graphics backend

  • Default: Uses WebGPU when available, falling back automatically to WebGL2.
  • Force WebGL2: Append ?backend=webgl2 to the URL (e.g. http://127.0.0.1:8000/?backend=webgl2).

Starting with objects hidden

  • Hide Show toggles at start: Append ?hide= with a comma-separated list of foam, buoy, barge and island (e.g. http://127.0.0.1:8000/?hide=barge,island). The checkboxes start unticked and still work.

Controls

Input Action
Drag (mouse or 1 finger) Orbit a full 360° turn and tilt camera elevation (27°–82°).
Scroll / Pinch / Camera distance slider Smoothly zoom between 5.6 m and 224 m from the focus point.
Arrow keys (canvas focused) Rotate bearing and tilt in 5° increments.
+ / - (canvas focused) Zoom in / out.
Home (canvas focused) Reset camera to the default north-facing view and distance.

Sea state & scene parameters

  • Wind speed (0–25 m/s): Drives spectral energy and spray advection. Setting wind to 0 lets the sea subside to flat water.
  • Wind blows toward (0°–360°): Compass bearing waves travel toward, clockwise from north (0° N maps to -Z, 90° E maps to +X).
  • Peak wavelength (1–200 m): Manual dominant wavelength.
  • Calculate wavelength from fetch: Switches to automatic JONSWAP peak estimation from wind speed and Open-water fetch (1–150 km), applying a fully developed sea limit.
  • Show toggles: Toggle Foam, Buoy, Barge (with waterline slam spray), and Island (coastal shoal with Beer-Lambert depth coloration).

Project Structure

Because there is no bundler, scripts load in order via <script defer> tags in index.html:

File Responsibility
index.html Page layout, <canvas>, sea-state controls, and script load order.
style.css HUD panel styling and responsive layout.
app.js UI bindings, pointer/keyboard camera controller, backend selection, and requestAnimationFrame loop.
spectrum.js Deep-water JONSWAP spectrum, Mitsuyasu directional spreading, 3-cascade wavenumber partition (384 m, 72 m, 13.5 m), and deterministic Gaussian phases.
foam.js Startup procedural baking of a seamless 256×256 tileable sea-foam texture (macro bubble web, fine bubbles, mist) and CPU mip chain.
meshes.js Procedural geometry for the adaptive ocean grid, moored buoy, raked steel cargo barge, coastal island/shoal (seafloorHeight), and splash billboard quad.
compute.js WebGPU WGSL compute shaders: spectrum evolution, 128-point shared-memory IFFT (rows & columns), Jacobian/normals/persistent foam, mip downsample, buoy/barge buoyancy, hull slam probes, and ballistic splash particles.
solver.js WebGPU compute pipeline orchestration, storage buffers, ping-pong foam history, and step() dispatch.
render.js WebGPU WGSL vertex/fragment shaders for water shading (shadeOcean), island, buoy, barge, and splash sprites.
view.js WebGPU render pipelines, 4× MSAA sRGB render target, anisotropic sampler, and draw pass.
webgl.js Complete WebGL2 fallback: 14-pass Stockham render-target IFFT in stacked RGBA32F textures, GPU buoyancy/splash transform-feedback/RTT passes, and GLSL ES 3.00 rendering.
tests/check.html & tests/checks.js Browser-based GPU and CPU verification suite for the WebGPU solver and spectrum math.

How to Update & Customize

There is no build or compile step—edit any file and refresh the browser to see changes immediately.

Common customization points

  1. Wave spectrum & cascades — Edit spectrum.js:
    • Adjust lengths (default [384, 72, 13.5]) to change the three periodic patch sizes (up to 4 cascades fit the uniform frame parameters in solver.js).
    • Tune upwind (residual upwind wave energy), spreadingExponent(), or JONSWAP peak enhancement (3.3).
  2. Wave chop, foam decay & buoyancy — Edit compute.js (WebGPU) and webgl.js (WebGL2):
    • Horizontal chop scale (1.35), standing-wave fraction (6%), persistent foam decay (~1.9 s), buoy/barge probe layout, and splash particle count (OceanCompute.splashCount, default 512).
  3. Procedural foam texture — Edit foam.js:
    • Modify Worley cell frequencies, domain warping, or channel packing (R: macro web, G: fine bubbles, B: mist density).
  4. Island bathymetry & meshes — Edit meshes.js:
    • Note: seafloorHeight(x, z) and islandCenter in meshes.js must stay synchronized with the shader seafloorHeight functions in render.js and webgl.js so shoreline surf and Beer-Lambert depth absorption align with the island mesh.
  5. Shading & lighting — Edit shadeOcean and object fragment shaders in render.js (WGSL) and webgl.js (GLSL).
  6. UI & camera defaults — Edit index.html, style.css, and app.js (baseDistance, initialTilt, minScale/maxScale, slider ranges, and default values).

Keeping backends in sync: Whenever you change simulation constants, bathymetry, or shading in compute.js / render.js, mirror the change in webgl.js so WebGPU and WebGL2 remain visually and physically consistent.

Verification & testing

After making changes:

  1. Run the GPU solver checks: Open http://127.0.0.1:8000/tests/check.html in a WebGPU-capable browser and verify all checks report PASS:
    • Cascade window partition sums to 1 and directional spreading integrates to 1 (error ~1.0e-9).
    • 2D inverse FFT matches an analytic Fourier mode across both complex lanes and verifies cascade isolation (~3.27e-7 max error).
    • Wave propagation agrees with all four cardinal compass bearings (0°, 90°, 180°, 270°) and 0°/360° wraparound.
    • Calm water (0 m/s) produces zero displacement; active waves heave and tilt the buoy.
    • Longer fetch increases peak wavelength in automatic mode.
  2. Test both backends visually: Check http://127.0.0.1:8000/ (WebGPU) and http://127.0.0.1:8000/?backend=webgl2 (WebGL2), verifying there are no console or shader compilation errors and toggling Foam, Buoy, Barge, and Island.

Publishing updates

git status
git add -A
git commit -m "Describe your update"
git push origin main

Technical Overview

Spectrum model

spectrum.js constructs a deep-water JONSWAP spectrum. Automatic mode estimates peak angular frequency from dimensionless fetch with a fully developed sea limit; manual mode places the peak at the selected wavelength. Directional energy follows a normalized Mitsuyasu-style cos(θ/2)^(2s) distribution peaking around the dominant frequency with attenuated upwind energy. Mapping angular-frequency density to horizontal wave-vector density includes (dω/dk)/k and cell area. Three periodic patches (384 m, 72 m, 13.5 m) partition wavenumber space with smooth complementary crossover windows, while fixed Gaussian samples keep wave phases continuous during slider changes.

References: JONSWAP measurements · Ocean Surface Generation and Rendering (Gamper 2018)

One frame

  1. Evolve the spectrum. Moves current complex amplitudes toward their targets while advancing phase with deep-water dispersion and a 6% standing-wave fraction. Short waves respond faster to wind changes than long waves; opposite wave vectors form conjugate pairs for real spatial heights.
  2. Transform all three cascades. Runs a 128-point inverse FFT across rows then columns—using shared memory per workgroup on WebGPU (compute.js) or a 14-pass Stockham render-target IFFT in a stacked RGBA32F texture on WebGL2 (webgl.js). Height occupies one complex lane and both horizontal displacements share the second.
  3. Build & shade the surface. Applies horizontal chop (1.35), computes central-difference normals and the smaller eigenvalue of the horizontal displacement Jacobian, gates crest compression to downwind-tilting faces, and advects a decaying foam trail (~1.9 s) into a mipmapped rgba16float texture array with per-frame normal renormalization across mips. The surface shader blends anisotropically filtered normals and persistent foam across cascades, layers dual-scale (22 m and 7.5 m) foam over breaking crests, shoreline surf, and the barge waterline, applies Beer-Lambert depth coloration over the coastal shoal, and renders linear light into an sRGB 4× MSAA target on WebGPU (sRGB-encoded on WebGL2).
  4. Float the buoy, barge & splash physics. Four probes integrate heave, pitch, and roll for the moored buoy, and six hull probes integrate the raked steel cargo barge. Sixteen waterline impact probes around the barge compare vertical water velocity against hull motion to spawn up to 512 GPU ballistic spray particles driven by gravity, drag, and wind advection. All rigid-body poses and particles remain on the GPU on both backends.

Reference benchmarks

Uncapped 1280×800 GPU benchmarks in Chrome on macOS (12 m/s, 45° NE, 38 m peak wavelength, 60-frame averages):

Implementation Backend Frame time Notes
Directed Ocean WebGPU 0.37 ms 0.19 ms solver + 4× MSAA render
Directed Ocean WebGL2 1.13 ms 3-cascade Stockham IFFT + GPU buoy
Extracted reference (/preview/) WebGPU 1.41 ms Three.js r185 + 3-cascade compute FFT

Looking for Collaborators

Interested in real-time ocean simulation, WebGPU/WGSL shaders, hydrodynamics, or building with Directed Games? Reach out on X at @jgrebski—PRs, ideas, and collaborators are welcome.


License

Licensed under the MIT License.

About

Zero-dependency real-time 3-cascade FFT ocean simulation for WebGPU and WebGL2

Resources

Stars

24 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages