简体   繁体   English

OpenGL 从机顶盒图像加载 rgb 纹理

[英]OpenGL loading rgb texture from stb image

I have a class for creating textures from a path but when i try to load in a texture with 3 channels (rgb) it gives me read access violation exception when running this line我有一个 class 用于从路径创建纹理,但是当我尝试加载具有 3 个通道(rgb)的纹理时,它在运行此行时给了我读取访问冲突异常

glTextureSubImage2D(m_RendererID, 0, 0, 0, m_Width, m_Height, m_DataFormat, GL_UNSIGNED_BYTE, data);

I tried to change the parameters in the stbi load function but that didn't work.我尝试更改 stbi 加载 function 中的参数,但这没有用。

When i load the image it sets the correct width, height and channel data so i don't know what i am doing wrong当我加载图像时,它会设置正确的宽度、高度和通道数据,所以我不知道我在做什么错

The pointer to the data isn't nullptr either指向数据的指针也不是 nullptr

OpenGLTexture2D::OpenGLTexture2D(const std::string& path)
    {
        RADIANT_PROFILE_FUNCTION();

        m_Path = path;

        stbi_set_flip_vertically_on_load(1);

        int width, height, channels;

        stbi_uc* data = stbi_load(path.c_str(), &width, &height, &channels, 0);
        RADIANT_CORE_ASSERT(data, "Failed To Load Image");

        m_Width = width;
        m_Height = height;

        if (channels == 4) {
            m_InternalFormat = GL_RGBA8;
            m_DataFormat = GL_RGBA;
        }
        else if (channels == 3) {
            m_InternalFormat = GL_RGB8;
            m_DataFormat = GL_RGB;
        }
        else {
            RADIANT_CORE_ERROR("Texture Format Not Supported, Channels: {0})", channels);   
        }

        glCreateTextures(GL_TEXTURE_2D, 1, &m_RendererID);
        glTextureStorage2D(m_RendererID, 1, m_InternalFormat, m_Width, m_Height);

        glTextureParameteri(m_RendererID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTextureParameteri(m_RendererID, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

        glTextureSubImage2D(m_RendererID, 0, 0, 0, m_Width, m_Height, m_DataFormat, GL_UNSIGNED_BYTE, data);

        stbi_image_free(data);
    }

When an RGB image is loaded to a texture object, GL_UNPACK_ALIGNMENT needs to be set to 1.当 RGB 图像加载到纹理 object 时,需要将GL_UNPACK_ALIGNMENT设置为 1。
By default GL_UNPACK_ALIGNMENT is 4, so each line of an image is assumed to be aligned to 4 bytes.默认情况下GL_UNPACK_ALIGNMENT为 4,因此假定图像的每一行对齐到 4 个字节。 The pixels in the buffer have a size of 3 bytes and are tightly packed, this would cause a misalignment:缓冲区中的像素大小为 3 字节并且被紧密打包,这会导致错位:

glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTextureSubImage2D(m_RendererID, 0, 0, 0, m_Width, m_Height, m_DataFormat, GL_UNSIGNED_BYTE, data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM