Tutorial 6 – Textures

Up until now we’ve been drawing simple polygons with at most, one colour per vertex. This puts fairly strong limitations on what we can render. Imagine something as simple as a chessboard. It would be nice to render it as one large quad, but if we were to carry on as we have been, we’d need to render 64 individual black and white squares, each with 4 vertices. By using textures we can go for the much simpler option.

What Are Textures?

A texture is simply an image that we apply to polygons in order to give them a more realistic or interesting appearance. This tutorial will look at how to set up and render textured polygons.

Unfortunately OpenGL doesn’t provide any built in functions for loading images, so for this tutorial we will focus on loading “procedural” textures i.e. using some data in an array of bytes as a texture. We’ll be creating a chessboard effect. To do this we fill an array with high and low (light and dark) values.

Once we have some data in memory to be used as a texture, we need to tell OpenGL how to use it. Firstly tell OpenGL that we want to create the texture, this call will give us a handle to the texture.

glGenTextures(1, &m_textureID);

Now that we have a handle to a texture object we need to tell OpenGL that we will be initialising it as a 2D texture.

glBindTexture(GL_TEXTURE_2D, m_textureID);

This tells OpenGL that any calls made to affect 2D textures should apply to our “m_textureID” variable. The first property we set is how the texels of our image data will be mixed with the fragments of the polygon that it is applied to. The diagram below shows the two options that are available in OpenGL.

By setting the texture environment to use textures as GL_DECALs, only the texels are used to colour polygons. If you use GL_MODULATE then the polygons original colour will be mixed with the texel colour to get the final result.

Once we have done this (I’ll hopefully add some further notes on the rest of the texture initialisation soon) we load the image data into the OpenGL texture using a call to glTexImage2D. In this call we tell OpenGL the size of the image being loaded, the colour data stored in each pixel and how we want OpenGL to store that data internally.

Now that our texture is loaded, all that remains is to draw a polygon with the texture applied to it.

First turn texture mapping on with a call to glEnable(GL_TEXTURE_2D). In the same way that we need to set the position and colour of each vertex when drawing polygons, we now need to set the texture coordinates. To do this we make a call to glTexCoord2f. These texture coordinates will apply to all vertices that are generated subsequently (i.e. every call to glVertex3f).

Remember to turn off texturing when you aren’t planning on using it or you may get some unexpected results. Below is a video demonstrating the kind of effects that you can achieve with basic texturing.