Sign in to follow this  
  • entries
    19
  • comments
    14
  • views
    6088

Locking a Vertex Buffer in Managed Code

Sign in to follow this  
LRiotto

65 views

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.
Sign in to follow this  


0 Comments


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now