ColladaLoader.cpp 83 KB

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