In this tutorial, you will learn :

  • What are UV coordinates
  • How to load textures yourself
  • How to use them in OpenGL
  • What is filtering and mipmapping, and how to use them
  • How to load texture more robustly with GLFW
  • What the alpha channel is

About UV coordinates

When texturing a mesh, you need a way to tell to OpenGL which part of the image has to be used for each triangle. This is done with UV coordinates.

Each vertex can have, on top of its position, a couple of floats, U and V. These coordinates are used to access the texture, in the following way :

Notice how the texture is distorted on the triangle.

Loading .BMP images yourself

Knowing the BMP file format is not crucial : plenty of libraries can load BMP files for you. But it’s very simple and can help you understand how things work under the hood. So we’ll write a BMP file loader from scratch, so that you know how it works, and never use it again.

Here is the declaration of the loading function :

1 GLuint loadBMP_custom(const char * imagepath);

so it’s used like this :

1 GLuint image = loadBMP_custom("./my_texture.bmp");

Let’s see how to read a BMP file, then.

First, we’ll need some data. These variable will be set when reading the file.

1 // Data read from the header of the BMP file
2 unsigned char header[54]; // Each BMP file begins by a 54-bytes header
3 unsigned int dataPos;     // Position in the file where the actual data begins
4 unsigned int width, height;
5 unsigned int imageSize;   // = width*height*3
6 // Actual RGB data
7 unsigned char * data;

We now have to actually open the file

1 // Open the file
2 FILE * file = fopen(imagepath,"rb");
3 if (!file){printf("Image could not be opened\n"); return 0;}

The first thing in the file is a 54-bytes header. It contains information such as “Is this file really a BMP file?”, the size of the image, the number of bits per pixel, etc. So let’s read this header :

1 if ( fread(header, 1, 54, file)!=54 ){ // If not 54 bytes read : problem
2     printf("Not a correct BMP file\n");
3     return false;
4 }

The header always begins by BM. As a matter of fact, here’s what you get when you open a .BMP file in a hexadecimal editor :

So we have to check that the two first bytes are really ‘B’ and ‘M’ :

1 if ( header[0]!='B' || header[1]!='M' ){
2     printf("Not a correct BMP file\n");
3     return 0;
4 }

Now we can read the size of the image, the location of the data in the file, etc :

1 // Read ints from the byte array
2 dataPos    = *(int*)&(header[0x0A]);
3 imageSize  = *(int*)&(header[0x22]);
4 width      = *(int*)&(header[0x12]);
5 height     = *(int*)&(header[0x16]);

We have to make up some info if it’s missing :

1 // Some BMP files are misformatted, guess missing information
2 if (imageSize==0)    imageSize=width*height*3; // 3 : one byte for each Red, Green and Blue component
3 if (dataPos==0)      dataPos=54; // The BMP header is done that way

Now that we know the size of the image, we can allocate some memory to read the image into, and read :

1 // Create a buffer
2 data = new unsigned char [imageSize];
4 // Read the actual data from the file into the buffer
5 fread(data,1,imageSize,file);
7 //Everything is in memory now, the file can be closed
8 fclose(file);

We arrive now at the real OpenGL part. Creating textures is very similar to creating vertex buffers : Create a texture, bind it, fill it, and configure it.

In glTexImage2D, the GL_RGB indicates that we are talking about a 3-component color, and GL_BGR says how exactly it is represented in RAM. As a matter of fact, BMP does not store Red->Green->Blue but Blue->Green->Red, so we have to tell it to OpenGL.

 1 // Create one OpenGL texture
 2 GLuint textureID;
 3 glGenTextures(1, &textureID);
 5 // "Bind" the newly created texture : all future texture functions will modify this texture
 6 glBindTexture(GL_TEXTURE_2D, textureID);
 8 // Give the image to OpenGL
 9 glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);

We’ll explain those last two lines later. Meanwhile, on the C++-side, you can use your new function to load a texture :

1 GLuint Texture = loadBMP_custom("uvtemplate.bmp");

Another very important point :** use power-of-two textures !**

  • good : 128x128, 256x256, 1024x1024, 2x2…
  • bad : 127x128, 3x5, …
  • okay but weird : 128*256

Using the texture in OpenGL

We’ll have a look at the fragment shader first. Most of it is straightforward :

 1 #version 330 core
 3 // Interpolated values from the vertex shaders
 4 in vec2 UV;
 6 // Ouput data
 7 out vec3 color;
 9 // Values that stay constant for the whole mesh.
10 uniform sampler2D myTextureSampler;
12 void main(){
14     // Output color = color of the texture at the specified UV
15     color = texture( myTextureSampler, UV ).rgb;
16 }

Three things :

  • The fragment shader needs UV coordinates. Seems fair.
  • It also needs a “sampler2D” in order to know which texture to access (you can access several texture in the same shader)
  • Finally, accessing a texture is done with texture(), which gives back a (R,G,B,A) vec4. We’ll see about the A shortly.

The vertex shader is simple too, you just have to pass the UVs to the fragment shader :

 1 #version 330 core
 3 // Input vertex data, different for all executions of this shader.
 4 layout(location = 0) in vec3 vertexPosition_modelspace;
 5 layout(location = 1) in vec2 vertexUV;
 7 // Output data ; will be interpolated for each fragment.
 8 out vec2 UV;
10 // Values that stay constant for the whole mesh.
11 uniform mat4 MVP;
13 void main(){
15     // Output position of the vertex, in clip space : MVP * position
16     gl_Position =  MVP * vec4(vertexPosition_modelspace,1);
18     // UV of the vertex. No special space for this one.
19     UV = vertexUV;
20 }

Remember “layout(location = 1) in vec2 vertexUV” from Tutorial 4 ? Well, we’ll have to do the exact same thing here, but instead of giving a buffer (R,G,B) triplets, we’ll give a buffer of (U,V) pairs.

 1 // Two UV coordinatesfor each vertex. They were created with Blender. You'll learn shortly how to do this yourself.
 2 static const GLfloat g_uv_buffer_data[] = {
 3     0.000059f, 1.0f-0.000004f,
 4     0.000103f, 1.0f-0.336048f,
 5     0.335973f, 1.0f-0.335903f,
 6     1.000023f, 1.0f-0.000013f,
 7     0.667979f, 1.0f-0.335851f,
 8     0.999958f, 1.0f-0.336064f,
 9     0.667979f, 1.0f-0.335851f,
10     0.336024f, 1.0f-0.671877f,
11     0.667969f, 1.0f-0.671889f,
12     1.000023f, 1.0f-0.000013f,
13     0.668104f, 1.0f-0.000013f,
14     0.667979f, 1.0f-0.335851f,
15     0.000059f, 1.0f-0.000004f,
16     0.335973f, 1.0f-0.335903f,
17     0.336098f, 1.0f-0.000071f,
18     0.667979f, 1.0f-0.335851f,
19     0.335973f, 1.0f-0.335903f,
20     0.336024f, 1.0f-0.671877f,
21     1.000004f, 1.0f-0.671847f,
22     0.999958f, 1.0f-0.336064f,
23     0.667979f, 1.0f-0.335851f,
24     0.668104f, 1.0f-0.000013f,
25     0.335973f, 1.0f-0.335903f,
26     0.667979f, 1.0f-0.335851f,
27     0.335973f, 1.0f-0.335903f,
28     0.668104f, 1.0f-0.000013f,
29     0.336098f, 1.0f-0.000071f,
30     0.000103f, 1.0f-0.336048f,
31     0.000004f, 1.0f-0.671870f,
32     0.336024f, 1.0f-0.671877f,
33     0.000103f, 1.0f-0.336048f,
34     0.336024f, 1.0f-0.671877f,
35     0.335973f, 1.0f-0.335903f,
36     0.667969f, 1.0f-0.671889f,
37     1.000004f, 1.0f-0.671847f,
38     0.667979f, 1.0f-0.335851f
39 };

The UV coordinates above correspond to the following model :

The rest is obvious. Generate the buffer, bind it, fill it, configure it, and draw the Vertex Buffer as usual. Just be careful to use 2 as the second parameter (size) of glVertexAttribPointer instead of 3.

This is the result :

and a zoomed-in version :

What is filtering and mipmapping, and how to use them

As you can see in the screenshot above, the texture quality is not that great. This is because in loadBMP_custom, we wrote :


This means that in our fragment shader, texture() takes the texel that is at the (U,V) coordinates, and continues happily.

There are several things we can do to improve this.

Linear filtering

With linear filtering, texture() also looks at the other texels around, and mixes the colours according to the distance to each center. This avoids the hard edges seen above.

This is much better, and this is used a lot, but if you want very high quality you can also use anisotropic filtering, which is a bit slower.

Anisotropic filtering

This one approximates the part of the image that is really seen through the fragment. For instance, if the following texture is seen from the side, and a little bit rotated, anisotropic filtering will compute the colour contained in the blue rectangle by taking a fixed number of samples (the “anisotropic level”) along its main direction.


Both linear and anisotropic filtering have a problem. If the texture is seen from far away, mixing only 4 texels won’t be enough. Actually, if your 3D model is so far away than it takes only 1 fragment on screen, ALL the texels of the image should be averaged to produce the final color. This is obviously not done for performance reasons. Instead, we introduce MipMaps :

  • At initialisation time, you scale down your image by 2, successively, until you only have a 1x1 image (which effectively is the average of all the texels in the image)
  • When you draw a mesh, you select which mipmap is the more appropriate to use given how big the texel should be.
  • You sample this mipmap with either nearest, linear or anisotropic filtering
  • For additional quality, you can also sample two mipmaps and blend the results.

Luckily, all this is very simple to do, OpenGL does everything for us provided that you ask him nicely :

1 // When MAGnifying the image (no bigger mipmap available), use LINEAR filtering
3 // When MINifying the image, use a LINEAR blend of two mipmaps, each filtered LINEARLY too
5 // Generate mipmaps, by the way.
6 glGenerateMipmap(GL_TEXTURE_2D);

How to load texture with GLFW

Our loadBMP_custom function is great because we made it ourselves, but using a dedicated library is better. GLFW2 can do that too (but only for TGA files, and this feature has been removed in GLFW3, that we now use) :

 1 GLuint loadTGA_glfw(const char * imagepath){
 3     // Create one OpenGL texture
 4     GLuint textureID;
 5     glGenTextures(1, &textureID);
 7     // "Bind" the newly created texture : all future texture functions will modify this texture
 8     glBindTexture(GL_TEXTURE_2D, textureID);
10     // Read the file, call glTexImage2D with the right parameters
11     glfwLoadTexture2D(imagepath, 0);
13     // Nice trilinear filtering.
14     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
15     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
18     glGenerateMipmap(GL_TEXTURE_2D);
20     // Return the ID of the texture we just created
21     return textureID;
22 }

Compressed Textures

At this point, you’re probably wondering how to load JPEG files instead of TGA.

Short answer : don’t. GPUs can’t understand JPEG. So you’ll compress your original image in JPEG, and decompress it so that the GPU can understand it. You’re back to raw images, but you lost image quality while compressing to JPEG.

There’s a better option.

Creating compressed textures

  • Download The Compressonator, an AMD tool
  • Load a Power-Of-Two texture in it
  • Generate mipmaps so that you won’t have to do it on runtime
  • Compress it in DXT1, DXT3 or in DXT5 (more about the differences between the various formats on Wikipedia) :

  • Export it as a .DDS file.

At this point, your image is compressed in a format that is directly compatible with the GPU. Whenever calling texture() in a shader, it will uncompress it on-the-fly. This can seem slow, but since it takes a LOT less memory, less data needs to be transferred. But memory transfers are expensive; and texture decompression is free (there is dedicated hardware for that). Typically, using texture compression yields a 20% increase in performance. So you save on performance and memory, at the expense of reduced quality.

Using the compressed texture

Let’s see how to load the image. It’s very similar to the BMP code, except that the header is organized differently :

 1 GLuint loadDDS(const char * imagepath){
 3     unsigned char header[124];
 5     FILE *fp;
 7     /* try to open the file */
 8     fp = fopen(imagepath, "rb");
 9     if (fp == NULL)
10         return 0;
12     /* verify the type of file */
13     char filecode[4];
14     fread(filecode, 1, 4, fp);
15     if (strncmp(filecode, "DDS ", 4) != 0) {
16         fclose(fp);
17         return 0;
18     }
20     /* get the surface desc */
21     fread(&header, 124, 1, fp); 
23     unsigned int height      = *(unsigned int*)&(header[8 ]);
24     unsigned int width         = *(unsigned int*)&(header[12]);
25     unsigned int linearSize     = *(unsigned int*)&(header[16]);
26     unsigned int mipMapCount = *(unsigned int*)&(header[24]);
27     unsigned int fourCC      = *(unsigned int*)&(header[80]);

After the header is the actual data : all the mipmap levels, successively. We can read them all in one batch :

1 unsigned char * buffer;
2     unsigned int bufsize;
3     /* how big is it going to be including all mipmaps? */
4     bufsize = mipMapCount > 1 ? linearSize * 2 : linearSize;
5     buffer = (unsigned char*)malloc(bufsize * sizeof(unsigned char));
6     fread(buffer, 1, bufsize, fp);
7     /* close the file pointer */
8     fclose(fp);

Here we’ll deal with 3 different formats : DXT1, DXT3 and DXT5. We need to convert the “fourCC” flag into a value that OpenGL understands.

 1 unsigned int components  = (fourCC == FOURCC_DXT1) ? 3 : 4;
 2     unsigned int format;
 3     switch(fourCC)
 4     {
 5     case FOURCC_DXT1:
 6         format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
 7         break;
 8     case FOURCC_DXT3:
 9         format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
10         break;
11     case FOURCC_DXT5:
12         format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
13         break;
14     default:
15         free(buffer);
16         return 0;
17     }

Creating the texture is done as usual :

1 // Create one OpenGL texture
2     GLuint textureID;
3     glGenTextures(1, &textureID);
5     // "Bind" the newly created texture : all future texture functions will modify this texture
6     glBindTexture(GL_TEXTURE_2D, textureID);

And now, we just have to fill each mipmap one after another :

 1 unsigned int blockSize = (format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) ? 8 : 16;
 2     unsigned int offset = 0;
 4     /* load the mipmaps */
 5     for (unsigned int level = 0; level < mipMapCount && (width || height); ++level)
 6     {
 7         unsigned int size = ((width+3)/4)*((height+3)/4)*blockSize;
 8         glCompressedTexImage2D(GL_TEXTURE_2D, level, format, width, height, 
 9             0, size, buffer + offset);
11         offset += size;
12         width  /= 2;
13         height /= 2;
14     }
15     free(buffer); 
17     return textureID;

Inversing the UVs

DXT compression comes from the DirectX world, where the V texture coordinate is inversed compared to OpenGL. So if you use compressed textures, you’ll have to use ( coord.u, 1.0-coord.v) to fetch the correct texel. You can do this whenever you want : in your export script, in your loader, in your shader…


You just learnt to create, load and use textures in OpenGL.

In general, you should only use compressed textures, since they are smaller to store, almost instantaneous to load, and faster to use; the main drawback it that you have to convert your images through The Compressonator (or any similar tool)


  • The DDS loader is implemented in the source code, but not the texture coordinate modification. Change the code at the appropriate place to display the cube correctly.
  • Experiment with the various DDS formats. Do they give different result ? Different compression ratios ?
  • Try not to generate mipmaps in The Compressonator. What is the result ? Give 3 different ways to fix this.