GLSL - pixel color based on alpha

Started by
4 comments, last by ardmax1 11 years, 10 months ago
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 ?
Advertisement
Yes, it is possible, and you just gave the answer yourself tongue.png
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]
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.
[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]
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.
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?

This topic is closed to new replies.

Advertisement