3 #include <assimp/postprocess.h>
4 #include <assimp/quaternion.h>
5 #include <glm/gtc/type_ptr.hpp>
7 glm::mat4 aiMatrixToMat4(aiMatrix4x4 from) {
9 for (int i = 0; i < 4; i++)
10 for (int j = 0; j < 4; j++)
11 to[i][j] = from[j][i];
16 Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) {
18 std::vector<glm::vec3> vertices, normals, tangents, bitangents;
19 std::vector<glm::vec2> texCoords;
21 for (int i = 0; i < aiMesh->mNumVertices; i++) {
22 if (aiMesh->HasPositions()) {
23 aiVector3D v = aiMesh->mVertices[i];
24 vertices.push_back(glm::vec3(v.x, v.y, v.z));
26 if (aiMesh->HasNormals()) {
27 aiVector3D v = aiMesh->mNormals[i];
28 normals.push_back(glm::vec3(v.x, v.y, v.z));
30 std::cerr << "Missing normals" << std::endl;
33 // check for texture coord set 0
34 if (aiMesh->HasTextureCoords(0)) {
35 const aiVector3D v = aiMesh->mTextureCoords[0][i];
36 texCoords.push_back(glm::vec2(v.x, v.y));
38 texCoords.push_back(glm::vec2(0));
40 materialIndex = aiMesh->mMaterialIndex;
43 std::vector<GLuint> indices;
45 for (int i = 0; i < aiMesh->mNumFaces; i++) {
46 const aiFace &face = aiMesh->mFaces[i];
47 if(face.mNumIndices == 3) {
48 indices.push_back(face.mIndices[0]);
49 indices.push_back(face.mIndices[1]);
50 indices.push_back(face.mIndices[2]);
54 numIndices = indices.size();
56 glGenVertexArrays(1, &vao);
57 glBindVertexArray(vao);
60 glGenBuffers(6, vbos);
61 GLuint vertexVbo = vbos[0], normalVbo = vbos[1], texCoordVbo = vbos[2], indicesVbo = vbos[3];
62 GLuint boneVbo = vbos[4];
64 GLuint posLoc = glGetAttribLocation(progId, "pos");
65 glBindBuffer(GL_ARRAY_BUFFER, vertexVbo);
66 glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);
67 glEnableVertexAttribArray(posLoc);
68 glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
70 GLuint normalLoc = glGetAttribLocation(progId, "unscaledNormal");
71 glBindBuffer(GL_ARRAY_BUFFER, normalVbo);
72 glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW);
73 glEnableVertexAttribArray(normalLoc);
74 glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
76 GLuint texCoordLoc = glGetAttribLocation(progId, "vTexCoord");
77 glBindBuffer(GL_ARRAY_BUFFER, texCoordVbo);
78 glBufferData(GL_ARRAY_BUFFER, texCoords.size() * sizeof(glm::vec2), &texCoords[0], GL_STATIC_DRAW);
79 glEnableVertexAttribArray(texCoordLoc);
80 glVertexAttribPointer(texCoordLoc, 2, GL_FLOAT, GL_FALSE, 0, 0);
82 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesVbo);
83 glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &indices[0], GL_STATIC_DRAW);
86 std::vector<VertBones> vertBones(aiMesh->mNumVertices);
88 std::map<unsigned int, std::vector<std::pair<unsigned int, float>>> boneWeightMap;
90 for (unsigned int i = 0; i < aiMesh->mNumBones; i++) {
91 aiBone *aiBone = aiMesh->mBones[i];
93 boneMap[std::string(aiBone->mName.C_Str())] = std::pair(i + 1, aiMatrixToMat4(aiBone->mOffsetMatrix));
95 for (int j = 0; j < aiBone->mNumWeights; j++) {
96 aiVertexWeight vw = aiBone->mWeights[j];
98 if (!boneWeightMap.count(vw.mVertexId)) boneWeightMap[vw.mVertexId] = std::vector<std::pair<unsigned int, float>>();
99 boneWeightMap[vw.mVertexId].push_back(std::pair(i + 1, vw.mWeight));
103 for (auto pair: boneWeightMap) {
104 unsigned int vertexId = pair.first;
105 for (int i = 0; i < pair.second.size() && i < 4; i++) {
106 unsigned int boneId = pair.second[i].first;
107 float weight = pair.second[i].second;
108 vertBones[vertexId].ids[i] = boneId;
109 vertBones[vertexId].weights[i] = weight;
113 glBindBuffer(GL_ARRAY_BUFFER, boneVbo);
114 glBufferData(GL_ARRAY_BUFFER, sizeof(VertBones) * vertBones.size(), &vertBones[0], GL_STATIC_DRAW);
116 GLuint boneIdLoc = glGetAttribLocation(progId, "boneIds");
117 glEnableVertexAttribArray(boneIdLoc);
118 glVertexAttribIPointer(boneIdLoc, 4, GL_INT, sizeof(VertBones), 0);
120 GLuint boneWeightLoc = glGetAttribLocation(progId, "boneWeights");
121 glEnableVertexAttribArray(boneWeightLoc);
122 glVertexAttribPointer(boneWeightLoc, 4, GL_FLOAT, GL_FALSE, sizeof(VertBones), (const GLvoid *)sizeof(VertBones::ids));
125 Model::Node::Node(const aiNode &node, GLuint progId, AnimMap *am): ai(node), progId(progId), animMap(am) {
126 for (int i = 0; i < node.mNumMeshes; i++) {
127 meshIndices.push_back(node.mMeshes[i]);
129 for (int i = 0; i < node.mNumChildren; i++) {
130 const aiNode *child = node.mChildren[i];
131 children.push_back(new Node(*child, progId, am));
135 glm::mat4 lerp(const aiNodeAnim *anim, const float tick) {
137 if (anim->mNumPositionKeys == 0) return glm::mat4(1.f);
140 for (int i = 0; i < anim->mNumPositionKeys; i++) {
141 aiVectorKey vk = anim->mPositionKeys[i];
142 if (vk.mTime > tick) {
149 lerpPos = anim->mPositionKeys[0].mValue;
151 auto X = anim->mPositionKeys[yIndex - 1];
152 auto Y = anim->mPositionKeys[yIndex];
154 lerpPos = (X.mValue * (float)(Y.mTime - tick) + Y.mValue * (float)(tick - X.mTime)) / (float)(Y.mTime - X.mTime);
157 aiMatrix4x4::Translation(lerpPos, result);
158 return aiMatrixToMat4(result);
161 glm::mat4 lerpRotation(const aiNodeAnim *anim, const float tick) {
163 for (int i = 0; i < anim->mNumRotationKeys; i++) {
164 aiQuatKey vk = anim->mRotationKeys[i];
165 if (vk.mTime > tick) {
173 result = anim->mRotationKeys[0].mValue;
176 auto X = anim->mRotationKeys[yIndex - 1];
177 auto Y = anim->mRotationKeys[yIndex];
179 float mix = (tick - X.mTime) / (Y.mTime - X.mTime);
181 aiQuaternion::Interpolate(result, X.mValue, Y.mValue, mix);
184 return aiMatrixToMat4(aiMatrix4x4(result.GetMatrix()));
187 glm::mat4 lerpScaling(const aiNodeAnim *anim, const float tick) {
189 for (int i = 0; i < anim->mNumScalingKeys; i++) {
190 aiVectorKey vk = anim->mScalingKeys[i];
191 if (vk.mTime > tick) {
199 lerpPos = anim->mScalingKeys[0].mValue;
201 auto X = anim->mScalingKeys[yIndex - 1];
202 auto Y = anim->mScalingKeys[yIndex];
204 lerpPos = (X.mValue * (float)(Y.mTime - tick) + Y.mValue * (float)(tick - X.mTime)) / (float)(Y.mTime - X.mTime);
207 aiMatrix4x4::Scaling(lerpPos, result);
208 return aiMatrixToMat4(result);
211 void Model::Node::draw( const std::vector<Mesh> &meshes,
212 const std::vector<Material> &materials,
215 glm::mat4 parentTrans = glm::mat4(1),
216 BoneTransforms boneTransforms = BoneTransforms()) const {
218 GLuint modelLoc = glGetUniformLocation(progId, "model");
220 glm::mat4 animTrans(1.f);
221 if (animMap->count(std::string(ai.mName.C_Str()))) {
222 for (const Animation anim: animMap->at(std::string(ai.mName.C_Str()))) {
223 float t = fmod(tick, anim.duration);
224 for (const aiNodeAnim *nodeAnim: anim.nodeAnims) {
225 animTrans *= lerp(nodeAnim, t);
226 animTrans *= lerpRotation(nodeAnim, t);
227 animTrans *= lerpScaling(nodeAnim, t);
230 /* std::cerr << std::string(ai.mName.C_Str()) << animTrans[0][0] << std::endl; */
234 glm::mat4 m = parentTrans * animTrans * aiMatrixToMat4(ai.mTransformation) * model;
236 for (auto child: children) {
237 //set to parent transforms
238 boneTransforms[std::string(ai.mName.C_Str())] = m;
241 for (unsigned int i: meshIndices) {
242 const Mesh &mesh = meshes[i];
243 glBindVertexArray(mesh.vao);
246 std::vector<glm::mat4> idBones(17, glm::mat4(1.f));
247 glUniformMatrix4fv(glGetUniformLocation(progId, "bones"), 17, GL_FALSE, glm::value_ptr(idBones[0]));
249 for (std::pair<std::string, std::pair<unsigned int, glm::mat4>> pair: mesh.boneMap) {
251 std::string nodeName = pair.first;
252 unsigned int boneId = pair.second.first;
253 glm::mat4 boneOffset = pair.second.second;
255 glm::mat4 boneTrans(1.f);
256 if (boneTransforms.count(nodeName)) boneTrans = boneTransforms[nodeName];
258 for (const Animation anim: animMap->at(nodeName)) {
259 float t = fmod(tick, anim.duration);
260 for (const aiNodeAnim *nodeAnim: anim.nodeAnims) {
261 boneTrans = boneTrans * lerp(nodeAnim, t);
262 boneTrans = boneTrans * lerpRotation(nodeAnim, t);
263 /* boneTrans = boneTrans * lerpScaling(nodeAnim, t); */
270 boneTrans = boneTrans * glm::inverse(boneOffset);
273 std::string boneLocStr = "bones[" + std::to_string(boneId) + "]";
274 GLuint boneLoc = glGetUniformLocation(progId, boneLocStr.c_str());
275 glUniformMatrix4fv(boneLoc, 1, GL_FALSE, glm::value_ptr(boneTrans));
278 Material material = materials[mesh.materialIndex];
281 glUniform1i(glGetUniformLocation(progId, "irradianceMap"), 4);
282 glActiveTexture(GL_TEXTURE4);
283 glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getIrradianceMap());
285 glUniform1i(glGetUniformLocation(progId, "prefilterMap"), 5);
286 glActiveTexture(GL_TEXTURE5);
287 glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getPrefilterMap());
289 glUniform1i(glGetUniformLocation(progId, "brdfMap"), 6);
290 glActiveTexture(GL_TEXTURE6);
291 glBindTexture(GL_TEXTURE_2D, skybox.getBRDFMap());
293 glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(m));
295 glDrawElements(GL_TRIANGLES, mesh.numIndices, GL_UNSIGNED_INT, 0);
297 for (Node *child: children) child->draw(meshes, materials, skybox, tick, m, boneTransforms);
300 Model::Model(const std::string &path, Program p): program(p) {
301 glUseProgram(p.progId);
303 const aiScene *scene = importer.ReadFile(path,
304 aiProcess_Triangulate | aiProcess_CalcTangentSpace | aiProcess_GenNormals | aiProcess_FlipUVs);
306 std::cerr << importer.GetErrorString() << std::endl;
310 for (int i = 0; i < scene->mNumMeshes; i++) {
311 const aiMesh *mesh = scene->mMeshes[i];
312 meshes.push_back(Mesh(mesh, p.progId));
315 // TODO: handle default material inserted at the end by assimp
316 for (unsigned int i = 0; i < scene->mNumMaterials - 1; i++) {
317 const aiMaterial &material = *scene->mMaterials[i];
318 materials.push_back(Material(material, p.progId));
321 AnimMap *animMap = new AnimMap();
322 for (int i = 0; i < scene->mNumAnimations; i++) {
323 const aiAnimation *aiAnim = scene->mAnimations[i];
325 std::map<std::string, std::vector<const aiNodeAnim*>> nodeAnims;
327 for (int j = 0; j < aiAnim->mNumChannels; j++) {
328 const aiNodeAnim *nodeAnim = aiAnim->mChannels[j];
329 std::string nodeName = std::string(nodeAnim->mNodeName.C_Str());
331 if (!nodeAnims.count(nodeName)) nodeAnims[nodeName] = std::vector<const aiNodeAnim*>();
333 nodeAnims[nodeName].push_back(nodeAnim);
336 for (std::pair<std::string, std::vector<const aiNodeAnim*>> pair: nodeAnims) {
337 std::string nodeName = pair.first;
339 if (!animMap->count(nodeName)) (*animMap)[nodeName] = std::vector<const Animation>();
340 (*animMap)[nodeName].push_back({ 7500, pair.second });
344 root = new Node(*(scene->mRootNode), p.progId, animMap);
347 void Model::draw(Skybox skybox, const float tick) const {
348 glUseProgram(program.progId);
349 root->draw(meshes, materials, skybox, tick);
352 Model::Node* Model::find(const std::string &name) {
353 return find(aiString(name));
356 Model::Node* Model::find(const aiString name) {
357 const aiNode *node = root->ai.FindNode(name);
358 Model::Node* res = root->findNode(*node);
362 Model::Node* Model::Node::findNode(const aiNode &aiNode) {
363 if (&ai == &aiNode) return this;
364 for (Model::Node *child: children) {
365 Model::Node *res = child->findNode(aiNode);