views:

147

answers:

2

I load multiple meshs from .x files in different mesh variables. Now I would like to calculate the bounding sphere across all the meshes I have loaded (and which are being displayed) Please guide me how this could be achieved. Can VertexBuffers be appended togather in one variable and the boundingSphere be computed using that? (if yes how are they vertexBuffers added togather) Otherwise what alternative would you suggest!? Thankx

A: 

I have an idea, what I would do is that I would determine the center of every single mesh object, and then determine the center of the collection of mesh objects by using the aforementioned information ...

A: 

Its surprisingly easy to do this:

You need to, firstly, average all your vertices. This gives you the center position.

This is done as follows in C++ (Sorry my C# is pretty rusty but it should give ya an idea):

D3DXVECTOR3 avgPos;

const rcpNum  = 1.0f / (float)numVerts; // Do this here as divides are far more epxensive than multiplies.
int count = 0;
while( count < numVerts )
{
    // Instead of adding everything up and then dividing by the number (which could lead 
    // to overflows) I'll divide by the number as I go along.  The result is the same.
    avgPos.x += vert[count].pos.x * rcpNum;
    avgPos.y += vert[count].pos.y * rcpNum;
    avgPos.z += vert[count].pos.z * rcpNum;
    count++;
}

Now you need to go through every vert and work out which vert is the furthest away from the center point.

Something like this would work (in C++):

float maxSqDist      = 0.0f;

int count = 0;
while( count < numVerts )
{
    D3DXVECTOR3 diff = avgPos - vert[count].pos;

    // Note we may as well use the square length as the sqrt is very expensive and the 
    // maximum square length will ALSO be the maximum length and yet we only need to
    // do one sqrt this way :)
    const float sqDist = D3DXVec3LengthSq( diff ); 
    if ( sqDist > maxSqDist )
    {
        maxSqDist = sqDist;
    }
    count++;
}

const float radius = sqrtf( maxSqDist );

And you now have your center position (avgPos) and your radius (radius) and, thus, all the info you need to define a bounding sphere.

Goz