ColladaLoader.cpp 84 KB

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