In order to load a texture we will use the following function :
bool LoadTexture(const char *fileName, GLuint *id)
This function will receive a texture filename and a pointer to a texture identifier. This identifier will be initialized from inside the function (if proceed). It will return true if the texture was successfully loaded, otherwise it will return false.
First we will read the texture file:
bool LoadTexture(const char *fileName, GLuint *id) {
FILE *f = fopen(fileName, "rb");
GLubyte *pixels = NULL;
if(!f) return false;
WORD width = 0, height = 0;
byte headerLength = 0;
byte imageType = 0;
byte bits = 0;
int format= 0;
int lineWidth = 0;
fread(&headerLength, sizeof(byte), 1, f);
//skip next byte
fseek(f,1,SEEK_CUR);
//read in the imageType (RLE, RGB, etc...)
fread(&imageType, sizeof(byte), 1, f);
//skip information we don't care about
fseek(f, 9, SEEK_CUR);
/*read the width, height and bits per pixel (16, 24 or 32). We only
will take care of 24 bits uncompressed TGAs*/
fread(&width, sizeof(WORD), 1, f);
fread(&height, sizeof(WORD), 1, f);
fread(&bits, sizeof(byte), 1, f);
//move the file pointer to the pixel data
fseek(f, headerLength + 1, SEEK_CUR);
//check if the image is not compressed.
if(imageType != 10)
{
//check if the image is a 24
if(bits == 24)
{
/*Another (faster) way to divide between 8. We want to know the
pixel size in bytes.*/
format = bits >> 3;
lineWidth = format * width;
pixels = new GLubyte[lineWidth * height];
//we are going to load the pixel data line by line
for(int y = 0; y < height; y++)
{
//Read current line of pixels
GLubyte *line = &(pixels[lineWidth * y]);
fread(line, lineWidth, 1, f);
/*Because the TGA is BGR instead of RGB, we must swap the R
and G components (OGL ES does not have the
GL_BGR_EXT extension*/
Now we will create the OpenGL Texture:
//Ask for a free texture name
glGenTextures(1, id);
/*first binding implies the texture object creation*/
glBindTexture(GL_TEXTURE_2D, *id);
/*Set texture properties: filtering and clamping modes*/
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
/*Upload pixels to the texture object*/
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB,
GL_UNSIGNED_BYTE, pixels);
/*Our copy in main main memory is no longer needed*/
delete [] pixels;
return true;
}
The texture will be loaded in the texture1 variable like this:
Gluint texture1 = 0;
bool result = LoadTexture("texturename.tga",&texture1);
