AGAL, PNG blending & Transparency (bug)?

So, to make this short, i was trying to find out how to make a fragment shader to be able to put several PNGs one on top of the other and have them mix togheder, i achieved that by using this code:

  • t3 = temporal variable.
  • t0 = transparentPNG with just lines and shading. It is a “tex”… a png that has just shading information.
  • t2 = base color “skin color”.  Just a color, no alpha. 
  • c1.w = 1 the number one.


"sub,,", // shading color - base color.
"mul,, t0.w", // multiply the above value by the alpha value of the shading layer.
"add,,", // add the above value to the base color.

That works fine, BUT it has an issue. If you draw a semi transparent white line for example, since colors in PNG are premultiplied by their alpha values, you will get a greyish color on top of the base color. So white %50 alpha will make the color below to look darker. To solve that, you have to remove the premultiplication ( idk if there’s a more optimal way to solve this, this is how i did it with the knowledge i have right now…). The color components of a PNG are multiplyed by their alpha component. If you divide them by their alpha you will inverse the operation, obtaining the original color without alpha.

 "div,, t3.w" , //Remove premultiplication by dividing by the alpha.
"mul,, t0.w",

Now there’s another issue. In SOME computers, it will work fine. but in some others, the new line added will turn fully transparent pixels into black pixels. Any pixel that has an alpha values greater than cero will look fine…. to solve that, you have to remove the premultiplication using a new number, that will be equal to the alpha value of the shading layer BUT it will be 1 (fully opaque) if the alpha value is equal to CERO. Final code…

 "sub t3.w, c1.w, t0.w", // t3.w = 1 - alpha value of shading layer. ( c1.w = 1 )
"sge t3.w, t3.w, c1.w", // t3.w = 1 if the value above was CERO, else ONE
"add t3.w, t3.w, t0.w", // now we ADD the alpha value. CERO will turn into ONE, the rest will remain the same.

"div,, t3.w" ,
"mul,, t0.w",

now it should work fine and the PNG will blend correctly with the base color just like in photoshop.

If you (the reader) know a better solution, please post it as a comment below, because i want to know how to do this properly. I’m just starting to learn this, so mabe i just made a complete mess and i dont know it.