]> git.sesse.net Git - movit/blob - mix_effect.frag
Add a new alpha handling method, INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK.
[movit] / mix_effect.frag
1 vec4 FUNCNAME(vec2 tc) {
2         vec4 first = INPUT1(tc);
3         vec4 second = INPUT2(tc);
4         vec4 result = vec4(PREFIX(strength_first)) * first + vec4(PREFIX(strength_second)) * second;
5
6         // Clamping alpha at some stage, either here or in AlphaDivisionEffect,
7         // is actually very important for some use cases. Consider, for instance,
8         // the case where we have additive blending (strength_first = strength_second = 1),
9         // and add two 50% gray 100% opaque (0.5, 0.5, 0.5, 1.0) pixels. Without
10         // alpha clamping, we'd get (1.0, 1.0, 1.0, 2.0), which would then in
11         // conversion to postmultiplied be divided back to (0.5, 0.5, 0.5)!
12         // Clamping alpha to 1.0 fixes the problem, and we get the expected result
13         // of (1.0, 1.0, 1.0). Similarly, adding (0.5, 0.5, 0.5, 0.5) to itself
14         // yields (1.0, 1.0, 1.0, 1.0) (100% white 100% opaque), which makes sense.
15         //
16         // The classic way of doing additive blending with premultiplied alpha
17         // is to give the additive component alpha=0, but this also doesn't make
18         // sense in a world where we could end up postmultiplied; just consider
19         // the case where we have first=(0, 0, 0, 0) (ie., completely transparent)
20         // and second=(0.5, 0.5, 0.5, 0.5) (ie., white at 50% opacity).
21         // Zeroing out the alpha of second would yield (0.5, 0.5, 0.5, 0.0),
22         // which has undefined RGB values in postmultiplied storage; certainly
23         // e.g. (0, 0, 0, 0) would not be an expected output. Also, it would
24         // break the expectation that A+B = B+A.
25         //
26         // Note that we do _not_ clamp RGB, since it might be useful to have
27         // out-of-gamut colors. We could choose to do the alpha clamping in
28         // AlphaDivisionEffect instead, though; I haven't thought a lot about
29         // if that would be better or not.
30         result.a = clamp(result.a, 0.0, 1.0);
31
32         return result;
33 }