idmillington / cyclone-physics

The Physics engine that accompanies the book "Game Physics Engine Design"
MIT License
908 stars 257 forks source link

How to build Bounding Volume Hierarchy? #36

Open RdlP opened 8 years ago

RdlP commented 8 years ago

I understand BVH and the code to create the hierarchy and I understand the code to insert nodes in the BVH but I don't understand how to insert bodies in the hierarchy. I mean I have a list with many bodies and I want to create the BVH.

To insert bodies is it enought with the follow?

BVHNode root;
for (int i=0; i<bodies.length; i++){
    RigidBody currentBody = bodies.get(i);
    root.insert(currentBody, volume);
}

The question is, to create the BVH is it engouth with create a node and iterate over all bodies and insert the bodies in the created BVH node (root)? Note: I have used a java syntax.

YukinoHayakawa commented 8 years ago

Yes if you just want a working BVH, no if you have many objects and chase for better performance. It's a sad truth that BVH is never used in demos come along with cyclone codes. I rolled my own BVH class and haven't used it neither. Also note that there are some errors in its implementation which may lead to missing of contacts (see other issues). For the insertion method which is used in the book, inserting objects one by one is sufficient to build a hierarchy. But for the greedy character (put object to the best position for it but not for the whole tree) of insertion method, using the final hierarchy is not guaranteed to be more effective than using brute-force detection between every possible pair, especially when objects are distributed and inserted in a random manner. If you want to take performance into consideration, you may want to do some research on BVH optimization (may be some quick algorithms to adjust BVH structure dynamically) or other building methods such as SAH-based methods (performed in a top-bottom manner, may not be useful if you use a dynamic BVH, which is very common in physics simulations).