ColladaLoader.cpp 81 KB

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