Skip to content

About

JS browser based library for hydrodynamic simulations

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

gradis-lib

GPU (WebGPU) 2D flood simulation as a library. It covers the solvers, the water you add and the terrain the water runs on.

  • Seven solvers. FluxCell is a second-order MUSCL-Hancock / HLLC shallow-water solver (fluxcell-gpu). The other six are explicit schemes: local Lax-Friedrichs, diffusive wave (plain and Manning), kinematic wave, relaxed diffusion and slope-proportional transfer.
  • GPU-resident state. Depth and velocity live in GPU buffers.
    • Advancing never reads them back.
    • FluxCell runs 256-step batches with its own GPU timestep and rollback.
    • The explicit schemes submit up to 256 substeps at once, with the CFL step reduced on the GPU.
  • Reads only when you ask.
    • Whole fields come back through persistent staging buffers.
    • A list of cells (gauges, sections) can be gathered on the GPU instead.
    • The per-cell maximum depth and speed can be kept on the GPU for flood maps.
    • The buffers are exposed for your own WebGPU passes or renderers.
  • Large grids. The engine needs 8 bytes per cell in its largest buffer. requestDevice() asks for the adapter's full limits, so tens of millions of cells fit on a desktop GPU.
  • Water.
    • Initial depth.
    • Point inflows [m³/s].
    • River inflows along a line, with a hydrograph.
    • Uniform rain and per-cell rain grids.
  • Terrain.
    • GeoTIFF reading: stripped or tiled; uncompressed, Deflate or LZW; with predictors; float or integer samples.
    • No-data masking.
    • Cell size from geographic or projected rasters.
    • An optional priority-flood depression fill on typed arrays (about 1 s for 4 million cells).

Requirements

  • A WebGPU device: Chrome or Edge 113+, including headless Chrome under Puppeteer or Playwright, or a WebGPU implementation for Node.
  • Node.js ≥ 18 to build and test.

Installation

git clone https://github.com/uihilab/gradis-lib.git
cd gradis-lib
npm install
npm run build        # shaders inlined into src/engine/shaders.ts, bundle to dist/ (ESM + CJS + .d.ts)

Then use it from another project with npm install ../gradis-lib, or npm pack and install the tarball.

FluxCell's shaders must be served next to it. fluxcell-gpu loads its .wgsl files relative to its own module.

  • Vite does this for you.
  • esbuild, tsup and Rollup need node_modules/fluxcell-gpu/src/shaders/ copied into a shaders/ folder next to the bundle. The browser example's tsup.config.ts shows how.

Quick start

import { requestDevice, readGeoTIFF, prepareDEM, Simulation } from 'gradis-lib';

const device = await requestDevice();
const dem = prepareDEM(await readGeoTIFF(await (await fetch('terrain.tif')).arrayBuffer()));   // { fill: 'full' } to fill depressions

const sim = await Simulation.create(device, { dem, solver: 'fluxcell', manning: 0.035, trackMaxima: true });
sim.addRiverInflow('river', sim.cellAt(x0, y0), sim.cellAt(x1, y1),
                   [{ t: 0, q: 50 }, { t: 3 * 3600, q: 600 }, { t: 12 * 3600, q: 80 }]);
sim.setRain(20);                                   // mm/h

await sim.run(12 * 3600, 900, async ({ t }) => {   // 15-minute reporting interval; nothing is read back
  const [g] = await sim.sample([sim.cellAt(gx, gy)]);
  console.log(t, g.h);
});

const { depth, speed } = await sim.maxima();       // flood map: maximum depth and speed per cell

Starting from arrays instead of a GeoTIFF:

const sim = await Simulation.create(device, {
  dem: { terrain, width, height, dx: 5 },          // row-major, row 0 north, metres
  depth: initialDepth,                             // optional
});

Prepared terrain can also come from your own arrays, here with every depression filled:

const dem = prepareDEM({ data, width, height }, { dx: 2, fill: 'full' });

Solvers

Name Scheme Velocity buffers
fluxcell FluxCell: 2nd-order MUSCL-Hancock, HLLC, hydrostatic reconstruction, fused kernel, GPU timestep with rollback m/s
lax-friedrichs Local Lax-Friedrichs (Rusanov), full shallow-water equations, well balanced, wetting and drying, CFL step from a GPU reduction m/s
diffusive-wave-manning Diffusive wave with Manning friction in the local inertial form (Bates et al. 2010; semi-implicit friction and theta = 0.7 face averaging, de Almeida et al. 2012): face discharges carried between steps m/s
diffusive-wave Diffusive (zero-inertia) wave: Manning discharge from the face flow depth and the water-surface slope m/s
kinematic-wave Kinematic wave, upwind: Manning discharge from the giving cell's depth along the water-surface slope (fills and spills hollows) m/s
relaxed-diffusion Gravity relaxation of the water surface at the shallow-water wave speed, no friction (fast screening) m/s
slope-proportional Velocity proportional to the water-surface slope (1 m/s at 1 %, at most 5 m/s): fast filling and spilling m/s

The explicit schemes compute each face discharge once for both cells it separates (mass is conserved to rounding), never move more than a fifth of the surface difference or a quarter of a cell's water through a face per substep, and take the CFL step of the GPU-reduced wave speed.

advance(seconds) always ends exactly on the requested time:

  • FluxCell stops on the target time.
  • Lax-Friedrichs logs the dt of every substep on the GPU and adds them up.
  • The fixed-step schemes split the interval into equal substeps below their stability limit.

Forcing (hydrographs) is taken at the interval's midpoint.

Water

Input Call
Initial depth [m] depth option, or setDepth(h)
Point inflow [m³/s] addPointInflow(id, [col, row], rate, radius?)
River inflow line addRiverInflow(id, from, to, q | [{ t, q }])
Uniform rain [mm/h] setRain(rate)
Rain grid [mm/h per cell] setRainGrid(grid)
Manning's n manning option, or setManning(n | grid)

River inflows. The discharge enters as a source spread evenly over the active cells of the line between the two cells, under every solver; draw the line across the channel where the river enters the grid.

Boundaries

All four grid edges are open, and cells masked as no data are open sinks. Closed sides are made by raising the terrain one or two cells in from the edge.

Lower level: Engine

sim.engine (or Engine.create(device, { terrain, width, height, dx, ... })) gives direct access:

  • Buffers: depthBuffer, velX, velY, terrainBuffer, manningBuffer, maskBuffer, maxDepthBuffer, maxSpeedBuffer.
  • Reads and controls: readDepth(), readState(), sample(cells), maxima(), budget() (FluxCell's volume accounting), setSolver(), and every input in SI units.

Example

npm run example:browser    # http://127.0.0.1:5310/examples/browser/

The playground runs five cases:

  • a dam break;
  • a river flood wave;
  • rain on a catchment;
  • an urban flash flood;
  • ponds filling and spilling.

It can also open your own GeoTIFF terrain. While it runs it shows depth, maximum depth, speed or water level over a hillshade, with gauges and a water balance.

Project layout

src/
  index.ts          public API
  Simulation.ts     terrain -> run, raster coordinates, rain in mm/h, reporting intervals
  engine/
    Engine.ts       GPU state, solvers, water inputs, advance, reads
    FluxCell.ts     FluxCell adapter (fluxcell-gpu)
    solvers.ts      solver names and substep limits
    shaders.ts      generated from shaders/*.wgsl
  dem/
    geotiff.ts      GeoTIFF reader
    prepare.ts      no-data mask, depression fill, cell size
  device.ts         WebGPU device with the adapter's limits
shaders/            WGSL solvers, rain, wave-speed reduction
tests/              CPU tests (GeoTIFF, fill, cell size); GPU checks (tests/gpu)
examples/browser/   playground

Development

npm install
npm run shaders     # regenerate src/engine/shaders.ts after editing shaders/*.wgsl
npm run build
npm run typecheck
npm test

Acknowledgements

gradis-lib is developed at the Hydroinformatics Lab at Tulane University.

License

MIT, see LICENSE.

About

JS browser based library for hydrodynamic simulations

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages