这节主要是介绍如何导入Mesh模型
运用插件assimp-vc140-mt.dll,搜索项目中的这个文件,并复制一份到运行目录:
git-learn-open-gl-master\bin\3.model_loading ,然后就能跑起来了
代码分析:
// load models
// -----------
Model ourModel(FileSystem::getPath("resources/objects/backpack/backpack.obj"));
while(true)中
// 空间坐标变换
// render the loaded model
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(0.0f, 0.0f, 0.0f)); // translate it down so it's at the center of the scene
model = glm::scale(model, glm::vec3(1.0f, 1.0f, 1.0f)); // it's a bit too big for our scene, so scale it down
ourShader.setMat4("model", model);
//进行显示
ourModel.Draw(ourShader);
分析Mesh.h:
#ifndef MESH_H
#define MESH_H
#include <glad/glad.h> // holds all OpenGL type declarations
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <learnopengl/shader.h>
#include <string>
#include <vector>
using namespace std;
#define MAX_BONE_INFLUENCE 4
//这个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
int m_BoneIDs[MAX_BONE_INFLUENCE];
//weights from each bone
float m_Weights[MAX_BONE_INFLUENCE];
};
struct Texture {
unsigned int id;
string type;
string path;
};
class Mesh {
public:
// mesh Data
vector<Vertex> vertices;
vector<unsigned int> indices;
vector<Texture> textures;
unsigned int VAO;
// constructor 初始化,其中就读取Vertex格式的数据
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 渲染Mesh,并根据图片的多少来遍历渲染
void Draw(Shader &shader)
{
// bind appropriate textures
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); // active proper texture unit before binding
// 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

这篇博客介绍了如何在OpenGL中导入和渲染3D模型,通过使用Assimp库解析OBJ文件。首先,确保assimp-vc140-mt.dll插件在正确目录下。然后,代码解析模型数据,创建顶点数组对象(VAO),设置顶点属性指针。在渲染循环中,进行空间坐标变换,加载并设置材质纹理,最后绘制模型。Mesh类包含了模型的顶点、索引和纹理信息,而Model类负责加载和处理这些模型数据。

1834

被折叠的 条评论
为什么被折叠?



