BVHLoader.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. /** Implementation of the BVH loader */
  2. /*
  3. ---------------------------------------------------------------------------
  4. Open Asset Import Library (assimp)
  5. ---------------------------------------------------------------------------
  6. Copyright (c) 2006-2022, assimp team
  7. All rights reserved.
  8. Redistribution and use of this software in source and binary forms,
  9. with or without modification, are permitted provided that the following
  10. conditions are met:
  11. * Redistributions of source code must retain the above
  12. copyright notice, this list of conditions and the
  13. following disclaimer.
  14. * Redistributions in binary form must reproduce the above
  15. copyright notice, this list of conditions and the
  16. following disclaimer in the documentation and/or other
  17. materials provided with the distribution.
  18. * Neither the name of the assimp team, nor the names of its
  19. contributors may be used to endorse or promote products
  20. derived from this software without specific prior
  21. written permission of the assimp team.
  22. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  25. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  26. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  27. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  28. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  29. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  30. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  32. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33. ---------------------------------------------------------------------------
  34. */
  35. #ifndef ASSIMP_BUILD_NO_BVH_IMPORTER
  36. #include "BVHLoader.h"
  37. #include <assimp/SkeletonMeshBuilder.h>
  38. #include <assimp/TinyFormatter.h>
  39. #include <assimp/fast_atof.h>
  40. #include <assimp/importerdesc.h>
  41. #include <assimp/scene.h>
  42. #include <assimp/IOSystem.hpp>
  43. #include <assimp/Importer.hpp>
  44. #include <map>
  45. #include <memory>
  46. using namespace Assimp;
  47. using namespace Assimp::Formatter;
  48. static const aiImporterDesc desc = {
  49. "BVH Importer (MoCap)",
  50. "",
  51. "",
  52. "",
  53. aiImporterFlags_SupportTextFlavour,
  54. 0,
  55. 0,
  56. 0,
  57. 0,
  58. "bvh"
  59. };
  60. // ------------------------------------------------------------------------------------------------
  61. // Aborts the file reading with an exception
  62. template<typename... T>
  63. AI_WONT_RETURN void BVHLoader::ThrowException(T&&... args) {
  64. throw DeadlyImportError(mFileName, ":", mLine, " - ", args...);
  65. }
  66. // ------------------------------------------------------------------------------------------------
  67. // Constructor to be privately used by Importer
  68. BVHLoader::BVHLoader() :
  69. mLine(),
  70. mAnimTickDuration(),
  71. mAnimNumFrames(),
  72. noSkeletonMesh() {}
  73. // ------------------------------------------------------------------------------------------------
  74. // Destructor, private as well
  75. BVHLoader::~BVHLoader() {}
  76. // ------------------------------------------------------------------------------------------------
  77. // Returns whether the class can handle the format of the given file.
  78. bool BVHLoader::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
  79. static const char *tokens[] = { "HIERARCHY" };
  80. return SearchFileHeaderForToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens));
  81. }
  82. // ------------------------------------------------------------------------------------------------
  83. void BVHLoader::SetupProperties(const Importer *pImp) {
  84. noSkeletonMesh = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, 0) != 0;
  85. }
  86. // ------------------------------------------------------------------------------------------------
  87. // Loader meta information
  88. const aiImporterDesc *BVHLoader::GetInfo() const {
  89. return &desc;
  90. }
  91. // ------------------------------------------------------------------------------------------------
  92. // Imports the given file into the given scene structure.
  93. void BVHLoader::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
  94. mFileName = pFile;
  95. // read file into memory
  96. std::unique_ptr<IOStream> file(pIOHandler->Open(pFile));
  97. if (file.get() == nullptr) {
  98. throw DeadlyImportError("Failed to open file ", pFile, ".");
  99. }
  100. size_t fileSize = file->FileSize();
  101. if (fileSize == 0) {
  102. throw DeadlyImportError("File is too small.");
  103. }
  104. mBuffer.resize(fileSize);
  105. file->Read(&mBuffer.front(), 1, fileSize);
  106. // start reading
  107. mReader = mBuffer.begin();
  108. mLine = 1;
  109. ReadStructure(pScene);
  110. if (!noSkeletonMesh) {
  111. // build a dummy mesh for the skeleton so that we see something at least
  112. SkeletonMeshBuilder meshBuilder(pScene);
  113. }
  114. // construct an animation from all the motion data we read
  115. CreateAnimation(pScene);
  116. }
  117. // ------------------------------------------------------------------------------------------------
  118. // Reads the file
  119. void BVHLoader::ReadStructure(aiScene *pScene) {
  120. // first comes hierarchy
  121. std::string header = GetNextToken();
  122. if (header != "HIERARCHY")
  123. ThrowException("Expected header string \"HIERARCHY\".");
  124. ReadHierarchy(pScene);
  125. // then comes the motion data
  126. std::string motion = GetNextToken();
  127. if (motion != "MOTION")
  128. ThrowException("Expected beginning of motion data \"MOTION\".");
  129. ReadMotion(pScene);
  130. }
  131. // ------------------------------------------------------------------------------------------------
  132. // Reads the hierarchy
  133. void BVHLoader::ReadHierarchy(aiScene *pScene) {
  134. std::string root = GetNextToken();
  135. if (root != "ROOT")
  136. ThrowException("Expected root node \"ROOT\".");
  137. // Go read the hierarchy from here
  138. pScene->mRootNode = ReadNode();
  139. }
  140. // ------------------------------------------------------------------------------------------------
  141. // Reads a node and recursively its children and returns the created node;
  142. aiNode *BVHLoader::ReadNode() {
  143. // first token is name
  144. std::string nodeName = GetNextToken();
  145. if (nodeName.empty() || nodeName == "{")
  146. ThrowException("Expected node name, but found \"", nodeName, "\".");
  147. // then an opening brace should follow
  148. std::string openBrace = GetNextToken();
  149. if (openBrace != "{")
  150. ThrowException("Expected opening brace \"{\", but found \"", openBrace, "\".");
  151. // Create a node
  152. aiNode *node = new aiNode(nodeName);
  153. std::vector<aiNode *> childNodes;
  154. // and create an bone entry for it
  155. mNodes.push_back(Node(node));
  156. Node &internNode = mNodes.back();
  157. // now read the node's contents
  158. std::string siteToken;
  159. while (1) {
  160. std::string token = GetNextToken();
  161. // node offset to parent node
  162. if (token == "OFFSET")
  163. ReadNodeOffset(node);
  164. else if (token == "CHANNELS")
  165. ReadNodeChannels(internNode);
  166. else if (token == "JOINT") {
  167. // child node follows
  168. aiNode *child = ReadNode();
  169. child->mParent = node;
  170. childNodes.push_back(child);
  171. } else if (token == "End") {
  172. // The real symbol is "End Site". Second part comes in a separate token
  173. siteToken.clear();
  174. siteToken = GetNextToken();
  175. if (siteToken != "Site")
  176. ThrowException("Expected \"End Site\" keyword, but found \"", token, " ", siteToken, "\".");
  177. aiNode *child = ReadEndSite(nodeName);
  178. child->mParent = node;
  179. childNodes.push_back(child);
  180. } else if (token == "}") {
  181. // we're done with that part of the hierarchy
  182. break;
  183. } else {
  184. // everything else is a parse error
  185. ThrowException("Unknown keyword \"", token, "\".");
  186. }
  187. }
  188. // add the child nodes if there are any
  189. if (childNodes.size() > 0) {
  190. node->mNumChildren = static_cast<unsigned int>(childNodes.size());
  191. node->mChildren = new aiNode *[node->mNumChildren];
  192. std::copy(childNodes.begin(), childNodes.end(), node->mChildren);
  193. }
  194. // and return the sub-hierarchy we built here
  195. return node;
  196. }
  197. // ------------------------------------------------------------------------------------------------
  198. // Reads an end node and returns the created node.
  199. aiNode *BVHLoader::ReadEndSite(const std::string &pParentName) {
  200. // check opening brace
  201. std::string openBrace = GetNextToken();
  202. if (openBrace != "{")
  203. ThrowException("Expected opening brace \"{\", but found \"", openBrace, "\".");
  204. // Create a node
  205. aiNode *node = new aiNode("EndSite_" + pParentName);
  206. // now read the node's contents. Only possible entry is "OFFSET"
  207. std::string token;
  208. while (1) {
  209. token.clear();
  210. token = GetNextToken();
  211. // end node's offset
  212. if (token == "OFFSET") {
  213. ReadNodeOffset(node);
  214. } else if (token == "}") {
  215. // we're done with the end node
  216. break;
  217. } else {
  218. // everything else is a parse error
  219. ThrowException("Unknown keyword \"", token, "\".");
  220. }
  221. }
  222. // and return the sub-hierarchy we built here
  223. return node;
  224. }
  225. // ------------------------------------------------------------------------------------------------
  226. // Reads a node offset for the given node
  227. void BVHLoader::ReadNodeOffset(aiNode *pNode) {
  228. // Offset consists of three floats to read
  229. aiVector3D offset;
  230. offset.x = GetNextTokenAsFloat();
  231. offset.y = GetNextTokenAsFloat();
  232. offset.z = GetNextTokenAsFloat();
  233. // build a transformation matrix from it
  234. pNode->mTransformation = aiMatrix4x4(1.0f, 0.0f, 0.0f, offset.x,
  235. 0.0f, 1.0f, 0.0f, offset.y,
  236. 0.0f, 0.0f, 1.0f, offset.z,
  237. 0.0f, 0.0f, 0.0f, 1.0f);
  238. }
  239. // ------------------------------------------------------------------------------------------------
  240. // Reads the animation channels for the given node
  241. void BVHLoader::ReadNodeChannels(BVHLoader::Node &pNode) {
  242. // number of channels. Use the float reader because we're lazy
  243. float numChannelsFloat = GetNextTokenAsFloat();
  244. unsigned int numChannels = (unsigned int)numChannelsFloat;
  245. for (unsigned int a = 0; a < numChannels; a++) {
  246. std::string channelToken = GetNextToken();
  247. if (channelToken == "Xposition")
  248. pNode.mChannels.push_back(Channel_PositionX);
  249. else if (channelToken == "Yposition")
  250. pNode.mChannels.push_back(Channel_PositionY);
  251. else if (channelToken == "Zposition")
  252. pNode.mChannels.push_back(Channel_PositionZ);
  253. else if (channelToken == "Xrotation")
  254. pNode.mChannels.push_back(Channel_RotationX);
  255. else if (channelToken == "Yrotation")
  256. pNode.mChannels.push_back(Channel_RotationY);
  257. else if (channelToken == "Zrotation")
  258. pNode.mChannels.push_back(Channel_RotationZ);
  259. else
  260. ThrowException("Invalid channel specifier \"", channelToken, "\".");
  261. }
  262. }
  263. // ------------------------------------------------------------------------------------------------
  264. // Reads the motion data
  265. void BVHLoader::ReadMotion(aiScene * /*pScene*/) {
  266. // Read number of frames
  267. std::string tokenFrames = GetNextToken();
  268. if (tokenFrames != "Frames:")
  269. ThrowException("Expected frame count \"Frames:\", but found \"", tokenFrames, "\".");
  270. float numFramesFloat = GetNextTokenAsFloat();
  271. mAnimNumFrames = (unsigned int)numFramesFloat;
  272. // Read frame duration
  273. std::string tokenDuration1 = GetNextToken();
  274. std::string tokenDuration2 = GetNextToken();
  275. if (tokenDuration1 != "Frame" || tokenDuration2 != "Time:")
  276. ThrowException("Expected frame duration \"Frame Time:\", but found \"", tokenDuration1, " ", tokenDuration2, "\".");
  277. mAnimTickDuration = GetNextTokenAsFloat();
  278. // resize value vectors for each node
  279. for (std::vector<Node>::iterator it = mNodes.begin(); it != mNodes.end(); ++it)
  280. it->mChannelValues.reserve(it->mChannels.size() * mAnimNumFrames);
  281. // now read all the data and store it in the corresponding node's value vector
  282. for (unsigned int frame = 0; frame < mAnimNumFrames; ++frame) {
  283. // on each line read the values for all nodes
  284. for (std::vector<Node>::iterator it = mNodes.begin(); it != mNodes.end(); ++it) {
  285. // get as many values as the node has channels
  286. for (unsigned int c = 0; c < it->mChannels.size(); ++c)
  287. it->mChannelValues.push_back(GetNextTokenAsFloat());
  288. }
  289. // after one frame worth of values for all nodes there should be a newline, but we better don't rely on it
  290. }
  291. }
  292. // ------------------------------------------------------------------------------------------------
  293. // Retrieves the next token
  294. std::string BVHLoader::GetNextToken() {
  295. // skip any preceding whitespace
  296. while (mReader != mBuffer.end()) {
  297. if (!isspace((unsigned char)*mReader))
  298. break;
  299. // count lines
  300. if (*mReader == '\n')
  301. mLine++;
  302. ++mReader;
  303. }
  304. // collect all chars till the next whitespace. BVH is easy in respect to that.
  305. std::string token;
  306. while (mReader != mBuffer.end()) {
  307. if (isspace((unsigned char)*mReader))
  308. break;
  309. token.push_back(*mReader);
  310. ++mReader;
  311. // little extra logic to make sure braces are counted correctly
  312. if (token == "{" || token == "}")
  313. break;
  314. }
  315. // empty token means end of file, which is just fine
  316. return token;
  317. }
  318. // ------------------------------------------------------------------------------------------------
  319. // Reads the next token as a float
  320. float BVHLoader::GetNextTokenAsFloat() {
  321. std::string token = GetNextToken();
  322. if (token.empty())
  323. ThrowException("Unexpected end of file while trying to read a float");
  324. // check if the float is valid by testing if the atof() function consumed every char of the token
  325. const char *ctoken = token.c_str();
  326. float result = 0.0f;
  327. ctoken = fast_atoreal_move<float>(ctoken, result);
  328. if (ctoken != token.c_str() + token.length())
  329. ThrowException("Expected a floating point number, but found \"", token, "\".");
  330. return result;
  331. }
  332. // ------------------------------------------------------------------------------------------------
  333. // Constructs an animation for the motion data and stores it in the given scene
  334. void BVHLoader::CreateAnimation(aiScene *pScene) {
  335. // create the animation
  336. pScene->mNumAnimations = 1;
  337. pScene->mAnimations = new aiAnimation *[1];
  338. aiAnimation *anim = new aiAnimation;
  339. pScene->mAnimations[0] = anim;
  340. // put down the basic parameters
  341. anim->mName.Set("Motion");
  342. anim->mTicksPerSecond = 1.0 / double(mAnimTickDuration);
  343. anim->mDuration = double(mAnimNumFrames - 1);
  344. // now generate the tracks for all nodes
  345. anim->mNumChannels = static_cast<unsigned int>(mNodes.size());
  346. anim->mChannels = new aiNodeAnim *[anim->mNumChannels];
  347. // FIX: set the array elements to nullptr to ensure proper deletion if an exception is thrown
  348. for (unsigned int i = 0; i < anim->mNumChannels; ++i)
  349. anim->mChannels[i] = nullptr;
  350. for (unsigned int a = 0; a < anim->mNumChannels; a++) {
  351. const Node &node = mNodes[a];
  352. const std::string nodeName = std::string(node.mNode->mName.data);
  353. aiNodeAnim *nodeAnim = new aiNodeAnim;
  354. anim->mChannels[a] = nodeAnim;
  355. nodeAnim->mNodeName.Set(nodeName);
  356. std::map<BVHLoader::ChannelType, int> channelMap;
  357. //Build map of channels
  358. for (unsigned int channel = 0; channel < node.mChannels.size(); ++channel) {
  359. channelMap[node.mChannels[channel]] = channel;
  360. }
  361. // translational part, if given
  362. if (node.mChannels.size() == 6) {
  363. nodeAnim->mNumPositionKeys = mAnimNumFrames;
  364. nodeAnim->mPositionKeys = new aiVectorKey[mAnimNumFrames];
  365. aiVectorKey *poskey = nodeAnim->mPositionKeys;
  366. for (unsigned int fr = 0; fr < mAnimNumFrames; ++fr) {
  367. poskey->mTime = double(fr);
  368. // Now compute all translations
  369. for (BVHLoader::ChannelType channel = Channel_PositionX; channel <= Channel_PositionZ; channel = (BVHLoader::ChannelType)(channel + 1)) {
  370. //Find channel in node
  371. std::map<BVHLoader::ChannelType, int>::iterator mapIter = channelMap.find(channel);
  372. if (mapIter == channelMap.end())
  373. throw DeadlyImportError("Missing position channel in node ", nodeName);
  374. else {
  375. int channelIdx = mapIter->second;
  376. switch (channel) {
  377. case Channel_PositionX:
  378. poskey->mValue.x = node.mChannelValues[fr * node.mChannels.size() + channelIdx];
  379. break;
  380. case Channel_PositionY:
  381. poskey->mValue.y = node.mChannelValues[fr * node.mChannels.size() + channelIdx];
  382. break;
  383. case Channel_PositionZ:
  384. poskey->mValue.z = node.mChannelValues[fr * node.mChannels.size() + channelIdx];
  385. break;
  386. default:
  387. break;
  388. }
  389. }
  390. }
  391. ++poskey;
  392. }
  393. } else {
  394. // if no translation part is given, put a default sequence
  395. aiVector3D nodePos(node.mNode->mTransformation.a4, node.mNode->mTransformation.b4, node.mNode->mTransformation.c4);
  396. nodeAnim->mNumPositionKeys = 1;
  397. nodeAnim->mPositionKeys = new aiVectorKey[1];
  398. nodeAnim->mPositionKeys[0].mTime = 0.0;
  399. nodeAnim->mPositionKeys[0].mValue = nodePos;
  400. }
  401. // rotation part. Always present. First find value offsets
  402. {
  403. // Then create the number of rotation keys
  404. nodeAnim->mNumRotationKeys = mAnimNumFrames;
  405. nodeAnim->mRotationKeys = new aiQuatKey[mAnimNumFrames];
  406. aiQuatKey *rotkey = nodeAnim->mRotationKeys;
  407. for (unsigned int fr = 0; fr < mAnimNumFrames; ++fr) {
  408. aiMatrix4x4 temp;
  409. aiMatrix3x3 rotMatrix;
  410. for (unsigned int channelIdx = 0; channelIdx < node.mChannels.size(); ++ channelIdx) {
  411. switch (node.mChannels[channelIdx]) {
  412. case Channel_RotationX:
  413. {
  414. const float angle = node.mChannelValues[fr * node.mChannels.size() + channelIdx] * float(AI_MATH_PI) / 180.0f;
  415. aiMatrix4x4::RotationX( angle, temp); rotMatrix *= aiMatrix3x3( temp);
  416. }
  417. break;
  418. case Channel_RotationY:
  419. {
  420. const float angle = node.mChannelValues[fr * node.mChannels.size() + channelIdx] * float(AI_MATH_PI) / 180.0f;
  421. aiMatrix4x4::RotationY( angle, temp); rotMatrix *= aiMatrix3x3( temp);
  422. }
  423. break;
  424. case Channel_RotationZ:
  425. {
  426. const float angle = node.mChannelValues[fr * node.mChannels.size() + channelIdx] * float(AI_MATH_PI) / 180.0f;
  427. aiMatrix4x4::RotationZ( angle, temp); rotMatrix *= aiMatrix3x3( temp);
  428. }
  429. break;
  430. default:
  431. break;
  432. }
  433. }
  434. rotkey->mTime = double(fr);
  435. rotkey->mValue = aiQuaternion(rotMatrix);
  436. ++rotkey;
  437. }
  438. }
  439. // scaling part. Always just a default track
  440. {
  441. nodeAnim->mNumScalingKeys = 1;
  442. nodeAnim->mScalingKeys = new aiVectorKey[1];
  443. nodeAnim->mScalingKeys[0].mTime = 0.0;
  444. nodeAnim->mScalingKeys[0].mValue.Set(1.0f, 1.0f, 1.0f);
  445. }
  446. }
  447. }
  448. #endif // !! ASSIMP_BUILD_NO_BVH_IMPORTER