为什么我的 OpenGL 纹理是黑色的(在 Dear ImGUI 中)?

Why is my OpenGL texture black (in Dear ImGUI)?

在 OpenGL 4.6 中,我(尝试)创建并初始化纯色纹理如下:

glCreateTextures(GL_TEXTURE_2D, 1, &_textureHandle);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); // This doesn't change the outcome
std::vector<unsigned char> data(3 * WIDTH * HEIGHT, static_cast<unsigned char>(200));
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, data.data());

然后我像这样在 Dear ImGUI 中使用纹理:

ImGui::Image((void*)(intptr_t) _textureHandle, ImVec2(WIDTH, HEIGHT));

然而,这只是显示黑色纹理。

我也尝试了不同的初始化方式(没用):

unsigned char* data = new unsigned char[3 * WIDTH * HEIGHT];
for (unsigned int i = 0; i < (int)(WIDTH * HEIGHT); i++) {
    data[i * 3] = (unsigned char)255;
    data[i * 3 + 1] = (unsigned char)50;
    data[i * 3 + 2] = (unsigned char)170;
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, data);

有人知道我做错了什么吗?

如果不生成 mipmaps (with glGenerateMipmap) 您必须将 GL_TEXTURE_MIN_FILTER 设置为非 mipmap 过滤器。如果您不将缩小函数更改为 GL_NEARESTGL_LINEAR.

,则纹理将是“Mipmap Incomplete”

Eiter 生成 mipmaps:

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, data.data());
glGenerateMipmap(GL_TEXTURE_2D);

或者使用 GL_LINEAR 缩小函数:

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP);

您使用 OpenGL 4.5 DSA 创建纹理,但没有使用 DSA 设置纹理参数和图像。
您必须使用 glTextureParameterglTextureStorage2DglTextureSubImage2D 而不是 glTexParameterglTexImage2D

glCreateTextures(GL_TEXTURE_2D, 1, &_textureHandle);
glTextureParameteri(_textureHandle, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTextureParameteri(_textureHandle, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTextureParameteri(_textureHandle, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTextureParameteri(_textureHandle, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
std::vector<unsigned char> data(3 * WIDTH * HEIGHT, static_cast<unsigned char>(200));
glTextureStorage2D(_textureHandle, 1, GL_RGB8, WIDTH, HEIGHT);
glTextureSubImage2D(_textureHandle, 0, 0, 0, WIDTH, HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, data.data());