Calculate Bounding Box of Hierarchy of Objects

If I have a parent with several child renderers, I want to be able to create a single bounding box model around all of them. Any clues how to do this?

Using a model - type box is fine but how do I calculate the size of it and it’s center position?

Thanks

Hi @Grimmy,

You will need to loop through all of the entities and their mesh instances and add/sum the bounding boxes.

That will give you the total bounding box that encloses all models. You can take a look at the model viewer → orbit-camera.js script, it includes a similar method used to frame your scene.

1 Like

This is great thanks but I’m creating a new box renderer and trying to scale it to the same size and scale as the bounding box but both the size and scale dont match. I have the following code where
boundingBoxEntitySize is a new pc.BoundingBox();

this.boundingBoxVisEntity.setLocalScale(this.boundingBoxEntitySize.halfExtents.scale(2));
this.boundingBoxVisEntity.setLocalPosition(this.boundingBoxEntitySize.center);
this.entity.addChild(this.boundingBoxVisEntity);

I’ve tried adding the boundingBoxVisEntity both before and after scaling/positioning and also tried setPosition but nothing comes close.

Failing that, how would I just go about rendering the bounding box so that I can actually see it?

This may be of help: Could somebody please kindly explain how to use DrawWireAlignedBox? - #2 by Leonidas

Thanks, but that code just seems to call some other internal function (this.app.drawWireAlignedBox(this.min, this.max, this.color):wink: and even once I have the result of that I would need to turn the result into an entity at correct position and scale…so effectively I would be doing exactly the same again but instead trying to match the size and position of the wireframe box instead of the boundingBoxEntitySize.

Maybe I should have said that I need the visualization as an entity so I can manipulate the material and do other stuff later.

I thought you were trying to visualize the bounding box, but know I understand you really want to scale an actual box entity to fit the bounding box.

Not sure what you are doing wrong though, try sharing an example project if possible.

Yes, I want an entity that matches exactly the bounding box. :slight_smile: The above code is really all there is…apart from my bounding box calculation:


 // Calculate the bounding box visualization
    this.boundingBoxEntitySize = this.calculateBoundingBox();

BoundingBoxVisualizer.prototype.calculateBoundingBox = function () {

   var meshInstances = this.entity.render.meshInstances;
    if (meshInstances.length > 0) 
    {
        var bbox = new pc.BoundingBox();
        bbox.copy(meshInstances[0].aabb);

        for (var i = 1; i < meshInstances.length; i++) 
        {
                bbox.add(meshInstances[i].aabb);
        }
    }

    return bbox;
};

See this post to see how to create an entity that is the same as the bounding box:

1 Like