You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1317 lines
45 KiB

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