/* simple4.c draw an n-gon with n vertices, moving left/right when press l/r keys the movement is implemented by keeping track of the center fof the polygon as a global variable, and moving it L/R note: another option would be to always draw the polygon centered at the origin, and use translation to move it L/R number of vertices can be increased/decreased, also the radius OpenGL 1.x Laura Toma */ #include #include #include #include #ifdef __APPLE__ #include #else #include #endif GLfloat red[3] = {1.0, 0.0, 0.0}; GLfloat green[3] = {0.0, 1.0, 0.0}; GLfloat blue[3] = {0.0, 0.0, 1.0}; GLfloat black[3] = {0.0, 0.0, 0.0}; GLfloat white[3] = {1.0, 1.0, 1.0}; GLfloat gray[3] = {0.5, 0.5, 0.5}; GLfloat yellow[3] = {1.0, 1.0, 0.0}; GLfloat magenta[3] = {1.0, 0.0, 1.0}; GLfloat cyan[3] = {0.0, 1.0, 1.0}; GLint fillmode = 0; float r = .5; //default radius int n = 6; //default nb of vertices /* we keep track globally of the coordinates of the center of the rectangle; they will be updated by the keys that implement move left and right */ GLfloat x_center = 0.0, y_center = 0.0; /* forward declarations of functions */ void display(void); void keypress(unsigned char key, int x, int y); int main(int argc, char** argv) { /* open a window */ glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(500, 500); glutInitWindowPosition(100,100); glutCreateWindow(argv[0]); /* OpenGL init */ glClearColor(0, 0, 0, 0); /* set background color black*/ glEnable(GL_DEPTH_TEST); //not necessary in 2D /* callback functions */ glutDisplayFunc(display); glutKeyboardFunc(keypress); /* event handler */ glutMainLoop(); return 0; } //draw an n-gon centered at (x_center, y_center) void draw_ngon() { int i; float a = 2*M_PI/n; if (fillmode) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } else { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } /* draw a polygon centered at x_center, y_center */ glBegin(GL_POLYGON); for (i=0; i<= n; i++) { glVertex2f(x_center + r*cos(a*i), y_center + r*sin(a*i)); } glEnd(); } void display(void) { glClear(GL_COLOR_BUFFER_BIT); draw_ngon(); glFlush(); } void keypress(unsigned char key, int x, int y) { switch(key) { case 'q': exit(0); break; case '+': r *= 1.1; glutPostRedisplay(); break; case '-': r *= .9; glutPostRedisplay(); break; case '<': n--; glutPostRedisplay(); break; case '>': n++; glutPostRedisplay(); break; case 'l': x_center -= 0.2; glutPostRedisplay(); break; case 'r': x_center += 0.2; glutPostRedisplay(); break; case 'u': y_center += 0.2; glutPostRedisplay(); break; case 'd': y_center -= 0.2; glutPostRedisplay(); break; case 'f': fillmode = !fillmode; glutPostRedisplay(); break; } }