【OpenGL】-007 在視窗上顯示一個三角形
阿新 • • 發佈:2018-11-05
【OpenGL】-007 在視窗上顯示一個三角形
文章目錄
1. 在視窗上顯示一個三角形
/* File: ogl_1.cpp Auther: freehawkzk Data: 2018.10.15 This is a simple opengl program in c++, just create a window and display a color triangle in the window. */ #include <GL/glut.h> void init(void) { glClearColor(0.0,0.0,0.0,0.0); glMatrixMode(GL_PROJECTION); glOrtho(-5,5,-5,5,5,15); glMatrixMode(GL_MODELVIEW); gluLookAt(0,0,10,0,0,0,0,1,0); return ; } /* 1. Clear window background 2. Draw triangle 3. Flush draw command */ void display(void) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0,0,0); glBegin(GL_TRIANGLES); glColor3f(1,0,0);glVertex2f(-5,5); glColor3f(0,1,0);glVertex2f(-5,-5); glColor3f(0,0,1);glVertex2f(5,-5); glEnd(); glFlush(); return ; } /* 1. Init glut 2. Init opengl display mode 3. Setup & create window 4. Init opengl device 5. Setup opengl display function 6. Go into main loop of glut */ int main(int argc, char* argv[]) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE); glutInitWindowPosition(0,0); glutInitWindowSize(500,500); glutCreateWindow("OGLWindow"); init(); glutDisplayFunc(display); glutMainLoop(); return 0; }
2. 效果
最終效果如下如所示。
3. 備註
從main函式的實現流程可以看出,使用GLUT進行視窗管理時,程式的工作流程主要如下:
- 1 初始化GLUT
主要通過呼叫glutInit
函式完成。 - 2 設定顯示模式
- 3 設定並建立視窗
- 4 初始化OpenGL
在這一步中,設定相機視點位置,投影方式等。 - 5 設定顯示回撥函式
顯示回撥函式是GLUT在需要進行顯示繪製的時候會呼叫的函式,該函式中使用者使用OpenGL進行內容繪製。 - 6 進入OpenGL渲染主迴圈
渲染主迴圈會使主執行緒處於迴圈工作過程中,從而確保程式主視窗一直顯示不會退出。 - 7 退出程式