Monitoring State Changes

Okay, on my big projects I’m having a hard time monitoring state changes. Since state changes (ex. glEnable(GL_TEXTURE_2D)) are costly on performance, what is a good system of setting up your code so you can easily tell which states are on, thus reducing redundant calls? Does it come down to performance vs. readability?

State blocks.

Create a class, say called CStateBlock. It has members, like colour, and array of textures, blending, alpha, etc. When you render a buffer you call the state block to setup state.

Now since your in to performance what you do next is sort your objects to be rendered by StateBlock, for example just add operator < and use an STL sort on it.

Now all the object are ordered efficiently, when renderering objects with the same state block don’t apply the state.

To go core you can create a system ordered on state change cost, say 100point for a texture change, 40 points for a light source change etc, this however is probably taking it too far as the CPU cost to determine this is probably more that the savings. On top of that different cards have different costs. It might work if you do a mini performance test on app start to configure the balance of the cost values.


(Note : I got this tip off two respected pro coders at muckyfoot and oddworld.)