The usual equation for blending two pixels with alpha is to use a source factor of “source alpha” and a destination factor of “one minus source alpha”.
That results in this equation:
In other words, it’s just a linear interpolation between and , using the alpha of the pixel you are writing to determine the weighting for the lerp.
Just to be clear, is the pixel in your frame buffer (ie the final result that shows up on your monitor) and is the new pixel you are trying to write or combine with the output image.
If you use pre-multiplied alpha, all that means is that is already multipled by which results in slightly less math:
Less math for the same results is always a good thing due to increased efficiency, but this also results in a higher quality results in the case of using mips. For more info on that check out this link: NVIDIA GameWorks – Alpha Blending: To Pre or Not To Pre
To achieve this in OpenGL or DirectX with pre-multiplied alpha textures, you just use a source factor of “one” and leave the destination factor at “one minus source alpha”.
If you are using alpha to write to a render target that also has an alpha channel, the math improvement is even better. Here is the equation with regular (post-multiplied) alpha in that scenario for combining the RGB portion of the pixels:
When working with pre-multiplied alpha it just goes back to the lerp:
When blending to a target with alpha, the equation to combine alpha is the old familiar lerp:
That makes the lerp form of color combining even nicer since it means the same math for all color channels of the pixel:
Confused about why alpha combining using lerp makes sense? It makes most sense to me when thinking about it like this… if you had something that was half opaque(Out.A = 0.5), then you looked at that through something that was 3/4 opaque (In.A = 0.75), only 25% of the light would get past the top layer (0.25), to reach the bottom layer. Only 50% of the light that reached the bottom layer gets through, so we cut that 25% in half to get 12.5% (0.125). Since alpha really means “opaqueness” (1.0 means no transparency), that means that the combined alpha is 1 – 0.125, or 0.875.
If you plug the numbers into the above equation you get the same result:
This compute graphics stack exchange question has some more great info on what premultiplied alpha can give you. It’s much more than I wrote here:
Does premultiplied alpha give order independent transparency?
Here’s a fun question… does alpha represent transparency, or does it represent how much of a pixel is covered by an opaque object? To find out the answer give this a read!
Jounral of Computer Graphics Techniques: Interpreting Alpha