Real-Time Water Simulation: From Particle Solving to Rendering
This article explains why real-time water simulation is difficult, compares the three common technical approaches, and walks through a practical particle-solver pipeline, including neighbor search, density constraints, time stepping, surface reconstruction, optical rendering, foam, parameter tuning, and troubleshooting. It also covers how AI-assisted programming can shorten the path from idea to prototype without replacing a solid understanding of fluid algorithms.
1. First, Clarify the Difficulty: Why Water Is One of the Hardest Effects to Implement
Many developers discover this when they first attempt a water demo: a model can generate hundreds of lines of code in a minute, but the result either looks like a pile of floating glass beads or like a boiling pot of porridge. The problem is usually not the rendering pipeline itself. It is the lack of a clear breakdown of the physical and visual characteristics of water.
The engineering difficulty of water simulation comes mainly from four overlapping factors:
- Incompressibility is a globally coupled problem. Gas can absorb error through density changes, but water cannot. A tiny local volume error can be instantly amplified during pressure solving, causing particles to clump together or the whole volume to “explode.”
- The free surface has no topological constraints. Water surfaces break, splash, and merge. There is no fixed triangle mesh that can be reused every frame. Instead, each frame must infer “where the water is and where the air is” from the particle distribution.
- Multiple scales coexist. A calm pool and a splash of foam can differ by three orders of magnitude in temporal and spatial scale. It is difficult for the same set of parameters to work well across all of them.
- Visual perception is extremely sensitive. People have an intuitive physical expectation of how water moves. Even small errors are noticed immediately. The tolerance is much lower than for stone, cloth, or smoke.
Only after understanding these four points can the technical choices below be justified.
2. Trade-offs Among Three Technical Approaches
The industry generally handles water with three broad categories. They are not replacements for one another. In practice, they are often combined.
1. Animated Water: Trading Assets for Cost
Pre-made normal/displacement maps and visual-effect sequences can be triggered when interaction occurs. The nonlinear behavior of waves is “baked” offline, so the runtime solving cost is almost zero. This is suitable for distant ocean surfaces, decorative fountains, and UI backgrounds. The drawback is limited interactive feedback. Users cannot truly “stir” the water in a meaningful way.
2. Grid or Height-Field Methods: Trading Equations for Stability
A height field can be used to model the water surface. Shallow-water equations can describe wave propagation, or spectral methods such as Gerstner wave superposition and FFT ocean spectra can generate large-scale ocean surfaces. The advantages are natural stability, easy computation of analytic normals, and predictable GPU cost. This approach is suitable for large-area water with weak interaction.
3. Particle Methods: Trading Compute for Freedom
Water is discretized into a large number of particles. Particles mainly interact with nearby neighbors, and constant density is maintained to reproduce fluid motion. This is the only path that naturally supports breaking, splashing, and vortices. It is also the mainstream implementation for “physical water.” The cost is the compute required for particle count, neighbor search, and multiple substep iterations.
In practice, a hybrid architecture is common: large calm water surfaces use a height field because it is cheap and stable; the user interaction area adds a particle layer to handle splashing and disturbance; distant water can use an animation layer to preserve the overall look. The key is to define the boundary rules between the systems. A common approach is to let particles write back to the height field as disturbances after they leave the water surface or decay below a threshold. This prevents the two systems from fighting at the boundary.
3. Core Implementation Pipeline of the Particle Solver
This section focuses on two particle methods with strong engineering validation: Smoothed Particle Hydrodynamics (SPH) and its incompressible variants, and the position-based fluid method (PBF). The advantage of PBF is explicit volume-error control and better stability with larger time steps. The cost is that each substep requires multiple constraint iterations.
1. Neighbor Search: From O(N²) to O(N)
A naive implementation checks every other particle for each particle. Once the particle count reaches the tens of thousands, this becomes unusable. The common approach is spatial hashing plus counting sort:
// Hash integer coordinates into grid cells to avoid dynamic allocationhash = (ix * 73856093) XOR (iy * 19349663) XOR (iz * 83492791)Per-frame flow:1. Compute cell indices from particle positions2. Perform prefix sum over indices to get the starting offset for each cell (counting sort)3. For each particle, iterate over 3x3x3 = 27 neighboring cells and collect candidates4. Perform a second filtering pass using the distance threshold h
Two details are easy to get wrong in implementation. First, the cell size should match the smoothing radius h. Otherwise, the neighbor search either misses neighbors or does unnecessary work. Second, rebuilding the hash every frame is usually simpler than maintaining an incremental structure, and it is also easier to parallelize on the GPU.
2. Density Constraints and Pressure Projection
The following is a simplified PBF substep skeleton. The logic matches mainstream implementations:
for substep in 1..S:# 1. Integrate external forces and predict positionsv += g * dtx_pred = x + v * dt# 2. Rebuild neighbor structurebuild_hash_grid(x_pred, h)# 3. Iterate density constraints to correct predicted positionsrepeat I times:for each particle i (parallel):rho_i = mass * sum_j W(r_ij, h) # accumulate smoothing kernelC_i = rho_i / rho0 - 1 # volume constraint errordP_i = -grad_C_i / (sum_k |grad_C_i|^2 + lambda_relax)for each particle i (parallel):x_pred += dP_i# 4. Derive velocity from position change and resolve boundary collisionsv = (x_pred - x) / dtx = x_predcollide_boundary(x, v) # normal bounce + tangential friction
Several points deserve special attention:
- The relaxation term
lambda_relaxis not optional. It is a regularization term in the denominator. It prevents division by near-zero values and numerical jitter when the constraint Jacobian becomes very small. If it is too small, particles may jitter at the surface. If it is too large, the water becomes overall “soft” and incompressibility worsens. - Visually incompressible does not mean mathematically incompressible. Strict incompressibility is often unattainable within a real-time budget. In practice, it is common to allow volume errors on the order of 1% and spend the saved compute on more iterations or more particles.
- Boundary handling should use predicted positions when testing collisions. A penetration correction should also be performed after velocity updates. Otherwise, high-speed particles can pass through container walls within a single frame.
- Surface tension can be added separately as a cohesion kernel term. Its purpose is to help water droplets maintain their shape instead of being stretched into thin filaments.
3. Time Step and Stability
The stability of explicit integration is constrained by the CFL condition: the displacement of a particle within one time step should not significantly exceed its neighbor scale. A common engineering solution is to use a fixed small time step with a variable number of substeps, rather than forcing stability with a variable time step:
fixed_dt = 1 / 60substeps = clamp(ceil(max_speed * fixed_dt / (0.4 * h)), 1, 4)
It is also important to decouple the rendering frame rate from the physics step. Physics advances with a fixed step, while rendering uses interpolation. This way, on lower-frame-rate devices the image may feel choppy, but the water will not “disappear.”
4. From Particles to Pixels: Rendering Pipeline Breakdown
The particle solver only tells us “where the mass is.” The visual quality depends on rendering.
1. Surface Reconstruction
Particles are discrete points. Rendering them directly as spheres will make them look like marbles. There are three common approaches:
- Screen-space fluid rendering: Write particle depth and normals into a G-buffer, apply bilateral filtering or smoothing, and reconstruct the surface. It is low cost, but edges may appear slightly soft.
- Isosurface extraction, such as Marching Cubes–style algorithms: Extract the isosurface from a density field. Geometry quality is the highest, but it requires 3D textures and additional triangle generation cost.
- Ray marching of an implicit surface: Accumulate the kernel function along the view ray in the shader. This is suitable for offline rendering or high-quality paths.
For normals, it is better to derive them from the density-field gradient rather than from particle velocity. Density gradients are more stable in regions where the surface breaks apart.
2. Optical Appearance
The realism of water mostly comes from getting three small things right:
- Fresnel effect: The closer the viewing angle is to grazing, the stronger the reflection. The Schlick approximation is sufficient. Pay attention to the base reflectance value. For water it is around 0.02. If it is too high, the surface will look metallic.
- Refraction and reflection: Refraction is usually implemented with screen-space distortion sampling. Reflection can use screen-space reflections, planar reflection maps, or environment probes, depending on the cost budget. When combining refraction and reflection, use the Fresnel term for weighting rather than simply adding them together.
- Caustics: An approximate method is to project light intensity onto the bottom surface according to the divergence of the water surface height, meaning areas where light converges or diverges. It is not physically exact, but it contributes strongly to the visual result. It is a cost-effective source of “cheap realism.”
3. Foam and Spray
Foam amplifies the perceived quality of water. A common approach is to use a two-channel time-evolving texture advected along the velocity field, mixed by three drivers: local speed, local density deviation, and vorticity. The important point is to give foam its own decay and lifecycle. Otherwise, it may look like the entire pool always has foam.
5. Parameter Tuning and Troubleshooting
The table below gives empirical ranges. Actual values must be calibrated for the specific scene. These are not performance guarantees for any product.
| Parameter | Empirical Range | Effect of Increasing / Decreasing |
|---|---|---|
| Particle count | 3k – 30k | Defines the upper limit of detail; cost grows roughly linearly |
Smoothing radius h |
1.5 – 3 times the initial particle spacing | Too large: the surface becomes mushy; too small: the density field becomes noisy |
| Constraint iterations | 2 – 4 | Improving incompressibility; returns diminish quickly |
| Substeps | 1 – 4 | Priority for stability; increase these before increasing iterations |
| Relaxation coefficient | 1e-3 – 1e-1 | Too small: jitter; too large: the water becomes soft |
| Rest density | Calibrated from particle count | Wrong calibration causes global expansion or collapse |
Common symptoms and corresponding troubleshooting directions:
- Particles clumping together: Constraint iterations are insufficient, or the kernel support radius does not match the particle spacing.
- Particles scattering or penetrating geometry: The time step is too large. Increase substeps first, then check whether boundaries are handled using predicted positions or post-update positions.
- High-frequency surface jitter: The relaxation term is too small, or normals/depth lack smoothing. Smooth the normals first, then fine-tune the relaxation term.
- Volume continuously expanding or collapsing: Rest density and mass calibration are wrong. Perform a static test: place the water under gravity for several seconds and check whether total center-of-mass drift and volume error converge.
- Near-field detail looks fine, but distant water looks sparse and broken: This is typical resolution dependence. Introduce LOD or hybrid partitioning instead of simply adding more particles.
The key to debugging efficiency is reproducibility and automated regression. Fix random seeds, save parameter sets along with recordings or screenshots as baselines, and run batch comparisons after every change. This kind of regression work is embarrassingly parallel and is well suited to containerized batch execution. Logs and runtime metrics should be collected centrally in a logging and monitoring system to avoid silent failures during long-running jobs.
6. How AI-Assisted Programming Shortens the Path from Idea to Demo
For “effect-driven” development tasks, the difficulty is that requirements are hard to formalize. A user may say, “the water needs to look more realistic,” but the implementation requires concrete values such as particle spacing, iteration count, and Fresnel coefficient. Current AI programming tools happen to fit several parts of this workflow, and developers should use them deliberately:
- Long context for specification alignment. Feed in solver constraints, performance budgets, and reference implementation code all at once so the model can reason within a complete context. This reduces the back-and-forth of explaining the same thing every turn. Writing constraints such as “maximum particle count,” “target frame rate,” and “which approaches are forbidden” in the context is far more effective than correcting mistakes afterward.
- Multimodal input for visual parameter calibration. Capture key frames from a reference image, or provide a reference video clip, and let the model translate “looks like this” into concrete values such as refraction strength, foam thresholds, and dispersion ranges. This is one of the hardest areas for text-only prompts.
- Adjustable reasoning depth for cost tiering. Use high reasoning effort for algorithm derivation, numerical-stability analysis, and constraint Jacobian derivation. Use low reasoning effort for boilerplate code, configuration changes, and naming refactors. Spending compute where actual reasoning is required is one of the most practical ways to use these tools.
- Built-in retrieval and code execution for closed-loop validation. Let the tool look up relevant public technical material, execute parameter sweeps, run numerical conservation checks, and read back logs. This is much more efficient than manually pasting error messages back and forth.
- Agentic decomposition for milestone-based progress. Break the task into milestones such as “solver skeleton → neighbor structure → surface reconstruction → optical appearance → performance optimization.” Give each milestone verifiable acceptance criteria, such as “after resting for 5 seconds under gravity, volume error is below 2%.” This gives the automated workflow a clear success criterion at each stage.
It is important to remember that these tools accelerate implementation and iteration. They do not replace an understanding of the algorithms. If numerical stability is delegated to a generation process that does not understand constraint projection, the usual result is water that looks plausible but blows up when it runs.
7. Practical Recommendations
If you are building a water effect, the recommended progression is:
- First establish static correctness: Test a single particle under gravity, then two particles, then a cube of water at rest. Confirm that volume error converges before discussing rendering.
- Then build the minimal rendering loop: Combine depth/normal reconstruction, Fresnel reflection, and a single refraction pass. Confirm that it “looks like water.”
- Finally add the presentation layers: Foam, caustics, splash particles, and interaction disturbances. These are multiplier effects. If the solver is wrong, they will only amplify the errors.
- Perform parameter sweeps and regression testing throughout: Save baselines, quantify the benefit of each tuning change, and avoid oscillating back and forth based only on intuition.
The engineering essence of water simulation is to decompose a globally coupled numerical problem into several controllable local approximations, then use rendering trade-offs to hide the remaining error inside human perceptual blind spots. Understanding which errors can be absorbed at which layer is more important than memorizing a particular formula.
