ColladaLoader.cpp 60 KB

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