Clockworkcoders Tutorials


Discarding Fragments

It is possible to tell the fragment shader it shouldn't write any pixel. This can be done using the "discard" statement.

This can be used - for example - to implement a color key.

Using the following texture, all red pixels should be removed (discarded!).

Texture with with red color key


varying vec2 vTexCoord;
void main(void)
   vTexCoord = gl_MultiTexCoord0.xy;
   gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
Vertex Shader Source Code

sampler2D myTexture;
           varying vec2 vTexCoord;
void main (void) 
   vec4 color = texture2D(myTexture, vTexCoord); 
   if (color.rgb == vec3(1.0,0.0,0.0))
   gl_FragColor = color;
Fragment Shader Source Code


If you start the shader you will get the following result:

There are still some red pixels visible. This is because the texture was filtered. This can be prevented by setting the texture parameters to:


This time it looks better.


Previous: Per Fragment Lighting

Back to Index