NatureGL Waterv1.1.0

Reference

API reference

Everything exported from src/index.js and build/index.js. The types are in build/*.d.ts. Units are metres, seconds and radians unless noted, sea level is y = 0, and colours are linear HDR THREE.Color values.

js
import {
  WaterSystem, BuiltinSky, Buoyancy, Wakes, MAX_HULLS, Caustics,
  WaveSpectrum, Bathymetry, FFTWaves, QUALITY_LEVELS,
  PRESETS, DEFAULT_PARAMS, getPresetParams,
  CAUSTIC_FN_GLSL, SKY_GLSL, NOISE_GLSL,
} from 'naturegl-water';

#WaterSystem

#WaterSystem.create(options): Promise<WaterSystem>static async

Builds the ocean mesh and the built-in sky dome and adds both to options.scene. The constructor is synchronous, since every texture is procedural; create() is async to match the other NatureGL packages, and new WaterSystem(options) works too.

OptionTypeDefault
rendererTHREE.WebGLRenderer—Required, WebGL2
sceneTHREE.Scene—Required. The ocean and sky dome are added here
cameraTHREE.PerspectiveCamera—Required. The camera render() draws
quality'low', 'medium', 'high', 'ultra''high'See Quality and performance
presetstring or Partial<WaterParams>'tropical'Starting params
bathymetryBathymetryDesc—Seabed for shoaling, breakers and shore foam
skySkyLike—External sky. Omit it for the built-in one
addSkybooleantrueAdd the built-in sky dome to the scene
manageFogbooleantrueKeep scene.fog (a FogExp2) matched to the sky haze and fogDensity
toneMapping'aces', 'reinhard', 'none''aces'Applied by render(). Leave renderer.toneMapping at NoToneMapping
overlayLayernumber30Objects on this layer draw after the water

#Frame

#water.update(dt): voidmethod

Advances time by dt seconds (clamped to 0.1). Eases params toward their targets, rebuilds and advances the spectrum, updates the sky, the underwater state, buoyancy, wakes and the foam simulation. Call it once per frame before render(), after you move your objects.

#water.render(target?): voidmethod

Runs the depth pipeline for scene and camera and composites into target (the canvas by default). Restores renderer.autoClear and the previous render target. See Rendering.

#water.renderHDR(): { texture, depthTexture }methodsince 1.1

Passes 1–3 only (world, water, overlay) into the pipeline's linear HDR target, with no bloom or tone mapping. depthTexture holds world and water-surface depth. The size is the drawing buffer × renderScale. The underwater colour grade is skipped; the underwater fog is kept.

#water.resize(): thismethod

Re-reads renderer.getDrawingBufferSize() and resizes the offscreen targets. render() does this on its own; the camera's aspect is yours to update.

#water.dispose(): voidmethod

Removes the ocean and sky from the scene and frees the GPU resources.

#Params and presets

#water.loadPreset(preset, opts?): thismethod

Switches to a built-in preset by id, or to any partial params object. Missing keys come from DEFAULT_PARAMS. opts.instant skips the ease.

#water.setParams(partial, opts?): thismethod

Changes some target params; the rest keep their values. opts.instant snaps.

#water.getParams(): WaterParamsmethod

A deep, JSON-safe copy of the target params. Paste it into a preset file.

Property
params: WaterParamsThe targets that presets and setParams write
current: WaterParamsThe eased values in use. Read these for UI sliders
exposure: number1.1 Read-only. What render() tone-maps with
time: numberSeconds since creation

#Quality

#water.setQualityLevel(level, overrides?): thismethod

Switches tier at runtime and rebuilds only what changed: spectrum size, grid, shaders, FFT, foam field, targets, and the bathymetry bake if its resolution changed. overrides replace single settings, for example setQualityLevel('high', { msaa: 0, ssrSteps: 32 }).

Property
qualityName: QualityLevelThe active tier
quality: QualitySettingsIts resolved settings, overrides included

#Sky and lights

#water.setSky(sky, opts?): thismethod

Plugs in an external sky, read every update(). null returns to the built-in sky and re-adds its dome if addSky. Options: sunIntensityScale (1), moonIntensityScale (1), moonTint, envIntensity (1), syncExposure (true). See Any sky-like object.

#water.bindLights(directional?, hemisphere?, opts?): thismethod

Points a DirectionalLight at the water's current key light (sun by day, moon by night) and colours a HemisphereLight from the sky. opts.distance (250) places the light from its target; opts.intensity (1.3) splits colour and intensity. See Sky and lighting.

Property
sky: SkyLikeThe active sky: externalSky or builtinSky
externalSky: SkyLike | nullThe sky passed to setSky
builtinSky: BuiltinSkyAlways present

#Bathymetry

#water.setBathymetry(desc): thismethod

Bakes a seabed from { heightAt(x, z), bounds, resolution?, shoreTrainMinRadius? } so waves shoal, breakers roll up the beach and shore foam follows the coast. null returns to open ocean. See Shorelines.

#Sampling

#water.sampleHeight(x, z): numbermethod

Surface height at world (x, z), including shoaling and breakers. The horizontal displacement is inverted in 4 fixed-point steps. Gerstner tiers evaluate the spectrum; FFT tiers read the swell cascade back from the GPU (1–3 frames old).

#water.sampleNormal(x, z, out?): THREE.Vector3method

Central differences of sampleHeight at ±0.5 m.

#water.isUnderwater(object?): booleanmethod

Whether object (default: the camera) is below the surface.

#Buoyancy

#water.buoyancy.addObject(object, options?): BuoyancyHandlemethod

Floats an object. Options: probes, size: { length, beam }, draft (0), heightSmoothing (2.5), rotationSmoothing, spring (true), tiltSample (0.8), rollJitter (0.012). You keep x, z and the heading; buoyancy writes height, pitch and roll. See Buoyancy and wakes.

#water.buoyancy.removeObject(objectOrHandle): voidmethod

Stops floating an object. handle.enabled = false pauses one instead.

#Wakes

#water.addWake(object, options?): WakeHandlemethod

Tracks a moving object: hull contact foam, a Kelvin V and a persistent trail. Options: length (10), beam (length / 3), headingOffset (0), useVelocityHeading (false). handle.speed is the measured speed in m/s. Up to MAX_HULLS (8) are drawn.

#water.removeWake(objectOrHandle): voidmethod

Frees the object's wake slot.

#Caustics

#water.caustics.patch(material, opts?): materialmethod

Adds animated caustics below sea level to a built-in lit material (Standard, Physical, Lambert, Phong, Toon), chaining onBeforeCompile. Options: strength (1), scale (0.11), lightAbsorption (0.25). See Caustics on your materials.

#State and diagnostics

Property
underwater: booleanThe camera is below the surface this frame
underwaterAmount: number0–1, smoothed
stats{ significantWaveHeight, chop, wind, underwater, sunElevation }
profiling: booleanTurn on GPU timing (EXT_disjoint_timer_query_webgl2)
gpuTimingsSmoothed ms per pass: world, water, overlay, foam, bloom, composite, and fft on FFT tiers
overlayLayer: numberThe layer drawn after the water
ocean: THREE.MeshThe ocean mesh in your scene (frustum culling off, follows the camera)
uniformsShared by every water shader. Safe to read
spectrum, bathymetry, wakes, foam, fft, pipelineThe subsystems. fft is null on Gerstner tiers, foam on low

#Other exports

#BuiltinSkyclass

The analytic sky: sun arc from time, zenith and horizon colours, a cloud deck, stars and moon. new BuiltinSky({ uniforms? }), mesh, sun, sunDirection, moon.direction, fogColor, ambient { sky, ground }, day, apply(params), follow(camera), bindLights(directional, hemisphere, opts), dispose(), and BuiltinSky.createUniforms().

#Buoyancyclass

new Buoyancy(surface) works with any object that has sampleHeight(x, z). addObject, removeObject, update(dt), objects.

#Wakesclass

add, remove, update(dt), list, and the hullA / hullB uniform arrays the shaders read. MAX_HULLS is 8.

#Causticsclass

new Caustics(uniforms), patch(material, opts), and the static Caustics.glsl (the same as CAUSTIC_FN_GLSL) for custom shaders.

#WaveSpectrumclass

The Gerstner spectrum shared by the GPU and the CPU: new WaveSpectrum(count), build(U, Lp, windAngle, chopScale), advance(dt), displacement(x, z, att, out), WA / WB uniform arrays, hs, chop, setCount(n).

#Bathymetryclass

bake(desc, defaultResolution), sample(x, z, out?) → { seabed, dist, dx, dz, train, breaking }, texture, trainTexture (1.1), xform, enabled.

#FFTWavesclass

The GPU FFT wave source: new FFTWaves(renderer, { size, cascades }), update(time, { wind, wavelength, windAngle, chop, hs }), sample(x, z, out) from the read-back swell cascade, targets[i].textures[0..1], slopeVariance[i], lambda, cascades[i] (L, rot, kmin, kmax, texel).

Export
PRESETSRecord<string, Partial<WaterParams>>: tropical, sunset, dusk, storm, foggy, moonlit, arctic
DEFAULT_PARAMSThe defaults every preset fills from. See Water parameters
getPresetParams(preset)Complete, deep-cloned params for a name or partial object. Throws on an unknown name
QUALITY_LEVELSSee Quality and performance
CAUSTIC_FN_GLSLcaustic(uv, t), causticRGB(worldPos, refrSun, t, scale)
SKY_GLSLSky uniforms plus skyBase(d), skyColor(d, withDisc), envReflect(d), hazeColor(d). Include NOISE_GLSL first
NOISE_GLSLsk_hash, sk_noise, sk_fbm, safeNormalize2