ASELoader.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2021, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file ASELoader.cpp
  35. * @brief Implementation of the ASE importer class
  36. */
  37. #ifndef ASSIMP_BUILD_NO_ASE_IMPORTER
  38. #ifndef ASSIMP_BUILD_NO_3DS_IMPORTER
  39. // internal headers
  40. #include "ASELoader.h"
  41. #include "Common/TargetAnimation.h"
  42. #include <assimp/SkeletonMeshBuilder.h>
  43. #include <assimp/StringComparison.h>
  44. #include <assimp/importerdesc.h>
  45. #include <assimp/scene.h>
  46. #include <assimp/DefaultLogger.hpp>
  47. #include <assimp/IOSystem.hpp>
  48. #include <assimp/Importer.hpp>
  49. #include <memory>
  50. // utilities
  51. #include <assimp/fast_atof.h>
  52. using namespace Assimp;
  53. using namespace Assimp::ASE;
  54. static const aiImporterDesc desc = {
  55. "ASE Importer",
  56. "",
  57. "",
  58. "Similar to 3DS but text-encoded",
  59. aiImporterFlags_SupportTextFlavour,
  60. 0,
  61. 0,
  62. 0,
  63. 0,
  64. "ase ask"
  65. };
  66. // ------------------------------------------------------------------------------------------------
  67. // Constructor to be privately used by Importer
  68. ASEImporter::ASEImporter() :
  69. mParser(), mBuffer(), pcScene(), configRecomputeNormals(), noSkeletonMesh() {
  70. // empty
  71. }
  72. // ------------------------------------------------------------------------------------------------
  73. // Destructor, private as well
  74. ASEImporter::~ASEImporter() {
  75. // empty
  76. }
  77. // ------------------------------------------------------------------------------------------------
  78. // Returns whether the class can handle the format of the given file.
  79. bool ASEImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool cs) const {
  80. // check file extension
  81. const std::string extension = GetExtension(pFile);
  82. if (extension == "ase" || extension == "ask") {
  83. return true;
  84. }
  85. if ((!extension.length() || cs) && pIOHandler) {
  86. static const char * const tokens[] = { "*3dsmax_asciiexport" };
  87. return SearchFileHeaderForToken(pIOHandler, pFile, tokens, 1);
  88. }
  89. return false;
  90. }
  91. // ------------------------------------------------------------------------------------------------
  92. // Loader meta information
  93. const aiImporterDesc *ASEImporter::GetInfo() const {
  94. return &desc;
  95. }
  96. // ------------------------------------------------------------------------------------------------
  97. // Setup configuration options
  98. void ASEImporter::SetupProperties(const Importer *pImp) {
  99. configRecomputeNormals = (pImp->GetPropertyInteger(
  100. AI_CONFIG_IMPORT_ASE_RECONSTRUCT_NORMALS, 1) ?
  101. true :
  102. false);
  103. noSkeletonMesh = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, 0) != 0;
  104. }
  105. // ------------------------------------------------------------------------------------------------
  106. // Imports the given file into the given scene structure.
  107. void ASEImporter::InternReadFile(const std::string &pFile,
  108. aiScene *pScene, IOSystem *pIOHandler) {
  109. std::unique_ptr<IOStream> file(pIOHandler->Open(pFile, "rb"));
  110. // Check whether we can read from the file
  111. if (file.get() == nullptr) {
  112. throw DeadlyImportError("Failed to open ASE file ", pFile, ".");
  113. }
  114. // Allocate storage and copy the contents of the file to a memory buffer
  115. std::vector<char> mBuffer2;
  116. TextFileToBuffer(file.get(), mBuffer2);
  117. this->mBuffer = &mBuffer2[0];
  118. this->pcScene = pScene;
  119. // ------------------------------------------------------------------
  120. // Guess the file format by looking at the extension
  121. // ASC is considered to be the older format 110,
  122. // ASE is the actual version 200 (that is currently written by max)
  123. // ------------------------------------------------------------------
  124. unsigned int defaultFormat;
  125. std::string::size_type s = pFile.length() - 1;
  126. switch (pFile.c_str()[s]) {
  127. case 'C':
  128. case 'c':
  129. defaultFormat = AI_ASE_OLD_FILE_FORMAT;
  130. break;
  131. default:
  132. defaultFormat = AI_ASE_NEW_FILE_FORMAT;
  133. };
  134. // Construct an ASE parser and parse the file
  135. ASE::Parser parser(mBuffer, defaultFormat);
  136. mParser = &parser;
  137. mParser->Parse();
  138. //------------------------------------------------------------------
  139. // Check whether we god at least one mesh. If we did - generate
  140. // materials and copy meshes.
  141. // ------------------------------------------------------------------
  142. if (!mParser->m_vMeshes.empty()) {
  143. // If absolutely no material has been loaded from the file
  144. // we need to generate a default material
  145. GenerateDefaultMaterial();
  146. // process all meshes
  147. bool tookNormals = false;
  148. std::vector<aiMesh *> avOutMeshes;
  149. avOutMeshes.reserve(mParser->m_vMeshes.size() * 2);
  150. for (std::vector<ASE::Mesh>::iterator i = mParser->m_vMeshes.begin(); i != mParser->m_vMeshes.end(); ++i) {
  151. if ((*i).bSkip) {
  152. continue;
  153. }
  154. BuildUniqueRepresentation(*i);
  155. // Need to generate proper vertex normals if necessary
  156. if (GenerateNormals(*i)) {
  157. tookNormals = true;
  158. }
  159. // Convert all meshes to aiMesh objects
  160. ConvertMeshes(*i, avOutMeshes);
  161. }
  162. if (tookNormals) {
  163. ASSIMP_LOG_DEBUG("ASE: Taking normals from the file. Use "
  164. "the AI_CONFIG_IMPORT_ASE_RECONSTRUCT_NORMALS setting if you "
  165. "experience problems");
  166. }
  167. // Now build the output mesh list. Remove dummies
  168. pScene->mNumMeshes = (unsigned int)avOutMeshes.size();
  169. aiMesh **pp = pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
  170. for (std::vector<aiMesh *>::const_iterator i = avOutMeshes.begin(); i != avOutMeshes.end(); ++i) {
  171. if (!(*i)->mNumFaces) {
  172. continue;
  173. }
  174. *pp++ = *i;
  175. }
  176. pScene->mNumMeshes = (unsigned int)(pp - pScene->mMeshes);
  177. // Build final material indices (remove submaterials and setup
  178. // the final list)
  179. BuildMaterialIndices();
  180. }
  181. // ------------------------------------------------------------------
  182. // Copy all scene graph nodes - lights, cameras, dummies and meshes
  183. // into one huge list.
  184. //------------------------------------------------------------------
  185. std::vector<BaseNode *> nodes;
  186. nodes.reserve(mParser->m_vMeshes.size() + mParser->m_vLights.size() + mParser->m_vCameras.size() + mParser->m_vDummies.size());
  187. // Lights
  188. for (auto &light : mParser->m_vLights)
  189. nodes.push_back(&light);
  190. // Cameras
  191. for (auto &camera : mParser->m_vCameras)
  192. nodes.push_back(&camera);
  193. // Meshes
  194. for (auto &mesh : mParser->m_vMeshes)
  195. nodes.push_back(&mesh);
  196. // Dummies
  197. for (auto &dummy : mParser->m_vDummies)
  198. nodes.push_back(&dummy);
  199. // build the final node graph
  200. BuildNodes(nodes);
  201. // build output animations
  202. BuildAnimations(nodes);
  203. // build output cameras
  204. BuildCameras();
  205. // build output lights
  206. BuildLights();
  207. // ------------------------------------------------------------------
  208. // If we have no meshes use the SkeletonMeshBuilder helper class
  209. // to build a mesh for the animation skeleton
  210. // FIXME: very strange results
  211. // ------------------------------------------------------------------
  212. if (!pScene->mNumMeshes) {
  213. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  214. if (!noSkeletonMesh) {
  215. SkeletonMeshBuilder skeleton(pScene);
  216. }
  217. }
  218. }
  219. // ------------------------------------------------------------------------------------------------
  220. void ASEImporter::GenerateDefaultMaterial() {
  221. ai_assert(nullptr != mParser);
  222. bool bHas = false;
  223. for (std::vector<ASE::Mesh>::iterator i = mParser->m_vMeshes.begin(); i != mParser->m_vMeshes.end(); ++i) {
  224. if ((*i).bSkip) continue;
  225. if (ASE::Face::DEFAULT_MATINDEX == (*i).iMaterialIndex) {
  226. (*i).iMaterialIndex = (unsigned int)mParser->m_vMaterials.size();
  227. bHas = true;
  228. }
  229. }
  230. if (bHas || mParser->m_vMaterials.empty()) {
  231. // add a simple material without submaterials to the parser's list
  232. mParser->m_vMaterials.push_back(ASE::Material(AI_DEFAULT_MATERIAL_NAME));
  233. ASE::Material &mat = mParser->m_vMaterials.back();
  234. mat.mDiffuse = aiColor3D(0.6f, 0.6f, 0.6f);
  235. mat.mSpecular = aiColor3D(1.0f, 1.0f, 1.0f);
  236. mat.mAmbient = aiColor3D(0.05f, 0.05f, 0.05f);
  237. mat.mShading = Discreet3DS::Gouraud;
  238. }
  239. }
  240. // ------------------------------------------------------------------------------------------------
  241. void ASEImporter::BuildAnimations(const std::vector<BaseNode *> &nodes) {
  242. // check whether we have at least one mesh which has animations
  243. std::vector<ASE::BaseNode *>::const_iterator i = nodes.begin();
  244. unsigned int iNum = 0;
  245. for (; i != nodes.end(); ++i) {
  246. // TODO: Implement Bezier & TCB support
  247. if ((*i)->mAnim.mPositionType != ASE::Animation::TRACK) {
  248. ASSIMP_LOG_WARN("ASE: Position controller uses Bezier/TCB keys. "
  249. "This is not supported.");
  250. }
  251. if ((*i)->mAnim.mRotationType != ASE::Animation::TRACK) {
  252. ASSIMP_LOG_WARN("ASE: Rotation controller uses Bezier/TCB keys. "
  253. "This is not supported.");
  254. }
  255. if ((*i)->mAnim.mScalingType != ASE::Animation::TRACK) {
  256. ASSIMP_LOG_WARN("ASE: Position controller uses Bezier/TCB keys. "
  257. "This is not supported.");
  258. }
  259. // We compare against 1 here - firstly one key is not
  260. // really an animation and secondly MAX writes dummies
  261. // that represent the node transformation.
  262. if ((*i)->mAnim.akeyPositions.size() > 1 || (*i)->mAnim.akeyRotations.size() > 1 || (*i)->mAnim.akeyScaling.size() > 1) {
  263. ++iNum;
  264. }
  265. if ((*i)->mTargetAnim.akeyPositions.size() > 1 && is_not_qnan((*i)->mTargetPosition.x)) {
  266. ++iNum;
  267. }
  268. }
  269. if (iNum) {
  270. // Generate a new animation channel and setup everything for it
  271. pcScene->mNumAnimations = 1;
  272. pcScene->mAnimations = new aiAnimation *[1];
  273. aiAnimation *pcAnim = pcScene->mAnimations[0] = new aiAnimation();
  274. pcAnim->mNumChannels = iNum;
  275. pcAnim->mChannels = new aiNodeAnim *[iNum];
  276. pcAnim->mTicksPerSecond = mParser->iFrameSpeed * mParser->iTicksPerFrame;
  277. iNum = 0;
  278. // Now iterate through all meshes and collect all data we can find
  279. for (i = nodes.begin(); i != nodes.end(); ++i) {
  280. ASE::BaseNode *me = *i;
  281. if (me->mTargetAnim.akeyPositions.size() > 1 && is_not_qnan(me->mTargetPosition.x)) {
  282. // Generate an extra channel for the camera/light target.
  283. // BuildNodes() does also generate an extra node, named
  284. // <baseName>.Target.
  285. aiNodeAnim *nd = pcAnim->mChannels[iNum++] = new aiNodeAnim();
  286. nd->mNodeName.Set(me->mName + ".Target");
  287. // If there is no input position channel we will need
  288. // to supply the default position from the node's
  289. // local transformation matrix.
  290. /*TargetAnimationHelper helper;
  291. if (me->mAnim.akeyPositions.empty())
  292. {
  293. aiMatrix4x4& mat = (*i)->mTransform;
  294. helper.SetFixedMainAnimationChannel(aiVector3D(
  295. mat.a4, mat.b4, mat.c4));
  296. }
  297. else helper.SetMainAnimationChannel (&me->mAnim.akeyPositions);
  298. helper.SetTargetAnimationChannel (&me->mTargetAnim.akeyPositions);
  299. helper.Process(&me->mTargetAnim.akeyPositions);*/
  300. // Allocate the key array and fill it
  301. nd->mNumPositionKeys = (unsigned int)me->mTargetAnim.akeyPositions.size();
  302. nd->mPositionKeys = new aiVectorKey[nd->mNumPositionKeys];
  303. ::memcpy(nd->mPositionKeys, &me->mTargetAnim.akeyPositions[0],
  304. nd->mNumPositionKeys * sizeof(aiVectorKey));
  305. }
  306. if (me->mAnim.akeyPositions.size() > 1 || me->mAnim.akeyRotations.size() > 1 || me->mAnim.akeyScaling.size() > 1) {
  307. // Begin a new node animation channel for this node
  308. aiNodeAnim *nd = pcAnim->mChannels[iNum++] = new aiNodeAnim();
  309. nd->mNodeName.Set(me->mName);
  310. // copy position keys
  311. if (me->mAnim.akeyPositions.size() > 1) {
  312. // Allocate the key array and fill it
  313. nd->mNumPositionKeys = (unsigned int)me->mAnim.akeyPositions.size();
  314. nd->mPositionKeys = new aiVectorKey[nd->mNumPositionKeys];
  315. ::memcpy(nd->mPositionKeys, &me->mAnim.akeyPositions[0],
  316. nd->mNumPositionKeys * sizeof(aiVectorKey));
  317. }
  318. // copy rotation keys
  319. if (me->mAnim.akeyRotations.size() > 1) {
  320. // Allocate the key array and fill it
  321. nd->mNumRotationKeys = (unsigned int)me->mAnim.akeyRotations.size();
  322. nd->mRotationKeys = new aiQuatKey[nd->mNumRotationKeys];
  323. // --------------------------------------------------------------------
  324. // Rotation keys are offsets to the previous keys.
  325. // We have the quaternion representations of all
  326. // of them, so we just need to concatenate all
  327. // (unit-length) quaternions to get the absolute
  328. // rotations.
  329. // Rotation keys are ABSOLUTE for older files
  330. // --------------------------------------------------------------------
  331. aiQuaternion cur;
  332. for (unsigned int a = 0; a < nd->mNumRotationKeys; ++a) {
  333. aiQuatKey q = me->mAnim.akeyRotations[a];
  334. if (mParser->iFileFormat > 110) {
  335. cur = (a ? cur * q.mValue : q.mValue);
  336. q.mValue = cur.Normalize();
  337. }
  338. nd->mRotationKeys[a] = q;
  339. // need this to get to Assimp quaternion conventions
  340. nd->mRotationKeys[a].mValue.w *= -1.f;
  341. }
  342. }
  343. // copy scaling keys
  344. if (me->mAnim.akeyScaling.size() > 1) {
  345. // Allocate the key array and fill it
  346. nd->mNumScalingKeys = (unsigned int)me->mAnim.akeyScaling.size();
  347. nd->mScalingKeys = new aiVectorKey[nd->mNumScalingKeys];
  348. ::memcpy(nd->mScalingKeys, &me->mAnim.akeyScaling[0],
  349. nd->mNumScalingKeys * sizeof(aiVectorKey));
  350. }
  351. }
  352. }
  353. }
  354. }
  355. // ------------------------------------------------------------------------------------------------
  356. // Build output cameras
  357. void ASEImporter::BuildCameras() {
  358. if (!mParser->m_vCameras.empty()) {
  359. pcScene->mNumCameras = (unsigned int)mParser->m_vCameras.size();
  360. pcScene->mCameras = new aiCamera *[pcScene->mNumCameras];
  361. for (unsigned int i = 0; i < pcScene->mNumCameras; ++i) {
  362. aiCamera *out = pcScene->mCameras[i] = new aiCamera();
  363. ASE::Camera &in = mParser->m_vCameras[i];
  364. // copy members
  365. out->mClipPlaneFar = in.mFar;
  366. out->mClipPlaneNear = (in.mNear ? in.mNear : 0.1f);
  367. out->mHorizontalFOV = in.mFOV;
  368. out->mName.Set(in.mName);
  369. }
  370. }
  371. }
  372. // ------------------------------------------------------------------------------------------------
  373. // Build output lights
  374. void ASEImporter::BuildLights() {
  375. if (!mParser->m_vLights.empty()) {
  376. pcScene->mNumLights = (unsigned int)mParser->m_vLights.size();
  377. pcScene->mLights = new aiLight *[pcScene->mNumLights];
  378. for (unsigned int i = 0; i < pcScene->mNumLights; ++i) {
  379. aiLight *out = pcScene->mLights[i] = new aiLight();
  380. ASE::Light &in = mParser->m_vLights[i];
  381. // The direction is encoded in the transformation matrix of the node.
  382. // In 3DS MAX the light source points into negative Z direction if
  383. // the node transformation is the identity.
  384. out->mDirection = aiVector3D(0.f, 0.f, -1.f);
  385. out->mName.Set(in.mName);
  386. switch (in.mLightType) {
  387. case ASE::Light::TARGET:
  388. out->mType = aiLightSource_SPOT;
  389. out->mAngleInnerCone = AI_DEG_TO_RAD(in.mAngle);
  390. out->mAngleOuterCone = (in.mFalloff ? AI_DEG_TO_RAD(in.mFalloff) : out->mAngleInnerCone);
  391. break;
  392. case ASE::Light::DIRECTIONAL:
  393. out->mType = aiLightSource_DIRECTIONAL;
  394. break;
  395. default:
  396. //case ASE::Light::OMNI:
  397. out->mType = aiLightSource_POINT;
  398. break;
  399. };
  400. out->mColorDiffuse = out->mColorSpecular = in.mColor * in.mIntensity;
  401. }
  402. }
  403. }
  404. // ------------------------------------------------------------------------------------------------
  405. void ASEImporter::AddNodes(const std::vector<BaseNode *> &nodes,
  406. aiNode *pcParent, const char *szName) {
  407. aiMatrix4x4 m;
  408. AddNodes(nodes, pcParent, szName, m);
  409. }
  410. // ------------------------------------------------------------------------------------------------
  411. // Add meshes to a given node
  412. void ASEImporter::AddMeshes(const ASE::BaseNode *snode, aiNode *node) {
  413. for (unsigned int i = 0; i < pcScene->mNumMeshes; ++i) {
  414. // Get the name of the mesh (the mesh instance has been temporarily stored in the third vertex color)
  415. const aiMesh *pcMesh = pcScene->mMeshes[i];
  416. const ASE::Mesh *mesh = (const ASE::Mesh *)pcMesh->mColors[2];
  417. if (mesh == snode) {
  418. ++node->mNumMeshes;
  419. }
  420. }
  421. if (node->mNumMeshes) {
  422. node->mMeshes = new unsigned int[node->mNumMeshes];
  423. for (unsigned int i = 0, p = 0; i < pcScene->mNumMeshes; ++i) {
  424. const aiMesh *pcMesh = pcScene->mMeshes[i];
  425. const ASE::Mesh *mesh = (const ASE::Mesh *)pcMesh->mColors[2];
  426. if (mesh == snode) {
  427. node->mMeshes[p++] = i;
  428. // Transform all vertices of the mesh back into their local space ->
  429. // at the moment they are pretransformed
  430. aiMatrix4x4 m = mesh->mTransform;
  431. m.Inverse();
  432. aiVector3D *pvCurPtr = pcMesh->mVertices;
  433. const aiVector3D *pvEndPtr = pvCurPtr + pcMesh->mNumVertices;
  434. while (pvCurPtr != pvEndPtr) {
  435. *pvCurPtr = m * (*pvCurPtr);
  436. pvCurPtr++;
  437. }
  438. // Do the same for the normal vectors, if we have them.
  439. // As always, inverse transpose.
  440. if (pcMesh->mNormals) {
  441. aiMatrix3x3 m3 = aiMatrix3x3(mesh->mTransform);
  442. m3.Transpose();
  443. pvCurPtr = pcMesh->mNormals;
  444. pvEndPtr = pvCurPtr + pcMesh->mNumVertices;
  445. while (pvCurPtr != pvEndPtr) {
  446. *pvCurPtr = m3 * (*pvCurPtr);
  447. pvCurPtr++;
  448. }
  449. }
  450. }
  451. }
  452. }
  453. }
  454. // ------------------------------------------------------------------------------------------------
  455. // Add child nodes to a given parent node
  456. void ASEImporter::AddNodes(const std::vector<BaseNode *> &nodes,
  457. aiNode *pcParent, const char *szName,
  458. const aiMatrix4x4 &mat) {
  459. const size_t len = szName ? ::strlen(szName) : 0;
  460. ai_assert(4 <= AI_MAX_NUMBER_OF_COLOR_SETS);
  461. // Receives child nodes for the pcParent node
  462. std::vector<aiNode *> apcNodes;
  463. // Now iterate through all nodes in the scene and search for one
  464. // which has *us* as parent.
  465. for (std::vector<BaseNode *>::const_iterator it = nodes.begin(), end = nodes.end(); it != end; ++it) {
  466. const BaseNode *snode = *it;
  467. if (szName) {
  468. if (len != snode->mParent.length() || ::strcmp(szName, snode->mParent.c_str()))
  469. continue;
  470. } else if (snode->mParent.length())
  471. continue;
  472. (*it)->mProcessed = true;
  473. // Allocate a new node and add it to the output data structure
  474. apcNodes.push_back(new aiNode());
  475. aiNode *node = apcNodes.back();
  476. node->mName.Set((snode->mName.length() ? snode->mName.c_str() : "Unnamed_Node"));
  477. node->mParent = pcParent;
  478. // Setup the transformation matrix of the node
  479. aiMatrix4x4 mParentAdjust = mat;
  480. mParentAdjust.Inverse();
  481. node->mTransformation = mParentAdjust * snode->mTransform;
  482. // Add sub nodes - prevent stack overflow due to recursive parenting
  483. if (node->mName != node->mParent->mName && node->mName != node->mParent->mParent->mName) {
  484. AddNodes(nodes, node, node->mName.data, snode->mTransform);
  485. }
  486. // Further processing depends on the type of the node
  487. if (snode->mType == ASE::BaseNode::Mesh) {
  488. // If the type of this node is "Mesh" we need to search
  489. // the list of output meshes in the data structure for
  490. // all those that belonged to this node once. This is
  491. // slightly inconvinient here and a better solution should
  492. // be used when this code is refactored next.
  493. AddMeshes(snode, node);
  494. } else if (is_not_qnan(snode->mTargetPosition.x)) {
  495. // If this is a target camera or light we generate a small
  496. // child node which marks the position of the camera
  497. // target (the direction information is contained in *this*
  498. // node's animation track but the exact target position
  499. // would be lost otherwise)
  500. if (!node->mNumChildren) {
  501. node->mChildren = new aiNode *[1];
  502. }
  503. aiNode *nd = new aiNode();
  504. nd->mName.Set(snode->mName + ".Target");
  505. nd->mTransformation.a4 = snode->mTargetPosition.x - snode->mTransform.a4;
  506. nd->mTransformation.b4 = snode->mTargetPosition.y - snode->mTransform.b4;
  507. nd->mTransformation.c4 = snode->mTargetPosition.z - snode->mTransform.c4;
  508. nd->mParent = node;
  509. // The .Target node is always the first child node
  510. for (unsigned int m = 0; m < node->mNumChildren; ++m)
  511. node->mChildren[m + 1] = node->mChildren[m];
  512. node->mChildren[0] = nd;
  513. node->mNumChildren++;
  514. // What we did is so great, it is at least worth a debug message
  515. ASSIMP_LOG_VERBOSE_DEBUG("ASE: Generating separate target node (", snode->mName, ")");
  516. }
  517. }
  518. // Allocate enough space for the child nodes
  519. // We allocate one slot more in case this is a target camera/light
  520. pcParent->mNumChildren = (unsigned int)apcNodes.size();
  521. if (pcParent->mNumChildren) {
  522. pcParent->mChildren = new aiNode *[apcNodes.size() + 1 /* PLUS ONE !!! */];
  523. // now build all nodes for our nice new children
  524. for (unsigned int p = 0; p < apcNodes.size(); ++p)
  525. pcParent->mChildren[p] = apcNodes[p];
  526. }
  527. return;
  528. }
  529. // ------------------------------------------------------------------------------------------------
  530. // Build the output node graph
  531. void ASEImporter::BuildNodes(std::vector<BaseNode *> &nodes) {
  532. ai_assert(nullptr != pcScene);
  533. // allocate the one and only root node
  534. aiNode *root = pcScene->mRootNode = new aiNode();
  535. root->mName.Set("<ASERoot>");
  536. // Setup the coordinate system transformation
  537. pcScene->mRootNode->mNumChildren = 1;
  538. pcScene->mRootNode->mChildren = new aiNode *[1];
  539. aiNode *ch = pcScene->mRootNode->mChildren[0] = new aiNode();
  540. ch->mParent = root;
  541. // Change the transformation matrix of all nodes
  542. for (BaseNode *node : nodes) {
  543. aiMatrix4x4 &m = node->mTransform;
  544. m.Transpose(); // row-order vs column-order
  545. }
  546. // add all nodes
  547. AddNodes(nodes, ch, nullptr);
  548. // now iterate through al nodes and find those that have not yet
  549. // been added to the nodegraph (= their parent could not be recognized)
  550. std::vector<const BaseNode *> aiList;
  551. for (std::vector<BaseNode *>::iterator it = nodes.begin(), end = nodes.end(); it != end; ++it) {
  552. if ((*it)->mProcessed) {
  553. continue;
  554. }
  555. // check whether our parent is known
  556. bool bKnowParent = false;
  557. // search the list another time, starting *here* and try to find out whether
  558. // there is a node that references *us* as a parent
  559. for (std::vector<BaseNode *>::const_iterator it2 = nodes.begin(); it2 != end; ++it2) {
  560. if (it2 == it) {
  561. continue;
  562. }
  563. if ((*it2)->mName == (*it)->mParent) {
  564. bKnowParent = true;
  565. break;
  566. }
  567. }
  568. if (!bKnowParent) {
  569. aiList.push_back(*it);
  570. }
  571. }
  572. // Are there any orphaned nodes?
  573. if (!aiList.empty()) {
  574. std::vector<aiNode *> apcNodes;
  575. apcNodes.reserve(aiList.size() + pcScene->mRootNode->mNumChildren);
  576. for (unsigned int i = 0; i < pcScene->mRootNode->mNumChildren; ++i)
  577. apcNodes.push_back(pcScene->mRootNode->mChildren[i]);
  578. delete[] pcScene->mRootNode->mChildren;
  579. for (std::vector<const BaseNode *>::/*const_*/ iterator i = aiList.begin(); i != aiList.end(); ++i) {
  580. const ASE::BaseNode *src = *i;
  581. // The parent is not known, so we can assume that we must add
  582. // this node to the root node of the whole scene
  583. aiNode *pcNode = new aiNode();
  584. pcNode->mParent = pcScene->mRootNode;
  585. pcNode->mName.Set(src->mName);
  586. AddMeshes(src, pcNode);
  587. AddNodes(nodes, pcNode, pcNode->mName.data);
  588. apcNodes.push_back(pcNode);
  589. }
  590. // Regenerate our output array
  591. pcScene->mRootNode->mChildren = new aiNode *[apcNodes.size()];
  592. for (unsigned int i = 0; i < apcNodes.size(); ++i)
  593. pcScene->mRootNode->mChildren[i] = apcNodes[i];
  594. pcScene->mRootNode->mNumChildren = (unsigned int)apcNodes.size();
  595. }
  596. // Reset the third color set to nullptr - we used this field to store a temporary pointer
  597. for (unsigned int i = 0; i < pcScene->mNumMeshes; ++i)
  598. pcScene->mMeshes[i]->mColors[2] = nullptr;
  599. // The root node should not have at least one child or the file is valid
  600. if (!pcScene->mRootNode->mNumChildren) {
  601. throw DeadlyImportError("ASE: No nodes loaded. The file is either empty or corrupt");
  602. }
  603. // Now rotate the whole scene 90 degrees around the x axis to convert to internal coordinate system
  604. pcScene->mRootNode->mTransformation = aiMatrix4x4(1.f, 0.f, 0.f, 0.f,
  605. 0.f, 0.f, 1.f, 0.f, 0.f, -1.f, 0.f, 0.f, 0.f, 0.f, 0.f, 1.f);
  606. }
  607. // ------------------------------------------------------------------------------------------------
  608. // Convert the imported data to the internal verbose representation
  609. void ASEImporter::BuildUniqueRepresentation(ASE::Mesh &mesh) {
  610. // allocate output storage
  611. std::vector<aiVector3D> mPositions;
  612. std::vector<aiVector3D> amTexCoords[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  613. std::vector<aiColor4D> mVertexColors;
  614. std::vector<aiVector3D> mNormals;
  615. std::vector<BoneVertex> mBoneVertices;
  616. unsigned int iSize = (unsigned int)mesh.mFaces.size() * 3;
  617. mPositions.resize(iSize);
  618. // optional texture coordinates
  619. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  620. if (!mesh.amTexCoords[i].empty()) {
  621. amTexCoords[i].resize(iSize);
  622. }
  623. }
  624. // optional vertex colors
  625. if (!mesh.mVertexColors.empty()) {
  626. mVertexColors.resize(iSize);
  627. }
  628. // optional vertex normals (vertex normals can simply be copied)
  629. if (!mesh.mNormals.empty()) {
  630. mNormals.resize(iSize);
  631. }
  632. // bone vertices. There is no need to change the bone list
  633. if (!mesh.mBoneVertices.empty()) {
  634. mBoneVertices.resize(iSize);
  635. }
  636. // iterate through all faces in the mesh
  637. unsigned int iCurrent = 0, fi = 0;
  638. for (std::vector<ASE::Face>::iterator i = mesh.mFaces.begin(); i != mesh.mFaces.end(); ++i, ++fi) {
  639. for (unsigned int n = 0; n < 3; ++n, ++iCurrent) {
  640. mPositions[iCurrent] = mesh.mPositions[(*i).mIndices[n]];
  641. // add texture coordinates
  642. for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++c) {
  643. if (mesh.amTexCoords[c].empty()) break;
  644. amTexCoords[c][iCurrent] = mesh.amTexCoords[c][(*i).amUVIndices[c][n]];
  645. }
  646. // add vertex colors
  647. if (!mesh.mVertexColors.empty()) {
  648. mVertexColors[iCurrent] = mesh.mVertexColors[(*i).mColorIndices[n]];
  649. }
  650. // add normal vectors
  651. if (!mesh.mNormals.empty()) {
  652. mNormals[iCurrent] = mesh.mNormals[fi * 3 + n];
  653. mNormals[iCurrent].Normalize();
  654. }
  655. // handle bone vertices
  656. if ((*i).mIndices[n] < mesh.mBoneVertices.size()) {
  657. // (sometimes this will cause bone verts to be duplicated
  658. // however, I' quite sure Schrompf' JoinVerticesStep
  659. // will fix that again ...)
  660. mBoneVertices[iCurrent] = mesh.mBoneVertices[(*i).mIndices[n]];
  661. }
  662. (*i).mIndices[n] = iCurrent;
  663. }
  664. }
  665. // replace the old arrays
  666. mesh.mNormals = mNormals;
  667. mesh.mPositions = mPositions;
  668. mesh.mVertexColors = mVertexColors;
  669. for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++c)
  670. mesh.amTexCoords[c] = amTexCoords[c];
  671. }
  672. // ------------------------------------------------------------------------------------------------
  673. // Copy a texture from the ASE structs to the output material
  674. void CopyASETexture(aiMaterial &mat, ASE::Texture &texture, aiTextureType type) {
  675. // Setup the texture name
  676. aiString tex;
  677. tex.Set(texture.mMapName);
  678. mat.AddProperty(&tex, AI_MATKEY_TEXTURE(type, 0));
  679. // Setup the texture blend factor
  680. if (is_not_qnan(texture.mTextureBlend))
  681. mat.AddProperty<ai_real>(&texture.mTextureBlend, 1, AI_MATKEY_TEXBLEND(type, 0));
  682. // Setup texture UV transformations
  683. mat.AddProperty<ai_real>(&texture.mOffsetU, 5, AI_MATKEY_UVTRANSFORM(type, 0));
  684. }
  685. // ------------------------------------------------------------------------------------------------
  686. // Convert from ASE material to output material
  687. void ASEImporter::ConvertMaterial(ASE::Material &mat) {
  688. // LARGE TODO: Much code her is copied from 3DS ... join them maybe?
  689. // Allocate the output material
  690. mat.pcInstance = new aiMaterial();
  691. // At first add the base ambient color of the
  692. // scene to the material
  693. mat.mAmbient.r += mParser->m_clrAmbient.r;
  694. mat.mAmbient.g += mParser->m_clrAmbient.g;
  695. mat.mAmbient.b += mParser->m_clrAmbient.b;
  696. aiString name;
  697. name.Set(mat.mName);
  698. mat.pcInstance->AddProperty(&name, AI_MATKEY_NAME);
  699. // material colors
  700. mat.pcInstance->AddProperty(&mat.mAmbient, 1, AI_MATKEY_COLOR_AMBIENT);
  701. mat.pcInstance->AddProperty(&mat.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  702. mat.pcInstance->AddProperty(&mat.mSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
  703. mat.pcInstance->AddProperty(&mat.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  704. // shininess
  705. if (0.0f != mat.mSpecularExponent && 0.0f != mat.mShininessStrength) {
  706. mat.pcInstance->AddProperty(&mat.mSpecularExponent, 1, AI_MATKEY_SHININESS);
  707. mat.pcInstance->AddProperty(&mat.mShininessStrength, 1, AI_MATKEY_SHININESS_STRENGTH);
  708. }
  709. // If there is no shininess, we can disable phong lighting
  710. else if (D3DS::Discreet3DS::Metal == mat.mShading ||
  711. D3DS::Discreet3DS::Phong == mat.mShading ||
  712. D3DS::Discreet3DS::Blinn == mat.mShading) {
  713. mat.mShading = D3DS::Discreet3DS::Gouraud;
  714. }
  715. // opacity
  716. mat.pcInstance->AddProperty<ai_real>(&mat.mTransparency, 1, AI_MATKEY_OPACITY);
  717. // Two sided rendering?
  718. if (mat.mTwoSided) {
  719. int i = 1;
  720. mat.pcInstance->AddProperty<int>(&i, 1, AI_MATKEY_TWOSIDED);
  721. }
  722. // shading mode
  723. aiShadingMode eShading = aiShadingMode_NoShading;
  724. switch (mat.mShading) {
  725. case D3DS::Discreet3DS::Flat:
  726. eShading = aiShadingMode_Flat;
  727. break;
  728. case D3DS::Discreet3DS::Phong:
  729. eShading = aiShadingMode_Phong;
  730. break;
  731. case D3DS::Discreet3DS::Blinn:
  732. eShading = aiShadingMode_Blinn;
  733. break;
  734. // I don't know what "Wire" shading should be,
  735. // assume it is simple lambertian diffuse (L dot N) shading
  736. case D3DS::Discreet3DS::Wire: {
  737. // set the wireframe flag
  738. unsigned int iWire = 1;
  739. mat.pcInstance->AddProperty<int>((int *)&iWire, 1, AI_MATKEY_ENABLE_WIREFRAME);
  740. }
  741. case D3DS::Discreet3DS::Gouraud:
  742. eShading = aiShadingMode_Gouraud;
  743. break;
  744. case D3DS::Discreet3DS::Metal:
  745. eShading = aiShadingMode_CookTorrance;
  746. break;
  747. }
  748. mat.pcInstance->AddProperty<int>((int *)&eShading, 1, AI_MATKEY_SHADING_MODEL);
  749. // DIFFUSE texture
  750. if (mat.sTexDiffuse.mMapName.length() > 0)
  751. CopyASETexture(*mat.pcInstance, mat.sTexDiffuse, aiTextureType_DIFFUSE);
  752. // SPECULAR texture
  753. if (mat.sTexSpecular.mMapName.length() > 0)
  754. CopyASETexture(*mat.pcInstance, mat.sTexSpecular, aiTextureType_SPECULAR);
  755. // AMBIENT texture
  756. if (mat.sTexAmbient.mMapName.length() > 0)
  757. CopyASETexture(*mat.pcInstance, mat.sTexAmbient, aiTextureType_AMBIENT);
  758. // OPACITY texture
  759. if (mat.sTexOpacity.mMapName.length() > 0)
  760. CopyASETexture(*mat.pcInstance, mat.sTexOpacity, aiTextureType_OPACITY);
  761. // EMISSIVE texture
  762. if (mat.sTexEmissive.mMapName.length() > 0)
  763. CopyASETexture(*mat.pcInstance, mat.sTexEmissive, aiTextureType_EMISSIVE);
  764. // BUMP texture
  765. if (mat.sTexBump.mMapName.length() > 0)
  766. CopyASETexture(*mat.pcInstance, mat.sTexBump, aiTextureType_HEIGHT);
  767. // SHININESS texture
  768. if (mat.sTexShininess.mMapName.length() > 0)
  769. CopyASETexture(*mat.pcInstance, mat.sTexShininess, aiTextureType_SHININESS);
  770. // store the name of the material itself, too
  771. if (mat.mName.length() > 0) {
  772. aiString tex;
  773. tex.Set(mat.mName);
  774. mat.pcInstance->AddProperty(&tex, AI_MATKEY_NAME);
  775. }
  776. return;
  777. }
  778. // ------------------------------------------------------------------------------------------------
  779. // Build output meshes
  780. void ASEImporter::ConvertMeshes(ASE::Mesh &mesh, std::vector<aiMesh *> &avOutMeshes) {
  781. // validate the material index of the mesh
  782. if (mesh.iMaterialIndex >= mParser->m_vMaterials.size()) {
  783. mesh.iMaterialIndex = (unsigned int)mParser->m_vMaterials.size() - 1;
  784. ASSIMP_LOG_WARN("Material index is out of range");
  785. }
  786. // If the material the mesh is assigned to is consisting of submeshes, split it
  787. if (!mParser->m_vMaterials[mesh.iMaterialIndex].avSubMaterials.empty()) {
  788. std::vector<ASE::Material> vSubMaterials = mParser->m_vMaterials[mesh.iMaterialIndex].avSubMaterials;
  789. std::vector<unsigned int> *aiSplit = new std::vector<unsigned int>[vSubMaterials.size()];
  790. // build a list of all faces per sub-material
  791. for (unsigned int i = 0; i < mesh.mFaces.size(); ++i) {
  792. // check range
  793. if (mesh.mFaces[i].iMaterial >= vSubMaterials.size()) {
  794. ASSIMP_LOG_WARN("Submaterial index is out of range");
  795. // use the last material instead
  796. aiSplit[vSubMaterials.size() - 1].push_back(i);
  797. } else
  798. aiSplit[mesh.mFaces[i].iMaterial].push_back(i);
  799. }
  800. // now generate submeshes
  801. for (unsigned int p = 0; p < vSubMaterials.size(); ++p) {
  802. if (!aiSplit[p].empty()) {
  803. aiMesh *p_pcOut = new aiMesh();
  804. p_pcOut->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  805. // let the sub material index
  806. p_pcOut->mMaterialIndex = p;
  807. // we will need this material
  808. mParser->m_vMaterials[mesh.iMaterialIndex].avSubMaterials[p].bNeed = true;
  809. // store the real index here ... color channel 3
  810. p_pcOut->mColors[3] = (aiColor4D *)(uintptr_t)mesh.iMaterialIndex;
  811. // store a pointer to the mesh in color channel 2
  812. p_pcOut->mColors[2] = (aiColor4D *)&mesh;
  813. avOutMeshes.push_back(p_pcOut);
  814. // convert vertices
  815. p_pcOut->mNumVertices = (unsigned int)aiSplit[p].size() * 3;
  816. p_pcOut->mNumFaces = (unsigned int)aiSplit[p].size();
  817. // receive output vertex weights
  818. std::vector<std::pair<unsigned int, float>> *avOutputBones = nullptr;
  819. if (!mesh.mBones.empty()) {
  820. avOutputBones = new std::vector<std::pair<unsigned int, float>>[mesh.mBones.size()];
  821. }
  822. // allocate enough storage for faces
  823. p_pcOut->mFaces = new aiFace[p_pcOut->mNumFaces];
  824. unsigned int iBase = 0, iIndex;
  825. if (p_pcOut->mNumVertices) {
  826. p_pcOut->mVertices = new aiVector3D[p_pcOut->mNumVertices];
  827. p_pcOut->mNormals = new aiVector3D[p_pcOut->mNumVertices];
  828. for (unsigned int q = 0; q < aiSplit[p].size(); ++q) {
  829. iIndex = aiSplit[p][q];
  830. p_pcOut->mFaces[q].mIndices = new unsigned int[3];
  831. p_pcOut->mFaces[q].mNumIndices = 3;
  832. for (unsigned int t = 0; t < 3; ++t, ++iBase) {
  833. const uint32_t iIndex2 = mesh.mFaces[iIndex].mIndices[t];
  834. p_pcOut->mVertices[iBase] = mesh.mPositions[iIndex2];
  835. p_pcOut->mNormals[iBase] = mesh.mNormals[iIndex2];
  836. // convert bones, if existing
  837. if (!mesh.mBones.empty()) {
  838. ai_assert(avOutputBones);
  839. // check whether there is a vertex weight for this vertex index
  840. if (iIndex2 < mesh.mBoneVertices.size()) {
  841. for (std::vector<std::pair<int, float>>::const_iterator
  842. blubb = mesh.mBoneVertices[iIndex2].mBoneWeights.begin();
  843. blubb != mesh.mBoneVertices[iIndex2].mBoneWeights.end(); ++blubb) {
  844. // NOTE: illegal cases have already been filtered out
  845. avOutputBones[(*blubb).first].push_back(std::pair<unsigned int, float>(
  846. iBase, (*blubb).second));
  847. }
  848. }
  849. }
  850. p_pcOut->mFaces[q].mIndices[t] = iBase;
  851. }
  852. }
  853. }
  854. // convert texture coordinates (up to AI_MAX_NUMBER_OF_TEXTURECOORDS sets supported)
  855. for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++c) {
  856. if (!mesh.amTexCoords[c].empty()) {
  857. p_pcOut->mTextureCoords[c] = new aiVector3D[p_pcOut->mNumVertices];
  858. iBase = 0;
  859. for (unsigned int q = 0; q < aiSplit[p].size(); ++q) {
  860. iIndex = aiSplit[p][q];
  861. for (unsigned int t = 0; t < 3; ++t) {
  862. p_pcOut->mTextureCoords[c][iBase++] = mesh.amTexCoords[c][mesh.mFaces[iIndex].mIndices[t]];
  863. }
  864. }
  865. // Setup the number of valid vertex components
  866. p_pcOut->mNumUVComponents[c] = mesh.mNumUVComponents[c];
  867. }
  868. }
  869. // Convert vertex colors (only one set supported)
  870. if (!mesh.mVertexColors.empty()) {
  871. p_pcOut->mColors[0] = new aiColor4D[p_pcOut->mNumVertices];
  872. iBase = 0;
  873. for (unsigned int q = 0; q < aiSplit[p].size(); ++q) {
  874. iIndex = aiSplit[p][q];
  875. for (unsigned int t = 0; t < 3; ++t) {
  876. p_pcOut->mColors[0][iBase++] = mesh.mVertexColors[mesh.mFaces[iIndex].mIndices[t]];
  877. }
  878. }
  879. }
  880. // Copy bones
  881. if (!mesh.mBones.empty()) {
  882. p_pcOut->mNumBones = 0;
  883. for (unsigned int mrspock = 0; mrspock < mesh.mBones.size(); ++mrspock)
  884. if (!avOutputBones[mrspock].empty()) p_pcOut->mNumBones++;
  885. p_pcOut->mBones = new aiBone *[p_pcOut->mNumBones];
  886. aiBone **pcBone = p_pcOut->mBones;
  887. for (unsigned int mrspock = 0; mrspock < mesh.mBones.size(); ++mrspock) {
  888. if (!avOutputBones[mrspock].empty()) {
  889. // we will need this bone. add it to the output mesh and
  890. // add all per-vertex weights
  891. aiBone *pc = *pcBone = new aiBone();
  892. pc->mName.Set(mesh.mBones[mrspock].mName);
  893. pc->mNumWeights = (unsigned int)avOutputBones[mrspock].size();
  894. pc->mWeights = new aiVertexWeight[pc->mNumWeights];
  895. for (unsigned int captainkirk = 0; captainkirk < pc->mNumWeights; ++captainkirk) {
  896. const std::pair<unsigned int, float> &ref = avOutputBones[mrspock][captainkirk];
  897. pc->mWeights[captainkirk].mVertexId = ref.first;
  898. pc->mWeights[captainkirk].mWeight = ref.second;
  899. }
  900. ++pcBone;
  901. }
  902. }
  903. // delete allocated storage
  904. delete[] avOutputBones;
  905. }
  906. }
  907. }
  908. // delete storage
  909. delete[] aiSplit;
  910. } else {
  911. // Otherwise we can simply copy the data to one output mesh
  912. // This codepath needs less memory and uses fast memcpy()s
  913. // to do the actual copying. So I think it is worth the
  914. // effort here.
  915. aiMesh *p_pcOut = new aiMesh();
  916. p_pcOut->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  917. // set an empty sub material index
  918. p_pcOut->mMaterialIndex = ASE::Face::DEFAULT_MATINDEX;
  919. mParser->m_vMaterials[mesh.iMaterialIndex].bNeed = true;
  920. // store the real index here ... in color channel 3
  921. p_pcOut->mColors[3] = (aiColor4D *)(uintptr_t)mesh.iMaterialIndex;
  922. // store a pointer to the mesh in color channel 2
  923. p_pcOut->mColors[2] = (aiColor4D *)&mesh;
  924. avOutMeshes.push_back(p_pcOut);
  925. // If the mesh hasn't faces or vertices, there are two cases
  926. // possible: 1. the model is invalid. 2. This is a dummy
  927. // helper object which we are going to remove later ...
  928. if (mesh.mFaces.empty() || mesh.mPositions.empty()) {
  929. return;
  930. }
  931. // convert vertices
  932. p_pcOut->mNumVertices = (unsigned int)mesh.mPositions.size();
  933. p_pcOut->mNumFaces = (unsigned int)mesh.mFaces.size();
  934. // allocate enough storage for faces
  935. p_pcOut->mFaces = new aiFace[p_pcOut->mNumFaces];
  936. // copy vertices
  937. p_pcOut->mVertices = new aiVector3D[mesh.mPositions.size()];
  938. memcpy(p_pcOut->mVertices, &mesh.mPositions[0],
  939. mesh.mPositions.size() * sizeof(aiVector3D));
  940. // copy normals
  941. p_pcOut->mNormals = new aiVector3D[mesh.mNormals.size()];
  942. memcpy(p_pcOut->mNormals, &mesh.mNormals[0],
  943. mesh.mNormals.size() * sizeof(aiVector3D));
  944. // copy texture coordinates
  945. for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++c) {
  946. if (!mesh.amTexCoords[c].empty()) {
  947. p_pcOut->mTextureCoords[c] = new aiVector3D[mesh.amTexCoords[c].size()];
  948. memcpy(p_pcOut->mTextureCoords[c], &mesh.amTexCoords[c][0],
  949. mesh.amTexCoords[c].size() * sizeof(aiVector3D));
  950. // setup the number of valid vertex components
  951. p_pcOut->mNumUVComponents[c] = mesh.mNumUVComponents[c];
  952. }
  953. }
  954. // copy vertex colors
  955. if (!mesh.mVertexColors.empty()) {
  956. p_pcOut->mColors[0] = new aiColor4D[mesh.mVertexColors.size()];
  957. memcpy(p_pcOut->mColors[0], &mesh.mVertexColors[0],
  958. mesh.mVertexColors.size() * sizeof(aiColor4D));
  959. }
  960. // copy faces
  961. for (unsigned int iFace = 0; iFace < p_pcOut->mNumFaces; ++iFace) {
  962. p_pcOut->mFaces[iFace].mNumIndices = 3;
  963. p_pcOut->mFaces[iFace].mIndices = new unsigned int[3];
  964. // copy indices
  965. p_pcOut->mFaces[iFace].mIndices[0] = mesh.mFaces[iFace].mIndices[0];
  966. p_pcOut->mFaces[iFace].mIndices[1] = mesh.mFaces[iFace].mIndices[1];
  967. p_pcOut->mFaces[iFace].mIndices[2] = mesh.mFaces[iFace].mIndices[2];
  968. }
  969. // copy vertex bones
  970. if (!mesh.mBones.empty() && !mesh.mBoneVertices.empty()) {
  971. std::vector<std::vector<aiVertexWeight>> avBonesOut(mesh.mBones.size());
  972. // find all vertex weights for this bone
  973. unsigned int quak = 0;
  974. for (std::vector<BoneVertex>::const_iterator harrypotter = mesh.mBoneVertices.begin();
  975. harrypotter != mesh.mBoneVertices.end(); ++harrypotter, ++quak) {
  976. for (std::vector<std::pair<int, float>>::const_iterator
  977. ronaldweasley = (*harrypotter).mBoneWeights.begin();
  978. ronaldweasley != (*harrypotter).mBoneWeights.end(); ++ronaldweasley) {
  979. aiVertexWeight weight;
  980. weight.mVertexId = quak;
  981. weight.mWeight = (*ronaldweasley).second;
  982. avBonesOut[(*ronaldweasley).first].push_back(weight);
  983. }
  984. }
  985. // now build a final bone list
  986. p_pcOut->mNumBones = 0;
  987. for (unsigned int jfkennedy = 0; jfkennedy < mesh.mBones.size(); ++jfkennedy)
  988. if (!avBonesOut[jfkennedy].empty()) p_pcOut->mNumBones++;
  989. p_pcOut->mBones = new aiBone *[p_pcOut->mNumBones];
  990. aiBone **pcBone = p_pcOut->mBones;
  991. for (unsigned int jfkennedy = 0; jfkennedy < mesh.mBones.size(); ++jfkennedy) {
  992. if (!avBonesOut[jfkennedy].empty()) {
  993. aiBone *pc = *pcBone = new aiBone();
  994. pc->mName.Set(mesh.mBones[jfkennedy].mName);
  995. pc->mNumWeights = (unsigned int)avBonesOut[jfkennedy].size();
  996. pc->mWeights = new aiVertexWeight[pc->mNumWeights];
  997. ::memcpy(pc->mWeights, &avBonesOut[jfkennedy][0],
  998. sizeof(aiVertexWeight) * pc->mNumWeights);
  999. ++pcBone;
  1000. }
  1001. }
  1002. }
  1003. }
  1004. }
  1005. // ------------------------------------------------------------------------------------------------
  1006. // Setup proper material indices and build output materials
  1007. void ASEImporter::BuildMaterialIndices() {
  1008. ai_assert(nullptr != pcScene);
  1009. // iterate through all materials and check whether we need them
  1010. for (unsigned int iMat = 0; iMat < mParser->m_vMaterials.size(); ++iMat) {
  1011. ASE::Material &mat = mParser->m_vMaterials[iMat];
  1012. if (mat.bNeed) {
  1013. // Convert it to the aiMaterial layout
  1014. ConvertMaterial(mat);
  1015. ++pcScene->mNumMaterials;
  1016. }
  1017. for (unsigned int iSubMat = 0; iSubMat < mat.avSubMaterials.size(); ++iSubMat) {
  1018. ASE::Material &submat = mat.avSubMaterials[iSubMat];
  1019. if (submat.bNeed) {
  1020. // Convert it to the aiMaterial layout
  1021. ConvertMaterial(submat);
  1022. ++pcScene->mNumMaterials;
  1023. }
  1024. }
  1025. }
  1026. // allocate the output material array
  1027. pcScene->mMaterials = new aiMaterial *[pcScene->mNumMaterials];
  1028. D3DS::Material **pcIntMaterials = new D3DS::Material *[pcScene->mNumMaterials];
  1029. unsigned int iNum = 0;
  1030. for (unsigned int iMat = 0; iMat < mParser->m_vMaterials.size(); ++iMat) {
  1031. ASE::Material &mat = mParser->m_vMaterials[iMat];
  1032. if (mat.bNeed) {
  1033. ai_assert(nullptr != mat.pcInstance);
  1034. pcScene->mMaterials[iNum] = mat.pcInstance;
  1035. // Store the internal material, too
  1036. pcIntMaterials[iNum] = &mat;
  1037. // Iterate through all meshes and search for one which is using
  1038. // this top-level material index
  1039. for (unsigned int iMesh = 0; iMesh < pcScene->mNumMeshes; ++iMesh) {
  1040. aiMesh *mesh = pcScene->mMeshes[iMesh];
  1041. if (ASE::Face::DEFAULT_MATINDEX == mesh->mMaterialIndex &&
  1042. iMat == (uintptr_t)mesh->mColors[3]) {
  1043. mesh->mMaterialIndex = iNum;
  1044. mesh->mColors[3] = nullptr;
  1045. }
  1046. }
  1047. iNum++;
  1048. }
  1049. for (unsigned int iSubMat = 0; iSubMat < mat.avSubMaterials.size(); ++iSubMat) {
  1050. ASE::Material &submat = mat.avSubMaterials[iSubMat];
  1051. if (submat.bNeed) {
  1052. ai_assert(nullptr != submat.pcInstance);
  1053. pcScene->mMaterials[iNum] = submat.pcInstance;
  1054. // Store the internal material, too
  1055. pcIntMaterials[iNum] = &submat;
  1056. // Iterate through all meshes and search for one which is using
  1057. // this sub-level material index
  1058. for (unsigned int iMesh = 0; iMesh < pcScene->mNumMeshes; ++iMesh) {
  1059. aiMesh *mesh = pcScene->mMeshes[iMesh];
  1060. if (iSubMat == mesh->mMaterialIndex && iMat == (uintptr_t)mesh->mColors[3]) {
  1061. mesh->mMaterialIndex = iNum;
  1062. mesh->mColors[3] = nullptr;
  1063. }
  1064. }
  1065. iNum++;
  1066. }
  1067. }
  1068. }
  1069. // Delete our temporary array
  1070. delete[] pcIntMaterials;
  1071. }
  1072. // ------------------------------------------------------------------------------------------------
  1073. // Generate normal vectors basing on smoothing groups
  1074. bool ASEImporter::GenerateNormals(ASE::Mesh &mesh) {
  1075. if (!mesh.mNormals.empty() && !configRecomputeNormals) {
  1076. // Check whether there are only uninitialized normals. If there are
  1077. // some, skip all normals from the file and compute them on our own
  1078. for (std::vector<aiVector3D>::const_iterator qq = mesh.mNormals.begin(); qq != mesh.mNormals.end(); ++qq) {
  1079. if ((*qq).x || (*qq).y || (*qq).z) {
  1080. return true;
  1081. }
  1082. }
  1083. }
  1084. // The array is reused.
  1085. ComputeNormalsWithSmoothingsGroups<ASE::Face>(mesh);
  1086. return false;
  1087. }
  1088. #endif // ASSIMP_BUILD_NO_3DS_IMPORTER
  1089. #endif // !! ASSIMP_BUILD_NO_BASE_IMPORTER