您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

1569 行
59 KiB

  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2012, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file Implementation of the Collada loader */
  35. #include "AssimpPCH.h"
  36. #ifndef ASSIMP_BUILD_NO_COLLADA_IMPORTER
  37. #include "../include/assimp/anim.h"
  38. #include "ColladaLoader.h"
  39. #include "ColladaParser.h"
  40. #include "fast_atof.h"
  41. #include "ParsingUtils.h"
  42. #include "SkeletonMeshBuilder.h"
  43. #include "time.h"
  44. using namespace Assimp;
  45. static const aiImporterDesc desc = {
  46. "Collada Importer",
  47. "",
  48. "",
  49. "http://collada.org",
  50. aiImporterFlags_SupportTextFlavour,
  51. 1,
  52. 3,
  53. 1,
  54. 5,
  55. "dae"
  56. };
  57. // ------------------------------------------------------------------------------------------------
  58. // Constructor to be privately used by Importer
  59. ColladaLoader::ColladaLoader()
  60. : noSkeletonMesh(), ignoreUpDirection(false)
  61. {}
  62. // ------------------------------------------------------------------------------------------------
  63. // Destructor, private as well
  64. ColladaLoader::~ColladaLoader()
  65. {}
  66. // ------------------------------------------------------------------------------------------------
  67. // Returns whether the class can handle the format of the given file.
  68. bool ColladaLoader::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  69. {
  70. // check file extension
  71. std::string extension = GetExtension(pFile);
  72. if( extension == "dae")
  73. return true;
  74. // XML - too generic, we need to open the file and search for typical keywords
  75. if( extension == "xml" || !extension.length() || checkSig) {
  76. /* If CanRead() is called in order to check whether we
  77. * support a specific file extension in general pIOHandler
  78. * might be NULL and it's our duty to return true here.
  79. */
  80. if (!pIOHandler)return true;
  81. const char* tokens[] = {"collada"};
  82. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  83. }
  84. return false;
  85. }
  86. // ------------------------------------------------------------------------------------------------
  87. void ColladaLoader::SetupProperties(const Importer* pImp)
  88. {
  89. noSkeletonMesh = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_NO_SKELETON_MESHES,0) != 0;
  90. ignoreUpDirection = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_COLLADA_IGNORE_UP_DIRECTION,0) != 0;
  91. }
  92. // ------------------------------------------------------------------------------------------------
  93. // Get file extension list
  94. const aiImporterDesc* ColladaLoader::GetInfo () const
  95. {
  96. return &desc;
  97. }
  98. // ------------------------------------------------------------------------------------------------
  99. // Imports the given file into the given scene structure.
  100. void ColladaLoader::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  101. {
  102. mFileName = pFile;
  103. // clean all member arrays - just for safety, it should work even if we did not
  104. mMeshIndexByID.clear();
  105. mMaterialIndexByName.clear();
  106. mMeshes.clear();
  107. newMats.clear();
  108. mLights.clear();
  109. mCameras.clear();
  110. mTextures.clear();
  111. mAnims.clear();
  112. // parse the input file
  113. ColladaParser parser( pIOHandler, pFile);
  114. if( !parser.mRootNode)
  115. throw DeadlyImportError( "Collada: File came out empty. Something is wrong here.");
  116. // reserve some storage to avoid unnecessary reallocs
  117. newMats.reserve(parser.mMaterialLibrary.size()*2);
  118. mMeshes.reserve(parser.mMeshLibrary.size()*2);
  119. mCameras.reserve(parser.mCameraLibrary.size());
  120. mLights.reserve(parser.mLightLibrary.size());
  121. // create the materials first, for the meshes to find
  122. BuildMaterials( parser, pScene);
  123. // build the node hierarchy from it
  124. pScene->mRootNode = BuildHierarchy( parser, parser.mRootNode);
  125. // ... then fill the materials with the now adjusted settings
  126. FillMaterials(parser, pScene);
  127. // Apply unitsize scale calculation
  128. pScene->mRootNode->mTransformation *= aiMatrix4x4(parser.mUnitSize, 0, 0, 0,
  129. 0, parser.mUnitSize, 0, 0,
  130. 0, 0, parser.mUnitSize, 0,
  131. 0, 0, 0, 1);
  132. if( !ignoreUpDirection ) {
  133. // Convert to Y_UP, if different orientation
  134. if( parser.mUpDirection == ColladaParser::UP_X)
  135. pScene->mRootNode->mTransformation *= aiMatrix4x4(
  136. 0, -1, 0, 0,
  137. 1, 0, 0, 0,
  138. 0, 0, 1, 0,
  139. 0, 0, 0, 1);
  140. else if( parser.mUpDirection == ColladaParser::UP_Z)
  141. pScene->mRootNode->mTransformation *= aiMatrix4x4(
  142. 1, 0, 0, 0,
  143. 0, 0, 1, 0,
  144. 0, -1, 0, 0,
  145. 0, 0, 0, 1);
  146. }
  147. // store all meshes
  148. StoreSceneMeshes( pScene);
  149. // store all materials
  150. StoreSceneMaterials( pScene);
  151. // store all lights
  152. StoreSceneLights( pScene);
  153. // store all cameras
  154. StoreSceneCameras( pScene);
  155. // store all animations
  156. StoreAnimations( pScene, parser);
  157. // If no meshes have been loaded, it's probably just an animated skeleton.
  158. if (!pScene->mNumMeshes) {
  159. if (!noSkeletonMesh) {
  160. SkeletonMeshBuilder hero(pScene);
  161. }
  162. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  163. }
  164. }
  165. // ------------------------------------------------------------------------------------------------
  166. // Recursively constructs a scene node for the given parser node and returns it.
  167. aiNode* ColladaLoader::BuildHierarchy( const ColladaParser& pParser, const Collada::Node* pNode)
  168. {
  169. // create a node for it
  170. aiNode* node = new aiNode();
  171. // find a name for the new node. It's more complicated than you might think
  172. node->mName.Set( FindNameForNode( pNode));
  173. // calculate the transformation matrix for it
  174. node->mTransformation = pParser.CalculateResultTransform( pNode->mTransforms);
  175. // now resolve node instances
  176. std::vector<const Collada::Node*> instances;
  177. ResolveNodeInstances(pParser,pNode,instances);
  178. // add children. first the *real* ones
  179. node->mNumChildren = pNode->mChildren.size()+instances.size();
  180. node->mChildren = new aiNode*[node->mNumChildren];
  181. for( size_t a = 0; a < pNode->mChildren.size(); a++)
  182. {
  183. node->mChildren[a] = BuildHierarchy( pParser, pNode->mChildren[a]);
  184. node->mChildren[a]->mParent = node;
  185. }
  186. // ... and finally the resolved node instances
  187. for( size_t a = 0; a < instances.size(); a++)
  188. {
  189. node->mChildren[pNode->mChildren.size() + a] = BuildHierarchy( pParser, instances[a]);
  190. node->mChildren[pNode->mChildren.size() + a]->mParent = node;
  191. }
  192. // construct meshes
  193. BuildMeshesForNode( pParser, pNode, node);
  194. // construct cameras
  195. BuildCamerasForNode(pParser, pNode, node);
  196. // construct lights
  197. BuildLightsForNode(pParser, pNode, node);
  198. return node;
  199. }
  200. // ------------------------------------------------------------------------------------------------
  201. // Resolve node instances
  202. void ColladaLoader::ResolveNodeInstances( const ColladaParser& pParser, const Collada::Node* pNode,
  203. std::vector<const Collada::Node*>& resolved)
  204. {
  205. // reserve enough storage
  206. resolved.reserve(pNode->mNodeInstances.size());
  207. // ... and iterate through all nodes to be instanced as children of pNode
  208. for (std::vector<Collada::NodeInstance>::const_iterator it = pNode->mNodeInstances.begin(),
  209. end = pNode->mNodeInstances.end(); it != end; ++it)
  210. {
  211. // find the corresponding node in the library
  212. const ColladaParser::NodeLibrary::const_iterator itt = pParser.mNodeLibrary.find((*it).mNode);
  213. const Collada::Node* nd = itt == pParser.mNodeLibrary.end() ? NULL : (*itt).second;
  214. // FIX for http://sourceforge.net/tracker/?func=detail&aid=3054873&group_id=226462&atid=1067632
  215. // need to check for both name and ID to catch all. To avoid breaking valid files,
  216. // the workaround is only enabled when the first attempt to resolve the node has failed.
  217. if (!nd) {
  218. nd = FindNode(pParser.mRootNode,(*it).mNode);
  219. }
  220. if (!nd)
  221. DefaultLogger::get()->error("Collada: Unable to resolve reference to instanced node " + (*it).mNode);
  222. else {
  223. // attach this node to the list of children
  224. resolved.push_back(nd);
  225. }
  226. }
  227. }
  228. // ------------------------------------------------------------------------------------------------
  229. // Resolve UV channels
  230. void ColladaLoader::ApplyVertexToEffectSemanticMapping(Collada::Sampler& sampler,
  231. const Collada::SemanticMappingTable& table)
  232. {
  233. std::map<std::string, Collada::InputSemanticMapEntry>::const_iterator it = table.mMap.find(sampler.mUVChannel);
  234. if (it != table.mMap.end()) {
  235. if (it->second.mType != Collada::IT_Texcoord)
  236. DefaultLogger::get()->error("Collada: Unexpected effect input mapping");
  237. sampler.mUVId = it->second.mSet;
  238. }
  239. }
  240. // ------------------------------------------------------------------------------------------------
  241. // Builds lights for the given node and references them
  242. void ColladaLoader::BuildLightsForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget)
  243. {
  244. BOOST_FOREACH( const Collada::LightInstance& lid, pNode->mLights)
  245. {
  246. // find the referred light
  247. ColladaParser::LightLibrary::const_iterator srcLightIt = pParser.mLightLibrary.find( lid.mLight);
  248. if( srcLightIt == pParser.mLightLibrary.end())
  249. {
  250. DefaultLogger::get()->warn("Collada: Unable to find light for ID \"" + lid.mLight + "\". Skipping.");
  251. continue;
  252. }
  253. const Collada::Light* srcLight = &srcLightIt->second;
  254. if (srcLight->mType == aiLightSource_AMBIENT) {
  255. DefaultLogger::get()->error("Collada: Skipping ambient light for the moment");
  256. continue;
  257. }
  258. // now fill our ai data structure
  259. aiLight* out = new aiLight();
  260. out->mName = pTarget->mName;
  261. out->mType = (aiLightSourceType)srcLight->mType;
  262. // collada lights point in -Z by default, rest is specified in node transform
  263. out->mDirection = aiVector3D(0.f,0.f,-1.f);
  264. out->mAttenuationConstant = srcLight->mAttConstant;
  265. out->mAttenuationLinear = srcLight->mAttLinear;
  266. out->mAttenuationQuadratic = srcLight->mAttQuadratic;
  267. // collada doesn't differenciate between these color types
  268. out->mColorDiffuse = out->mColorSpecular = out->mColorAmbient = srcLight->mColor*srcLight->mIntensity;
  269. // convert falloff angle and falloff exponent in our representation, if given
  270. if (out->mType == aiLightSource_SPOT) {
  271. out->mAngleInnerCone = AI_DEG_TO_RAD( srcLight->mFalloffAngle );
  272. // ... some extension magic.
  273. if (srcLight->mOuterAngle >= ASSIMP_COLLADA_LIGHT_ANGLE_NOT_SET*(1-1e-6f))
  274. {
  275. // ... some deprecation magic.
  276. if (srcLight->mPenumbraAngle >= ASSIMP_COLLADA_LIGHT_ANGLE_NOT_SET*(1-1e-6f))
  277. {
  278. // Need to rely on falloff_exponent. I don't know how to interpret it, so I need to guess ....
  279. // epsilon chosen to be 0.1
  280. out->mAngleOuterCone = AI_DEG_TO_RAD (acos(pow(0.1f,1.f/srcLight->mFalloffExponent))+
  281. srcLight->mFalloffAngle);
  282. }
  283. else {
  284. out->mAngleOuterCone = out->mAngleInnerCone + AI_DEG_TO_RAD( srcLight->mPenumbraAngle );
  285. if (out->mAngleOuterCone < out->mAngleInnerCone)
  286. std::swap(out->mAngleInnerCone,out->mAngleOuterCone);
  287. }
  288. }
  289. else out->mAngleOuterCone = AI_DEG_TO_RAD( srcLight->mOuterAngle );
  290. }
  291. // add to light list
  292. mLights.push_back(out);
  293. }
  294. }
  295. // ------------------------------------------------------------------------------------------------
  296. // Builds cameras for the given node and references them
  297. void ColladaLoader::BuildCamerasForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget)
  298. {
  299. BOOST_FOREACH( const Collada::CameraInstance& cid, pNode->mCameras)
  300. {
  301. // find the referred light
  302. ColladaParser::CameraLibrary::const_iterator srcCameraIt = pParser.mCameraLibrary.find( cid.mCamera);
  303. if( srcCameraIt == pParser.mCameraLibrary.end())
  304. {
  305. DefaultLogger::get()->warn("Collada: Unable to find camera for ID \"" + cid.mCamera + "\". Skipping.");
  306. continue;
  307. }
  308. const Collada::Camera* srcCamera = &srcCameraIt->second;
  309. // orthographic cameras not yet supported in Assimp
  310. if (srcCamera->mOrtho) {
  311. DefaultLogger::get()->warn("Collada: Orthographic cameras are not supported.");
  312. }
  313. // now fill our ai data structure
  314. aiCamera* out = new aiCamera();
  315. out->mName = pTarget->mName;
  316. // collada cameras point in -Z by default, rest is specified in node transform
  317. out->mLookAt = aiVector3D(0.f,0.f,-1.f);
  318. // near/far z is already ok
  319. out->mClipPlaneFar = srcCamera->mZFar;
  320. out->mClipPlaneNear = srcCamera->mZNear;
  321. // ... but for the rest some values are optional
  322. // and we need to compute the others in any combination.
  323. if (srcCamera->mAspect != 10e10f)
  324. out->mAspect = srcCamera->mAspect;
  325. if (srcCamera->mHorFov != 10e10f) {
  326. out->mHorizontalFOV = srcCamera->mHorFov;
  327. if (srcCamera->mVerFov != 10e10f && srcCamera->mAspect == 10e10f) {
  328. out->mAspect = tan(AI_DEG_TO_RAD(srcCamera->mHorFov)) /
  329. tan(AI_DEG_TO_RAD(srcCamera->mVerFov));
  330. }
  331. }
  332. else if (srcCamera->mAspect != 10e10f && srcCamera->mVerFov != 10e10f) {
  333. out->mHorizontalFOV = 2.0f * AI_RAD_TO_DEG(atan(srcCamera->mAspect *
  334. tan(AI_DEG_TO_RAD(srcCamera->mVerFov) * 0.5f)));
  335. }
  336. // Collada uses degrees, we use radians
  337. out->mHorizontalFOV = AI_DEG_TO_RAD(out->mHorizontalFOV);
  338. // add to camera list
  339. mCameras.push_back(out);
  340. }
  341. }
  342. // ------------------------------------------------------------------------------------------------
  343. // Builds meshes for the given node and references them
  344. void ColladaLoader::BuildMeshesForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget)
  345. {
  346. // accumulated mesh references by this node
  347. std::vector<size_t> newMeshRefs;
  348. newMeshRefs.reserve(pNode->mMeshes.size());
  349. // add a mesh for each subgroup in each collada mesh
  350. BOOST_FOREACH( const Collada::MeshInstance& mid, pNode->mMeshes)
  351. {
  352. const Collada::Mesh* srcMesh = NULL;
  353. const Collada::Controller* srcController = NULL;
  354. // find the referred mesh
  355. ColladaParser::MeshLibrary::const_iterator srcMeshIt = pParser.mMeshLibrary.find( mid.mMeshOrController);
  356. if( srcMeshIt == pParser.mMeshLibrary.end())
  357. {
  358. // if not found in the mesh-library, it might also be a controller referring to a mesh
  359. ColladaParser::ControllerLibrary::const_iterator srcContrIt = pParser.mControllerLibrary.find( mid.mMeshOrController);
  360. if( srcContrIt != pParser.mControllerLibrary.end())
  361. {
  362. srcController = &srcContrIt->second;
  363. srcMeshIt = pParser.mMeshLibrary.find( srcController->mMeshId);
  364. if( srcMeshIt != pParser.mMeshLibrary.end())
  365. srcMesh = srcMeshIt->second;
  366. }
  367. if( !srcMesh)
  368. {
  369. DefaultLogger::get()->warn( boost::str( boost::format( "Collada: Unable to find geometry for ID \"%s\". Skipping.") % mid.mMeshOrController));
  370. continue;
  371. }
  372. } else
  373. {
  374. // ID found in the mesh library -> direct reference to an unskinned mesh
  375. srcMesh = srcMeshIt->second;
  376. }
  377. // build a mesh for each of its subgroups
  378. size_t vertexStart = 0, faceStart = 0;
  379. for( size_t sm = 0; sm < srcMesh->mSubMeshes.size(); ++sm)
  380. {
  381. const Collada::SubMesh& submesh = srcMesh->mSubMeshes[sm];
  382. if( submesh.mNumFaces == 0)
  383. continue;
  384. // find material assigned to this submesh
  385. std::string meshMaterial;
  386. std::map<std::string, Collada::SemanticMappingTable >::const_iterator meshMatIt = mid.mMaterials.find( submesh.mMaterial);
  387. const Collada::SemanticMappingTable* table = NULL;
  388. if( meshMatIt != mid.mMaterials.end())
  389. {
  390. table = &meshMatIt->second;
  391. meshMaterial = table->mMatName;
  392. }
  393. else
  394. {
  395. DefaultLogger::get()->warn( boost::str( boost::format( "Collada: No material specified for subgroup <%s> in geometry <%s>.") % submesh.mMaterial % mid.mMeshOrController));
  396. if( !mid.mMaterials.empty() )
  397. meshMaterial = mid.mMaterials.begin()->second.mMatName;
  398. }
  399. // OK ... here the *real* fun starts ... we have the vertex-input-to-effect-semantic-table
  400. // given. The only mapping stuff which we do actually support is the UV channel.
  401. std::map<std::string, size_t>::const_iterator matIt = mMaterialIndexByName.find( meshMaterial);
  402. unsigned int matIdx;
  403. if( matIt != mMaterialIndexByName.end())
  404. matIdx = matIt->second;
  405. else
  406. matIdx = 0;
  407. if (table && !table->mMap.empty() ) {
  408. std::pair<Collada::Effect*, aiMaterial*>& mat = newMats[matIdx];
  409. // Iterate through all texture channels assigned to the effect and
  410. // check whether we have mapping information for it.
  411. ApplyVertexToEffectSemanticMapping(mat.first->mTexDiffuse, *table);
  412. ApplyVertexToEffectSemanticMapping(mat.first->mTexAmbient, *table);
  413. ApplyVertexToEffectSemanticMapping(mat.first->mTexSpecular, *table);
  414. ApplyVertexToEffectSemanticMapping(mat.first->mTexEmissive, *table);
  415. ApplyVertexToEffectSemanticMapping(mat.first->mTexTransparent,*table);
  416. ApplyVertexToEffectSemanticMapping(mat.first->mTexBump, *table);
  417. }
  418. // built lookup index of the Mesh-Submesh-Material combination
  419. ColladaMeshIndex index( mid.mMeshOrController, sm, meshMaterial);
  420. // if we already have the mesh at the library, just add its index to the node's array
  421. std::map<ColladaMeshIndex, size_t>::const_iterator dstMeshIt = mMeshIndexByID.find( index);
  422. if( dstMeshIt != mMeshIndexByID.end()) {
  423. newMeshRefs.push_back( dstMeshIt->second);
  424. }
  425. else
  426. {
  427. // else we have to add the mesh to the collection and store its newly assigned index at the node
  428. aiMesh* dstMesh = CreateMesh( pParser, srcMesh, submesh, srcController, vertexStart, faceStart);
  429. // store the mesh, and store its new index in the node
  430. newMeshRefs.push_back( mMeshes.size());
  431. mMeshIndexByID[index] = mMeshes.size();
  432. mMeshes.push_back( dstMesh);
  433. vertexStart += dstMesh->mNumVertices; faceStart += submesh.mNumFaces;
  434. // assign the material index
  435. dstMesh->mMaterialIndex = matIdx;
  436. if(dstMesh->mName.length == 0)
  437. {
  438. dstMesh->mName = mid.mMeshOrController;
  439. }
  440. }
  441. }
  442. }
  443. // now place all mesh references we gathered in the target node
  444. pTarget->mNumMeshes = newMeshRefs.size();
  445. if( newMeshRefs.size())
  446. {
  447. pTarget->mMeshes = new unsigned int[pTarget->mNumMeshes];
  448. std::copy( newMeshRefs.begin(), newMeshRefs.end(), pTarget->mMeshes);
  449. }
  450. }
  451. // ------------------------------------------------------------------------------------------------
  452. // Creates a mesh for the given ColladaMesh face subset and returns the newly created mesh
  453. aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada::Mesh* pSrcMesh, const Collada::SubMesh& pSubMesh,
  454. const Collada::Controller* pSrcController, size_t pStartVertex, size_t pStartFace)
  455. {
  456. aiMesh* dstMesh = new aiMesh;
  457. dstMesh->mName = pSrcMesh->mName;
  458. // count the vertices addressed by its faces
  459. const size_t numVertices = std::accumulate( pSrcMesh->mFaceSize.begin() + pStartFace,
  460. pSrcMesh->mFaceSize.begin() + pStartFace + pSubMesh.mNumFaces, 0);
  461. // copy positions
  462. dstMesh->mNumVertices = numVertices;
  463. dstMesh->mVertices = new aiVector3D[numVertices];
  464. std::copy( pSrcMesh->mPositions.begin() + pStartVertex, pSrcMesh->mPositions.begin() +
  465. pStartVertex + numVertices, dstMesh->mVertices);
  466. // normals, if given. HACK: (thom) Due to the glorious Collada spec we never
  467. // know if we have the same number of normals as there are positions. So we
  468. // also ignore any vertex attribute if it has a different count
  469. if( pSrcMesh->mNormals.size() >= pStartVertex + numVertices)
  470. {
  471. dstMesh->mNormals = new aiVector3D[numVertices];
  472. std::copy( pSrcMesh->mNormals.begin() + pStartVertex, pSrcMesh->mNormals.begin() +
  473. pStartVertex + numVertices, dstMesh->mNormals);
  474. }
  475. // tangents, if given.
  476. if( pSrcMesh->mTangents.size() >= pStartVertex + numVertices)
  477. {
  478. dstMesh->mTangents = new aiVector3D[numVertices];
  479. std::copy( pSrcMesh->mTangents.begin() + pStartVertex, pSrcMesh->mTangents.begin() +
  480. pStartVertex + numVertices, dstMesh->mTangents);
  481. }
  482. // bitangents, if given.
  483. if( pSrcMesh->mBitangents.size() >= pStartVertex + numVertices)
  484. {
  485. dstMesh->mBitangents = new aiVector3D[numVertices];
  486. std::copy( pSrcMesh->mBitangents.begin() + pStartVertex, pSrcMesh->mBitangents.begin() +
  487. pStartVertex + numVertices, dstMesh->mBitangents);
  488. }
  489. // same for texturecoords, as many as we have
  490. // empty slots are not allowed, need to pack and adjust UV indexes accordingly
  491. for( size_t a = 0, real = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; a++)
  492. {
  493. if( pSrcMesh->mTexCoords[a].size() >= pStartVertex + numVertices)
  494. {
  495. dstMesh->mTextureCoords[real] = new aiVector3D[numVertices];
  496. for( size_t b = 0; b < numVertices; ++b)
  497. dstMesh->mTextureCoords[real][b] = pSrcMesh->mTexCoords[a][pStartVertex+b];
  498. dstMesh->mNumUVComponents[real] = pSrcMesh->mNumUVComponents[a];
  499. ++real;
  500. }
  501. }
  502. // same for vertex colors, as many as we have. again the same packing to avoid empty slots
  503. for( size_t a = 0, real = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; a++)
  504. {
  505. if( pSrcMesh->mColors[a].size() >= pStartVertex + numVertices)
  506. {
  507. dstMesh->mColors[real] = new aiColor4D[numVertices];
  508. std::copy( pSrcMesh->mColors[a].begin() + pStartVertex, pSrcMesh->mColors[a].begin() + pStartVertex + numVertices,dstMesh->mColors[real]);
  509. ++real;
  510. }
  511. }
  512. // create faces. Due to the fact that each face uses unique vertices, we can simply count up on each vertex
  513. size_t vertex = 0;
  514. dstMesh->mNumFaces = pSubMesh.mNumFaces;
  515. dstMesh->mFaces = new aiFace[dstMesh->mNumFaces];
  516. for( size_t a = 0; a < dstMesh->mNumFaces; ++a)
  517. {
  518. size_t s = pSrcMesh->mFaceSize[ pStartFace + a];
  519. aiFace& face = dstMesh->mFaces[a];
  520. face.mNumIndices = s;
  521. face.mIndices = new unsigned int[s];
  522. for( size_t b = 0; b < s; ++b)
  523. face.mIndices[b] = vertex++;
  524. }
  525. // create bones if given
  526. if( pSrcController)
  527. {
  528. // refuse if the vertex count does not match
  529. // if( pSrcController->mWeightCounts.size() != dstMesh->mNumVertices)
  530. // throw DeadlyImportError( "Joint Controller vertex count does not match mesh vertex count");
  531. // resolve references - joint names
  532. const Collada::Accessor& jointNamesAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mJointNameSource);
  533. const Collada::Data& jointNames = pParser.ResolveLibraryReference( pParser.mDataLibrary, jointNamesAcc.mSource);
  534. // joint offset matrices
  535. const Collada::Accessor& jointMatrixAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mJointOffsetMatrixSource);
  536. const Collada::Data& jointMatrices = pParser.ResolveLibraryReference( pParser.mDataLibrary, jointMatrixAcc.mSource);
  537. // joint vertex_weight name list - should refer to the same list as the joint names above. If not, report and reconsider
  538. const Collada::Accessor& weightNamesAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mWeightInputJoints.mAccessor);
  539. if( &weightNamesAcc != &jointNamesAcc)
  540. throw DeadlyImportError( "Temporary implementational lazyness. If you read this, please report to the author.");
  541. // vertex weights
  542. const Collada::Accessor& weightsAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mWeightInputWeights.mAccessor);
  543. const Collada::Data& weights = pParser.ResolveLibraryReference( pParser.mDataLibrary, weightsAcc.mSource);
  544. if( !jointNames.mIsStringArray || jointMatrices.mIsStringArray || weights.mIsStringArray)
  545. throw DeadlyImportError( "Data type mismatch while resolving mesh joints");
  546. // sanity check: we rely on the vertex weights always coming as pairs of BoneIndex-WeightIndex
  547. if( pSrcController->mWeightInputJoints.mOffset != 0 || pSrcController->mWeightInputWeights.mOffset != 1)
  548. throw DeadlyImportError( "Unsupported vertex_weight addressing scheme. ");
  549. // create containers to collect the weights for each bone
  550. size_t numBones = jointNames.mStrings.size();
  551. std::vector<std::vector<aiVertexWeight> > dstBones( numBones);
  552. // build a temporary array of pointers to the start of each vertex's weights
  553. typedef std::vector< std::pair<size_t, size_t> > IndexPairVector;
  554. std::vector<IndexPairVector::const_iterator> weightStartPerVertex;
  555. weightStartPerVertex.resize(pSrcController->mWeightCounts.size(),pSrcController->mWeights.end());
  556. IndexPairVector::const_iterator pit = pSrcController->mWeights.begin();
  557. for( size_t a = 0; a < pSrcController->mWeightCounts.size(); ++a)
  558. {
  559. weightStartPerVertex[a] = pit;
  560. pit += pSrcController->mWeightCounts[a];
  561. }
  562. // now for each vertex put the corresponding vertex weights into each bone's weight collection
  563. for( size_t a = pStartVertex; a < pStartVertex + numVertices; ++a)
  564. {
  565. // which position index was responsible for this vertex? that's also the index by which
  566. // the controller assigns the vertex weights
  567. size_t orgIndex = pSrcMesh->mFacePosIndices[a];
  568. // find the vertex weights for this vertex
  569. IndexPairVector::const_iterator iit = weightStartPerVertex[orgIndex];
  570. size_t pairCount = pSrcController->mWeightCounts[orgIndex];
  571. for( size_t b = 0; b < pairCount; ++b, ++iit)
  572. {
  573. size_t jointIndex = iit->first;
  574. size_t vertexIndex = iit->second;
  575. float weight = ReadFloat( weightsAcc, weights, vertexIndex, 0);
  576. // one day I gonna kill that XSI Collada exporter
  577. if( weight > 0.0f)
  578. {
  579. aiVertexWeight w;
  580. w.mVertexId = a - pStartVertex;
  581. w.mWeight = weight;
  582. dstBones[jointIndex].push_back( w);
  583. }
  584. }
  585. }
  586. // count the number of bones which influence vertices of the current submesh
  587. size_t numRemainingBones = 0;
  588. for( std::vector<std::vector<aiVertexWeight> >::const_iterator it = dstBones.begin(); it != dstBones.end(); ++it)
  589. if( it->size() > 0)
  590. numRemainingBones++;
  591. // create bone array and copy bone weights one by one
  592. dstMesh->mNumBones = numRemainingBones;
  593. dstMesh->mBones = new aiBone*[numRemainingBones];
  594. size_t boneCount = 0;
  595. for( size_t a = 0; a < numBones; ++a)
  596. {
  597. // omit bones without weights
  598. if( dstBones[a].size() == 0)
  599. continue;
  600. // create bone with its weights
  601. aiBone* bone = new aiBone;
  602. bone->mName = ReadString( jointNamesAcc, jointNames, a);
  603. bone->mOffsetMatrix.a1 = ReadFloat( jointMatrixAcc, jointMatrices, a, 0);
  604. bone->mOffsetMatrix.a2 = ReadFloat( jointMatrixAcc, jointMatrices, a, 1);
  605. bone->mOffsetMatrix.a3 = ReadFloat( jointMatrixAcc, jointMatrices, a, 2);
  606. bone->mOffsetMatrix.a4 = ReadFloat( jointMatrixAcc, jointMatrices, a, 3);
  607. bone->mOffsetMatrix.b1 = ReadFloat( jointMatrixAcc, jointMatrices, a, 4);
  608. bone->mOffsetMatrix.b2 = ReadFloat( jointMatrixAcc, jointMatrices, a, 5);
  609. bone->mOffsetMatrix.b3 = ReadFloat( jointMatrixAcc, jointMatrices, a, 6);
  610. bone->mOffsetMatrix.b4 = ReadFloat( jointMatrixAcc, jointMatrices, a, 7);
  611. bone->mOffsetMatrix.c1 = ReadFloat( jointMatrixAcc, jointMatrices, a, 8);
  612. bone->mOffsetMatrix.c2 = ReadFloat( jointMatrixAcc, jointMatrices, a, 9);
  613. bone->mOffsetMatrix.c3 = ReadFloat( jointMatrixAcc, jointMatrices, a, 10);
  614. bone->mOffsetMatrix.c4 = ReadFloat( jointMatrixAcc, jointMatrices, a, 11);
  615. bone->mNumWeights = dstBones[a].size();
  616. bone->mWeights = new aiVertexWeight[bone->mNumWeights];
  617. std::copy( dstBones[a].begin(), dstBones[a].end(), bone->mWeights);
  618. // apply bind shape matrix to offset matrix
  619. aiMatrix4x4 bindShapeMatrix;
  620. bindShapeMatrix.a1 = pSrcController->mBindShapeMatrix[0];
  621. bindShapeMatrix.a2 = pSrcController->mBindShapeMatrix[1];
  622. bindShapeMatrix.a3 = pSrcController->mBindShapeMatrix[2];
  623. bindShapeMatrix.a4 = pSrcController->mBindShapeMatrix[3];
  624. bindShapeMatrix.b1 = pSrcController->mBindShapeMatrix[4];
  625. bindShapeMatrix.b2 = pSrcController->mBindShapeMatrix[5];
  626. bindShapeMatrix.b3 = pSrcController->mBindShapeMatrix[6];
  627. bindShapeMatrix.b4 = pSrcController->mBindShapeMatrix[7];
  628. bindShapeMatrix.c1 = pSrcController->mBindShapeMatrix[8];
  629. bindShapeMatrix.c2 = pSrcController->mBindShapeMatrix[9];
  630. bindShapeMatrix.c3 = pSrcController->mBindShapeMatrix[10];
  631. bindShapeMatrix.c4 = pSrcController->mBindShapeMatrix[11];
  632. bindShapeMatrix.d1 = pSrcController->mBindShapeMatrix[12];
  633. bindShapeMatrix.d2 = pSrcController->mBindShapeMatrix[13];
  634. bindShapeMatrix.d3 = pSrcController->mBindShapeMatrix[14];
  635. bindShapeMatrix.d4 = pSrcController->mBindShapeMatrix[15];
  636. bone->mOffsetMatrix *= bindShapeMatrix;
  637. // HACK: (thom) Some exporters address the bone nodes by SID, others address them by ID or even name.
  638. // Therefore I added a little name replacement here: I search for the bone's node by either name, ID or SID,
  639. // and replace the bone's name by the node's name so that the user can use the standard
  640. // find-by-name method to associate nodes with bones.
  641. const Collada::Node* bnode = FindNode( pParser.mRootNode, bone->mName.data);
  642. if( !bnode)
  643. bnode = FindNodeBySID( pParser.mRootNode, bone->mName.data);
  644. // assign the name that we would have assigned for the source node
  645. if( bnode)
  646. bone->mName.Set( FindNameForNode( bnode));
  647. else
  648. DefaultLogger::get()->warn( boost::str( boost::format( "ColladaLoader::CreateMesh(): could not find corresponding node for joint \"%s\".") % bone->mName.data));
  649. // and insert bone
  650. dstMesh->mBones[boneCount++] = bone;
  651. }
  652. }
  653. return dstMesh;
  654. }
  655. // ------------------------------------------------------------------------------------------------
  656. // Stores all meshes in the given scene
  657. void ColladaLoader::StoreSceneMeshes( aiScene* pScene)
  658. {
  659. pScene->mNumMeshes = mMeshes.size();
  660. if( mMeshes.size() > 0)
  661. {
  662. pScene->mMeshes = new aiMesh*[mMeshes.size()];
  663. std::copy( mMeshes.begin(), mMeshes.end(), pScene->mMeshes);
  664. mMeshes.clear();
  665. }
  666. }
  667. // ------------------------------------------------------------------------------------------------
  668. // Stores all cameras in the given scene
  669. void ColladaLoader::StoreSceneCameras( aiScene* pScene)
  670. {
  671. pScene->mNumCameras = mCameras.size();
  672. if( mCameras.size() > 0)
  673. {
  674. pScene->mCameras = new aiCamera*[mCameras.size()];
  675. std::copy( mCameras.begin(), mCameras.end(), pScene->mCameras);
  676. mCameras.clear();
  677. }
  678. }
  679. // ------------------------------------------------------------------------------------------------
  680. // Stores all lights in the given scene
  681. void ColladaLoader::StoreSceneLights( aiScene* pScene)
  682. {
  683. pScene->mNumLights = mLights.size();
  684. if( mLights.size() > 0)
  685. {
  686. pScene->mLights = new aiLight*[mLights.size()];
  687. std::copy( mLights.begin(), mLights.end(), pScene->mLights);
  688. mLights.clear();
  689. }
  690. }
  691. // ------------------------------------------------------------------------------------------------
  692. // Stores all textures in the given scene
  693. void ColladaLoader::StoreSceneTextures( aiScene* pScene)
  694. {
  695. pScene->mNumTextures = mTextures.size();
  696. if( mTextures.size() > 0)
  697. {
  698. pScene->mTextures = new aiTexture*[mTextures.size()];
  699. std::copy( mTextures.begin(), mTextures.end(), pScene->mTextures);
  700. mTextures.clear();
  701. }
  702. }
  703. // ------------------------------------------------------------------------------------------------
  704. // Stores all materials in the given scene
  705. void ColladaLoader::StoreSceneMaterials( aiScene* pScene)
  706. {
  707. pScene->mNumMaterials = newMats.size();
  708. if (newMats.size() > 0) {
  709. pScene->mMaterials = new aiMaterial*[newMats.size()];
  710. for (unsigned int i = 0; i < newMats.size();++i)
  711. pScene->mMaterials[i] = newMats[i].second;
  712. newMats.clear();
  713. }
  714. }
  715. // ------------------------------------------------------------------------------------------------
  716. // Stores all animations
  717. void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pParser)
  718. {
  719. // recursivly collect all animations from the collada scene
  720. StoreAnimations( pScene, pParser, &pParser.mAnims, "");
  721. // catch special case: many animations with the same length, each affecting only a single node.
  722. // we need to unite all those single-node-anims to a proper combined animation
  723. for( size_t a = 0; a < mAnims.size(); ++a)
  724. {
  725. aiAnimation* templateAnim = mAnims[a];
  726. if( templateAnim->mNumChannels == 1)
  727. {
  728. // search for other single-channel-anims with the same duration
  729. std::vector<size_t> collectedAnimIndices;
  730. for( size_t b = a+1; b < mAnims.size(); ++b)
  731. {
  732. aiAnimation* other = mAnims[b];
  733. if( other->mNumChannels == 1 && other->mDuration == templateAnim->mDuration && other->mTicksPerSecond == templateAnim->mTicksPerSecond )
  734. collectedAnimIndices.push_back( b);
  735. }
  736. // if there are other animations which fit the template anim, combine all channels into a single anim
  737. if( !collectedAnimIndices.empty() )
  738. {
  739. aiAnimation* combinedAnim = new aiAnimation();
  740. combinedAnim->mName = aiString( std::string( "combinedAnim_") + char( '0' + a));
  741. combinedAnim->mDuration = templateAnim->mDuration;
  742. combinedAnim->mTicksPerSecond = templateAnim->mTicksPerSecond;
  743. combinedAnim->mNumChannels = collectedAnimIndices.size() + 1;
  744. combinedAnim->mChannels = new aiNodeAnim*[combinedAnim->mNumChannels];
  745. // add the template anim as first channel by moving its aiNodeAnim to the combined animation
  746. combinedAnim->mChannels[0] = templateAnim->mChannels[0];
  747. templateAnim->mChannels[0] = NULL;
  748. delete templateAnim;
  749. // combined animation replaces template animation in the anim array
  750. mAnims[a] = combinedAnim;
  751. // move the memory of all other anims to the combined anim and erase them from the source anims
  752. for( size_t b = 0; b < collectedAnimIndices.size(); ++b)
  753. {
  754. aiAnimation* srcAnimation = mAnims[collectedAnimIndices[b]];
  755. combinedAnim->mChannels[1 + b] = srcAnimation->mChannels[0];
  756. srcAnimation->mChannels[0] = NULL;
  757. delete srcAnimation;
  758. }
  759. // in a second go, delete all the single-channel-anims that we've stripped from their channels
  760. // back to front to preserve indices - you know, removing an element from a vector moves all elements behind the removed one
  761. while( !collectedAnimIndices.empty() )
  762. {
  763. mAnims.erase( mAnims.begin() + collectedAnimIndices.back());
  764. collectedAnimIndices.pop_back();
  765. }
  766. }
  767. }
  768. }
  769. // now store all anims in the scene
  770. if( !mAnims.empty())
  771. {
  772. pScene->mNumAnimations = mAnims.size();
  773. pScene->mAnimations = new aiAnimation*[mAnims.size()];
  774. std::copy( mAnims.begin(), mAnims.end(), pScene->mAnimations);
  775. }
  776. mAnims.clear();
  777. }
  778. // ------------------------------------------------------------------------------------------------
  779. // Constructs the animations for the given source anim
  780. void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pParser, const Collada::Animation* pSrcAnim, const std::string pPrefix)
  781. {
  782. std::string animName = pPrefix.empty() ? pSrcAnim->mName : pPrefix + "_" + pSrcAnim->mName;
  783. // create nested animations, if given
  784. for( std::vector<Collada::Animation*>::const_iterator it = pSrcAnim->mSubAnims.begin(); it != pSrcAnim->mSubAnims.end(); ++it)
  785. StoreAnimations( pScene, pParser, *it, animName);
  786. // create animation channels, if any
  787. if( !pSrcAnim->mChannels.empty())
  788. CreateAnimation( pScene, pParser, pSrcAnim, animName);
  789. }
  790. // ------------------------------------------------------------------------------------------------
  791. // Constructs the animation for the given source anim
  792. void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pParser, const Collada::Animation* pSrcAnim, const std::string& pName)
  793. {
  794. // collect a list of animatable nodes
  795. std::vector<const aiNode*> nodes;
  796. CollectNodes( pScene->mRootNode, nodes);
  797. std::vector<aiNodeAnim*> anims;
  798. for( std::vector<const aiNode*>::const_iterator nit = nodes.begin(); nit != nodes.end(); ++nit)
  799. {
  800. // find all the collada anim channels which refer to the current node
  801. std::vector<Collada::ChannelEntry> entries;
  802. std::string nodeName = (*nit)->mName.data;
  803. // find the collada node corresponding to the aiNode
  804. const Collada::Node* srcNode = FindNode( pParser.mRootNode, nodeName);
  805. // ai_assert( srcNode != NULL);
  806. if( !srcNode)
  807. continue;
  808. // now check all channels if they affect the current node
  809. for( std::vector<Collada::AnimationChannel>::const_iterator cit = pSrcAnim->mChannels.begin();
  810. cit != pSrcAnim->mChannels.end(); ++cit)
  811. {
  812. const Collada::AnimationChannel& srcChannel = *cit;
  813. Collada::ChannelEntry entry;
  814. // we expect the animation target to be of type "nodeName/transformID.subElement". Ignore all others
  815. // find the slash that separates the node name - there should be only one
  816. std::string::size_type slashPos = srcChannel.mTarget.find( '/');
  817. if( slashPos == std::string::npos)
  818. continue;
  819. if( srcChannel.mTarget.find( '/', slashPos+1) != std::string::npos)
  820. continue;
  821. std::string targetID = srcChannel.mTarget.substr( 0, slashPos);
  822. if( targetID != srcNode->mID)
  823. continue;
  824. // find the dot that separates the transformID - there should be only one or zero
  825. std::string::size_type dotPos = srcChannel.mTarget.find( '.');
  826. if( dotPos != std::string::npos)
  827. {
  828. if( srcChannel.mTarget.find( '.', dotPos+1) != std::string::npos)
  829. continue;
  830. entry.mTransformId = srcChannel.mTarget.substr( slashPos+1, dotPos - slashPos - 1);
  831. std::string subElement = srcChannel.mTarget.substr( dotPos+1);
  832. if( subElement == "ANGLE")
  833. entry.mSubElement = 3; // last number in an Axis-Angle-Transform is the angle
  834. else if( subElement == "X")
  835. entry.mSubElement = 0;
  836. else if( subElement == "Y")
  837. entry.mSubElement = 1;
  838. else if( subElement == "Z")
  839. entry.mSubElement = 2;
  840. else
  841. DefaultLogger::get()->warn( boost::str( boost::format( "Unknown anim subelement <%s>. Ignoring") % subElement));
  842. } else
  843. {
  844. // no subelement following, transformId is remaining string
  845. entry.mTransformId = srcChannel.mTarget.substr( slashPos+1);
  846. }
  847. // determine which transform step is affected by this channel
  848. entry.mTransformIndex = SIZE_MAX;
  849. for( size_t a = 0; a < srcNode->mTransforms.size(); ++a)
  850. if( srcNode->mTransforms[a].mID == entry.mTransformId)
  851. entry.mTransformIndex = a;
  852. if( entry.mTransformIndex == SIZE_MAX) {
  853. continue;
  854. }
  855. entry.mChannel = &(*cit);
  856. entries.push_back( entry);
  857. }
  858. // if there's no channel affecting the current node, we skip it
  859. if( entries.empty())
  860. continue;
  861. // resolve the data pointers for all anim channels. Find the minimum time while we're at it
  862. float startTime = 1e20f, endTime = -1e20f;
  863. for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it)
  864. {
  865. Collada::ChannelEntry& e = *it;
  866. e.mTimeAccessor = &pParser.ResolveLibraryReference( pParser.mAccessorLibrary, e.mChannel->mSourceTimes);
  867. e.mTimeData = &pParser.ResolveLibraryReference( pParser.mDataLibrary, e.mTimeAccessor->mSource);
  868. e.mValueAccessor = &pParser.ResolveLibraryReference( pParser.mAccessorLibrary, e.mChannel->mSourceValues);
  869. e.mValueData = &pParser.ResolveLibraryReference( pParser.mDataLibrary, e.mValueAccessor->mSource);
  870. // time count and value count must match
  871. if( e.mTimeAccessor->mCount != e.mValueAccessor->mCount)
  872. throw DeadlyImportError( boost::str( boost::format( "Time count / value count mismatch in animation channel \"%s\".") % e.mChannel->mTarget));
  873. if( e.mTimeAccessor->mCount > 0 )
  874. {
  875. // find bounding times
  876. startTime = std::min( startTime, ReadFloat( *e.mTimeAccessor, *e.mTimeData, 0, 0));
  877. endTime = std::max( endTime, ReadFloat( *e.mTimeAccessor, *e.mTimeData, e.mTimeAccessor->mCount-1, 0));
  878. }
  879. }
  880. std::vector<aiMatrix4x4> resultTrafos;
  881. if( !entries.empty() && entries.front().mTimeAccessor->mCount > 0 )
  882. {
  883. // create a local transformation chain of the node's transforms
  884. std::vector<Collada::Transform> transforms = srcNode->mTransforms;
  885. // now for every unique point in time, find or interpolate the key values for that time
  886. // and apply them to the transform chain. Then the node's present transformation can be calculated.
  887. float time = startTime;
  888. while( 1)
  889. {
  890. for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it)
  891. {
  892. Collada::ChannelEntry& e = *it;
  893. // find the keyframe behind the current point in time
  894. size_t pos = 0;
  895. float postTime = 0.f;
  896. while( 1)
  897. {
  898. if( pos >= e.mTimeAccessor->mCount)
  899. break;
  900. postTime = ReadFloat( *e.mTimeAccessor, *e.mTimeData, pos, 0);
  901. if( postTime >= time)
  902. break;
  903. ++pos;
  904. }
  905. pos = std::min( pos, e.mTimeAccessor->mCount-1);
  906. // read values from there
  907. float temp[16];
  908. for( size_t c = 0; c < e.mValueAccessor->mSize; ++c)
  909. temp[c] = ReadFloat( *e.mValueAccessor, *e.mValueData, pos, c);
  910. // if not exactly at the key time, interpolate with previous value set
  911. if( postTime > time && pos > 0)
  912. {
  913. float preTime = ReadFloat( *e.mTimeAccessor, *e.mTimeData, pos-1, 0);
  914. float factor = (time - postTime) / (preTime - postTime);
  915. for( size_t c = 0; c < e.mValueAccessor->mSize; ++c)
  916. {
  917. float v = ReadFloat( *e.mValueAccessor, *e.mValueData, pos-1, c);
  918. temp[c] += (v - temp[c]) * factor;
  919. }
  920. }
  921. // Apply values to current transformation
  922. std::copy( temp, temp + e.mValueAccessor->mSize, transforms[e.mTransformIndex].f + e.mSubElement);
  923. }
  924. // Calculate resulting transformation
  925. aiMatrix4x4 mat = pParser.CalculateResultTransform( transforms);
  926. // out of lazyness: we store the time in matrix.d4
  927. mat.d4 = time;
  928. resultTrafos.push_back( mat);
  929. // find next point in time to evaluate. That's the closest frame larger than the current in any channel
  930. float nextTime = 1e20f;
  931. for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it)
  932. {
  933. Collada::ChannelEntry& e = *it;
  934. // find the next time value larger than the current
  935. size_t pos = 0;
  936. while( pos < e.mTimeAccessor->mCount)
  937. {
  938. float t = ReadFloat( *e.mTimeAccessor, *e.mTimeData, pos, 0);
  939. if( t > time)
  940. {
  941. nextTime = std::min( nextTime, t);
  942. break;
  943. }
  944. ++pos;
  945. }
  946. }
  947. // no more keys on any channel after the current time -> we're done
  948. if( nextTime > 1e19)
  949. break;
  950. // else construct next keyframe at this following time point
  951. time = nextTime;
  952. }
  953. }
  954. // there should be some keyframes, but we aren't that fixated on valid input data
  955. // ai_assert( resultTrafos.size() > 0);
  956. // build an animation channel for the given node out of these trafo keys
  957. if( !resultTrafos.empty() )
  958. {
  959. aiNodeAnim* dstAnim = new aiNodeAnim;
  960. dstAnim->mNodeName = nodeName;
  961. dstAnim->mNumPositionKeys = resultTrafos.size();
  962. dstAnim->mNumRotationKeys= resultTrafos.size();
  963. dstAnim->mNumScalingKeys = resultTrafos.size();
  964. dstAnim->mPositionKeys = new aiVectorKey[resultTrafos.size()];
  965. dstAnim->mRotationKeys = new aiQuatKey[resultTrafos.size()];
  966. dstAnim->mScalingKeys = new aiVectorKey[resultTrafos.size()];
  967. for( size_t a = 0; a < resultTrafos.size(); ++a)
  968. {
  969. aiMatrix4x4 mat = resultTrafos[a];
  970. double time = double( mat.d4); // remember? time is stored in mat.d4
  971. mat.d4 = 1.0f;
  972. dstAnim->mPositionKeys[a].mTime = time;
  973. dstAnim->mRotationKeys[a].mTime = time;
  974. dstAnim->mScalingKeys[a].mTime = time;
  975. mat.Decompose( dstAnim->mScalingKeys[a].mValue, dstAnim->mRotationKeys[a].mValue, dstAnim->mPositionKeys[a].mValue);
  976. }
  977. anims.push_back( dstAnim);
  978. } else
  979. {
  980. DefaultLogger::get()->warn( "Collada loader: found empty animation channel, ignored. Please check your exporter.");
  981. }
  982. }
  983. if( !anims.empty())
  984. {
  985. aiAnimation* anim = new aiAnimation;
  986. anim->mName.Set( pName);
  987. anim->mNumChannels = anims.size();
  988. anim->mChannels = new aiNodeAnim*[anims.size()];
  989. std::copy( anims.begin(), anims.end(), anim->mChannels);
  990. anim->mDuration = 0.0f;
  991. for( size_t a = 0; a < anims.size(); ++a)
  992. {
  993. anim->mDuration = std::max( anim->mDuration, anims[a]->mPositionKeys[anims[a]->mNumPositionKeys-1].mTime);
  994. anim->mDuration = std::max( anim->mDuration, anims[a]->mRotationKeys[anims[a]->mNumRotationKeys-1].mTime);
  995. anim->mDuration = std::max( anim->mDuration, anims[a]->mScalingKeys[anims[a]->mNumScalingKeys-1].mTime);
  996. }
  997. anim->mTicksPerSecond = 1;
  998. mAnims.push_back( anim);
  999. }
  1000. }
  1001. // ------------------------------------------------------------------------------------------------
  1002. // Add a texture to a material structure
  1003. void ColladaLoader::AddTexture ( aiMaterial& mat, const ColladaParser& pParser,
  1004. const Collada::Effect& effect,
  1005. const Collada::Sampler& sampler,
  1006. aiTextureType type, unsigned int idx)
  1007. {
  1008. // first of all, basic file name
  1009. const aiString name = FindFilenameForEffectTexture( pParser, effect, sampler.mName );
  1010. mat.AddProperty( &name, _AI_MATKEY_TEXTURE_BASE, type, idx );
  1011. // mapping mode
  1012. int map = aiTextureMapMode_Clamp;
  1013. if (sampler.mWrapU)
  1014. map = aiTextureMapMode_Wrap;
  1015. if (sampler.mWrapU && sampler.mMirrorU)
  1016. map = aiTextureMapMode_Mirror;
  1017. mat.AddProperty( &map, 1, _AI_MATKEY_MAPPINGMODE_U_BASE, type, idx);
  1018. map = aiTextureMapMode_Clamp;
  1019. if (sampler.mWrapV)
  1020. map = aiTextureMapMode_Wrap;
  1021. if (sampler.mWrapV && sampler.mMirrorV)
  1022. map = aiTextureMapMode_Mirror;
  1023. mat.AddProperty( &map, 1, _AI_MATKEY_MAPPINGMODE_V_BASE, type, idx);
  1024. // UV transformation
  1025. mat.AddProperty(&sampler.mTransform, 1,
  1026. _AI_MATKEY_UVTRANSFORM_BASE, type, idx);
  1027. // Blend mode
  1028. mat.AddProperty((int*)&sampler.mOp , 1,
  1029. _AI_MATKEY_TEXBLEND_BASE, type, idx);
  1030. // Blend factor
  1031. mat.AddProperty((float*)&sampler.mWeighting , 1,
  1032. _AI_MATKEY_TEXBLEND_BASE, type, idx);
  1033. // UV source index ... if we didn't resolve the mapping, it is actually just
  1034. // a guess but it works in most cases. We search for the frst occurence of a
  1035. // number in the channel name. We assume it is the zero-based index into the
  1036. // UV channel array of all corresponding meshes. It could also be one-based
  1037. // for some exporters, but we won't care of it unless someone complains about.
  1038. if (sampler.mUVId != UINT_MAX)
  1039. map = sampler.mUVId;
  1040. else {
  1041. map = -1;
  1042. for (std::string::const_iterator it = sampler.mUVChannel.begin();it != sampler.mUVChannel.end(); ++it){
  1043. if (IsNumeric(*it)) {
  1044. map = strtoul10(&(*it));
  1045. break;
  1046. }
  1047. }
  1048. if (-1 == map) {
  1049. DefaultLogger::get()->warn("Collada: unable to determine UV channel for texture");
  1050. map = 0;
  1051. }
  1052. }
  1053. mat.AddProperty(&map,1,_AI_MATKEY_UVWSRC_BASE,type,idx);
  1054. }
  1055. // ------------------------------------------------------------------------------------------------
  1056. // Fills materials from the collada material definitions
  1057. void ColladaLoader::FillMaterials( const ColladaParser& pParser, aiScene* /*pScene*/)
  1058. {
  1059. for (std::vector<std::pair<Collada::Effect*, aiMaterial*> >::iterator it = newMats.begin(),
  1060. end = newMats.end(); it != end; ++it)
  1061. {
  1062. aiMaterial& mat = (aiMaterial&)*it->second;
  1063. Collada::Effect& effect = *it->first;
  1064. // resolve shading mode
  1065. int shadeMode;
  1066. if (effect.mFaceted) /* fixme */
  1067. shadeMode = aiShadingMode_Flat;
  1068. else {
  1069. switch( effect.mShadeType)
  1070. {
  1071. case Collada::Shade_Constant:
  1072. shadeMode = aiShadingMode_NoShading;
  1073. break;
  1074. case Collada::Shade_Lambert:
  1075. shadeMode = aiShadingMode_Gouraud;
  1076. break;
  1077. case Collada::Shade_Blinn:
  1078. shadeMode = aiShadingMode_Blinn;
  1079. break;
  1080. case Collada::Shade_Phong:
  1081. shadeMode = aiShadingMode_Phong;
  1082. break;
  1083. default:
  1084. DefaultLogger::get()->warn("Collada: Unrecognized shading mode, using gouraud shading");
  1085. shadeMode = aiShadingMode_Gouraud;
  1086. break;
  1087. }
  1088. }
  1089. mat.AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  1090. // double-sided?
  1091. shadeMode = effect.mDoubleSided;
  1092. mat.AddProperty<int>( &shadeMode, 1, AI_MATKEY_TWOSIDED);
  1093. // wireframe?
  1094. shadeMode = effect.mWireframe;
  1095. mat.AddProperty<int>( &shadeMode, 1, AI_MATKEY_ENABLE_WIREFRAME);
  1096. // add material colors
  1097. mat.AddProperty( &effect.mAmbient, 1,AI_MATKEY_COLOR_AMBIENT);
  1098. mat.AddProperty( &effect.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  1099. mat.AddProperty( &effect.mSpecular, 1,AI_MATKEY_COLOR_SPECULAR);
  1100. mat.AddProperty( &effect.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  1101. mat.AddProperty( &effect.mTransparent, 1, AI_MATKEY_COLOR_TRANSPARENT);
  1102. mat.AddProperty( &effect.mReflective, 1, AI_MATKEY_COLOR_REFLECTIVE);
  1103. // scalar properties
  1104. mat.AddProperty( &effect.mShininess, 1, AI_MATKEY_SHININESS);
  1105. mat.AddProperty( &effect.mReflectivity, 1, AI_MATKEY_REFLECTIVITY);
  1106. mat.AddProperty( &effect.mRefractIndex, 1, AI_MATKEY_REFRACTI);
  1107. // transparency, a very hard one. seemingly not all files are following the
  1108. // specification here .. but we can trick.
  1109. if (effect.mTransparency >= 0.f && effect.mTransparency < 1.f) {
  1110. effect.mTransparency = 1.f- effect.mTransparency;
  1111. mat.AddProperty( &effect.mTransparency, 1, AI_MATKEY_OPACITY );
  1112. mat.AddProperty( &effect.mTransparent, 1, AI_MATKEY_COLOR_TRANSPARENT );
  1113. }
  1114. // add textures, if given
  1115. if( !effect.mTexAmbient.mName.empty())
  1116. /* It is merely a lightmap */
  1117. AddTexture( mat, pParser, effect, effect.mTexAmbient, aiTextureType_LIGHTMAP);
  1118. if( !effect.mTexEmissive.mName.empty())
  1119. AddTexture( mat, pParser, effect, effect.mTexEmissive, aiTextureType_EMISSIVE);
  1120. if( !effect.mTexSpecular.mName.empty())
  1121. AddTexture( mat, pParser, effect, effect.mTexSpecular, aiTextureType_SPECULAR);
  1122. if( !effect.mTexDiffuse.mName.empty())
  1123. AddTexture( mat, pParser, effect, effect.mTexDiffuse, aiTextureType_DIFFUSE);
  1124. if( !effect.mTexBump.mName.empty())
  1125. AddTexture( mat, pParser, effect, effect.mTexBump, aiTextureType_NORMALS);
  1126. if( !effect.mTexTransparent.mName.empty())
  1127. AddTexture( mat, pParser, effect, effect.mTexTransparent, aiTextureType_OPACITY);
  1128. if( !effect.mTexReflective.mName.empty())
  1129. AddTexture( mat, pParser, effect, effect.mTexReflective, aiTextureType_REFLECTION);
  1130. }
  1131. }
  1132. // ------------------------------------------------------------------------------------------------
  1133. // Constructs materials from the collada material definitions
  1134. void ColladaLoader::BuildMaterials( ColladaParser& pParser, aiScene* /*pScene*/)
  1135. {
  1136. newMats.reserve(pParser.mMaterialLibrary.size());
  1137. for( ColladaParser::MaterialLibrary::const_iterator matIt = pParser.mMaterialLibrary.begin(); matIt != pParser.mMaterialLibrary.end(); ++matIt)
  1138. {
  1139. const Collada::Material& material = matIt->second;
  1140. // a material is only a reference to an effect
  1141. ColladaParser::EffectLibrary::iterator effIt = pParser.mEffectLibrary.find( material.mEffect);
  1142. if( effIt == pParser.mEffectLibrary.end())
  1143. continue;
  1144. Collada::Effect& effect = effIt->second;
  1145. // create material
  1146. aiMaterial* mat = new aiMaterial;
  1147. aiString name( matIt->first);
  1148. mat->AddProperty(&name,AI_MATKEY_NAME);
  1149. // store the material
  1150. mMaterialIndexByName[matIt->first] = newMats.size();
  1151. newMats.push_back( std::pair<Collada::Effect*, aiMaterial*>( &effect,mat) );
  1152. }
  1153. // ScenePreprocessor generates a default material automatically if none is there.
  1154. // All further code here in this loader works well without a valid material so
  1155. // we can safely let it to ScenePreprocessor.
  1156. #if 0
  1157. if( newMats.size() == 0)
  1158. {
  1159. aiMaterial* mat = new aiMaterial;
  1160. aiString name( AI_DEFAULT_MATERIAL_NAME );
  1161. mat->AddProperty( &name, AI_MATKEY_NAME);
  1162. const int shadeMode = aiShadingMode_Phong;
  1163. mat->AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  1164. aiColor4D colAmbient( 0.2f, 0.2f, 0.2f, 1.0f), colDiffuse( 0.8f, 0.8f, 0.8f, 1.0f), colSpecular( 0.5f, 0.5f, 0.5f, 0.5f);
  1165. mat->AddProperty( &colAmbient, 1, AI_MATKEY_COLOR_AMBIENT);
  1166. mat->AddProperty( &colDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  1167. mat->AddProperty( &colSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
  1168. const float specExp = 5.0f;
  1169. mat->AddProperty( &specExp, 1, AI_MATKEY_SHININESS);
  1170. }
  1171. #endif
  1172. }
  1173. // ------------------------------------------------------------------------------------------------
  1174. // Resolves the texture name for the given effect texture entry
  1175. aiString ColladaLoader::FindFilenameForEffectTexture( const ColladaParser& pParser,
  1176. const Collada::Effect& pEffect, const std::string& pName)
  1177. {
  1178. // recurse through the param references until we end up at an image
  1179. std::string name = pName;
  1180. while( 1)
  1181. {
  1182. // the given string is a param entry. Find it
  1183. Collada::Effect::ParamLibrary::const_iterator it = pEffect.mParams.find( name);
  1184. // if not found, we're at the end of the recursion. The resulting string should be the image ID
  1185. if( it == pEffect.mParams.end())
  1186. break;
  1187. // else recurse on
  1188. name = it->second.mReference;
  1189. }
  1190. // find the image referred by this name in the image library of the scene
  1191. ColladaParser::ImageLibrary::const_iterator imIt = pParser.mImageLibrary.find( name);
  1192. if( imIt == pParser.mImageLibrary.end())
  1193. {
  1194. throw DeadlyImportError( boost::str( boost::format(
  1195. "Collada: Unable to resolve effect texture entry \"%s\", ended up at ID \"%s\".") % pName % name));
  1196. }
  1197. aiString result;
  1198. // if this is an embedded texture image setup an aiTexture for it
  1199. if (imIt->second.mFileName.empty())
  1200. {
  1201. if (imIt->second.mImageData.empty()) {
  1202. throw DeadlyImportError("Collada: Invalid texture, no data or file reference given");
  1203. }
  1204. aiTexture* tex = new aiTexture();
  1205. // setup format hint
  1206. if (imIt->second.mEmbeddedFormat.length() > 3) {
  1207. DefaultLogger::get()->warn("Collada: texture format hint is too long, truncating to 3 characters");
  1208. }
  1209. strncpy(tex->achFormatHint,imIt->second.mEmbeddedFormat.c_str(),3);
  1210. // and copy texture data
  1211. tex->mHeight = 0;
  1212. tex->mWidth = imIt->second.mImageData.size();
  1213. tex->pcData = (aiTexel*)new char[tex->mWidth];
  1214. memcpy(tex->pcData,&imIt->second.mImageData[0],tex->mWidth);
  1215. // setup texture reference string
  1216. result.data[0] = '*';
  1217. result.length = 1 + ASSIMP_itoa10(result.data+1,MAXLEN-1,mTextures.size());
  1218. // and add this texture to the list
  1219. mTextures.push_back(tex);
  1220. }
  1221. else
  1222. {
  1223. result.Set( imIt->second.mFileName );
  1224. ConvertPath(result);
  1225. }
  1226. return result;
  1227. }
  1228. // ------------------------------------------------------------------------------------------------
  1229. // Convert a path read from a collada file to the usual representation
  1230. void ColladaLoader::ConvertPath (aiString& ss)
  1231. {
  1232. // TODO: collada spec, p 22. Handle URI correctly.
  1233. // For the moment we're just stripping the file:// away to make it work.
  1234. // Windoes doesn't seem to be able to find stuff like
  1235. // 'file://..\LWO\LWO2\MappingModes\earthSpherical.jpg'
  1236. if (0 == strncmp(ss.data,"file://",7))
  1237. {
  1238. ss.length -= 7;
  1239. memmove(ss.data,ss.data+7,ss.length);
  1240. ss.data[ss.length] = '\0';
  1241. }
  1242. // Maxon Cinema Collada Export writes "file:///C:\andsoon" with three slashes...
  1243. // I need to filter it without destroying linux paths starting with "/somewhere"
  1244. if( ss.data[0] == '/' && isalpha( ss.data[1]) && ss.data[2] == ':' )
  1245. {
  1246. ss.length--;
  1247. memmove( ss.data, ss.data+1, ss.length);
  1248. ss.data[ss.length] = 0;
  1249. }
  1250. // find and convert all %xy special chars
  1251. char* out = ss.data;
  1252. for( const char* it = ss.data; it != ss.data + ss.length; /**/ )
  1253. {
  1254. if( *it == '%' && (it + 3) < ss.data + ss.length )
  1255. {
  1256. // separate the number to avoid dragging in chars from behind into the parsing
  1257. char mychar[3] = { it[1], it[2], 0 };
  1258. size_t nbr = strtoul16( mychar);
  1259. it += 3;
  1260. *out++ = (char)(nbr & 0xFF);
  1261. } else
  1262. {
  1263. *out++ = *it++;
  1264. }
  1265. }
  1266. // adjust length and terminator of the shortened string
  1267. *out = 0;
  1268. ss.length = (ptrdiff_t) (out - ss.data);
  1269. }
  1270. // ------------------------------------------------------------------------------------------------
  1271. // Reads a float value from an accessor and its data array.
  1272. float ColladaLoader::ReadFloat( const Collada::Accessor& pAccessor, const Collada::Data& pData, size_t pIndex, size_t pOffset) const
  1273. {
  1274. // FIXME: (thom) Test for data type here in every access? For the moment, I leave this to the caller
  1275. size_t pos = pAccessor.mStride * pIndex + pAccessor.mOffset + pOffset;
  1276. ai_assert( pos < pData.mValues.size());
  1277. return pData.mValues[pos];
  1278. }
  1279. // ------------------------------------------------------------------------------------------------
  1280. // Reads a string value from an accessor and its data array.
  1281. const std::string& ColladaLoader::ReadString( const Collada::Accessor& pAccessor, const Collada::Data& pData, size_t pIndex) const
  1282. {
  1283. size_t pos = pAccessor.mStride * pIndex + pAccessor.mOffset;
  1284. ai_assert( pos < pData.mStrings.size());
  1285. return pData.mStrings[pos];
  1286. }
  1287. // ------------------------------------------------------------------------------------------------
  1288. // Collects all nodes into the given array
  1289. void ColladaLoader::CollectNodes( const aiNode* pNode, std::vector<const aiNode*>& poNodes) const
  1290. {
  1291. poNodes.push_back( pNode);
  1292. for( size_t a = 0; a < pNode->mNumChildren; ++a)
  1293. CollectNodes( pNode->mChildren[a], poNodes);
  1294. }
  1295. // ------------------------------------------------------------------------------------------------
  1296. // Finds a node in the collada scene by the given name
  1297. const Collada::Node* ColladaLoader::FindNode( const Collada::Node* pNode, const std::string& pName) const
  1298. {
  1299. if( pNode->mName == pName || pNode->mID == pName)
  1300. return pNode;
  1301. for( size_t a = 0; a < pNode->mChildren.size(); ++a)
  1302. {
  1303. const Collada::Node* node = FindNode( pNode->mChildren[a], pName);
  1304. if( node)
  1305. return node;
  1306. }
  1307. return NULL;
  1308. }
  1309. // ------------------------------------------------------------------------------------------------
  1310. // Finds a node in the collada scene by the given SID
  1311. const Collada::Node* ColladaLoader::FindNodeBySID( const Collada::Node* pNode, const std::string& pSID) const
  1312. {
  1313. if( pNode->mSID == pSID)
  1314. return pNode;
  1315. for( size_t a = 0; a < pNode->mChildren.size(); ++a)
  1316. {
  1317. const Collada::Node* node = FindNodeBySID( pNode->mChildren[a], pSID);
  1318. if( node)
  1319. return node;
  1320. }
  1321. return NULL;
  1322. }
  1323. // ------------------------------------------------------------------------------------------------
  1324. // Finds a proper name for a node derived from the collada-node's properties
  1325. std::string ColladaLoader::FindNameForNode( const Collada::Node* pNode) const
  1326. {
  1327. // now setup the name of the node. We take the name if not empty, otherwise the collada ID
  1328. // FIX: Workaround for XSI calling the instanced visual scene 'untitled' by default.
  1329. if (!pNode->mName.empty() && pNode->mName != "untitled")
  1330. return pNode->mName;
  1331. else if (!pNode->mID.empty())
  1332. return pNode->mID;
  1333. else if (!pNode->mSID.empty())
  1334. return pNode->mSID;
  1335. else
  1336. {
  1337. // No need to worry. Unnamed nodes are no problem at all, except
  1338. // if cameras or lights need to be assigned to them.
  1339. return boost::str( boost::format( "$ColladaAutoName$_%d") % clock());
  1340. }
  1341. }
  1342. #endif // !! ASSIMP_BUILD_NO_DAE_IMPORTER