Search code examples
c++openglglutgluopengl-compat

How to draw different colored line strips with Legacy OpenGL?


So, I have a matrix of pairs of x and y coordinates, each line in the matrix represents a route, which I would like to represent as a GL_LINE_STRIP in OpenGL. The thing is I would like to draw the lines with different colors each time. I thought my code would work, but somehow OpenGL keeps drawing the line_strips with the same color.

I thought this would do the work, xy is the matrix of pairs of coordinates:

static void Redraw(void)
{
    ...
    glClear(GL_COLOR_BUFFER_BIT);
   //drawing routes
    srand(time(NULL));
    for(int i = 0; i < xy.size(); i++)
    {   
        vector<pair<int, int>> route = xy[i];
        double r = ((double) rand() / (RAND_MAX));
        double g = ((double) rand() / (RAND_MAX));
        double b = ((double) rand() / (RAND_MAX));
        glColor3f(r,g,b);
        glLineWidth(2);
        glBegin(GL_LINE_STRIP);

        for(int j = 0; j < route.size();j++)
            glVertex2d(route[j].first, route[j].second);

        glEnd();
    }
    glFlush();
}

and my main:

int main(int argc,char *argv[])
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(1080,720);
    glutInitWindowPosition(0,0);
    glutCreateWindow("h_constante");
    gluOrtho2D(0,1000,0,1000);
    glutDisplayFunc(Redraw);
    glutMainLoop();


    return 0;
}

Solution

  • I was pushing all my nodes inside the first line in the matrix so I was actually drawing one big GL_LINE_STRIP. Thanks a lot for all the help!