OpenGL GLSL texture transparency
Asked Answered
P

1

10

I want to make transparency on my 32bit bitmap texture using GLSL. My fragment shader looks like this:

#version 120
uniform sampler2D myTexture;
varying vec2 TexCoord;

void main(void)
{
    if(texture2D(myTexture, TexCoord).a != 1.0f)
    {
        discard;
    }
    gl_FragColor = texture2D(myTexture, TexCoord);
}

But that makes transparent only the pixels where alpha is equal 0 and I want to maintain the fade from the texture. For example in this picture the first image is the texture, the second is the texture mask and the third is the desired result:

Example

The texture and the texture mask are in one 32bit bitmap.

Does anyone know, how to achieve this using GLSL?

Pentarchy answered 22/1, 2015 at 0:0 Comment(3)
This is achieved by blending. opengl.org/archives/resources/faq/technical/transparency.htmEtz
I know, but that's the immediate mode only and it's really inaccurate, I want to do it with shaders. The blending also makes some annoying transparent border around the mask.Pentarchy
Blending does work well with shaders and modern OpengGL.Etz
C
14

You need to enable GL_BLEND, and the alpha output of your fragment shader will be used to blend the fragment output with the framebuffer.

glEnable(GL_BLEND);
glBlendFunc(..., ...);

glDraw????(...);

// You don't have to do it here, but GL_BLEND will remain enabled
// until you disable it again.
glDisable(GL_BLEND);

If you use premultiplied alpha,

glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

If you use non-premultiplied alpha,

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

The fragment shader can't do the blending because it doesn't have access to the framebuffer.

Cerelly answered 22/1, 2015 at 0:44 Comment(2)
Ok thank you, can you tell me please, how can I get rid of the residue of the texture so it can be seen through on objects behing the texture? In this picture i.imgur.com/QDmXb0z.png?1 you can see a slider bar and the caret. The transparency is on the caret, but the bar is not visible through the alpha pixels. Why?Pentarchy
Yes... if you draw transparent objects, you can't use ordinary depth testing, you have to sort the objects and draw back-to-front (unless you use order-independent transparency, but most people don't). A typical scene will start with the solid objects (front-to back, for better performance) followed by the transparent objects, which must be back-to-front.Cerelly

© 2022 - 2024 — McMap. All rights reserved.