OgreSkeleton.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2012, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. #include "AssimpPCH.h"
  34. #ifndef ASSIMP_BUILD_NO_OGRE_IMPORTER
  35. #include "OgreImporter.hpp"
  36. #include "TinyFormatter.h"
  37. using namespace std;
  38. namespace Assimp
  39. {
  40. namespace Ogre
  41. {
  42. void OgreImporter::LoadSkeleton(std::string FileName, vector<Bone> &Bones, vector<Animation> &Animations) const
  43. {
  44. const aiScene* const m_CurrentScene=this->m_CurrentScene;//make sure, that we can access but not change the scene
  45. (void)m_CurrentScene;
  46. //most likely the skeleton file will only end with .skeleton
  47. //But this is a xml reader, so we need: .skeleton.xml
  48. FileName+=".xml";
  49. DefaultLogger::get()->debug(string("Loading Skeleton: ")+FileName);
  50. //Open the File:
  51. boost::scoped_ptr<IOStream> File(m_CurrentIOHandler->Open(FileName));
  52. if(NULL==File.get())
  53. throw DeadlyImportError("Failed to open skeleton file "+FileName+".");
  54. //Read the Mesh File:
  55. boost::scoped_ptr<CIrrXML_IOStreamReader> mIOWrapper(new CIrrXML_IOStreamReader(File.get()));
  56. XmlReader* SkeletonFile = irr::io::createIrrXMLReader(mIOWrapper.get());
  57. if(!SkeletonFile)
  58. throw DeadlyImportError(string("Failed to create XML Reader for ")+FileName);
  59. XmlRead(SkeletonFile);
  60. if(string("skeleton")!=SkeletonFile->getNodeName())
  61. throw DeadlyImportError("No <skeleton> node in SkeletonFile: "+FileName);
  62. //------------------------------------load bones-----------------------------------------
  63. XmlRead(SkeletonFile);
  64. if(string("bones")!=SkeletonFile->getNodeName())
  65. throw DeadlyImportError("No bones node in skeleton "+FileName);
  66. XmlRead(SkeletonFile);
  67. while(string("bone")==SkeletonFile->getNodeName())
  68. {
  69. //TODO: Maybe we can have bone ids for the errrors, but normaly, they should never appear, so what....
  70. //read a new bone:
  71. Bone NewBone;
  72. NewBone.Id=GetAttribute<int>(SkeletonFile, "id");
  73. NewBone.Name=GetAttribute<string>(SkeletonFile, "name");
  74. //load the position:
  75. XmlRead(SkeletonFile);
  76. if(string("position")!=SkeletonFile->getNodeName())
  77. throw DeadlyImportError("Position is not first node in Bone!");
  78. NewBone.Position.x=GetAttribute<float>(SkeletonFile, "x");
  79. NewBone.Position.y=GetAttribute<float>(SkeletonFile, "y");
  80. NewBone.Position.z=GetAttribute<float>(SkeletonFile, "z");
  81. //Rotation:
  82. XmlRead(SkeletonFile);
  83. if(string("rotation")!=SkeletonFile->getNodeName())
  84. throw DeadlyImportError("Rotation is not the second node in Bone!");
  85. NewBone.RotationAngle=GetAttribute<float>(SkeletonFile, "angle");
  86. XmlRead(SkeletonFile);
  87. if(string("axis")!=SkeletonFile->getNodeName())
  88. throw DeadlyImportError("No axis specified for bone rotation!");
  89. NewBone.RotationAxis.x=GetAttribute<float>(SkeletonFile, "x");
  90. NewBone.RotationAxis.y=GetAttribute<float>(SkeletonFile, "y");
  91. NewBone.RotationAxis.z=GetAttribute<float>(SkeletonFile, "z");
  92. //append the newly loaded bone to the bone list
  93. Bones.push_back(NewBone);
  94. //Proceed to the next bone:
  95. XmlRead(SkeletonFile);
  96. }
  97. //The bones in the file a not neccesarly ordered by there id's so we do it now:
  98. std::sort(Bones.begin(), Bones.end());
  99. //now the id of each bone should be equal to its position in the vector:
  100. //so we do a simple check:
  101. {
  102. bool IdsOk=true;
  103. for(int i=0; i<static_cast<signed int>(Bones.size()); ++i)//i is signed, because all Id's are also signed!
  104. {
  105. if(Bones[i].Id!=i)
  106. IdsOk=false;
  107. }
  108. if(!IdsOk)
  109. throw DeadlyImportError("Bone Ids are not valid!"+FileName);
  110. }
  111. DefaultLogger::get()->debug((Formatter::format(),"Number of bones: ",Bones.size()));
  112. //________________________________________________________________________________
  113. //----------------------------load bonehierarchy--------------------------------
  114. if(string("bonehierarchy")!=SkeletonFile->getNodeName())
  115. throw DeadlyImportError("no bonehierarchy node in "+FileName);
  116. DefaultLogger::get()->debug("loading bonehierarchy...");
  117. XmlRead(SkeletonFile);
  118. while(string("boneparent")==SkeletonFile->getNodeName())
  119. {
  120. string Child, Parent;
  121. Child=GetAttribute<string>(SkeletonFile, "bone");
  122. Parent=GetAttribute<string>(SkeletonFile, "parent");
  123. unsigned int ChildId, ParentId;
  124. ChildId=find(Bones.begin(), Bones.end(), Child)->Id;
  125. ParentId=find(Bones.begin(), Bones.end(), Parent)->Id;
  126. Bones[ChildId].ParentId=ParentId;
  127. Bones[ParentId].Children.push_back(ChildId);
  128. XmlRead(SkeletonFile);
  129. }
  130. //_____________________________________________________________________________
  131. //--------- Calculate the WorldToBoneSpace Matrix recursively for all bones: ------------------
  132. BOOST_FOREACH(Bone &theBone, Bones)
  133. {
  134. if(-1==theBone.ParentId) //the bone is a root bone
  135. {
  136. theBone.CalculateBoneToWorldSpaceMatrix(Bones);
  137. }
  138. }
  139. //_______________________________________________________________________
  140. //---------------------------load animations-----------------------------
  141. if(string("animations")==SkeletonFile->getNodeName())//animations are optional values
  142. {
  143. DefaultLogger::get()->debug("Loading Animations");
  144. XmlRead(SkeletonFile);
  145. while(string("animation")==SkeletonFile->getNodeName())
  146. {
  147. Animation NewAnimation;
  148. NewAnimation.Name=GetAttribute<string>(SkeletonFile, "name");
  149. NewAnimation.Length=GetAttribute<float>(SkeletonFile, "length");
  150. //Load all Tracks
  151. XmlRead(SkeletonFile);
  152. if(string("tracks")!=SkeletonFile->getNodeName())
  153. throw DeadlyImportError("no tracks node in animation");
  154. XmlRead(SkeletonFile);
  155. while(string("track")==SkeletonFile->getNodeName())
  156. {
  157. Track NewTrack;
  158. NewTrack.BoneName=GetAttribute<string>(SkeletonFile, "bone");
  159. //Load all keyframes;
  160. XmlRead(SkeletonFile);
  161. if(string("keyframes")!=SkeletonFile->getNodeName())
  162. throw DeadlyImportError("no keyframes node!");
  163. XmlRead(SkeletonFile);
  164. while(string("keyframe")==SkeletonFile->getNodeName())
  165. {
  166. Keyframe NewKeyframe;
  167. NewKeyframe.Time=GetAttribute<float>(SkeletonFile, "time");
  168. //loop over the attributes:
  169. while(true) //will quit, if a Node is not a animationkey
  170. {
  171. XmlRead(SkeletonFile);
  172. //If any property doesn't show up, it will keep its initialization value
  173. //Position:
  174. if(string("translate")==SkeletonFile->getNodeName())
  175. {
  176. NewKeyframe.Position.x=GetAttribute<float>(SkeletonFile, "x");
  177. NewKeyframe.Position.y=GetAttribute<float>(SkeletonFile, "y");
  178. NewKeyframe.Position.z=GetAttribute<float>(SkeletonFile, "z");
  179. }
  180. //Rotation:
  181. else if(string("rotate")==SkeletonFile->getNodeName())
  182. {
  183. float RotationAngle=GetAttribute<float>(SkeletonFile, "angle");
  184. aiVector3D RotationAxis;
  185. XmlRead(SkeletonFile);
  186. if(string("axis")!=SkeletonFile->getNodeName())
  187. throw DeadlyImportError("No axis for keyframe rotation!");
  188. RotationAxis.x=GetAttribute<float>(SkeletonFile, "x");
  189. RotationAxis.y=GetAttribute<float>(SkeletonFile, "y");
  190. RotationAxis.z=GetAttribute<float>(SkeletonFile, "z");
  191. if(0==RotationAxis.x && 0==RotationAxis.y && 0==RotationAxis.z)//we have an invalid rotation axis
  192. {
  193. RotationAxis.x=1.0f;
  194. if(0!=RotationAngle)//if we don't rotate at all, the axis does not matter
  195. {
  196. DefaultLogger::get()->warn("Invalid Rotation Axis in Keyframe!");
  197. }
  198. }
  199. NewKeyframe.Rotation=aiQuaternion(RotationAxis, RotationAngle);
  200. }
  201. //Scaling:
  202. else if(string("scale")==SkeletonFile->getNodeName())
  203. {
  204. NewKeyframe.Scaling.x=GetAttribute<float>(SkeletonFile, "x");
  205. NewKeyframe.Scaling.y=GetAttribute<float>(SkeletonFile, "y");
  206. NewKeyframe.Scaling.z=GetAttribute<float>(SkeletonFile, "z");
  207. }
  208. //we suppose, that we read all attributes and this is a new keyframe or the end of the animation
  209. else
  210. break;
  211. }
  212. NewTrack.Keyframes.push_back(NewKeyframe);
  213. }
  214. NewAnimation.Tracks.push_back(NewTrack);
  215. }
  216. Animations.push_back(NewAnimation);
  217. }
  218. }
  219. //_____________________________________________________________________________
  220. }
  221. void OgreImporter::CreateAssimpSkeleton(const std::vector<Bone> &Bones, const std::vector<Animation> &/*Animations*/)
  222. {
  223. if(!m_CurrentScene->mRootNode)
  224. throw DeadlyImportError("No root node exists!!");
  225. if(0!=m_CurrentScene->mRootNode->mNumChildren)
  226. throw DeadlyImportError("Root Node already has childnodes!");
  227. //Createt the assimp bone hierarchy
  228. vector<aiNode*> RootBoneNodes;
  229. BOOST_FOREACH(const Bone &theBone, Bones)
  230. {
  231. if(-1==theBone.ParentId) //the bone is a root bone
  232. {
  233. //which will recursily add all other nodes
  234. RootBoneNodes.push_back(CreateAiNodeFromBone(theBone.Id, Bones, m_CurrentScene->mRootNode));
  235. }
  236. }
  237. if(RootBoneNodes.size() > 0)
  238. {
  239. m_CurrentScene->mRootNode->mNumChildren=RootBoneNodes.size();
  240. m_CurrentScene->mRootNode->mChildren=new aiNode*[RootBoneNodes.size()];
  241. memcpy(m_CurrentScene->mRootNode->mChildren, &RootBoneNodes[0], sizeof(aiNode*)*RootBoneNodes.size());
  242. }
  243. }
  244. void OgreImporter::PutAnimationsInScene(const std::vector<Bone> &Bones, const std::vector<Animation> &Animations)
  245. {
  246. //-----------------Create the Assimp Animations --------------------
  247. if(Animations.size()>0)//Maybe the model had only a skeleton and no animations. (If it also has no skeleton, this function would'nt have been called
  248. {
  249. m_CurrentScene->mNumAnimations=Animations.size();
  250. m_CurrentScene->mAnimations=new aiAnimation*[Animations.size()];
  251. for(unsigned int i=0; i<Animations.size(); ++i)//create all animations
  252. {
  253. aiAnimation* NewAnimation=new aiAnimation();
  254. NewAnimation->mName=Animations[i].Name;
  255. NewAnimation->mDuration=Animations[i].Length;
  256. NewAnimation->mTicksPerSecond=1.0f;
  257. //Create all tracks in this animation
  258. NewAnimation->mNumChannels=Animations[i].Tracks.size();
  259. NewAnimation->mChannels=new aiNodeAnim*[Animations[i].Tracks.size()];
  260. for(unsigned int j=0; j<Animations[i].Tracks.size(); ++j)
  261. {
  262. aiNodeAnim* NewNodeAnim=new aiNodeAnim();
  263. NewNodeAnim->mNodeName=Animations[i].Tracks[j].BoneName;
  264. //we need this, to acces the bones default pose, which we need to make keys absolute to the default bone pose
  265. vector<Bone>::const_iterator CurBone=find(Bones.begin(), Bones.end(), NewNodeAnim->mNodeName);
  266. aiMatrix4x4 t0, t1;
  267. aiMatrix4x4 DefBonePose=aiMatrix4x4::Translation(CurBone->Position, t1)
  268. * aiMatrix4x4::Rotation(CurBone->RotationAngle, CurBone->RotationAxis, t0);
  269. //Create the keyframe arrays...
  270. unsigned int KeyframeCount=Animations[i].Tracks[j].Keyframes.size();
  271. NewNodeAnim->mNumPositionKeys=KeyframeCount;
  272. NewNodeAnim->mNumRotationKeys=KeyframeCount;
  273. NewNodeAnim->mNumScalingKeys =KeyframeCount;
  274. NewNodeAnim->mPositionKeys=new aiVectorKey[KeyframeCount];
  275. NewNodeAnim->mRotationKeys=new aiQuatKey[KeyframeCount];
  276. NewNodeAnim->mScalingKeys =new aiVectorKey[KeyframeCount];
  277. //...and fill them
  278. for(unsigned int k=0; k<KeyframeCount; ++k)
  279. {
  280. aiMatrix4x4 t2, t3;
  281. //Create a matrix to transfrom a vector from the bones default pose to the bone bones in this animation key
  282. aiMatrix4x4 PoseToKey=
  283. aiMatrix4x4::Translation(Animations[i].Tracks[j].Keyframes[k].Position, t3) //pos
  284. * aiMatrix4x4(Animations[i].Tracks[j].Keyframes[k].Rotation.GetMatrix()) //rot
  285. * aiMatrix4x4::Scaling(Animations[i].Tracks[j].Keyframes[k].Scaling, t2); //scale
  286. //calculate the complete transformation from world space to bone space
  287. aiMatrix4x4 CompleteTransform=DefBonePose * PoseToKey;
  288. aiVector3D Pos;
  289. aiQuaternion Rot;
  290. aiVector3D Scale;
  291. CompleteTransform.Decompose(Scale, Rot, Pos);
  292. double Time=Animations[i].Tracks[j].Keyframes[k].Time;
  293. NewNodeAnim->mPositionKeys[k].mTime=Time;
  294. NewNodeAnim->mPositionKeys[k].mValue=Pos;
  295. NewNodeAnim->mRotationKeys[k].mTime=Time;
  296. NewNodeAnim->mRotationKeys[k].mValue=Rot;
  297. NewNodeAnim->mScalingKeys[k].mTime=Time;
  298. NewNodeAnim->mScalingKeys[k].mValue=Scale;
  299. }
  300. NewAnimation->mChannels[j]=NewNodeAnim;
  301. }
  302. m_CurrentScene->mAnimations[i]=NewAnimation;
  303. }
  304. }
  305. //TODO: Auf nicht vorhandene Animationskeys achten!
  306. //#pragma warning (s.o.)
  307. //__________________________________________________________________
  308. }
  309. aiNode* OgreImporter::CreateAiNodeFromBone(int BoneId, const std::vector<Bone> &Bones, aiNode* ParentNode)
  310. {
  311. //----Create the node for this bone and set its values-----
  312. aiNode* NewNode=new aiNode(Bones[BoneId].Name);
  313. NewNode->mParent=ParentNode;
  314. aiMatrix4x4 t0,t1;
  315. NewNode->mTransformation=
  316. aiMatrix4x4::Translation(Bones[BoneId].Position, t0)
  317. *aiMatrix4x4::Rotation(Bones[BoneId].RotationAngle, Bones[BoneId].RotationAxis, t1)
  318. ;
  319. //__________________________________________________________
  320. //---------- recursivly create all children Nodes: ----------
  321. NewNode->mNumChildren=Bones[BoneId].Children.size();
  322. NewNode->mChildren=new aiNode*[Bones[BoneId].Children.size()];
  323. for(unsigned int i=0; i<Bones[BoneId].Children.size(); ++i)
  324. {
  325. NewNode->mChildren[i]=CreateAiNodeFromBone(Bones[BoneId].Children[i], Bones, NewNode);
  326. }
  327. //____________________________________________________
  328. return NewNode;
  329. }
  330. void Bone::CalculateBoneToWorldSpaceMatrix(vector<Bone> &Bones)
  331. {
  332. //Calculate the matrix for this bone:
  333. aiMatrix4x4 t0,t1;
  334. aiMatrix4x4 Transf= aiMatrix4x4::Rotation(-RotationAngle, RotationAxis, t1)
  335. * aiMatrix4x4::Translation(-Position, t0);
  336. if(-1==ParentId)
  337. {
  338. BoneToWorldSpace=Transf;
  339. }
  340. else
  341. {
  342. BoneToWorldSpace=Transf*Bones[ParentId].BoneToWorldSpace;
  343. }
  344. //and recursivly for all children:
  345. BOOST_FOREACH(int theChildren, Children)
  346. {
  347. Bones[theChildren].CalculateBoneToWorldSpaceMatrix(Bones);
  348. }
  349. }
  350. }//namespace Ogre
  351. }//namespace Assimp
  352. #endif // !! ASSIMP_BUILD_NO_OGRE_IMPORTER