Patrick Bolter
Patrick Bolter

Reputation: 13

My OpenGL program only uses the last texture loaded (C++)

I have this issue with my loader:

int loadTexture(char *file)
{
    // Load the image
    SDL_Surface *tex = IMG_Load(file);
    GLuint t;

    cout << "Loading image: " << string(file) << "\n";
    if (tex) {
        glGenTextures(1, &t); // Generating 1 texture
        glBindTexture(GL_TEXTURE_2D, t); // Bind the texture
        glTexImage2D(GL_TEXTURE_2D, 0, 3, tex->w, tex->h, 0, GL_RGB, GL_UNSIGNED_BYTE, tex->pixels); // Map texture
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Set minifying parameter to linear
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Set magnifying parameter to linear
        SDL_FreeSurface(tex); // Free the surface from memory
        cout << "   > Image loaded: " << string(file) << "\n\n";
        return t; // return the texture index
    }
    else {
        cout << "   > Failed to load image: " << IMG_GetError() << "\n\n";
        SDL_FreeSurface(tex); // Free the surface from memory
        return -1; // return -1 in case the image failed to load
    }

}

It loads the images just fine but only the last image loaded is used when drawing my objects:

textTest = loadTexture("assets/test_texture_64.png");
textTest2 = loadTexture("assets/test_texture2_64.png");
textTest3 = loadTexture("assets/test_texture3_64.png");
textTest4 = loadTexture("assets/test_texture4_64.png");

Texture files: https://i.sstatic.net/CPmFX.png

The program running: https://i.sstatic.net/WI70C.png

Before drawing an object I use glBindTexture(GL_TEXTURE_2D, t) where t is the name of the texture I want to use. I'm new to OpenGL and C++ so I'm having trouble understanding the issue here.

Upvotes: 0

Views: 610

Answers (1)

clambake
clambake

Reputation: 822

You should check if loadTexture returns different texture IDs when you load the textures. Then you need to be sure that you bind the right textures onto the object using glBindTexture(...) which you say you are doing already.

How are you drawing your object right now? Is multi texturing involved? Be sure to have the right glPushMatrix / glPopMatrix calls before and after drawing your object.

From looking at your loader it looks correct to me although you do not glEnable and glDisable GL_TEXTURE_2D but that should not matter.

Upvotes: 1

Related Questions