1
votes

I have a vertex structure:

public struct VertexMultitextured
{
    public Vector3 Position;
    public Vector3 Normal;
    public Vector4 TextureCoordinate;
    public Vector4 TexWeights;

    public static int SizeInBytes = (3 + 3 + 4 + 4) * sizeof(float);
    public static VertexElement[] VertexElements = new VertexElement[]
 {
     new VertexElement( 0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0 ),
     new VertexElement( sizeof(float) * 3, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0 ),
     new VertexElement( sizeof(float) * 6, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 0 ),
     new VertexElement( sizeof(float) * 10, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 1 ),
 };
}

and I would like to create a VertexBuffer that uses it. If I use this line:

terrainVertexBuffer = new VertexBuffer(device, typeof(VertexMultitextured), vertices.Length, BufferUsage.WriteOnly);

I get an error that my structure "does not implement the IVertexType interface," so how do I go about implementing that? Or is there just an easier way to use this custom struct?

Thanks!

1

1 Answers

3
votes

You're almost there. What you've got there looks a bit like the old style for XNA 3.1. The way to do this was improved in XNA 4.0 - see this blog post.

Just like the error says, your VertexMultitextured needs to implement IVertexType (MSDN), which requires you implement this property. Here's what that would look like:

public struct VertexMultitextured : IVertexType
{
    // ... all your data members ...

    static readonly VertexDeclaration MyVertexDeclaration
            = new VertexDeclaration(new VertexElement[] {
                // ... your vertex element array ...
            });

    public VertexDeclaration VertexDeclaration
    {
        get { return MyVertexDeclaration; }
    }
}

(The alternative to implementing the interface is to create the VertexDeclaration anywhere, and pass that to the other constructor of VertexBuffer.)

You no longer need to keep a reference to your VertexElement array around - you can just pass it to the constructor of VertexDeclaration and forget about it. You don't need to keep track of the size, either, VertexDeclaration will calculate it from your array of elements.