参考文献:https://learnopengl.com/#!Getting-started/OpenGL

前置:OpenGL基础27:网格

一、模型

有了mesh类之后,接下来就是实现一个model类将各个mesh拼成一个模型

首先是模型的创建:很好理解,就是一次绘制其所有的mesh:

public:Model(const GLchar* path){this->loadModel(path);}void Draw(Shader shader){for (GLuint i = 0; i < this->meshes.size(); i++)this->meshes[i].Draw(shader);}

接下来就是模型的导入:

其中的scene对象是Assimp的数据结构的根对象(场景对象),一旦有了场景对象,就可以从已加载模型中获取所有需要的数据

  • importer.ReadFile:函数第一个参数为模型的路径,第二个参数可以让Assimp导入数据时做一些额外的计算或操作

有以下几种常见的设置:

  • aiProcess_Triangulate:将模型三角化
  • aiProcess_FlipUVs:沿y轴翻转坐标(这个在 OpenGL基础9:纹理 这一章中有过类似的介绍:为什么要翻转y轴)
  • aiProcess_GenNormals : 如果模型没有包含法线向量,就为每个顶点创建法线(暂时不需要了解)
  • aiProcess_SplitLargeMeshes : 把大的网格成几个小的的下级网格,当渲染有一个最大数量顶点的限制时或者只能处理小块网格时很有用(暂时不需要了解)
  • aiProcess_OptimizeMeshes : 和上个选项相反,它把几个网格结合为一个更大的网格(暂时不需要了解)
void loadModel(string path)
{Assimp::Importer importer;const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs);if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode){cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << endl;return;}this->directory = path.substr(0, path.find_last_of('/'));this->processNode(scene->mRootNode, scene);
}

注意一下代码中的 this->directory 路径,样例中是指向了对应模型的文件夹,但是有的时候模型文件内的贴图路径是绝对路径又或者默认退回上一层目录,这个时候要不修改模型文件,要不就修改这里的 this->directory

对于Assimp的结构,每个节点包含一个网格集合的索引,每个索引指向一个在场景对象中特定的网格位置,如果想要获取并处理这些网格索引,就需要进行类似于树递归的操作:

Assimp数据简单结构模型(来源于openGL.cn)
//依次处理所有的场景节点
void processNode(aiNode* node, const aiScene* scene)
{for (GLuint i = 0; i < node->mNumMeshes; i++){aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];this->meshes.push_back(this->processMesh(mesh, scene));}for (GLuint i = 0; i < node->mNumChildren; i++)this->processNode(node->mChildren[i], scene);
}

用上面的方法,就可以获得每个节点的网格了,当然对于原始的 aimesh 对象要将它们全部转换成我们自己定义的网格对象:这个很好办,只需要获取每个网格相关的属性并把这些属性储存到我们自己的对象就可以了,包括处理顶点坐标、法线和纹理坐标、顶点索引以及材质

  • 关于纹理:Assimp允许一个模型的每个顶点有8个不同的纹理坐标,暂时只关心第一组纹理坐标,当然啦,网格也可能完全没有纹理坐标
  • 关于顶点索引:Assimp的接口定义每个网格有一个以面(faces)为单位的数组,每个面代表一个单独的图元,可以从其中获取绘制的顺序索引
  • 关于材质:网格中有指向材质对象的索引,想要获取网格的材质对象,需要索引场景的mMaterials数组
//将所有原始的aimesh对象全部转换成我们自己定义的网格对象
Mesh processMesh(aiMesh* mesh, const aiScene* scene)
{vector<Vertex> vertices;vector<GLuint> indices;vector<Texture> textures;//处理顶点坐标、法线和纹理坐标for (GLuint 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;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;}elsevertex.TexCoords = glm::vec2(0.0f, 0.0f);vertices.push_back(vertex);}//处理顶点索引for (GLuint i = 0; i < mesh->mNumFaces; i++){aiFace face = mesh->mFaces[i];for (GLuint j = 0; j < face.mNumIndices; j++)indices.push_back(face.mIndices[j]);}//处理材质aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];vector<Texture> diffuseMaps = this->loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());vector<Texture> specularMaps = this->loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());return Mesh(vertices, indices, textures);
}

对于纹理的读取:

获取了aimaterial对象后,可以从中加载网格的diffuse或/和specular纹理,每个材质都储存了一个数组,这个数组为每个纹理类型提供纹理位置,不同的纹理类型都以aiTextureType_为前缀

  • GetTextureCount((aiTextureType)type):检验材质中储存的纹理,获取对应类型的纹理
  • GetTexture((aiTextureType)type, i, &str):获取对应纹理的位置,前两个参数为类型和下标,获取的位置会存入第三个参数
//遍历所有给定纹理类型的纹理位置,获取纹理的文件位置,然后加载生成纹理
vector<Texture> loadMaterialTextures(aiMaterial* mat, int type, string typeName)
{vector<Texture> textures;for (GLuint i = 0; i < mat->GetTextureCount((aiTextureType)type); i++){aiString str;mat->GetTexture((aiTextureType)type, i, &str);GLboolean skip = false;for (GLuint j = 0; j < textures_loaded.size(); j++){if (std::strcmp(textures_loaded[j].path.C_Str(), 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);this->textures_loaded.push_back(texture);}}return textures;
}

二、测试

有了model.h和mesh.h之后,在主代码中生成模型就非常简单了,只需要考虑其光照和空间变换

可以将之前的“正方体箱子”替换成全新的箱子模型

主代码如下(删除了之前的所有箱子,保留了所有光源):

#include<iostream>
#include<opengl/glew.h>
#define GLEW_STATIC
#include<GLFW/glfw3.h>
#include"Shader.h"
#include"Camera.h"
#include<glm/glm.hpp>
#include<glm/gtc/matrix_transform.hpp>
#include<glm/gtc/type_ptr.hpp>
#include"Mesh.h"
#include"Model.h"
#include<opengl/freeglut.h>
#include<SOIL.h>bool keys[1024];
Camera camera;
GLfloat lastX, lastY;
bool firstMouse = true;
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void cameraMove();
const GLuint WIDTH = 800, HEIGHT = 600;int main()
{glfwInit();glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);glfwMakeContextCurrent(window);glfwSetKeyCallback(window, key_callback);glfwSetCursorPosCallback(window, mouse_callback);glfwSetScrollCallback(window, scroll_callback);glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);glewExperimental = GL_TRUE;glewInit();int width, height;glfwGetFramebufferSize(window, &width, &height);glViewport(0, 0, width, height);Shader shaderObj("ObjVShader.vert", "ObjFShader.frag");Shader shaderLight("LightVShader.vert", "LightFShader.frag");GLfloat vertices[] = {-0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f,  0.0f,0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f,  0.0f,0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f,  1.0f,0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f,  1.0f,-0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f,  1.0f,-0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f,  0.0f,-0.5f, -0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  0.0f,  0.0f,0.5f, -0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  1.0f,  0.0f,0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  1.0f,  1.0f,0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  1.0f,  1.0f,-0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  0.0f,  1.0f,-0.5f, -0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  0.0f,  0.0f,-0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,  1.0f,  0.0f,-0.5f,  0.5f, -0.5f, -1.0f,  0.0f,  0.0f,  1.0f,  1.0f,-0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,  0.0f,  1.0f,-0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,  0.0f,  1.0f,-0.5f, -0.5f,  0.5f, -1.0f,  0.0f,  0.0f,  0.0f,  0.0f,-0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,  1.0f,  0.0f,0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,  1.0f,  0.0f,0.5f,  0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  1.0f,  1.0f,0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  0.0f,  1.0f,0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  0.0f,  1.0f,0.5f, -0.5f,  0.5f,  1.0f,  0.0f,  0.0f,  0.0f,  0.0f,0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,  1.0f,  0.0f,-0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,  0.0f,  1.0f,0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,  1.0f,  1.0f,0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,  1.0f,  0.0f,0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,  1.0f,  0.0f,-0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,  0.0f,  0.0f,-0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,  0.0f,  1.0f,-0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,  0.0f,  1.0f,0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,  1.0f,  1.0f,0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  1.0f,  0.0f,0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  1.0f,  0.0f,-0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  0.0f,  0.0f,-0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,  0.0f,  1.0f};glm::vec3 positions[] = {glm::vec3(0.0f, -1.78f, 0.0f),glm::vec3(0.0f, -0.89f, 0.0f),glm::vec3(0.0f, -0.0f, 0.0f),glm::vec3(-2.0f, -1.78f, 0.0f),glm::vec3(-2.0f, -0.89f, 0.0f),glm::vec3(-3.0f, -1.78f, 0.0f),glm::vec3(-2.0f, -1.78f, 1.0f),glm::vec3(-1.0f, -1.78f, -4.0f),};glm::vec3 pointLightPositions[] = {glm::vec3(-1.0f, 0.0f, -2.0f),glm::vec3(0.0f, -1.0f, 2.0f),glm::vec3(-5.0f, -1.0f, 1.0f),};GLuint VBO, VAO;glGenVertexArrays(1, &VAO);glGenBuffers(1, &VBO);glBindVertexArray(VAO);glBindBuffer(GL_ARRAY_BUFFER, VBO);glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);glEnableVertexAttribArray(0);glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));glEnableVertexAttribArray(1);glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));glEnableVertexAttribArray(2);GLuint lightVAO;glGenVertexArrays(1, &lightVAO);glBindVertexArray(lightVAO);glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);//VBO数据已经绑定且我们就用之前的顶点数据,所以无需再管理VBOglEnableVertexAttribArray(0);glBindBuffer(GL_ARRAY_BUFFER, 0);glBindVertexArray(0);glEnable(GL_DEPTH_TEST);Model ourModel("Object/wood/file.fbx");while (!glfwWindowShouldClose(window)){glfwPollEvents();glClearColor(0.0f, 0.0f, 0.0f, 1.0f);glClear(GL_COLOR_BUFFER_BIT);glClear(GL_DEPTH_BUFFER_BIT);cameraMove();shaderLight.Use();glm::mat4 view = camera.GetViewMatrix();glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 100.0f);glm::mat4 model = glm::mat4(1.0f);GLint modelLoc = glGetUniformLocation(shaderLight.Program, "model");GLint viewLoc = glGetUniformLocation(shaderLight.Program, "view");GLint projLoc = glGetUniformLocation(shaderLight.Program, "projection");glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));glBindVertexArray(lightVAO);for (int i = 0; i <= 2; i++){model = glm::translate(glm::mat4(1.0f), pointLightPositions[i]);model = glm::scale(model, glm::vec3(0.2f));glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));glDrawArrays(GL_TRIANGLES, 0, 36);}shaderObj.Use();glUniform3f(glGetUniformLocation(shaderObj.Program, "sunLight.direction"), -0.2f, -1.0f, -0.3f);glUniform3f(glGetUniformLocation(shaderObj.Program, "sunLight.diffuse"), 0.4f, 0.4f, 0.4f);glUniform3f(glGetUniformLocation(shaderObj.Program, "sunLight.specular"), 0.5f, 0.5f, 0.5f);glUniform3f(glGetUniformLocation(shaderObj.Program, "pointLights[0].position"), pointLightPositions[0].x, pointLightPositions[0].y, pointLightPositions[0].z);glUniform3f(glGetUniformLocation(shaderObj.Program, "pointLights[0].diffuse"), 0.8f, 0.8f, 0.8f);glUniform3f(glGetUniformLocation(shaderObj.Program, "pointLights[0].specular"), 1.0f, 1.0f, 1.0f);glUniform1f(glGetUniformLocation(shaderObj.Program, "pointLights[0].k0"), 1.0f);glUniform1f(glGetUniformLocation(shaderObj.Program, "pointLights[0].k1"), 0.09);glUniform1f(glGetUniformLocation(shaderObj.Program, "pointLights[0].k2"), 0.032);glUniform3f(glGetUniformLocation(shaderObj.Program, "pointLights[1].position"), pointLightPositions[1].x, pointLightPositions[1].y, pointLightPositions[1].z);glUniform3f(glGetUniformLocation(shaderObj.Program, "pointLights[1].diffuse"), 0.8f, 0.8f, 0.8f);glUniform3f(glGetUniformLocation(shaderObj.Program, "pointLights[1].specular"), 1.0f, 1.0f, 1.0f);glUniform1f(glGetUniformLocation(shaderObj.Program, "pointLights[1].k0"), 1.0f);glUniform1f(glGetUniformLocation(shaderObj.Program, "pointLights[1].k1"), 0.09);glUniform1f(glGetUniformLocation(shaderObj.Program, "pointLights[1].k2"), 0.032);glUniform3f(glGetUniformLocation(shaderObj.Program, "pointLights[2].position"), pointLightPositions[2].x, pointLightPositions[2].y, pointLightPositions[2].z);glUniform3f(glGetUniformLocation(shaderObj.Program, "pointLights[2].diffuse"), 0.8f, 0.8f, 0.8f);glUniform3f(glGetUniformLocation(shaderObj.Program, "pointLights[2].specular"), 1.0f, 1.0f, 1.0f);glUniform1f(glGetUniformLocation(shaderObj.Program, "pointLights[2].k0"), 1.0f);glUniform1f(glGetUniformLocation(shaderObj.Program, "pointLights[2].k1"), 0.09);glUniform1f(glGetUniformLocation(shaderObj.Program, "pointLights[2].k2"), 0.032);glUniform3f(glGetUniformLocation(shaderObj.Program, "spotLight.position"), camera.Position.x, camera.Position.y, camera.Position.z);glUniform3f(glGetUniformLocation(shaderObj.Program, "spotLight.direction"), camera.Front.x, camera.Front.y, camera.Front.z);glUniform3f(glGetUniformLocation(shaderObj.Program, "spotLight.diffuse"), 1.0f, 1.0f, 1.0f);glUniform3f(glGetUniformLocation(shaderObj.Program, "spotLight.specular"), 1.0f, 1.0f, 1.0f);glUniform1f(glGetUniformLocation(shaderObj.Program, "spotLight.k0"), 1.0f);glUniform1f(glGetUniformLocation(shaderObj.Program, "spotLight.k1"), 0.09);glUniform1f(glGetUniformLocation(shaderObj.Program, "spotLight.k2"), 0.032);glUniform1f(glGetUniformLocation(shaderObj.Program, "spotLight.cutOff"), glm::cos(glm::radians(12.5f)));glUniform1f(glGetUniformLocation(shaderObj.Program, "spotLight.outCutOff"), glm::cos(glm::radians(16.0f)));glUniform3f(glGetUniformLocation(shaderObj.Program, "ambient"), 0.2f, 0.2f, 0.2f);glUniform3f(glGetUniformLocation(shaderObj.Program, "viewPos"), camera.Position.x, camera.Position.y, camera.Position.z);modelLoc = glGetUniformLocation(shaderObj.Program, "model");viewLoc = glGetUniformLocation(shaderObj.Program, "view");projLoc = glGetUniformLocation(shaderObj.Program, "projection");glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));for (int i = 0; i <= 7; i++){model = glm::translate(glm::mat4(1.0f), positions[i]);model = glm::scale(model, glm::vec3(0.01f));glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));ourModel.Draw(shaderObj);}glBindVertexArray(0);glfwSwapBuffers(window);}glDeleteVertexArrays(1, &VAO);glDeleteBuffers(1, &VBO);glfwTerminate();return 0;
}GLfloat deltaTime = 0.0f;
GLfloat lastFrame = 0.0f;
void cameraMove()
{GLfloat currentFrame = glfwGetTime();deltaTime = currentFrame - lastFrame;lastFrame = currentFrame;GLfloat cameraSpeed = 1.0f * deltaTime;if (keys[GLFW_KEY_W])camera.ProcessKeyboard(Camera_Movement(FORWARD), deltaTime);if (keys[GLFW_KEY_S])camera.ProcessKeyboard(Camera_Movement(BACKWARD), deltaTime);if (keys[GLFW_KEY_A])camera.ProcessKeyboard(Camera_Movement(LEFT), deltaTime);if (keys[GLFW_KEY_D])camera.ProcessKeyboard(Camera_Movement(RIGHT), deltaTime);
}void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)glfwSetWindowShouldClose(window, GL_TRUE);if (action == GLFW_PRESS)           //如果当前是按下操作keys[key] = true;else if (action == GLFW_RELEASE)            //松开键盘keys[key] = false;
}void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{camera.ProcessMouseScroll(yoffset);
}void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{if (firstMouse){lastX = xpos;lastY = ypos;firstMouse = false;}GLfloat xoffset = xpos - lastX;GLfloat yoffset = lastY - ypos;lastX = xpos;lastY = ypos;GLfloat sensitivity = 0.05;xoffset *= sensitivity;yoffset *= sensitivity;camera.ProcessMouseMovement(xoffset, yoffset);
}

完整的model.h代码:

#ifndef MODEL_H
#define MODEL_H
#include<vector>
#include<string>
#include"Shader.h"
#include"Mesh.h"
#include<opengl/glew.h>
#include<SOIL.h>
#include<glm/glm.hpp>
#include<glm/gtc/matrix_transform.hpp>
#include<assimp/Importer.hpp>
#include<assimp/scene.h>
#include<assimp/postprocess.h>
using namespace std;
GLint TextureFromFile(const char* path, string directory);class Model
{public:Model(const GLchar* path){this->loadModel(path);}void Draw(Shader shader){for (GLuint i = 0; i < this->meshes.size(); i++)this->meshes[i].Draw(shader);}private:vector<Mesh> meshes;string directory;vector<Texture> textures_loaded;void loadModel(string path){Assimp::Importer importer;const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs);if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode){cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << endl;return;}this->directory = path.substr(0, path.find_last_of('/'));this->processNode(scene->mRootNode, scene);}//依次处理所有的场景节点void processNode(aiNode* node, const aiScene* scene){for (GLuint i = 0; i < node->mNumMeshes; i++){aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];this->meshes.push_back(this->processMesh(mesh, scene));}for (GLuint i = 0; i < node->mNumChildren; i++)this->processNode(node->mChildren[i], scene);}//将所有原始的aimesh对象全部转换成我们自己定义的网格对象Mesh processMesh(aiMesh* mesh, const aiScene* scene){vector<Vertex> vertices;vector<GLuint> indices;vector<Texture> textures;//处理顶点坐标、法线和纹理坐标for (GLuint 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;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;//暂时只考虑第一组纹理坐标,Assimp允许一个模型的每个顶点有8个不同的纹理坐标,只是可能用不到vec.x = mesh->mTextureCoords[0][i].x;vec.y = mesh->mTextureCoords[0][i].y;vertex.TexCoords = vec;}elsevertex.TexCoords = glm::vec2(0.0f, 0.0f);vertices.push_back(vertex);}//处理顶点索引for (GLuint i = 0; i < mesh->mNumFaces; i++){aiFace face = mesh->mFaces[i];for (GLuint j = 0; j < face.mNumIndices; j++){indices.push_back(face.mIndices[j]);}}//处理材质if (mesh->mMaterialIndex >= 0){aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];vector<Texture> diffuseMaps = this->loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());vector<Texture> specularMaps = this->loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());}return Mesh(vertices, indices, textures);}//遍历所有给定纹理类型的纹理位置,获取纹理的文件位置,然后加载生成纹理vector<Texture> loadMaterialTextures(aiMaterial* mat, int type, string typeName){vector<Texture> textures;cout << typeName << endl;for (GLuint i = 0; i < mat->GetTextureCount((aiTextureType)type); i++){aiString str;mat->GetTexture((aiTextureType)type, i, &str);GLboolean skip = false;for (GLuint j = 0; j < textures_loaded.size(); j++){if (std::strcmp(textures_loaded[j].path.C_Str(), 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);this->textures_loaded.push_back(texture);}}return textures;}
};GLint TextureFromFile(const char* path, string directory)
{string filename = string(path);filename = directory + '/' + filename;cout << filename << endl;GLuint textureID;glGenTextures(1, &textureID);int width, height;unsigned char* image = SOIL_load_image(filename.c_str(), &width, &height, 0, SOIL_LOAD_RGB);glBindTexture(GL_TEXTURE_2D, textureID);glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);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);glBindTexture(GL_TEXTURE_2D, 0);SOIL_free_image_data(image);return textureID;
}
#endif

对于着色器,只需要修改材质的名字就好了:

#version 330 core
layout (location = 0) in vec3 position;
layout (location = 1) in vec3 normal;
layout (location = 2) in vec2 texture;
out vec2 texIn;
out vec3 normalIn;
out vec3 fragPosIn;
uniform mat4 model;             //模型矩阵
uniform mat4 view;              //观察矩阵
uniform mat4 projection;        //投影矩阵
void main()
{gl_Position = projection * view * model * vec4(position, 1.0);texIn = texture;fragPosIn = vec3(model * vec4(position, 1.0f));normalIn = mat3(transpose(inverse(model))) * normal;
}///#version 330 core
struct Material
{sampler2D texture_diffuse1;      //贴图sampler2D texture_specular1;     //镜面贴图sampler2D emission;     //放射贴图float shininess;        //反光度
};
struct SunLight             //平行光
{vec3 direction;vec3 diffuse;vec3 specular;
};
struct PointLight           //点光源
{vec3 position;vec3 diffuse;vec3 specular;float k0, k1, k2;
};
struct SpotLight            //聚光灯
{vec3 position;vec3 direction;vec3 diffuse;vec3 specular;float k0, k1, k2;float cutOff, outCutOff;
};
uniform vec3 ambient;
uniform Material material;
uniform SunLight sunLight;
uniform PointLight pointLights[3];
uniform SpotLight spotLight;
vec3 CalcSunLight(SunLight light, vec3 normal, vec3 viewDir);
vec3 CalcPointLight(PointLight light, vec3 normal, vec3 fragPos, vec3 viewDir);
vec3 CalcSpotLight(SpotLight light, vec3 normal, vec3 fragPos, vec3 viewDir);
out vec4 color;
uniform vec3 viewPos;
in vec2 texIn;
in vec3 fragPosIn;
in vec3 normalIn;
void main()
{//环境光vec3 ambient = ambient * vec3(texture(material.texture_diffuse1, texIn));vec3 viewDir = normalize(viewPos - fragPosIn);vec3 normal = normalize(normalIn);vec3 result = CalcSunLight(sunLight, normal, viewDir);for (int i = 0; i <= 2; i++)result = result + CalcPointLight(pointLights[i], normal, fragPosIn, viewDir);result = result + CalcSpotLight(spotLight, normal, fragPosIn, viewDir);color = vec4(result, 1.0f);
}vec3 CalcSunLight(SunLight light, vec3 normal, vec3 viewDir)
{vec3 lightDir = normalize(-light.direction);float diff = max(dot(normal, lightDir), 0.0f);vec3 diffuse = light.diffuse * (diff * vec3(texture(material.texture_diffuse1, texIn)));vec3 reflectDir = reflect(-lightDir, normal);float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);vec3 specular = light.specular * (spec * vec3(texture(material.texture_specular1, texIn)));return diffuse + specular;
}vec3 CalcPointLight(PointLight light, vec3 normal, vec3 fragPos, vec3 viewDir)
{vec3 lightDir = normalize(light.position - fragPos);float diff = max(dot(normal, lightDir), 0.0f);vec3 diffuse = light.diffuse * (diff * vec3(texture(material.texture_diffuse1, texIn)));vec3 reflectDir = reflect(-lightDir, normal);float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);vec3 specular = light.specular * (spec * vec3(texture(material.texture_specular1, texIn)));float dis = length(light.position - fragPos);float attenuation = 1.0f / (light.k0 + light.k1 * dis + light.k2 * (dis * dis));diffuse *= attenuation;specular *= attenuation;return diffuse + specular;
}vec3 CalcSpotLight(SpotLight light, vec3 normal, vec3 fragPos, vec3 viewDir)
{vec3 lightDir = normalize(light.position - fragPos);float theta = dot(lightDir, normalize(-light.direction));float lightSoft = clamp((theta - light.outCutOff) / (light.cutOff - light.outCutOff), 0.0f, 1.0f);float diff = max(dot(normal, lightDir), 0.0f);vec3 diffuse = light.diffuse * (diff * vec3(texture(material.texture_diffuse1, texIn)));vec3 reflectDir = reflect(-lightDir, normal);float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);vec3 specular = light.specular * (spec * vec3(texture(material.texture_specular1, texIn)));float dis = length(light.position - fragPos);float attenuation = 1.0f / (light.k0 + light.k1 * dis + light.k2 * (dis * dis));diffuse *= attenuation * lightSoft;specular *= attenuation * lightSoft;return diffuse + specular;
}

OpenGL基础28:模型相关推荐

  1. OpenGL基础37:反射与折射

    前置:OpenGL基础20:镜面光照 一.反射 不一定所有的光源都是简单的白光,不仅如此,光线也是可以多次反射的,例如一面镜子,可以从中看到远处的风景,一些金属材质的物体表面也会反射周围物体的光 这主 ...

  2. Computer Graphics Through OpenGL From Theory to Experiments - 学习笔记2 Tricks of the Trade opengl基础

    一个 OpenGL 工具箱 顶点数组及其绘制命令 // // squareAnnulus1.cpp // // 该程序绘制一个方形环作为三角形条带 // 顶点使用 glVertex3f() 指定,颜色 ...

  3. 【OpenGL】计算机图形学实验一:OpenGL基础实验(实验环境的熟悉、简单图形的绘制和输出)

    实验一:OpenGL基础实验 (实验环境的熟悉.简单图形的绘制和输出) 1.实验目的和要求 学习基本的OpenGL图形绘制和输出函数,掌握使用基于C++  OpenGL开发图形程序的流程. 2.实验设 ...

  4. OpenGL实现太阳系模型 —— Juwend

    OpenGL实现太阳系模型 发表于 2012 年 12 月 30 日 由 Juwend OpenGL是一个非常强大的图形引擎.传说当下最流行的图形引擎有两套,其中之一就是Windows平台上最常用的D ...

  5. OpenGL 基础光照ColorsBasic Lighting

    OpenGL 基础光照ColorsBasic Lighting 基础光照ColorsBasic Lighting简介 环境光照 漫反射光照 法向量 计算漫反射光照 最后一件事 镜面光照 基础光照Col ...

  6. OpenGL基础54:点光源阴影

    前置: OpenGL基础53:阴影映射(下) 一.万象阴影贴图 之前成功实现了平行光阴影,生成阴影贴图时使用的矩阵是正交矩阵,若是想要实现点光源的阴影效果,那么理论上只需要修改投影矩阵为透视矩阵就好了 ...

  7. OpenGL基础53:阴影映射(下)

    接上文:OpenGL基础52:阴影映射(上) 五.阴影失真 按照上文的计算的结果,一个很明显的问题是:对于参与计算深度贴图的物体,其表面可以看到这样的栅格状的阴影,这种常见的错误表现也叫做阴影失真(S ...

  8. OpenGL基础50:HDR

    一.HDR与LDR 由于显示器只能显示值为0.0到1.0间的颜色,因此当数据存储在帧缓冲(Framebuffer)中时,亮度和颜色的值也是默认被限制在0.0到1.0之间的,这个颜色范围即是LDR(Lo ...

  9. OpenGL基础46:切线空间

    到这里,关于OpenGL基础的了解要接近尾声了,上一个节点是<OpenGL基础25:多光源>.在此章之后,学习openGL的各种教程的同时,可以转战想要了解的渲染引擎,也可以去github ...

最新文章

  1. 科大讯飞:让世界听见AI的声音
  2. Linux 配置IP地址,子网,网关,DNS,linux远程, wget 下载工具
  3. python替换文本文件单词_在大型文本文件中替换一组单词
  4. 关于企业应用架构中前置机的作用
  5. Shell命令-文件及目录操作之chattr、lsattr
  6. java native code_原生代码(native code)
  7. 2020年第十八届西电程序设计竞赛网络预选赛之Problem A 失败的在线考试
  8. 使用FD_CLOEXEC实现close-on-exec,关闭子进程无用文件描述符
  9. Mina2.0快速入门
  10. IBM Cognos 10 启动报错
  11. java日历数据_JAVA 常用数据类型 之日历类
  12. 8年Android开发教你如何写简历,详细的Android学习指南
  13. 2019面试题:谈谈你的IT职业发展路径规划
  14. 用R语言进行分位数回归
  15. (转)全新2007高校BBS上20个睿智的冷笑话
  16. l10n i18n vue_带有Vue的更多i18n:格式和后备
  17. 开源python语音识别_5 款不错的开源语音识别/语音文字转换系统
  18. C#《原CSharp》第三回 万文疑谋生思绪 璃月港口见清玉
  19. 前端基础知识点整理(html+css+js基础)、不包含框架
  20. C语言函数大全-- o 开头的函数

热门文章

  1. 零基础学python难吗-零基础学Python难吗,或者有什么其他数据加工软件推荐?
  2. python是什么类型的编程语言-Python是个什么语言?
  3. python初学者怎么入门-终于晓得python入门后怎么学精
  4. 简析三星新专利,语音识别技术的新方法
  5. 讯飞庭审语音识别系统亮相最高人民法院工作报告
  6. 策略模式和工厂模式的区别_设计模式系列 — 策略模式
  7. Vuex的State核心概念
  8. java黄历_黄历查询API免费接口,黄历查询API接口付费定制-进制数据
  9. 导入php项目_商业裂变,之项目技术实战(第九节:程序框架的安装)
  10. YUV转IPLImage(RGB)