BVHLoader.cpp 17 KB

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