# Fluid Simulation

from Red Blob Games
29 Nov 2021

I had tried fluid simulation back in the 90s and it was a lot of fun. I did it on a hex grid, and with erosion, sedimentation, and other fun stuff. I’ve wanted to try out Jos Stam’s famous paper[1], so I’m looking at Mike Ash’s blog post[2] and also watching a Coding Train video[3], and attempting to write it with shaders. Unorganized notes for myself:

• “density” means the amount of dye in the fluid; the fluid is incompressible so the total amount in any grid cell is constant
• `diffuse` is used to smear out the density (dye can spread out) but it is also used to smear out the velocities; it’s a blur function?
• `set_bnd` sets the boundary cells; I’m going to let it wrap around and ignore this for now
• `lin_solve` seems to be setting `X` to `(X0 + a*sum(neighbor X)) / (1 + 6*a)`, for some `a` which makes no sense to me, as it’s viscosity * N² ?! Why would N matter here??
• `project` looks complicated and also confusing, as it takes two parameters `p` and `div` but then Vx and Vy are passed into these two?! Looks like they need temporaries and are reusing some of the arrays that aren’t being used. From the paper, it’s a “Hodge decomposition” step: subtract the gradient field from the vector field to end up with a field that preserves fluid volume (since it’s incompressible we want it to be constant). In theory the gradient field is low but it adds up so this step makes the simulation stable.
• `advect` is complicated because it’s doing linear interpolation from the matrix, but in GL I can ask the texture lookup to do that for me. Instead of forward simulating the fluid from each grid square through the velocity field, which is tricky and also might be unstable, Jos backward simulates, asking how much fluid will end up in each grid square, and this is stable.

I ended up reading the paper, reading the blog post, and watching the talk, but not actually implementing anything :-( especially after reading at the end of the paper that parts of it are patented (although I’m guessing that would be expired by now).

I mostly used this project to motivate myself to learn the techniques. I really should implement it at some point but I don’t actually have a use for it right now.

Email me , or tweet @redblobgames, or comment: