• Register
Post news RSS GPU Physics (January 7, 2020)

This is an area of exploration for now, but I thought I’d put this in the development log because it’s pretty cool.

Posted by on


GPU Physics

"This is an area of exploration for now, but I thought I’d put this in the development log because it’s pretty cool.

Physics in Unity is very CPU heavy, and it’s unthinkable to have many rigid bodies interacting with each other without causing slowdowns or hiccups. But what if you want 50k+ rigid body objects in your game?

The answer is GPU acceleration. Really, the answer to most performance problems is to offload some CPU computation to the GPU - if it’s possible to do so. It’s not easy though, because CPUs and GPUs work very differently. CPU is super fast for traditional linear tasks and can access memory easily. GPU is super fast for parallel tasks, but it’s stateless.

Lucky for us, smart people at Microsoft and Nvidia have developed ways to facilitate writing general computing code on the GPU. Compute shader, direct compute, GPGPU, all those things are awesome. The power of the GPU with the convenience of the CPU! Well, sort of.

It does require quite a bit of setup to be able to use the GPU for general computing purposes. You have to write in HLSL, and you have to create structured buffers and/or render textures in order to be able to look at the previous frame’s data and do computing on the GPU. It also took me a while to get used to the parallel computing paradigm required for GPU programming

The physics demo in the clip above is 70k particles with collisions enabled between every particle in the scene. Frame rate is above 60fps even when using complicated spring equations for physics. The trick for optimizing this was to put particles into cubic grid cells so that they’d only have to check collision against the balls in the same grid cell. The entire pool is composed of hundreds of cubic grid cells. Balls don’t have to check collision against as many other balls with this idea, so it improves performance (and accuracy for some reason) - it just requires work to setup.

It’s going to take some work to support different types of collider shapes other than a sphere, but I think I can do it. I wanted to try making a pool of skulls (AS MANY SKULLS AS POSSIBLE) that players can walk around in with collision in the game. I think this will be possible with GPU physics.

I’ve also tried DOTS physics before, and that’s very performant too when it’s fully multi-threaded on the CPU with burst compiler and all of those ECS things enabled, but for now, I think GPU physics is more reliable. ECS in Unity is still in preview and could be unstable depending on what you’re doing." (c) Sean, the Wonhon: A Vengeful Spirit developer.

Post a comment
Sign in or join with:

Only registered members can share their thoughts. So come on! Join the community today (totally free - or sign in with your social account on the right) and join in the conversation.