I wanted to try out some low‑level programming and get a better feel of how game engines handle physics, so I spent the last few days building a 2D fluid simulation.
The math is based on the Navier‑Stokes equations, using Jos Stam's famous GDC '03 paper ("Real‑Time Fluid Dynamics for Games") as the foundation.
You can check out the open‑source repo here if you want to look at the C++ code: https://github.com/Aj4y7/flu.id
The optimisation challenge
Getting the math to work was one thing, but keeping it from lagging was the hardest part. As soon as I bumped the grid size to 256x256, the framerate dropped badly. To bring it back to a smooth 60 fps I had to completely re‑architect it:
1. CPU Multithreading (OpenMP)
Originally the physics loops (Gauss‑Seidel relaxation, semi‑Lagrangian advection) were stuck on a single thread. I added OpenMP to flatten the 2D arrays so the heavy maths are now split across all my CPU cores.
2. Bypassing CPU graphics (Vertex Arrays)
At first I was plotting pixels on the CPU – incredibly slow. I stripped out software rendering, batched the grid geometry into two triangles per cell (sf::VertexArray) and sent it straight to the GPU.
3. Pre‑computed LUTs
Calculating the Viridis colour map needs expensive power and sine maths. I pre‑computed these into a 1‑D texture at startup. Now the CPU just passes density values and the GPU textures it instantly.
(https://preview.redd.it/ahqivoe3m7sg1.gif?format=png8&s=d85a864ad195f5916a0c0e4449661f32e34c7cb7)
I'm thinking of forking it just to rename it aadu‑paadu simulator.