2
0

ColladaLoader.cpp 81 KB

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