OpenGL 蓝书学习(第四版)第十一章
OpenGL 蓝书学习(第四版)第十一章
每次写球体世界都需要很长时间。
球体世界
#if defined(__APPLE__) && defined(__MACH__)
#include <GLUT/glut.h>
#include <OpenGL/gl.h>
#include <OpenGL/glext.h>
#include <OpenGL/gltypes.h>
#else
extern "C" {
#include <GL/freeglut.h>
}
#endif
#include <iostream>
#include <string_view>
#include <array>
#include <fstream>
#include <vector>
#include <string>
#include <numbers>
#include <array>
#include <random>
// 常量
static constexpr GLfloat PI = std::numbers::pi_v<GLfloat>;
static constexpr std::string_view WINDOW_TITLE = "OpenGL Window";
static constexpr GLint WINDOW_WIDTH = 800;
static constexpr GLint WINDOW_HEIGHT = 600;
static constexpr GLuint NUM_SPHERES = 30;
static constexpr GLuint NUM_TEXTURES = 3;
static constexpr GLuint GROUND_TEXTURE = 0;
static constexpr GLuint TORUS_TEXTURE = 1;
static constexpr GLuint SPHERE_TEXTURE = 2;
static constexpr std::array<std::string, NUM_TEXTURES> TEXTURE_FILES = {
"../image/grass.tga",
"../image/wood.tga",
"../image/orb.tga",
};
static constexpr GLfloat lightPos[] = { -100.0f, 100.0f, 50.0f, 1.0f }; // Point source
static constexpr GLfloat fNoLight[] = { 0.0f, 0.0f, 0.0f, 0.0f };
static constexpr GLfloat flowLight[] = { 0.25f, 0.25f, 0.25f, 1.0f }; // 浅灰色
static constexpr GLfloat fBrightLight[] = { 1.0f, 1.0f, 1.0f, 1.0f }; // 白色
/**
OpenGL 变换矩阵 16个元素,列主序存储
x y z w
x 0, 4, 8, 12
y 1, 5, 9, 13
z 2, 6, 10, 14
w 3, 7, 11, 15
单位矩阵
1, 0, 0, 0
0, 1, 0, 0
0, 0, 1, 0
0, 0, 0, 1
*/
struct GLFrame {
GLfloat vLocation[3]; // 位置 -> move x, y, z
GLfloat vUp[3]; // 上方向 -> y
GLfloat vForward[3]; // 前方向 -> z(负方向) x-> 通过 yz叉积计算 -> 归一化为单位向量
};
// Targa 图像文件头结构体
#pragma pack(push, 1) // 关闭结构体对齐填充
struct TargaHeader {
// 图像 ID 区长度,0 = 无
GLubyte idLength;
GLubyte colorMapType; // 0 = 无调色板
GLubyte dataTypeCode; // 图像数据类型代码 2 = 未压缩真彩图(非 RLE)
GLushort colorMapOrigin; // 调色板起始索引
GLushort colorMapLength; // 调色板颜色的数量
GLubyte colorMapDepth; // 调色板每条颜色的位数
GLushort xOrigin; // 图像在屏幕上的 X 坐标
GLushort yOrigin; // 图像在屏幕上的 Y 坐标
GLushort width; // 图像宽度
GLushort height; // 图像高度
// 每像素 24 位 = RGB 各 8 位
GLubyte bitsPerPixel;
// 0 表示自下而上存储
GLubyte imageDescriptor;
};
#pragma pack(pop) // 恢复结构体对齐填充
std::ostream& operator<<(std::ostream& os, const TargaHeader& header) {
os << "TargaHeader { "
<< "idLength=" << static_cast<int>(header.idLength) << ", "
<< "colorMapType=" << static_cast<int>(header.colorMapType) << ", "
<< "dataTypeCode=" << static_cast<int>(header.dataTypeCode) << ", "
<< "colorMapOrigin=" << header.colorMapOrigin << ", "
<< "colorMapLength=" << header.colorMapLength << ", "
<< "colorMapDepth=" << static_cast<int>(header.colorMapDepth) << ", "
<< "xOrigin=" << header.xOrigin << ", "
<< "yOrigin=" << header.yOrigin << ", "
<< "width=" << header.width << ", "
<< "height=" << header.height << ", "
<< "bitsPerPixel=" << static_cast<int>(header.bitsPerPixel) << ", "
<< "imageDescriptor=" << static_cast<int>(header.imageDescriptor)
<< " }";
return os;
}
// 变量
static GLint mainWindowId = 0;
static GLbyte iRenderMode = 0;
static GLFrame camera; // 相机位置和方向
static GLFrame spheres[NUM_SPHERES];
static GLfloat shadowMatrix[16];
static GLuint textures[NUM_TEXTURES];
static GLuint groundList, sphereList, torusList;
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;
static GLfloat zRot = 0.0f;
void makeShadowMatrix(GLfloat m[16], const GLfloat planeEq[4], const GLfloat lightPos[4]) {
const GLfloat dot = planeEq[0] * lightPos[0] + planeEq[1] * lightPos[1] +
planeEq[2] * lightPos[2] + planeEq[3] * lightPos[3];
m[0] = dot - lightPos[0] * planeEq[0]; // 第 1 列(列主序)
m[1] = - lightPos[1] * planeEq[0];
m[2] = - lightPos[2] * planeEq[0];
m[3] = - lightPos[3] * planeEq[0];
m[4] = - lightPos[0] * planeEq[1]; // 第 2 列
m[5] = dot - lightPos[1] * planeEq[1];
m[6] = - lightPos[2] * planeEq[1];
m[7] = - lightPos[3] * planeEq[1];
m[8] = - lightPos[0] * planeEq[2]; // 第 3 列
m[9] = - lightPos[1] * planeEq[2];
m[10] = dot - lightPos[2] * planeEq[2];
m[11] = - lightPos[3] * planeEq[2];
m[12] = - lightPos[0] * planeEq[3]; // 第 4 列
m[13] = - lightPos[1] * planeEq[3];
m[14] = - lightPos[2] * planeEq[3];
m[15] = dot - lightPos[3] * planeEq[3];
}
void gltInitFrame(GLFrame *frame){
frame->vLocation[0] = 0.0F;
frame->vLocation[1] = 0.0F;
frame->vLocation[2] = 0.0F;
frame->vUp[0] = 0.0F;
frame->vUp[1] = 1.0F;
frame->vUp[2] = 0.0F;
frame->vForward[0] = 0.0F;
frame->vForward[1] = 0.0F;
frame->vForward[2] = -1.0F; // 相机朝向为-z
}
/**
* 视图矩阵 = 上面的逆:旋转转置 + 平移取负
* 把世界挪到相机眼前
*/
void gltApplyCameraTransform(const GLFrame *pCamera) {
// 算出相机右向量 (Right vector)
GLfloat r[3];
r[0] = pCamera->vForward[1] * pCamera->vUp[2] - pCamera->vForward[2] * pCamera->vUp[1];
r[1] = pCamera->vForward[2] * pCamera->vUp[0] - pCamera->vForward[0] * pCamera->vUp[2];
r[2] = pCamera->vForward[0] * pCamera->vUp[1] - pCamera->vForward[1] * pCamera->vUp[0];
// 构建视图矩阵 (View matrix) 列主序 (column-major order)
GLfloat m[16]; // 同样的轴,改填「行」,即转置
m[0]=r[0]; m[4]=r[1]; m[8] =r[2]; m[12]=0.0F;
m[1]=pCamera->vUp[0]; m[5]=pCamera->vUp[1]; m[9] =pCamera->vUp[2]; m[13]=0.0F;
m[2]=-pCamera->vForward[0]; m[6]=-pCamera->vForward[1]; m[10]=-pCamera->vForward[2]; m[14]=0.0F;
m[3]=0.0F; m[7]=0.0F; m[11]=0.0F; m[15]=1.0F;
glMultMatrixf(m);
glTranslatef(-pCamera->vLocation[0], -pCamera->vLocation[1], -pCamera->vLocation[2]);
}
/**
* 物体矩阵 = 相机矩阵的逆:旋转的轴填「列」(不平移取负,平移直接进第 4 列)
* 四列依次是: right、up、-forward、location
* 物体→世界
*/
void gltApplyActorTransform(const GLFrame *frame){
// 算出物体的右向量 (Right vector)
GLfloat r[3];
r[0] = frame->vForward[1] * frame->vUp[2] - frame->vForward[2] * frame->vUp[1];
r[1] = frame->vForward[2] * frame->vUp[0] - frame->vForward[0] * frame->vUp[2];
r[2] = frame->vForward[0] * frame->vUp[1] - frame->vForward[1] * frame->vUp[0];
// 构建物体矩阵 (Model matrix) 列主序 (column-major order)
// 第三列必须是 -forward: right × up = -forward,这样才是右手系(行列式 +1);
// 若填 +forward 则行列式为负,几何体会被镜像,开着 GL_CULL_FACE 时整个模型会被剔除
GLfloat m[16];
m[0]=r[0]; m[4]=frame->vUp[0]; m[8] =-frame->vForward[0]; m[12]=frame->vLocation[0];
m[1]=r[1]; m[5]=frame->vUp[1]; m[9] =-frame->vForward[1]; m[13]=frame->vLocation[1];
m[2]=r[2]; m[6]=frame->vUp[2]; m[10]=-frame->vForward[2]; m[14]=frame->vLocation[2];
m[3]=0.0F; m[7]=0.0F; m[11]=0.0F; m[15]=1.0F;
glMultMatrixf(m);
}
void gltMoveFrameForward(GLFrame* frame, const GLfloat distance){
frame->vLocation[0] += frame->vForward[0] * distance;
frame->vLocation[1] += frame->vForward[1] * distance;
frame->vLocation[2] += frame->vForward[2] * distance;
}
/**
* 绕帧自身的 up 轴旋转(本地 Y 轴 / yaw),up 轴本身不变。
* @param angle 单位是「弧度」,不是度。正值按右手法则绕 up 轴转(LEFT 键传 +0.1 ≈ 左转 5.7°)。
*
* 公式是 Rodrigues 旋转公式在「旋转轴 ⊥ 被旋转向量」时的化简形式:
* v' = v·cosθ + (axis × v)·sinθ
* 完整形式还多一项 axis·(axis·v)·(1-cosθ),因为 up ⊥ forward 而恒为 0。
* 前提: vUp 与 vForward 互相垂直且都是单位向量,否则这个简式不成立。
*/
void gltRotateFrameY(GLFrame* frame, const GLfloat angle){
// axis × forward —— 注意这是 -right(right = forward × up),
// 这个负号决定了旋转方向,别误当成右向量
const GLfloat vAxisCross[3] = {
frame->vUp[1] * frame->vForward[2] - frame->vUp[2] * frame->vForward[1],
frame->vUp[2] * frame->vForward[0] - frame->vUp[0] * frame->vForward[2],
frame->vUp[0] * frame->vForward[1] - frame->vUp[1] * frame->vForward[0]
};
// 角度转弧度
const GLfloat rad = angle; // 如果 angle 是弧度,则直接使用;如果是度,需要转换为弧度:angle * M_PI / 180.0f
const GLfloat fCos = std::cos(rad);
const GLfloat fSin = std::sin(rad);
// vAxisCross 已提前算好,每个分量只依赖自己的旧值,可以直接原地更新,省掉临时数组
frame->vForward[0] = fCos * frame->vForward[0] + fSin * vAxisCross[0];
frame->vForward[1] = fCos * frame->vForward[1] + fSin * vAxisCross[1];
frame->vForward[2] = fCos * frame->vForward[2] + fSin * vAxisCross[2];
// 反复旋转会累积浮点漂移(实测 100 万次后长度偏 +1.2%),归一化抹掉它。
// forward 长度不为 1 会直接变成视图矩阵的缩放,整个世界会被放大/缩小
const GLfloat len = std::sqrt(frame->vForward[0] * frame->vForward[0] +
frame->vForward[1] * frame->vForward[1] +
frame->vForward[2] * frame->vForward[2]);
frame->vForward[0] /= len;
frame->vForward[1] /= len;
frame->vForward[2] /= len;
}
void drawGround(){
constexpr GLfloat fExtent = 20.0F;
constexpr GLfloat fStep = 1.0F;
constexpr GLfloat y = -0.4F;
glBindTexture(GL_TEXTURE_2D, textures[GROUND_TEXTURE]); // 草地
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
for (GLfloat i = -fExtent; i <= fExtent; i += fStep) {
glBegin(GL_TRIANGLE_STRIP);
for (GLfloat j = fExtent; j >= -fExtent; j -= fStep) {
glTexCoord2f((i + fExtent) / fExtent * 2.0F, (j - fExtent) / -fExtent * 2.0F);
glNormal3f(0.0F,1.0F,0.0F);
glVertex3f(i, y, j);
glTexCoord2f((i + fExtent + fStep) / fExtent * 2.0F, (j - fExtent) / -fExtent * 2.0F);
glNormal3f(0.0F,1.0F,0.0F);
glVertex3f(i + fStep, y, j);
}
glEnd();
}
}
void drawSphere(const GLfloat radius, const GLint slices, const GLint stacks) {
const GLfloat sliceStep = 2.0F * PI / static_cast<GLfloat>(slices);
const GLfloat stackStep = PI / static_cast<GLfloat>(stacks);
for (GLint i = 0; i <= stacks; ++i) {
const GLfloat stackAngle1 = i * stackStep;
const GLfloat stackAngle2 = (i + 1) * stackStep;
glBegin(GL_TRIANGLE_STRIP);
for (GLint j = 0; j <= slices; ++j) {
const GLfloat sliceAngle1 = j * sliceStep;
const GLfloat sliceAngle2 = (j + 1) * sliceStep;
const GLfloat nx1 = std::sin(stackAngle1) * std::cos(sliceAngle1);
const GLfloat ny1 = std::cos(stackAngle1);
const GLfloat nz1 = std::sin(stackAngle1) * std::sin(sliceAngle1);
const GLfloat x1 = radius * nx1;
const GLfloat y1 = radius * ny1;
const GLfloat z1 = radius * nz1;
const GLfloat nx2 = std::sin(stackAngle2) * std::cos(sliceAngle1);
const GLfloat ny2 = std::cos(stackAngle2);
const GLfloat nz2 = std::sin(stackAngle2) * std::sin(sliceAngle1);
const GLfloat x2 = radius * nx2;
const GLfloat y2 = radius * ny2;
const GLfloat z2 = radius * nz2;
glNormal3f(nx1, ny1, nz1);
glTexCoord2f(static_cast<GLfloat>(j) / slices, // 左下角
1.0F - static_cast<GLfloat>(i) / stacks);
glVertex3f(x1, y1, z1);
glNormal3f(nx2, ny2, nz2);
glTexCoord2f(static_cast<GLfloat>(j) / slices,
1.0F - static_cast<GLfloat>(i + 1) / stacks);
glVertex3f(x2, y2, z2);
}
glEnd();
}
}
void drawTorus(const GLfloat majorRadius, const GLfloat minorRadius, const int numMajor, const int numMinor) {
const GLfloat majorStep = 2.0F * PI / static_cast<GLfloat>(numMajor);
const GLfloat minorStep = 2.0F * PI / static_cast<GLfloat>(numMinor);
for (int i = 0; i < numMajor; ++i) {
const GLfloat u0 = i * majorStep;
const GLfloat u1 = u0 + majorStep;
glBegin(GL_TRIANGLE_STRIP);
for (int j = 0; j <= numMinor; ++j) {
const GLfloat v0 = j * minorStep;
// 计算两个顶点的坐标
const GLfloat n0[3] = {
std::cos(v0) * std::cos(u0),
std::cos(v0) * std::sin(u0),
std::sin(v0)
};
const GLfloat x00 = (majorRadius + minorRadius * std::cos(v0)) * std::cos(u0);
const GLfloat y00 = (majorRadius + minorRadius * std::cos(v0)) * std::sin(u0);
const GLfloat z00 = minorRadius * std::sin(v0);
const GLfloat n1[3] = {
std::cos(v0) * std::cos(u1),
std::cos(v0) * std::sin(u1),
std::sin(v0)
};
const GLfloat x01 = (majorRadius + minorRadius * std::cos(v0)) * std::cos(u1);
const GLfloat y01 = (majorRadius + minorRadius * std::cos(v0)) * std::sin(u1);
const GLfloat z01 = minorRadius * std::sin(v0);
glNormal3f(n0[0], n0[1], n0[2]);
glTexCoord2f(static_cast<GLfloat>(j) / numMinor, static_cast<GLfloat>(i) / numMajor);
glVertex3f(x00, y00, z00);
glNormal3f(n1[0], n1[1], n1[2]);
glTexCoord2f(static_cast<GLfloat>(j) / numMinor, static_cast<GLfloat>(i + 1) / numMajor);
glVertex3f(x01, y01, z01);
}
glEnd();
}
}
void drawInhabitant(const GLboolean isShadow) {
if (isShadow) {
glColor4f(0.0f, 0.0f, 0.0f, 0.6f); // 设置阴影颜色为半透明黑色
} else {
yRot += 0.5f;
glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // 设置物体颜色为白色
}
glBindTexture(GL_TEXTURE_2D, textures[SPHERE_TEXTURE]); // 绑定纹理
// 画球
for(GLuint i = 0; i < NUM_SPHERES; ++i) {
glPushMatrix();
gltApplyActorTransform(&spheres[i]);
if(iRenderMode == 0) {
drawSphere(0.1f, 40, 20);
} else {
glCallList(sphereList);
}
glPopMatrix();
}
// 画球体绕着圆环旋转
glPushMatrix();
glTranslatef(0.0f, 0.1f, -2.5f);
glPushMatrix();
glRotatef(-yRot * 2.0f, 0.0f, 1.0f, 0.0f); // 绕y轴旋转
glTranslatef(1.0f, 0.0f, 0.0f); // 可以根据需要调整球体的位置
if(iRenderMode == 0) {
drawSphere(0.1f, 40, 20);
} else {
glCallList(sphereList);
}
glPopMatrix();
if(isShadow) {
glMaterialfv(GL_FRONT, GL_SPECULAR, fBrightLight);
}
glRotatef(yRot, 0.0f, 1.0f, 0.0f); // 绕y轴旋转
glBindTexture(GL_TEXTURE_2D, textures[TORUS_TEXTURE]);
if(iRenderMode == 0) {
drawTorus(0.35f, 0.15f, 61, 37);
} else {
glCallList(torusList);
}
glMaterialfv(GL_FRONT, GL_SPECULAR, fNoLight);
glPopMatrix();
}
void setupRc(){
glClearColor(flowLight[0], flowLight[1], flowLight[2], flowLight[3]);
// 模版缓冲区设置
glStencilOp(GL_INCR, GL_INCR, GL_INCR);
glClearStencil(0);
glStencilFunc(GL_EQUAL, 0, 0x01); // 设置模板测试函数,只有模板值等于0的片段才会通过测试
// 面剔除设置
glCullFace(GL_BACK);
glFrontFace(GL_CCW); // 设置前面朝向为逆时针
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST); // 启用深度测试
glEnable(GL_STENCIL_TEST); // 启用模板测试
glEnable(GL_MULTISAMPLE_ARB); // 启用多重采样抗锯齿
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, fNoLight); // 设置全局光照模型的环境光
glLightfv(GL_LIGHT0, GL_AMBIENT, flowLight); // 设置光源0的环境光
glLightfv(GL_LIGHT0, GL_DIFFUSE, fBrightLight); // 设置光源0的漫反射光
glLightfv(GL_LIGHT0, GL_SPECULAR, fBrightLight); // 设置光源0的镜面反射光
glEnable(GL_LIGHTING); // 启用光照
glEnable(GL_LIGHT0); // 启用光源0
// 启用独立的镜面反射颜色控制,使得镜面反射颜色不受材质漫反射颜色的影响
glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
// 计算阴影变换矩阵
// 选择地面三个点即可 // y = -0.4 平面 -> y + 0.4 = 0;
static constexpr GLfloat planeEq[4] = { 0.0f, 1.0f, 0.0f, 0.4f }; // y = -0.4 平面 -> y + 0.4 = 0;
makeShadowMatrix(shadowMatrix, planeEq, lightPos);
glEnable(GL_COLOR_MATERIAL); // 启用颜色材质,使得物体颜色影响材质的环境光和漫反射光
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE); // 设置前面材质的环境光和漫反射光由颜色控制
glMaterialfv(GL_FRONT, GL_SPECULAR, fBrightLight); // 设置前面材质的镜面反射光
glMaterialf(GL_FRONT, GL_SHININESS, 128.0f); // 设置前面材质的高光指数
// 初始化每个球体的位置
// 使用c++11的随机数生成器初始化球体位置
gltInitFrame(&camera);
std::random_device rd;
std::mt19937_64 gen(rd());
std::uniform_real_distribution<GLfloat> dis(-20.0f, 20.0f);
for(GLuint i = 0; i < NUM_SPHERES; ++ i) {
gltInitFrame(&spheres[i]);
spheres[i].vLocation[0] = dis(gen); // x
spheres[i].vLocation[1] = 0.0f; // y
spheres[i].vLocation[2] = dis(gen); // z
}
glEnable(GL_TEXTURE_2D);
glGenTextures(NUM_TEXTURES, textures);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // 纹理颜色 和 物体颜色进行相乘
for(GLuint i = 0; i < NUM_TEXTURES; ++i) {
std::ifstream file(TEXTURE_FILES[i], std::ios::binary);
if(!file) {
throw std::runtime_error("Failed to open texture file: " + TEXTURE_FILES[i]);
}
TargaHeader header;
file.read(reinterpret_cast<char*>(&header), sizeof(header));
if(!file) {
throw std::runtime_error("Failed to read Targa header from file: " + TEXTURE_FILES[i]);
}
std::vector<GLubyte> imageData(header.width * header.height * (header.bitsPerPixel / 8));
file.read(reinterpret_cast<char*>(imageData.data()), imageData.size());
if(!file) {
throw std::runtime_error("Failed to read Targa image data from file: " + TEXTURE_FILES[i]);
}
glBindTexture(GL_TEXTURE_2D, textures[i]);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, header.width, header.height, 0, GL_BGR, GL_UNSIGNED_BYTE, imageData.data());
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
groundList = glGenLists(3);
sphereList = groundList + 1;
torusList = groundList + 2;
glNewList(groundList, GL_COMPILE);
drawGround();
glEndList();
glNewList(sphereList, GL_COMPILE);
drawSphere(0.1f, 40, 20);
glEndList();
glNewList(torusList, GL_COMPILE);
drawTorus(0.35f, 0.15f, 61, 37);
glEndList();
}
void shutdownRc(){
glDeleteLists(groundList, 3);
glDeleteTextures(NUM_TEXTURES, textures);
}
void renderScene(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glPushMatrix();
gltApplyCameraTransform(&camera);
glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
glColor3f(1.0f, 1.0f, 1.0f); // 设置颜色为白色
if(iRenderMode == 0) {
drawGround();
} else {
glCallList(groundList);
}
// 绘制阴影,需要关闭深度测试
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING); // 关闭光照以绘制阴影
glDisable(GL_TEXTURE_2D); // 关闭纹理以绘制阴影
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // 设置混合函数以实现透明阴影效果
glEnable(GL_STENCIL_TEST); // 启用模板测试以绘制阴影
glPushMatrix();
glMultMatrixf(shadowMatrix);
drawInhabitant(GL_TRUE);
glPopMatrix();
glDisable(GL_STENCIL_TEST); // 禁用模板测试
glDisable(GL_BLEND); // 禁用混合
glEnable(GL_TEXTURE_2D); // 恢复纹理
glEnable(GL_LIGHTING); // 恢复光照
glEnable(GL_DEPTH_TEST); // 恢复深度测试
drawInhabitant(GL_FALSE);
glPopMatrix();
glutSwapBuffers();
}
void changeSize(const int w, int h) {
if(h == 0) h = 1;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, static_cast<GLfloat>(w) / static_cast<GLfloat>(h), 1.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void processMenu(const int option){
iRenderMode = option;
glutSetWindow(mainWindowId);
glutPostRedisplay(); // 请求重新绘制场景以应用新的渲染模式
}
void timerFunc(const int value){
glutPostRedisplay();
glutTimerFunc(3, timerFunc, 1);
}
void specialKeys(const int key, const int x, const int y){
switch(key){
case GLUT_KEY_UP:
gltMoveFrameForward(&camera, 0.1f);
break;
case GLUT_KEY_DOWN:
gltMoveFrameForward(&camera, -0.1f);
break;
case GLUT_KEY_LEFT:
gltRotateFrameY(&camera, 0.1f);
break;
case GLUT_KEY_RIGHT:
gltRotateFrameY(&camera, -0.1f);
break;
}
glutPostRedisplay();
}
auto main(int argc, char **argv) -> int {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
mainWindowId = glutCreateWindow(WINDOW_TITLE.data());
glutDisplayFunc(renderScene);
glutReshapeFunc(changeSize);
glutSpecialFunc(specialKeys);
glutCreateMenu(processMenu);
glutAddMenuEntry("Without Display Lists", 0);
glutAddMenuEntry("With Display Lists",1);
glutAttachMenu(GLUT_RIGHT_BUTTON);
setupRc();
glutTimerFunc(33, timerFunc, 1);
glutMainLoop();
shutdownRc();
return 0;
}
使用顶点数组
#if defined(__APPLE__) && defined(__MACH__)
#include <GLUT/glut.h>
#include <OpenGL/gl.h>
#include <OpenGL/glext.h>
#else
extern "C" {
#include <GL/freeglut.h>
}
#endif
#include <iostream>
#include <stdexcept>
#include <fstream>
#include <vector>
#include <numbers>
#include <cmath>
#include <random>
static constexpr GLfloat PI = std::numbers::pi_v<GLfloat>;
static constexpr GLint WINDOW_WIDTH = 800;
static constexpr GLint WINDOW_HEIGHT = 600;
static constexpr GLint TEXTURE_COUNT = 2;
struct GLFrame {
GLfloat vLocation[3]; // 位置 -> move x, y, z
GLfloat vUp[3]; // 上方向 -> y
GLfloat vForward[3]; // 前方向 -> z x-> 通过 yz叉积计算 -> 归一化为单位向量
};
// 小星星数量定义
static constexpr GLint SMALL_STAR = 100;
static constexpr GLint MEDIUM_STAR = 40;
static constexpr GLint LARGE_STAR = 15;
static GLfloat smallStars[SMALL_STAR][2];
static GLfloat mediumStars[MEDIUM_STAR][2];
static GLfloat largeStars[LARGE_STAR][2];
static GLuint textures[TEXTURE_COUNT];
static GLint drawMode = 1;
static int mainWindowId = 0;
// Targa 图像文件头结构体
#pragma pack(push, 1) // 关闭结构体对齐填充
struct TargaHeader {
// 图像 ID 区长度,0 = 无
GLubyte idLength;
GLubyte colorMapType; // 0 = 无调色板
GLubyte dataTypeCode; // 图像数据类型代码 2 = 未压缩真彩图(非 RLE)
GLushort colorMapOrigin; // 调色板起始索引
GLushort colorMapLength; // 调色板颜色的数量
GLubyte colorMapDepth; // 调色板每条颜色的位数
GLushort xOrigin; // 图像在屏幕上的 X 坐标
GLushort yOrigin; // 图像在屏幕上的 Y 坐标
GLushort width; // 图像宽度
GLushort height; // 图像高度
// 每像素 24 位 = RGB 各 8 位
GLubyte bitsPerPixel;
// 0 表示自下而上存储
GLubyte imageDescriptor;
};
#pragma pack(pop) // 恢复结构体对齐填充
std::ostream& operator<<(std::ostream& os, const TargaHeader& header) {
os << "TargaHeader { "
<< "idLength=" << static_cast<int>(header.idLength) << ", "
<< "colorMapType=" << static_cast<int>(header.colorMapType) << ", "
<< "dataTypeCode=" << static_cast<int>(header.dataTypeCode) << ", "
<< "colorMapOrigin=" << header.colorMapOrigin << ", "
<< "colorMapLength=" << header.colorMapLength << ", "
<< "colorMapDepth=" << static_cast<int>(header.colorMapDepth) << ", "
<< "xOrigin=" << header.xOrigin << ", "
<< "yOrigin=" << header.yOrigin << ", "
<< "width=" << header.width << ", "
<< "height=" << header.height << ", "
<< "bitsPerPixel=" << static_cast<int>(header.bitsPerPixel) << ", "
<< "imageDescriptor=" << static_cast<int>(header.imageDescriptor)
<< " }";
return os;
}
void setupRc(){
// small stars
std::random_device rd; // 硬件熵源,用于播种
std::mt19937_64 gen(rd()); // Mersenne Twister 引擎
std::uniform_int_distribution<std::int32_t> dis(
std::numeric_limits<std::int32_t>::min(),
std::numeric_limits<std::int32_t>::max()
);
for(int i = 0; i < SMALL_STAR; ++i){
smallStars[i][0] = static_cast<GLfloat>(dis(gen) % WINDOW_WIDTH); // [-20, 20]
smallStars[i][1] = static_cast<GLfloat>(dis(gen) % (WINDOW_HEIGHT - 100) + 100); // [-20, 20]
}
for(int i = 0; i < MEDIUM_STAR; ++i){
mediumStars[i][0] = static_cast<GLfloat>(dis(gen) % WINDOW_WIDTH * 10) / 10.0F; // [-20, 20]
mediumStars[i][1] = static_cast<GLfloat>(dis(gen) % (WINDOW_HEIGHT - 100) + 100); // [-20, 20]
}
for(int i = 0; i < LARGE_STAR; ++i){
largeStars[i][0] = static_cast<GLfloat>(dis(gen) % WINDOW_WIDTH * 10) / 10.0F; // [-20, 20]
largeStars[i][1] = static_cast<GLfloat>(dis(gen) % (WINDOW_HEIGHT - 100) * 10) / 10.0F + 100.0F; // [-20, 20]
}
glClearColor(0.0F, 0.0F, 0.0F, 1.0F);
glColor3f(0.0f, 0.0f, 0.0f);
glGenTextures(TEXTURE_COUNT, textures);
glBindTexture(GL_TEXTURE_2D, textures[0]);
TargaHeader header;
std::ifstream file("../image/star.tga", std::ios::binary);
if(file){
file.read(reinterpret_cast<char*>(&header), sizeof(TargaHeader));
}
std::vector<char> imageData(header.width * header.height * (header.bitsPerPixel / 8));
if(file){
file.read(imageData.data(), imageData.size());
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, header.width, header.height, 0, GL_BGR, GL_UNSIGNED_BYTE, imageData.data());
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, textures[1]);
TargaHeader header2;
std::ifstream file2("../image/moon.tga", std::ios::binary);
if(file2){
file2.read(reinterpret_cast<char*>(&header2), sizeof(TargaHeader));
}
std::vector<char> imageData2(header2.width * header2.height * (header2.bitsPerPixel / 8));
if(file2){
file2.read(imageData2.data(), imageData2.size());
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, header2.width, header2.height, 0, GL_BGR, GL_UNSIGNED_BYTE, imageData2.data());
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
glTexEnvi(GL_POINT_SPRITE, GL_TEXTURE_ENV_MODE, GL_DECAL);
}
void shutdownRc(){
glDeleteTextures(TEXTURE_COUNT, textures);
}
void renderScene(){
// Rendering code goes here
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1.0F, 1.0F, 1.0F);
if(drawMode == 3) {
glEnable(GL_POINT_SPRITE);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textures[0]);
glEnable(GL_BLEND);
}
glPointSize(7.0f); // Example point size, adjust as needed
// glBegin(GL_POINTS);
// for (int i = 0; i < SMALL_STAR; ++i) {
// glVertex2fv(smallStars[i]);
// }
// glEnd();
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, smallStars);
glDrawArrays(GL_POINTS, 0, SMALL_STAR);
glPointSize(12.0F);
// glBegin(GL_POINTS);
// for (int i = 0; i < MEDIUM_STAR; ++i) {
// glVertex2fv(mediumStars[i]);
// }
// glEnd();
glVertexPointer(2, GL_FLOAT, 0, mediumStars);
glDrawArrays(GL_POINTS, 0, MEDIUM_STAR);
glPointSize(20.0F);
// glBegin(GL_POINTS);
// for (int i = 0; i < LARGE_STAR; ++i) {
// glVertex2fv(largeStars[i]);
// }
// glEnd();
glVertexPointer(2, GL_FLOAT, 0, largeStars);
glDrawArrays(GL_POINTS, 0, LARGE_STAR);
glPointSize(120.0F);
if(drawMode == 3) {
glDisable(GL_BLEND);
glBindTexture(GL_TEXTURE_2D, textures[1]);
}
glBegin(GL_POINTS);
glVertex2f(700.0F, 500.0F);
glEnd();
glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_VERTEX_ARRAY);
glDisable(GL_POINT_SPRITE);
// Draw distant horizon
glLineWidth(3.5F);
glBegin(GL_LINE_STRIP);
glVertex2f(0.0f, 25.0f);
glVertex2f(50.0f, 100.0f);
glVertex2f(100.0f, 25.0f);
glVertex2f(225.0f, 115.0f);
glVertex2f(300.0f, 50.0f);
glVertex2f(375.0f, 100.0f);
glVertex2f(460.0f, 25.0f);
glVertex2f(525.0f, 100.0f);
glVertex2f(600.0f, 20.0f);
glVertex2f(675.0f, 70.0f);
glVertex2f(750.0f, 25.0f);
glVertex2f(800.0f, 90.0f);
glEnd();
glutSwapBuffers();
}
void changeSize(const int w, int h){
if(h == 0) h = 1;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// gluPerspective(45.0, static_cast<double>(w)/static_cast<double>(h), 1.0, 100.0);
glOrtho(0.0, w, 0.0, h, -1.0, 1); // 使用正交投影替代透视投影
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void gltMoveFrameForward(GLFrame* frame, const GLfloat distance){
frame->vLocation[0] += frame->vForward[0] * distance;
frame->vLocation[1] += frame->vForward[1] * distance;
frame->vLocation[2] += frame->vForward[2] * distance;
}
/**
* 绕帧自身的 up 轴旋转(本地 Y 轴 / yaw),up 轴本身不变。
* @param angle 单位是「弧度」,不是度。正值按右手法则绕 up 轴转(LEFT 键传 +0.1 ≈ 左转 5.7°)。
*
* 公式是 Rodrigues 旋转公式在「旋转轴 ⊥ 被旋转向量」时的化简形式:
* v' = v·cosθ + (axis × v)·sinθ
* 完整形式还多一项 axis·(axis·v)·(1-cosθ),因为 up ⊥ forward 而恒为 0。
* 前提: vUp 与 vForward 互相垂直且都是单位向量,否则这个简式不成立。
*/
void gltRotateFrameY(GLFrame* frame, const GLfloat angle){
// axis × forward —— 注意这是 -right(right = forward × up),
// 这个负号决定了旋转方向,别误当成右向量
const GLfloat vAxisCross[3] = {
frame->vUp[1] * frame->vForward[2] - frame->vUp[2] * frame->vForward[1],
frame->vUp[2] * frame->vForward[0] - frame->vUp[0] * frame->vForward[2],
frame->vUp[0] * frame->vForward[1] - frame->vUp[1] * frame->vForward[0]
};
// 角度转弧度
const GLfloat rad = angle; // 如果 angle 是弧度,则直接使用;如果是度,需要转换为弧度:angle * M_PI / 180.0f
const GLfloat fCos = std::cos(rad);
const GLfloat fSin = std::sin(rad);
// vAxisCross 已提前算好,每个分量只依赖自己的旧值,可以直接原地更新,省掉临时数组
frame->vForward[0] = fCos * frame->vForward[0] + fSin * vAxisCross[0];
frame->vForward[1] = fCos * frame->vForward[1] + fSin * vAxisCross[1];
frame->vForward[2] = fCos * frame->vForward[2] + fSin * vAxisCross[2];
// 反复旋转会累积浮点漂移(实测 100 万次后长度偏 +1.2%),归一化抹掉它。
// forward 长度不为 1 会直接变成视图矩阵的缩放,整个世界会被放大/缩小
const GLfloat len = std::sqrt(frame->vForward[0] * frame->vForward[0] +
frame->vForward[1] * frame->vForward[1] +
frame->vForward[2] * frame->vForward[2]);
frame->vForward[0] /= len;
frame->vForward[1] /= len;
frame->vForward[2] /= len;
}
void specialKeys(int key, int x, int y){
switch(key){
case GLUT_KEY_UP:
// gltMoveFrameForward(&frameCamera, 0.1f);
break;
case GLUT_KEY_DOWN:
// gltMoveFrameForward(&frameCamera, -0.1f);
break;
case GLUT_KEY_LEFT:
// gltRotateFrameY(&frameCamera, 0.1f);
break;
case GLUT_KEY_RIGHT:
// gltRotateFrameY(&frameCamera, -0.1f);
break;
}
glutPostRedisplay();
}
void timerFunc(const int _){
glutPostRedisplay();
glutTimerFunc(33, timerFunc, 1); // 大约 30 FPS
}
void processMenu(int option){
drawMode = option;
switch(option){
case 1:
// Normal Point
glDisable(GL_BLEND);
glDisable(GL_LINE_SMOOTH);
glDisable(GL_POINT_SMOOTH);
glDisable(GL_TEXTURE_2D);
glDisable(GL_POINT_SPRITE);
break;
case 2:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glEnable(GL_POINT_SMOOTH);
glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glDisable(GL_TEXTURE_2D);
glDisable(GL_POINT_SPRITE);
break;
case 3:
// Point Sprites
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);
glDisable(GL_LINE_SMOOTH);
glDisable(GL_POINT_SMOOTH);
glDisable(GL_POLYGON_SMOOTH);
break;
}
glutSetWindow(mainWindowId);
glutPostRedisplay();
}
int main(int args, char** argv){
std::cout << "Starting program..." << std::endl;
glutInit(&args, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
mainWindowId = glutCreateWindow("OpenGL Window");
if(mainWindowId == 0){
throw std::runtime_error("Failed to create main window");
}
// ======= 事件处理 =======
glutDisplayFunc(renderScene);
glutReshapeFunc(changeSize);
glutSpecialFunc(specialKeys);
glutCreateMenu(processMenu); // 如果有菜单状态处理函数
glutAddMenuEntry("Normal Point", 1);
glutAddMenuEntry("Antialiased Points", 2);
glutAddMenuEntry("Point Sprites", 3);
glutAttachMenu(GLUT_RIGHT_BUTTON); // 将菜单附加到鼠标右键
// ======= 渲染循环 =======
GLint iUnits;
glGetIntegerv(GL_MAX_TEXTURE_UNITS, &iUnits);
std::cout << "Max texture units: " << iUnits << std::endl;
setupRc();
glutMainLoop();
shutdownRc();
return 0;
}
F-16
#if defined(__APPLE__) && defined(__MACH__)
#include <GLUT/glut.h>
#include <OpenGL/gl.h>
#include <OpenGL/glext.h>
#else
extern "C" {
#include <GL/freeglut.h>
}
#endif
#include <iostream>
#include <stdexcept>
#include <fstream>
#include <vector>
#include <numbers>
static constexpr GLfloat PI = std::numbers::pi_v<GLfloat>;
static constexpr GLint WINDOW_WIDTH = 800;
static constexpr GLint WINDOW_HEIGHT = 600;
static constexpr GLint TEXTURE_COUNT = 2;
static constexpr GLint BODY_TEXTURE = 0;
static constexpr GLint GLASS_TEXTURE = 1;
static constexpr std::array<std::string, TEXTURE_COUNT> TEXTURE_FILES = {
"../image/body.tga",
"../image/glass.tga"
};
static constexpr GLfloat fAmbientLight[] = {0.1f, 0.1f, 0.1f, 0.0f}; // 环境光
static constexpr GLfloat fDiffuseLight[] = {1.0f, 1.0f, 1.0f, 0.0f}; // 漫反射光
static constexpr GLfloat fSpecularLight[] = {0.5f, 0.5f, 0.5f, 0.0f}; // 镜面反射光
static constexpr GLfloat fLightPosition[] = {-100.0f, 100.0f, 100.0f, 1.0f}; // 光源位置
// 变量
static GLuint textureObjects[TEXTURE_COUNT];
static GLint mainWindowId = 0;
static GLuint bodyList, glassList;
static GLfloat xRot = 0.0f; // Rotation angle around the X-axis
static GLfloat yRot = 0.0f; // Rotation angle around the Y-axis
// 引入外部的变量,这里仅仅声明一下
// body
extern GLshort face_indicies[3704][9]; // body
extern GLfloat vertices[1898][3];
extern GLfloat normals[2716][3]; // body normals
extern GLfloat textures[2925][2]; // body texture coordinates
// glass
extern GLshort face_indiciesGlass[352][9]; // glass
extern GLfloat verticesGlass[197][3]; // glass vertices
extern GLfloat normalsGlass[227][3]; // glass normals
extern GLfloat texturesGlass[227][2]; // glass texture coordinates
// Targa 图像文件头结构体
#pragma pack(push, 1) // 关闭结构体对齐填充
struct TargaHeader {
// 图像 ID 区长度,0 = 无
GLubyte idLength;
GLubyte colorMapType; // 0 = 无调色板
GLubyte dataTypeCode; // 图像数据类型代码 2 = 未压缩真彩图(非 RLE)
GLushort colorMapOrigin; // 调色板起始索引
GLushort colorMapLength; // 调色板颜色的数量
GLubyte colorMapDepth; // 调色板每条颜色的位数
GLushort xOrigin; // 图像在屏幕上的 X 坐标
GLushort yOrigin; // 图像在屏幕上的 Y 坐标
GLushort width; // 图像宽度
GLushort height; // 图像高度
// 每像素 24 位 = RGB 各 8 位
GLubyte bitsPerPixel;
// 0 表示自下而上存储
GLubyte imageDescriptor;
};
#pragma pack(pop) // 恢复结构体对齐填充
std::ostream& operator<<(std::ostream& os, const TargaHeader& header) {
os << "TargaHeader { "
<< "idLength=" << static_cast<int>(header.idLength) << ", "
<< "colorMapType=" << static_cast<int>(header.colorMapType) << ", "
<< "dataTypeCode=" << static_cast<int>(header.dataTypeCode) << ", "
<< "colorMapOrigin=" << header.colorMapOrigin << ", "
<< "colorMapLength=" << header.colorMapLength << ", "
<< "colorMapDepth=" << static_cast<int>(header.colorMapDepth) << ", "
<< "xOrigin=" << header.xOrigin << ", "
<< "yOrigin=" << header.yOrigin << ", "
<< "width=" << header.width << ", "
<< "height=" << header.height << ", "
<< "bitsPerPixel=" << static_cast<int>(header.bitsPerPixel) << ", "
<< "imageDescriptor=" << static_cast<int>(header.imageDescriptor)
<< " }";
return os;
}
void drawBody(){
glBegin(GL_TRIANGLES); // Assuming the body is made of triangles
for(GLuint i = 0; i < 3704; ++i){
for(GLuint j = 0; j < 3; ++j){
// j = 0,1,2 对应顶点索引
// j + 3 对应法线索引
// j + 6 对应纹理坐标索引
glNormal3fv(normals[face_indicies[i][j + 3]]);
glTexCoord2fv(textures[face_indicies[i][j + 6]]);
glVertex3fv(vertices[face_indicies[i][j]]);
}
}
glEnd();
}
void drawGlass(){
glBegin(GL_TRIANGLES); // Assuming the glass is made of triangles
for(GLuint i = 0; i < 352; ++i){
for(GLuint j = 0; j < 3; ++j){
glNormal3fv(normalsGlass[face_indiciesGlass[i][j + 3]]);
glTexCoord2fv(texturesGlass[face_indiciesGlass[i][j + 6]]);
glVertex3fv(verticesGlass[face_indiciesGlass[i][j]]);
}
}
glEnd();
}
void setupRc(){
glClearColor(0.0F, 0.0F, 0.5F, 1.0F);
glEnable(GL_DEPTH_TEST); // Enable depth testing for 3D rendering
glEnable(GL_CULL_FACE); // Enable face culling
glFrontFace(GL_CCW); // Define front faces as counter-clockwise
glCullFace(GL_BACK); // Cull back faces
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glGenTextures(TEXTURE_COUNT, textureObjects);
glBindTexture(GL_TEXTURE_2D, textureObjects[BODY_TEXTURE]);
TargaHeader header;
std::ifstream file("../image/body.tga", std::ios::binary);
if(file){
file.read(reinterpret_cast<char*>(&header), sizeof(TargaHeader));
}
std::vector<char> imageData(header.width * header.height * (header.bitsPerPixel / 8));
if(file){
file.read(imageData.data(), imageData.size());
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, header.width, header.height, 0, GL_BGR, GL_UNSIGNED_BYTE, imageData.data());
glGenerateMipmap(GL_TEXTURE_2D);
GLfloat fLargest;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest); // 获取最大各向异性值
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glBindTexture(GL_TEXTURE_2D, textureObjects[GLASS_TEXTURE]);
TargaHeader header2;
std::ifstream file2("../image/glass.tga", std::ios::binary);
if(file2){
file2.read(reinterpret_cast<char*>(&header2), sizeof(TargaHeader));
}
std::vector<char> imageData2(header2.width * header2.height * (header2.bitsPerPixel / 8));
if(file2){
file2.read(imageData2.data(), imageData2.size());
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, header2.width, header2.height, 0, GL_BGR, GL_UNSIGNED_BYTE, imageData2.data());
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glEnable(GL_TEXTURE_2D);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL); // 开启颜色材质功能
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE); // 设置前面材质的环境光和漫反射光由颜色控制
glMaterialfv(GL_FRONT, GL_SPECULAR, fSpecularLight); // 设置前面材质的镜面反射光
glMaterialf(GL_FRONT, GL_SHININESS, 128.0f); // 设置前面材质的高光指数
glLightfv(GL_LIGHT0, GL_AMBIENT, fAmbientLight); // 设置光源的环境光
glLightfv(GL_LIGHT0, GL_DIFFUSE, fDiffuseLight); // 设置光源的漫反射光
glLightfv(GL_LIGHT0, GL_SPECULAR, fSpecularLight); // 设置光源的镜面反射光
glLightfv(GL_LIGHT0, GL_POSITION, fLightPosition); // 设置光源位置
glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR); // 设置光照模型使用独立的镜面反射颜色
glEnable(GL_RESCALE_NORMAL); // 开启法线重缩放,用于保持法线长度一致,避免缩放物体时光照计算错误
bodyList = glGenLists(2); // 生成显示列表
glassList = bodyList + 1; // 生成玻璃显示列表
glNewList(bodyList, GL_COMPILE);
drawBody();
glEndList();
glNewList(glassList, GL_COMPILE);
drawGlass();
glEndList();
}
void shutdownRc(){
glDeleteLists(bodyList, 2); // 删除显示列表
glDeleteTextures(TEXTURE_COUNT, textureObjects);
}
void renderScene(){
// Rendering code goes here
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glTranslatef(0.0f, 0.0f, -3.0f); // Example translation, adjust as needed
glRotated(xRot, 1.0F, 0.0F, 0.0F);
glRotated(yRot, 0.0F, 1.0F, 0.0F);
glPushMatrix(); // Save the current matrix state
glRotated(-90.0f, 1.0F, 0.0F, 0.0F);
glBindTexture(GL_TEXTURE_2D, textureObjects[BODY_TEXTURE]); // Example binding, adjust as needed
glScalef(0.01f, 0.01f, 0.01f);
glCallList(bodyList); // Draw the body using the display list
glPopMatrix();
glEnable(GL_BLEND); // Enable blending for transparency effects
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Set the blending function for transparency
glTranslatef(0.0f, 0.132f, 0.555f);
glBindTexture(GL_TEXTURE_2D, textureObjects[GLASS_TEXTURE]); // Example binding, adjust as needed
glScalef(0.01f, 0.01f, 0.01f);
glFrontFace(GL_CW); // Set the front face winding order for correct culling of transparent objects
glCallList(glassList); // Draw the glass using the display list
glFrontFace(GL_CCW); // Restore the default front face winding order after drawing transparent objects
glCallList(glassList);
glDisable(GL_BLEND); // Disable blending after drawing transparent objects
glPopMatrix();
glutSwapBuffers();
}
void changeSize(const int w, int h){
if(h == 0) h = 1;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// 注意:正交投影 glOrtho(0, w, 0, h, -1, 1) 的可视 z 范围是 [-1, 1],
// 而模型被平移到 z = -4,会被整个裁掉;x/y 又是像素单位,模型坐标只有 ±1。
// 所以这里必须用透视投影(模型在 z=-4,缩放 0.01 后尺寸约 ±1)。
gluPerspective(45.0, static_cast<double>(w)/static_cast<double>(h), 1.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
/**
* 绕帧自身的 up 轴旋转(本地 Y 轴 / yaw),up 轴本身不变。
* @param angle 单位是「弧度」,不是度。正值按右手法则绕 up 轴转(LEFT 键传 +0.1 ≈ 左转 5.7°)。
*
* 公式是 Rodrigues 旋转公式在「旋转轴 ⊥ 被旋转向量」时的化简形式:
* v' = v·cosθ + (axis × v)·sinθ
* 完整形式还多一项 axis·(axis·v)·(1-cosθ),因为 up ⊥ forward 而恒为 0。
* 前提: vUp 与 vForward 互相垂直且都是单位向量,否则这个简式不成立。
*/
void specialKeys(int key, int x, int y){
switch(key){
case GLUT_KEY_UP:
xRot -= 5.7f; // Rotate up by 5.7 degrees (0.1 radians)
break;
case GLUT_KEY_DOWN:
xRot += 5.7f; // Rotate down by 5.7 degrees (0.1 radians)
break;
case GLUT_KEY_LEFT:
yRot -= 5.7f; // Rotate left by 5.7 degrees (0.1 radians)
break;
case GLUT_KEY_RIGHT:
yRot += 5.7f; // Rotate right by 5.7 degrees (0.1 radians)
break;
}
glutPostRedisplay();
}
void timerFunc(const int _){
glutPostRedisplay();
glutTimerFunc(33, timerFunc, 1); // 大约 30 FPS
}
void processMenu(int option){
switch(option){
case 1:
// Normal Point
glDisable(GL_BLEND);
glDisable(GL_LINE_SMOOTH);
glDisable(GL_POINT_SMOOTH);
glDisable(GL_TEXTURE_2D);
glDisable(GL_POINT_SPRITE);
break;
case 2:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glEnable(GL_POINT_SMOOTH);
glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glDisable(GL_TEXTURE_2D);
glDisable(GL_POINT_SPRITE);
break;
case 3:
// Point Sprites
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);
glDisable(GL_LINE_SMOOTH);
glDisable(GL_POINT_SMOOTH);
glDisable(GL_POLYGON_SMOOTH);
break;
}
glutSetWindow(mainWindowId);
glutPostRedisplay();
}
int main(int args, char** argv){
std::cout << "Starting program..." << std::endl;
glutInit(&args, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
mainWindowId = glutCreateWindow("OpenGL Window");
if(mainWindowId == 0){
throw std::runtime_error("Failed to create main window");
}
// ======= 事件处理 =======
glutDisplayFunc(renderScene);
glutReshapeFunc(changeSize);
glutSpecialFunc(specialKeys);
glutCreateMenu(processMenu); // 如果有菜单状态处理函数
glutAddMenuEntry("Normal Point", 1);
glutAddMenuEntry("Antialiased Points", 2);
glutAddMenuEntry("Point Sprites", 3);
glutAttachMenu(GLUT_RIGHT_BUTTON); // 将菜单附加到鼠标右键
// ======= 渲染循环 =======
GLint iUnits;
glGetIntegerv(GL_MAX_TEXTURE_UNITS, &iUnits);
std::cout << "Max texture units: " << iUnits << std::endl;
setupRc();
glutMainLoop();
shutdownRc();
return 0;
}
F-16 顶点数组优化
#if defined(__APPLE__) && defined(__MACH__)
#include <GLUT/glut.h>
#include <OpenGL/gl.h>
#include <OpenGL/glext.h>
#else
extern "C" {
#include <GL/freeglut.h>
}
#endif
#include <iostream>
#include <stdexcept>
#include <fstream>
#include <vector>
#include <numbers>
#include <array>
#include <cstddef>
static constexpr GLfloat PI = std::numbers::pi_v<GLfloat>;
static constexpr GLint WINDOW_WIDTH = 800;
static constexpr GLint WINDOW_HEIGHT = 600;
static constexpr GLint TEXTURE_COUNT = 2;
static constexpr GLint BODY_TEXTURE = 0;
static constexpr GLint GLASS_TEXTURE = 1;
static constexpr std::array<std::string, TEXTURE_COUNT> TEXTURE_FILES = {
"../image/body.tga",
"../image/glass.tga"
};
static constexpr GLfloat fAmbientLight[] = {0.1f, 0.1f, 0.1f, 0.0f}; // 环境光
static constexpr GLfloat fDiffuseLight[] = {1.0f, 1.0f, 1.0f, 0.0f}; // 漫反射光
static constexpr GLfloat fSpecularLight[] = {0.5f, 0.5f, 0.5f, 0.0f}; // 镜面反射光
static constexpr GLfloat fLightPosition[] = {-100.0f, 100.0f, 100.0f, 1.0f}; // 光源位置
// 变量
static GLuint textureObjects[TEXTURE_COUNT];
static GLint mainWindowId = 0;
static GLfloat xRot = 0.0f; // Rotation angle around the X-axis
static GLfloat yRot = 0.0f; // Rotation angle around the Y-axis
// 引入外部的变量,这里仅仅声明一下
// body
extern GLshort face_indicies[3704][9]; // body
extern GLfloat vertices[1898][3];
extern GLfloat normals[2716][3]; // body normals
extern GLfloat textures[2925][2]; // body texture coordinates
// glass
extern GLshort face_indiciesGlass[352][9]; // glass
extern GLfloat verticesGlass[197][3]; // glass vertices
extern GLfloat normalsGlass[227][3]; // glass normals
extern GLfloat texturesGlass[227][2]; // glass texture coordinates
// ---- 顶点数组 / VBO ----
// 模型是“每个角一套索引”(v/n/t),而一次 DrawArrays 只有一条顶点流,
// 所以先把每个角展开成一个交错顶点:position + normal + uv。
struct MeshVertex {
GLfloat position[3];
GLfloat normal[3];
GLfloat texCoord[2];
};
static_assert(sizeof(MeshVertex) == 8 * sizeof(GLfloat), "MeshVertex should be tightly packed");
struct Mesh {
GLuint vbo = 0;
GLsizei vertexCount = 0;
};
static Mesh bodyMesh;
static Mesh glassMesh;
// Targa 图像文件头结构体
#pragma pack(push, 1) // 关闭结构体对齐填充
struct TargaHeader {
// 图像 ID 区长度,0 = 无
GLubyte idLength;
GLubyte colorMapType; // 0 = 无调色板
GLubyte dataTypeCode; // 图像数据类型代码 2 = 未压缩真彩图(非 RLE)
GLushort colorMapOrigin; // 调色板起始索引
GLushort colorMapLength; // 调色板颜色的数量
GLubyte colorMapDepth; // 调色板每条颜色的位数
GLushort xOrigin; // 图像在屏幕上的 X 坐标
GLushort yOrigin; // 图像在屏幕上的 Y 坐标
GLushort width; // 图像宽度
GLushort height; // 图像高度
// 每像素 24 位 = RGB 各 8 位
GLubyte bitsPerPixel;
// 0 表示自下而上存储
GLubyte imageDescriptor;
};
#pragma pack(pop) // 恢复结构体对齐填充
std::ostream& operator<<(std::ostream& os, const TargaHeader& header) {
os << "TargaHeader { "
<< "idLength=" << static_cast<int>(header.idLength) << ", "
<< "colorMapType=" << static_cast<int>(header.colorMapType) << ", "
<< "dataTypeCode=" << static_cast<int>(header.dataTypeCode) << ", "
<< "colorMapOrigin=" << header.colorMapOrigin << ", "
<< "colorMapLength=" << header.colorMapLength << ", "
<< "colorMapDepth=" << static_cast<int>(header.colorMapDepth) << ", "
<< "xOrigin=" << header.xOrigin << ", "
<< "yOrigin=" << header.yOrigin << ", "
<< "width=" << header.width << ", "
<< "height=" << header.height << ", "
<< "bitsPerPixel=" << static_cast<int>(header.bitsPerPixel) << ", "
<< "imageDescriptor=" << static_cast<int>(header.imageDescriptor)
<< " }";
return os;
}
/**
* 把每个三角形的三个角点展开成独立顶点,交错写入一条顶点流,并上传到 VBO。
* 展开后顶点数 = 三角形数 * 3(body: 3704*3 = 11112)。
*/
Mesh buildMesh(const GLfloat (*positions)[3],
const GLfloat (*normals)[3],
const GLfloat (*texCoords)[2],
const GLshort (*faces)[9],
int faceCount)
{
std::vector<MeshVertex> data;
data.reserve(static_cast<std::size_t>(faceCount) * 3);
for (int i = 0; i < faceCount; ++i) {
for (int j = 0; j < 3; ++j) {
const GLshort vi = faces[i][j];
const GLshort ni = faces[i][j + 3];
const GLshort ti = faces[i][j + 6];
MeshVertex v{};
v.position[0] = positions[vi][0];
v.position[1] = positions[vi][1];
v.position[2] = positions[vi][2];
v.normal[0] = normals[ni][0];
v.normal[1] = normals[ni][1];
v.normal[2] = normals[ni][2];
v.texCoord[0] = texCoords[ti][0];
v.texCoord[1] = texCoords[ti][1];
data.push_back(v);
}
}
Mesh mesh;
mesh.vertexCount = static_cast<GLsizei>(data.size());
glGenBuffers(1, &mesh.vbo);
glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
glBufferData(GL_ARRAY_BUFFER,
static_cast<GLsizeiptr>(data.size() * sizeof(MeshVertex)),
data.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return mesh;
}
/**
* 用顶点数组 + VBO 一次画完整个网格。
* 注意:绑定 VBO 后,gl*Pointer 的最后一个参数是缓冲区内的字节偏移,不是内存地址。
*/
void drawMesh(const Mesh& mesh)
{
if (mesh.vbo == 0 || mesh.vertexCount == 0) {
return;
}
glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, static_cast<GLsizei>(sizeof(MeshVertex)),
reinterpret_cast<const GLvoid*>(offsetof(MeshVertex, position)));
glNormalPointer(GL_FLOAT, static_cast<GLsizei>(sizeof(MeshVertex)),
reinterpret_cast<const GLvoid*>(offsetof(MeshVertex, normal)));
glTexCoordPointer(2, GL_FLOAT, static_cast<GLsizei>(sizeof(MeshVertex)),
reinterpret_cast<const GLvoid*>(offsetof(MeshVertex, texCoord)));
glDrawArrays(GL_TRIANGLES, 0, mesh.vertexCount);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void setupRc(){
glClearColor(0.0F, 0.0F, 0.5F, 1.0F);
glEnable(GL_DEPTH_TEST); // Enable depth testing for 3D rendering
glEnable(GL_CULL_FACE); // Enable face culling
glFrontFace(GL_CCW); // Define front faces as counter-clockwise
glCullFace(GL_BACK); // Cull back faces
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glGenTextures(TEXTURE_COUNT, textureObjects);
glBindTexture(GL_TEXTURE_2D, textureObjects[BODY_TEXTURE]);
TargaHeader header;
std::ifstream file("../image/body.tga", std::ios::binary);
if(file){
file.read(reinterpret_cast<char*>(&header), sizeof(TargaHeader));
}
std::vector<char> imageData(header.width * header.height * (header.bitsPerPixel / 8));
if(file){
file.read(imageData.data(), imageData.size());
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, header.width, header.height, 0, GL_BGR, GL_UNSIGNED_BYTE, imageData.data());
glGenerateMipmap(GL_TEXTURE_2D);
GLfloat fLargest;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest); // 获取最大各向异性值
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glBindTexture(GL_TEXTURE_2D, textureObjects[GLASS_TEXTURE]);
TargaHeader header2;
std::ifstream file2("../image/glass.tga", std::ios::binary);
if(file2){
file2.read(reinterpret_cast<char*>(&header2), sizeof(TargaHeader));
}
std::vector<char> imageData2(header2.width * header2.height * (header2.bitsPerPixel / 8));
if(file2){
file2.read(imageData2.data(), imageData2.size());
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, header2.width, header2.height, 0, GL_BGR, GL_UNSIGNED_BYTE, imageData2.data());
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glEnable(GL_TEXTURE_2D);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL); // 开启颜色材质功能
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE); // 设置前面材质的环境光和漫反射光由颜色控制
glMaterialfv(GL_FRONT, GL_SPECULAR, fSpecularLight); // 设置前面材质的镜面反射光
glMaterialf(GL_FRONT, GL_SHININESS, 128.0f); // 设置前面材质的高光指数
glLightfv(GL_LIGHT0, GL_AMBIENT, fAmbientLight); // 设置光源的环境光
glLightfv(GL_LIGHT0, GL_DIFFUSE, fDiffuseLight); // 设置光源的漫反射光
glLightfv(GL_LIGHT0, GL_SPECULAR, fSpecularLight); // 设置光源的镜面反射光
glLightfv(GL_LIGHT0, GL_POSITION, fLightPosition); // 设置光源位置
glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR); // 设置光照模型使用独立的镜面反射颜色
glEnable(GL_RESCALE_NORMAL); // 开启法线重缩放,用于保持法线长度一致,避免缩放物体时光照计算错误
// 一次性展开并上传到 VBO
bodyMesh = buildMesh(vertices, normals, textures, face_indicies, 3704);
glassMesh = buildMesh(verticesGlass, normalsGlass, texturesGlass, face_indiciesGlass, 352);
}
void shutdownRc(){
glDeleteBuffers(1, &bodyMesh.vbo);
glDeleteBuffers(1, &glassMesh.vbo);
glDeleteTextures(TEXTURE_COUNT, textureObjects);
}
void renderScene(){
// Rendering code goes here
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glTranslatef(0.0f, 0.0f, -3.0f); // Example translation, adjust as needed
glRotated(xRot, 1.0F, 0.0F, 0.0F);
glRotated(yRot, 0.0F, 1.0F, 0.0F);
glPushMatrix(); // Save the current matrix state
glRotated(-90.0f, 1.0F, 0.0F, 0.0F);
glBindTexture(GL_TEXTURE_2D, textureObjects[BODY_TEXTURE]); // Example binding, adjust as needed
glScalef(0.01f, 0.01f, 0.01f);
drawMesh(bodyMesh); // 一次 DrawArrays 画完机身
glPopMatrix();
glEnable(GL_BLEND); // Enable blending for transparency effects
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Set the blending function for transparency
glTranslatef(0.0f, 0.132f, 0.555f);
glBindTexture(GL_TEXTURE_2D, textureObjects[GLASS_TEXTURE]); // Example binding, adjust as needed
glScalef(0.01f, 0.01f, 0.01f);
glFrontFace(GL_CW); // Set the front face winding order for correct culling of transparent objects
drawMesh(glassMesh); // 顶点数组 + VBO 画玻璃
glFrontFace(GL_CCW); // Restore the default front face winding order after drawing transparent objects
drawMesh(glassMesh);
glDisable(GL_BLEND); // Disable blending after drawing transparent objects
glPopMatrix();
glutSwapBuffers();
}
void changeSize(const int w, int h){
if(h == 0) h = 1;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// 注意:正交投影 glOrtho(0, w, 0, h, -1, 1) 的可视 z 范围是 [-1, 1],
// 而模型被平移到 z = -3,会被整个裁掉;x/y 又是像素单位,模型坐标只有 ±1。
// 所以这里必须用透视投影(模型在 z=-3,缩放 0.01 后尺寸约 ±1)。
gluPerspective(45.0, static_cast<double>(w)/static_cast<double>(h), 1.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
/**
* 绕帧自身的 up 轴旋转(本地 Y 轴 / yaw),up 轴本身不变。
* @param angle 单位是「弧度」,不是度。正值按右手法则绕 up 轴转(LEFT 键传 +0.1 ≈ 左转 5.7°)。
*
* 公式是 Rodrigues 旋转公式在「旋转轴 ⊥ 被旋转向量」时的化简形式:
* v' = v·cosθ + (axis × v)·sinθ
* 完整形式还多一项 axis·(axis·v)·(1-cosθ),因为 up ⊥ forward 而恒为 0。
* 前提: vUp 与 vForward 互相垂直且都是单位向量,否则这个简式不成立。
*/
void specialKeys(int key, int x, int y){
switch(key){
case GLUT_KEY_UP:
xRot -= 5.7f; // Rotate up by 5.7 degrees (0.1 radians)
break;
case GLUT_KEY_DOWN:
xRot += 5.7f; // Rotate down by 5.7 degrees (0.1 radians)
break;
case GLUT_KEY_LEFT:
yRot -= 5.7f; // Rotate left by 5.7 degrees (0.1 radians)
break;
case GLUT_KEY_RIGHT:
yRot += 5.7f; // Rotate right by 5.7 degrees (0.1 radians)
break;
}
glutPostRedisplay();
}
void timerFunc(const int _){
glutPostRedisplay();
glutTimerFunc(33, timerFunc, 1); // 大约 30 FPS
}
void processMenu(int option){
switch(option){
case 1:
// Normal Point
glDisable(GL_BLEND);
glDisable(GL_LINE_SMOOTH);
glDisable(GL_POINT_SMOOTH);
glDisable(GL_TEXTURE_2D);
glDisable(GL_POINT_SPRITE);
break;
case 2:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glEnable(GL_POINT_SMOOTH);
glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glDisable(GL_TEXTURE_2D);
glDisable(GL_POINT_SPRITE);
break;
case 3:
// Point Sprites
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);
glDisable(GL_LINE_SMOOTH);
glDisable(GL_POINT_SMOOTH);
glDisable(GL_POLYGON_SMOOTH);
break;
}
glutSetWindow(mainWindowId);
glutPostRedisplay();
}
int main(int args, char** argv){
std::cout << "Starting program..." << std::endl;
glutInit(&args, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
mainWindowId = glutCreateWindow("OpenGL Window");
if(mainWindowId == 0){
throw std::runtime_error("Failed to create main window");
}
// ======= 事件处理 =======
glutDisplayFunc(renderScene);
glutReshapeFunc(changeSize);
glutSpecialFunc(specialKeys);
glutCreateMenu(processMenu); // 如果有菜单状态处理函数
glutAddMenuEntry("Normal Point", 1);
glutAddMenuEntry("Antialiased Points", 2);
glutAddMenuEntry("Point Sprites", 3);
glutAttachMenu(GLUT_RIGHT_BUTTON); // 将菜单附加到鼠标右键
// ======= 渲染循环 =======
GLint iUnits;
glGetIntegerv(GL_MAX_TEXTURE_UNITS, &iUnits);
std::cout << "Max texture units: " << iUnits << std::endl;
setupRc();
glutMainLoop();
shutdownRc();
return 0;
}
F-16 顶点数组+元素缓存
#if defined(__APPLE__) && defined(__MACH__)
#include <GLUT/glut.h>
#include <OpenGL/gl.h>
#include <OpenGL/glext.h>
#else
extern "C" {
#include <GL/freeglut.h>
}
#endif
#include <iostream>
#include <stdexcept>
#include <fstream>
#include <vector>
#include <numbers>
#include <array>
#include <cstddef>
#include <cstdint>
#include <unordered_map>
static constexpr GLfloat PI = std::numbers::pi_v<GLfloat>;
static constexpr GLint WINDOW_WIDTH = 800;
static constexpr GLint WINDOW_HEIGHT = 600;
static constexpr GLint TEXTURE_COUNT = 2;
static constexpr GLint BODY_TEXTURE = 0;
static constexpr GLint GLASS_TEXTURE = 1;
static constexpr std::array<std::string, TEXTURE_COUNT> TEXTURE_FILES = {
"../image/body.tga",
"../image/glass.tga"
};
static constexpr GLfloat fAmbientLight[] = {0.1f, 0.1f, 0.1f, 0.0f}; // 环境光
static constexpr GLfloat fDiffuseLight[] = {1.0f, 1.0f, 1.0f, 0.0f}; // 漫反射光
static constexpr GLfloat fSpecularLight[] = {0.5f, 0.5f, 0.5f, 0.0f}; // 镜面反射光
static constexpr GLfloat fLightPosition[] = {-100.0f, 100.0f, 100.0f, 1.0f}; // 光源位置
// 变量
static GLuint textureObjects[TEXTURE_COUNT];
static GLint mainWindowId = 0;
static GLfloat xRot = 0.0f; // Rotation angle around the X-axis
static GLfloat yRot = 0.0f; // Rotation angle around the Y-axis
// 引入外部的变量,这里仅仅声明一下
// body
extern GLshort face_indicies[3704][9]; // body
extern GLfloat vertices[1898][3];
extern GLfloat normals[2716][3]; // body normals
extern GLfloat textures[2925][2]; // body texture coordinates
// glass
extern GLshort face_indiciesGlass[352][9]; // glass
extern GLfloat verticesGlass[197][3]; // glass vertices
extern GLfloat normalsGlass[227][3]; // glass normals
extern GLfloat texturesGlass[227][2]; // glass texture coordinates
// ---- 顶点数组 / VBO ----
// 模型是“每个角一套索引”(v/n/t),而一次 DrawArrays 只有一条顶点流,
// 所以先把每个角展开成一个交错顶点:position + normal + uv。
struct MeshVertex {
GLfloat position[3];
GLfloat normal[3];
GLfloat texCoord[2];
};
static_assert(sizeof(MeshVertex) == 8 * sizeof(GLfloat), "MeshVertex should be tightly packed");
struct Mesh {
GLuint vbo = 0; // 去重后的唯一顶点
GLuint ibo = 0; // 索引缓冲
GLsizei vertexCount = 0; // 唯一顶点数
GLsizei indexCount = 0; // 索引数 = 三角形数 * 3
};
static Mesh bodyMesh;
static Mesh glassMesh;
// Targa 图像文件头结构体
#pragma pack(push, 1) // 关闭结构体对齐填充
struct TargaHeader {
// 图像 ID 区长度,0 = 无
GLubyte idLength;
GLubyte colorMapType; // 0 = 无调色板
GLubyte dataTypeCode; // 图像数据类型代码 2 = 未压缩真彩图(非 RLE)
GLushort colorMapOrigin; // 调色板起始索引
GLushort colorMapLength; // 调色板颜色的数量
GLubyte colorMapDepth; // 调色板每条颜色的位数
GLushort xOrigin; // 图像在屏幕上的 X 坐标
GLushort yOrigin; // 图像在屏幕上的 Y 坐标
GLushort width; // 图像宽度
GLushort height; // 图像高度
// 每像素 24 位 = RGB 各 8 位
GLubyte bitsPerPixel;
// 0 表示自下而上存储
GLubyte imageDescriptor;
};
#pragma pack(pop) // 恢复结构体对齐填充
std::ostream& operator<<(std::ostream& os, const TargaHeader& header) {
os << "TargaHeader { "
<< "idLength=" << static_cast<int>(header.idLength) << ", "
<< "colorMapType=" << static_cast<int>(header.colorMapType) << ", "
<< "dataTypeCode=" << static_cast<int>(header.dataTypeCode) << ", "
<< "colorMapOrigin=" << header.colorMapOrigin << ", "
<< "colorMapLength=" << header.colorMapLength << ", "
<< "colorMapDepth=" << static_cast<int>(header.colorMapDepth) << ", "
<< "xOrigin=" << header.xOrigin << ", "
<< "yOrigin=" << header.yOrigin << ", "
<< "width=" << header.width << ", "
<< "height=" << header.height << ", "
<< "bitsPerPixel=" << static_cast<int>(header.bitsPerPixel) << ", "
<< "imageDescriptor=" << static_cast<int>(header.imageDescriptor)
<< " }";
return os;
}
/**
* 把每个三角形的三个角点展开成独立顶点,交错写入一条顶点流,并上传到 VBO。
* 展开后顶点数 = 三角形数 * 3(body: 3704*3 = 11112)。
*/
/**
* 把“每个角一套索引”的模型展开,并按 (v, n, t) 三元组去重,
* 生成「唯一顶点数组 + 索引数组」,分别上传到 VBO / IBO。
*
* body: 11112 个角点 -> 3274 个唯一顶点;glass: 1056 -> 227。
*/
Mesh buildMesh(const char* name,
const GLfloat (*positions)[3],
const GLfloat (*normalData)[3],
const GLfloat (*texCoords)[2],
const GLshort (*faces)[9],
int faceCount)
{
const std::size_t cornerCount = static_cast<std::size_t>(faceCount) * 3;
std::vector<MeshVertex> uniqueVertices;
std::vector<GLushort> indices;
uniqueVertices.reserve(cornerCount);
indices.reserve(cornerCount);
// key = (vi << 32) | (ni << 16) | ti,三个索引都 < 65536,不会冲突
std::unordered_map<std::uint64_t, GLushort> lookup;
lookup.reserve(cornerCount);
for (int i = 0; i < faceCount; ++i) {
for (int j = 0; j < 3; ++j) {
const GLshort vi = faces[i][j];
const GLshort ni = faces[i][j + 3];
const GLshort ti = faces[i][j + 6];
const std::uint64_t key =
(static_cast<std::uint64_t>(vi) << 32) |
(static_cast<std::uint64_t>(ni) << 16) |
static_cast<std::uint64_t>(ti);
const auto it = lookup.find(key);
if (it != lookup.end()) {
indices.push_back(it->second);
continue;
}
if (uniqueVertices.size() > 0xFFFFu) {
throw std::runtime_error("Too many unique vertices for GLushort indices");
}
MeshVertex v{};
v.position[0] = positions[vi][0];
v.position[1] = positions[vi][1];
v.position[2] = positions[vi][2];
v.normal[0] = normalData[ni][0];
v.normal[1] = normalData[ni][1];
v.normal[2] = normalData[ni][2];
v.texCoord[0] = texCoords[ti][0];
v.texCoord[1] = texCoords[ti][1];
const GLushort id = static_cast<GLushort>(uniqueVertices.size());
uniqueVertices.push_back(v);
indices.push_back(id);
lookup.emplace(key, id);
}
}
Mesh mesh;
mesh.vertexCount = static_cast<GLsizei>(uniqueVertices.size());
mesh.indexCount = static_cast<GLsizei>(indices.size());
// 唯一顶点 -> VBO
glGenBuffers(1, &mesh.vbo);
glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
glBufferData(GL_ARRAY_BUFFER,
static_cast<GLsizeiptr>(uniqueVertices.size() * sizeof(MeshVertex)),
uniqueVertices.data(), GL_STATIC_DRAW);
// 索引 -> IBO
glGenBuffers(1, &mesh.ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
static_cast<GLsizeiptr>(indices.size() * sizeof(GLushort)),
indices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
std::cout << name << ": " << cornerCount << " corners -> "
<< mesh.vertexCount << " unique vertices, "
<< mesh.indexCount << " indices" << std::endl;
return mesh;
}
/**
* 用顶点数组 + VBO/IBO 一次画完整个网格。
* 注意:绑定 VBO 后,gl*Pointer 的最后一个参数是缓冲区内的字节偏移,不是内存地址。
*/
void drawMesh(const Mesh& mesh)
{
if (mesh.vbo == 0 || mesh.ibo == 0 || mesh.indexCount == 0) {
return;
}
glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.ibo);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, static_cast<GLsizei>(sizeof(MeshVertex)),
reinterpret_cast<const GLvoid*>(offsetof(MeshVertex, position)));
glNormalPointer(GL_FLOAT, static_cast<GLsizei>(sizeof(MeshVertex)),
reinterpret_cast<const GLvoid*>(offsetof(MeshVertex, normal)));
glTexCoordPointer(2, GL_FLOAT, static_cast<GLsizei>(sizeof(MeshVertex)),
reinterpret_cast<const GLvoid*>(offsetof(MeshVertex, texCoord)));
glDrawElements(GL_TRIANGLES, mesh.indexCount, GL_UNSIGNED_SHORT, nullptr);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void setupRc(){
glClearColor(0.0F, 0.0F, 0.5F, 1.0F);
glEnable(GL_DEPTH_TEST); // Enable depth testing for 3D rendering
glEnable(GL_CULL_FACE); // Enable face culling
glFrontFace(GL_CCW); // Define front faces as counter-clockwise
glCullFace(GL_BACK); // Cull back faces
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glGenTextures(TEXTURE_COUNT, textureObjects);
glBindTexture(GL_TEXTURE_2D, textureObjects[BODY_TEXTURE]);
TargaHeader header;
std::ifstream file("../image/body.tga", std::ios::binary);
if(file){
file.read(reinterpret_cast<char*>(&header), sizeof(TargaHeader));
}
std::vector<char> imageData(header.width * header.height * (header.bitsPerPixel / 8));
if(file){
file.read(imageData.data(), imageData.size());
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, header.width, header.height, 0, GL_BGR, GL_UNSIGNED_BYTE, imageData.data());
glGenerateMipmap(GL_TEXTURE_2D);
GLfloat fLargest;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest); // 获取最大各向异性值
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glBindTexture(GL_TEXTURE_2D, textureObjects[GLASS_TEXTURE]);
TargaHeader header2;
std::ifstream file2("../image/glass.tga", std::ios::binary);
if(file2){
file2.read(reinterpret_cast<char*>(&header2), sizeof(TargaHeader));
}
std::vector<char> imageData2(header2.width * header2.height * (header2.bitsPerPixel / 8));
if(file2){
file2.read(imageData2.data(), imageData2.size());
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, header2.width, header2.height, 0, GL_BGR, GL_UNSIGNED_BYTE, imageData2.data());
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glEnable(GL_TEXTURE_2D);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL); // 开启颜色材质功能
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE); // 设置前面材质的环境光和漫反射光由颜色控制
glMaterialfv(GL_FRONT, GL_SPECULAR, fSpecularLight); // 设置前面材质的镜面反射光
glMaterialf(GL_FRONT, GL_SHININESS, 128.0f); // 设置前面材质的高光指数
glLightfv(GL_LIGHT0, GL_AMBIENT, fAmbientLight); // 设置光源的环境光
glLightfv(GL_LIGHT0, GL_DIFFUSE, fDiffuseLight); // 设置光源的漫反射光
glLightfv(GL_LIGHT0, GL_SPECULAR, fSpecularLight); // 设置光源的镜面反射光
glLightfv(GL_LIGHT0, GL_POSITION, fLightPosition); // 设置光源位置
glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR); // 设置光照模型使用独立的镜面反射颜色
glEnable(GL_RESCALE_NORMAL); // 开启法线重缩放,用于保持法线长度一致,避免缩放物体时光照计算错误
// 一次性展开并上传到 VBO
bodyMesh = buildMesh("body", vertices, normals, textures, face_indicies, 3704);
glassMesh = buildMesh("glass", verticesGlass, normalsGlass, texturesGlass, face_indiciesGlass, 352);
}
void shutdownRc(){
glDeleteBuffers(1, &bodyMesh.vbo);
glDeleteBuffers(1, &bodyMesh.ibo);
glDeleteBuffers(1, &glassMesh.vbo);
glDeleteBuffers(1, &glassMesh.ibo);
glDeleteTextures(TEXTURE_COUNT, textureObjects);
}
void renderScene(){
// Rendering code goes here
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glTranslatef(0.0f, 0.0f, -3.0f); // Example translation, adjust as needed
glRotated(xRot, 1.0F, 0.0F, 0.0F);
glRotated(yRot, 0.0F, 1.0F, 0.0F);
glPushMatrix(); // Save the current matrix state
glRotated(-90.0f, 1.0F, 0.0F, 0.0F);
glBindTexture(GL_TEXTURE_2D, textureObjects[BODY_TEXTURE]); // Example binding, adjust as needed
glScalef(0.01f, 0.01f, 0.01f);
drawMesh(bodyMesh); // 一次 DrawArrays 画完机身
glPopMatrix();
glEnable(GL_BLEND); // Enable blending for transparency effects
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Set the blending function for transparency
glTranslatef(0.0f, 0.132f, 0.555f);
glBindTexture(GL_TEXTURE_2D, textureObjects[GLASS_TEXTURE]); // Example binding, adjust as needed
glScalef(0.01f, 0.01f, 0.01f);
glFrontFace(GL_CW); // Set the front face winding order for correct culling of transparent objects
drawMesh(glassMesh); // 顶点数组 + VBO 画玻璃
glFrontFace(GL_CCW); // Restore the default front face winding order after drawing transparent objects
drawMesh(glassMesh);
glDisable(GL_BLEND); // Disable blending after drawing transparent objects
glPopMatrix();
glutSwapBuffers();
}
void changeSize(const int w, int h){
if(h == 0) h = 1;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// 注意:正交投影 glOrtho(0, w, 0, h, -1, 1) 的可视 z 范围是 [-1, 1],
// 而模型被平移到 z = -3,会被整个裁掉;x/y 又是像素单位,模型坐标只有 ±1。
// 所以这里必须用透视投影(模型在 z=-3,缩放 0.01 后尺寸约 ±1)。
gluPerspective(45.0, static_cast<double>(w)/static_cast<double>(h), 1.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
/**
* 绕帧自身的 up 轴旋转(本地 Y 轴 / yaw),up 轴本身不变。
* @param angle 单位是「弧度」,不是度。正值按右手法则绕 up 轴转(LEFT 键传 +0.1 ≈ 左转 5.7°)。
*
* 公式是 Rodrigues 旋转公式在「旋转轴 ⊥ 被旋转向量」时的化简形式:
* v' = v·cosθ + (axis × v)·sinθ
* 完整形式还多一项 axis·(axis·v)·(1-cosθ),因为 up ⊥ forward 而恒为 0。
* 前提: vUp 与 vForward 互相垂直且都是单位向量,否则这个简式不成立。
*/
void specialKeys(int key, int x, int y){
switch(key){
case GLUT_KEY_UP:
xRot -= 5.7f; // Rotate up by 5.7 degrees (0.1 radians)
break;
case GLUT_KEY_DOWN:
xRot += 5.7f; // Rotate down by 5.7 degrees (0.1 radians)
break;
case GLUT_KEY_LEFT:
yRot -= 5.7f; // Rotate left by 5.7 degrees (0.1 radians)
break;
case GLUT_KEY_RIGHT:
yRot += 5.7f; // Rotate right by 5.7 degrees (0.1 radians)
break;
}
glutPostRedisplay();
}
void timerFunc(const int _){
glutPostRedisplay();
glutTimerFunc(33, timerFunc, 1); // 大约 30 FPS
}
void processMenu(int option){
switch(option){
case 1:
// Normal Point
glDisable(GL_BLEND);
glDisable(GL_LINE_SMOOTH);
glDisable(GL_POINT_SMOOTH);
glDisable(GL_TEXTURE_2D);
glDisable(GL_POINT_SPRITE);
break;
case 2:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glEnable(GL_POINT_SMOOTH);
glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glDisable(GL_TEXTURE_2D);
glDisable(GL_POINT_SPRITE);
break;
case 3:
// Point Sprites
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);
glDisable(GL_LINE_SMOOTH);
glDisable(GL_POINT_SMOOTH);
glDisable(GL_POLYGON_SMOOTH);
break;
}
glutSetWindow(mainWindowId);
glutPostRedisplay();
}
int main(int args, char** argv){
std::cout << "Starting program..." << std::endl;
glutInit(&args, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
mainWindowId = glutCreateWindow("OpenGL Window");
if(mainWindowId == 0){
throw std::runtime_error("Failed to create main window");
}
// ======= 事件处理 =======
glutDisplayFunc(renderScene);
glutReshapeFunc(changeSize);
glutSpecialFunc(specialKeys);
glutCreateMenu(processMenu); // 如果有菜单状态处理函数
glutAddMenuEntry("Normal Point", 1);
glutAddMenuEntry("Antialiased Points", 2);
glutAddMenuEntry("Point Sprites", 3);
glutAttachMenu(GLUT_RIGHT_BUTTON); // 将菜单附加到鼠标右键
// ======= 渲染循环 =======
GLint iUnits;
glGetIntegerv(GL_MAX_TEXTURE_UNITS, &iUnits);
std::cout << "Max texture units: " << iUnits << std::endl;
setupRc();
glutMainLoop();
shutdownRc();
return 0;
}
F-16 + 天空盒
#if defined(__APPLE__) && defined(__MACH__)
#include <GLUT/glut.h>
#include <OpenGL/gl.h>
#else
extern "C" {
#include <GL/freeglut.h>
}
#endif
#include <iostream>
#include <stdexcept>
#include <array>
#include <string>
#include <unordered_map>
#include <fstream>
#include <vector>
#include <numbers>
static constexpr GLfloat PI = std::numbers::pi_v<GLfloat>;
static constexpr GLint WINDOW_WIDTH = 800;
static constexpr GLint WINDOW_HEIGHT = 600;
static constexpr GLint CUBE_FACES_COUNT = 6;
static constexpr std::array<std::string, CUBE_FACES_COUNT> CUBE_FACES = {
"../image/pos_x.tga",
"../image/neg_x.tga",
"../image/pos_y.tga",
"../image/neg_y.tga",
"../image/pos_z.tga",
"../image/neg_z.tga"
};
static constexpr GLint CUBE[CUBE_FACES_COUNT] = {
GL_TEXTURE_CUBE_MAP_POSITIVE_X,
GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
};
static constexpr GLuint NUM_TEXTURES = 3;
static constexpr GLuint CUBE_MAP = 0;
static constexpr GLuint BODY_TEXTURES = 1;
static constexpr GLuint GLASS_TEXTURES = 2;
static constexpr GLfloat fAmbientLight[] = { 0.075f, 0.075f, 0.075f, 0.0f }; // 环境光
static constexpr GLfloat fDiffuseLight[] = { 1.0f, 1.0f, 1.0f, 0.0f }; // 漫反射光
static constexpr GLfloat fSpecularLight[] = { 0.25f, 0.25f, 0.25f, 0.0f }; // 镜面反射光
static constexpr GLfloat fLightPosition[] = { -50.0f, 100.0f, 100.0f, 1.0f }; // 光源位置
struct GLFrame {
GLfloat vLocation[3]; // 位置 -> move x, y, z
GLfloat vUp[3]; // 上方向 -> y
GLfloat vForward[3]; // 前方向 -> z x-> 通过 yz叉积计算 -> 归一化为单位向量
};
// Targa 图像文件头结构体
#pragma pack(push, 1) // 关闭结构体对齐填充
struct TargaHeader {
// 图像 ID 区长度,0 = 无
GLubyte idLength;
GLubyte colorMapType; // 0 = 无调色板
GLubyte dataTypeCode; // 图像数据类型代码 2 = 未压缩真彩图(非 RLE)
GLushort colorMapOrigin; // 调色板起始索引
GLushort colorMapLength; // 调色板颜色的数量
GLubyte colorMapDepth; // 调色板每条颜色的位数
GLushort xOrigin; // 图像在屏幕上的 X 坐标
GLushort yOrigin; // 图像在屏幕上的 Y 坐标
GLushort width; // 图像宽度
GLushort height; // 图像高度
// 每像素 24 位 = RGB 各 8 位
GLubyte bitsPerPixel;
// 0 表示自下而上存储
GLubyte imageDescriptor;
};
#pragma pack(pop) // 恢复结构体对齐填充
std::ostream& operator<<(std::ostream& os, const TargaHeader& header) {
os << "TargaHeader { "
<< "idLength=" << static_cast<int>(header.idLength) << ", "
<< "colorMapType=" << static_cast<int>(header.colorMapType) << ", "
<< "dataTypeCode=" << static_cast<int>(header.dataTypeCode) << ", "
<< "colorMapOrigin=" << header.colorMapOrigin << ", "
<< "colorMapLength=" << header.colorMapLength << ", "
<< "colorMapDepth=" << static_cast<int>(header.colorMapDepth) << ", "
<< "xOrigin=" << header.xOrigin << ", "
<< "yOrigin=" << header.yOrigin << ", "
<< "width=" << header.width << ", "
<< "height=" << header.height << ", "
<< "bitsPerPixel=" << static_cast<int>(header.bitsPerPixel) << ", "
<< "imageDescriptor=" << static_cast<int>(header.imageDescriptor)
<< " }";
return os;
}
static GLFrame frameCamera;
static GLuint textureObjects[NUM_TEXTURES];
// 引入外部的变量,这里仅仅声明一下
// body
extern GLshort face_indicies[3704][9]; // body
extern GLfloat vertices[1898][3];
extern GLfloat normals[2716][3]; // body normals
extern GLfloat textures[2925][2]; // body texture coordinates
// glass
extern GLshort face_indiciesGlass[352][9]; // glass
extern GLfloat verticesGlass[197][3]; // glass vertices
extern GLfloat normalsGlass[227][3]; // glass normals
extern GLfloat texturesGlass[227][2]; // glass texture coordinates
// ---- 顶点数组 / VBO ----
// 模型是“每个角一套索引”(v/n/t),而一次 DrawArrays 只有一条顶点流,
// 所以先把每个角展开成一个交错顶点:position + normal + uv。
struct MeshVertex {
GLfloat position[3];
GLfloat normal[3];
GLfloat texCoord[2];
};
static_assert(sizeof(MeshVertex) == 8 * sizeof(GLfloat), "MeshVertex should be tightly packed");
struct Mesh {
GLuint vbo = 0; // 去重后的唯一顶点
GLuint ibo = 0; // 索引缓冲
GLsizei vertexCount = 0; // 唯一顶点数
GLsizei indexCount = 0; // 索引数 = 三角形数 * 3
};
// 参考实现 thundergl.cpp 在 SetupRC 里对两个网格都做了 Scale(0.01f):
// 原始模型机身长 225 个单位,缩到 2.25 才会和"天空盒 50 / 相机抬 20 / 模型放 -3"这套参数匹配。
// 注意必须烘进顶点里(而不是画的时候 glScalef),否则玻璃罩的平移量会被一起缩放。
static constexpr GLfloat MODEL_SCALE = 0.01F;
static Mesh bodyMesh;
static Mesh glassMesh;
static GLfloat yRot = 0.0f;
Mesh buildMesh(const char* name,
const GLfloat (*positions)[3],
const GLfloat (*normalData)[3],
const GLfloat (*texCoords)[2],
const GLshort (*faces)[9],
int faceCount);
void gltInitFrame(GLFrame *pFrame) {
pFrame->vLocation[0] = 0.0f;
pFrame->vLocation[1] = 0.0f;
pFrame->vLocation[2] = 0.0f;
pFrame->vUp[0] = 0.0f;
pFrame->vUp[1] = 1.0f;
pFrame->vUp[2] = 0.0f;
pFrame->vForward[0] = 0.0f;
pFrame->vForward[1] = 0.0f;
pFrame->vForward[2] = -1.0f; // 为什么是-1?
}
void setupRc(){
gltInitFrame(&frameCamera);
frameCamera.vLocation[1] = 20.0F; // 对应参考实现的 frameCamera.MoveUp(20.0f)
glCullFace(GL_BACK); // 指定要剔除的面为背面
glFrontFace(GL_CCW); // 指定顶点的逆时针顺序为正面
glEnable(GL_CULL_FACE); // 启用面剔除
glEnable(GL_DEPTH_TEST); // 启用深度测试
glGenTextures(NUM_TEXTURES, textureObjects);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureObjects[CUBE_MAP]);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
for(int i = 0; i < CUBE_FACES_COUNT; i++){
std::ifstream file(CUBE_FACES[i], std::ios::binary);
if(!file){
throw std::runtime_error("Failed to open texture file: " + std::string(CUBE_FACES[i]));
}
TargaHeader targaHeader;
file.read(reinterpret_cast<char*>(&targaHeader), sizeof(TargaHeader));
if(!file){
throw std::runtime_error("Failed to read Targa header from file: " + std::string(CUBE_FACES[i]));
}
std::cout << "tga file: " << CUBE_FACES[i] << ", header: " << targaHeader << std::endl;
const std::size_t imageSize = targaHeader.width * targaHeader.height * (targaHeader.bitsPerPixel / 8);
std::vector<char> imageData(imageSize);
file.read(imageData.data(), imageSize);
if(!file){
throw std::runtime_error("Failed to read image data from file: " + std::string(CUBE_FACES[i]));
}
glTexImage2D(CUBE[i], 0, GL_RGB, targaHeader.width, targaHeader.height, 0, GL_BGR, GL_UNSIGNED_BYTE, imageData.data());
}
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP);
glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP);
glEnable(GL_TEXTURE_CUBE_MAP);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// body
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureObjects[BODY_TEXTURES]);
std::ifstream file1("../image/body.tga", std::ios::binary);
TargaHeader header1;
if(!file1){
throw std::runtime_error("read body error...");
}
file1.read(reinterpret_cast<char*>(&header1), sizeof(TargaHeader));
if(!file1) {
throw std::runtime_error("read body error1...");
}
std::vector<char> imageData1(header1.width * header1.height * (header1.bitsPerPixel / 8));
file1.read(imageData1.data(), imageData1.size());
if(!file1){
throw std::runtime_error("read body error2...");
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, header1.width, header1.height, 0, GL_BGR, GL_UNSIGNED_BYTE, imageData1.data());
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// 各向异性过滤是扩展:不支持时上面的查询会失败、fLargest 保持 0,
// 而 GL_TEXTURE_MAX_ANISOTROPY_EXT 只接受 >= 1 的值,直接传 0 会报 GL_INVALID_VALUE
GLfloat fLargest = 0.0f;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest);
std::cout << "Max anisotropy: " << fLargest << std::endl;
if (fLargest >= 1.0F) {
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest);
}
glBindTexture(GL_TEXTURE_2D, textureObjects[GLASS_TEXTURES]);
std::ifstream file2("../image/glass.tga", std::ios::binary);
TargaHeader header2;
if(!file2){
throw std::runtime_error("read glass error...");
}
file2.read(reinterpret_cast<char*>(&header2), sizeof(TargaHeader));
if(!file2) {
throw std::runtime_error("read glass error1...");
}
std::vector<char> imageData2(header2.width * header2.height * (header2.bitsPerPixel / 8));
file2.read(imageData2.data(), imageData2.size());
if(!file2){
throw std::runtime_error("read glass error2...");
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, header2.width, header2.height, 0, GL_BGR, GL_UNSIGNED_BYTE, imageData2.data());
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
if (fLargest >= 1.0F) {
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest);
}
glActiveTexture(GL_TEXTURE0);
glEnable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// 开启灯光
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_AMBIENT, fAmbientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, fDiffuseLight);
glLightfv(GL_LIGHT0, GL_SPECULAR, fSpecularLight);
glLightfv(GL_LIGHT0, GL_POSITION, fLightPosition);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
glMaterialfv(GL_FRONT, GL_SPECULAR, fDiffuseLight);
glMaterialf(GL_FRONT, GL_SHININESS, 128.0f);
// 参考实现还有这两句,缺了会显得更「平」:
// 全局环境光;镜面高光不参与纹理调制(高光直接叠加在贴图之上)
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, fAmbientLight);
glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
glEnable(GL_RESCALE_NORMAL); // 开启法线重缩放,用于保持法线长度一致,避免缩放物体时光照计算错误
// 一次性展开并上传到 VBO
bodyMesh = buildMesh("body", vertices, normals, textures, face_indicies, 3704);
glassMesh = buildMesh("glass", verticesGlass, normalsGlass, texturesGlass, face_indiciesGlass, 352);
}
void shutdownRc(){
std::cout << "Shutting down rendering context..." << std::endl;
glDeleteBuffers(1, &bodyMesh.vbo);
glDeleteBuffers(1, &bodyMesh.ibo);
glDeleteBuffers(1, &glassMesh.vbo);
glDeleteBuffers(1, &glassMesh.ibo);
glDeleteTextures(NUM_TEXTURES, textureObjects);
}
void drawSkyBox(){
// 参考实现是 50;模型按 0.01 缩放后机身只有 2.25 长,50 够用
constexpr GLfloat SIZE = 50.0F; // Skybox size
glBegin(GL_QUADS);
// neg x
glMultiTexCoord3f(GL_TEXTURE1, -1.0F, -1.0F, 1.0F);
glVertex3f(-SIZE, -SIZE, SIZE);
glMultiTexCoord3f(GL_TEXTURE1, -1.0F, -1.0F, -1.0F);
glVertex3f(-SIZE, -SIZE, -SIZE);
glMultiTexCoord3f(GL_TEXTURE1, -1.0F, 1.0F, -1.0F);
glVertex3f(-SIZE, SIZE, -SIZE);
glMultiTexCoord3f(GL_TEXTURE1, -1.0F, 1.0F, 1.0F);
glVertex3f(-SIZE, SIZE, SIZE);
// pos x
glMultiTexCoord3f(GL_TEXTURE1, 1.0F, -1.0F, -1.0F);
glVertex3f(SIZE, -SIZE, -SIZE);
glMultiTexCoord3f(GL_TEXTURE1, 1.0F, -1.0F, 1.0F);
glVertex3f(SIZE, -SIZE, SIZE);
glMultiTexCoord3f(GL_TEXTURE1, 1.0F, 1.0F, 1.0F);
glVertex3f(SIZE, SIZE, SIZE);
glMultiTexCoord3f(GL_TEXTURE1, 1.0F, 1.0F, -1.0F);
glVertex3f(SIZE, SIZE, -SIZE);
// neg z
glMultiTexCoord3f(GL_TEXTURE1, -1.0F, -1.0F, -1.0F);
glVertex3f(-SIZE, -SIZE, -SIZE);
glMultiTexCoord3f(GL_TEXTURE1, 1.0F, -1.0F, -1.0F);
glVertex3f( SIZE, -SIZE, -SIZE);
glMultiTexCoord3f(GL_TEXTURE1, 1.0F, 1.0F, -1.0F);
glVertex3f( SIZE, SIZE, -SIZE);
glMultiTexCoord3f(GL_TEXTURE1, -1.0F, 1.0F, -1.0F);
glVertex3f(-SIZE, SIZE, -SIZE);
// pos z
glMultiTexCoord3f(GL_TEXTURE1, 1.0F, -1.0F, 1.0F);
glVertex3f( SIZE, -SIZE, SIZE);
glMultiTexCoord3f(GL_TEXTURE1, -1.0F, -1.0F, 1.0F);
glVertex3f(-SIZE, -SIZE, SIZE);
glMultiTexCoord3f(GL_TEXTURE1, -1.0F, 1.0F, 1.0F);
glVertex3f(-SIZE, SIZE, SIZE);
glMultiTexCoord3f(GL_TEXTURE1, 1.0F, 1.0F, 1.0F);
glVertex3f( SIZE, SIZE, SIZE);
// pos y
glMultiTexCoord3f(GL_TEXTURE1, -1.0F, 1.0F, 1.0F);
glVertex3f(-SIZE, SIZE, SIZE);
glMultiTexCoord3f(GL_TEXTURE1, -1.0F, 1.0F, -1.0F);
glVertex3f(-SIZE, SIZE, -SIZE);
glMultiTexCoord3f(GL_TEXTURE1, 1.0F, 1.0F, -1.0F);
glVertex3f( SIZE, SIZE, -SIZE);
glMultiTexCoord3f(GL_TEXTURE1, 1.0F, 1.0F, 1.0F);
glVertex3f( SIZE, SIZE, SIZE);
// neg y
glMultiTexCoord3f(GL_TEXTURE1, -1.0F, -1.0F, -1.0F);
glVertex3f(-SIZE, -SIZE, -SIZE);
glMultiTexCoord3f(GL_TEXTURE1, -1.0F, -1.0F, 1.0F);
glVertex3f(-SIZE, -SIZE, SIZE);
glMultiTexCoord3f(GL_TEXTURE1, 1.0F, -1.0F, 1.0F);
glVertex3f( SIZE, -SIZE, SIZE);
glMultiTexCoord3f(GL_TEXTURE1, 1.0F, -1.0F, -1.0F);
glVertex3f( SIZE, -SIZE, -SIZE);
glEnd();
}
void drawSphere(const GLfloat radius, const GLint slices, const GLint stacks) {
const GLfloat sliceStep = 2.0F * PI / static_cast<GLfloat>(slices);
const GLfloat stackStep = PI / static_cast<GLfloat>(stacks);
for (GLint i = 0; i < stacks; ++i) {
const GLfloat stackAngle1 = i * stackStep;
const GLfloat stackAngle2 = (i + 1) * stackStep;
glBegin(GL_TRIANGLE_STRIP);
for (GLint j = 0; j <= slices; ++j) {
const GLfloat sliceAngle1 = j * sliceStep;
const GLfloat sliceAngle2 = (j + 1) * sliceStep;
const GLfloat nx1 = std::sin(stackAngle1) * std::cos(sliceAngle1);
const GLfloat ny1 = std::cos(stackAngle1);
const GLfloat nz1 = std::sin(stackAngle1) * std::sin(sliceAngle1);
const GLfloat x1 = radius * nx1;
const GLfloat y1 = radius * ny1;
const GLfloat z1 = radius * nz1;
const GLfloat nx2 = std::sin(stackAngle2) * std::cos(sliceAngle1);
const GLfloat ny2 = std::cos(stackAngle2);
const GLfloat nz2 = std::sin(stackAngle2) * std::sin(sliceAngle1);
const GLfloat x2 = radius * nx2;
const GLfloat y2 = radius * ny2;
const GLfloat z2 = radius * nz2;
// 每个 j 先发下圈顶点、再发上圈顶点,三角形绕序从球外看才是逆时针(GL_CCW)。
// 若「先上后下」,整颗球的外表面会被当作背面剔除,实际渲染的是远侧内表面,
// 反射向量在竖直方向上是反的,天空就会被贴到球的下半部分。
glNormal3f(nx2, ny2, nz2);
glTexCoord2f(static_cast<GLfloat>(j) / slices,
1.0F - static_cast<GLfloat>(i + 1) / stacks);
glVertex3f(x2, y2, z2);
glNormal3f(nx1, ny1, nz1);
glTexCoord2f(static_cast<GLfloat>(j) / slices, // 左下角
1.0F - static_cast<GLfloat>(i) / stacks);
glVertex3f(x1, y1, z1);
}
glEnd();
}
}
void drawTorus(const GLfloat majorRadius, const GLfloat minorRadius, const int numMajor, const int numMinor) {
const GLfloat majorStep = 2.0F * PI / static_cast<GLfloat>(numMajor);
const GLfloat minorStep = 2.0F * PI / static_cast<GLfloat>(numMinor);
for (int i = 0; i < numMajor; ++i) {
const GLfloat u0 = i * majorStep;
const GLfloat u1 = u0 + majorStep;
glBegin(GL_TRIANGLE_STRIP);
for (int j = 0; j <= numMinor; ++j) {
const GLfloat v0 = j * minorStep;
// 计算两个顶点的坐标
const GLfloat n0[3] = {
std::cos(v0) * std::cos(u0),
std::cos(v0) * std::sin(u0),
std::sin(v0)
};
const GLfloat x00 = (majorRadius + minorRadius * std::cos(v0)) * std::cos(u0);
const GLfloat y00 = (majorRadius + minorRadius * std::cos(v0)) * std::sin(u0);
const GLfloat z00 = minorRadius * std::sin(v0);
const GLfloat n1[3] = {
std::cos(v0) * std::cos(u1),
std::cos(v0) * std::sin(u1),
std::sin(v0)
};
const GLfloat x01 = (majorRadius + minorRadius * std::cos(v0)) * std::cos(u1);
const GLfloat y01 = (majorRadius + minorRadius * std::cos(v0)) * std::sin(u1);
const GLfloat z01 = minorRadius * std::sin(v0);
glNormal3f(n0[0], n0[1], n0[2]);
glTexCoord2f(static_cast<GLfloat>(j) / numMinor, static_cast<GLfloat>(i) / numMajor);
glVertex3f(x00, y00, z00);
glNormal3f(n1[0], n1[1], n1[2]);
glTexCoord2f(static_cast<GLfloat>(j) / numMinor, static_cast<GLfloat>(i + 1) / numMajor);
glVertex3f(x01, y01, z01);
}
glEnd();
}
}
/**
* 把每个三角形的三个角点展开成独立顶点,交错写入一条顶点流,并上传到 VBO。
* 展开后顶点数 = 三角形数 * 3(body: 3704*3 = 11112)。
*/
/**
* 把“每个角一套索引”的模型展开,并按 (v, n, t) 三元组去重,
* 生成「唯一顶点数组 + 索引数组」,分别上传到 VBO / IBO。
*
* body: 11112 个角点 -> 3274 个唯一顶点;glass: 1056 -> 227。
*/
Mesh buildMesh(const char* name,
const GLfloat (*positions)[3],
const GLfloat (*normalData)[3],
const GLfloat (*texCoords)[2],
const GLshort (*faces)[9],
int faceCount)
{
const std::size_t cornerCount = static_cast<std::size_t>(faceCount) * 3;
std::vector<MeshVertex> uniqueVertices;
std::vector<GLushort> indices;
uniqueVertices.reserve(cornerCount);
indices.reserve(cornerCount);
// key = (vi << 32) | (ni << 16) | ti,三个索引都 < 65536,不会冲突
std::unordered_map<std::uint64_t, GLushort> lookup;
lookup.reserve(cornerCount);
for (int i = 0; i < faceCount; ++i) {
for (int j = 0; j < 3; ++j) {
const GLshort vi = faces[i][j];
const GLshort ni = faces[i][j + 3];
const GLshort ti = faces[i][j + 6];
const std::uint64_t key =
(static_cast<std::uint64_t>(vi) << 32) |
(static_cast<std::uint64_t>(ni) << 16) |
static_cast<std::uint64_t>(ti);
const auto it = lookup.find(key);
if (it != lookup.end()) {
indices.push_back(it->second);
continue;
}
if (uniqueVertices.size() > 0xFFFFu) {
throw std::runtime_error("Too many unique vertices for GLushort indices");
}
MeshVertex v{};
v.position[0] = positions[vi][0] * MODEL_SCALE;
v.position[1] = positions[vi][1] * MODEL_SCALE;
v.position[2] = positions[vi][2] * MODEL_SCALE;
v.normal[0] = normalData[ni][0];
v.normal[1] = normalData[ni][1];
v.normal[2] = normalData[ni][2];
v.texCoord[0] = texCoords[ti][0];
v.texCoord[1] = texCoords[ti][1];
const GLushort id = static_cast<GLushort>(uniqueVertices.size());
uniqueVertices.push_back(v);
indices.push_back(id);
lookup.emplace(key, id);
}
}
Mesh mesh;
mesh.vertexCount = static_cast<GLsizei>(uniqueVertices.size());
mesh.indexCount = static_cast<GLsizei>(indices.size());
// 唯一顶点 -> VBO
glGenBuffers(1, &mesh.vbo);
glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
glBufferData(GL_ARRAY_BUFFER,
static_cast<GLsizeiptr>(uniqueVertices.size() * sizeof(MeshVertex)),
uniqueVertices.data(), GL_STATIC_DRAW);
// 索引 -> IBO
glGenBuffers(1, &mesh.ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
static_cast<GLsizeiptr>(indices.size() * sizeof(GLushort)),
indices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
std::cout << name << ": " << cornerCount << " corners -> "
<< mesh.vertexCount << " unique vertices, "
<< mesh.indexCount << " indices" << std::endl;
return mesh;
}
/**
* 用顶点数组 + VBO/IBO 一次画完整个网格。
* 注意:绑定 VBO 后,gl*Pointer 的最后一个参数是缓冲区内的字节偏移,不是内存地址。
*/
void drawMesh(const Mesh& mesh)
{
if (mesh.vbo == 0 || mesh.ibo == 0 || mesh.indexCount == 0) {
return;
}
glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.ibo);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, static_cast<GLsizei>(sizeof(MeshVertex)),
reinterpret_cast<const GLvoid*>(offsetof(MeshVertex, position)));
glNormalPointer(GL_FLOAT, static_cast<GLsizei>(sizeof(MeshVertex)),
reinterpret_cast<const GLvoid*>(offsetof(MeshVertex, normal)));
glTexCoordPointer(2, GL_FLOAT, static_cast<GLsizei>(sizeof(MeshVertex)),
reinterpret_cast<const GLvoid*>(offsetof(MeshVertex, texCoord)));
glDrawElements(GL_TRIANGLES, mesh.indexCount, GL_UNSIGNED_SHORT, nullptr);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void drawThunderBird(){
glActiveTexture(GL_TEXTURE1);
glDisable(GL_TEXTURE_CUBE_MAP);
glActiveTexture(GL_TEXTURE0);
glPushMatrix();
glRotatef(-90.0f, 1.0f, 0.0f, 0.0f);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glBindTexture(GL_TEXTURE_2D, textureObjects[BODY_TEXTURES]);
drawMesh(bodyMesh);
glPopMatrix();
glActiveTexture(GL_TEXTURE1);
glEnable(GL_TEXTURE_CUBE_MAP);
glActiveTexture(GL_TEXTURE0);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor4f(1.0f, 1.0f, 1.0f, 0.25f);
glBindTexture(GL_TEXTURE_2D, textureObjects[GLASS_TEXTURES]);
glDepthMask(GL_FALSE); // 透明物体不写深度:否则背面那趟会把正面的混合挡掉
glTranslatef(0.0f, 0.132f, 0.555f);
glFrontFace(GL_CW);
drawMesh(glassMesh);
glFrontFace(GL_CCW); // 恢复默认的面剔除方向
drawMesh(glassMesh);
glDepthMask(GL_TRUE);
glDisable(GL_BLEND);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // 别把 0.25 的 alpha 泄漏给后面的绘制
}
/**
* 视图矩阵 = 上面的逆:旋转转置 + 平移取负
* 把世界挪到相机眼前
*/
void gltApplyCameraTransform(const GLFrame *pCamera) {
// 算出相机右向量 (Right vector)
GLfloat r[3];
r[0] = pCamera->vForward[1] * pCamera->vUp[2] - pCamera->vForward[2] * pCamera->vUp[1];
r[1] = pCamera->vForward[2] * pCamera->vUp[0] - pCamera->vForward[0] * pCamera->vUp[2];
r[2] = pCamera->vForward[0] * pCamera->vUp[1] - pCamera->vForward[1] * pCamera->vUp[0];
// 构建视图矩阵 (View matrix) 列主序 (column-major order)
GLfloat m[16]; // 同样的轴,改填「行」,即转置
m[0]=r[0]; m[4]=r[1]; m[8] =r[2]; m[12]=0.0F;
m[1]=pCamera->vUp[0]; m[5]=pCamera->vUp[1]; m[9] =pCamera->vUp[2]; m[13]=0.0F;
m[2]=-pCamera->vForward[0]; m[6]=-pCamera->vForward[1]; m[10]=-pCamera->vForward[2]; m[14]=0.0F;
m[3]=0.0F; m[7]=0.0F; m[11]=0.0F; m[15]=1.0F;
glMultMatrixf(m);
glTranslatef(-pCamera->vLocation[0], -pCamera->vLocation[1], -pCamera->vLocation[2]);
}
/**
* 物体矩阵 = 相机矩阵的逆:旋转的轴填「列」(不平移取负,平移直接进第 4 列)
* 四列依次是: right、up、-forward、location
* 物体→世界
*/
void gltApplyActorTransform(const GLFrame *frame){
// 算出物体的右向量 (Right vector)
GLfloat r[3];
r[0] = frame->vForward[1] * frame->vUp[2] - frame->vForward[2] * frame->vUp[1];
r[1] = frame->vForward[2] * frame->vUp[0] - frame->vForward[0] * frame->vUp[2];
r[2] = frame->vForward[0] * frame->vUp[1] - frame->vForward[1] * frame->vUp[0];
// 构建物体矩阵 (Model matrix) 列主序 (column-major order)
// 第三列必须是 -forward: right × up = -forward,这样才是右手系(行列式 +1);
// 若填 +forward 则行列式为负,几何体会被镜像,开着 GL_CULL_FACE 时整个模型会被剔除
GLfloat m[16];
m[0]=r[0]; m[4]=frame->vUp[0]; m[8] =-frame->vForward[0]; m[12]=frame->vLocation[0];
m[1]=r[1]; m[5]=frame->vUp[1]; m[9] =-frame->vForward[1]; m[13]=frame->vLocation[1];
m[2]=r[2]; m[6]=frame->vUp[2]; m[10]=-frame->vForward[2]; m[14]=frame->vLocation[2];
m[3]=0.0F; m[7]=0.0F; m[11]=0.0F; m[15]=1.0F;
glMultMatrixf(m);
}
/**
* 反射贴图用的纹理矩阵:相机视图旋转的逆(旋转矩阵的逆就是转置)。
*
* GL_REFLECTION_MAP 生成的 (s,t,r) 已经是 eye space 的方向,
* 而 cubemap 的面(以及天空盒)是按世界方向对齐的,所以需要转回 world space:
* R_world = V⁻¹ · R_eye = Vᵀ · R_eye
* 环境贴图视为无限远,只取旋转部分,不平移。
*
* 注意不要直接拿视图矩阵 V(world → eye)来乘:那样相机每旋转 θ,
* 反射方向会被多转一次,和天空盒对不上。
*/
void gltGetCameraInverseMatrix(const GLFrame *pCamera, GLfloat *m){
// 算出相机右向量 (Right vector)
GLfloat r[3];
r[0] = pCamera->vForward[1] * pCamera->vUp[2] - pCamera->vForward[2] * pCamera->vUp[1];
r[1] = pCamera->vForward[2] * pCamera->vUp[0] - pCamera->vForward[0] * pCamera->vUp[2];
r[2] = pCamera->vForward[0] * pCamera->vUp[1] - pCamera->vForward[1] * pCamera->vUp[0];
// V 的三行分别是 right、up、-forward;转置后它们变成三列。
// 列主序数组里直接按「列 = V 原来的行」填入即可。
m[0]=r[0]; m[4]=pCamera->vUp[0]; m[8] =-pCamera->vForward[0]; m[12]=0.0F;
m[1]=r[1]; m[5]=pCamera->vUp[1]; m[9] =-pCamera->vForward[1]; m[13]=0.0F;
m[2]=r[2]; m[6]=pCamera->vUp[2]; m[10]=-pCamera->vForward[2]; m[14]=0.0F;
m[3]=0.0F; m[7]=0.0F; m[11]=0.0F; m[15]=1.0F;
}
void renderScene(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// ---- 天空盒:只跟随相机的「旋转」,不跟随平移,这样相机飞到哪儿都被罩在正中 ----
GLFrame skyFrame = frameCamera;
skyFrame.vLocation[0] = 0.0F;
skyFrame.vLocation[1] = 0.0F;
skyFrame.vLocation[2] = 0.0F;
glPushMatrix();
glLoadIdentity();
gltApplyCameraTransform(&skyFrame);
glActiveTexture(GL_TEXTURE0);
glDisable(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE1);
glEnable(GL_TEXTURE_CUBE_MAP);
glDisable(GL_TEXTURE_GEN_S);
glDisable(GL_TEXTURE_GEN_T);
glDisable(GL_TEXTURE_GEN_R);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glDepthMask(GL_FALSE); // 天空盒只当背景:不写深度,才不会挡住后面的模型
drawSkyBox();
glDepthMask(GL_TRUE);
glEnable(GL_TEXTURE_GEN_S);
glEnable(GL_TEXTURE_GEN_T);
glEnable(GL_TEXTURE_GEN_R);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glDisable(GL_TEXTURE_CUBE_MAP);
glActiveTexture(GL_TEXTURE0);
glEnable(GL_TEXTURE_2D);
glPopMatrix(); // 天空盒的 modelview 收尾
glPushMatrix();
gltApplyCameraTransform(&frameCamera); // 真正的相机(含平移)
// ---- 反射用的纹理矩阵:作用于 1 号单元,push / pop 必须配对 ----
glActiveTexture(GL_TEXTURE1);
glMatrixMode(GL_TEXTURE);
glPushMatrix(); // 纹理矩阵栈
// 反射坐标在 eye space,用相机旋转的逆转回 world space,才能和天空盒对齐
GLfloat cameraInverse[16];
gltGetCameraInverseMatrix(&frameCamera, cameraInverse);
glMultMatrixf(cameraInverse);
glMatrixMode(GL_MODELVIEW);
glActiveTexture(GL_TEXTURE0);
glPushMatrix(); // 模型的 modelview
yRot += 0.1f;
if(yRot > 360.0f) yRot = 0.0f;
glTranslatef(0.0f, 19.6f, -3.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);
drawThunderBird();
glPopMatrix();
// 必须回到 TEXTURE 模式再 pop,否则弹掉的是 modelview
glActiveTexture(GL_TEXTURE1);
glMatrixMode(GL_TEXTURE);
glPopMatrix(); // 纹理矩阵栈
glMatrixMode(GL_MODELVIEW);
glActiveTexture(GL_TEXTURE0);
glPopMatrix();
glutSwapBuffers();
}
void changeSize(const int w, int h){
if(h == 0) h = 1;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(35.0, static_cast<double>(w)/static_cast<double>(h), 1.0, 1000.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void gltMoveFrameForward(GLFrame* frame, const GLfloat distance){
frame->vLocation[0] += frame->vForward[0] * distance;
frame->vLocation[1] += frame->vForward[1] * distance;
frame->vLocation[2] += frame->vForward[2] * distance;
}
/**
* 绕帧自身的 up 轴旋转(本地 Y 轴 / yaw),up 轴本身不变。
* @param angle 单位是「弧度」,不是度。正值按右手法则绕 up 轴转(LEFT 键传 +0.1 ≈ 左转 5.7°)。
*
* 公式是 Rodrigues 旋转公式在「旋转轴 ⊥ 被旋转向量」时的化简形式:
* v' = v·cosθ + (axis × v)·sinθ
* 完整形式还多一项 axis·(axis·v)·(1-cosθ),因为 up ⊥ forward 而恒为 0。
* 前提: vUp 与 vForward 互相垂直且都是单位向量,否则这个简式不成立。
*/
void gltRotateFrameY(GLFrame* frame, const GLfloat angle){
// axis × forward —— 注意这是 -right(right = forward × up),
// 这个负号决定了旋转方向,别误当成右向量
const GLfloat vAxisCross[3] = {
frame->vUp[1] * frame->vForward[2] - frame->vUp[2] * frame->vForward[1],
frame->vUp[2] * frame->vForward[0] - frame->vUp[0] * frame->vForward[2],
frame->vUp[0] * frame->vForward[1] - frame->vUp[1] * frame->vForward[0]
};
// 角度转弧度
const GLfloat rad = angle; // 如果 angle 是弧度,则直接使用;如果是度,需要转换为弧度:angle * M_PI / 180.0f
const GLfloat fCos = std::cos(rad);
const GLfloat fSin = std::sin(rad);
// vAxisCross 已提前算好,每个分量只依赖自己的旧值,可以直接原地更新,省掉临时数组
frame->vForward[0] = fCos * frame->vForward[0] + fSin * vAxisCross[0];
frame->vForward[1] = fCos * frame->vForward[1] + fSin * vAxisCross[1];
frame->vForward[2] = fCos * frame->vForward[2] + fSin * vAxisCross[2];
// 反复旋转会累积浮点漂移(实测 100 万次后长度偏 +1.2%),归一化抹掉它。
// forward 长度不为 1 会直接变成视图矩阵的缩放,整个世界会被放大/缩小
const GLfloat len = std::sqrt(frame->vForward[0] * frame->vForward[0] +
frame->vForward[1] * frame->vForward[1] +
frame->vForward[2] * frame->vForward[2]);
frame->vForward[0] /= len;
frame->vForward[1] /= len;
frame->vForward[2] /= len;
}
void specialKeys(int key, int x, int y){
switch(key){
case GLUT_KEY_UP:
gltMoveFrameForward(&frameCamera, 0.1f);
break;
case GLUT_KEY_DOWN:
gltMoveFrameForward(&frameCamera, -0.1f);
break;
case GLUT_KEY_LEFT:
gltRotateFrameY(&frameCamera, 0.1f);
break;
case GLUT_KEY_RIGHT:
gltRotateFrameY(&frameCamera, -0.1f);
break;
}
glutPostRedisplay();
}
void timerFunc(const int _){
glutPostRedisplay();
glutTimerFunc(33, timerFunc, 1); // 大约 30 FPS
}
int main(int args, char** argv){
std::cout << "Starting program..." << std::endl;
glutInit(&args, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
const int mainWindowId = glutCreateWindow("OpenGL Window");
if(mainWindowId == 0){
throw std::runtime_error("Failed to create main window");
}
// ======= 事件处理 =======
glutDisplayFunc(renderScene);
glutReshapeFunc(changeSize);
glutSpecialFunc(specialKeys);
glutTimerFunc(33, timerFunc, 1); // 启动定时器,大约 30 FPS
// ======= 渲染循环 =======
GLint iUnits;
glGetIntegerv(GL_MAX_TEXTURE_UNITS, &iUnits);
std::cout << "Max texture units: " << iUnits << std::endl;
setupRc();
glutMainLoop();
shutdownRc();
return 0;
}

浙公网安备 33010602011771号