OpenGL: 正交投影

代码如下:

#define GLUT_DISABLE_ATEXIT_HACK

#include "gl/glut.h"
#pragma comment(lib, "glut32.lib")

GLboolean Large = GL_FALSE; //坐标单位变大或变小
GLint Width;				//视区宽度
GLint Height;				//视区高度

//显示 回调函数
void OnDisplay(void)
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glEnable(GL_DEPTH_TEST); //启用深度检测

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glRotatef(30.0f, 1.0f, 0.0f, 0.0f);
	glRotatef(15.0f, 0.0f, 1.0f, 0.0f);

	glColor3f(0.7f, 0.5f, 0.3f);
	glutSolidTeapot(50.0f);

	glutSwapBuffers();
}
//窗口尺寸变化后的回调函数
void OnReShape(int w,int h)
{
	glViewport(0, 0, w, h);
	Width  = w;
	Height = h;
	glMatrixMode(GL_PROJECTION); //将当前矩阵指定为投影模式
	glLoadIdentity();

	if (0 != h)
	{
		GLfloat aspect =(float)w / (float)h;

		//设置三维投影区
		if(!Large)
		{
			if (w <= h) //较小的坐标单位
			{
				glOrtho(-100.0f, 100.0f, -100.0f / aspect, 100.0f / aspect, -100.0f, 100.0f);
			} 
			else
			{
				glOrtho(-100.0f * aspect, 100.0f * aspect, -100.0f, 100.0f, -100.0f, 100.0f);
			}
		}
		else
		{
			if (w <= h) //较大的坐标单位
			{
				glOrtho(-60.0f, 60.0f, -60.0f / aspect, 60.0f / aspect, -60.0f, 60.0f);
			} 
			else
			{
				glOrtho(-60.0f * aspect, 60.0f * aspect, -60.0f, 60.0f, -60.0f, 60.0f);
			}
		}
	}
}

void OnMouse(GLint button,GLint state,GLint x, GLint y)
{
	if(button == GLUT_LEFT_BUTTON && state == GLUT_UP) //鼠标左键释放
	{
		Large= !Large; //逻辑变量取反
	}
	OnReShape(Width, Height);
	glutPostRedisplay();
}

void SetupLights()
{
	GLfloat ambientLight[]  ={0.2f,  0.2f,  0.2f,  1.0f};//环境光
	GLfloat diffuseLight[]  ={0.9f,  0.9f,  0.9f,  1.0f};//漫反射
	GLfloat specularLight[] ={1.0f,  1.0f,  1.0f,  1.0f};//镜面光
	GLfloat lightPos[]      ={50.0f, 80.0f, 60.0f, 1.0f};//光源位置

	glEnable(GL_LIGHTING);			//启用光照
	glLightfv(GL_LIGHT0, GL_AMBIENT,  ambientLight);	//设置环境光源
	glLightfv(GL_LIGHT0, GL_DIFFUSE,  diffuseLight);	//设置漫反射光源
	glLightfv(GL_LIGHT0, GL_SPECULAR, specularLight);	//设置镜面光源
	glLightfv(GL_LIGHT0, GL_POSITION, lightPos);		//设置灯光位置
	glEnable(GL_LIGHT0);			//打开第一个灯光

	glEnable(GL_COLOR_MATERIAL);	//启用材质的颜色跟踪
	glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);	//指定材料着色的面
	glMaterialfv(GL_FRONT, GL_SPECULAR, specularLight); //指定材料对镜面光的反应
	glMateriali(GL_FRONT, GL_SHININESS, 100);			//指定反射系数
}
void main(int argc,char* argv[])
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutInitWindowSize(600, 480);
	glutCreateWindow("OpenGL正交投影");

	glutReshapeFunc(OnReShape);
	glutDisplayFunc(OnDisplay);
	glutMouseFunc(OnMouse);

	SetupLights();

	glutMainLoop();
}

运行效果如下:

OpenGL: 正交投影_第1张图片OpenGL: 正交投影_第2张图片

你可能感兴趣的:(OpenGL)