将 glDrawElements 与多个网格一起使用

Using glDrawElements with multiple meshes

我可以使用 glDrawArrays 成功绘制如下场景:

这种技术有点慢,所以我决定制作一个索引缓冲区并尝试使用 glDrawElements。结果如下所示:

您可能已经看到,右上角的方块渲染不正确,飞机下方的方块消失了。

生成缓冲区的代码

//create vertex and index buffer 
glGenBuffers(1, &gVertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, gVertexBuffer);   
glGenBuffers(1, &gIndexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gIndexBuffer);

// Define the size of the buffers   
GLuint floatAmount = 0;
GLuint GLuintAmount = 0;
for each (MeshObject* mesh in meshes)
{
    floatAmount += mesh->GetFloatAmount();
    GLuintAmount += mesh->GetGLuintAmount();
}
glBufferData(GL_ARRAY_BUFFER, floatAmount, 0, GL_STATIC_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, GLuintAmount, 0, GL_STATIC_DRAW);


// Define size and offset of the different subdata in the buffers
GLuint offsetVer = 0;
GLuint offsetInd = 0;
for each (MeshObject* mesh in meshes)
{
    // Set offset for mesh
    mesh->SetOffset(offsetVer / sizeof(Point));
    mesh->SetOffsetInd(offsetInd);

    glBufferSubData(GL_ARRAY_BUFFER,
        offsetVer,
        mesh->GetFloatAmount(),
        mesh->GetPoints().data());

    glBufferSubData(GL_ELEMENT_ARRAY_BUFFER,
        offsetInd,
        mesh->GetGLuintAmount(),
        mesh->GetIndicies().data());

    offsetVer += mesh->GetFloatAmount();
    offsetInd += mesh->GetGLuintAmount();
}

...以及渲染代码

glBindBuffer(GL_ARRAY_BUFFER, gVertexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gIndexBuffer);

mat4 vwMatrix = localCamera->GetPVMatrix() * mh->GetWorld();

glUniformMatrix4fv(projectionviewworldMatrixUniformLocation, 1, GL_FALSE, &(GLfloat)vwMatrix[0][0]);

//glDrawArrays(GL_TRIANGLES, mh->mesh->GetOffset(), mh->mesh->GetPoints().size());
glDrawElements(GL_TRIANGLES, mh->mesh->GetIndicies().size(), GL_UNSIGNED_INT, (void*)mh->mesh->GetOffsetInd());

//GLuint size = mh->mesh->GetIndicies().size();
//GLuint IndSize = mh->mesh->GetOffsetInd();
//glDrawElements(GL_TRIANGLES, size, GL_UNSIGNED_INT, (void*)IndSize);

您需要在索引缓冲区的每个元素上添加 offsetVer。这是一个例子:

网格 A(1 个三角形)

Vertices: v0 v1 v2
Indices: 0 1 2

网格 B(1 个三角形)

Vertices: v3 v4 v5
Indices: 0 1 2

这就是您的组合缓冲区的样子:

Vertices: v0 v1 v2 v3 v4 v5
Indices: 0 1 2 0 1 2

应该是这样的:

Vertices: v0 v1 v2 v3 v4 v5
Indices: 0 1 2 3 4 5