透视投影
三维空间物体显示近大远小。
透视投影区域是个棱锥体:
透视投影显示效果:
opengl透视投影函数:
void APIENTRY gluPerspective (GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar);
代码实例:
/*
* 透视投影
*/
#define GLEW_STATIC
#include <stdio.h>
#include <stdlib.h>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <math.h>
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" ) //这行是取消显示控制台
char szTitle[64] = "opengl view";
// Window dimensions
const GLuint WIDTH = 800, HEIGHT = 600;
static void error_callback(int error, const char* description) {
fputs(description, stderr);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}
//顶点数据
struct Vertex {
float x, y, z;
};
// 绘制
static void render(GLFWwindow * window) {
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// 这里坐标数据是三维空间中的
// 屏幕左边为-1 右边为1 上面为1 下面为-1
Vertex arVert[] =
{
{0.5f, 0.1, -0.5},
{0.2f, 0.3, -.5},
{0.8f, 0.3, -.5},
};
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(Vertex), arVert);
glDrawArrays(GL_TRIANGLES, 0, 3);
glfwSwapBuffers(window);
glfwPollEvents();
}
int main(void) {
GLFWwindow * window;
glfwSetErrorCallback(error_callback);
if(!glfwInit()) return -1;
window = glfwCreateWindow(WIDTH, HEIGHT, szTitle, NULL, NULL);
if(!window) {
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, key_callback);
glewExperimental = GL_TRUE;
glewInit();
glViewport(0, 0, WIDTH, HEIGHT); //设置opengl视口 即看到的显示区域
glMatrixMode(GL_PROJECTION); //设置当前操作的是投影矩阵队列
glLoadIdentity(); //将队列最上层的一个投影矩阵清空成单位矩阵
//gluPerspective (GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar);
//fovy 角度 视角
//aspect 宽高比
//zNear 近裁剪面
//zFar 远裁剪面
gluPerspective(60, double(WIDTH) / double(HEIGHT), 0.1, 1000);//产生一个新的投影矩阵并和上面的投影矩阵队列最上面单位矩阵相乘,实际上就是产生一个投影矩阵并放到投影矩阵队列的最上面
while(!glfwWindowShouldClose(window)) {
render(window);
}
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}