【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 退出程序