OpenGL:如何将多个纹理传递给具有一个变量的着色器?

OpenGL : How can I pass multiple texture to a shader with one variable?

我根据这段代码 (https://github.com/Bly7/OBJ-Loader) 从 Obj 文件中加载了 material 和纹理信息。现在我想加载 Sponza 并渲染它。但是,有10张或更多的贴图,即使全部传给shader,也需要对应到合适的顶点。看从Obj文件加载的结果,每个部分都分配了贴图

示例。

Mesh 0 : Pillar
position0(x, y, z), position1(x, y, z), uv0(x, y) ... 
diffuse texture : tex0.png

Mesh 1 : Wall
position0(x, y, z), position1(x, y, z), uv0(x, y) ... 
diffuse texture : tex1.png
.
. 
.

纹理保存为一个数组,每个都有对应的网格索引。在我看来,将顶点信息传递给着色器时,如果将其除以网格数并同时传递纹理,效果会很好。但是,我不确定这个想法是否正确,我尝试了几种方法都没有用。

这是当前的简单代码。

main.cpp :
do {
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture[i]);  // texture[] : Array of textures loaded from obj file.
    glUniform1i(glGetUniformLocation(shaderID, "myTex"), 0);

    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, vertex_position);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER, texCoord);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);    

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element);
    glDrawElements(GL_TRIANGLES, element_indices.size(), GL_UNSIGNED_INT, (void*)0);

} while(glfwWindowShouldClose(window) == 0);

Fragment shader :
layout(location = 0) out vec4 out_color;
// from vertex shader
in vec2 texCoord; 

uniform sampler2D myTex;

void main() {
    out_color = texture(myTex, texCoord);
}

我想对应上面代码中的“i”加载的网格索引。如果我的想法有误,或者有其他方法,请告诉我。

由于您的模型每个网格只有一个纹理,我可以建议使用这个简单的代码:

do {
    glActiveTexture(GL_TEXTURE0);
    glUniform1i(glGetUniformLocation(shaderID, "myTex"), 0);
    
    for (unsigned int i = 0; i < mesh_count; i++) {
        glcall(glBindTexture(type, texture[i]));
        
        // Bind vertex and index (or element) buffer and setup vertex attribute pointers
        
        // Draw mesh
    }
} while (window_open);

代码多self-explaning。它首先激活纹理槽 0,然后为每个网格绑定纹理、顶点缓冲区、索引或元素缓冲区,并为绘制网格做任何准备工作。然后它发出绘制调用。

请注意,这是非常基本的示例。使用此代码,大多数模型看起来都很奇怪。我会推荐 LearnOpenGL 的 this tutorial,它以一种简单的方式更广泛地解释了这一点。