代码如下:
#define GLUT_DISABLE_ATEXIT_HACK
#include "gl/glut.h"
#pragma comment(lib, "glut32.lib")
void OnDisplay(void)
{
GLfloat mat[]=
{
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, -1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
};
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(1.0f, 0.0f, 1.0f);
glBegin(GL_QUADS);
{
glVertex3i(0, -30, -30);
glVertex3i(0, 30, -30);
glVertex3i(0, 30, 30);
glVertex3i(0, -30, 30);
}
glEnd();
glPushMatrix();
{
glTranslatef(30.0f, 0.0f, 0.0f);
glColor3f(1.0f, 1.0f, 0.0f);
glutSolidCube(50.0f);
}
glPopMatrix();
glPushMatrix();
{
glMultMatrixf(mat);
glTranslatef(-30.0f, 0.0f, 0.0f);
glColor3f(1.0f, 0.0f, 0.0f);
glutSolidCube(50.0f);
}
glPopMatrix();
glutSwapBuffers();
}
void OnReShape(int w,int h)
{
GLfloat aspect =(GLfloat)w / (GLfloat)h;
GLfloat nRange = 100.0f;
glViewport(0, 0, w, 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);
}
}
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);
SetupLights();
glutMainLoop();
}
运行效果如下: