ColladaLoader.cpp 71 KB

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