Packing textures

When preparing the graphics for an OpenGL or Direct3D game it’s generally a good idea to pack all images into larger textures instead of creating hundreds or even thousands of small ones.

Packing textures has two advantages. First, it saves video memory because there’s less padding to power-of-two dimensions that’s required. Second, it makes rendering significantly faster because there are less texture state changes (ie. glBindTexture). That’s an expensive operation and doing it 20 times instead of 600 per frame really makes a big difference.

Sometimes it’s called a “texture atlas”.

For Devastro, I did all the packing manually right in Photoshop. Whenever I finished a sprite, I opened all my existing textures, searched for a free spot and pasted the sprite there. Then I had to start a custom sprite editor and select the new sprite within the texture so the game would know it’s coordinates. That was… quite time consuming… to say the least, hehe.

So for my future games I wanted to upgrade my workflow in this area.

The basic idea for allocating the images effectively is creating a quad-tree that keeps track of what parts of the large texture are used and which are free. Then you add your images into the tree, largest first, dividing the quads according to their size and adding more textures as necessary.

There are tools that create a texture atlas for you automatically, but it’s usually done “offline”. I wanted to do it on the fly when the game starts. That way there’s no extra action to be taken between exporting the images from Photoshop and starting the game to see them.

It took me a while to get right but now it’s working perfectly and it’s surprisingly fast, too.