#### Jay Taylor's notes

back to listing index### Fluid Simulation (with WebGL demo) - Zero Wind :: Jamie Wong

[web search]*jamie-wong.com*)

# Fluid Simulation (with WebGL demo)

*Note: The demos in this post rely on WebGL features that might not be
implemented in mobile browsers.*

About a year and a half ago, I had a passing interest in trying to figure out how to make a fluid simulation. At the time, it felt just a bit out of my reach, requiring knowledge of shaders, vector calculus, and numerical computation that were all just a little bit past my grasp. At the time, I was working through the Fluid Simulation Course Notes from SIGGRAPH 2007, and was struggling with the math. Now armed with a bit more knowledge and a lot more time, and with the help of other less dense resources like GPU Gems Chapter 38. Fast Fluid Dynamics Simulation on the GPU, I was finally able to figure out enough to get something working. I am still a beginner at simulations like this, and I’m going to brazenly ignore things like numerical stability, but hopefully I can help leapfrog you past a few places I got stuck.

We’re going to work with the simplest 2D fluid simulation, where the entire area is full of fluid, and we’re going to ignore viscosity.

# The Velocity Field

As compared to a rigid, unrotating solid, where every bit of the thing has to be moving in the same direction at the same speed, each bit of a fluid might be moving differently. One way to model this is to use a vector field representing velocity. For any given (x,y) (x, y) (x,y) coordinate, this field will tell you the velocity of the fluid at that point.

u⃗(x,y)=(ux,uy) \vec u(x, y) = (u_x, u_y) u⃗(x,y)=(ux,uy)

A nice way to get an intuition about what a given field looks like is to sample the function in a grid of points, then draw arrows starting at each grid point whose size and orientation are dictated by the value of the function at that point. For the purposes of this post, we’re always going to be working over the domain x∈[−1,1] x \in [-1, 1] x∈[−1,1], y∈[−1,1] y \in [-1, 1] y∈[−1,1].

For instance, here’s a very simple field u⃗(x,y)=(1,0) \vec u(x, y) = (1, 0) u⃗(x,y)=(1,0) representing everything moving at a constant speed to the right.

And here’s a more interesting one u⃗(x,y)=(x,y) \vec u(x, y) = (x, y) u⃗(x,y)=(x,y) where things move away from the origin, increasing in speed the farther away from the origin they are.

We’re going to play with this one, u⃗(x,y)=(sin(2πy),sin(2πx)) \vec u(x, y) = \left( \sin (2 \pi y), \sin (2 \pi x) \right) u⃗(x,y)=(sin(2πy),sin(2πx)), since it creates some interesting visual results once we start making the fluid move accordingly.

For a more thorough introduction to vector fields, check out the Introduction to Vector Fields video on Khan Academy. The rest of the videos on multivariate calculus might prove useful for understanding concepts in fluid flow too.

Now then, let’s get things moving.

# Advection

Advection is the transfer of a property from one place to another due to the motion of the fluid. If you’ve got some black dye in some water, and the water is moving to the right, then surprise surprise, the black dye moves right.

If the fluid is moving in a more complex manner, that black dye will get pulled through the liquid in a more complex manner.

Before we dive into how advection works, we need to talk a bit about the format of the data underlying these simulations.

The simulation consist of two fields: color and velocity. Each field is represented by a two dimensional grid. For simplicity, we use the same dimensions as the output pixel grid.

Previously, I described the velocity field as an analytical function u⃗(x,y) \vec u(x, y) u⃗(x,y). In practice, that analytical function is only used to initialize the grid values.

The simulation runs by stepping forward bit-by-bit in time, with the state of the color and velocity grids depending only on the state of the color and velocity grids from the previous time step. We’ll use u⃗(p⃗,t) \vec u(\vec p, t) u⃗(p⃗,t) to represent the velocity grid at 2d position p⃗ \vec p p⃗ and time t t t, and c⃗(p⃗,t) \vec c(\vec p, t) c⃗(p⃗,t) to represent the color in the same manner.

So how do we move forward in time? Let’s just talk about how the color field changes for now. If we consider each grid point as a little particle in the fluid, then one approach is to update the color of the fluid where that particle will be, one time step in the future.

In order to run these simulations in real-time at high resolution, we want to implement them on the GPU. It turns out that this method of updating the value at the new location of the particle is difficult to implement on the GPU.

First, the position we want to write, p⃗+u⃗(p⃗,t)Δt \vec p + \vec u(\vec p, t) \Delta t p⃗+u⃗(p⃗,t)Δt might not lie on a grid point, so we’d have to distribute the impact of the write across the surrounding grid points. Second, many of our imaginary particles might end up in the same place, meaning we need to analyze the entire grid before we decide what the new values of each grid point might be.

So, instead of figuring out where our imaginary particles at the grid points *go
to*, we’ll figure out where they *came from* in order to calculate the next time
step.

With this scheme, we only need to write to a single grid point, and we don’t need to consider the contributions of imaginary particles coming from multiple different places.

The last teensy hurdle is figuring out the value of c⃗(p⃗−u⃗(p⃗,t)Δt,t) \vec c(\vec p - \vec u(\vec p, t) \Delta t, t ) c⃗(p⃗−u⃗(p⃗,t)Δt,t), since p⃗−u⃗(p⃗,t) \vec p - \vec u(\vec p, t) p⃗−u⃗(p⃗,t) might not be at a grid point. We can hop this hurdle using bilinear interpolation on the surrounding 4 grid points (the ones linked by the dashed grey rectangle above).

# Advecting the Velocity Field

Barring a bizarre sequence of perfectly aligned fans underneath the liquid,
there’s no reason why the velocity field wouldn’t change over time. Just as
black ink would move through the fluid, so too will the velocity field itself!
Just as we can *advect* c⃗ \vec c c⃗ through u⃗ \vec u u⃗, we can also
*advect* u⃗ \vec u u⃗ through itself!

Intuitively you can think of it this way: a particle moving in a certain direction will continue moving in that direction, even after it’s moved.

Since we’re storing velocity in a grid just like we did with color, we can use the exact same routine to advect velocity through itself. Below, watch the velocity change over time, with an initial velocity field of u⃗=(1,sin(2πy)) \vec u = (1, \sin(2 \pi y)) u⃗=(1,sin(2πy)).

If you tried playing around with this, and saw a bunch of weird hard edges and might’ve thought to yourself “I don’t think fluids work like that…”, you’d be right. We’re missing an important ingredient, but before we look at the solution, let’s take a closer look at the problem.

# Divergent Fields

Something about the velocity field below makes this intuitively not feel like a
fluid. Fluids just don’t *behave* like this.

Same problem with this one…

If you look at where the arrows are pointing in each of the above 2 simulations, you’ll see that there are spots where the all the arrows point away from that spot, and others where all the arrows point toward that spot. Assuming the volume of the liquid is staying constant, the density of the fluid has to be changing for such a velocity field to be possible.

Water is roughly incompressible. That means that at every spot, you have to have the same amount of fluid entering that spot as leaving it.

Mathematically, we can represent this fact by saying a field is
*divergence-free*. The divergence of a velocity field u⃗ \vec u u⃗, indicated
with div(u⃗) div(\vec u) div(u⃗) or ∇⋅u⃗ \nabla \cdot \vec u ∇⋅u⃗, is a measure of how
much net stuff is entering or leaving a given spot in the field. For our 2D
velocity field, it’s defined like this:

The first of the two not-very-fluidy fields above has an equation u⃗(x,y)=(x,y) \vec u(x, y) = (x, y) u⃗(x,y)=(x,y). Taking the divergence, we find:

This positive value tells us that, in all places, more stuff is leaving that point than entering it. In physical terms, this means that the density is decreasing uniformly everywhere.

The other not-very-fluidy field has an equation u⃗(x,y)=sin(2πx),0) \vec u(x, y) = \sin(2 \pi x), 0) u⃗(x,y)=sin(2πx),0). If we look at its divergence, we see:

Which tells us that in some places, density is increasing (where ∇⋅u⃗<0 \nabla \cdot \vec u < 0 ∇⋅u⃗<0), and in others, density is decreasing (where ∇⋅u⃗>0 \nabla \cdot \vec u > 0 ∇⋅u⃗>0).

Doing the same operation on the more fluidy looking swirly velocity field u⃗=(sin(2πy),sin(2πx) \vec u = (\sin ( 2 \pi y), \sin ( 2 \pi x ) u⃗=(sin(2πy),sin(2πx) that you saw in the section about advection, we discover ∇⋅u⃗=0 \nabla \cdot \vec u = 0 ∇⋅u⃗=0.

An incompressible fluid will have a divergence of zero everywhere. So, if we want our simulated fluid to look kind of like a real fluid, we better make sure it’s divergence-free.

Since our velocity field undergoes advection and can be influenced by clicking and dragging around the fluid, having an initially divergence-free velocity field isn’t enough to guarantee that the field will continue to be divergence-free. For example, if we take our swirly simulation and start advecting the velocity field through itself, we end up with something divergent:

So we need a way of taking a divergent field and *making* it divergence-free. To
understand what force makes that happen in the real world, we need to talk about
some honest-to-goodness physics.

# Navier-Stokes

The Navier-Stokes equations describe the motion of fluids. Here are the Navier-Stokes equations for incompressible fluid flow:

Where u⃗ \vec u u⃗ is the velocity field, ρ \rho ρ is density, p p p is pressure, ν \nu ν is the kinematic viscosity, and F⃗ \vec F F⃗ is external forces acting upon the fluid.

Since we’re pretending the viscosity of our fluid is zero, we can drop the ν \nu ν term in the first equation. In our simple simulation, external forces are only applied by dragging the mouse, so we’ll ignore that term for now, opting to allow it to influence the velocity field directly.

Dropping those terms, we’re left with the following:

We can expand this to its partial derivative form, expanding vector components to leave us with only scalar variables.

Remembering that these fields are all functions on (x,y,t) (x, y, t) (x,y,t), we can approximate the partial derivatives with finite differences. For instance, we can approximate the partial derivative of ux u_x ux with respect to t t t like so:

Because the procedure ends up being the same for both components, we’ll focus on only the x x x component here. Applying finite differences to all of the partial derivatives, we have this:

Ultimately what we want is u⃗(x,y,t+Δt) \vec u(x, y, t + \Delta t) u⃗(x,y,t+Δt), which will tell us, for a given point, what the velocity will be at the next time step. So let’s solve for that by rearranging the big long formula above:

If you look at the first three terms in this expression, what does it look like they conceptually represent? It looks like they represent the next velocity after we’ve taken into account changes due to the motion of the fluid itself. That sounds an awful like advection as discussed earlier. In fact, it will work quite well if we substitute the velocity field after it’s undergone advection. We’ll call the advected velocity field u⃗a \vec u ^ a u⃗a. So now we have:

So after all of that, we have an equation that relates the velocity field at the next time tick to the current velocity field after it’s undergone advection, followed by application of pressure.

We know that a divergence-free field that undergoes advection isn’t necessarily still divergence-free, and yet we know that the Navier-Stokes equations for impressible flow represent divergence-free velocity fields, so therefore we have our answer about what in nature prevents the velocity field from becoming divergent: pressure!

# Solving for Pressure

Now that we have an equation that relates u⃗ \vec u u⃗ to p p p. This is where the math gets messy. We start from the second Navier-Stokes equation for incompressible flow, applied at time t+Δt t + \Delta t t+Δt, and apply finite differences again:

Here, we can substitute our equations for u⃗ \vec u u⃗ expressed in terms of u⃗a \vec u ^ a u⃗a and p p p to get this monster:

Rearranging to have all of the p p p terms on the left and all the u⃗a \vec u ^ a u⃗a terms on the right, and multiplying both sides by 2ϵ 2 \epsilon 2ϵ, we have: