Locking a Vertex Buffer in Managed Code

Published November 29, 2004
Advertisement
Every example I have come across seems to lock a VB in the following manner:

VB.Lock(0,0);

This returns an array (or a stream depending on the overload) of the entire buffer. This is fine and dandy for small vb's but once a threshold is reached, your performance hits a wall with a splat!

Microsoft's documentation on the subject isn't overly clear (at least it wasn't to me) so I hope to shed some light on the subject (at least on the first parameter of the following call).


public Array Lock(int offsetToLock, Type typeVertex, LockFlags flags, int[] ranks);


Microsoft's description of the first parameter is:
offsetToLock System.Int32. Offset into the vertex data to lock, in bytes. To lock the entire vertex buffer, specify 0 for both param_Int32_sizeToLock and param_Int32_offsetToLock.

In order to properly calculate the offset, you need to know how big (in bytes) the vertex structure is. This is the structure you used when creating the buffer and can be done using the Marshal.SizeOf command. (Make sure to include the using System.Runtime.InteropServices; to cut down on dereferencing)

An example of this call:
int vbStructSize = Marshal.SizeOf(typeof(CustomVertex.PositionColoredTextured));

You can also use the sizeof operator but this is an unsafe call and would require the /unsafe compiler option to be set and to be wrapped in an unsafe block.

An example of this would look like:
int vbStructSize;

unsafe
{
vbStructSize = sizeof(CustomVertex.PositionColoredTextured);
}

So now that the structure size is known, calculating the offset is done by multiplying this size by the number of vertices you want to skip over.

// Skip to the 10th element
vbOffset = vbStructSize * 10;

CustomVertex.PositionColored[] TileVerts = (CustomVertex.PositionColored[])VB.Lock(vbOffset,typeof(CustomVertex.PositionColored), LockFlags.None,new int[]{24});

This will return a populated, single dimensioned TileVerts array of 24 elements. Don't forget to Unlock the VB as soon as you are done modifying or using it.

I hope this helps.
Previous Entry All about Spans
Next Entry Engine Update
0 likes 0 comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Profile
Author
Advertisement

Latest Entries

Advertisement