13.003 Computational Geometry and Visualization

GLUT Library example


Here is the complete code for the example program:

#include <math.h>                    /* standard math library */
#include <GL/gl.h>                   /* OpenGL library */
#include <GL/glu.h>                  /* OpenGL utility library */
#include "/mit/13.003/include/glut.h"                    /* GLUT library */

/**************************************************************
 * function prototypes
 *************************************************************/
void displayCB(void);                /* window display callback */
void reshapeCB(int, int);            /* window reshape callback */

/**************************************************************
 *  Main program - Open window with initial window size, title
 *  bar, RGBA display mode, and handle input events.
 *************************************************************/
void main(int argc, char **argv)
{
  glutInit(&argc, argv);             /* Initialize GLUT */
  glutInitDisplayMode(GLUT_RGB);     /* Set the initial display mode */

  glutCreateWindow("OpenGL Example 1 - Square");   /* Create window */

  glutReshapeFunc(reshapeCB);        /* Register reshape callback for window */
  glutDisplayFunc(displayCB);        /* Register display callback for window */

  glutMainLoop();                    /* Enter the event loop */
}

/***************************************************************
 *  This callback function is automatically called whenever
 *  the window changes shape.
 **************************************************************/
void reshapeCB(int width, int height)
{
  glViewport(0, 0, width, height);    /* set the viewport to fill window */
}

/***************************************************************
 *  This callback function is automatically called whenever
 *  the window needs to be redrawn.
 **************************************************************/
void displayCB(void)
{
  glClearColor(0.0, 0.0, 0.0, 0.0);   /* set the clear color to black */
  glClear(GL_COLOR_BUFFER_BIT);       /* erase the window to black */

  gluOrtho2D(-1.0, 1.0, -1.0, 1.0);   /* 2D orthographic projection */

  glColor3f(1.0, 1.0, 1.0);           /* set color to white */

  glBegin(GL_POLYGON);                /* start a polygon */
  glVertex2f(-0.5, -0.5);             /* vertices of polygon ... */
  glVertex2f(-0.5,  0.5);
  glVertex2f( 0.5,  0.5);
  glVertex2f( 0.5, -0.5);
  glEnd();                            /* end of polygon */

  glFlush();                          /* actually draw on screen */
}


On to "Making the Example Programs"
Back to "Introduction to graphics with OpenGL"
Back to "Lectures on OpenGL and Computer Graphics"