OgreSkeleton.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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::ReadSkeleton(const std::string &pFile, Assimp::IOSystem *pIOHandler, const aiScene *pScene,
  43. const std::string &skeletonFile, vector<Bone> &Bones, vector<Animation> &Animations) const
  44. {
  45. //most likely the skeleton file will only end with .skeleton
  46. //But this is a xml reader, so we need: .skeleton.xml
  47. string skeletonPath = skeletonFile + ".xml";
  48. DefaultLogger::get()->debug(string("Loading Skeleton: ")+skeletonFile);
  49. //Open the File:
  50. boost::scoped_ptr<IOStream> File(pIOHandler->Open(skeletonFile));
  51. if(NULL==File.get())
  52. throw DeadlyImportError("Failed to open skeleton file "+skeletonFile+".");
  53. //Read the Mesh File:
  54. boost::scoped_ptr<CIrrXML_IOStreamReader> mIOWrapper(new CIrrXML_IOStreamReader(File.get()));
  55. XmlReader* SkeletonFile = irr::io::createIrrXMLReader(mIOWrapper.get());
  56. if(!SkeletonFile)
  57. throw DeadlyImportError(string("Failed to create XML Reader for ")+skeletonFile);
  58. NextNode(SkeletonFile);
  59. if(string("skeleton")!=SkeletonFile->getNodeName())
  60. throw DeadlyImportError("No <skeleton> node in SkeletonFile: "+skeletonFile);
  61. //------------------------------------load bones-----------------------------------------
  62. NextNode(SkeletonFile);
  63. if(string("bones")!=SkeletonFile->getNodeName())
  64. throw DeadlyImportError("No bones node in skeleton "+skeletonFile);
  65. NextNode(SkeletonFile);
  66. while(string("bone")==SkeletonFile->getNodeName())
  67. {
  68. //TODO: Maybe we can have bone ids for the errrors, but normaly, they should never appear, so what....
  69. //read a new bone:
  70. Bone NewBone;
  71. NewBone.Id=GetAttribute<int>(SkeletonFile, "id");
  72. NewBone.Name=GetAttribute<string>(SkeletonFile, "name");
  73. //load the position:
  74. NextNode(SkeletonFile);
  75. if(string("position")!=SkeletonFile->getNodeName())
  76. throw DeadlyImportError("Position is not first node in Bone!");
  77. NewBone.Position.x=GetAttribute<float>(SkeletonFile, "x");
  78. NewBone.Position.y=GetAttribute<float>(SkeletonFile, "y");
  79. NewBone.Position.z=GetAttribute<float>(SkeletonFile, "z");
  80. //Rotation:
  81. NextNode(SkeletonFile);
  82. if(string("rotation")!=SkeletonFile->getNodeName())
  83. throw DeadlyImportError("Rotation is not the second node in Bone!");
  84. NewBone.RotationAngle=GetAttribute<float>(SkeletonFile, "angle");
  85. NextNode(SkeletonFile);
  86. if(string("axis")!=SkeletonFile->getNodeName())
  87. throw DeadlyImportError("No axis specified for bone rotation!");
  88. NewBone.RotationAxis.x=GetAttribute<float>(SkeletonFile, "x");
  89. NewBone.RotationAxis.y=GetAttribute<float>(SkeletonFile, "y");
  90. NewBone.RotationAxis.z=GetAttribute<float>(SkeletonFile, "z");
  91. //append the newly loaded bone to the bone list
  92. Bones.push_back(NewBone);
  93. //Proceed to the next bone:
  94. NextNode(SkeletonFile);
  95. }
  96. //The bones in the file a not neccesarly ordered by there id's so we do it now:
  97. std::sort(Bones.begin(), Bones.end());
  98. //now the id of each bone should be equal to its position in the vector:
  99. //so we do a simple check:
  100. {
  101. bool IdsOk=true;
  102. for(int i=0; i<static_cast<signed int>(Bones.size()); ++i)//i is signed, because all Id's are also signed!
  103. {
  104. if(Bones[i].Id!=i)
  105. IdsOk=false;
  106. }
  107. if(!IdsOk)
  108. throw DeadlyImportError("Bone Ids are not valid!"+skeletonFile);
  109. }
  110. DefaultLogger::get()->debug((Formatter::format(),"Number of bones: ",Bones.size()));
  111. //________________________________________________________________________________
  112. //----------------------------load bonehierarchy--------------------------------
  113. if(string("bonehierarchy")!=SkeletonFile->getNodeName())
  114. throw DeadlyImportError("no bonehierarchy node in "+skeletonFile);
  115. DefaultLogger::get()->debug("loading bonehierarchy...");
  116. NextNode(SkeletonFile);
  117. while(string("boneparent")==SkeletonFile->getNodeName())
  118. {
  119. string Child, Parent;
  120. Child=GetAttribute<string>(SkeletonFile, "bone");
  121. Parent=GetAttribute<string>(SkeletonFile, "parent");
  122. unsigned int ChildId, ParentId;
  123. ChildId=find(Bones.begin(), Bones.end(), Child)->Id;
  124. ParentId=find(Bones.begin(), Bones.end(), Parent)->Id;
  125. Bones[ChildId].ParentId=ParentId;
  126. Bones[ParentId].Children.push_back(ChildId);
  127. NextNode(SkeletonFile);
  128. }
  129. //_____________________________________________________________________________
  130. //--------- Calculate the WorldToBoneSpace Matrix recursively for all bones: ------------------
  131. BOOST_FOREACH(Bone &theBone, Bones)
  132. {
  133. if(-1==theBone.ParentId) //the bone is a root bone
  134. {
  135. theBone.CalculateBoneToWorldSpaceMatrix(Bones);
  136. }
  137. }
  138. //_______________________________________________________________________
  139. //---------------------------load animations-----------------------------
  140. if(string("animations")==SkeletonFile->getNodeName())//animations are optional values
  141. {
  142. DefaultLogger::get()->debug("Loading Animations");
  143. NextNode(SkeletonFile);
  144. while(string("animation")==SkeletonFile->getNodeName())
  145. {
  146. Animation NewAnimation;
  147. NewAnimation.Name=GetAttribute<string>(SkeletonFile, "name");
  148. NewAnimation.Length=GetAttribute<float>(SkeletonFile, "length");
  149. //Load all Tracks
  150. NextNode(SkeletonFile);
  151. if(string("tracks")!=SkeletonFile->getNodeName())
  152. throw DeadlyImportError("no tracks node in animation");
  153. NextNode(SkeletonFile);
  154. while(string("track")==SkeletonFile->getNodeName())
  155. {
  156. Track NewTrack;
  157. NewTrack.BoneName=GetAttribute<string>(SkeletonFile, "bone");
  158. //Load all keyframes;
  159. NextNode(SkeletonFile);
  160. if(string("keyframes")!=SkeletonFile->getNodeName())
  161. throw DeadlyImportError("no keyframes node!");
  162. NextNode(SkeletonFile);
  163. while(string("keyframe")==SkeletonFile->getNodeName())
  164. {
  165. KeyFrame NewKeyframe;
  166. NewKeyframe.Time=GetAttribute<float>(SkeletonFile, "time");
  167. //loop over the attributes:
  168. while(true) //will quit, if a Node is not a animationkey
  169. {
  170. NextNode(SkeletonFile);
  171. //If any property doesn't show up, it will keep its initialization value
  172. //Position:
  173. if(string("translate")==SkeletonFile->getNodeName())
  174. {
  175. NewKeyframe.Position.x=GetAttribute<float>(SkeletonFile, "x");
  176. NewKeyframe.Position.y=GetAttribute<float>(SkeletonFile, "y");
  177. NewKeyframe.Position.z=GetAttribute<float>(SkeletonFile, "z");
  178. }
  179. //Rotation:
  180. else if(string("rotate")==SkeletonFile->getNodeName())
  181. {
  182. float RotationAngle=GetAttribute<float>(SkeletonFile, "angle");
  183. aiVector3D RotationAxis;
  184. NextNode(SkeletonFile);
  185. if(string("axis")!=SkeletonFile->getNodeName())
  186. throw DeadlyImportError("No axis for keyframe rotation!");
  187. RotationAxis.x=GetAttribute<float>(SkeletonFile, "x");
  188. RotationAxis.y=GetAttribute<float>(SkeletonFile, "y");
  189. RotationAxis.z=GetAttribute<float>(SkeletonFile, "z");
  190. if(0==RotationAxis.x && 0==RotationAxis.y && 0==RotationAxis.z)//we have an invalid rotation axis
  191. {
  192. RotationAxis.x=1.0f;
  193. if(0!=RotationAngle)//if we don't rotate at all, the axis does not matter
  194. {
  195. DefaultLogger::get()->warn("Invalid Rotation Axis in KeyFrame!");
  196. }
  197. }
  198. NewKeyframe.Rotation=aiQuaternion(RotationAxis, RotationAngle);
  199. }
  200. //Scaling:
  201. else if(string("scale")==SkeletonFile->getNodeName())
  202. {
  203. NewKeyframe.Scaling.x=GetAttribute<float>(SkeletonFile, "x");
  204. NewKeyframe.Scaling.y=GetAttribute<float>(SkeletonFile, "y");
  205. NewKeyframe.Scaling.z=GetAttribute<float>(SkeletonFile, "z");
  206. }
  207. //we suppose, that we read all attributes and this is a new keyframe or the end of the animation
  208. else
  209. break;
  210. }
  211. NewTrack.Keyframes.push_back(NewKeyframe);
  212. }
  213. NewAnimation.Tracks.push_back(NewTrack);
  214. }
  215. Animations.push_back(NewAnimation);
  216. }
  217. }
  218. //_____________________________________________________________________________
  219. }
  220. void OgreImporter::CreateAssimpSkeleton(aiScene *pScene, const std::vector<Bone> &Bones, const std::vector<Animation> &/*Animations*/)
  221. {
  222. if(!pScene->mRootNode)
  223. throw DeadlyImportError("No root node exists!!");
  224. if(0!=pScene->mRootNode->mNumChildren)
  225. throw DeadlyImportError("Root Node already has childnodes!");
  226. //Createt the assimp bone hierarchy
  227. vector<aiNode*> RootBoneNodes;
  228. BOOST_FOREACH(const Bone &theBone, Bones)
  229. {
  230. if(-1==theBone.ParentId) //the bone is a root bone
  231. {
  232. //which will recursily add all other nodes
  233. RootBoneNodes.push_back(CreateAiNodeFromBone(theBone.Id, Bones, pScene->mRootNode));
  234. }
  235. }
  236. if(RootBoneNodes.size() > 0)
  237. {
  238. pScene->mRootNode->mNumChildren=RootBoneNodes.size();
  239. pScene->mRootNode->mChildren=new aiNode*[RootBoneNodes.size()];
  240. memcpy(pScene->mRootNode->mChildren, &RootBoneNodes[0], sizeof(aiNode*)*RootBoneNodes.size());
  241. }
  242. }
  243. void OgreImporter::PutAnimationsInScene(aiScene *pScene, const std::vector<Bone> &Bones, const std::vector<Animation> &Animations)
  244. {
  245. // TODO: Auf nicht vorhandene Animationskeys achten!
  246. // @todo Pay attention to non-existing animation Keys (google translated from above german comment)
  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. pScene->mNumAnimations=Animations.size();
  250. pScene->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. pScene->mAnimations[i]=NewAnimation;
  303. }
  304. }
  305. }
  306. aiNode* OgreImporter::CreateAiNodeFromBone(int BoneId, const std::vector<Bone> &Bones, aiNode* ParentNode)
  307. {
  308. //----Create the node for this bone and set its values-----
  309. aiNode* NewNode=new aiNode(Bones[BoneId].Name);
  310. NewNode->mParent=ParentNode;
  311. aiMatrix4x4 t0,t1;
  312. NewNode->mTransformation=
  313. aiMatrix4x4::Translation(Bones[BoneId].Position, t0)
  314. *aiMatrix4x4::Rotation(Bones[BoneId].RotationAngle, Bones[BoneId].RotationAxis, t1)
  315. ;
  316. //__________________________________________________________
  317. //---------- recursivly create all children Nodes: ----------
  318. NewNode->mNumChildren=Bones[BoneId].Children.size();
  319. NewNode->mChildren=new aiNode*[Bones[BoneId].Children.size()];
  320. for(unsigned int i=0; i<Bones[BoneId].Children.size(); ++i)
  321. {
  322. NewNode->mChildren[i]=CreateAiNodeFromBone(Bones[BoneId].Children[i], Bones, NewNode);
  323. }
  324. //____________________________________________________
  325. return NewNode;
  326. }
  327. void Bone::CalculateBoneToWorldSpaceMatrix(vector<Bone> &Bones)
  328. {
  329. //Calculate the matrix for this bone:
  330. aiMatrix4x4 t0,t1;
  331. aiMatrix4x4 Transf= aiMatrix4x4::Rotation(-RotationAngle, RotationAxis, t1)
  332. * aiMatrix4x4::Translation(-Position, t0);
  333. if(-1==ParentId)
  334. {
  335. BoneToWorldSpace=Transf;
  336. }
  337. else
  338. {
  339. BoneToWorldSpace=Transf*Bones[ParentId].BoneToWorldSpace;
  340. }
  341. //and recursivly for all children:
  342. BOOST_FOREACH(int theChildren, Children)
  343. {
  344. Bones[theChildren].CalculateBoneToWorldSpaceMatrix(Bones);
  345. }
  346. }
  347. }//namespace Ogre
  348. }//namespace Assimp
  349. #endif // !! ASSIMP_BUILD_NO_OGRE_IMPORTER