//水平有限,拿出一段初学OPENGL的代码与大家分享(光照下一个旋转的立方体)。大家有什么好的资料也可以发出来。
//开发库文件太大不好发出来,有机会我再传上来
//在工程-》设置-》LINK中加入 opengl32.lib glu32.lib
#define win32_lean_and_mean//使用简便的WINDOW调用函数
#include <windows.h>
#include <gl/gl.h> //以下是三个GL的头文件
#include <gl/glu.h>
#include <gl/glaux.h>
float angle=0.0f;
HDC g_HDC;//用与WINDOWS窗口交换的设备上下文句柄
//GL中最多有8个光,每个光可以有四种光模拟现实光
float ambientLight[] = { 0.3f, 0.5f, 0.8f, 1.0f }; // 环境光
float diffuseLight[] = { 0.25f, 0.25f, 0.25f, 1.0f }; // 散射光
float lightPosition[] = { 0.0f, 0.0f, 0.0f, 1.0f }; // 光源位置
////// 材质属性有点类似光源
float matAmbient[] = { 1.0f, 1.0f, 1.0f, 1.0f };
float matDiff[] = { 1.0f, 1.0f, 1.0f, 1.0f};
// 初始化OPENGL
void Initialize()
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // 清理背景为黑色
glShadeModel(GL_SMOOTH); // 平滑处理
glEnable(GL_DEPTH_TEST); // 启用深度检测
glEnable(GL_LIGHTING); // 启用光
glEnable(GL_NORMALIZE);
// 设置材质属性
glMaterialfv(GL_FRONT, GL_AMBIENT, matAmbient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, matDiff);
// 设置0号光源
glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
//启用0号光源
glEnable(GL_LIGHT0);
}
void DrawCube(float xPos, float yPos, float zPos)//绘制一个立方体
{
glPushMatrix();
glTranslatef(xPos, yPos, zPos);
glMatrixMode(GL_MODELVIEW);
glRotatef(angle,1.0f,0.0f,0.0f);
glRotatef(angle,0.0f,1.0f,0.0f);
glRotatef(angle,0.0f,0.0f,1.0f);
glBegin(GL_POLYGON);
glNormal3f(0.0f, 1.0f, 0.0f); // 顶面法向量
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();
glBegin(GL_POLYGON);
glNormal3f(0.0f, 0.0f, 1.0f); // 正面法向量
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();
glBegin(GL_POLYGON);
glNormal3f(1.0f, 0.0f, 0.0f); // 右面法向量
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();
glBegin(GL_POLYGON);
glNormal3f(-1.0f, 0.0f, 0.0f); // 左面法向量
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();
glBegin(GL_POLYGON);
glNormal3f(0.0f, -1.0f, 0.0f); // 底面法向量
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();
glBegin(GL_POLYGON);
glNormal3f(0.0f, 0.0f, -1.0f); // 背面法向量
glVertex3