Do boning and animation properly
[opengl.git] / model.cpp
index 3c1ecf4830c2ce95989a09bfb4935cfb7d21d767..5302df06238038d32a686e8bffb2c62881f19a91 100644 (file)
--- a/model.cpp
+++ b/model.cpp
@@ -2,6 +2,7 @@
 #include <iostream>
 #include <assimp/quaternion.h>
 #include <glm/gtc/type_ptr.hpp>
+#include "util.hpp"
 
 
 Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) {
@@ -19,7 +20,7 @@ Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) {
                        normals.push_back(glm::vec3(v.x, v.y, v.z));
                } else {
                        std::cerr << "Missing normals" << std::endl;
-                       exit(1);
+                       abort();
                }
                // check for texture coord set 0
                if (aiMesh->HasTextureCoords(0)) {
@@ -81,12 +82,13 @@ Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) {
        for (unsigned int i = 0; i < aiMesh->mNumBones; i++) {
                aiBone *aiBone = aiMesh->mBones[i];
 
-               boneMap[std::string(aiBone->mName.C_Str())] = std::pair(i + 1, aiMatrixToMat4(aiBone->mOffsetMatrix));
+               boneMap[std::string(aiBone->mName.C_Str())] = std::pair(i + 1, aiBone);
 
                for (int j = 0; j < aiBone->mNumWeights; j++) {
                        aiVertexWeight vw = aiBone->mWeights[j];
 
-                       if (!boneWeightMap.count(vw.mVertexId)) boneWeightMap[vw.mVertexId] = std::vector<std::pair<unsigned int, float>>();
+                       if (!boneWeightMap.count(vw.mVertexId))
+                               boneWeightMap[vw.mVertexId] = std::vector<std::pair<unsigned int, float>>();
                        boneWeightMap[vw.mVertexId].push_back(std::pair(i + 1, vw.mWeight));
                }
        }
@@ -202,33 +204,39 @@ glm::mat4 lerpScaling(const aiNodeAnim *anim, const float tick) {
        return aiMatrixToMat4(result);
 }
 
-void Model::Node::draw(        const std::vector<Mesh> &meshes,
-                                               const std::vector<Material> &materials,
-                                               const Skybox skybox,
-                                               const float tick,
-                                               glm::mat4 parentTrans = glm::mat4(1),
-                                               BoneTransforms boneTransforms = BoneTransforms()) const {
-
-       GLuint modelLoc = glGetUniformLocation(progId, "model");
-
-       glm::mat4 animTrans(1.f);
+glm::mat4 Model::Node::totalTrans(const glm::mat4 parentTrans, const float tick) const {
+       glm::mat4 aiTrans = aiMatrixToMat4(ai.mTransformation);
        if (animMap->count(std::string(ai.mName.C_Str()))) {
                for (const Animation anim: animMap->at(std::string(ai.mName.C_Str()))) {
+                       // animations are *absolute*
+                       // they replace aiNode.mTransformation!!
+                       aiTrans = glm::mat4(1);
                        float t = fmod(tick, anim.duration);
                        for (const aiNodeAnim *nodeAnim: anim.nodeAnims) {
-                               animTrans *= lerpPosition(nodeAnim, t);
-                               animTrans *= lerpRotation(nodeAnim, t);
-                               animTrans *= lerpScaling(nodeAnim, t);
+                               aiTrans *= lerpPosition(nodeAnim, t);
+                               aiTrans *= lerpRotation(nodeAnim, t);
+                               aiTrans *= lerpScaling(nodeAnim, t);
+                       }
                }
        }
+
+       glm::mat4 m = parentTrans * aiTrans * transform;
+       return m;
 }
 
+void Model::Node::draw(        const std::vector<Mesh> &meshes,
+                                               const std::vector<Material> &materials,
+                                               const Skybox skybox,
+                                               const float tick,
+                                               const BoneTransforms &boneTransforms,
+                                               glm::mat4 parentTrans = glm::mat4(1)) const {
 
-       glm::mat4 m = parentTrans * animTrans * aiMatrixToMat4(ai.mTransformation);
+       GLuint modelLoc = glGetUniformLocation(progId, "model");
+       glm::mat4 m = totalTrans(parentTrans, tick);
 
-       /* for (auto child: children) { */
-       /*      boneTransforms[std::string(ai.mName.C_Str())] = m; */
-       /* } */
+#ifdef DEBUG_NODES
+       drawDebugNode(m);
+#endif
 
        for (unsigned int i: meshIndices) {
                const Mesh &mesh = meshes[i];
@@ -238,35 +246,23 @@ void Model::Node::draw(   const std::vector<Mesh> &meshes,
                std::vector<glm::mat4> idBones(17, glm::mat4(1.f));
                glUniformMatrix4fv(glGetUniformLocation(progId, "bones"), 17, GL_FALSE, glm::value_ptr(idBones[0]));
 
-               for (std::pair<std::string, std::pair<unsigned int, glm::mat4>> pair: mesh.boneMap) {
-
-                       std::string nodeName = pair.first;
+               // bonemap: map from bone nodes to bone ids and aiBones
+               for (auto pair: mesh.boneMap) {
 
-                       if (animMap->count(nodeName) <= 0) break;
+                       std::string boneName = pair.first;
 
                        unsigned int boneId = pair.second.first;
+                       aiBone *bone = pair.second.second;
                        // This is actually an inverse-bind matrix
-                       // i.e. position of the mesh in bone space
+                       // i.e. transforms bone space -> mesh space
                        // so no need to inverse again!
                        // https://github.com/assimp/assimp/pull/1803/files
-                       glm::mat4 boneOffset = pair.second.second;
-
-                       glm::mat4 boneTrans(1.f);
-                       /* if (boneTransforms.count(nodeName)) { */
-                       /*      std::cerr << "got bone transform from map" << std::endl; */
-                       /*      boneTrans = boneTransforms[nodeName]; */
-                       /* } */
-                       for (const Animation anim: animMap->at(nodeName)) {
-                               float t = fmod(tick, anim.duration);
-                               for (const aiNodeAnim *nodeAnim: anim.nodeAnims) {
-                                       boneTrans = boneTrans * lerpPosition(nodeAnim, t);
-                                       boneTrans = boneTrans * lerpRotation(nodeAnim, t);
-                                       boneTrans = boneTrans * lerpScaling(nodeAnim, t);
-                               }
-                       }
+                       glm::mat4 boneOffset = aiMatrixToMat4(bone->mOffsetMatrix);
 
-                       boneTrans = boneTrans * boneOffset;
+                       if (!boneTransforms.count(boneName)) abort();
+                       glm::mat4 boneTrans = boneTransforms.at(boneName);
 
+                       boneTrans = boneTrans * boneOffset;
 
                        std::string boneLocStr = "bones[" + std::to_string(boneId) + "]";
                        GLuint boneLoc = glGetUniformLocation(progId, boneLocStr.c_str());
@@ -292,7 +288,23 @@ void Model::Node::draw(    const std::vector<Mesh> &meshes,
 
                glDrawElements(GL_TRIANGLES, mesh.numIndices, GL_UNSIGNED_INT, 0);
        }
-       for (Node *child: children) child->draw(meshes, materials, skybox, tick, m, boneTransforms);
+       for (Node *child: children) child->draw(meshes, materials, skybox, tick, boneTransforms, m);
+}
+
+void printMatrix4x4(aiMatrix4x4 m) {
+       fprintf(stderr, "%f, %f, %f, %f\n", m.a1, m.a2, m.a3, m.a4);
+       fprintf(stderr, "%f, %f, %f, %f\n", m.b1, m.b2, m.b3, m.b4);
+       fprintf(stderr, "%f, %f, %f, %f\n", m.c1, m.c2, m.c3, m.c4);
+       fprintf(stderr, "%f, %f, %f, %f\n", m.d1, m.d2, m.d3, m.d4);
+}
+
+void printHierarchy(aiNode *n, int indent = 0) {
+       for (int i = 0; i < indent; i++)
+               fprintf(stderr, "\t");
+       fprintf(stderr,"%s\n", n->mName.C_Str());
+       printMatrix4x4(n->mTransformation);
+       for (int i = 0; i < n->mNumChildren; i++)
+               printHierarchy(n->mChildren[i], indent + 1);
 }
 
 Model::Model(const aiScene *scene, Program p): program(p) {
@@ -303,13 +315,11 @@ Model::Model(const aiScene *scene, Program p): program(p) {
                meshes.push_back(Mesh(mesh, p.progId));
        }
 
-       // TODO: handle default material inserted at the end by assimp
        for (unsigned int i = 0; i < scene->mNumMaterials; i++) {
                const aiMaterial &material = *scene->mMaterials[i];
                materials.push_back(Material(material, *scene, p.progId));
        }
 
-       AnimMap *animMap = new AnimMap();
        for (int i = 0; i < scene->mNumAnimations; i++) {
                const aiAnimation *aiAnim = scene->mAnimations[i];
 
@@ -327,44 +337,49 @@ Model::Model(const aiScene *scene, Program p): program(p) {
                for (std::pair<std::string, std::vector<const aiNodeAnim*>> pair: nodeAnims) {
                        std::string nodeName = pair.first;
 
-                       if (!animMap->count(nodeName)) (*animMap)[nodeName] = std::vector<const Animation>();
-                       (*animMap)[nodeName].push_back({ aiAnim->mDuration, pair.second });
+                       if (!animMap.count(nodeName)) animMap[nodeName] = std::vector<const Animation>();
+                       animMap[nodeName].push_back({ aiAnim->mDuration, pair.second });
                }
        }
 
-       root = new Node(*(scene->mRootNode), p.progId, animMap);
+       root = new Node(*(scene->mRootNode), p.progId, &animMap);
 }
 
-/* void Model::calcBoneTransforms(aiNode &node, glm::mat4 parentTrans = glm::mat4(1), BoneTransforms boneTrans = BoneTransforms()) { */
-/*     glm::mat4 animTrans(1.f); */
-/*     if (animMap->count(std::string(ai.mName.C_Str()))) { */
-/*             for (const Animation anim: animMap->at(std::string(ai.mName.C_Str()))) { */
-/*                     float t = fmod(tick, anim.duration); */
-/*                     for (const aiNodeAnim *nodeAnim: anim.nodeAnims) { */
-/*                             animTrans *= lerpPosition(nodeAnim, t); */
-/*                             animTrans *= lerpRotation(nodeAnim, t); */
-/*                             animTrans *= lerpScaling(nodeAnim, t); */
-/*                     } */
-/*             } */
-/*     } */
 
+std::map<std::string, glm::mat4> Model::calcBoneTransforms(const Node &n, const float tick, const std::set<std::string> bones, const glm::mat4 parentTrans = glm::mat4(1)) const {
+       std::string name = std::string(n.ai.mName.C_Str());
 
-/*     glm::mat4 m = parentTrans * animTrans * aiMatrixToMat4(ai.mTransformation) * model; */
-/* } */
+       glm::mat4 m = n.totalTrans(parentTrans, tick);
+
+       BoneTransforms res;
+       if (bones.count(name) > 0)
+               res[std::string(n.ai.mName.C_Str())] = m; // take part in hierarchy
+       else
+               m = glm::mat4(1); // ignore this node transformation
+       for (const auto child: n.getChildren())
+               res.merge(calcBoneTransforms(*child, tick, bones, m));
+       return res;
+}
 
 void Model::draw(Skybox skybox, const float tick) const {
        glUseProgram(program.progId);
 
+       std::set<std::string> bones;
+       for (auto m: this->meshes) {
+               for (auto b: m.boneMap) {
+                       bones.insert(b.first);
+               }
+       }
+       auto boneTransforms = calcBoneTransforms(*root, tick, bones);
 
-
-       root->draw(meshes, materials, skybox, tick);
+       root->draw(meshes, materials, skybox, tick, boneTransforms);
 }
 
-Model::Node* Model::find(const std::string &name) {
+Model::Node* Model::find(const std::string &name) const {
        return find(aiString(name));
 }
 
-Model::Node* Model::find(const aiString name) {
+Model::Node* Model::find(const aiString name) const {
        const aiNode *node = root->ai.FindNode(name);
        Model::Node* res = root->findNode(*node);
        return res;