如何计算跨多个网格的边界框/球体(C#)

时间:2010-06-15 12:03:05

标签: c# directx mesh bounding-box vertex-buffer

我从不同网格变量中的.x文件加载多个网格物体。 现在我想计算我加载的所有网格(以及正在显示的网格)的边界球体 请指导我如何实现这一目标。 VertexBuffers可以在一个变量中附加togather并使用它来计算boundingSphere吗? (如果是,他们如何添加vertexBuffers togather) 否则你会建议什么替代方案!? Thankx

2 个答案:

答案 0 :(得分:2)

这样做非常容易:

首先,您需要平均所有顶点。这为您提供了中心位置。

这在C ++中完成如下(对不起,我的C#非常生疏,但它应该给你一个想法):

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++;
}

现在你需要遍历每个顶点并找出哪个顶点离中心点最远。

这样的东西可以使用(在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 );

现在你有了你的中心位置(avgPos)和半径(半径),因此,你需要定义一个边界球的所有信息。

答案 1 :(得分:0)

我有一个想法,我会做的是确定每个网格物体的中心,然后使用上述信息确定网格物体集合的中心......

相关问题