Let's take the simplest case of rendering two overlapping transparent rectangles, one red and one green, both with alpha=0.5
. Assume that the drawing order is from back to front, meaning that the rectangle farther from the camera is drawn first.
In realistic scenarios, irrespective of which rectangle happens to be in front, the overlapping color should be the same, i.e. RGBA = [0.5, 0.5, 0.0, 0.5]
.
In practice, however, assuming that we are blending with weights SRC_ALPHA
and ONE_MINUS_SRC_ALPHA
, the overlapping color is dominated by the color of the front rectangle, as in this image:
I believe this happens because the first rectangle is blended with the background color, and the second rectangle is then blended with the resultant color. With this logic, assuming white background, the overlapping color in the two cases works out to be:
Red on top: 0.5*(0.5*[1,1,1,0] + 0.5*[0,1,0,0.5]) + 0.5*[1,0,0,0.5] = [0.75, 0.50, 0.25, 0.375]
Green on top: 0.5*(0.5*[1,1,1,0] + 0.5*[1,0,0,0.5]) + 0.5*[0,1,0,0.5] = [0.50, 0.75, 0.25, 0.375]
which explains the dominance of the color on top. In principle, this could be easily corrected if all the objects were blended first, and the resultant color is blended with the background color.
Is there a way to achieve this in OpenGL?