无法将纹理绑定到 GL_QUADS

Can't bind a texture to a GL_QUADS

我尝试在 OpenGL 中制作动画,我的顶点和动画正在运行,但我想为其添加背景图像,使用诸如 bmp 之类的文件或其他文件。

所以在阅读了几篇之后,我尝试了四边形技术,它只是显示一个四边形并将纹理绑定到它。

我使用 STB_Image 库,似乎我正确地指向了我的文件(如果我在文件名上出错,我的程序肯定会得到更快的响应)。

然后我实现了打印以查看它是否捕获了正确的文件并且确实如此!

我的代码看起来像这样,我的结果是一个出现在正确坐标中的白色方块,但没有出现纹理,文件已正确加载(打印了正确的尺寸),它只是没有绑定或出现在广场上...

glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);

int width, height, nrChannels;
unsigned char* data = stbi_load("test.jpg", &width, &height, &nrChannels, 0);
if (data == NULL) {
    printf("Error in loading the image\n");
    exit(1);
}
printf("Loaded image with a width of %dpx, a height of %dpx and %d channels\n", width, height, nrChannels);
unsigned int texture;

glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glBegin(GL_QUADS);
glVertex2f(2.0, 1.0);
glTexCoord2f(2.0, 1.0);
glVertex2f(8.0, 1.0);
glTexCoord2f(8.0, 1.0);
glVertex2f(8.0, 7.0);
glTexCoord2f(8.0, 7.0);
glVertex2f(2.0, 7.0);
glTexCoord2f(2.0, 7.0);
glEnd();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
if (data)
{
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
}
else
{
    std::cout << "Failed to load texture" << std::endl;
}

glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);

有什么想法吗?

glTexImage2D指定纹理对象的二维纹理图像。您必须这样做才能绘制四边形。
此外,二维纹理必须由 glEnable(GL_TEXTURE_2D) 启用。 纹理坐标必须在 [0.0, 1.0] 范围内(参见 How do opengl texture coordinates work?)。
glTexCoord2f has to be set before glVertex2f,因为调用glVertex时,当前颜色、法线和纹理坐标与顶点相关联。
由于您不生成 mipmaps (glGenerateMipmap), the texture minifying function (GL_TEXTURE_MIN_FILTER) 必须设置为 GL_LINEARGL_NEAREST。否则纹理将是不完整的 mipmap。

glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
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_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
if (data)
{
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
}
else
{
    std::cout << "Failed to load texture" << std::endl;
}
glBindTexture(GL_TEXTURE_2D, 0);
glClear(GL_COLOR_BUFFER_BIT);

glBindTexture(GL_TEXTURE_2D, texture);
glEnable(GL_TEXTURE_2D);

glColor4f(1.0, 1.0, 1.0, 1.0);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 1.0);
glVertex2f(2.0, 1.0);
glTexCoord2f(1.0, 1.0);
glVertex2f(8.0, 1.0);
glTexCoord2f(1.0, 0.0);
glVertex2f(8.0, 7.0);
glTexCoord2f(0.0, 0.0);
glVertex2f(2.0, 7.0);
glEnd();

glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);

glColor3f(1.0, 1.0, 1.0);