C++/OpenGL/GLSL Texture Manipulation

Just learning some GLSL and playing about with vertex and fragment shaders – not a bad first start, but it’s going to take a significant amount of time and effort to get to really writing some descent shaders – it’s just very, very different from fixed-pipeline stuff… What you’re looking at is a texture where I’ve drawn some stuff on it in bright red, and then in the fragment shader anything found in the texture to be bright red gets discarded, effectively leaving in empty, like a cut-out =D

All in, the project’s around 500 lines of source, with the shaders being merely:

Vertex Shader

#version 110 // Olde...
 
varying vec2 vTexCoord; // varying is now deprecated.. will re-write soon
 
void main(void)
{
   vTexCoord = gl_MultiTexCoord0; 
   gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; // 3D vertex -> 2D window position transformation
}

Fragment Shader

sampler2D myTexture;    // Apparently this should not be a uniform variable as you shouldn't loop through uniform variables for performance reasons...
varying vec2 vTexCoord; // Pass through from our vertex shader. Should be type "in" in more recent versions of GLSL
 
void main (void) 
{  
   vec4 color = texture2D(myTexture, vTexCoord); 
 
   if (color.r > 0.9 && (color.g < 0.15 && color.b < 0.15))
      discard; 
 
   gl_FragColor = color;
}

The Linux Code::Blocks project will all source & image can be found below, but you’ll need to have or install libGL, libGLEW, libglfw, libIL, libILU, libILUT for it to work right out of the box. The linkage details are all in the Code::Blocks project file (and also in the .depend file if you don’t use C::B) so you can see what you need if there’s anything missing.

Download: GLSL-Texture-Manipulation-Test.zip

Update: Ha! Hadn’t thought of this before, but I guess what I’m really doing is Chroma-Keying (or Colour-Keying, whatever you prefer)… And you can do the same thing in SDL/OpenGL without using any shaders like this.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.