views:

919

answers:

3

Hey, I have this script to load a SDL_Surface and save it as a OpenGL texture:

typedef GLuint texture;

texture load_texture(std::string fname){
 SDL_Surface *tex_surf = IMG_Load(fname.c_str());
 if(!tex_surf){
  return 0;
 }
 texture ret;
 glGenTextures(1, &ret);
 glBindTexture(GL_TEXTURE_2D, ret);
 glTexImage2D(GL_TEXTURE_2D, 0, 3, tex_surf->w, tex_surf->h, 0, GL_RGB, GL_UNSIGNED_BYTE, tex_surf->pixels);
 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
 SDL_FreeSurface(tex_surf);
 return ret;
}

The problem is that it isn't working. When I call the function from the main function, it just doesn't load any image (when displaying it's just turning the drawing color), and when calling from any function outside the main function, the program crashes. It's this line that makes the program crash:

2D(GL_TEXTURE_2D, 0, 3, tex_surf->w, tex_surf->h, 0, GL_RGB, GL_UNSIGNED_BYTE, tex_surf->pixels);

Can anybody see a mistake in this?

+1  A: 

My bet is you need to convert the SDL_Surface before trying to cram it into an OpenGL texture. Here's something that should give you the general idea:

SDL_Surface* originalSurface; // Load like an other SDL_Surface

int w = pow(2, ceil( log(originalSurface->w)/log(2) ) ); // Round up to the nearest power of two

SDL_Surface* newSurface = 
  SDL_CreateRGBSurface(0, w, w, 24, 0xff000000, 0x00ff0000, 0x0000ff00, 0);
SDL_BlitSurface(originalSurface, 0, newSurface, 0); // Blit onto a purely RGB Surface

texture ret;

glGenTextures( 1, &ret );
glBindTexture( GL_TEXTURE_2D, ret );
glTexImage2D( GL_TEXTURE_2D, 0, 3, w, w, 0, GL_RGB,
    GL_UNSIGNED_BYTE, newSurface->pixels );

I found the original code here. There may be some other useful posts on GameDev as well.

Zack Mulgrew
Thanks, it fixed the crashing, the texture just still isn't displayed...
Without more source it would be very hard to determine why your blitting is not working. Can you post the code you use to render?
Zack Mulgrew
A: 

I'm not sure if you're doing this somewhere outside your code snippet, but have you called

glEnable(GL_TEXTURE_2D);

at some point?

ParoXoN
A: 

Also, the default GL_REPLACE texture blending mode will multiply the current glColor with the incoming texel RGB values. Consequence: glColor3f(0,0,0) will give you black where your texture should be :)

Make sure you glColor3f(1,1,1) before drawing your textured geometry.

genpfault