1

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

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.

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

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);
    }
2
  • 2
    What is the size of the texture? Is the width of the texture divisible by 4? If not try: glPixelStorei(GL_UNPACK_ALIGNMENT, 1); Commented Dec 27, 2020 at 18:21
  • width = 3049 height = 2049 Commented Dec 27, 2020 at 18:26

1 Answer 1

1

When an RGB image is loaded to a texture object, GL_UNPACK_ALIGNMENT needs to be set to 1.
By default GL_UNPACK_ALIGNMENT is 4, so each line of an image is assumed to be aligned to 4 bytes. The pixels in the buffer have a size of 3 bytes and are tightly packed, this would cause a misalignment:

glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTextureSubImage2D(m_RendererID, 0, 0, 0, m_Width, m_Height, m_DataFormat, GL_UNSIGNED_BYTE, data);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.