BVHLoader.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. /** Implementation of the BVH loader */
  2. /*
  3. ---------------------------------------------------------------------------
  4. Open Asset Import Library (assimp)
  5. ---------------------------------------------------------------------------
  6. Copyright (c) 2006-2021, 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 cs) const {
  79. // check file extension
  80. const std::string extension = GetExtension(pFile);
  81. if (extension == "bvh")
  82. return true;
  83. if ((!extension.length() || cs) && pIOHandler) {
  84. const char *tokens[] = { "HIERARCHY" };
  85. return SearchFileHeaderForToken(pIOHandler, pFile, tokens, 1);
  86. }
  87. return false;
  88. }
  89. // ------------------------------------------------------------------------------------------------
  90. void BVHLoader::SetupProperties(const Importer *pImp) {
  91. noSkeletonMesh = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, 0) != 0;
  92. }
  93. // ------------------------------------------------------------------------------------------------
  94. // Loader meta information
  95. const aiImporterDesc *BVHLoader::GetInfo() const {
  96. return &desc;
  97. }
  98. // ------------------------------------------------------------------------------------------------
  99. // Imports the given file into the given scene structure.
  100. void BVHLoader::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
  101. mFileName = pFile;
  102. // read file into memory
  103. std::unique_ptr<IOStream> file(pIOHandler->Open(pFile));
  104. if (file.get() == nullptr) {
  105. throw DeadlyImportError("Failed to open file ", pFile, ".");
  106. }
  107. size_t fileSize = file->FileSize();
  108. if (fileSize == 0) {
  109. throw DeadlyImportError("File is too small.");
  110. }
  111. mBuffer.resize(fileSize);
  112. file->Read(&mBuffer.front(), 1, fileSize);
  113. // start reading
  114. mReader = mBuffer.begin();
  115. mLine = 1;
  116. ReadStructure(pScene);
  117. if (!noSkeletonMesh) {
  118. // build a dummy mesh for the skeleton so that we see something at least
  119. SkeletonMeshBuilder meshBuilder(pScene);
  120. }
  121. // construct an animation from all the motion data we read
  122. CreateAnimation(pScene);
  123. }
  124. // ------------------------------------------------------------------------------------------------
  125. // Reads the file
  126. void BVHLoader::ReadStructure(aiScene *pScene) {
  127. // first comes hierarchy
  128. std::string header = GetNextToken();
  129. if (header != "HIERARCHY")
  130. ThrowException("Expected header string \"HIERARCHY\".");
  131. ReadHierarchy(pScene);
  132. // then comes the motion data
  133. std::string motion = GetNextToken();
  134. if (motion != "MOTION")
  135. ThrowException("Expected beginning of motion data \"MOTION\".");
  136. ReadMotion(pScene);
  137. }
  138. // ------------------------------------------------------------------------------------------------
  139. // Reads the hierarchy
  140. void BVHLoader::ReadHierarchy(aiScene *pScene) {
  141. std::string root = GetNextToken();
  142. if (root != "ROOT")
  143. ThrowException("Expected root node \"ROOT\".");
  144. // Go read the hierarchy from here
  145. pScene->mRootNode = ReadNode();
  146. }
  147. // ------------------------------------------------------------------------------------------------
  148. // Reads a node and recursively its childs and returns the created node;
  149. aiNode *BVHLoader::ReadNode() {
  150. // first token is name
  151. std::string nodeName = GetNextToken();
  152. if (nodeName.empty() || nodeName == "{")
  153. ThrowException("Expected node name, but found \"", nodeName, "\".");
  154. // then an opening brace should follow
  155. std::string openBrace = GetNextToken();
  156. if (openBrace != "{")
  157. ThrowException("Expected opening brace \"{\", but found \"", openBrace, "\".");
  158. // Create a node
  159. aiNode *node = new aiNode(nodeName);
  160. std::vector<aiNode *> childNodes;
  161. // and create an bone entry for it
  162. mNodes.push_back(Node(node));
  163. Node &internNode = mNodes.back();
  164. // now read the node's contents
  165. std::string siteToken;
  166. while (1) {
  167. std::string token = GetNextToken();
  168. // node offset to parent node
  169. if (token == "OFFSET")
  170. ReadNodeOffset(node);
  171. else if (token == "CHANNELS")
  172. ReadNodeChannels(internNode);
  173. else if (token == "JOINT") {
  174. // child node follows
  175. aiNode *child = ReadNode();
  176. child->mParent = node;
  177. childNodes.push_back(child);
  178. } else if (token == "End") {
  179. // The real symbol is "End Site". Second part comes in a separate token
  180. siteToken.clear();
  181. siteToken = GetNextToken();
  182. if (siteToken != "Site")
  183. ThrowException("Expected \"End Site\" keyword, but found \"", token, " ", siteToken, "\".");
  184. aiNode *child = ReadEndSite(nodeName);
  185. child->mParent = node;
  186. childNodes.push_back(child);
  187. } else if (token == "}") {
  188. // we're done with that part of the hierarchy
  189. break;
  190. } else {
  191. // everything else is a parse error
  192. ThrowException("Unknown keyword \"", token, "\".");
  193. }
  194. }
  195. // add the child nodes if there are any
  196. if (childNodes.size() > 0) {
  197. node->mNumChildren = static_cast<unsigned int>(childNodes.size());
  198. node->mChildren = new aiNode *[node->mNumChildren];
  199. std::copy(childNodes.begin(), childNodes.end(), node->mChildren);
  200. }
  201. // and return the sub-hierarchy we built here
  202. return node;
  203. }
  204. // ------------------------------------------------------------------------------------------------
  205. // Reads an end node and returns the created node.
  206. aiNode *BVHLoader::ReadEndSite(const std::string &pParentName) {
  207. // check opening brace
  208. std::string openBrace = GetNextToken();
  209. if (openBrace != "{")
  210. ThrowException("Expected opening brace \"{\", but found \"", openBrace, "\".");
  211. // Create a node
  212. aiNode *node = new aiNode("EndSite_" + pParentName);
  213. // now read the node's contents. Only possible entry is "OFFSET"
  214. std::string token;
  215. while (1) {
  216. token.clear();
  217. token = GetNextToken();
  218. // end node's offset
  219. if (token == "OFFSET") {
  220. ReadNodeOffset(node);
  221. } else if (token == "}") {
  222. // we're done with the end node
  223. break;
  224. } else {
  225. // everything else is a parse error
  226. ThrowException("Unknown keyword \"", token, "\".");
  227. }
  228. }
  229. // and return the sub-hierarchy we built here
  230. return node;
  231. }
  232. // ------------------------------------------------------------------------------------------------
  233. // Reads a node offset for the given node
  234. void BVHLoader::ReadNodeOffset(aiNode *pNode) {
  235. // Offset consists of three floats to read
  236. aiVector3D offset;
  237. offset.x = GetNextTokenAsFloat();
  238. offset.y = GetNextTokenAsFloat();
  239. offset.z = GetNextTokenAsFloat();
  240. // build a transformation matrix from it
  241. pNode->mTransformation = aiMatrix4x4(1.0f, 0.0f, 0.0f, offset.x,
  242. 0.0f, 1.0f, 0.0f, offset.y,
  243. 0.0f, 0.0f, 1.0f, offset.z,
  244. 0.0f, 0.0f, 0.0f, 1.0f);
  245. }
  246. // ------------------------------------------------------------------------------------------------
  247. // Reads the animation channels for the given node
  248. void BVHLoader::ReadNodeChannels(BVHLoader::Node &pNode) {
  249. // number of channels. Use the float reader because we're lazy
  250. float numChannelsFloat = GetNextTokenAsFloat();
  251. unsigned int numChannels = (unsigned int)numChannelsFloat;
  252. for (unsigned int a = 0; a < numChannels; a++) {
  253. std::string channelToken = GetNextToken();
  254. if (channelToken == "Xposition")
  255. pNode.mChannels.push_back(Channel_PositionX);
  256. else if (channelToken == "Yposition")
  257. pNode.mChannels.push_back(Channel_PositionY);
  258. else if (channelToken == "Zposition")
  259. pNode.mChannels.push_back(Channel_PositionZ);
  260. else if (channelToken == "Xrotation")
  261. pNode.mChannels.push_back(Channel_RotationX);
  262. else if (channelToken == "Yrotation")
  263. pNode.mChannels.push_back(Channel_RotationY);
  264. else if (channelToken == "Zrotation")
  265. pNode.mChannels.push_back(Channel_RotationZ);
  266. else
  267. ThrowException("Invalid channel specifier \"", channelToken, "\".");
  268. }
  269. }
  270. // ------------------------------------------------------------------------------------------------
  271. // Reads the motion data
  272. void BVHLoader::ReadMotion(aiScene * /*pScene*/) {
  273. // Read number of frames
  274. std::string tokenFrames = GetNextToken();
  275. if (tokenFrames != "Frames:")
  276. ThrowException("Expected frame count \"Frames:\", but found \"", tokenFrames, "\".");
  277. float numFramesFloat = GetNextTokenAsFloat();
  278. mAnimNumFrames = (unsigned int)numFramesFloat;
  279. // Read frame duration
  280. std::string tokenDuration1 = GetNextToken();
  281. std::string tokenDuration2 = GetNextToken();
  282. if (tokenDuration1 != "Frame" || tokenDuration2 != "Time:")
  283. ThrowException("Expected frame duration \"Frame Time:\", but found \"", tokenDuration1, " ", tokenDuration2, "\".");
  284. mAnimTickDuration = GetNextTokenAsFloat();
  285. // resize value vectors for each node
  286. for (std::vector<Node>::iterator it = mNodes.begin(); it != mNodes.end(); ++it)
  287. it->mChannelValues.reserve(it->mChannels.size() * mAnimNumFrames);
  288. // now read all the data and store it in the corresponding node's value vector
  289. for (unsigned int frame = 0; frame < mAnimNumFrames; ++frame) {
  290. // on each line read the values for all nodes
  291. for (std::vector<Node>::iterator it = mNodes.begin(); it != mNodes.end(); ++it) {
  292. // get as many values as the node has channels
  293. for (unsigned int c = 0; c < it->mChannels.size(); ++c)
  294. it->mChannelValues.push_back(GetNextTokenAsFloat());
  295. }
  296. // after one frame worth of values for all nodes there should be a newline, but we better don't rely on it
  297. }
  298. }
  299. // ------------------------------------------------------------------------------------------------
  300. // Retrieves the next token
  301. std::string BVHLoader::GetNextToken() {
  302. // skip any preceding whitespace
  303. while (mReader != mBuffer.end()) {
  304. if (!isspace((unsigned char)*mReader))
  305. break;
  306. // count lines
  307. if (*mReader == '\n')
  308. mLine++;
  309. ++mReader;
  310. }
  311. // collect all chars till the next whitespace. BVH is easy in respect to that.
  312. std::string token;
  313. while (mReader != mBuffer.end()) {
  314. if (isspace((unsigned char)*mReader))
  315. break;
  316. token.push_back(*mReader);
  317. ++mReader;
  318. // little extra logic to make sure braces are counted correctly
  319. if (token == "{" || token == "}")
  320. break;
  321. }
  322. // empty token means end of file, which is just fine
  323. return token;
  324. }
  325. // ------------------------------------------------------------------------------------------------
  326. // Reads the next token as a float
  327. float BVHLoader::GetNextTokenAsFloat() {
  328. std::string token = GetNextToken();
  329. if (token.empty())
  330. ThrowException("Unexpected end of file while trying to read a float");
  331. // check if the float is valid by testing if the atof() function consumed every char of the token
  332. const char *ctoken = token.c_str();
  333. float result = 0.0f;
  334. ctoken = fast_atoreal_move<float>(ctoken, result);
  335. if (ctoken != token.c_str() + token.length())
  336. ThrowException("Expected a floating point number, but found \"", token, "\".");
  337. return result;
  338. }
  339. // ------------------------------------------------------------------------------------------------
  340. // Constructs an animation for the motion data and stores it in the given scene
  341. void BVHLoader::CreateAnimation(aiScene *pScene) {
  342. // create the animation
  343. pScene->mNumAnimations = 1;
  344. pScene->mAnimations = new aiAnimation *[1];
  345. aiAnimation *anim = new aiAnimation;
  346. pScene->mAnimations[0] = anim;
  347. // put down the basic parameters
  348. anim->mName.Set("Motion");
  349. anim->mTicksPerSecond = 1.0 / double(mAnimTickDuration);
  350. anim->mDuration = double(mAnimNumFrames - 1);
  351. // now generate the tracks for all nodes
  352. anim->mNumChannels = static_cast<unsigned int>(mNodes.size());
  353. anim->mChannels = new aiNodeAnim *[anim->mNumChannels];
  354. // FIX: set the array elements to nullptr to ensure proper deletion if an exception is thrown
  355. for (unsigned int i = 0; i < anim->mNumChannels; ++i)
  356. anim->mChannels[i] = nullptr;
  357. for (unsigned int a = 0; a < anim->mNumChannels; a++) {
  358. const Node &node = mNodes[a];
  359. const std::string nodeName = std::string(node.mNode->mName.data);
  360. aiNodeAnim *nodeAnim = new aiNodeAnim;
  361. anim->mChannels[a] = nodeAnim;
  362. nodeAnim->mNodeName.Set(nodeName);
  363. std::map<BVHLoader::ChannelType, int> channelMap;
  364. //Build map of channels
  365. for (unsigned int channel = 0; channel < node.mChannels.size(); ++channel) {
  366. channelMap[node.mChannels[channel]] = channel;
  367. }
  368. // translational part, if given
  369. if (node.mChannels.size() == 6) {
  370. nodeAnim->mNumPositionKeys = mAnimNumFrames;
  371. nodeAnim->mPositionKeys = new aiVectorKey[mAnimNumFrames];
  372. aiVectorKey *poskey = nodeAnim->mPositionKeys;
  373. for (unsigned int fr = 0; fr < mAnimNumFrames; ++fr) {
  374. poskey->mTime = double(fr);
  375. // Now compute all translations
  376. for (BVHLoader::ChannelType channel = Channel_PositionX; channel <= Channel_PositionZ; channel = (BVHLoader::ChannelType)(channel + 1)) {
  377. //Find channel in node
  378. std::map<BVHLoader::ChannelType, int>::iterator mapIter = channelMap.find(channel);
  379. if (mapIter == channelMap.end())
  380. throw DeadlyImportError("Missing position channel in node ", nodeName);
  381. else {
  382. int channelIdx = mapIter->second;
  383. switch (channel) {
  384. case Channel_PositionX:
  385. poskey->mValue.x = node.mChannelValues[fr * node.mChannels.size() + channelIdx];
  386. break;
  387. case Channel_PositionY:
  388. poskey->mValue.y = node.mChannelValues[fr * node.mChannels.size() + channelIdx];
  389. break;
  390. case Channel_PositionZ:
  391. poskey->mValue.z = node.mChannelValues[fr * node.mChannels.size() + channelIdx];
  392. break;
  393. default:
  394. break;
  395. }
  396. }
  397. }
  398. ++poskey;
  399. }
  400. } else {
  401. // if no translation part is given, put a default sequence
  402. aiVector3D nodePos(node.mNode->mTransformation.a4, node.mNode->mTransformation.b4, node.mNode->mTransformation.c4);
  403. nodeAnim->mNumPositionKeys = 1;
  404. nodeAnim->mPositionKeys = new aiVectorKey[1];
  405. nodeAnim->mPositionKeys[0].mTime = 0.0;
  406. nodeAnim->mPositionKeys[0].mValue = nodePos;
  407. }
  408. // rotation part. Always present. First find value offsets
  409. {
  410. // Then create the number of rotation keys
  411. nodeAnim->mNumRotationKeys = mAnimNumFrames;
  412. nodeAnim->mRotationKeys = new aiQuatKey[mAnimNumFrames];
  413. aiQuatKey *rotkey = nodeAnim->mRotationKeys;
  414. for (unsigned int fr = 0; fr < mAnimNumFrames; ++fr) {
  415. aiMatrix4x4 temp;
  416. aiMatrix3x3 rotMatrix;
  417. for (unsigned int channelIdx = 0; channelIdx < node.mChannels.size(); ++ channelIdx) {
  418. switch (node.mChannels[channelIdx]) {
  419. case Channel_RotationX:
  420. {
  421. const float angle = node.mChannelValues[fr * node.mChannels.size() + channelIdx] * float(AI_MATH_PI) / 180.0f;
  422. aiMatrix4x4::RotationX( angle, temp); rotMatrix *= aiMatrix3x3( temp);
  423. }
  424. break;
  425. case Channel_RotationY:
  426. {
  427. const float angle = node.mChannelValues[fr * node.mChannels.size() + channelIdx] * float(AI_MATH_PI) / 180.0f;
  428. aiMatrix4x4::RotationY( angle, temp); rotMatrix *= aiMatrix3x3( temp);
  429. }
  430. break;
  431. case Channel_RotationZ:
  432. {
  433. const float angle = node.mChannelValues[fr * node.mChannels.size() + channelIdx] * float(AI_MATH_PI) / 180.0f;
  434. aiMatrix4x4::RotationZ( angle, temp); rotMatrix *= aiMatrix3x3( temp);
  435. }
  436. break;
  437. default:
  438. break;
  439. }
  440. }
  441. rotkey->mTime = double(fr);
  442. rotkey->mValue = aiQuaternion(rotMatrix);
  443. ++rotkey;
  444. }
  445. }
  446. // scaling part. Always just a default track
  447. {
  448. nodeAnim->mNumScalingKeys = 1;
  449. nodeAnim->mScalingKeys = new aiVectorKey[1];
  450. nodeAnim->mScalingKeys[0].mTime = 0.0;
  451. nodeAnim->mScalingKeys[0].mValue.Set(1.0f, 1.0f, 1.0f);
  452. }
  453. }
  454. }
  455. #endif // !! ASSIMP_BUILD_NO_BVH_IMPORTER