ASELoader.cpp 53 KB

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