Download the source code for this post Download the source code for this post

Eh up chucks, welcome back. This is just a quick post to cover something I couldn’t quite fit into my last tutorial.

Colour Packing

In my previous post we sent colour data alongside each vertex position. Now, we were being a bit wasteful there, as for each vertex, we sent 3 floats to keep it company. You can imagine that if we had tens of thousands of vertices, then that’s a lot of bandwidth we are using up. Do we really need a float to represent each colour component?

That’s 32 bits of data (2^32 = 4,294,967,296) to represent a value between 0 and 255? Okay, you got me, the 32 bits aren’t used in the way that they are for Integers when they represent a float, but it’s still a lot of bits and bytes to be pushing around willy nilly.

What we can do instead, is use something called colour packing to pack the RGBA components into a single float. This saves a ton of bandwidth at the cost of some slight loss of colour precision. As me old granddad used to say “You don’t get ought for free in this life lad.” We have 32-bits to play with, which means each component (RGBA) are allocated 8 bits each, which gives them a range of 0-255. That’s not quite true, due to the complexities of encoding a float, but it’s not too far off.

Code Changes

Previously, when we created our mesh, it looked like this:

triangleMesh = new Mesh(true, 3, 0,
  new VertexAttribute(Usage.Position, 2, "a_position"),
  new VertexAttribute(Usage.ColorUnpacked, 4, "a_color"));

We need to change this to:

triangleMesh = new Mesh(true, 3, 0,
  new VertexAttribute(Usage.Position, 2, "a_position"),
  new VertexAttribute(Usage.ColorPacked, 4, "a_color"));

One important detail here, is that we still need pass 4 for the number of components, even though we are encoding the colours into a single float.

The bandwidth hungry way we encoded the colour data previously looked like this:

triangleMesh.setVertices(new float[] {
	0f, 0.5f, 1, 0, 0, 1, 		// red top vertex
	0.5f, -0.5f, 1, 1, 1, 1,  	// white bottom right vertex
	-0.5f, -0.5f, 0, 0, 1, 1 	// blue bottom left vertex
});

We simply change this to:

float red = Color.toFloatBits(255, 0, 0, 255);
float white = Color.toFloatBits(255, 255, 255, 255);
float blue = Color.toFloatBits(0, 0, 255, 255);

triangleMesh.setVertices(new float[] {
	0f, 0.5f, red,		// red top vertex
	0.5f, -0.5f, white,	// white bottom right vertex
	-0.5f, -0.5f, blue 	// blue bottom left vertex
});

And that’s yer lot. When you run the program, it will look like before:

Tutorial 3.

You can now sleep safe and sound at night, knowing that you haven’t been wasteful with that limited bandwidth.

Show/Hide juicy details

I have nothing

Coming up Next…

In the next installment, we wrap up this triangle madness, which will lead the way to the first XNA related topic I’d like to cover. Be there or be square quad.

JK