模型加载
在实际项目中,我们很少手动定义顶点数据,而是从3D建模软件导出的模型文件中加载。本章介绍如何使用Assimp库加载复杂的3D模型。
模型文件格式
常见的3D模型文件格式:
| 格式 | 说明 |
|---|---|
| OBJ | 简单、广泛支持,但不支持动画 |
| FBX | Autodesk格式,支持动画和骨骼 |
| glTF | 现代格式,Web标准,支持PBR |
| COLLADA | XML格式,功能完整 |
| 3DS | 3ds Max旧格式 |
| BLEND | Blender原生格式 |
Assimp库
Assimp(Open Asset Import Library)是一个跨平台的3D模型加载库,支持多种格式。
安装Assimp
# Windows (vcpkg)
vcpkg install assimp
# Linux
sudo apt-get install libassimp-dev
# macOS
brew install assimp
CMake配置
find_package(assimp REQUIRED)
target_link_libraries(your_target assimp::assimp)
模型结构
一个典型的模型结构:
Model
├── Mesh[]
│ ├── Vertex[]
│ │ ├── Position
│ │ ├── Normal
│ │ ├── TexCoords
│ │ └── Tangent/BiTangent
│ ├── Indices[]
│ └── Texture[]
│ ├── diffuse
│ ├── specular
│ └── normal
└── Node hierarchy
网格类(Mesh)
// Mesh.h
#pragma once
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <string>
#include <vector>
struct Vertex {
glm::vec3 Position;
glm::vec3 Normal;
glm::vec2 TexCoords;
glm::vec3 Tangent;
glm::vec3 Bitangent;
};
struct Texture {
unsigned int id;
std::string type;
std::string path;
};
class Mesh {
public:
std::vector<Vertex> vertices;
std::vector<unsigned int> indices;
std::vector<Texture> textures;
unsigned int VAO;
Mesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices,
std::vector<Texture> textures) {
this->vertices = vertices;
this->indices = indices;
this->textures = textures;
setupMesh();
}
void Draw(Shader& shader) {
unsigned int diffuseNr = 1;
unsigned int specularNr = 1;
unsigned int normalNr = 1;
unsigned int heightNr = 1;
for (unsigned int i = 0; i < textures.size(); i++) {
glActiveTexture(GL_TEXTURE0 + i);
std::string number;
std::string name = textures[i].type;
if (name == "texture_diffuse")
number = std::to_string(diffuseNr++);
else if (name == "texture_specular")
number = std::to_string(specularNr++);
else if (name == "texture_normal")
number = std::to_string(normalNr++);
else if (name == "texture_height")
number = std::to_string(heightNr++);
glUniform1i(glGetUniformLocation(shader.ID, (name + number).c_str()), i);
glBindTexture(GL_TEXTURE_2D, textures[i].id);
}
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glActiveTexture(GL_TEXTURE0);
}
private:
unsigned int VBO, EBO;
void setupMesh() {
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex),
&vertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int),
&indices[0], GL_STATIC_DRAW);
// 位置
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
// 法线
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
(void*)offsetof(Vertex, Normal));
// 纹理坐标
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex),
(void*)offsetof(Vertex, TexCoords));
// 切线
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
(void*)offsetof(Vertex, Tangent));
// 副切线
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
(void*)offsetof(Vertex, Bitangent));
glBindVertexArray(0);
}
};
模型类(Model)
// Model.h
#pragma once
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include "Mesh.h"
#include "Shader.h"
#include <string>
#include <vector>
#include <map>
unsigned int TextureFromFile(const char* path, const std::string& directory);
class Model {
public:
std::vector<Texture> textures_loaded;
std::vector<Mesh> meshes;
std::string directory;
bool gammaCorrection;
Model(std::string const& path, bool gamma = false) : gammaCorrection(gamma) {
loadModel(path);
}
void Draw(Shader& shader) {
for (unsigned int i = 0; i < meshes.size(); i++)
meshes[i].Draw(shader);
}
private:
void loadModel(std::string const& path) {
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(path,
aiProcess_Triangulate | aiProcess_GenSmoothNormals |
aiProcess_FlipUVs | aiProcess_CalcTangentSpace);
if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) {
std::cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << std::endl;
return;
}
directory = path.substr(0, path.find_last_of('/'));
processNode(scene->mRootNode, scene);
}
void processNode(aiNode* node, const aiScene* scene) {
for (unsigned int i = 0; i < node->mNumMeshes; i++) {
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
meshes.push_back(processMesh(mesh, scene));
}
for (unsigned int i = 0; i < node->mNumChildren; i++) {
processNode(node->mChildren[i], scene);
}
}
Mesh processMesh(aiMesh* mesh, const aiScene* scene) {
std::vector<Vertex> vertices;
std::vector<unsigned int> indices;
std::vector<Texture> textures;
for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
Vertex vertex;
glm::vec3 vector;
vector.x = mesh->mVertices[i].x;
vector.y = mesh->mVertices[i].y;
vector.z = mesh->mVertices[i].z;
vertex.Position = vector;
if (mesh->HasNormals()) {
vector.x = mesh->mNormals[i].x;
vector.y = mesh->mNormals[i].y;
vector.z = mesh->mNormals[i].z;
vertex.Normal = vector;
}
if (mesh->mTextureCoords[0]) {
glm::vec2 vec;
vec.x = mesh->mTextureCoords[0][i].x;
vec.y = mesh->mTextureCoords[0][i].y;
vertex.TexCoords = vec;
vector.x = mesh->mTangents[i].x;
vector.y = mesh->mTangents[i].y;
vector.z = mesh->mTangents[i].z;
vertex.Tangent = vector;
vector.x = mesh->mBitangents[i].x;
vector.y = mesh->mBitangents[i].y;
vector.z = mesh->mBitangents[i].z;
vertex.Bitangent = vector;
} else {
vertex.TexCoords = glm::vec2(0.0f, 0.0f);
}
vertices.push_back(vertex);
}
for (unsigned int i = 0; i < mesh->mNumFaces; i++) {
aiFace face = mesh->mFaces[i];
for (unsigned int j = 0; j < face.mNumIndices; j++)
indices.push_back(face.mIndices[j]);
}
aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
std::vector<Texture> diffuseMaps = loadMaterialTextures(material,
aiTextureType_DIFFUSE, "texture_diffuse");
textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
std::vector<Texture> specularMaps = loadMaterialTextures(material,
aiTextureType_SPECULAR, "texture_specular");
textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
std::vector<Texture> normalMaps = loadMaterialTextures(material,
aiTextureType_HEIGHT, "texture_normal");
textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
std::vector<Texture> heightMaps = loadMaterialTextures(material,
aiTextureType_AMBIENT, "texture_height");
textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());
return Mesh(vertices, indices, textures);
}
std::vector<Texture> loadMaterialTextures(aiMaterial* mat, aiTextureType type,
std::string typeName) {
std::vector<Texture> textures;
for (unsigned int i = 0; i < mat->GetTextureCount(type); i++) {
aiString str;
mat->GetTexture(type, i, &str);
bool skip = false;
for (unsigned int j = 0; j < textures_loaded.size(); j++) {
if (std::strcmp(textures_loaded[j].path.data(), str.C_Str()) == 0) {
textures.push_back(textures_loaded[j]);
skip = true;
break;
}
}
if (!skip) {
Texture texture;
texture.id = TextureFromFile(str.C_Str(), this->directory);
texture.type = typeName;
texture.path = str.C_Str();
textures.push_back(texture);
textures_loaded.push_back(texture);
}
}
return textures;
}
};
unsigned int TextureFromFile(const char* path, const std::string& directory) {
std::string filename = std::string(path);
filename = directory + '/' + filename;
unsigned int textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char* data = stbi_load(filename.c_str(), &width, &height, &nrComponents, 0);
if (data) {
GLenum format;
if (nrComponents == 1) format = GL_RED;
else if (nrComponents == 3) format = GL_RGB;
else if (nrComponents == 4) format = GL_RGBA;
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format,
GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
} else {
std::cout << "Texture failed to load at path: " << path << std::endl;
stbi_image_free(data);
}
return textureID;
}
使用模型类
#include "Model.h"
#include "Shader.h"
#include "Camera.h"
int main() {
// 初始化...
Shader ourShader("model.vs", "model.fs");
Model ourModel("resources/objects/backpack/backpack.obj");
while (!glfwWindowShouldClose(window)) {
processInput(window);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
ourShader.use();
glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom),
800.0f / 600.0f, 0.1f, 100.0f);
glm::mat4 view = camera.GetViewMatrix();
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(0.0f, 0.0f, 0.0f));
model = glm::scale(model, glm::vec3(1.0f, 1.0f, 1.0f));
ourShader.setMat4("projection", projection);
ourShader.setMat4("view", view);
ourShader.setMat4("model", model);
ourModel.Draw(ourShader);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
模型着色器
// model.vs
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoords;
out vec2 TexCoords;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main() {
TexCoords = aTexCoords;
gl_Position = projection * view * model * vec4(aPos, 1.0);
}
// model.fs
#version 330 core
out vec4 FragColor;
in vec2 TexCoords;
uniform sampler2D texture_diffuse1;
void main() {
FragColor = texture(texture_diffuse1, TexCoords);
}
Assimp后处理标志
加载模型时可以指定后处理标志:
| 标志 | 说明 |
|---|---|
| aiProcess_Triangulate | 将所有面转换为三角形 |
| aiProcess_GenNormals | 为没有法线的面生成法线 |
| aiProcess_GenSmoothNormals | 生成平滑法线 |
| aiProcess_FlipUVs | 翻转纹理坐标Y轴 |
| aiProcess_CalcTangentSpace | 计算切线和副切线 |
| aiProcess_JoinIdenticalVertices | 合并相同顶点 |
| aiProcess_ImproveCacheLocality | 优化顶点缓存 |
| aiProcess_RemoveRedundantMaterials | 移除冗余材质 |
优化建议
1. 纹理缓存
避免重复加载相同的纹理:
std::map<std::string, unsigned int> textureCache;
unsigned int loadTextureCached(const std::string& path) {
if (textureCache.find(path) != textureCache.end()) {
return textureCache[path];
}
unsigned int id = loadTexture(path);
textureCache[path] = id;
return id;
}
2. 实例化渲染
对于相同模型的多个实例,使用实例化渲染:
glDrawElementsInstanced(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0, instanceCount);
3. LOD(细节层次)
根据距离使用不同精度的模型:
Model* getModelByDistance(float distance) {
if (distance < 10.0f) return highDetailModel;
else if (distance < 50.0f) return mediumDetailModel;
else return lowDetailModel;
}
小结
模型加载是3D应用开发的重要环节:
- Assimp库支持多种模型格式
- 模型由网格层次结构组成
- 每个网格包含顶点、索引和纹理
- 正确处理后处理标志可以获得更好的模型数据
下一章我们将学习 高级OpenGL,包括帧缓冲、立方体贴图等高级技术。
模型资源
可以从以下网站获取免费3D模型: