Sign in to follow this  

Opengl texture

Recommended Posts

This topic might go to opengl forum but I thought that its more likely to be a newbie question. I can't seem to load a image file and use it as a texture in opengl.I am using c++ and sdl. Here is the function that I found
GLuint load_texture()
     GLuint texture; // Texture object handle
    SDL_Surface *surface = SDL_LoadBMP("naber.bmp"); // Gives us the information to make the texture
    GLenum texture_format;
GLint  nOfColors;

if ( surface ) { 
	// Check that the image's width is a power of 2
	if ( (surface->w & (surface->w - 1)) != 0 ) {
		printf("warning: image.bmp's width is not a power of 2\n");
	// Also check if the height is a power of 2
	if ( (surface->h & (surface->h - 1)) != 0 ) {
		printf("warning: image.bmp's height is not a power of 2\n");
        // get the number of channels in the SDL surface
        nOfColors = surface->format->BytesPerPixel;
        if (nOfColors == 4)     // contains an alpha channel
                if (surface->format->Rmask == 0x000000ff)
                        texture_format = GL_RGBA;
                        texture_format = GL_BGRA;
        } else if (nOfColors == 3)     // no alpha channel
                if (surface->format->Rmask == 0x000000ff)
                        texture_format = GL_RGB;
                        texture_format = GL_BGR;
        } else {
                printf("warning: the image is not truecolor..  this will probably break\n");
                // this error should not go unhandled
	// Have OpenGL generate a texture object handle for us
	glGenTextures( 1, &texture );
	// Bind the texture object
	glBindTexture( GL_TEXTURE_2D, texture );
	// Set the texture's stretching properties
	// Edit the texture object's image data using the information SDL_Surface gives us
	glTexImage2D( GL_TEXTURE_2D, 0, nOfColors, surface->w, surface->h, 0,
                      texture_format, GL_UNSIGNED_BYTE, surface->pixels );
else {
	printf("SDL could not load image.bmp: %s\n", SDL_GetError());
	return 1;
// Free the SDL_Surface only if it was successfully created
if ( surface ) { 
	SDL_FreeSurface( surface );
    // Clear the screen before drawing
    // Bind the texture to which subsequent calls refer to
    glBindTexture( GL_TEXTURE_2D, texture );


solved the first problem, I just had to add
	gluBuild2DMipmaps( GL_TEXTURE_2D, 3, surface->w, surface->h,
        texture_format, GL_UNSIGNED_BYTE, surface->pixels );

after the glTexImage2D(); but can I use the same thing with trancparency?(I mean does sdl_loadbmp provide it to us and what else I should change?) I'll try to do that

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this