Jump to content
  • Advertisement
Sign in to follow this  
ardmax1

GLSL - pixel color based on alpha

This topic is 2171 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi,
is it possible to write GLSL shader such that it will change each texture pixel color based on its alpha value ?
Something like:
[source lang="cpp"]
vec4 pixel = texture2D( texture, pos );
if( pixel.a > 0.5f ){
pixel = vec4( 0.0, 1.0, 0.0, 1.0 );
}else{
pixel = vec4( 1.0, 0.0, 0.0, 1.0 );
}[/source]
If it is, could you guys give me tips on how to make it ?

Share this post


Link to post
Share on other sites
Advertisement
If it should work, then i have error somewhere else.

This produces just red
fragment:
[sourcelang="cpp"]varying vec4 pos;
uniform sampler2D texture;

void main(){
vec4 pixel = texture2D(texture, vec2(pos));
if (pixel.a > 0.5){
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}else{
gl_FragColor = vec4(0.0, 0.0, 1.0, 0.3);
}
}
[/source]
vertex:
[source lang="cpp"]varying vec4 pos;

void main(){
pos = gl_MultiTexCoord0;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}[/source]

Share this post


Link to post
Share on other sites
Have you enabled alpha blending? How have you created the texture? The shaders look ok, so I'm guessing the problem is outside of the shaders. Edited by Cornstalks

Share this post


Link to post
Share on other sites
Sampling the alpha channel of a texture does not require alpha blending to the framebuffer to be enabled. Make sure that your texture actually does have an alpha channel, and it's not all 1.f in each pixel.

Try debugging visually the contents of the alpha channel with the following fragment shader:



varying vec4 pos;
uniform sampler2D texture;

void main(){
vec4 pixel = texture2D(texture, vec2(pos));
gl_FragColor = vec4(pixel.aaa, 1.0);
}


this should render the alpha channel out in grayscale, so you can confirm that it is not all white.

Share this post


Link to post
Share on other sites
ok I found out was the problem.
First it was caused by clearing texture, which is used to apply shaders on whole screen rather that on parts that are drawn (This is I think SFML problem).
Second, I had to normalize position, so it looks like this now
[source]pixel = texture2D(texture, pos.xy / texResolution);[/source]
but why this makes texture flip vertically?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!