ColladaLoader.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. /** Implementation of the Collada 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 "ColladaLoader.h"
  38. #include "ColladaParser.h"
  39. using namespace Assimp;
  40. // ------------------------------------------------------------------------------------------------
  41. // Constructor to be privately used by Importer
  42. ColladaLoader::ColladaLoader()
  43. {
  44. }
  45. // ------------------------------------------------------------------------------------------------
  46. // Destructor, private as well
  47. ColladaLoader::~ColladaLoader()
  48. {
  49. }
  50. // ------------------------------------------------------------------------------------------------
  51. // Returns whether the class can handle the format of the given file.
  52. bool ColladaLoader::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  53. {
  54. // check file extension
  55. std::string::size_type pos = pFile.find_last_of('.');
  56. // no file extension - can't read
  57. if( pos == std::string::npos)
  58. return false;
  59. std::string extension = pFile.substr( pos);
  60. for( std::string::iterator it = extension.begin(); it != extension.end(); ++it)
  61. *it = tolower( *it);
  62. if( extension == ".dae")
  63. return true;
  64. return false;
  65. }
  66. // ------------------------------------------------------------------------------------------------
  67. // Imports the given file into the given scene structure.
  68. void ColladaLoader::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  69. {
  70. mFileName = pFile;
  71. // parse the input file
  72. ColladaParser parser( pFile);
  73. if( !parser.mRootNode)
  74. throw new ImportErrorException( "File came out empty. Somethings wrong here.");
  75. // create the materials first, for the meshes to find
  76. BuildMaterials( parser, pScene);
  77. // build the node hierarchy from it
  78. pScene->mRootNode = BuildHierarchy( parser, parser.mRootNode);
  79. // Convert to Z_UP, if different orientation
  80. if( parser.mUpDirection == ColladaParser::UP_X)
  81. pScene->mRootNode->mTransformation *= aiMatrix4x4(
  82. 0, -1, 0, 0,
  83. 0, 0, -1, 0,
  84. 1, 0, 0, 0,
  85. 0, 0, 0, 1);
  86. else if( parser.mUpDirection == ColladaParser::UP_Y)
  87. pScene->mRootNode->mTransformation *= aiMatrix4x4(
  88. 1, 0, 0, 0,
  89. 0, 0, -1, 0,
  90. 0, 1, 0, 0,
  91. 0, 0, 0, 1);
  92. // store all meshes
  93. StoreSceneMeshes( pScene);
  94. }
  95. // ------------------------------------------------------------------------------------------------
  96. // Recursively constructs a scene node for the given parser node and returns it.
  97. aiNode* ColladaLoader::BuildHierarchy( const ColladaParser& pParser, const Collada::Node* pNode)
  98. {
  99. // create a node for it
  100. aiNode* node = new aiNode( pNode->mName);
  101. // calculate the transformation matrix for it
  102. node->mTransformation = pParser.CalculateResultTransform( pNode->mTransforms);
  103. // add children
  104. node->mNumChildren = pNode->mChildren.size();
  105. node->mChildren = new aiNode*[node->mNumChildren];
  106. for( unsigned int a = 0; a < pNode->mChildren.size(); a++)
  107. {
  108. node->mChildren[a] = BuildHierarchy( pParser, pNode->mChildren[a]);
  109. node->mChildren[a]->mParent = node;
  110. }
  111. // construct meshes
  112. BuildMeshesForNode( pParser, pNode, node);
  113. return node;
  114. }
  115. // ------------------------------------------------------------------------------------------------
  116. // Builds meshes for the given node and references them
  117. void ColladaLoader::BuildMeshesForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget)
  118. {
  119. // accumulated mesh references by this node
  120. std::vector<size_t> newMeshRefs;
  121. // for the moment we simply ignore all material tags and transfer the meshes one by one
  122. BOOST_FOREACH( const Collada::MeshInstance& mid, pNode->mMeshes)
  123. {
  124. // find the referred mesh
  125. ColladaParser::MeshLibrary::const_iterator srcMeshIt = pParser.mMeshLibrary.find( mid.mMesh);
  126. if( srcMeshIt == pParser.mMeshLibrary.end())
  127. {
  128. DefaultLogger::get()->warn( boost::str( boost::format( "Unable to find geometry for ID \"%s\". Skipping.") % mid.mMesh));
  129. continue;
  130. }
  131. const Collada::Mesh* srcMesh = srcMeshIt->second;
  132. // build a mesh for each of its subgroups
  133. size_t vertexStart = 0, faceStart = 0;
  134. for( size_t sm = 0; sm < srcMesh->mSubMeshes.size(); ++sm)
  135. {
  136. const Collada::SubMesh& submesh = srcMesh->mSubMeshes[sm];
  137. // find material assigned to this submesh
  138. std::map<std::string, std::string>::const_iterator meshMatIt = mid.mMaterials.find( submesh.mMaterial);
  139. std::string meshMaterial;
  140. if( meshMatIt != mid.mMaterials.end())
  141. meshMaterial = meshMatIt->second;
  142. else
  143. DefaultLogger::get()->warn( boost::str( boost::format( "No material specified for subgroup \"%s\" in geometry \"%s\".") % submesh.mMaterial % mid.mMesh));
  144. // built lookup index of the Mesh-Submesh-Material combination
  145. ColladaMeshIndex index( mid.mMesh, sm, meshMaterial);
  146. // if we already have the mesh at the library, just add its index to the node's array
  147. std::map<ColladaMeshIndex, size_t>::const_iterator dstMeshIt = mMeshIndexByID.find( index);
  148. if( dstMeshIt != mMeshIndexByID.end())
  149. {
  150. newMeshRefs.push_back( dstMeshIt->second);
  151. } else
  152. {
  153. // else we have to add the mesh to the collection and store its newly assigned index at the node
  154. aiMesh* dstMesh = new aiMesh;
  155. // count the vertices addressed by its faces
  156. size_t numVertices =
  157. std::accumulate( srcMesh->mFaceSize.begin() + faceStart, srcMesh->mFaceSize.begin() + faceStart + submesh.mNumFaces, 0);
  158. // copy positions
  159. dstMesh->mNumVertices = numVertices;
  160. dstMesh->mVertices = new aiVector3D[numVertices];
  161. std::copy( srcMesh->mPositions.begin() + vertexStart, srcMesh->mPositions.begin() + vertexStart + numVertices, dstMesh->mVertices);
  162. // normals, if given. HACK: (thom) Due to the fucking Collada spec we never know if we have the same
  163. // number of normals as there are positions. So we also ignore any vertex attribute if it has a different count
  164. if( srcMesh->mNormals.size() == srcMesh->mPositions.size())
  165. {
  166. dstMesh->mNormals = new aiVector3D[numVertices];
  167. std::copy( srcMesh->mNormals.begin() + vertexStart, srcMesh->mNormals.begin() + vertexStart + numVertices, dstMesh->mNormals);
  168. }
  169. // same for texturecoords, as many as we have
  170. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; a++)
  171. {
  172. if( srcMesh->mTexCoords[a].size() == srcMesh->mPositions.size())
  173. {
  174. dstMesh->mTextureCoords[a] = new aiVector3D[numVertices];
  175. for( size_t b = vertexStart; b < vertexStart + numVertices; ++b)
  176. dstMesh->mTextureCoords[a][b].Set( srcMesh->mTexCoords[a][b].x, srcMesh->mTexCoords[a][b].y, 0.0f);
  177. dstMesh->mNumUVComponents[a] = 2;
  178. }
  179. }
  180. // same for vertex colors, as many as we have
  181. for( size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; a++)
  182. {
  183. if( srcMesh->mColors[a].size() == srcMesh->mPositions.size())
  184. {
  185. dstMesh->mColors[a] = new aiColor4D[numVertices];
  186. std::copy( srcMesh->mColors[a].begin() + vertexStart, srcMesh->mColors[a].begin() + vertexStart + numVertices, dstMesh->mColors[a]);
  187. }
  188. }
  189. // create faces. Due to the fact that each face uses unique vertices, we can simply count up on each vertex
  190. size_t vertex = 0;
  191. dstMesh->mNumFaces = submesh.mNumFaces;
  192. dstMesh->mFaces = new aiFace[dstMesh->mNumFaces];
  193. for( size_t a = 0; a < dstMesh->mNumFaces; ++a)
  194. {
  195. size_t s = srcMesh->mFaceSize[ faceStart + a];
  196. aiFace& face = dstMesh->mFaces[a];
  197. face.mNumIndices = s;
  198. face.mIndices = new unsigned int[s];
  199. for( size_t b = 0; b < s; ++b)
  200. face.mIndices[b] = vertex++;
  201. }
  202. // store the mesh, and store its new index in the node
  203. newMeshRefs.push_back( mMeshes.size());
  204. mMeshIndexByID[index] = mMeshes.size();
  205. mMeshes.push_back( dstMesh);
  206. vertexStart += numVertices; faceStart += submesh.mNumFaces;
  207. // assign the material index
  208. std::map<std::string, size_t>::const_iterator matIt = mMaterialIndexByName.find( meshMaterial);
  209. if( matIt != mMaterialIndexByName.end())
  210. dstMesh->mMaterialIndex = matIt->second;
  211. else
  212. dstMesh->mMaterialIndex = 0;
  213. }
  214. }
  215. }
  216. // now place all mesh references we gathered in the target node
  217. pTarget->mNumMeshes = newMeshRefs.size();
  218. if( newMeshRefs.size())
  219. {
  220. pTarget->mMeshes = new unsigned int[pTarget->mNumMeshes];
  221. std::copy( newMeshRefs.begin(), newMeshRefs.end(), pTarget->mMeshes);
  222. }
  223. }
  224. // ------------------------------------------------------------------------------------------------
  225. // Stores all meshes in the given scene
  226. void ColladaLoader::StoreSceneMeshes( aiScene* pScene)
  227. {
  228. pScene->mNumMeshes = mMeshes.size();
  229. if( mMeshes.size() > 0)
  230. {
  231. pScene->mMeshes = new aiMesh*[mMeshes.size()];
  232. std::copy( mMeshes.begin(), mMeshes.end(), pScene->mMeshes);
  233. }
  234. }
  235. // ------------------------------------------------------------------------------------------------
  236. // Constructs materials from the collada material definitions
  237. void ColladaLoader::BuildMaterials( const ColladaParser& pParser, aiScene* pScene)
  238. {
  239. std::vector<aiMaterial*> newMats;
  240. for( ColladaParser::MaterialLibrary::const_iterator matIt = pParser.mMaterialLibrary.begin(); matIt != pParser.mMaterialLibrary.end(); ++matIt)
  241. {
  242. const Collada::Material& material = matIt->second;
  243. // a material is only a reference to an effect
  244. ColladaParser::EffectLibrary::const_iterator effIt = pParser.mEffectLibrary.find( material.mEffect);
  245. if( effIt == pParser.mEffectLibrary.end())
  246. continue;
  247. const Collada::Effect& effect = effIt->second;
  248. // create material
  249. Assimp::MaterialHelper* mat = new Assimp::MaterialHelper;
  250. aiString name( matIt->first);
  251. mat->AddProperty( &name, AI_MATKEY_NAME);
  252. int shadeMode;
  253. switch( effect.mShadeType)
  254. {
  255. case Collada::Shade_Constant: shadeMode = aiShadingMode_NoShading; break;
  256. case Collada::Shade_Lambert: shadeMode = aiShadingMode_Gouraud; break;
  257. case Collada::Shade_Blinn: shadeMode = aiShadingMode_Blinn; break;
  258. default: shadeMode = aiShadingMode_Phong; break;
  259. }
  260. mat->AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  261. mat->AddProperty( &effect.mAmbient, 1, AI_MATKEY_COLOR_AMBIENT);
  262. mat->AddProperty( &effect.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  263. mat->AddProperty( &effect.mSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
  264. mat->AddProperty( &effect.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  265. mat->AddProperty( &effect.mShininess, 1, AI_MATKEY_SHININESS);
  266. mat->AddProperty( &effect.mRefractIndex, 1, AI_MATKEY_REFRACTI);
  267. // add textures, if given
  268. if( !effect.mTexAmbient.empty())
  269. mat->AddProperty( &FindFilenameForEffectTexture( pParser, effect, effect.mTexAmbient), AI_MATKEY_TEXTURE_AMBIENT( 0));
  270. if( !effect.mTexDiffuse.empty())
  271. mat->AddProperty( &FindFilenameForEffectTexture( pParser, effect, effect.mTexDiffuse), AI_MATKEY_TEXTURE_DIFFUSE( 0));
  272. if( !effect.mTexEmissive.empty())
  273. mat->AddProperty( &FindFilenameForEffectTexture( pParser, effect, effect.mTexEmissive), AI_MATKEY_TEXTURE_EMISSIVE( 0));
  274. if( !effect.mTexSpecular.empty())
  275. mat->AddProperty( &FindFilenameForEffectTexture( pParser, effect, effect.mTexSpecular), AI_MATKEY_TEXTURE_SPECULAR( 0));
  276. // store the material
  277. mMaterialIndexByName[matIt->first] = newMats.size();
  278. newMats.push_back( mat);
  279. }
  280. // store a dummy material if none were given
  281. if( newMats.size() == 0)
  282. {
  283. Assimp::MaterialHelper* mat = new Assimp::MaterialHelper;
  284. aiString name( std::string( "dummy"));
  285. mat->AddProperty( &name, AI_MATKEY_NAME);
  286. int shadeMode = aiShadingMode_Phong;
  287. mat->AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  288. 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);
  289. mat->AddProperty( &colAmbient, 1, AI_MATKEY_COLOR_AMBIENT);
  290. mat->AddProperty( &colDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  291. mat->AddProperty( &colSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
  292. float specExp = 5.0f;
  293. mat->AddProperty( &specExp, 1, AI_MATKEY_SHININESS);
  294. }
  295. // store the materials in the scene
  296. pScene->mNumMaterials = newMats.size();
  297. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
  298. std::copy( newMats.begin(), newMats.end(), pScene->mMaterials);
  299. }
  300. // ------------------------------------------------------------------------------------------------
  301. // Resolves the texture name for the given effect texture entry
  302. const aiString& ColladaLoader::FindFilenameForEffectTexture( const ColladaParser& pParser, const Collada::Effect& pEffect, const std::string& pName)
  303. {
  304. // recurse through the param references until we end up at an image
  305. std::string name = pName;
  306. while( 1)
  307. {
  308. // the given string is a param entry. Find it
  309. Collada::Effect::ParamLibrary::const_iterator it = pEffect.mParams.find( name);
  310. // if not found, we're at the end of the recursion. The resulting string should be the image ID
  311. if( it == pEffect.mParams.end())
  312. break;
  313. // else recurse on
  314. name = it->second.mReference;
  315. }
  316. // find the image referred by this name in the image library of the scene
  317. ColladaParser::ImageLibrary::const_iterator imIt = pParser.mImageLibrary.find( name);
  318. if( imIt == pParser.mImageLibrary.end())
  319. throw new ImportErrorException( boost::str( boost::format( "Unable to resolve effect texture entry \"%s\", ended up at ID \"%s\".") % pName % name));
  320. static aiString result;
  321. result.Set( imIt->second.mFileName);
  322. return result;
  323. }