定义一个简单形体(OpenGL提供的基础形体,如立方体、球体等),并生成正交投影及透视投影视图
时间: 2023-08-18 12:09:55 浏览: 188
以下是使用OpenGL生成一个立方体并生成正交投影和透视投影视图的示例代码:
```C++
#include <GL/glut.h>
void display()
{
// 清除屏幕
glClear(GL_COLOR_BUFFER_BIT);
// 设置正交投影视图
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1, 1, -1, 1, -1, 1);
// 绘制立方体
glBegin(GL_QUADS);
// 上面
glColor3f(1, 0, 0);
glVertex3f(-0.5f, 0.5f, -0.5f);
glVertex3f(-0.5f, 0.5f, 0.5f);
glVertex3f(0.5f, 0.5f, 0.5f);
glVertex3f(0.5f, 0.5f, -0.5f);
// 下面
glColor3f(0, 1, 0);
glVertex3f(-0.5f, -0.5f, -0.5f);
glVertex3f(0.5f, -0.5f, -0.5f);
glVertex3f(0.5f, -0.5f, 0.5f);
glVertex3f(-0.5f, -0.5f, 0.5f);
// 前面
glColor3f(0, 0, 1);
glVertex3f(-0.5f, -0.5f, 0.5f);
glVertex3f(0.5f, -0.5f, 0.5f);
glVertex3f(0.5f, 0.5f, 0.5f);
glVertex3f(-0.5f, 0.5f, 0.5f);
// 后面
glColor3f(1, 1, 0);
glVertex3f(-0.5f, -0.5f, -0.5f);
glVertex3f(-0.5f, 0.5f, -0.5f);
glVertex3f(0.5f, 0.5f, -0.5f);
glVertex3f(0.5f, -0.5f, -0.5f);
// 左面
glColor3f(0, 1, 1);
glVertex3f(-0.5f, -0.5f, -0.5f);
glVertex3f(-0.5f, -0.5f, 0.5f);
glVertex3f(-0.5f, 0.5f, 0.5f);
glVertex3f(-0.5f, 0.5f, -0.5f);
// 右面
glColor3f(1, 0, 1);
glVertex3f(0.5f, -0.5f, -0.5f);
glVertex3f(0.5f, 0.5f, -0.5f);
glVertex3f(0.5f, 0.5f, 0.5f);
glVertex3f(0.5f, -0.5f, 0.5f);
glEnd();
// 设置透视投影视图
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0f, 1.0f, 1.0f, 100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0.0f, 0.0f, 5.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
// 绘制立方体
glBegin(GL_QUADS);
// 上面
glColor3f(1, 0, 0);
glVertex3f(-0.5f, 0.5f, -0.5f);
glVertex3f(-0.5f, 0.5f, 0.5f);
glVertex3f(0.5f, 0.5f, 0.5f);
glVertex3f(0.5f, 0.5f, -0.5f);
// 下面
glColor3f(0, 1, 0);
glVertex3f(-0.5f, -0.5f, -0.5f);
glVertex3f(0.5f, -0.5f, -0.5f);
glVertex3f(0.5f, -0.5f, 0.5f);
glVertex3f(-0.5f, -0.5f, 0.5f);
// 前面
glColor3f(0, 0, 1);
glVertex3f(-0.5f, -0.5f, 0.5f);
glVertex3f(0.5f, -0.5f, 0.5f);
glVertex3f(0.5f, 0.5f, 0.5f);
glVertex3f(-0.5f, 0.5f, 0.5f);
// 后面
glColor3f(1, 1, 0);
glVertex3f(-0.5f, -0.5f, -0.5f);
glVertex3f(-0.5f, 0.5f, -0.5f);
glVertex3f(0.5f, 0.5f, -0.5f);
glVertex3f(0.5f, -0.5f, -0.5f);
// 左面
glColor3f(0, 1, 1);
glVertex3f(-0.5f, -0.5f, -0.5f);
glVertex3f(-0.5f, -0.5f, 0.5f);
glVertex3f(-0.5f, 0.5f, 0.5f);
glVertex3f(-0.5f, 0.5f, -0.5f);
// 右面
glColor3f(1, 0, 1);
glVertex3f(0.5f, -0.5f, -0.5f);
glVertex3f(0.5f, 0.5f, -0.5f);
glVertex3f(0.5f, 0.5f, 0.5f);
glVertex3f(0.5f, -0.5f, 0.5f);
glEnd();
// 刷新屏幕
glutSwapBuffers();
}
int main(int argc, char** argv)
{
// 初始化GLUT
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowSize(800, 800);
glutCreateWindow("OpenGL");
// 设置显示回调函数
glutDisplayFunc(display);
// 进入主循环
glutMainLoop();
return 0;
}
```
在该示例中,我们首先使用正交投影视图绘制了一个立方体,然后使用透视投影视图再次绘制了相同的立方体。在透视投影视图中,我们使用了`gluPerspective()`函数来设置透视投影矩阵,并使用`gluLookAt()`函数设置相机位置和方向。
阅读全文