相同网格的多个图像,没有重复的三角形传输

Multiple images of same mesh without duplicate triangle transfers

我使用 OpenGL、GLEW 和 GLFW 为同一网格拍摄多张图像。网格(三角形)在每次拍摄中都不会改变,只有 ModelViewMatrix 会改变。

这是我的主循环的重要代码:

for (int i = 0; i < number_of_images; i++) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    /* set GL_MODELVIEW matrix depending on i */
    glBegin(GL_TRIANGLES);
    for (Triangle &t : mesh) {
        for (Point &p : t) {
            glVertex3f(p.x, p.y, p.z);
        }
    }
    glReadPixels(/*...*/) // get picture and store it somewhere
    glfwSwapBuffers();
}

如您所见,我 set/transfer 我想拍摄的每个镜头的三角形顶点。有没有只需要传输一次的解决方案?我的网格很大,所以这个传输需要一些时间。

2016年你不能使用glBegin/glEnd。决不。使用 Vertex Array Obejcts instead; and use custom vertex and/or geometry 着色器重新定位和修改顶点数据。使用这些技术,您只需将数据上传到 GPU 一次,然后您就可以通过各种变换绘制相同的网格。

以下是您的代码的概要:

// 1. Initialization.
// Object handles:
GLuint vao;
GLuint verticesVbo;
// Generate and bind vertex array object.
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
// Generate a buffer object.
glGenBuffers(1, &verticesVbo);
// Enable vertex attribute number 0, which
// corresponds to vertex coordinates in older OpenGL versions.
const GLuint ATTRIBINDEX_VERTEX = 0;
glEnableVertexAttribArray(ATTRIBINDEX_VERTEX);
// Bind buffer object.
glBindBuffer(GL_ARRAY_BUFFER, verticesVbo);
// Mesh geometry. In your actual code you probably will generate
// or load these data instead of hard-coding.
// This is an example of a single triangle.
GLfloat vertices[] = {
    0.0f, 0.0f, -9.0f,
    0.0f, 0.1f, -9.0f,
    1.0f, 1.0f, -9.0f
};
// Determine vertex data format.
glVertexAttribPointer(ATTRIBINDEX_VERTEX, 3, GL_FLOAT, GL_FALSE, 0, 0);
// Pass actual data to the GPU.
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*3*3, vertices, GL_STATIC_DRAW);
// Initialization complete - unbinding objects.
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

// 2. Draw calls.
while(/* draw calls are needed */) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glBindVertexArray(vao);
    // Set transformation matrix and/or other
    // transformation parameters here using glUniform* calls.
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glBindVertexArray(0); // Unbinding just as an example in case if some other code will bind something else later.
}

顶点着色器可能如下所示:

layout(location=0) in vec3 vertex_pos;
uniform mat4 viewProjectionMatrix; // Assuming you set this before glDrawArrays.

void main(void) {
    gl_Position = viewProjectionMatrix * vec4(vertex_pos, 1.0f);
}

另请参阅 this page 一本优秀的现代加速图形书籍。

@BDL 已经评论说您应该放弃立即模式绘图调用 (glBegin … glEnd) 并切换到从顶点缓冲区对象 (VBO) 获取数据的顶点数组绘图(glDrawElements、glDrawArrays)。 @Sergey 在他的回答中提到了 Vertex Array Objects,但这些实际上是 VBO 的状态容器。

您必须了解的一件非常重要的事情 – 以及您提出问题的方式显然是您还没有意识到的事情 – OpenGL 不处理 "meshes", "scenes" 之类的。 OpenGL 只是一个绘图 API。它绘制点……线……和三角形……一次一个……它们之间没有任何联系。而已。因此,当您显示 "same" 事物的多个视图时,您 必须 绘制 几次。没有办法解决这个问题。

最新版本的 OpenGL 支持多视口渲染,但它仍然需要几何着色器将几何乘以几块来绘制。