SDL OpenGL 纹理受到绿色调的困扰

SDL OpenGL Textures Plagued with Green Tint

我在尝试使用 SDL_image 将图像加载到 OpenGL 纹理时收到意外输出。

我的代码的相关部分是:

/**
 * Load texture
 * @param {char*} [filename] File name to load
 * @param {int*} [textw] Texture width pointer (value returned)
 * @param {int*} [texth] Texture height pointer (value returned)
 * @return {GLuint}
 * @link http://sdl.beuc.net/sdl.wiki/OpenGL_Texture_Example
 **/
GLuint LoadTexture(char *filename, int *textw, int *texth) {

    GLuint textureid;
    int mode;

    SDL_Surface *surface = IMG_Load(filename);

    // could not load filename
    if (!surface) {
        return 0;
    }

    // work out what format to tell glTexImage2D to use...
    if (surface->format->BytesPerPixel == 3) { // RGB 24bit
        mode = GL_RGB;
        printf( "GL_RGB\n" );
    } else if (surface->format->BytesPerPixel == 4) { // RGBA 32bit
        mode = GL_RGBA;
        printf( "GL_RGBA\n" );
    } else {
        SDL_FreeSurface(surface);
        return 0;
    }

    // Record texture dimensions
    *textw = surface->w;
    *texth = surface->h;

    // create one texture name
    glGenTextures(1, &textureid);

    // tell opengl to use the generated texture name
    glBindTexture(GL_TEXTURE_2D, textureid);

    // this reads from the sdl surface and puts it into an opengl texture
    glTexImage2D(GL_TEXTURE_2D, 0, mode, surface->w, surface->h, 0, mode, GL_UNSIGNED_BYTE, surface->pixels);

    // these affect how this texture is drawn later on...
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    // clean up
    SDL_FreeSurface(surface);

    return textureid;

}

/**
 * Render
 * @param {GLuint} [textureid] OpenGL texture to apply
 **/
void render( textureid ) {

    //Clear color buffer
    glClear( GL_COLOR_BUFFER_BIT );

    //Render quad
    if ( gRenderQuad ) {

        // Set color
        glColor3f(0.0f,1.0f,0.0f); 

        // tell opengl to use the generated texture name
        glBindTexture(GL_TEXTURE_2D, textureid);
        glEnable(GL_TEXTURE_2D);

        // Draw rectangle
        glBegin( GL_QUADS );

        // Top left
        glTexCoord2i(0, 1);
        glVertex2f( -1.0f, -1.0f );

        // Top right
        glTexCoord2i(1, 1);
        glVertex2f( 1.0f, -1.0f );

        // Bottom left
        glTexCoord2i(1, 0);
        glVertex2f( 1.0f, 1.0f );

        // Bottom right
        glTexCoord2i(0, 0);
        glVertex2f( -1.0f, 1.0f );

        glEnd();

        glDisable(GL_TEXTURE_2D );

    }

}

我加载的原生图片是:

但输出是:

根据我在另一个 Stack Overflow post 上阅读的内容,我认为这可能是一个反向通道问题,但建议的解决方案无法解决我的问题。我的 approach/code 怎么了?

据我所知,加载纹理没有任何问题。输出具有绿色色调的原因是因为您设置了:

glColor3f(0.0f, 1.0f, 0.0f);

此颜色值将与纹理中的颜色样本相乘,这意味着最终输出的红色和蓝色分量将始终为 0,这就是图像呈现绿色调的原因。如果您想使用原始纹理颜色,您应该始终设置:

glColor3f(1.0f, 1.0f, 1.0f);