Fluid Simulation Optimization on Rust

52 points N4ivePackag3

Hey, I**'m a completely noob on rust**. Keep that in mind. And I need a little bit of help.

I've been creating a fluid simulation on rust following Sebastian Lague's implementation on Unity.
I wanted to learn rust so I decided that this fluid simulation should be my first project.

I was physicist before I became a software engineer. ButI've mostly worked with Python, JavaScript, Java. I tried to implement this first on C++, got a more stressed than I've should, than decided to try Rust, and everything worked fine. I'm starting to like this language.

I decided to use Piston crate as a way to visualize my simulation, it's just there to render particles on the screen, that's it. Piston is doing its job slowly, probably that is completely my fault because of how I'm using it, but I don't know how I could draw the particles faster.

Currently the simulation behave as it should. The fluid does behave as a fluid very similarly to Lague's implementation, I've also implemented an algorithm Lague describes to reduce the complexity from O(n²) to O(n). This obviously helps a lot, it consists in dividing space into grids, and calculation interaction only on pair of particles on neighboring grids. I've even used Leap frog integration instead of Euler's, so I could achieve better results with a small time step on the simulation, something Lague wanted to implement himself.

But... it is still too slow. Too slow.

Lague's implementation (even without his GPU parallelization) is able to handle easily 4k particles at 60FPS, while anything above 1k - 2k particles leads to updating time beyond 1/60 of a second, so it does not run at 60 FPS.

The main difference from our implementations besides the obvious fact that he is using Unity while I'm using Rust/Piston, is that I have not implemented multi-threading in my code. At first I thought, "oh obviously, that's it". But when I tried to use Rayon Crate to implement this I ended up with a code much slower than before (an order of magnitude at least). And then I started reading lots of things about people saying multi-threading is not the holy grail... and yeah its not... but idk I'm sure I'm messing this up somewhere.

I'm open to ANY recommendations, suggestions anything.

How can I draw the particles faster? How can I update their state faster? Is there another algorithm trick that could help me? How can I achieve multi-threading? Should I? I'm doing something wrong?

Idk. Here's the repo, In case someone needs/wants to take a look.

Took a lot of effort to get here