我正在从 leanrnOpenGL : Textures 学习 openGL 纹理
我可以区分 glGetUniformLocation
和“纹理单元”。
glGetUniformLocation
:表示程序对象中特定统一变量位置的整数。
纹理单元:纹理的位置称为纹理单元。
页面有以下句子:
We also have to tell OpenGL to which texture unit each shader sampler belongs to
by setting each sampler using `glUniform1i`.
对应的代码如下:
ourShader.use();
glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), 0); // set it manually
ourShader.setInt("texture2", 1); // or with shader class
我做了一些错误的修改如下:
texture1
的纹理单元值分配给 3,将 texture2
分配给 4。glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), 3);
ourShader.setInt("texture2", 4);
程序可以执行,但显示完全纯黑色的纹理(或什么都没有?)
纹理单元的值必须从0开始吗?为什么?
为什么分配 3 或 4 会导致错误的效果?
答案 0 :(得分:0)
在@Rabbid76的指导下,我得到了答案。
在learnOpenGL : Texture的原文中,有一句话引起了我的困惑:
This location of a texture is more commonly known as a texture unit.
@Rabbid76 纠正我:
The binding point between the texture object and the sampler uniform is the `texture unit`.
纹理单元的值必须从0开始吗?
答:没有。
我们至少可以指定为 0~15。
OpenGL should have a at least a minimum of 16 texture units for you to use
which you can activate using GL_TEXTURE0 to GL_TEXTURE15.
对应,绘制时,
通过指定 glActiveTexture
到 GL_TEXTURE0
来调用 GL_TEXTURE15
。
以下是我更正后的正确代码:
// set `3` `4` as texture unit value
glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), 3);
ourShader.setInt("texture2", 4);
// bind textures on corresponding texture units
glActiveTexture(GL_TEXTURE3); // replace GL_TEXTURE0 with GL_TEXTURE3
glBindTexture(GL_TEXTURE_2D, texture1);
glActiveTexture(GL_TEXTURE4); // replace GL_TEXTURE1 with GL_TEXTURE4
glBindTexture(GL_TEXTURE_2D, texture2);
代码正常运行并显示正确的叠加效果(不再是黑色视图)。