ColladaLoader.cpp 60 KB

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