ColladaLoader.cpp 53 KB

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