Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drawing several triangles with different colours with one glDrawArrays command

I'm trying to write something in OpenGL, and I'm a beginner so sorry for any mistakes I make.

in general I just wanted to draw two triangles with different colours and I did using the following code:

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;
}

now.. if I . want to draw both triangles in the same command I can do

    glDrawArrays(GL_TRIANGLES, 0, 6);

but then it draws the two triangles in the same colour.

is there a way to draw each triangle in a different colour by still using only one glDrawArrays() command?

if not.. is there some other command I should go for ?

thank you

like image 626
ufk Avatar asked Sep 13 '25 17:09

ufk


1 Answers

In the description of glDrawArrays it is written :

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.

Is that your solution ?

like image 177
bruno Avatar answered Sep 16 '25 19:09

bruno