【发布时间】:2019-08-23 07:46:17
【问题描述】:
我需要在我的着色器中使用两个纹理,一个在顶点着色器中,另一个在片段着色器中。在这两种情况下,它们都在 uniform sampler2D tex1; 或 uniform sampler2D tex2; 等着色器中引用,但是我不确定如何正确使用相关的 GL 调用。
初始化
首先,我如何创建这两个纹理?我需要像这样使用多个纹理单元吗
GLuint texIdx[2] = {0, 1};
GLuint texName[2];
GLint texUniformID[2];
// Initialize first texture
glActiveTexture (GL_TEXTURE0 + texIdx[0]);
glGenTextures (1, &texName[0]);
glBindTexture (GL_TEXTURE_2D, texName[0]);
glTexImage2D (GL_TEXTURE_2D, 0, GL_R32F, xDim0, yDim0, 0, GL_RED, GL_FLOAT, someTextureData);
// Initialize second texture
glActiveTexture (GL_TEXTURE0 + texIdx[1]);
glGenTextures (1, &texName[1]);
glBindTexture (GL_TEXTURE_2D, texName[1]);
glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB, xDim1, yDim1, 0, GL_RGB, GL_FLOAT, someOther1TextureData);
// Set the uniforms to refer to the textures
texUniformID[0] = glGetUniformLocation (myShaderProgram, "tex1");
texUniformID[1] = glGetUniformLocation (myShaderProgram, "tex2");
glUniform1i (texUniformID[0], texIdx[0]);
glUniform1i (texUniformID[1], texIdx[1]);
或者我可以使用单个纹理单元,因为glGenTextures 允许我创建多个纹理,有点像这样:
GLuint texName[2];
GLint texUniformID[2];
// Activate some texture unit
glActiveTexture (GL_TEXTURE0);
// Generate two textures
glGenTextures (2, texName);
// Initialize first texture
glBindTexture (GL_TEXTURE_2D, texName[0]);
glTexImage2D (GL_TEXTURE_2D, 0, GL_R32F, xDim0, yDim0, 0, GL_RED, GL_FLOAT, someTextureData);
// Initialize second texture
glBindTexture (GL_TEXTURE_2D, texName[1]);
glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB, xDim1, yDim1, 0, GL_RGB, GL_FLOAT, someOther1TextureData);
// Set the uniforms to refer to the textures
texUniformID[0] = glGetUniformLocation (myShaderProgram, "tex1");
texUniformID[1] = glGetUniformLocation (myShaderProgram, "tex2");
glUniform1i (texUniformID[0], /* what parameter here? */);
glUniform1i (texUniformID[1], /* what parameter here? */);
总而言之,我不明白一方面拥有多个纹理单元以及通过调用glGenTextures 创建多个纹理的能力有什么意义,以及正确的方法是什么如果我需要在着色器程序中使用多个纹理。
渲染期间的使用
作为后续问题,如果我以正确的方式初始化了多个纹理,在调用 glDrawElements 期间激活两个纹理以激活的正确调用顺序是什么?调用的正确顺序是什么在运行时成功更新纹理glTexSubImage2D?
跟进问题
现在更进一步,如果我在渲染调用中使用多个不同的着色器程序并且它们都使用纹理,应该如何处理?每个着色器程序的每个纹理都应该使用唯一的纹理单元吗?
【问题讨论】:
标签: c++ opengl shader textures