首页 文章

从SDL2表面创建OpenGL纹理 - 奇怪的像素值

提问于
浏览
6

我正在尝试使用SDL2为Wavefront Objects的OpenGL渲染加载纹理(目前我正在使用固定管道进行测试,但我最终计划移动到着色器) . 问题是应用于四边形的加载纹理(以及使用纹理右下角的一小部分的模型)如下所示:

A sample of the effect http://image-upload.de/image/daKaEf/e433b140c9.png This is the texture I used

使用SDL函数绘制时,图像加载正常并且看起来完全正常,因此可能是转换为已损坏的OGL纹理 . 请注意,我启用了alpha混合,纹理仍然完全不透明 - 因此值不是完全随机的,可能不是未初始化的内存 . 这是我转换表面的代码(从这里的各种教程和问题拼凑而成):

GLuint glMakeTexture(bool mipmap = false, int request_size = 0) { // Only works on 32 Bit Surfaces
    GLuint texture = 0;
    if ((bool)_surface) {
        int w,h;
        if (request_size) { // NPOT and rectangular textures are widely supported since at least a decade now; you should never need this...
            w = h = request_size;
            if (w<_surface->w || h<_surface->h) return 0; // No can do.
        } else {
            w = _surface->w;
            h = _surface->h;
        }

        SDL_LockSurface(&*_surface);
        std::cout<<"Bits: "<<(int)_surface->format->BytesPerPixel<<std::endl;

        Uint8 *temp = (Uint8*)malloc(w*h*sizeof(Uint32)); // Yes, I know it's 4...
        if (!temp) return 0;

        // Optimized code
        /*for (int y = 0; y<h; y++) { // Pitch is given in bytes, so we need to cast to 8 bit here!
            memcpy(temp+y*w*sizeof(Uint32),(Uint8*)_surface->pixels+y*_surface->pitch,_surface->w*sizeof(Uint32));
            if (w>_surface->w) memset(temp+y*w*sizeof(Uint32)+_surface->w,0,(w-_surface->w)*sizeof(Uint32));
        }
        for (int y = _surface->h; y<h; y++) memset(temp+y*w*sizeof(Uint32),0,w*sizeof(Uint32));
        GLenum format = (_surface->format->Rmask==0xFF)?GL_RGBA:GL_BGRA;*/

        // Naive code for testing
        for (int y = 0; y<_surface->h; y++)
            for (int x = 0; x<_surface->w; x++) {
                int mempos = (x+y*w)*4;
                SDL_Color pcol = get_pixel(x,y);
                temp[mempos] = pcol.r;
                temp[mempos+1] = pcol.g;
                temp[mempos+2] = pcol.b;
                temp[mempos+3] = pcol.a;
            }
        GLenum format = GL_RGBA;

        SDL_UnlockSurface(&*_surface);

        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);
        if (mipmap) glTexParameteri(texture, GL_GENERATE_MIPMAP, GL_TRUE);
        glTexImage2D(GL_TEXTURE_2D, 0, format, w, h, 0, format, GL_UNSIGNED_BYTE, temp);
        if (mipmap) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        else glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        free(temp); // Always clean up...
    }
    return texture;
}

编辑:_surface实际上是SDD_Surface的std :: shared_ptr . 因此,&*何时(取消)锁定它 .

顺便说一句,SDL声称表面在我的机器上被格式化为32位RGBA,我已经检查过了 .

绑定纹理并绘制四边形的代码在这里:

glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glBindTexture(GL_TEXTURE_2D,_texture[MAP_KD]);

static bool once = true;
if (once) {
    int tex;
    glGetIntegerv(GL_TEXTURE_BINDING_2D, &tex);
    bool valid = glIsTexture(tex);
    std::cout<<tex<<" "<<valid<<std::endl;
    once = false;
}
glBegin(GL_TRIANGLE_STRIP);
    //glColor3f(1.f,1.f,1.f);
    glNormal3f(0,1,0);
    glTexCoord2f(0.f,0.f); glVertex3f(0,0,0);
    glTexCoord2f(0.f,1.f); glVertex3f(0,0,1);
    glTexCoord2f(1.f,0.f); glVertex3f(1,0,0);
    glTexCoord2f(1.f,1.f); glVertex3f(1,0,1);
glEnd();

稍后从索引列表中绘制ax;代码太长了,无法在这里分享(此外,除了纹理之外,它还可以正常工作) .

我也尝试过将_surface-> pixels传递给glTexImage2D()的许多教程中找到的朴素方法,但这也无济于事(我听说这是错误的方法,因为音高!=宽* BytesPerPixel一般) . 已经过时的“优化”代码看起来完全一样,顺便说一下(如预期的那样) . 为了更好的测试,我编写了下半部分 . 将所有像素设置为特定颜色或使纹理部分透明按预期工作,因此我假设OpenGL正确加载temp中的值 . 我很可能理解SDL2 Surfaces中的内存布局已经搞砸了 .

最终编辑:解决方案(重置GL_UNPACK_ROW_LENGTH是关键,感谢Peter Clark):

GLuint glTexture(bool mipmap = false) {
    GLuint texture = 0;
    if ((bool)_surface) {
        GLenum texture_format, internal_format, tex_type;
        if (_surface->format->BytesPerPixel == 4) {
            if (_surface->format->Rmask == 0x000000ff) {
                texture_format = GL_RGBA;
                tex_type = GL_UNSIGNED_INT_8_8_8_8_REV;
            } else {
                texture_format = GL_BGRA;
                tex_type = GL_UNSIGNED_INT_8_8_8_8;
            }
            internal_format = GL_RGBA8;
        } else {
            if (_surface->format->Rmask == 0x000000ff) {
                texture_format = GL_RGB;
                tex_type = GL_UNSIGNED_BYTE;
            } else {
                texture_format = GL_BGR;
                tex_type = GL_UNSIGNED_BYTE;
            }
            internal_format = GL_RGB8;
        }

        int alignment = 8;
        while (_surface->pitch%alignment) alignment>>=1; // x%1==0 for any x
        glPixelStorei(GL_UNPACK_ALIGNMENT,alignment);

        int expected_pitch = (_surface->w*_surface->format->BytesPerPixel+alignment-1)/alignment*alignment;
        if (_surface->pitch-expected_pitch>=alignment) // Alignment alone wont't solve it now
            glPixelStorei(GL_UNPACK_ROW_LENGTH,_surface->pitch/_surface->format->BytesPerPixel);
        else glPixelStorei(GL_UNPACK_ROW_LENGTH,0);

        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);

        glTexImage2D(GL_TEXTURE_2D, 0, internal_format, _surface->w, _surface->h, 0, texture_format, tex_type, _surface->pixels);
        if (mipmap) {
            glGenerateMipmap(GL_TEXTURE_2D);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        } else {
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        }
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        glPixelStorei(GL_UNPACK_ALIGNMENT,4);
        glPixelStorei(GL_UNPACK_ROW_LENGTH,0);
    }
    return texture;
}

1 回答

  • 3

    像素存储对齐

    您需要告诉OpenGL图像的对齐方式是glPixelStorei(GL_UNPACK_ALIGNMENT, [1,2,4,8]) . 这将是2的最大幂,即8的音高除数 . 如果它不是可接受的值之一,则可能需要另外设置 GL_UNPACK_ROW_LENGTH - 请参阅this answer for more details and advice on that topic . 有一点需要注意 - GL_UNPACK_ROW_LENGTH 是行长度 in pixels ,其中 SDL_Surface::pitch 是行长度 in bytes . 最重要的是,您必须确保将internal_format,format和pixel_type设置为与SDL_Surface包含的内容相匹配 . One more resource on this topic.

    “完整”纹理

    你也没有创建complete texture when not using mipmaps . 要创建一个没有mipmap的"complete"纹理(可以读取或写入的纹理),必须使用 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0) 指定最大mipmap级别为0(基本图像),因为默认值为1000 .

    请注意:您正在使用 glTexParameteri(texture, GL_GENERATE_MIPMAP, GL_TRUE) 自动生成mipmap . 虽然这应该有用(虽然我不熟悉它),be aware that this method is deprecated支持现代OpenGL中的glGenerateMipmaps .

    可能的解决方案

    // Load texture into surface...
    // Error check..
    // Bind GL texture...
    
    // Calculate required align using pitch (largest power of 2 that is a divisor of pitch)
    
    glPixelStorei(GL_UNPACK_ALIGNMENT, align);
    //glPixelStorei(GL_UNPACK_ROW_LENGTH, row_length); // row_length = pitch / bytes_per_pixel
    
    glTexImage2D(
      GL_TEXTURE_2D, 
      0, 
      internal_format,
      sdl_surface->w,
      sdl_surface->h,
      0, 
      format,
      pixel_type, 
      sdl_surface->pixels);
    // Check for errors
    
    if(use_mipmaps)
    {
      glGenerateMipmap(GL_TEXTURE_2D);
      // Check for errors
    
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, /* filter mode */);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, /* filter mode */);
      // Check for errors
    }
    else
    {
      // This makes the texture complete 
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
    
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, /* filter mode */);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, /* filter mode */);
      // Check for errors
    }
    
    // Potentially reset GL_UNPACK_ALIGNMENT and/or GL_UNPACK_ROW_LENGTH to their default values
    // Cleanup
    

    错误检查

    请注意,使用 glGetError() 添加一些错误检查并不是一个坏主意,我已将其标记为 Check for errors . 您可以打印错误(如果有)然后放置断点/断言 . 我通常使用一个宏,所以我可以在发布版本中禁用大多数错误检查 - 这样做的效果如下:

    #ifdef MYPROJ_GRAPHICS_DEBUG
    #define ASSERT_IF_GL_ERROR \
    { \
      GLenum last_error = glGetError(); \
      if(last_error != GL_NO_ERROR); \
      { \
        printf("GL Error: %d", last_error); \
      } \
      __debugbreak(); // Visual Studio intrinsic - other compilers have similar intrinsics
    } 
    #else
    #define ASSERT_IF_GL_ERROR
    #endif
    

    It is always a good idea to do error checking ,它可能会显示一些有关它发生的信息 . 虽然,因为它听起来像驱动程序在一些未定义的行为后崩溃,所以在这种情况下它是's possible it won't .

    一种可能的替代方案

    我认为值得一提的是,在回答这个问题之前我并没有意识到这个问题 . 我没有碰到它,因为我通常使用stb_image来加载纹理 . 我提出它的原因是在 stb_image 的文档中声明 "There is no padding between image scanlines or between pixels, regardless of format." ,意思是 stb_image 为你处理它 . 如果您可以控制您必须加载的图像(例如,如果您正在制作游戏并控制资产的创建) stb_image 是另一个图像加载选项 .

相关问题