I have a large number of rectangles, and some overlap others; each rectangle has an absolute z-order and color. (Each "rectangle" is actually an axially aligned bounding rectangle of the particle effect, a grid or texture and can be translucent. But it’s easier to ignore the colored rectangles if you are not trying to drop the rectangles after the others, so I will use this in the description of the problem: )
The cost of changing the “color” is quite high; it is much faster to draw two blue rectangles in a row than to draw two multi-colored rectangles.
The cost of drawing rectangles that are not even on the screen is too high and should be avoided.
If the two rectangles do not overlap, the order they draw relative to each other is not important. Its only if they overlap is that z-order is important.
For example:

1 (red) and 4 (red) can be assembled together. 2 (blue) and 5 (blue) can also be brought together, as well as 3 (green) and 7 (green). But 8 (red) needs to be drawn after 6 (blue). therefore, we either draw all three red together and draw blue in two sets, or draw all blue together and draw red in two sets.
And some of the rectangles can sometimes move around. (Not all of them, some rectangles are known to be static, others are known to move.)
I will draw this scene in JavaScript / webGL.
How can I draw the rectangles in a reasonable order to minimize color changes, with a good compromise of the code for rejecting JavaScript and discarding the GPU?
(Just working on which rectangles overlap and which are expensive to see, I have a basic quadtree , and this accelerated my scene, draw-ops for the whole scene), now the question is how to minimize OpenGL state changes as much as possible and combine attribute arrays )
UPDATE I created a very simple test application to illustrate the problem and serve as the basis for demonstrating solutions: http://williame.github.com/opt_rects/
The source code is on github and can be easily forked: https://github.com/williame/opt_rects
It turns out that it is difficult to make a small test application with enough state change to actually recreate the problem that I see in my full game. At some point you will have to take this as a task that state changes can be quite expensive. It is also important how to speed up the spatial index (quadtree in the demo) and the general approach.
javascript math algorithm spatial-index webgl
Will Jan 14 '13 at 8:28 2013-01-14 08:28
source share