ColladaLoader.cpp 83 KB

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