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];
15 Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) {
17 std::vector<glm::vec3> vertices, normals, tangents, bitangents;
18 std::vector<glm::vec2> texCoords;
20 for (int i = 0; i < aiMesh->mNumVertices; i++) {
21 if (aiMesh->HasPositions()) {
22 aiVector3D v = aiMesh->mVertices[i];
23 vertices.push_back(glm::vec3(v.x, v.y, v.z));
25 if (aiMesh->HasNormals()) {
26 aiVector3D v = aiMesh->mNormals[i];
27 normals.push_back(glm::vec3(v.x, v.y, v.z));
29 std::cerr << "Missing normals" << std::endl;
32 // check for texture coord set 0
33 if (aiMesh->HasTextureCoords(0)) {
34 const aiVector3D v = aiMesh->mTextureCoords[0][i];
35 texCoords.push_back(glm::vec2(v.x, v.y));
37 texCoords.push_back(glm::vec2(0));
39 materialIndex = aiMesh->mMaterialIndex;
42 std::vector<GLuint> indices;
44 for (int i = 0; i < aiMesh->mNumFaces; i++) {
45 const aiFace &face = aiMesh->mFaces[i];
46 if(face.mNumIndices == 3) {
47 indices.push_back(face.mIndices[0]);
48 indices.push_back(face.mIndices[1]);
49 indices.push_back(face.mIndices[2]);
53 numIndices = indices.size();
55 glGenVertexArrays(1, &vao);
56 glBindVertexArray(vao);
59 glGenBuffers(6, vbos);
60 GLuint vertexVbo = vbos[0], normalVbo = vbos[1], texCoordVbo = vbos[2], indicesVbo = vbos[3];
61 GLuint boneVbo = vbos[4];
63 GLuint posLoc = glGetAttribLocation(progId, "pos");
64 glBindBuffer(GL_ARRAY_BUFFER, vertexVbo);
65 glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);
66 glEnableVertexAttribArray(posLoc);
67 glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
69 GLuint normalLoc = glGetAttribLocation(progId, "unscaledNormal");
70 glBindBuffer(GL_ARRAY_BUFFER, normalVbo);
71 glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW);
72 glEnableVertexAttribArray(normalLoc);
73 glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
75 GLuint texCoordLoc = glGetAttribLocation(progId, "vTexCoord");
76 glBindBuffer(GL_ARRAY_BUFFER, texCoordVbo);
77 glBufferData(GL_ARRAY_BUFFER, texCoords.size() * sizeof(glm::vec2), &texCoords[0], GL_STATIC_DRAW);
78 glEnableVertexAttribArray(texCoordLoc);
79 glVertexAttribPointer(texCoordLoc, 2, GL_FLOAT, GL_FALSE, 0, 0);
81 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesVbo);
82 glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &indices[0], GL_STATIC_DRAW);
85 std::vector<VertBones> vertBones(aiMesh->mNumVertices);
87 std::map<unsigned int, std::vector<std::pair<unsigned int, float>>> boneWeightMap;
89 for (unsigned int i = 0; i < aiMesh->mNumBones; i++) {
90 aiBone *aiBone = aiMesh->mBones[i];
92 boneMap[std::string(aiBone->mName.C_Str())] = std::pair(i + 1, aiMatrixToMat4(aiBone->mOffsetMatrix));
94 for (int j = 0; j < aiBone->mNumWeights; j++) {
95 aiVertexWeight vw = aiBone->mWeights[j];
97 if (!boneWeightMap.count(vw.mVertexId)) boneWeightMap[vw.mVertexId] = std::vector<std::pair<unsigned int, float>>();
98 boneWeightMap[vw.mVertexId].push_back(std::pair(i + 1, vw.mWeight));
102 for (auto pair: boneWeightMap) {
103 unsigned int vertexId = pair.first;
104 for (int i = 0; i < pair.second.size() && i < 4; i++) {
105 unsigned int boneId = pair.second[i].first;
106 float weight = pair.second[i].second;
107 vertBones[vertexId].ids[i] = boneId;
108 vertBones[vertexId].weights[i] = weight;
112 glBindBuffer(GL_ARRAY_BUFFER, boneVbo);
113 glBufferData(GL_ARRAY_BUFFER, sizeof(VertBones) * vertBones.size(), &vertBones[0], GL_STATIC_DRAW);
115 GLuint boneIdLoc = glGetAttribLocation(progId, "boneIds");
116 glEnableVertexAttribArray(boneIdLoc);
117 glVertexAttribIPointer(boneIdLoc, 4, GL_INT, sizeof(VertBones), 0);
119 GLuint boneWeightLoc = glGetAttribLocation(progId, "boneWeights");
120 glEnableVertexAttribArray(boneWeightLoc);
121 glVertexAttribPointer(boneWeightLoc, 4, GL_FLOAT, GL_FALSE, sizeof(VertBones), (const GLvoid *)sizeof(VertBones::ids));
124 Model::Node::Node(const aiNode &node, GLuint progId, AnimMap *am): ai(node), progId(progId), animMap(am) {
125 for (int i = 0; i < node.mNumMeshes; i++) {
126 meshIndices.push_back(node.mMeshes[i]);
128 for (int i = 0; i < node.mNumChildren; i++) {
129 const aiNode *child = node.mChildren[i];
130 children.push_back(new Node(*child, progId, am));
134 glm::mat4 lerpPosition(const aiNodeAnim *anim, const float tick) {
135 if (anim->mNumPositionKeys == 0) return glm::mat4(1.f);
138 for (int i = 0; i < anim->mNumPositionKeys; i++) {
139 aiVectorKey vk = anim->mPositionKeys[i];
140 if (vk.mTime > tick) {
147 lerpPos = anim->mPositionKeys[0].mValue;
148 } else if (yIndex == -1) {
149 lerpPos = anim->mPositionKeys[anim->mNumPositionKeys - 1].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;
174 } else if (yIndex == -1) {
175 result = anim->mRotationKeys[anim->mNumRotationKeys - 1].mValue;
178 auto X = anim->mRotationKeys[yIndex - 1];
179 auto Y = anim->mRotationKeys[yIndex];
181 float mix = (tick - X.mTime) / (Y.mTime - X.mTime);
183 aiQuaternion::Interpolate(result, X.mValue, Y.mValue, mix);
186 return aiMatrixToMat4(aiMatrix4x4(result.GetMatrix()));
189 glm::mat4 lerpScaling(const aiNodeAnim *anim, const float tick) {
191 for (int i = 0; i < anim->mNumScalingKeys; i++) {
192 aiVectorKey vk = anim->mScalingKeys[i];
193 if (vk.mTime > tick) {
201 lerpPos = anim->mScalingKeys[0].mValue;
203 auto X = anim->mScalingKeys[yIndex - 1];
204 auto Y = anim->mScalingKeys[yIndex];
206 lerpPos = (X.mValue * (float)(Y.mTime - tick) + Y.mValue * (float)(tick - X.mTime)) / (float)(Y.mTime - X.mTime);
209 aiMatrix4x4::Scaling(lerpPos, result);
210 return aiMatrixToMat4(result);
213 void Model::Node::draw( const std::vector<Mesh> &meshes,
214 const std::vector<Material> &materials,
217 glm::mat4 parentTrans = glm::mat4(1),
218 BoneTransforms boneTransforms = BoneTransforms()) const {
220 GLuint modelLoc = glGetUniformLocation(progId, "model");
222 glm::mat4 animTrans(1.f);
223 if (animMap->count(std::string(ai.mName.C_Str()))) {
224 for (const Animation anim: animMap->at(std::string(ai.mName.C_Str()))) {
225 float t = fmod(tick, anim.duration);
226 for (const aiNodeAnim *nodeAnim: anim.nodeAnims) {
227 animTrans *= lerpPosition(nodeAnim, t);
228 animTrans *= lerpRotation(nodeAnim, t);
229 animTrans *= lerpScaling(nodeAnim, t);
235 glm::mat4 m = parentTrans * animTrans * aiMatrixToMat4(ai.mTransformation) * model;
237 for (auto child: children) {
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)) {
257 std::cerr << "got bone transform from map" << std::endl;
258 boneTrans = boneTransforms[nodeName];
260 for (const Animation anim: animMap->at(nodeName)) {
261 float t = fmod(tick, anim.duration);
262 for (const aiNodeAnim *nodeAnim: anim.nodeAnims) {
263 boneTrans = boneTrans * lerpPosition(nodeAnim, t);
264 boneTrans = boneTrans * lerpRotation(nodeAnim, t);
265 boneTrans = boneTrans * lerpScaling(nodeAnim, t);
269 boneTrans = boneTrans * glm::inverse(boneOffset);
272 std::string boneLocStr = "bones[" + std::to_string(boneId) + "]";
273 GLuint boneLoc = glGetUniformLocation(progId, boneLocStr.c_str());
274 glUniformMatrix4fv(boneLoc, 1, GL_FALSE, glm::value_ptr(boneTrans));
277 Material material = materials[mesh.materialIndex];
280 glUniform1i(glGetUniformLocation(progId, "irradianceMap"), 4);
281 glActiveTexture(GL_TEXTURE4);
282 glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getIrradianceMap());
284 glUniform1i(glGetUniformLocation(progId, "prefilterMap"), 5);
285 glActiveTexture(GL_TEXTURE5);
286 glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getPrefilterMap());
288 glUniform1i(glGetUniformLocation(progId, "brdfMap"), 6);
289 glActiveTexture(GL_TEXTURE6);
290 glBindTexture(GL_TEXTURE_2D, skybox.getBRDFMap());
292 glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(m));
294 glDrawElements(GL_TRIANGLES, mesh.numIndices, GL_UNSIGNED_INT, 0);
296 for (Node *child: children) child->draw(meshes, materials, skybox, tick, m, boneTransforms);
299 Model::Model(const std::string &path, Program p): program(p) {
300 glUseProgram(p.progId);
302 const aiScene *scene = importer.ReadFile(path,
303 aiProcess_Triangulate | aiProcess_CalcTangentSpace | aiProcess_GenNormals | aiProcess_FlipUVs);
305 std::cerr << importer.GetErrorString() << std::endl;
309 for (int i = 0; i < scene->mNumMeshes; i++) {
310 const aiMesh *mesh = scene->mMeshes[i];
311 meshes.push_back(Mesh(mesh, p.progId));
314 // TODO: handle default material inserted at the end by assimp
315 for (unsigned int i = 0; i < scene->mNumMaterials - 1; i++) {
316 const aiMaterial &material = *scene->mMaterials[i];
317 materials.push_back(Material(material, *scene, p.progId));
320 AnimMap *animMap = new AnimMap();
321 for (int i = 0; i < scene->mNumAnimations; i++) {
322 const aiAnimation *aiAnim = scene->mAnimations[i];
324 std::map<std::string, std::vector<const aiNodeAnim*>> nodeAnims;
326 for (int j = 0; j < aiAnim->mNumChannels; j++) {
327 const aiNodeAnim *nodeAnim = aiAnim->mChannels[j];
328 std::string nodeName = std::string(nodeAnim->mNodeName.C_Str());
330 if (!nodeAnims.count(nodeName)) nodeAnims[nodeName] = std::vector<const aiNodeAnim*>();
332 nodeAnims[nodeName].push_back(nodeAnim);
335 for (std::pair<std::string, std::vector<const aiNodeAnim*>> pair: nodeAnims) {
336 std::string nodeName = pair.first;
338 if (!animMap->count(nodeName)) (*animMap)[nodeName] = std::vector<const Animation>();
339 (*animMap)[nodeName].push_back({ aiAnim->mDuration, pair.second });
343 root = new Node(*(scene->mRootNode), p.progId, animMap);
346 /* void Model::calcBoneTransforms(aiNode &node, glm::mat4 parentTrans = glm::mat4(1), BoneTransforms boneTrans = BoneTransforms()) { */
347 /* glm::mat4 animTrans(1.f); */
348 /* if (animMap->count(std::string(ai.mName.C_Str()))) { */
349 /* for (const Animation anim: animMap->at(std::string(ai.mName.C_Str()))) { */
350 /* float t = fmod(tick, anim.duration); */
351 /* for (const aiNodeAnim *nodeAnim: anim.nodeAnims) { */
352 /* animTrans *= lerpPosition(nodeAnim, t); */
353 /* animTrans *= lerpRotation(nodeAnim, t); */
354 /* animTrans *= lerpScaling(nodeAnim, t); */
360 /* glm::mat4 m = parentTrans * animTrans * aiMatrixToMat4(ai.mTransformation) * model; */
363 void Model::draw(Skybox skybox, const float tick) const {
364 glUseProgram(program.progId);
368 root->draw(meshes, materials, skybox, tick);
371 Model::Node* Model::find(const std::string &name) {
372 return find(aiString(name));
375 Model::Node* Model::find(const aiString name) {
376 const aiNode *node = root->ai.FindNode(name);
377 Model::Node* res = root->findNode(*node);
381 Model::Node* Model::Node::findNode(const aiNode &aiNode) {
382 if (&ai == &aiNode) return this;
383 for (Model::Node *child: children) {
384 Model::Node *res = child->findNode(aiNode);