ColladaLoader.cpp 62 KB

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