Search code examples
c++opengltexturesopengl-4

OpenGL Texture DSA not showing texture


I'm attempting to use the newer DSA functions to show textures but it's not working at all.

Here is the code for using the older approach.

unsigned int containerTexture = 0;
glGenTextures(1, &containerTexture);
glBindTexture(GL_TEXTURE_2D, containerTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

int width = 0, height = 0, channelCount = 0;
stbi_set_flip_vertically_on_load(true);
unsigned char* pixels = stbi_load("res/textures/container.jpg", &width, &height, &channelCount, 0);
if (pixels) {
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels);
    glGenerateMipmap(GL_TEXTURE_2D);
} else {
    cerr << "Failed to load texture! \n";
}
stbi_image_free(pixels);

Here is the DSA version.

unsigned int containerTexture = 0;

int width = 0, height = 0, channelCount = 0;
stbi_set_flip_vertically_on_load(true);
unsigned char* pixels = stbi_load("res/textures/container.jpg", &width, &height, &channelCount, 0);
if (pixels) {
    glCreateTextures(GL_TEXTURE_2D, 1, &containerTexture);

    glTextureParameteri(containerTexture, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTextureParameteri(containerTexture, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTextureParameteri(containerTexture, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTextureParameteri(containerTexture, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glTextureStorage2D(containerTexture, 1, GL_RGB8, width, height);
    glTextureSubImage2D(containerTexture, 1, 0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels);
    glGenerateTextureMipmap(containerTexture);

    glBindTextureUnit(0, containerTexture);
} else {
    cerr << "Failed to load texture! \n";
}
stbi_image_free(pixels);

Solution

  • The 2nd parameter to glTextureSubImage2D is the level to be set. Mipmap levels are zero-based, therefore the base level is 0 and not 1 as in your code:

    glTextureSubImage2D(containerTexture, 0, 0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels);