使用一个 glDrawArrays 命令绘制多个不同颜色的三角形

drawing several triangles with different colours with one glDrawArrays command

我正在尝试用 OpenGL 编写一些东西,我是初学者,对于我犯的任何错误,我深表歉意。

一般来说,我只是想画两个不同颜色的三角形,我使用了下面的代码:

float vertices[] = {
        -0.5f, -0.6f, 0.0f,
        0.5f, -0.6f, 0.0f,
        0.4f,  0.5f, 0.0f,
        0.5f, 0.6f, 0.0f,
        -0.5f, 0.6f, 0.0f,
        -0.4f,  -0.5f, 0.0f

};

void display() {
    std::cout << "frame";
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
    glClear(GL_COLOR_BUFFER_BIT);         // Clear the color buffer
    // activate and specify pointer to vertex array
    glEnableClientState(GL_VERTEX_ARRAY);
    glVertexPointer(3, GL_FLOAT, 0, vertices);

// draw a cube
    glColor3f(1.0f, 0.0f, 0.0f); // Red

    glDrawArrays(GL_TRIANGLES, 0, 3);
    //glColor3f(0.0f, 1.0f, 0.0f); // Green
    glDrawArrays(GL_TRIANGLES, 3, 3);

    glDisableClientState(GL_VERTEX_ARRAY);
    glFlush();  // Render now
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);                 // Initialize GLUT
    glutCreateWindow("OpenGL Setup Test"); // Create a window with the given title
    glutInitWindowSize(320, 320);   // Set the window's initial width & height
    glutInitWindowPosition(50, 50); // Position the window's initial top-left corner
    glutDisplayFunc(display); // Register display callback handler for window re-paint
    glutMainLoop();           // Enter the infinitely event-processing loop
    return 0;
}

现在.. 如果我 .想在同一个命令中绘制两个三角形我可以做

    glDrawArrays(GL_TRIANGLES, 0, 6);

但随后它以相同的颜色绘制了两个三角形。

有没有办法只使用一个 glDrawArrays() 命令来用不同颜色绘制每个三角形?

如果不是..还有其他我应该去的命令吗?

谢谢

description of glDrawArrays中写着:

Instead of calling a GL procedure to pass each individual vertex attribute, you can use glVertexAttribPointer to prespecify separate arrays of vertices, normals, and colors and use them to construct a sequence of primitives with a single call to glDrawArrays.

这是你的解决方案吗?

"if not.. is there some other command I should go for ?" 自 decades.See Fixed Function Pipeline and Legacy OpenGL 以来,固定函数属性和客户端功能已弃用。 阅读 Vertex Specification and Shader 了解最先进的渲染方式。


无论如何,您可以通过 glColorPointer 定义颜色属性数组,因此每个顶点坐标都与一个单独的颜色属性相关联:

float colors[] = {
     1.0f, 0.0f, 0.0f, // red
     1.0f, 0.0f, 0.0f,
     1.0f, 0.0f, 0.0f,
     0.0f, 1.0f, 0.0f, // green
     0.0f, 1.0f, 0.0f,
     0.0f, 1.0f, 0.0f
};

glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, vertices);

glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(3, GL_FLOAT, 0, colors);

glDrawArrays(GL_TRIANGLES, 0, 6);