ColladaLoader.cpp 71 KB

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