In previous notes we rendered primitives by populating a vertex array and using the array as data to a primitive drawing function. While effective, this approach has drawbacks;
These problems can be easily solved using Vertex and index buffer.
The VertexBuffer represent a set of vertices streamed to the graphics card.
// an array of the vertices that have to be drawn
VertexPositionColor[] vertices = new VertexPositionColor[4];
Then replace the declaration of your vertices by the following code (explanation below):
// create our square by setting up the vertices
// because we are using an indexbuffer, we only need 4 vertices instead of 6 (2 triangles)
vertices[0].Position = new Vector3(650, 100, 0);
vertices[0].Color = Color.Red;
vertices[1].Position = new Vector3(750, 200, 0);
vertices[1].Color = Color.Red;
vertices[2].Position = new Vector3(650, 200, 0);
vertices[2].Color = Color.Red;
vertices[3].Position = new Vector3(750, 100, 0);
vertices[3].Color = Color.Red;
vertexbuffer = new VertexBuffer(GraphicsDevice, VertexPositionColor.SizeInBytes * vertices.Length, BufferUsage.WriteOnly);
vertexbuffer.SetData(vertices);
IndexBuffer stores a list of indices to a vertexbuffer. The primitive drawing code uses these indices to determine the drawing ordere of the vertices
// set up our indices // because a square consist of 2 triangles, we need 6 points in our indexbuffer short[] indices = new short[6]; indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 0; indices[4] = 3; indices[5] = 1; indexbuffer = new IndexBuffer(GraphicsDevice, typeof(short), 6,BufferUsage.WriteOnly); indexbuffer.SetData(indices);
These are two method for drawing indexed primitives;
graphics.GraphicsDevice.Vertices[0].SetSource( vertexbuffer, 0,VertexPositionColor.SizeInBytes);
graphics.GraphicsDevice.Indices = indexbuffer;
basicEffect.Begin();
basicEffect.CurrentTechnique.Passes[0].Begin();
graphics.GraphicsDevice.DrawIndexedPrimitives(PrimitiveTyp.Linelist, 0, 0, points, 0,2);
// tell basic effect that we're done.
basicEffect.CurrentTechnique.Passes[0].End();
basicEffect.End();