BVHLoader.cpp 19 KB

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