Since no existing code fit my requirements, I started working on my own fluid simulator a few weeks ago. The idea was to try both a grid-based and a particle-based method, and see which worked better for my situation. I started with the grid-based version.
My code was not based on Stam’s work, because I had not discovered that at the time. Instead, I based my code on the FORTRAN code of the CFD course labs. That code, in turn, was based on the SOLA-VOF code from a 1979 paper by Hirt and Nichols called Volume of Fluid (VOF) Method for the Dynamics of Free Boundaries. The actual code is available as a scanned PDF. Working my way through 2000 lines of FORTRAN code was not my idea of fun, but it has been very educational.
I began in vanilla C++, because debugging and experimenting with CPU code is so much easier than with shader code. I used OpenGL and GLFW for some quick visualization.
I currently have a test setup showing a so-called “lid-driven cavity flow”. This is a popular test case where a square box with fluid is simulated, which is driven at the top as if a conveyor belt were used as the lid. At a sufficiently high viscosity, this should result in a stable situation. As you can see in the screenshot, it does create a nice swirl. A nice counter-swirl is created in the bottom left corner. However, I’m still having instability problems. The artifacts on the right side eventually develop into a wobbly mess that keeps swirling around. It looks very interesting, runs in real time on the CPU, and the simulation does not explode, but it’s far from perfect yet.
This simulation assumes that everything is homogeneous: there is no distinction between air and water. Adding this is more difficult than you might think at first, because each grid cell may be partially filled with water. Letting this water go with the flow (its own flow, mind you; this is called “self-advection”) can cause ‘smearing’ of these values, and you’d end up with lots of partially-filled cells. This is not how real water behaves: at a given point in space, either there’s water or there isn’t. This a major problem when using a grid method to simulate these so-called free-surface flows.
The plan for this week is to fix the bug(s) causing these artifacts, stabilize the flow, then add the free surface to separate water from air. The VOF paper should contain enough information to get this working.