Texturing

This tutorial explains how to use textures and samplers.

Texturing is done in the fragment shader. Some vertex shader implementations are also capable of accessing textures, but that's not the goal of this tutorial. First, you need to define a sampler2D uniform variable. This is the access point to texture data. So add the following line at global scope:

uniform sampler2D myTextureMap;

Now you can read data from this sampler by using the texture2D function. This functions takes a sampler variable an a texture coordinate vector as arguments. It is used in the following way:

gl_FragColor = texture2D( myTextureMap, gl_TexCoord[0].st );

This looks up a vec4 value from myTextureMap at the coordinates gl_TexCoord[0].st. These coordiates are the interpolated result of the vertex shader output. If you do not write to gl_TexCoord[0] in your vertex shader, the value in the fagment shader is undefined! The initial vertex shader passes through gl_MultiTexCoord0, which holds the texture coords of the test model.

If you compile your shader and look at the results, you should see nothing. That's because you have only defined a sampler, but no texture image! This will be the next step. Go to the 'Textures' tab and click the button inside the GL_TEXTURE0 box. You can now load an image file into the texture mapping unit GL_TEXTURE0. Depending on you OpenGL implementation, you have several texture mapping units available in which you can load texture images. Now you should see the image mapped onto the test model.

Now click the button in the GL_TEXTURE1 box and load another image. You will still see the image of GL_TEXTURE0. To use the image in GL_TEXTURE1 you must set the value of the sampler 'myTextureMap' to 1 in the spin box.

Samplers are basically integers, that identify a texture mapping unit. This way your shader does not 'see' the details of the OpenGL implementation and you can define multiple samplers with different semantics but pointing to the same texture mapping unit. It's simply a level of abstraction between the shader an the application in which the shader is embedded. You can define more samplers and play around with them to learn the way how texture mapping units and samplers interact.

The 'Bilinear filtering' check box enables texture filtering. It can help to improve visual quality.

Continue with Lighting and materials


Generated on Sun Mar 2 17:12:31 2008 for Shader Maker by  doxygen 1.5.4