OgreSkeleton.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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 aSource and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of aSource 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.h"
  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. string filename = skeletonFile;
  46. if (EndsWith(filename, ".skeleton"))
  47. {
  48. 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.");
  49. filename += ".xml";
  50. }
  51. if (!pIOHandler->Exists(filename))
  52. {
  53. DefaultLogger::get()->error("Failed to find skeleton file '" + filename + "', skeleton will be missing.");
  54. return;
  55. }
  56. boost::scoped_ptr<IOStream> file(pIOHandler->Open(filename));
  57. if (!file.get())
  58. throw DeadlyImportError("Failed to open skeleton file " + filename);
  59. boost::scoped_ptr<CIrrXML_IOStreamReader> stream(new CIrrXML_IOStreamReader(file.get()));
  60. XmlReader* reader = irr::io::createIrrXMLReader(stream.get());
  61. if (!reader)
  62. throw DeadlyImportError("Failed to create XML reader for skeleton file " + filename);
  63. DefaultLogger::get()->debug("Reading skeleton '" + filename + "'");
  64. // Root
  65. NextNode(reader);
  66. if (!CurrentNodeNameEquals(reader, "skeleton"))
  67. throw DeadlyImportError("Root node is not <skeleton> but <" + string(reader->getNodeName()) + "> in " + filename);
  68. // Bones
  69. NextNode(reader);
  70. if (!CurrentNodeNameEquals(reader, "bones"))
  71. throw DeadlyImportError("No <bones> node in skeleton " + skeletonFile);
  72. NextNode(reader);
  73. while(CurrentNodeNameEquals(reader, "bone"))
  74. {
  75. //TODO: Maybe we can have bone ids for the errrors, but normaly, they should never appear, so what....
  76. /// @todo What does the above mean?
  77. Bone bone;
  78. bone.Id = GetAttribute<int>(reader, "id");
  79. bone.Name = GetAttribute<string>(reader, "name");
  80. NextNode(reader);
  81. if (!CurrentNodeNameEquals(reader, "position"))
  82. throw DeadlyImportError("Position is not first node in Bone!");
  83. bone.Position.x = GetAttribute<float>(reader, "x");
  84. bone.Position.y = GetAttribute<float>(reader, "y");
  85. bone.Position.z = GetAttribute<float>(reader, "z");
  86. NextNode(reader);
  87. if (!CurrentNodeNameEquals(reader, "rotation"))
  88. throw DeadlyImportError("Rotation is not the second node in Bone!");
  89. bone.RotationAngle = GetAttribute<float>(reader, "angle");
  90. NextNode(reader);
  91. if (!CurrentNodeNameEquals(reader, "axis"))
  92. throw DeadlyImportError("No axis specified for bone rotation!");
  93. bone.RotationAxis.x = GetAttribute<float>(reader, "x");
  94. bone.RotationAxis.y = GetAttribute<float>(reader, "y");
  95. bone.RotationAxis.z = GetAttribute<float>(reader, "z");
  96. Bones.push_back(bone);
  97. NextNode(reader);
  98. }
  99. // Order bones by Id
  100. std::sort(Bones.begin(), Bones.end());
  101. // Validate that bone indexes are not skipped.
  102. /** @note Left this from original authors code, but not sure if this is strictly necessary
  103. as per the Ogre skeleton spec. It might be more that other (later) code in this imported does not break. */
  104. for (size_t i=0, len=Bones.size(); i<len; ++i)
  105. if (static_cast<int>(Bones[i].Id) != static_cast<int>(i))
  106. throw DeadlyImportError("Bone Ids are not in sequence in " + skeletonFile);
  107. DefaultLogger::get()->debug(Formatter::format() << " - Bones " << Bones.size());
  108. // Bone hierarchy
  109. if (!CurrentNodeNameEquals(reader, "bonehierarchy"))
  110. throw DeadlyImportError("No <bonehierarchy> node found after <bones> in " + skeletonFile);
  111. NextNode(reader);
  112. while(CurrentNodeNameEquals(reader, "boneparent"))
  113. {
  114. string childName = GetAttribute<string>(reader, "bone");
  115. string parentName = GetAttribute<string>(reader, "parent");
  116. vector<Bone>::iterator iterChild = find(Bones.begin(), Bones.end(), childName);
  117. vector<Bone>::iterator iterParent = find(Bones.begin(), Bones.end(), parentName);
  118. if (iterChild != Bones.end() && iterParent != Bones.end())
  119. {
  120. iterChild->ParentId = iterParent->Id;
  121. iterParent->Children.push_back(iterChild->Id);
  122. }
  123. else
  124. DefaultLogger::get()->warn("Failed to find bones for parenting: Child " + childName + " Parent " + parentName);
  125. NextNode(reader);
  126. }
  127. // Calculate bone matrices for root bones. Recursively does their children.
  128. BOOST_FOREACH(Bone &theBone, Bones)
  129. {
  130. if (!theBone.IsParented())
  131. theBone.CalculateBoneToWorldSpaceMatrix(Bones);
  132. }
  133. aiVector3D zeroVec(0.f, 0.f, 0.f);
  134. // Animations
  135. if (CurrentNodeNameEquals(reader, "animations"))
  136. {
  137. DefaultLogger::get()->debug(" - Animations");
  138. NextNode(reader);
  139. while(CurrentNodeNameEquals(reader, "animation"))
  140. {
  141. Animation animation;
  142. animation.Name = GetAttribute<string>(reader, "name");
  143. animation.Length = GetAttribute<float>(reader, "length");
  144. // Tracks
  145. NextNode(reader);
  146. if (!CurrentNodeNameEquals(reader, "tracks"))
  147. throw DeadlyImportError("No <tracks> node found in animation '" + animation.Name + "' in " + skeletonFile);
  148. NextNode(reader);
  149. while(CurrentNodeNameEquals(reader, "track"))
  150. {
  151. Track track;
  152. track.BoneName = GetAttribute<string>(reader, "bone");
  153. // Keyframes
  154. NextNode(reader);
  155. if (!CurrentNodeNameEquals(reader, "keyframes"))
  156. throw DeadlyImportError("No <keyframes> node found in a track in animation '" + animation.Name + "' in " + skeletonFile);
  157. NextNode(reader);
  158. while(CurrentNodeNameEquals(reader, "keyframe"))
  159. {
  160. KeyFrame keyFrame;
  161. keyFrame.Time = GetAttribute<float>(reader, "time");
  162. NextNode(reader);
  163. while(CurrentNodeNameEquals(reader, "translate") || CurrentNodeNameEquals(reader, "rotate") || CurrentNodeNameEquals(reader, "scale"))
  164. {
  165. if (CurrentNodeNameEquals(reader, "translate"))
  166. {
  167. keyFrame.Position.x = GetAttribute<float>(reader, "x");
  168. keyFrame.Position.y = GetAttribute<float>(reader, "y");
  169. keyFrame.Position.z = GetAttribute<float>(reader, "z");
  170. }
  171. else if (CurrentNodeNameEquals(reader, "rotate"))
  172. {
  173. float angle = GetAttribute<float>(reader, "angle");
  174. NextNode(reader);
  175. if(string("axis")!=reader->getNodeName())
  176. throw DeadlyImportError("No axis for keyframe rotation!");
  177. aiVector3D axis;
  178. axis.x = GetAttribute<float>(reader, "x");
  179. axis.y = GetAttribute<float>(reader, "y");
  180. axis.z = GetAttribute<float>(reader, "z");
  181. if (axis.Equal(zeroVec))
  182. {
  183. axis.x = 1.0f;
  184. if (angle != 0)
  185. DefaultLogger::get()->warn("Found invalid a key frame with a zero rotation axis in animation '" + animation.Name + "'");
  186. }
  187. keyFrame.Rotation = aiQuaternion(axis, angle);
  188. }
  189. else if (CurrentNodeNameEquals(reader, "scale"))
  190. {
  191. keyFrame.Scaling.x = GetAttribute<float>(reader, "x");
  192. keyFrame.Scaling.y = GetAttribute<float>(reader, "y");
  193. keyFrame.Scaling.z = GetAttribute<float>(reader, "z");
  194. }
  195. NextNode(reader);
  196. }
  197. track.Keyframes.push_back(keyFrame);
  198. }
  199. animation.Tracks.push_back(track);
  200. }
  201. Animations.push_back(animation);
  202. DefaultLogger::get()->debug(Formatter::format() << " " << animation.Name << " (" << animation.Length << " sec, " << animation.Tracks.size() << " tracks)");
  203. }
  204. }
  205. }
  206. void OgreImporter::CreateAssimpSkeleton(aiScene *pScene, const std::vector<Bone> &bones, const std::vector<Animation> &animations)
  207. {
  208. if (bones.empty())
  209. return;
  210. if (!pScene->mRootNode)
  211. throw DeadlyImportError("Creating Assimp skeleton: No root node created!");
  212. if (pScene->mRootNode->mNumChildren > 0)
  213. throw DeadlyImportError("Creating Assimp skeleton: Root node already has children!");
  214. // Bones
  215. vector<aiNode*> rootBones;
  216. BOOST_FOREACH(const Bone &bone, bones)
  217. {
  218. if (!bone.IsParented())
  219. rootBones.push_back(CreateNodeFromBone(bone.Id, bones, pScene->mRootNode));
  220. }
  221. if (!rootBones.empty())
  222. {
  223. pScene->mRootNode->mChildren = new aiNode*[rootBones.size()];
  224. pScene->mRootNode->mNumChildren = rootBones.size();
  225. for(size_t i=0, len=rootBones.size(); i<len; ++i)
  226. pScene->mRootNode->mChildren[i] = rootBones[i];
  227. }
  228. // TODO: Auf nicht vorhandene Animationskeys achten!
  229. // @todo Pay attention to non-existing animation Keys (google translated from above german comment)
  230. // Animations
  231. if (!animations.empty())
  232. {
  233. pScene->mAnimations = new aiAnimation*[animations.size()];
  234. pScene->mNumAnimations = animations.size();
  235. for(size_t ai=0, alen=animations.size(); ai<alen; ++ai)
  236. {
  237. const Animation &aSource = animations[ai];
  238. aiAnimation *animation = new aiAnimation();
  239. animation->mName = aSource.Name;
  240. animation->mDuration = aSource.Length;
  241. animation->mTicksPerSecond = 1.0f;
  242. // Tracks
  243. animation->mChannels = new aiNodeAnim*[aSource.Tracks.size()];
  244. animation->mNumChannels = aSource.Tracks.size();
  245. for(size_t ti=0, tlen=aSource.Tracks.size(); ti<tlen; ++ti)
  246. {
  247. const Track &tSource = aSource.Tracks[ti];
  248. aiNodeAnim *animationNode = new aiNodeAnim();
  249. animationNode->mNodeName = tSource.BoneName;
  250. // We need this, to access the bones default pose.
  251. // Which we need to make keys absolute to the default bone pose.
  252. vector<Bone>::const_iterator boneIter = find(bones.begin(), bones.end(), tSource.BoneName);
  253. if (boneIter == bones.end())
  254. {
  255. for(unsigned int a=0; a<ai; a++)
  256. delete pScene->mAnimations[a];
  257. delete [] pScene->mAnimations;
  258. pScene->mAnimations = NULL;
  259. pScene->mNumAnimations = 0;
  260. DefaultLogger::get()->error("Failed to find bone for name " + tSource.BoneName + " when creating animation " + aSource.Name +
  261. ". This is a serious error, animations wont be imported.");
  262. return;
  263. }
  264. aiMatrix4x4 t0, t1;
  265. aiMatrix4x4 defaultBonePose = aiMatrix4x4::Translation(boneIter->Position, t1) * aiMatrix4x4::Rotation(boneIter->RotationAngle, boneIter->RotationAxis, t0);
  266. // Keyframes
  267. unsigned int numKeyframes = tSource.Keyframes.size();
  268. animationNode->mPositionKeys = new aiVectorKey[numKeyframes];
  269. animationNode->mRotationKeys = new aiQuatKey[numKeyframes];
  270. animationNode->mScalingKeys = new aiVectorKey[numKeyframes];
  271. animationNode->mNumPositionKeys = numKeyframes;
  272. animationNode->mNumRotationKeys = numKeyframes;
  273. animationNode->mNumScalingKeys = numKeyframes;
  274. //...and fill them
  275. for(size_t kfi=0; kfi<numKeyframes; ++kfi)
  276. {
  277. const KeyFrame &kfSource = tSource.Keyframes[kfi];
  278. // Create a matrix to transform a vector from the bones
  279. // default pose to the bone bones in this animation key
  280. aiMatrix4x4 t2, t3;
  281. aiMatrix4x4 keyBonePose =
  282. aiMatrix4x4::Translation(kfSource.Position, t3) *
  283. aiMatrix4x4(kfSource.Rotation.GetMatrix()) *
  284. aiMatrix4x4::Scaling(kfSource.Scaling, t2);
  285. // Calculate the complete transformation from world space to bone space
  286. aiMatrix4x4 CompleteTransform = defaultBonePose * keyBonePose;
  287. aiVector3D kfPos; aiQuaternion kfRot; aiVector3D kfScale;
  288. CompleteTransform.Decompose(kfScale, kfRot, kfPos);
  289. animationNode->mPositionKeys[kfi].mTime = static_cast<double>(kfSource.Time);
  290. animationNode->mRotationKeys[kfi].mTime = static_cast<double>(kfSource.Time);
  291. animationNode->mScalingKeys[kfi].mTime = static_cast<double>(kfSource.Time);
  292. animationNode->mPositionKeys[kfi].mValue = kfPos;
  293. animationNode->mRotationKeys[kfi].mValue = kfRot;
  294. animationNode->mScalingKeys[kfi].mValue = kfScale;
  295. }
  296. animation->mChannels[ti] = animationNode;
  297. }
  298. pScene->mAnimations[ai] = animation;
  299. }
  300. }
  301. }
  302. aiNode* OgreImporter::CreateNodeFromBone(int boneId, const std::vector<Bone> &bones, aiNode* parent)
  303. {
  304. aiMatrix4x4 t0,t1;
  305. const Bone &source = bones[boneId];
  306. aiNode* boneNode = new aiNode(source.Name);
  307. boneNode->mParent = parent;
  308. boneNode->mTransformation = aiMatrix4x4::Translation(source.Position, t0) * aiMatrix4x4::Rotation(source.RotationAngle, source.RotationAxis, t1);
  309. if (!source.Children.empty())
  310. {
  311. boneNode->mChildren = new aiNode*[source.Children.size()];
  312. boneNode->mNumChildren = source.Children.size();
  313. for(size_t i=0, len=source.Children.size(); i<len; ++i)
  314. boneNode->mChildren[i] = CreateNodeFromBone(source.Children[i], bones, boneNode);
  315. }
  316. return boneNode;
  317. }
  318. void Bone::CalculateBoneToWorldSpaceMatrix(vector<Bone> &Bones)
  319. {
  320. aiMatrix4x4 t0, t1;
  321. aiMatrix4x4 transform = aiMatrix4x4::Rotation(-RotationAngle, RotationAxis, t1) * aiMatrix4x4::Translation(-Position, t0);
  322. if (!IsParented())
  323. BoneToWorldSpace = transform;
  324. else
  325. BoneToWorldSpace = transform * Bones[ParentId].BoneToWorldSpace;
  326. // Recursively for all children now that the parent matrix has been calculated.
  327. BOOST_FOREACH(int childId, Children)
  328. {
  329. Bones[childId].CalculateBoneToWorldSpaceMatrix(Bones);
  330. }
  331. }
  332. } // Ogre
  333. } // Assimp
  334. #endif // ASSIMP_BUILD_NO_OGRE_IMPORTER