OpenGL - 3점을 찍어 삼각형 그리기
설명
마우스로 폼위의 3점을 찍으면 그 점을 꼭지점으로 삼각형을 그린다.
소스설명
설명은 주석으로 대체하였다.
parameter
#define POINTS 100 GLfloat pos[POINTS][2];//point array GLfloat Width = 600.0; //form width GLfloat Height = 600.0; //form height GLint n = 0; //number of points
렌더링함수
/// <summary> /// Renders the scene. /// </summary> void RenderScene(void) { int i; glClear(GL_COLOR_BUFFER_BIT); glColor3f(1, 0, 0);//red color glPointSize(10.0f);//size 10 glEnableClientState(GL_VERTEX_ARRAY);// enable array for (i = 0; i < 3; i++) { glBegin(GL_POINTS);//dot glVertex2f(pos[i][0], pos[i][1]);//dot position } if (i>2 && (pos[2][0] != 0))//draw triangle when the number of points are greater than two { glBegin(GL_TRIANGLES); glVertex2f(pos[0][0], pos[0][1]); glVertex2f(pos[1][0], pos[1][1]); glVertex2f(pos[2][0], pos[2][1]); } glEnd(); glFlush();//flush }
마우스 클릭 이벤트
/// <summary> /// Mouse button event. /// </summary> /// <param name="button">The button.</param> /// <param name="state">The state.</param> /// <param name="x">The x.</param> /// <param name="y">The y.</param> void mousebutton(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON) { if (state == GLUT_DOWN) { pos[n][0] = x / Width; pos[n][1] = (Height - y) / Height; if (n > 2)//when then number of points greater than two { pos[n % 3][0] = pos[n][0];//x pos[n % 3][1] = pos[n][1];//y } n++; RenderScene();//rendering } } }
윈폼 크기 변경 함수
/// <summary> /// winform size changed /// </summary> /// <param name="w">width</param> /// <param name="h">height</param> void ChangeSize(int w, int h) { GLfloat asepectRatio; Width = w; Height = h; if (Height == 0) Height = 1; glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, 1.0, 0.0, 1.0); } void main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(Width, Height); glutInitWindowPosition(0, 0); glutCreateWindow("ex2"); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glMatrixMode(GL_PROJECTION); glutDisplayFunc(RenderScene); glutReshapeFunc(ChangeSize); glutMouseFunc(mousebutton); glutMainLoop(); }
결과물
'SW > OpenGL' 카테고리의 다른 글
OpenGL - 쉐이딩(Shading, line, flat smooth) (0) | 2017.09.13 |
---|---|
OpenGL - 16개의 움직이는 랜덤 티팟 (0) | 2017.09.12 |
OpenGL - 로봇 팔 만들기 (0) | 2017.09.12 |
OpenGL - 정육면체 xyz축 회전 (0) | 2017.09.12 |
OpenGL - 사각형 회전, 색바꾸기 (0) | 2017.09.12 |