/* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2012, assimp team All rights reserved. Redistribution and use of this software in aSource and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of aSource code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------- */ #include "AssimpPCH.h" #ifndef ASSIMP_BUILD_NO_OGRE_IMPORTER #include "OgreImporter.h" #include "TinyFormatter.h" using namespace std; namespace Assimp { namespace Ogre { void OgreImporter::ReadSkeleton(const std::string &pFile, Assimp::IOSystem *pIOHandler, const aiScene *pScene, const std::string &skeletonFile, vector &Bones, vector &Animations) const { string filename = skeletonFile; if (EndsWith(filename, ".skeleton")) { DefaultLogger::get()->warn("Mesh is referencing a Ogre binary skeleton. Parsing binary Ogre assets is not supported at the moment. Trying to find .skeleton.xml file instead."); filename += ".xml"; } if (!pIOHandler->Exists(filename)) { DefaultLogger::get()->error("Failed to find skeleton file '" + filename + "', skeleton will be missing."); return; } boost::scoped_ptr file(pIOHandler->Open(filename)); if (!file.get()) throw DeadlyImportError("Failed to open skeleton file " + filename); boost::scoped_ptr stream(new CIrrXML_IOStreamReader(file.get())); XmlReader* reader = irr::io::createIrrXMLReader(stream.get()); if (!reader) throw DeadlyImportError("Failed to create XML reader for skeleton file " + filename); DefaultLogger::get()->debug("Reading skeleton '" + filename + "'"); // Root NextNode(reader); if (!CurrentNodeNameEquals(reader, "skeleton")) throw DeadlyImportError("Root node is not but <" + string(reader->getNodeName()) + "> in " + filename); // Bones NextNode(reader); if (!CurrentNodeNameEquals(reader, "bones")) throw DeadlyImportError("No node in skeleton " + skeletonFile); NextNode(reader); while(CurrentNodeNameEquals(reader, "bone")) { //TODO: Maybe we can have bone ids for the errrors, but normaly, they should never appear, so what.... /// @todo What does the above mean? Bone bone; bone.Id = GetAttribute(reader, "id"); bone.Name = GetAttribute(reader, "name"); NextNode(reader); if (!CurrentNodeNameEquals(reader, "position")) throw DeadlyImportError("Position is not first node in Bone!"); bone.Position.x = GetAttribute(reader, "x"); bone.Position.y = GetAttribute(reader, "y"); bone.Position.z = GetAttribute(reader, "z"); NextNode(reader); if (!CurrentNodeNameEquals(reader, "rotation")) throw DeadlyImportError("Rotation is not the second node in Bone!"); bone.RotationAngle = GetAttribute(reader, "angle"); NextNode(reader); if (!CurrentNodeNameEquals(reader, "axis")) throw DeadlyImportError("No axis specified for bone rotation!"); bone.RotationAxis.x = GetAttribute(reader, "x"); bone.RotationAxis.y = GetAttribute(reader, "y"); bone.RotationAxis.z = GetAttribute(reader, "z"); Bones.push_back(bone); NextNode(reader); } // Order bones by Id std::sort(Bones.begin(), Bones.end()); // Validate that bone indexes are not skipped. /** @note Left this from original authors code, but not sure if this is strictly necessary as per the Ogre skeleton spec. It might be more that other (later) code in this imported does not break. */ for (size_t i=0, len=Bones.size(); i(Bones[i].Id) != static_cast(i)) throw DeadlyImportError("Bone Ids are not in sequence in " + skeletonFile); DefaultLogger::get()->debug(Formatter::format() << " - Bones " << Bones.size()); // Bone hierarchy if (!CurrentNodeNameEquals(reader, "bonehierarchy")) throw DeadlyImportError("No node found after in " + skeletonFile); NextNode(reader); while(CurrentNodeNameEquals(reader, "boneparent")) { string childName = GetAttribute(reader, "bone"); string parentName = GetAttribute(reader, "parent"); vector::iterator iterChild = find(Bones.begin(), Bones.end(), childName); vector::iterator iterParent = find(Bones.begin(), Bones.end(), parentName); if (iterChild != Bones.end() && iterParent != Bones.end()) { iterChild->ParentId = iterParent->Id; iterParent->Children.push_back(iterChild->Id); } else DefaultLogger::get()->warn("Failed to find bones for parenting: Child " + childName + " Parent " + parentName); NextNode(reader); } // Calculate bone matrices for root bones. Recursively does their children. BOOST_FOREACH(Bone &theBone, Bones) { if (!theBone.IsParented()) theBone.CalculateBoneToWorldSpaceMatrix(Bones); } aiVector3D zeroVec(0.f, 0.f, 0.f); // Animations if (CurrentNodeNameEquals(reader, "animations")) { DefaultLogger::get()->debug(" - Animations"); NextNode(reader); while(CurrentNodeNameEquals(reader, "animation")) { Animation animation; animation.Name = GetAttribute(reader, "name"); animation.Length = GetAttribute(reader, "length"); // Tracks NextNode(reader); if (!CurrentNodeNameEquals(reader, "tracks")) throw DeadlyImportError("No node found in animation '" + animation.Name + "' in " + skeletonFile); NextNode(reader); while(CurrentNodeNameEquals(reader, "track")) { Track track; track.BoneName = GetAttribute(reader, "bone"); // Keyframes NextNode(reader); if (!CurrentNodeNameEquals(reader, "keyframes")) throw DeadlyImportError("No node found in a track in animation '" + animation.Name + "' in " + skeletonFile); NextNode(reader); while(CurrentNodeNameEquals(reader, "keyframe")) { KeyFrame keyFrame; keyFrame.Time = GetAttribute(reader, "time"); NextNode(reader); while(CurrentNodeNameEquals(reader, "translate") || CurrentNodeNameEquals(reader, "rotate") || CurrentNodeNameEquals(reader, "scale")) { if (CurrentNodeNameEquals(reader, "translate")) { keyFrame.Position.x = GetAttribute(reader, "x"); keyFrame.Position.y = GetAttribute(reader, "y"); keyFrame.Position.z = GetAttribute(reader, "z"); } else if (CurrentNodeNameEquals(reader, "rotate")) { float angle = GetAttribute(reader, "angle"); NextNode(reader); if(string("axis")!=reader->getNodeName()) throw DeadlyImportError("No axis for keyframe rotation!"); aiVector3D axis; axis.x = GetAttribute(reader, "x"); axis.y = GetAttribute(reader, "y"); axis.z = GetAttribute(reader, "z"); if (axis.Equal(zeroVec)) { axis.x = 1.0f; if (angle != 0) DefaultLogger::get()->warn("Found invalid a key frame with a zero rotation axis in animation '" + animation.Name + "'"); } keyFrame.Rotation = aiQuaternion(axis, angle); } else if (CurrentNodeNameEquals(reader, "scale")) { keyFrame.Scaling.x = GetAttribute(reader, "x"); keyFrame.Scaling.y = GetAttribute(reader, "y"); keyFrame.Scaling.z = GetAttribute(reader, "z"); } NextNode(reader); } track.Keyframes.push_back(keyFrame); } animation.Tracks.push_back(track); } Animations.push_back(animation); DefaultLogger::get()->debug(Formatter::format() << " " << animation.Name << " (" << animation.Length << " sec, " << animation.Tracks.size() << " tracks)"); } } } void OgreImporter::CreateAssimpSkeleton(aiScene *pScene, const std::vector &bones, const std::vector &animations) { if (bones.empty()) return; if (!pScene->mRootNode) throw DeadlyImportError("Creating Assimp skeleton: No root node created!"); if (pScene->mRootNode->mNumChildren > 0) throw DeadlyImportError("Creating Assimp skeleton: Root node already has children!"); // Bones vector rootBones; BOOST_FOREACH(const Bone &bone, bones) { if (!bone.IsParented()) rootBones.push_back(CreateNodeFromBone(bone.Id, bones, pScene->mRootNode)); } if (!rootBones.empty()) { pScene->mRootNode->mChildren = new aiNode*[rootBones.size()]; pScene->mRootNode->mNumChildren = rootBones.size(); for(size_t i=0, len=rootBones.size(); imRootNode->mChildren[i] = rootBones[i]; } // TODO: Auf nicht vorhandene Animationskeys achten! // @todo Pay attention to non-existing animation Keys (google translated from above german comment) // Animations if (!animations.empty()) { pScene->mAnimations = new aiAnimation*[animations.size()]; pScene->mNumAnimations = animations.size(); for(size_t ai=0, alen=animations.size(); aimName = aSource.Name; animation->mDuration = aSource.Length; animation->mTicksPerSecond = 1.0f; // Tracks animation->mChannels = new aiNodeAnim*[aSource.Tracks.size()]; animation->mNumChannels = aSource.Tracks.size(); for(size_t ti=0, tlen=aSource.Tracks.size(); timNodeName = tSource.BoneName; // We need this, to access the bones default pose. // Which we need to make keys absolute to the default bone pose. vector::const_iterator boneIter = find(bones.begin(), bones.end(), tSource.BoneName); if (boneIter == bones.end()) { for(unsigned int a=0; amAnimations[a]; delete [] pScene->mAnimations; pScene->mAnimations = NULL; pScene->mNumAnimations = 0; DefaultLogger::get()->error("Failed to find bone for name " + tSource.BoneName + " when creating animation " + aSource.Name + ". This is a serious error, animations wont be imported."); return; } aiMatrix4x4 t0, t1; aiMatrix4x4 defaultBonePose = aiMatrix4x4::Translation(boneIter->Position, t1) * aiMatrix4x4::Rotation(boneIter->RotationAngle, boneIter->RotationAxis, t0); // Keyframes unsigned int numKeyframes = tSource.Keyframes.size(); animationNode->mPositionKeys = new aiVectorKey[numKeyframes]; animationNode->mRotationKeys = new aiQuatKey[numKeyframes]; animationNode->mScalingKeys = new aiVectorKey[numKeyframes]; animationNode->mNumPositionKeys = numKeyframes; animationNode->mNumRotationKeys = numKeyframes; animationNode->mNumScalingKeys = numKeyframes; //...and fill them for(size_t kfi=0; kfimPositionKeys[kfi].mTime = static_cast(kfSource.Time); animationNode->mRotationKeys[kfi].mTime = static_cast(kfSource.Time); animationNode->mScalingKeys[kfi].mTime = static_cast(kfSource.Time); animationNode->mPositionKeys[kfi].mValue = kfPos; animationNode->mRotationKeys[kfi].mValue = kfRot; animationNode->mScalingKeys[kfi].mValue = kfScale; } animation->mChannels[ti] = animationNode; } pScene->mAnimations[ai] = animation; } } } aiNode* OgreImporter::CreateNodeFromBone(int boneId, const std::vector &bones, aiNode* parent) { aiMatrix4x4 t0,t1; const Bone &source = bones[boneId]; aiNode* boneNode = new aiNode(source.Name); boneNode->mParent = parent; boneNode->mTransformation = aiMatrix4x4::Translation(source.Position, t0) * aiMatrix4x4::Rotation(source.RotationAngle, source.RotationAxis, t1); if (!source.Children.empty()) { boneNode->mChildren = new aiNode*[source.Children.size()]; boneNode->mNumChildren = source.Children.size(); for(size_t i=0, len=source.Children.size(); imChildren[i] = CreateNodeFromBone(source.Children[i], bones, boneNode); } return boneNode; } void Bone::CalculateBoneToWorldSpaceMatrix(vector &Bones) { aiMatrix4x4 t0, t1; aiMatrix4x4 transform = aiMatrix4x4::Rotation(-RotationAngle, RotationAxis, t1) * aiMatrix4x4::Translation(-Position, t0); if (!IsParented()) BoneToWorldSpace = transform; else BoneToWorldSpace = transform * Bones[ParentId].BoneToWorldSpace; // Recursively for all children now that the parent matrix has been calculated. BOOST_FOREACH(int childId, Children) { Bones[childId].CalculateBoneToWorldSpaceMatrix(Bones); } } } // Ogre } // Assimp #endif // ASSIMP_BUILD_NO_OGRE_IMPORTER