vrshoot

view libs/assimp/BVHLoader.cpp @ 2:334d17aed7de

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