首页 > 解决方案 > OpenGL 纹理 DSA 不显示纹理

问题描述

我正在尝试使用较新的 DSA 函数来显示纹理,但它根本不起作用。

这是使用旧方法的代码。

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);

这是 DSA 版本。

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);

标签: c++opengltexturesopengl-4

解决方案


第二个参数 toglTextureSubImage2Dlevel要设置的。Mipmap 级别是从零开始的,因此基本级别01您的代码中的不同:

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

推荐阅读