dirkwillem
dirkwillem

Reputation: 55

sdl surface to opengl texture

How can I convert a .png image to an OpenGL surface, with SDL? what I have now:

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;
}

and my code to draw the thing:

glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, tex);

        //Use blurry texture mapping (replace GL_LINEAR with GL_NEAREST for blocky)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        glColor4f( 1.0, 1.0, 1.0, 1.0 ); //Don't use special coloring

        glBegin(GL_QUADS);

        glTexCoord2f(0.0f, 0.0f);
        glVertex3f(0.0f, 0.0f, 0.0f);
        glTexCoord2f(1.0f, 0.0f);
        glVertex3f(128.0f, 0.0f, 0.0f);
        glTexCoord2f(1.0f, 1.0f);
        glVertex3f(128.0f, 128.0f, 0.0f);
        glTexCoord2f(0.0f, 1.0f);
        glVertex3f(0.0f, 128.0f, 0.0f);

        glEnd();

        glDisable(GL_TEXTURE_2D);

The problem is that it only works with .bmp files, and they turn bluish, so what is wrong? Also, when I try to load a .png, it shows up really weird.

Upvotes: 3

Views: 2906

Answers (1)

Eelke
Eelke

Reputation: 21993

Wrong colors can be caused by getting the channel order wrong. The code I have lying around for loading .bmp's uses GL_BGR instead of GL_RGB so I think that will solve your problem with bmp's.

The problem with your png image is more likely caused by the png being 32-bits per pixel. Probably the best solution for you is to inspect the format field of the SDL surface to determine to appropriate flags/values to pass to glTexImage2D.

Upvotes: 2

Related Questions