Sunday, June 11, 2006

One OpenGL example

  1. Initialization procedures
  2. Callback Functions
  3. main()
  4. Window and coordinate system creation
  5. State initialization
  6. Callback functions registration
  7. Infinite Event Handling loop

code:

#include
#include
#include
static GLfloat spin = 0.0; // degree of spinning
void myInit(void)
{
glClearColor (1.0, 1.0, 1.0, 0.0); // set black background color
glShadeModel (GL_FLAT);
}
void myDisplay(void)
{ int xc = 0;
int yc = 0;
int rad = 20;
glClear(GL_COLOR_BUFFER_BIT); // clear the screen
// glPushMatrix ();
glRotatef (spin, 0.0, 1.0, 0.0);
glColor3f (1.0, 0.0, 0.0); // set the drawing color
glBegin(GL_LINE_LOOP);
for (int angle=0; angle< 365; angle=angle+5)
{
float angle_radians = angle * (float)3.14159 / (float)180;
float x = xc + rad * (float)cos(angle_radians);
float y = yc + rad * (float)sin(angle_radians);
glVertex2f(x,y);
}
glEnd();
spin += 5.0f; //
glPopMatrix ();
glutSwapBuffers ();
}

void myReshape ( int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION); // set "camera shape"
glLoadIdentity (); // clear the matrix
// viewing transformation
glOrtho (-40.0, 40.0, -40.0, 40.0, -1.0, 1.0);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
}

void myMouse(int button, int state, int x, int y)
{
switch (button) {
case GLUT_LEFT_BUTTON:
if (state == GLUT_DOWN)
glutIdleFunc(myDisplay);
break;
case GLUT_MIDDLE_BUTTON:
if (state == GLUT_DOWN)
glutIdleFunc(NULL);
break;
case GLUT_RIGHT_BUTTON:
if (state == GLUT_DOWN)
exit (-1);
break;
}
}

/*
*Request double buffer display mode.
* Register mouse input callback functions
*/

int main(int argc, char** argv)
{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB); // set display mode
glutInitWindowSize (250, 250); // set screen window size
glutInitWindowPosition (100, 100); // set window position on screen
glutCreateWindow (argv[0]); // open the screen window
myInit ();
glutDisplayFunc(myDisplay); // register redraw function
glutReshapeFunc(myReshape); // register reshape function
glutMouseFunc(myMouse); // register myMouse function
//glutIdleFunc(&myDisplay);
glutMainLoop(); // go into a perpetual loop
return 0;
}


No comments:

Post a Comment