2
votes

I'm using OpenGL ES 2.0 to create the following scene:

Draw a background image on the entire screen and above it draw another overlay image that fades in and out (alpha changes)

I also need to use "Screen blend" to blend the overlay and the background textures.

So I created a shader that blends the two textures, I thought that I can use a uniform (randomAlpha) to change the overlay texture alpha over time and create a fade animation, but the following code doesn't do the trick, the overlay texture opacity doesn't changes!

I know there is an "Alpha Blend" that I can use to blend the overlay and the background textures, but the problem is that I want the final overlay (after opacity changes) to blend the background with a "Screen Blend" not an "Alpha Blend"

This is how my fragment shader main method looks like:

 void main()
 {
     mediump vec4 background = texture2D(backgroundTexture, backgroundCoords);
     mediump vec4 overlay = texture2D(overlayTexture, overlayCoords);

     overlay.a = randomAlpha;

     // add overlay to background (using screen blend)
     mediump vec4 whiteColor = vec4(1.0);
     gl_FragColor = whiteColor - ((whiteColor - overlay) * (whiteColor - background));

  } 

Clearly I missing something important here..
How can I change the texture's opacity? how can I create the fade effect?

1

1 Answers

3
votes

Like you already figured it's just a matter of blending.

What you're missing is that you need to re-calculate the rgb channels, when you change the alpha value when you want to blend to textures together.

void main()
{
    mediump vec4 background = texture2D(backgroundTexture, backgroundCoords);
    mediump vec4 overlay = texture2D(overlayTexture, overlayCoords);

    overlay.a = randomAlpha;
    background.a = 1.0 - overlay.a;

    gl_FragColor = vec4(background.rgb * background.a + overlay.rgb * overlay.a, 1.0);
}

Here is a simplified version of the above code, the above code is just easier to understand and read.

void main()
{
    mediump vec4 background = texture2D(backgroundTexture, backgroundCoords);
    mediump vec4 overlay = texture2D(overlayTexture, overlayCoords);

    overlay.rgb *= randomAlpha;
    background.rgb *= 1.0 - randomAlpha;

    gl_FragColor = vec4(background.rgb + overlay.rgb, 1.0);
}