SteinSOFT.net
  SDL & OpenGL textures

In this code snippet I will show you how to use OpenGL textures in SDL. I will show you some code that loads an image file using the built-in image loading functions of SDL and creates an OpenGL texture from it. Then I will show you a work-around that is necessary for using image files loaded by SDL.

First let's take a quick look at the standard BMP loading function included in SDL, SDL_LoadBMP(..):

SDL_Surface *SDL_LoadBMP(const char *file);

This function returns a pointer to a SDL_Surface struct after loading BMP file found at file. After using it, it should be freed with SDL_FreeSurface(SDL_Surface *surface).

Here's a quick snippet that shows how to create an OpenGL texture after loading an Bitmap file:

GLuint texture;
//Load Bitmap
SDL_Surface* bmpFile = SDL_LoadBMP("data/test.bmp");
 
/* Standard OpenGL texture creation code */
glPixelStorei(GL_UNPACK_ALIGNMENT,4);
 		
glGenTextures(1,&texture);
glBindTexture(GL_TEXTURE_2D,texture);
 
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,minFilter);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,magFilter);
 		
gluBuild2DMipmaps(GL_TEXTURE_2D,3,bmpFile->w,
   bmpFile->h,GL_BGR_EXT,
   GL_UNSIGNED_BYTE,bmpFile->pixels);
 
//Free surface after using it
SDL_FreeSurface(bmpFile);

I think the code is pretty self-explaining. First we load the bitmap from file and then we use the member variables of SDL_Surface to get the necessary information to create an OpenGL texture. Don't forget to free the surface after creating the texture as we don't want to waste memory.

Now you could use the created texture but when first using it, you will notice that the texture is flipped and mirrored on the X-Axis. To solve the problem you have to use a little work-around that simply flipps and mirrors the texture matrix to represent textures correctly again. Use this code e.g. in your OpenGL init function:

/** 
 OpenGL Projection init..
 **/
 
//change to texture matrix and do the trick
glMatrixMode(GL_TEXTURE);
glRotatef(180.0f,0.0f,0.0f,1.0f);
glScalef(-1.0f,1.0f,1.0f);
 
//back to normal
glMatrixMode(GL_MODELVIEW);

That's it! If you have further questions, take a look at the message board. Happy Coding!

Copyright © by SteinSOFT