[SOLVED] Changing only colors in a vertex buffer

Hi there,

can you think of a clever way to swap all color components of all vertices in a vertex buffer, without re-writing the whole thing? Like setting values with an offset for each element in the array:

  0, // offset in bytes from buffer start
  new[] { colorVertex0, colorVertex1, colorVertex3, ... }, // split positions 
  0,   // start index in array
  3,   // number or array elements
  12, // size of single array element
  24  // offset in bytes for each element (position + normal)

Or would it be better, to store an ID in every vertex and grab the colors from a second color-only-buffer?


The example given in the documentation seems to be incorrect. There the first parameter is used to achieve this. But the first parameter does not define a per-element-offset, but an absolute offset from the buffer’s start.

Is GraphicsDevice.SetVertexBuffers maybe an option? You keep the colors in a separate vertex buffer and stream both buffers simultaneously.

Might be a solution. Since I draw very big meshes with millions of vertices, I decided to keep the interleaved buffer for performance reasons. I found out how to change the colors only : )

// My vertex declaration has the color as first value.
using VEF = VertexElementFormat;
using VEU = VertexElementUsage;
static readonly VertexDeclaration VertexDeclaration = new VertexDeclaration(
  new VertexElement( 0, VEF.Color, VEU.Color, 0 ),
  new VertexElement( 4, VEF.Vector3, VEU.Position, 0 ),
  new VertexElement( 16, VEF.Vector3, VEU.Normal, 0 ),
  new VertexElement( 28, VEF.Vector2, VEU.TextureCoordinate, 0 ));

// For this reason calculating the position in the buffer is pretty easy.
public override void SetVertexColors( Color[] colors, int offset )
  // offset ... I use multiple meshes in the buffer.
  //            Offset is the number of all vertices
  //            of preceding meshes.
  // 36 ...     My vertex size in bytes.

    36 * offset,          // vertex size * vertex count of other meshes
    colors, 	          // Array of colors.
    0, 			          // Use all elements of color array.
    colors.Length, 	      // Use all elements.
    36 );				  // Set only the color. 36 Bytes between them.

Thanks for your hints : )