8000 GitHub - SamG-Coder/WaterCuda: Infinite procedural islands and a spectral ocean, authored in CUDA and rendered in the browser with WebGPU. · GitHub
[go: up one dir, main page]

Skip to content
SamG-CoderPublic

About

Infinite procedural islands and a spectral ocean, authored in CUDA and rendered in the browser with WebGPU.

Resources

Stars

47 stars

Watchers

0 watching

Forks

Repository files navigation

WaterCuda

WaterCuda: a procedural island and spectral ocean, captured from the browser renderer

Open the live demo ↗ · Shallows · Golden hour · Aerial

The cover is an unedited 1280 × 720 frame exported from WaterCuda in the browser, seed 884, Clear coast. Click it to explore the same island. Use a recent Chrome or Edge with WebGPU support; the first GPU compilation can take a while.

Coastal ecology / 003: seeded offshore sandbars, shallow channels, dunes and procedural shrubs with GPU-generated foliage billboards, wind movement and persistent terrain coverage. See the coastal ecology notes. See the implementation and validation notes.

An experimental browser renderer for a procedural infinite archipelago, using the same CUDA source → WGSL → WebGPU compute architecture as stratum-city. Islands, terrain materials, ocean displacement, sky, reflections and final pixels are generated by the .cu programs. JavaScript handles input, floating-origin bookkeeping, compilation and dispatch.

Live threaded WASM startup: the same 19 CUDA kernels also run on shared-memory CPU threads while WebGPU compiles, then hand over at the current camera and world time. The default Pages app starts with a low-resolution CPU image and retains all existing controls, then switches to the normal adaptive-resolution GPU renderer. During CPU startup, adaptive resolution ranges from 96 to 320 pixels wide based on measured render time. A separate WebGL2 pass runs NVIDIA NIS directional scaling at 2× with restrained sharpening; browser scaling fits that result to the viewport. The first image and fallback do not depend on NIS being available. The upscaler and CPU threads are released at handover. See NIS source and port details. A scope-local service worker enables the cross-origin isolation required by WASM threads on GitHub Pages (one automatic reload on the first visit). Browsers without isolation use the normal GPU startup; ?startup=gpu also opts out of the CPU preview. The reusable backend comes from CUDA-WebShader, with its source revision pinned in vendor/cuda-webshader/UPSTREAM.json. See build instructions, measurements and limits. Pages builds WASM from the current .cu sources using Emscripten 6.0.10; for local development run npm run build:wasm with that SDK activated before npm start.

New views: Sandbars · Procedural scrub

Pirate ship: choose the Pirate ship camera button (or ?seed=884&view=ship&hour=12&weather=clear). The shared kernels/ship.cu generates a curved hull, three masts, nine billowing square sails, a forward jib, rigging, cannons, stern windows and a skull pennant. Analytic surfaces replace a large triangle mesh; whole-ship and mast bounds reject irrelevant rays, and subpixel rigging/material detail simplifies with distance. The ship view starts third-person control at world position (650, 650). W/S moves along mouse aim, A/D turns, mouse pitch controls speed-dependent climb/dive, wheel changes speed and Shift boosts. Space/Q/E have no vertical action in ship mode. Four samples of the existing spectral ocean set hull height, pitch and roll in a single CUDA invocation each frame. Water tilt fades out during lift-off. The camera stays level and follows the vessel. This is an arcade sailing/flying controller; full rigid-body hydrodynamics and an explorable interior are not implemented. Native CUDA is the default visual/performance test path.

Run

Requires Node.js 20+ and a WebGPU-capable browser. No npm dependencies to install.

git clone https://github.com/SamG-Coder/WaterCuda.git
cd WaterCuda
npm start

Open http://localhost:8090 in Chrome or Edge. On Windows, double-click START.bat. The first driver compilation can take up to a couple of minutes on tested hardware. The loading screen remains visible until the first frame completes. Later loads use verified shader artifacts and the browser cache. Use localhost or HTTPS, not file://.

Explore

  • Drag to look; WASD or arrows fly along the camera's actual viewing direction; Q/E descend/rise. Space also rises.
  • F, the Free camera button, or double-clicking the scene captures mouse-look; Esc releases it. Drag remains available when pointer lock is unsupported.
  • Shift boosts speed; Z slows down; wheel adjusts flight speed without an upper speed cap. Z avoids the browser's Ctrl+W shortcut.
  • 1/2/3/4 select Coast, Aerial, Waterline and Shallows. Scrub and Sandbars buttons open the new close views. H hides/restores the interface.
  • Change the world seed and press ↻. ?seed=12345 opens a specific seed.
  • Sea/light presets, water clarity, sun direction, wind, sunlight, resolution and island reflections are adjustable. Auto targets 60 FPS using measured GPU time; fixed resolutions remain available.
  • Begin drift moves the camera; Pause world freezes waves and weather. Save image exports the computed frame without the interface.
  • Under the surface includes footprint/normal diagnostics and real GPU checks.

Use 7 or Dive reef for the underwater preview (seed 884). Q/E now allow diving below sea level.

Generation and level of detail

World: deterministic 4,800 m cells contain bounded procedural islands or open water. Integer cell identities are separate from camera-relative floating-point positions. Visiting new cells does not allocate persistent island meshes or grow memory usage.

Terrain: the ray tracer traverses cells, rejects island bounds, then evaluates the shared height field. Broad island silhouettes remain present; high-frequency relief and material grain fade with the projected pixel footprint. The current algorithm is bounded analytical ray marching, not a quadtree mesh or a precomputed min/max hierarchy.

Underwater: a continuous seeded seabed connects island shelves across open ocean. Large reef regions contain irregular raised outcrops separated by empty sand/rock areas. Depth controls living cover and growth forms. See underwater implementation notes for current limits and validation.

Water: four 256 × 256 spectral cascades replace the small analytic wave sum that produced regular crosshatching. CUDA generates a seeded directional Phillips spectrum, evolves it with deep-water dispersion, performs row/column inverse FFTs, and builds height/slope/energy mipmaps. Patch sizes are 32, 128, 512 and 2,048 metres, covering approximately 0.35–192 m wavelengths. Ray intersections use the resulting displaced height field. Trilinear mip sampling follows the projected pixel footprint; lost slope variance goes into shading roughness. Integer modular sampling preserves the field when the origin changes. The combined ocean repeats spatially every 2,048 m; island descriptors are independent.

Coastal ecology: submerged sandbanks and deeper channels share the terrain height field; offshore deposits stay at least 1.8 m below mean sea level. Nearby shrubs use two crossed texture cards and a 64 KiB habitat cache. CUDA generates four foliage variants, matching overhead crowns and filtered mipmaps once at startup (2.73 MiB including the cache). Between 65 and 125 m the cards blend into matching seeded crowns in the terrain material; distant plants have no range cutoff. Unresolved crowns become filtered habitat coverage.

Close-up terrain materials use metre-based triplanar colour and bump detail with separate surface filtering, so fine shading detail can remain visible near the camera.

Shading: Fresnel reflection, GGX/Smith sun highlights, Snell refraction direction, depth-dependent absorption/scattering, approximate seabed refraction, irregular shoreline foam and caustics. Island reflections trace each visible water pixel using its own wave normal, avoiding block artifacts from half-resolution reconstruction. Terrain adds stratified rock colour, vegetation variation and terrain shadows. Direct and reflected island views share analytically integrated height-dependent haze. No downloaded scene textures, HDRIs or imported models; foliage textures are generated on the GPU. Fonts are optional Google Fonts with system fallbacks.

Scheduling: input runs on the browser animation clock; rendering allows at most two outstanding frames without blocking input on GPU completion. Under the surface reports GPU time for spectrum generation, visibility, reflections and shading. The ocean needs about 13.3 MiB of constant storage including cached coefficients, FFT scratch and mipmaps; per-pixel visibility/reflection buffers scale with the selected resolution.

Validation

npm test
npm run test:native

npm test translates all seventeen CUDA entry points and runs twenty Node tests for free flight, focus handling, diagonal speed, frame-rate independence, world rebasing, seed validation and render alignment, cached wave scheduling, sea looks, shader contracts and the browser fixture server. test:native needs a C++17 compiler (g++, or set CXX), checks terrain against dense traversal and computes an independent double-precision CPU inverse FFT. It regenerates tests/ocean-reference.json, used by browser GPU checks.

Open http://localhost:8090/?test=1 to execute ten GPU checks in the actual browser. They check cached/eager wave equivalence, determinism, terrain and wave rebasing, distant integer coordinates, seed variation, unresolved wave energy, agreement with the independent CPU FFT and WebGPU validation errors.

Verified on this machine in the Chromium-based in-app browser:

  • All twelve CUDA entry points translated and created working WebGPU pipelines.
  • Seventeen Node tests and ten browser GPU checks passed.
  • 192 terrain rays across three occupied seeded islands plus 200 low-angle waterline hillside rays: zero hit/miss mismatches against 0.25 m dense traversal; maximum distance difference about 0.52 m.
  • 100 island seeds checked for terrain bounds and cell-edge continuity; 60 close material samples checked for finite output, rebasing stability and detail filtering.
  • 100 spectral-water rays: maximum surface-equation residual below 0.004 m.
  • The earlier coastal-light release observed approximately 59–60 FPS in seed-884 coastal and shallow-water views at 1280 × 720, with GPU totals around 6–9 ms during spot checks. These are not controlled cross-version or cross-device benchmarks.
  • Frame rate depends on view, reflections and internal resolution. The UI reports observed presentation FPS; this is not a cross-device benchmark.

Current scope and next steps

This is an interactive renderer with a real spectral ocean, not a full fluid simulation. Foam and caustics remain procedural approximations. There are no trees, erosion simulation, breaking surf, underwater camera mode, collision-constrained walking or temporal antialiasing yet. Reflections can still shimmer in motion, especially near distant coastlines. Terrain marching uses a heuristic slope bound and one-metre minimum steps; tiny intersections outside the tested fixtures are not guaranteed. Island reflection queries fade out at 6.5 km, and the primary draw distance is 18 km. Integer coordinates are finite (roughly ±2.147 billion cells); “infinite” means on-demand generation without a prebuilt map boundary.

The next realism pass should add horizontal choppy-wave displacement, a local shallow-water region coupled to terrain depth, persistent advected foam, and temporal reflection filtering. A GPU min/max terrain hierarchy would allow conservative empty-space skipping at higher terrain detail. See architecture notes.

Source and attribution

kernels/ is the scene source. src/ contains the browser shell, renderer and shader loader. generated/ and Water.cu are generated outputs. vendor/cuda-webshader/ and the shader loader/build support are adapted from stratum-city at commit 62ef0b067a68407c76ced0bb58b6bfd4b753d6ca; the original MIT license and bundled third-party notices are retained.

Native C++ / CUDA version

The native/ subfolder builds a Windows desktop viewer and headless renderer with NVIDIA CUDA. It compiles the exact same kernels/*.cu files directly with nvcc, including the ocean FFT, terrain, billboards and shading. From the repository root, run powershell -ExecutionPolicy Bypass -File native/build.ps1 -Test -Run. See the native README for requirements, controls and image export.

Dynamic weather

Seeded regional weather drives moving clouds, rain, lightning, local wave strength and surface wetness in the shared CUDA source. Use the Weather control to select automatic weather or inspect Clear, Overcast, Rain and Thunderstorm. Native builds use T or --weather auto|clear|overcast|rain|storm.

See weather implementation and controls for the regional model, performance measurements and approximation limits.

The sky now follows a shared day/night clock: moving sunlight, sunset colours, stars and moonlight, with weather-controlled clouds. Use World time to inspect an hour, or open ?seed=884&view=coast&hour=18 for sunset. A full day lasts 24 real minutes; Pause world freezes the cycle.

Shoreline traversal now uses GPU-generated conservative terrain bounds and a min/max hierarchy to skip empty space. Terrain detail and final procedural intersections remain intact. See performance measurements and validation.

The vessel drives a persistent local 128 x 128 height/velocity wave grid at 2 m spacing (256 KiB, two banks), with hull pressure, propagation and damping. It composes with spectral ocean height and normals; it is a local linear wave simulation, not a full fluid solver or FFT spectrum feedback. Submerged movement has depth/speed-dependent drag. Press V to leave the ship at its current position and use normal fly camera; V reattaches. Underwater optics and reef generation work in both modes. Native previews use automatic seeded weather by default; T cycles weather overrides.

Ship movement uses swept hull/terrain checks and seabed clearance; collision corrections feed back into the controller. Neutral steering has a small pitch dead zone. Fast water entry adds an impulse to the local wave grid, foam and bounded spray. Sweeps use 2 m steps over at most 256 m per rendered frame, limiting extreme per-frame travel to avoid skipping terrain.

Ship camera/control refinement: the chase distance is 100 m. Left-drag freely orbits without changing vessel heading or pitch. Right-drag or F mouse capture steers/pitches with gradual response; A/D turns, W/S accelerates/reverses, and release coasts. Scroll remains speed control. The surface is no longer treated as partly submerged drag, and wave-driven heave/roll is damped. V exits/re-enters the ship.

CPU checkerboard rendering

The production threaded WASM fallback alternates the two diagonal pixel pairs in each 2x2 block. Its persistent shared image buffer retains the opposite phase; camera movement fills missing pixels from current neighbours to avoid stale trails. Resolution, seed and mode changes initialize a complete frame. NIS presents the reconstructed image afterward.

The CPU controller starts at 128 pixels wide and increases width by 32 after sustained frame times below 45 ms, reducing it above 55 ms. It measures worker round-trip and presentation submission, targets roughly 20 FPS, and grows buffers on demand up to the viewport width or a 2,073,600-pixel memory budget. Browser presentation completion is not GPU-timed. The WASM build adapts generated dispatch wrappers; CUDA source and the WebGPU/native rendering paths are unchanged.

A lightweight geometry-guided checkerboard resolve runs in the CPU worker before NIS. It clamps temporal history to fresh neighbouring colours, rejects history during camera motion, and reduces history reuse on animated water. It uses existing depth, normal and material buffers and keeps raw checkerboard samples separate from the filtered output. This is a custom small filter inspired by denoising techniques, not an integration of NVIDIA NRD.

CPU workers scale with reported hardware concurrency: up to eight rendering workers, reserving two logical CPUs on machines with enough cores. The CPU timing panel exposes each render stage. Once NIS is active, presentation skips the redundant 2D fallback paint; it resumes if NIS becomes unavailable.

During camera movement, the resolve forward-projects previous measured terrain/coral samples using the same camera ray convention as the renderer. Depth, material and normal checks reject invalid history; a nearest-depth buffer resolves overlaps. Water, sky, foliage and the moving ship do not reuse camera-only motion history. Resizing and origin rebasing reset history.

The generated CPU checkerboard dispatch enumerates only the 32 active lanes of each 8x8 tile. Run node tools/cpu-benchmark.mjs after building WASM for a fixed 257x145, eight-worker, 60-frame moving-scene benchmark with an output SHA-256. An optional argument selects another generated WASM directory for comparison. Small-batch and LTO trials did not show a useful gain; production retains 8x8 tiles and the existing compiler flags.

About

Infinite procedural islands and a spectral ocean, authored in CUDA and rendered in the browser with WebGPU.

Resources

Stars

47 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0