Search This Blog

Playing with Gravity to Learn CUDA: Optimization

The CUDA gravity simulator has reached the point where it has a simulation engine that can display a 1024-body simulation in real-time. (Check it out from the beginning.) In getting to that point, we hit the limit on the number of threads that can be started in a single thread block in CUDA, but of course, that is not the end of the story. We can still increase the number of bodies in the simulation further, and after we've explored how to do that, we'll experiment with the parameters of the simulation to see if we can get anything interesting going that looks like a star cluster. Spoiler alert: we can, and we will.

Model of the Solar System

Playing with Gravity to Learn CUDA: An N-Body Simulation

Now that we have a working simulation engine and a real-time display of a running simulation, it's time to see what we can do with this gravity simulator we've been building in CUDA. We'll start off with a complete simulation of the solar system to see if we can get a reasonable multi-body system simulating correctly. Then we'll move on to filling up the 640 cores on my GeForce GTX 1050 card to make full use of the GPU and see where the base limits are for this simulator. This should be fun.

Model of the Solar System

Playing with Gravity to Learn CUDA: Simulation Display

We're building a gravity simulation on a GPU using CUDA, and last time we actually got a working simulator running for a 2-body system. That was exciting, but there were some drawbacks, namely the printout-copy-paste-to-spreadsheet-and-graph way of visualizing the simulation. In this post we're going to remedy that issue with a simulation display that shows the position of the bodies graphically while the simulation is running and that also runs on the graphics card alongside the simulation. We'll even make the position buffer multipurpose so that we can calculate the positions directly into this buffer, and then turn around and draw those positions into a window from the same buffer. No copying required, not even automated copying. 

Making this display for the gravity simulator turned out to be more difficult than I thought because I haven't programmed in OpenGL since the graphics course I took in college, and I've certainly never done any OpenGL-CUDA interop before. I managed to pull something together by leaning heavily on the N-Body sample project that's part of the nVidia CUDA sample projects. This sample project is also a gravity simulator, but the underlying simulation engine is substantially different than the one we've built so far. Even so, I was able to use the renderer without any modifications. Let's see how it works.

Earth in the Sun's orbit