OpenGL程式設計 基礎篇(四)與滑鼠的互動
阿新 • • 發佈:2018-12-30
#include "stdafx.h" #include <cstdlib> #include <gl\glut.h> const int screenWidth = 600; const int screenHeight = 480; class GLintPoint { public: GLint x; GLint y; GLintPoint(){ x = 0; y = 0; } GLintPoint(GLint a, GLint b){ x = a; y = b; } }; voidmyInit(){ glClearColor(1.0, 1.0, 1.0, 0.0); glColor3f(0.0f, 0.0f, 0.0f); glPointSize(2.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, (GLdouble)screenWidth, 0.0, (GLdouble)screenHeight); } void drawDot(GLint x, GLint y){ glBegin(GL_POINTS); glVertex2i(x, y); glEnd(); }void myDisplay(GLintPoint corner[3]){ //繪製Sierrapinski墊片的函式,引數為三個座標點 glClear(GL_COLOR_BUFFER_BIT); int index = rand() % 3; GLintPoint point = corner[index]; drawDot(point.x, point.y); for (int i = 0; i < 55000; i++){ index = rand() % 3; point.x = (point.x + corner[index].x) / 2; point.y = (point.y + corner[index].y) / 2; //printf("%d %d\n", point.x, point.y); drawDot(point.x, point.y); } glFlush(); } //Simple One 用滑鼠放置點,使用者每次按下左鍵時,就會在螢幕視窗滑鼠所在位置繪製出一個點;如果使用者按下右鍵,就改變視窗背景顏色 void myMouse(int button, int state, int x, int y){ if (state == GLUT_DOWN){ if (button == GLUT_LEFT_BUTTON){ drawDot(x, screenHeight - y); glFlush(); } else if (button == GLUT_RIGHT_BUTTON){ glClearColor(1.0f,0.0f,0.0f,0.0f); glClear(GL_COLOR_BUFFER_BIT); glFlush(); } } return; } //Sierpinski 用滑鼠控制Sierpinski墊片 void myMouseForSierpinski(int button, int state, int x, int y) { static GLintPoint corner[3]; static int numCorners = 0; if (state == GLUT_DOWN){ if (button == GLUT_LEFT_BUTTON){ corner[numCorners].x = x; corner[numCorners].y = screenHeight - y; if (++numCorners == 3){ myDisplay(corner); numCorners = 0; } } } else if (button == GLUT_RIGHT_BUTTON){ glClear(GL_COLOR_BUFFER_BIT); glFlush(); } } void myDis(){} int main(int argc, char **argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE); glutInitWindowPosition(100, 100); glutInitWindowSize(screenWidth, screenHeight); glutCreateWindow("Mouse Sierpinski"); glutMouseFunc(myMouseForSierpinski); //glutMouseFunc(myMouse); glutDisplayFunc(myDis); myInit(); glutMainLoop(); return 0; }