I have a large number of rectangles, and some overlap others; each rectangle has an absolute z-order and a colour. (Each \'rectangle\' is actually the axis-aligned bou
Here's a possibility. You'll have to benchmark it to see if it's actually an improvement.
For all rectangles, back to front:
If this rectangle has been marked as drawn, skip to the next one
Set a screen-sized unseen surface to all black
Call this rectangle's color "the color"
For rectangles starting with this one and proceeding toward the front
If (this rectangle's color is the color and
all the pixels of this rectangle on the unseen are black) then
Add this rectangle to the to-draw list
Draw a white rectangle with this rectangle's shape on the unseen surface
If the unseen surface is more than half white, break
For all rectangles on the to-draw list:
Draw the rectangle
Mark it as drawn
It's not guaranteed to be the most optimal in terms of ordering, but I think it will come pretty close, and it's worst-case quadratic in the pre-drawing step. It does depend on readbacks from the graphics buffer being fast. One trick that might help there is to create a new one pixel surface that is a shrunken version of the area of interest. Its color will be the fraction of the original that was white.