Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - fastest sorting algorithm for objects based on distance

Tags:

c++

sorting

I'm trying to make a game or 3D application using openGL. The game/program will have many objects in them and drawn to the screen(around 7000 of them). When I render them, I would need to calculate the distance between the camera and the object and sort them in order to correctly render the objects within the scene. Knowing this, what is the best way to sort them? I really want the sorting to be done really fast, but I've heard there are "trade off" for them, so what algorithm should I use to get the best performance out of it?

Any help would be greatly appreciated.

Edit: a lot of people are talking about the z-buffer/depth buffer. This doesn't work in some cases like a few people talked about. This is why I asked this question.

like image 354
Danny Avatar asked Feb 17 '26 02:02

Danny


2 Answers

Sorting by distance doesn't solve the transparency problem perfectly. Consider the situation where two transparent surfaces intersect and each has a part which is closer to you. Perhaps rare in games, but still something to consider if you don't want an occasional glitched look to your renderer.

The better solution is order-independent transparency. With the latest graphics hardware supporting atomic operations, you can use an A-buffer to do this with little memory overhead and in a single pass so it is pretty efficient. See for example this article.

The issue of sorting your scene is still a valid one, though, even if it isn't for transparency -- it is still useful to sort opaque objects front to back to to allow depth testing to discard unseen fragments. For this, Vaughn provided the great solution of BSP trees -- these have been used for this purpose for as long as 3D games have been around.

like image 79
Cory Nelson Avatar answered Feb 18 '26 15:02

Cory Nelson


Use http://en.wikipedia.org/wiki/Insertion_sort which has O(n) complexity for nearly sorted arrrays.

In your case by exploiting temporal cohesion insertion sort gives fastest results. It is used for http://en.wikipedia.org/wiki/Sweep_and_prune

From link above:

In many applications, the configuration of physical bodies from one time step to the next changes very little. Many of the objects may not move at all. Algorithms have been designed so that the calculations done in a preceding time step can be reused in the current time step, resulting in faster completion of the calculation.

So in such cases insertion sort is best(or similar sorts with O(n) at best case)

like image 21
Gorkem Avatar answered Feb 18 '26 15:02

Gorkem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!