1.数据格式
3D建模工具生成的数据文件格式.obj或COLLADA格式,通过模型导入库Assimp能在OpenGL中使用模型数据——了解.obj格式数据格式
2.Assimp库导入方法
(1)到GitHub下载Assimp
(2)通过CMake编译后得到解决方案assimp.sln,并在vs中编译运行获取.lib与.dll文件
(3)与glfw类似导入到项目中
可能出现的问题:在项目运行时无法找到assimp的.dll文件
解决方法:
将assimp的.lib与.dll文件添加到与项目解决方案的.exe同目录下,如下图:
3.mesh.h
(1)vertex结构体
struct Vertex {
//position
glm::vec3 Position;
//normal
glm::vec3 Normal;
//texCoords
glm::vec2 TexCoords;
//tangent
glm::vec3 Tangent;
//bitangent
glm::vec3 Bitangent;
//bone indexes which will influence this vertex,vec1、vec2、vec3、vec4
int m_BoneIDs[MAX_BONE_INFLUENCE];
//weights from each bone
float m_Weights[MAX_BONE_INFLUENCE];
};
(2)texture结构体
struct Texture {
//Texture id
unsigned int id;
//Texture type:diffuse/specular
string type;
//Texture path:loaded
string path;
};
(3)mesh类
class Mesh {
public:
// mesh Data
vector<Vertex> vertices;
vector<unsigned int> indices;
vector<Texture> textures;
unsigned int VAO;
// constructor
Mesh(vector<Vertex> vertices, vector<unsigned int> indices, vector<Texture> textures)
{
this->vertices = vertices;
this->indices = indices;
this->textures = textures;
// now that we have all the required data, set the vertex buffers and its attribute pointers.
//顶点缓冲对象、顶点数组对象操作,顶点数据读取、绑定
setupMesh();
}
// render the mesh
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); //绑定纹理前激活
// retrieve texture number (the N in diffuse_textureN)
string number;
string name = textures[i].type;
if (name == "texture_diffuse")
number = std::to_string(diffuseNr++);
else if (name == "texture_specular")
number = std::to_string(specularNr++); // transfer unsigned int to string
else if (name == "texture_normal")
number = std::to_string(normalNr++); // transfer unsigned int to string
else if (name == "texture_height")
number = std::to_string(heightNr++); // transfer unsigned int to string
// now set the sampler to the correct texture unit
glUniform1i(glGetUniformLocation(shader.ID, (name + number).c_str()), i);
// and finally bind the texture
glBindTexture(GL_TEXTURE_2D, textures[i].id);
}
//网格绘制
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, static_cast<unsigned int>(indices.size()), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
// always good practice to set everything back to defaults once configured.
glActiveTexture(GL_TEXTURE0);
}
private:
// render data
unsigned int VBO, EBO;
// initializes all the buffer objects/arrays
void setupMesh()
{
// create buffers/arrays
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &