Skip to content

Guide: Creating vertex index buffers and drawing geometry

Alan Stagner edited this page Jun 9, 2020 · 1 revision

Creating vertex and index buffers in BNA is super simple.

First, define your vertex struct type. BNA uses reflection to generate the appropriate vertex buffer bindings for you, so decorate your struct type with the "Reflect" attribute and then make sure each field has a "VertexUsage" attribute to let BNA know how to bind each field:

using BNA.Graphics;

// ...

[Packed, Reflect]
struct MyVertex
{
    [VertexUsage(.Position)]
    public Vec4 Position;

    [VertexUsage(.Color)]
    public Vec4 Color;
}

Keep in mind that your struct needs to follow a few rules: The entire struct must be a multiple of 16 bytes, and no single field must cross a 16-byte boundary (this is due to the way the graphics driver expects the fields to be aligned). You can always accomplish this by manually inserting padding between fields and at the end of the struct, and BNA will help you by analyzing the struct and telling you if and where you need to insert padding at runtime.

Next, construct a new VertexBuffer and then give it an array of these vertices:

let myVertexArray = new MyVertex[36];
let myVertexBuffer = new VertexBuffer(graphicsDevice);
myVertexBuffer.Set(myVertexArray);

Note that you can call Set more than once! As a performance tip: if you pass the same vertex type and make sure the new array is less than or equal to the previous size, the vertex buffer will not reallocate its internal GPU buffers or vertex buffer bindings.

Next, create an index buffer to refer to these vertices. You can Set an index buffer with either a uint16 array or a uint32 array:

let myIndices = new uint16[36];
let myIndexBuffer = new IndexBuffer(graphicsDevice);
myIndexBuffer.Set(myIndices);

Finally, now that you have a vertex and an index buffer, you can draw some geometry (note: always make sure you apply an effect to draw that geometry with first!):

myEffect.ApplyEffect(0);
graphicsDevice.DrawIndexedPrimitives(.TriangleList, myVertexBuffer, 12, myIndexBuffer);