WebGPU notes / 48
WebGPU Fluid Simulation in Rust: GPU Water with wgpu
Simulate interactive water with Position Based Fluids, a GPU neighbor grid, a buoyant sphere, motion-driven ripples and wakes, subtle foam and splashes, and a smooth refractive surface.
Store the water data on the GPU
This example uses sib::render to run as a native app with wgpu or in a browser with WebGPU. Code creates all the shapes, colors, and lighting.
The water is made of small simulated particles. The default is 2,048 particles which can be changed as well. Their spacing, interaction range, collision size, and visible size change together, keeping the amount of water roughly the same at every setting.
Each particle uses 48 bytes of GPU memory. Three vec4<f32> values store its position,
velocity, density, and surface direction. Half the particles start in a shallow pool. The rest enter in groups
through the round inlet, spaced to match the speed of the stream. A negative value in the position's W component
stores how long a particle must wait before entering.
Each physics update advances time by 1/60 of a second. A timer tracks how many updates are due. The app can run up to two updates per displayed frame, which lets it keep up at 30 fps and handle small changes in frame timing. After a long pause or delay, it drops extra catch-up work to avoid overloading the GPU. Pausing stops physics and clears the timer. Reset restores the water and sphere.
Physics and drawing read the GPU data directly. The app copies 64 bytes of sphere data back to the CPU at most once every four frames. This updates mouse selection and sliders without making the simulation wait for the copy. Reset makes the app ignore any older copy that is still pending.
Find nearby particles
Each particle needs to find nearby particles to work out how the water should move. A 3D grid makes this faster. Each cell is as wide as a particle's interaction range, and the largest grid fits in 35×24×21 cells. The GPU clears the grid, then records which particles are in each cell. A particle only needs to search its own cell and the 26 cells around it.
Each cell stores up to 64 particle numbers next to each other in memory for fast reading. It also keeps a linked list, where each entry points to the next particle. If a cell has more than 64 particles, the search uses the full list, so crowded cells do not lose any neighbors. They still take more work to search. The grid is rebuilt after each round of position changes and before calculating velocity.
Keep particles from crowding together
The physics follows Position Based Fluids by Miles Macklin and Matthias Müller. The solver estimates how tightly particles are packed by giving nearby particles more weight than distant ones. It compares this density with a reference value from evenly spaced, resting particles. If the density is too high, it calculates small position changes to spread the particles out. The same spacing and interaction-range ratio is used at every particle setting.
sample surrounding water and integrate floating sphere
predict positions with gravity and body reaction impulse
repeat solver_iterations:
clear grid / build grid
calculate density multipliers
correct positions into the other buffer
clear grid / build grid
reconstruct velocities into the other buffer
apply neighbor viscosity into persistent particles
advect foam and integrate spray
propagate surface waves with two half steps
The solver repeats these density checks twice by default. You can increase this to six rounds. Each GPU dispatch, or batch of compute work, finishes calculating the correction amounts before the next batch reads them. The batches share one compute pass, and wgpu handles the required memory synchronization. Each round reads one buffer of predicted positions and writes the updated positions to another.
A small extra pressure helps stop particles from forming clumps. The solver limits how far each correction can move a particle. It also moves particles out of the sphere and keeps them inside the simulation area.
The solver calculates velocity from the final change in position. A separate step blends each particle's velocity with those of its neighbors to simulate viscosity, then slows it slightly. Speed is limited to 12 world units per second. Using a separate step keeps particles from reading velocity values while another step is changing them.
Make the sphere float
The copper-colored sphere acts like a light, hollow ball. The GPU stores its position, velocity, how much of it is underwater, and the push it returns to the water. A group of 64 GPU threads checks nearby particles to estimate the water level and flow around the ball.
Gravity pulls the ball down. Buoyancy pushes it up based on the volume below the estimated water level. Drag reduces the speed difference between the ball and the water, helping it move with the flow. The ball also collides with the basin floor and walls.
The nearby water receives an opposite push from buoyancy and drag. The moving ball also pushes particles out of its way. This lets the water and ball affect each other without waiting for data to return to the CPU. Drawing uses the ball's current GPU position, so its shape, shadows, and reflections stay together even if the slider values update later. A density below that of water lets the ball float if the water is deep enough. A higher density makes it sink.
Dragging the ball or using its X/Z sliders lets you control its position directly. Release it to let gravity and water forces move it again. Pausing stops the water and the ball's automatic movement. You can still move the camera and place the ball by hand.
Draw the water surface
The renderer reads the particle data already on the GPU. Nearby particles help it estimate the surface normal, which is the direction pointing out of the water. Particles at the surface appear as overlapping, flattened spheres. Separate droplets stay round.
A depth pass finds the visible front of these shapes and records its distance from the camera in an RG32F texture. A Depth32Float depth buffer keeps the closest surface visible. Another pass adds up the distances that light would travel through the particles. This gives a rough estimate of water thickness.
Four filters smooth the depth image: two horizontal passes and two vertical passes, each reading 25 samples. These bilateral filters blend nearby depths while keeping large depth changes apart. The shader blends between pixels to build a smooth surface and calculate its direction. Extra smoothing reduces small bumps on the pool while keeping the stream and separate drops distinct.
Reflection changes with the viewing angle, using the Fresnel effect. Reflected rays can hit the basin, inlet, or ball. If they miss, they use lighting from a studio-like environment created in code. Refraction bends the view through the water. Water thickness and light absorption, calculated with the Beer–Lambert rule, give it its color. The basin has tiles, dark outer walls, and shadows near contact points. Rounded tubes form the metal inlet. Depth checks decide which parts of the scene are visible in front of the water.
Particle debug view skips smoothing, draws smaller particles, and colors them by speed. To reduce GPU work, the water is drawn at 65% of the display width and height, with a maximum size of 960×540 and the same aspect ratio. The result is smoothly enlarged to fill the display. The controls stay at full resolution, and the drawing textures are recreated when the window size changes. The example uses standard WebGPU features. Its main physics shader uses eight storage buffers.
Create ripples and a wake
A separate 160×96 grid adds waves that are too small for the particle simulation to show. Each cell stores the water height, vertical speed, and surface slope. Two GPU updates per physics step move waves across the grid and gradually reduce their strength. They read and write alternating buffers. Wave speed depends on water depth and gravity, with a limit to keep the updates stable. Waves bounce off the basin walls and lose extra energy near the edges.
When the ball moves through the water, it pushes the surface up in front and draws it down behind. Moving it up or down sends ripples outward. The grid keeps the previous wave data, so the wake remains along the ball's old path after it turns or stops. A still ball, or one outside the water, creates no new waves. Existing waves keep spreading and fading. Pause freezes them, and reset clears them. Changing the particle count does not change the wave grid size, and turning foam off does not turn waves off.
The water shader reads the wave height and slope at each visible point. It uses them to adjust the surface position and direction for reflections and refraction. The effect becomes weaker on spray and raised sheets of water. These waves add visual detail based on the ball's motion. They do not push the particles or ball back.
Add foam and splashes
The GPU has space for 1,024 extra particles that show foam and spray around the ball. Free slots check exposed water particles near the wet ball. A greater speed difference between the ball and water creates more foam, and stronger movement can throw drops into the air. Calm water stops creating new effects.
Foam follows the water particle that created it. It lines up with the surface and flow, then fades over about one to two seconds. Spray takes some of its motion from the water and ball. Most drops are small and follow low arcs; stronger impacts can throw them higher. Gravity pulls them down. They disappear when they return to the water or hit the ball or basin.
Foam and spray are visual effects, so they do not change the amount of water or add forces to it. One quarter of the slots is reserved for spray, leaving room for new splashes while older foam fades. The fixed number of slots and one extra compute dispatch limit the work at every particle setting.
Overlapping foam shapes form a smooth trail along the flow. An R16F texture stores how much foam covers each point. The water shader colors the combined foam once with a faint green-blue tint. A limit on its opacity keeps the water visible underneath, even where many shapes overlap.
Spray is drawn later as partly transparent drops with small reflections and highlights. Faster drops stretch slightly in their direction of travel. Depth checks hide drops behind solid objects, and foam is only drawn on visible water. Both effects use the same reduced resolution as the water and need no extra texture files. They pause with the simulation, clear on reset, and are hidden in particle debug view. Toggle Foam & splashes to compare the result.