ASELoader.cpp 46 KB

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