1 // It's actually (but surprisingly) not correct to do a mix() here;
2 // it would be if we had postmultiplied alpha and didn't have to worry
3 // about alpha in the bottom layer, but given that we use premultiplied
4 // alpha all over, top shouldn't actually be multiplied by anything.
6 // These formulas come from Wikipedia:
8 // http://en.wikipedia.org/wiki/Alpha_compositing
10 // We use the associative version given. However, note that since we want
11 // _output_ to be premultiplied, C_o from Wikipedia is not what we want,
12 // but rather c_o (which is not explicitly given, but obviously is just
13 // C_o without the division by alpha_o).
15 vec4 FUNCNAME(vec2 tc) {
16 vec4 bottom = INPUT1(tc);
17 vec4 top = INPUT2(tc);
19 // Postmultiplied version.
20 float new_alpha = mix(bottom.a, 1.0, top.a);
21 if (new_alpha < 1e-6) {
22 // new_alpha = 0 only if top.a = bottom.a = 0, at least as long as
23 // both alphas are within range. (If they're not, the result is not
24 // meaningful anyway.) And if new_alpha = 0, we don't really have
25 // any meaningful output anyway, so just set it to zero instead of
26 // getting division-by-zero below.
29 vec3 premultiplied_color = mix(bottom.rgb * bottom.aaa, top.rgb, top.a);
30 vec3 color = premultiplied_color / new_alpha;
31 return vec4(color.r, color.g, color.b, new_alpha);
34 return top + (1.0 - top.a) * bottom;