//A very simple opengl/GLUT program #include #include #include #include using namespace std; //global variables - necessary evil when using GLUT //global width and height int GW; int GH; //current mouse position in pixel coordinate int x; int y; //a structure to store 2D points - this could also be a class typedef struct vector2 { float x; float y; //constructor which takes input values vector2(float in_x, float in_y) : x(in_x), y(in_y) {} //default constructor vector2() : x(0), y(0) {} } vector2; //keep track of which drawing mode we are in points or square //mode ==0 means draw square otherwise draw points int mode; //an stl vector to keep track off all the points clicked by the mouse vector all_points; //helper drawing routines void draw_square() { glBegin(GL_POLYGON); glColor3f(1.0, 0.0, 0.0); glVertex2f(-0.5,-0.5); glColor3f(0.0, 1.0, 0.0); glVertex2f(-0.5,0.5); glColor3f(0.0, 0.0, 1.0); glVertex2f(0.5,0.5); glColor3f(0.0, 0.0, 0.0); glVertex2f(0.5,-0.5); glEnd(); } void draw_all_pts() { glPointSize(2.0); glBegin(GL_POINTS); glColor3f(0.5, 0.2, 0.8); //iterate through all the points and draw them for (int i=0; i < all_points.size(); i++) { glVertex2f(all_points[i].x, all_points[i].y); } glEnd(); } //the reshape callback void reshape(int w, int h) { GW = w; GH = h; glViewport(0, 0, w, h); glLoadIdentity(); gluOrtho2D( -(float)w/h, (float)w/h, -1, 1); } //the display call back - all drawing should be done in this function void display() { glClear(GL_COLOR_BUFFER_BIT); if (mode == 0) draw_square(); else draw_all_pts(); glFlush(); } //conversion from pixel to world - unsimplified float p2w_x(int p_x) { } float p2w_y(int p_y) { } //the mouse button callback void mouse(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON) { if (state == GLUT_DOWN) { /* if the left button is clicked */ printf("mouse clicked at %d %d\n", x, y); all_points.push_back(vector2(p2w_x(x), p2w_y(GH-1-y))); glutPostRedisplay(); } } } //the mouse move callback void mouseMove(int x, int y) { printf("mouse moved at %d %d\n", x, y); } //the keyboard callback void keyboard(unsigned char key, int x, int y ){ switch( key ) { case 'm': mode = !mode; glutPostRedisplay(); break; case 'q': case 'Q' : exit( EXIT_SUCCESS ); break; case 'h' : case 'H' : printf("hello!\n"); break; } } int main( int argc, char** argv ){ glutInit( &argc, argv ); //intializations glutInitWindowSize(200, 200); glutInitWindowPosition(100, 100); glutCreateWindow( "My Second Window" ); glClearColor(1.0, 1.0, 1.0, 1.0); //global variable intialization GW = GH = 200; mode = 0; //register the callback functions glutDisplayFunc( display ); glutMouseFunc( mouse ); glutMotionFunc( mouseMove ); glutKeyboardFunc( keyboard ); glutReshapeFunc( reshape ); glutMainLoop(); }