使用OpenGL纹理的SDL_CreateRGBSurface会产生黑色纹理

时间:2013-06-08 21:09:52

标签: c++ opengl sdl

我正在尝试使用SDL_CreateRGBSurfaceSDL_FillRect函数创建纹理, 但遗憾的是我没有这样做;我得到的只是一个黑色矩形。

为了完成这项任务,我正在使用以下代码(用于从IMG_Load文件加载纹理):

#if SDL_BYTEORDER == SDL_BIG_ENDIAN
        rmask = 0xff000000;
        gmask = 0x00ff0000;
        bmask = 0x0000ff00;
        amask = 0x000000ff;
#else
        rmask = 0x000000ff;
        gmask = 0x0000ff00;
        bmask = 0x00ff0000;
        amask = 0xff000000;
#endif
        rect = SDL_CreateRGBSurface(SDL_SWSURFACE, _w,_h,24,rmask,gmask,bmask,amask);
        if(rect == NULL ) {
            fprintf(stderr, "CreateRGBSurface failed: %s\n", SDL_GetError());
            exit(1);
        }

        Uint32 color = SDL_MapRGBA(rect->format,255,255,0,126);
        SDL_FillRect(rect,NULL,color);
        render.load(rect);

以下代码位于纹理加载

void Texture::load(SDL_Surface* surface){
    ogl_check_error("surface load");
    GLenum texture_format;
    GLint  nOfColors;
    if (  surface  ) { 

        // 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;
                else
                        texture_format = GL_BGRA;
        } else if (nOfColors == 3){    // no alpha channel

            if (surface->format->Rmask == 0x000000ff)
                    texture_format = GL_RGB;
            else
                    texture_format = GL_BGR;
         }else {
            cerr<<"bad surface"<<endl;
            exit(1);
            }

    // 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
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

    // 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());
    SDL_Quit();
    exit(1);
}    
ogl_check_error("after surface load");
width = surface->w;
height = surface -> h;


}

2 个答案:

答案 0 :(得分:0)

对于后代 - 我已经设置了错误的深度,它应该是32而不是24 ......

答案 1 :(得分:0)

你正在设置sdl_gl_attributes吗?

像           SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,8);          SDL_GL_SetAttribute(SDL_GL_RED_SIZE,8);     SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,8);     SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE,8);     SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,16);     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1);     SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE,8);