meds
meds

Reputation: 22936

Grabbing the vertices and indices from a Microsoft.Xna.Framework.Graphics.Model?

Is it possible to grab the indices/vertices from an XNA model object? I want to process the geometry for collision detection.

Upvotes: 0

Views: 604

Answers (1)

Tim Jones
Tim Jones

Reputation: 1786

I wrote a blog post recently on drawing a bounding box for an XNA model, and the source include includes a VertexElementExtractor class which should do exactly what you want. Since it's short I'll include the code here:

public static class VertexElementExtractor
{
    public static Vector3[] GetVertexElement(ModelMeshPart meshPart, VertexElementUsage usage)
    {
        VertexDeclaration vd = meshPart.VertexBuffer.VertexDeclaration;
        VertexElement[] elements = vd.GetVertexElements();

        Func<VertexElement, bool> elementPredicate = ve => ve.VertexElementUsage == usage && ve.VertexElementFormat == VertexElementFormat.Vector3;
        if (!elements.Any(elementPredicate))
            return null;

        VertexElement element = elements.First(elementPredicate);

        Vector3[] vertexData = new Vector3[meshPart.NumVertices];
        meshPart.VertexBuffer.GetData((meshPart.VertexOffset * vd.VertexStride) + element.Offset,
            vertexData, 0, vertexData.Length, vd.VertexStride);

        return vertexData;
    }
}

If possible, however, I recommend extracting the vertices at build-time, using the XNA Content Pipeline. The Picking with Triangle Accuracy sample on App Hub does this.

Upvotes: 1

Related Questions