代码如下:
#define GLUT_DISABLE_ATEXIT_HACK
#include "gl/glut.h"
#pragma comment(lib, "glut32.lib")
typedef struct EyePoint
{
GLfloat x;
GLfloat y;
GLfloat z;
} EYEPOINT;
EYEPOINT Eye;
GLint WinWidth;
GLint WinHeight;
void OnDisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_MODELVIEW);
glColor3f(1.0f, 0.0f, 0.0f);
glutSolidCube(50.0f);
glutSwapBuffers();
}
void OnReShape(int w, int h)
{
GLfloat aspect = (GLfloat)w / (GLfloat)h;
GLfloat nRange = 100.0f;
glViewport(0, 0, w, h);
WinWidth = w;
WinHeight = h;
glMatrixMode(GL_PROJECTION); //将当前矩阵指定为投影模式
glLoadIdentity();
//设置三维投影区
if (w <= h)
{
glOrtho(-nRange, nRange, -nRange * aspect, nRange * aspect, -nRange, nRange);
}
else
{
glOrtho(-nRange, nRange, -nRange / aspect, nRange / aspect, -nRange, nRange);
}
gluLookAt(Eye.x, Eye.y, Eye.z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
}
void OnKeyboard(int key, int x, int y)
{
switch(key)
{
case GLUT_KEY_LEFT:
Eye.x -= 2.0f;
break;
case GLUT_KEY_RIGHT:
Eye.x += 2.0f;
break;
case GLUT_KEY_DOWN:
Eye.y -= 2.0f;
break;
case GLUT_KEY_UP:
Eye.y += 2.0f;
break;
case GLUT_KEY_PAGE_DOWN:
Eye.z -= 2.0f;
break;
case GLUT_KEY_PAGE_UP:
Eye.z += 2.0f;
}
OnReShape(WinWidth, WinHeight);
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);
glutSpecialFunc(OnKeyboard); //设置处理特殊击键的回调函数
Eye.x = 0.0f; //初始化眼睛的坐标
Eye.y = 0.0f;
Eye.z = 10.0f;
SetupLights();
glutMainLoop();
}
运行如下: