opengl之加载模型

加载模型的时候要用到Assimp库,我这里通过github地址下载:Assimp GitHub地址

下载完之后需要用cmake编译到对应的IDE平台,我这里选择vs2017,点击generate就可以生成对应的工程了,让后再Debug目录下的dll文件复制到与exe文件同目录的位置就行了:

将.lib文件放到vs中的库文件就行了

 

 

include文件也同样需要连接到上面去,具体参考之前的环境配置文章相关内容这里就不在赘述了。

 opengl中文网中加载模型用到了几个类:Mesh和Model

Mesh负责处理网格数据,Model负责加载和加工网格数据并将其显示出来。

Mesh.h:

#ifndef MESH_H
#define MESH_H
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <assimp/material.h>
#include <assimp/scene.h>
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
#include <GLFW/glfw3.h>
#include <gl/GL.h>
#include <string>
#include <vector>
#include "shader.h"
#include <glad/glad.h>
using namespace std;
typedef unsigned int uint;
// 顶点结构体,利用结构体的内存结构是连续的特性进行设计
struct Vertex {
	glm::vec3 position;
	glm::vec3 normal;
	glm::vec2 texCoords;
	glm::vec3 tangent;
	glm::vec3 bitangent;
};
// 贴图结构体包括id,贴图的类型(漫反射贴图或者是镜面光贴图),和贴图的具体路径
struct Texture {
	uint id;
	string type;
	aiString path;
};
class Mesh {
public:
    // 盛放顶点数组的容器
	vector<Vertex> vertices;
    // 盛放索引位置的容器
	vector<uint> indices;
    // 盛放贴图的容器
	vector<Texture> textures;
    // 网格构造器
	Mesh(vector<Vertex> vertices, vector<uint> indices, vector<Texture> textures);
    // 绘制
	void Draw(Shader shader);
private:
	uint VAO, VBO, EBO;
	void setupMesh();
};
#endif

Mesh.cpp:

#include "mesh.h"
Mesh::Mesh(vector<Vertex> vertices, vector<uint> indices, vector<Texture> textures) {
	this->vertices = vertices;
	this->indices = indices;
	this->textures = textures;
	setupMesh();
}
void Mesh::Draw(Shader shader) {
	uint diffuseNr = 1;
	uint specularNr = 1;
	for (uint i = 0; i < textures.size(); i++) {
		glActiveTexture(GL_TEXTURE0 + i);
		// 获取纹理序号
		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++);
		}
		/*shader.setFloat(("material." + name + number).c_str(), i);*/
		shader.setInt((name + number).c_str(),i);
		glBindTexture(GL_TEXTURE_2D,textures[i].id);
	}
	glActiveTexture(GL_TEXTURE0);
	// 绘制网格
	glBindVertexArray(VAO);
	glDrawElements(GL_TRIANGLES,indices.size(),GL_UNSIGNED_INT,&indices[0]);
	//glBindVertexArray(0);
}
// 将顶点数据和索引数据送往显卡
void Mesh::setupMesh() {
	glGenBuffers(1, &VBO);
	glGenBuffers(1, &EBO);
	glGenVertexArrays(1,&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(uint), &indices[0], GL_STATIC_DRAW);
	glBindVertexArray(VAO);

	glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,sizeof(Vertex),(void *)(0));
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,sizeof(Vertex),(void *)(offsetof(Vertex,normal)));
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(2,2,GL_FLOAT,GL_FALSE,sizeof(Vertex),(void *)(offsetof(Vertex, texCoords)));
	glEnableVertexAttribArray(2);
	glBindVertexArray(0);
	glBindBuffer(GL_ARRAY_BUFFER,0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

你可能会问我怎么获得顶点数据和索引数据,贴图数据呢:这里就是加载模型的时候这些数据都在模型里了。

 model.h:

#ifndef MODEL_H
#define MODEL_H
#include <iostream>
#include <string>
#include "shader.h"
#include "mesh.h"
#include <vector>
#include <assimp/material.h>
#include <assimp/scene.h>
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
#include "stb_image.h"
#include <glad/glad.h>
using namespace std;
class Model {
public:
    // 通过路径加载模型
	Model(string path);
	Model();
    // 绘制(内部调用的还是mesh.draw)
	void Draw(Shader shader);
private:
	vector<Texture> textures_loaded;
	vector<Mesh> meshes;
	string directory;
	void loadModel(string path);
	void processNode(aiNode* node,const aiScene* scene);
	Mesh processMesh(aiMesh* mesh, const aiScene* scene);
	vector<Texture> loadMaterialTextures(aiMaterial* mat, aiTextureType type, string typeName);
	uint TextureFromFile(const char* path, const string &directory);
};
#endif

model.cpp:

#include "model.h"
Model::Model(string path) {
	loadModel(path);
}
Model::Model() {

}
void Model::Draw(Shader shader) {
	for (uint i = 0; i < meshes.size(); i++) {
		meshes[i].Draw(shader);
	}
}
void Model::loadModel(string path) {
	Assimp::Importer import;
	const aiScene *scene = import.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs);
	if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) {
		cout << "error::assimp::" << import.GetErrorString() << endl;
		return;
	}
	directory = path.substr(0, path.find_last_of('/'));
	processNode(scene->mRootNode, scene);
}
void Model::processNode(aiNode* node, const aiScene* scene) {
	for (uint i = 0; i < node->mNumMeshes; i++) {
		aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];
		meshes.push_back(processMesh(mesh, scene));
	}
	for (uint i = 0; i < node->mNumChildren; i++) {
		processNode(node->mChildren[i], scene);
	}
}
// 组装Mesh对象分别包括组装顶点数据,索引数据,贴图数据等
Mesh Model::processMesh(aiMesh* mesh, const aiScene* scene) {
	vector<Vertex> vertices;
	vector<uint> indices;
	vector<Texture> textures;
	// 处理顶点坐标属性
	for (uint i = 0; i < mesh->mNumVertices; i++) {
		Vertex vertex;
		// 处理顶点位置,法线,纹理坐标
		glm::vec3 pos;
		//pos.x = mesh->mVertices[i].x;
		//pos.x = mesh->mVertices[i].x;
		pos.x = mesh->mVertices[i].x;
		pos.y = mesh->mVertices[i].y;
		pos.z = mesh->mVertices[i].z;
		vertex.position = pos;
		glm::vec3 normalPos;
		normalPos.x = mesh->mNormals[i].x;
		normalPos.y = mesh->mNormals[i].y;
		normalPos.z = mesh->mNormals[i].z;
		vertex.normal = normalPos;
		if (mesh->mTextureCoords[0]) {
			glm::vec2 vec;
			vec.x = mesh->mTextureCoords[0][i].x;
			vec.y = mesh->mTextureCoords[0][i].y;
			vertex.texCoords = vec;
		}
		else {
			vertex.texCoords = glm::vec2(0.0f, 0.0f);
		}
		// 将其压入到vertices中
		vertices.push_back(vertex);
	}
	// 处理索引
	for (uint j = 0; j < mesh->mNumFaces; j++) {
		aiFace face = mesh->mFaces[j];
		for (uint i = 0; i < face.mNumIndices; i++) {
			indices.push_back(face.mIndices[i]);
		}
	}
	if (mesh->mMaterialIndex >= 0) {
		aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
		vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
		textures.insert(textures.end(),diffuseMaps.begin(),diffuseMaps.end());
		vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
		textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
		// normal maps
		vector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_normal");
		textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
		// height maps
		vector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, "texture_height");
		textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());
	}
	return Mesh(vertices, indices, textures);
}
vector<Texture> Model::loadMaterialTextures(aiMaterial* mat, aiTextureType type, string typeName) {
	vector<Texture> textures;
	for (uint i = 0; i < mat->GetTextureCount(type); i++) {
		aiString str;
		mat->GetTexture(type, i, &str);
		bool skip = false;
		for (uint j = 0; j < textures_loaded.size(); j++) {
			if (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;
			textures.push_back(texture);
			textures_loaded.push_back(texture);
		}
	}
	return textures;
}
uint Model::TextureFromFile(const char* path, const string &directory) {
	string filename = string(path);
	filename = directory + "/" + filename;
	uint 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 {
		cout << "texture failed to load at path" << endl;
		stbi_image_free(data);
	}
	return textureId;
}

 效果:

猜你喜欢

转载自blog.csdn.net/lck8989/article/details/102468468