Search code examples
c++openglglut

Display window and line segment in OpenGL


The line isn't showing up. What is wrong with the code?

#include<windows.h>
 //#ifdef __APPLE__
 //#include <GLUT/glut.h>
 //#else
#include <GL/glut.h>
//#endif
//#include <stdlib.h>

void init(void){
  glClearColor(1.0, 1.0,1.0,0.0);
  glMatrixMode(GL_PROJECTION);
  gluOrtho2D(0.0, 200.0, 0.0,150.0);
 }

 void lineSegment(void){
   glClear(GL_COLOR_BUFFER_BIT);
   glColor3f(1.0f, 0.0f, 0.0f);     // Red

  //glColor3f(0.2, 0.4, 0.2);
  glBegin(GL_LINE);
  glVertex2i(180,15);
  glVertex2i(10,145);
  glEnd();
  glFlush();
}


int main(int argc, char* argv[]){
   glutInit(&argc,argv);
   glutInitDisplayMode(GLUT_DOUBLE); // Enable double buffered mode
   //glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
   glutInitWindowPosition(50,100);
   glutInitWindowSize(400,300);
   glutCreateWindow("An example OpenGL Program");
   init();
    glutDisplayFunc(lineSegment);
   glutMainLoop();
 return 0;
}

Solution

    • You're requesting a GLUT_DOUBLE-buffered window but are failing to call glutSwapBuffers() at the end of your glutDisplayFunc() callback. glFlush() is not sufficient.
    • GL_LINE is not a valid argument for glBegin(). You're thinking of GL_LINES.

    All together:

    #include <GL/glut.h>
    
    void init()
    {
        glClearColor( 1.0, 1.0, 1.0, 0.0 );
        glMatrixMode( GL_PROJECTION );
        gluOrtho2D( 0.0, 200.0, 0.0, 150.0 );
    }
    
    void lineSegment()
    {
        glClear( GL_COLOR_BUFFER_BIT );
        glColor3f( 1.0f, 0.0f, 0.0f );     // Red
        glBegin( GL_LINES );
        glVertex2i( 180, 15 );
        glVertex2i( 10, 145 );
        glEnd();
        glutSwapBuffers();
    }
    
    int main( int argc, char* argv[] )
    {
        glutInit( &argc, argv );
        glutInitDisplayMode( GLUT_DOUBLE ); // Enable double buffered mode
        glutInitWindowSize( 400, 300 );
        glutCreateWindow( "An example OpenGL Program" );
        init();
        glutDisplayFunc( lineSegment );
        glutMainLoop();
        return 0;
    }