3DSConverter.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  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 Implementation of the 3ds importer class */
  35. #ifndef ASSIMP_BUILD_NO_3DS_IMPORTER
  36. // internal headers
  37. #include "3DSLoader.h"
  38. #include "TargetAnimation.h"
  39. #include <assimp/scene.h>
  40. #include <assimp/DefaultLogger.hpp>
  41. #include "StringComparison.h"
  42. #include <memory>
  43. #include <cctype>
  44. using namespace Assimp;
  45. // ------------------------------------------------------------------------------------------------
  46. // Setup final material indices, generae a default material if necessary
  47. void Discreet3DSImporter::ReplaceDefaultMaterial()
  48. {
  49. // Try to find an existing material that matches the
  50. // typical default material setting:
  51. // - no textures
  52. // - diffuse color (in grey!)
  53. // NOTE: This is here to workaround the fact that some
  54. // exporters are writing a default material, too.
  55. unsigned int idx = 0xcdcdcdcd;
  56. for (unsigned int i = 0; i < mScene->mMaterials.size();++i)
  57. {
  58. std::string s = mScene->mMaterials[i].mName;
  59. for ( std::string::iterator it = s.begin(); it != s.end(); ++it ) {
  60. *it = static_cast< char >( ::tolower( *it ) );
  61. }
  62. if (std::string::npos == s.find("default"))continue;
  63. if (mScene->mMaterials[i].mDiffuse.r !=
  64. mScene->mMaterials[i].mDiffuse.g ||
  65. mScene->mMaterials[i].mDiffuse.r !=
  66. mScene->mMaterials[i].mDiffuse.b)continue;
  67. if (mScene->mMaterials[i].sTexDiffuse.mMapName.length() != 0 ||
  68. mScene->mMaterials[i].sTexBump.mMapName.length() != 0 ||
  69. mScene->mMaterials[i].sTexOpacity.mMapName.length() != 0 ||
  70. mScene->mMaterials[i].sTexEmissive.mMapName.length() != 0 ||
  71. mScene->mMaterials[i].sTexSpecular.mMapName.length() != 0 ||
  72. mScene->mMaterials[i].sTexShininess.mMapName.length() != 0 )
  73. {
  74. continue;
  75. }
  76. idx = i;
  77. }
  78. if (0xcdcdcdcd == idx)idx = (unsigned int)mScene->mMaterials.size();
  79. // now iterate through all meshes and through all faces and
  80. // find all faces that are using the default material
  81. unsigned int cnt = 0;
  82. for (std::vector<D3DS::Mesh>::iterator
  83. i = mScene->mMeshes.begin();
  84. i != mScene->mMeshes.end();++i)
  85. {
  86. for (std::vector<unsigned int>::iterator
  87. a = (*i).mFaceMaterials.begin();
  88. a != (*i).mFaceMaterials.end();++a)
  89. {
  90. // NOTE: The additional check seems to be necessary,
  91. // some exporters seem to generate invalid data here
  92. if (0xcdcdcdcd == (*a))
  93. {
  94. (*a) = idx;
  95. ++cnt;
  96. }
  97. else if ( (*a) >= mScene->mMaterials.size())
  98. {
  99. (*a) = idx;
  100. DefaultLogger::get()->warn("Material index overflow in 3DS file. Using default material");
  101. ++cnt;
  102. }
  103. }
  104. }
  105. if (cnt && idx == mScene->mMaterials.size())
  106. {
  107. // We need to create our own default material
  108. D3DS::Material sMat;
  109. sMat.mDiffuse = aiColor3D(0.3f,0.3f,0.3f);
  110. sMat.mName = "%%%DEFAULT";
  111. mScene->mMaterials.push_back(sMat);
  112. DefaultLogger::get()->info("3DS: Generating default material");
  113. }
  114. }
  115. // ------------------------------------------------------------------------------------------------
  116. // Check whether all indices are valid. Otherwise we'd crash before the validation step is reached
  117. void Discreet3DSImporter::CheckIndices(D3DS::Mesh& sMesh)
  118. {
  119. for (std::vector< D3DS::Face >::iterator i = sMesh.mFaces.begin(); i != sMesh.mFaces.end();++i)
  120. {
  121. // check whether all indices are in range
  122. for (unsigned int a = 0; a < 3;++a)
  123. {
  124. if ((*i).mIndices[a] >= sMesh.mPositions.size())
  125. {
  126. DefaultLogger::get()->warn("3DS: Vertex index overflow)");
  127. (*i).mIndices[a] = (uint32_t)sMesh.mPositions.size()-1;
  128. }
  129. if ( !sMesh.mTexCoords.empty() && (*i).mIndices[a] >= sMesh.mTexCoords.size())
  130. {
  131. DefaultLogger::get()->warn("3DS: Texture coordinate index overflow)");
  132. (*i).mIndices[a] = (uint32_t)sMesh.mTexCoords.size()-1;
  133. }
  134. }
  135. }
  136. }
  137. // ------------------------------------------------------------------------------------------------
  138. // Generate out unique verbose format representation
  139. void Discreet3DSImporter::MakeUnique(D3DS::Mesh& sMesh)
  140. {
  141. // TODO: really necessary? I don't think. Just a waste of memory and time
  142. // to do it now in a separate buffer.
  143. // Allocate output storage
  144. std::vector<aiVector3D> vNew (sMesh.mFaces.size() * 3);
  145. std::vector<aiVector3D> vNew2;
  146. if (sMesh.mTexCoords.size())
  147. vNew2.resize(sMesh.mFaces.size() * 3);
  148. for (unsigned int i = 0, base = 0; i < sMesh.mFaces.size();++i)
  149. {
  150. D3DS::Face& face = sMesh.mFaces[i];
  151. // Positions
  152. for (unsigned int a = 0; a < 3;++a,++base)
  153. {
  154. vNew[base] = sMesh.mPositions[face.mIndices[a]];
  155. if (sMesh.mTexCoords.size())
  156. vNew2[base] = sMesh.mTexCoords[face.mIndices[a]];
  157. face.mIndices[a] = base;
  158. }
  159. }
  160. sMesh.mPositions = vNew;
  161. sMesh.mTexCoords = vNew2;
  162. }
  163. // ------------------------------------------------------------------------------------------------
  164. // Convert a 3DS texture to texture keys in an aiMaterial
  165. void CopyTexture(aiMaterial& mat, D3DS::Texture& texture, aiTextureType type)
  166. {
  167. // Setup the texture name
  168. aiString tex;
  169. tex.Set( texture.mMapName);
  170. mat.AddProperty( &tex, AI_MATKEY_TEXTURE(type,0));
  171. // Setup the texture blend factor
  172. if (is_not_qnan(texture.mTextureBlend))
  173. mat.AddProperty<ai_real>( &texture.mTextureBlend, 1, AI_MATKEY_TEXBLEND(type,0));
  174. // Setup the texture mapping mode
  175. mat.AddProperty<int>((int*)&texture.mMapMode,1,AI_MATKEY_MAPPINGMODE_U(type,0));
  176. mat.AddProperty<int>((int*)&texture.mMapMode,1,AI_MATKEY_MAPPINGMODE_V(type,0));
  177. // Mirroring - double the scaling values
  178. // FIXME: this is not really correct ...
  179. if (texture.mMapMode == aiTextureMapMode_Mirror)
  180. {
  181. texture.mScaleU *= 2.0;
  182. texture.mScaleV *= 2.0;
  183. texture.mOffsetU /= 2.0;
  184. texture.mOffsetV /= 2.0;
  185. }
  186. // Setup texture UV transformations
  187. mat.AddProperty<ai_real>(&texture.mOffsetU,5,AI_MATKEY_UVTRANSFORM(type,0));
  188. }
  189. // ------------------------------------------------------------------------------------------------
  190. // Convert a 3DS material to an aiMaterial
  191. void Discreet3DSImporter::ConvertMaterial(D3DS::Material& oldMat,
  192. aiMaterial& mat)
  193. {
  194. // NOTE: Pass the background image to the viewer by bypassing the
  195. // material system. This is an evil hack, never do it again!
  196. if (0 != mBackgroundImage.length() && bHasBG)
  197. {
  198. aiString tex;
  199. tex.Set( mBackgroundImage);
  200. mat.AddProperty( &tex, AI_MATKEY_GLOBAL_BACKGROUND_IMAGE);
  201. // Be sure this is only done for the first material
  202. mBackgroundImage = std::string("");
  203. }
  204. // At first add the base ambient color of the scene to the material
  205. oldMat.mAmbient.r += mClrAmbient.r;
  206. oldMat.mAmbient.g += mClrAmbient.g;
  207. oldMat.mAmbient.b += mClrAmbient.b;
  208. aiString name;
  209. name.Set( oldMat.mName);
  210. mat.AddProperty( &name, AI_MATKEY_NAME);
  211. // Material colors
  212. mat.AddProperty( &oldMat.mAmbient, 1, AI_MATKEY_COLOR_AMBIENT);
  213. mat.AddProperty( &oldMat.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  214. mat.AddProperty( &oldMat.mSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
  215. mat.AddProperty( &oldMat.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  216. // Phong shininess and shininess strength
  217. if (D3DS::Discreet3DS::Phong == oldMat.mShading ||
  218. D3DS::Discreet3DS::Metal == oldMat.mShading)
  219. {
  220. if (!oldMat.mSpecularExponent || !oldMat.mShininessStrength)
  221. {
  222. oldMat.mShading = D3DS::Discreet3DS::Gouraud;
  223. }
  224. else
  225. {
  226. mat.AddProperty( &oldMat.mSpecularExponent, 1, AI_MATKEY_SHININESS);
  227. mat.AddProperty( &oldMat.mShininessStrength, 1, AI_MATKEY_SHININESS_STRENGTH);
  228. }
  229. }
  230. // Opacity
  231. mat.AddProperty<ai_real>( &oldMat.mTransparency,1,AI_MATKEY_OPACITY);
  232. // Bump height scaling
  233. mat.AddProperty<ai_real>( &oldMat.mBumpHeight,1,AI_MATKEY_BUMPSCALING);
  234. // Two sided rendering?
  235. if (oldMat.mTwoSided)
  236. {
  237. int i = 1;
  238. mat.AddProperty<int>(&i,1,AI_MATKEY_TWOSIDED);
  239. }
  240. // Shading mode
  241. aiShadingMode eShading = aiShadingMode_NoShading;
  242. switch (oldMat.mShading)
  243. {
  244. case D3DS::Discreet3DS::Flat:
  245. eShading = aiShadingMode_Flat; break;
  246. // I don't know what "Wire" shading should be,
  247. // assume it is simple lambertian diffuse shading
  248. case D3DS::Discreet3DS::Wire:
  249. {
  250. // Set the wireframe flag
  251. unsigned int iWire = 1;
  252. mat.AddProperty<int>( (int*)&iWire,1,AI_MATKEY_ENABLE_WIREFRAME);
  253. }
  254. case D3DS::Discreet3DS::Gouraud:
  255. eShading = aiShadingMode_Gouraud; break;
  256. // assume cook-torrance shading for metals.
  257. case D3DS::Discreet3DS::Phong :
  258. eShading = aiShadingMode_Phong; break;
  259. case D3DS::Discreet3DS::Metal :
  260. eShading = aiShadingMode_CookTorrance; break;
  261. // FIX to workaround a warning with GCC 4 who complained
  262. // about a missing case Blinn: here - Blinn isn't a valid
  263. // value in the 3DS Loader, it is just needed for ASE
  264. case D3DS::Discreet3DS::Blinn :
  265. eShading = aiShadingMode_Blinn; break;
  266. }
  267. mat.AddProperty<int>( (int*)&eShading,1,AI_MATKEY_SHADING_MODEL);
  268. // DIFFUSE texture
  269. if( oldMat.sTexDiffuse.mMapName.length() > 0)
  270. CopyTexture(mat,oldMat.sTexDiffuse, aiTextureType_DIFFUSE);
  271. // SPECULAR texture
  272. if( oldMat.sTexSpecular.mMapName.length() > 0)
  273. CopyTexture(mat,oldMat.sTexSpecular, aiTextureType_SPECULAR);
  274. // OPACITY texture
  275. if( oldMat.sTexOpacity.mMapName.length() > 0)
  276. CopyTexture(mat,oldMat.sTexOpacity, aiTextureType_OPACITY);
  277. // EMISSIVE texture
  278. if( oldMat.sTexEmissive.mMapName.length() > 0)
  279. CopyTexture(mat,oldMat.sTexEmissive, aiTextureType_EMISSIVE);
  280. // BUMP texture
  281. if( oldMat.sTexBump.mMapName.length() > 0)
  282. CopyTexture(mat,oldMat.sTexBump, aiTextureType_HEIGHT);
  283. // SHININESS texture
  284. if( oldMat.sTexShininess.mMapName.length() > 0)
  285. CopyTexture(mat,oldMat.sTexShininess, aiTextureType_SHININESS);
  286. // REFLECTION texture
  287. if( oldMat.sTexReflective.mMapName.length() > 0)
  288. CopyTexture(mat,oldMat.sTexReflective, aiTextureType_REFLECTION);
  289. // Store the name of the material itself, too
  290. if( oldMat.mName.length()) {
  291. aiString tex;
  292. tex.Set( oldMat.mName);
  293. mat.AddProperty( &tex, AI_MATKEY_NAME);
  294. }
  295. }
  296. // ------------------------------------------------------------------------------------------------
  297. // Split meshes by their materials and generate output aiMesh'es
  298. void Discreet3DSImporter::ConvertMeshes(aiScene* pcOut)
  299. {
  300. std::vector<aiMesh*> avOutMeshes;
  301. avOutMeshes.reserve(mScene->mMeshes.size() * 2);
  302. unsigned int iFaceCnt = 0,num = 0;
  303. aiString name;
  304. // we need to split all meshes by their materials
  305. for (std::vector<D3DS::Mesh>::iterator i = mScene->mMeshes.begin(); i != mScene->mMeshes.end();++i) {
  306. std::unique_ptr< std::vector<unsigned int>[] > aiSplit(new std::vector<unsigned int>[mScene->mMaterials.size()]);
  307. name.length = ASSIMP_itoa10(name.data,num++);
  308. unsigned int iNum = 0;
  309. for (std::vector<unsigned int>::const_iterator a = (*i).mFaceMaterials.begin();
  310. a != (*i).mFaceMaterials.end();++a,++iNum)
  311. {
  312. aiSplit[*a].push_back(iNum);
  313. }
  314. // now generate submeshes
  315. for (unsigned int p = 0; p < mScene->mMaterials.size();++p)
  316. {
  317. if (aiSplit[p].empty()) {
  318. continue;
  319. }
  320. aiMesh* meshOut = new aiMesh();
  321. meshOut->mName = name;
  322. meshOut->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  323. // be sure to setup the correct material index
  324. meshOut->mMaterialIndex = p;
  325. // use the color data as temporary storage
  326. meshOut->mColors[0] = (aiColor4D*)(&*i);
  327. avOutMeshes.push_back(meshOut);
  328. // convert vertices
  329. meshOut->mNumFaces = (unsigned int)aiSplit[p].size();
  330. meshOut->mNumVertices = meshOut->mNumFaces*3;
  331. // allocate enough storage for faces
  332. meshOut->mFaces = new aiFace[meshOut->mNumFaces];
  333. iFaceCnt += meshOut->mNumFaces;
  334. meshOut->mVertices = new aiVector3D[meshOut->mNumVertices];
  335. meshOut->mNormals = new aiVector3D[meshOut->mNumVertices];
  336. if ((*i).mTexCoords.size())
  337. {
  338. meshOut->mTextureCoords[0] = new aiVector3D[meshOut->mNumVertices];
  339. }
  340. for (unsigned int q = 0, base = 0; q < aiSplit[p].size();++q)
  341. {
  342. unsigned int index = aiSplit[p][q];
  343. aiFace& face = meshOut->mFaces[q];
  344. face.mIndices = new unsigned int[3];
  345. face.mNumIndices = 3;
  346. for (unsigned int a = 0; a < 3;++a,++base)
  347. {
  348. unsigned int idx = (*i).mFaces[index].mIndices[a];
  349. meshOut->mVertices[base] = (*i).mPositions[idx];
  350. meshOut->mNormals [base] = (*i).mNormals[idx];
  351. if ((*i).mTexCoords.size())
  352. meshOut->mTextureCoords[0][base] = (*i).mTexCoords[idx];
  353. face.mIndices[a] = base;
  354. }
  355. }
  356. }
  357. }
  358. // Copy them to the output array
  359. pcOut->mNumMeshes = (unsigned int)avOutMeshes.size();
  360. pcOut->mMeshes = new aiMesh*[pcOut->mNumMeshes]();
  361. for (unsigned int a = 0; a < pcOut->mNumMeshes;++a) {
  362. pcOut->mMeshes[a] = avOutMeshes[a];
  363. }
  364. // We should have at least one face here
  365. if (!iFaceCnt) {
  366. throw DeadlyImportError("No faces loaded. The mesh is empty");
  367. }
  368. }
  369. // ------------------------------------------------------------------------------------------------
  370. // Add a node to the scenegraph and setup its final transformation
  371. void Discreet3DSImporter::AddNodeToGraph(aiScene* pcSOut,aiNode* pcOut,
  372. D3DS::Node* pcIn, aiMatrix4x4& /*absTrafo*/)
  373. {
  374. std::vector<unsigned int> iArray;
  375. iArray.reserve(3);
  376. aiMatrix4x4 abs;
  377. // Find all meshes with the same name as the node
  378. for (unsigned int a = 0; a < pcSOut->mNumMeshes;++a)
  379. {
  380. const D3DS::Mesh* pcMesh = (const D3DS::Mesh*)pcSOut->mMeshes[a]->mColors[0];
  381. ai_assert(NULL != pcMesh);
  382. if (pcIn->mName == pcMesh->mName)
  383. iArray.push_back(a);
  384. }
  385. if (!iArray.empty())
  386. {
  387. // The matrix should be identical for all meshes with the
  388. // same name. It HAS to be identical for all meshes .....
  389. D3DS::Mesh* imesh = ((D3DS::Mesh*)pcSOut->mMeshes[iArray[0]]->mColors[0]);
  390. // Compute the inverse of the transformation matrix to move the
  391. // vertices back to their relative and local space
  392. aiMatrix4x4 mInv = imesh->mMat, mInvTransposed = imesh->mMat;
  393. mInv.Inverse();mInvTransposed.Transpose();
  394. aiVector3D pivot = pcIn->vPivot;
  395. pcOut->mNumMeshes = (unsigned int)iArray.size();
  396. pcOut->mMeshes = new unsigned int[iArray.size()];
  397. for (unsigned int i = 0;i < iArray.size();++i) {
  398. const unsigned int iIndex = iArray[i];
  399. aiMesh* const mesh = pcSOut->mMeshes[iIndex];
  400. if (mesh->mColors[1] == NULL)
  401. {
  402. // Transform the vertices back into their local space
  403. // fixme: consider computing normals after this, so we don't need to transform them
  404. const aiVector3D* const pvEnd = mesh->mVertices + mesh->mNumVertices;
  405. aiVector3D* pvCurrent = mesh->mVertices, *t2 = mesh->mNormals;
  406. for (; pvCurrent != pvEnd; ++pvCurrent, ++t2) {
  407. *pvCurrent = mInv * (*pvCurrent);
  408. *t2 = mInvTransposed * (*t2);
  409. }
  410. // Handle negative transformation matrix determinant -> invert vertex x
  411. if (imesh->mMat.Determinant() < 0.0f)
  412. {
  413. /* we *must* have normals */
  414. for (pvCurrent = mesh->mVertices, t2 = mesh->mNormals; pvCurrent != pvEnd; ++pvCurrent, ++t2) {
  415. pvCurrent->x *= -1.f;
  416. t2->x *= -1.f;
  417. }
  418. DefaultLogger::get()->info("3DS: Flipping mesh X-Axis");
  419. }
  420. // Handle pivot point
  421. if (pivot.x || pivot.y || pivot.z)
  422. {
  423. for (pvCurrent = mesh->mVertices; pvCurrent != pvEnd; ++pvCurrent) {
  424. *pvCurrent -= pivot;
  425. }
  426. }
  427. mesh->mColors[1] = (aiColor4D*)1;
  428. }
  429. else
  430. mesh->mColors[1] = (aiColor4D*)1;
  431. // Setup the mesh index
  432. pcOut->mMeshes[i] = iIndex;
  433. }
  434. }
  435. // Setup the name of the node
  436. // First instance keeps its name otherwise something might break, all others will be postfixed with their instance number
  437. if (pcIn->mInstanceNumber > 1)
  438. {
  439. char tmp[12];
  440. ASSIMP_itoa10(tmp, pcIn->mInstanceNumber);
  441. std::string tempStr = pcIn->mName + "_inst_";
  442. tempStr += tmp;
  443. pcOut->mName.Set(tempStr);
  444. }
  445. else
  446. pcOut->mName.Set(pcIn->mName);
  447. // Now build the transformation matrix of the node
  448. // ROTATION
  449. if (pcIn->aRotationKeys.size()){
  450. // FIX to get to Assimp's quaternion conventions
  451. for (std::vector<aiQuatKey>::iterator it = pcIn->aRotationKeys.begin(); it != pcIn->aRotationKeys.end(); ++it) {
  452. (*it).mValue.w *= -1.f;
  453. }
  454. pcOut->mTransformation = aiMatrix4x4( pcIn->aRotationKeys[0].mValue.GetMatrix() );
  455. }
  456. else if (pcIn->aCameraRollKeys.size())
  457. {
  458. aiMatrix4x4::RotationZ(AI_DEG_TO_RAD(- pcIn->aCameraRollKeys[0].mValue),
  459. pcOut->mTransformation);
  460. }
  461. // SCALING
  462. aiMatrix4x4& m = pcOut->mTransformation;
  463. if (pcIn->aScalingKeys.size())
  464. {
  465. const aiVector3D& v = pcIn->aScalingKeys[0].mValue;
  466. m.a1 *= v.x; m.b1 *= v.x; m.c1 *= v.x;
  467. m.a2 *= v.y; m.b2 *= v.y; m.c2 *= v.y;
  468. m.a3 *= v.z; m.b3 *= v.z; m.c3 *= v.z;
  469. }
  470. // TRANSLATION
  471. if (pcIn->aPositionKeys.size())
  472. {
  473. const aiVector3D& v = pcIn->aPositionKeys[0].mValue;
  474. m.a4 += v.x;
  475. m.b4 += v.y;
  476. m.c4 += v.z;
  477. }
  478. // Generate animation channels for the node
  479. if (pcIn->aPositionKeys.size() > 1 || pcIn->aRotationKeys.size() > 1 ||
  480. pcIn->aScalingKeys.size() > 1 || pcIn->aCameraRollKeys.size() > 1 ||
  481. pcIn->aTargetPositionKeys.size() > 1)
  482. {
  483. aiAnimation* anim = pcSOut->mAnimations[0];
  484. ai_assert(NULL != anim);
  485. if (pcIn->aCameraRollKeys.size() > 1)
  486. {
  487. DefaultLogger::get()->debug("3DS: Converting camera roll track ...");
  488. // Camera roll keys - in fact they're just rotations
  489. // around the camera's z axis. The angles are given
  490. // in degrees (and they're clockwise).
  491. pcIn->aRotationKeys.resize(pcIn->aCameraRollKeys.size());
  492. for (unsigned int i = 0; i < pcIn->aCameraRollKeys.size();++i)
  493. {
  494. aiQuatKey& q = pcIn->aRotationKeys[i];
  495. aiFloatKey& f = pcIn->aCameraRollKeys[i];
  496. q.mTime = f.mTime;
  497. // FIX to get to Assimp quaternion conventions
  498. q.mValue = aiQuaternion(0.f,0.f,AI_DEG_TO_RAD( /*-*/ f.mValue));
  499. }
  500. }
  501. #if 0
  502. if (pcIn->aTargetPositionKeys.size() > 1)
  503. {
  504. DefaultLogger::get()->debug("3DS: Converting target track ...");
  505. // Camera or spot light - need to convert the separate
  506. // target position channel to our representation
  507. TargetAnimationHelper helper;
  508. if (pcIn->aPositionKeys.empty())
  509. {
  510. // We can just pass zero here ...
  511. helper.SetFixedMainAnimationChannel(aiVector3D());
  512. }
  513. else helper.SetMainAnimationChannel(&pcIn->aPositionKeys);
  514. helper.SetTargetAnimationChannel(&pcIn->aTargetPositionKeys);
  515. // Do the conversion
  516. std::vector<aiVectorKey> distanceTrack;
  517. helper.Process(&distanceTrack);
  518. // Now add a new node as child, name it <ourName>.Target
  519. // and assign the distance track to it. This is that the
  520. // information where the target is and how it moves is
  521. // not lost
  522. D3DS::Node* nd = new D3DS::Node();
  523. pcIn->push_back(nd);
  524. nd->mName = pcIn->mName + ".Target";
  525. aiNodeAnim* nda = anim->mChannels[anim->mNumChannels++] = new aiNodeAnim();
  526. nda->mNodeName.Set(nd->mName);
  527. nda->mNumPositionKeys = (unsigned int)distanceTrack.size();
  528. nda->mPositionKeys = new aiVectorKey[nda->mNumPositionKeys];
  529. ::memcpy(nda->mPositionKeys,&distanceTrack[0],
  530. sizeof(aiVectorKey)*nda->mNumPositionKeys);
  531. }
  532. #endif
  533. // Cameras or lights define their transformation in their parent node and in the
  534. // corresponding light or camera chunks. However, we read and process the latter
  535. // to to be able to return valid cameras/lights even if no scenegraph is given.
  536. for (unsigned int n = 0; n < pcSOut->mNumCameras;++n) {
  537. if (pcSOut->mCameras[n]->mName == pcOut->mName) {
  538. pcSOut->mCameras[n]->mLookAt = aiVector3D(0.f,0.f,1.f);
  539. }
  540. }
  541. for (unsigned int n = 0; n < pcSOut->mNumLights;++n) {
  542. if (pcSOut->mLights[n]->mName == pcOut->mName) {
  543. pcSOut->mLights[n]->mDirection = aiVector3D(0.f,0.f,1.f);
  544. }
  545. }
  546. // Allocate a new node anim and setup its name
  547. aiNodeAnim* nda = anim->mChannels[anim->mNumChannels++] = new aiNodeAnim();
  548. nda->mNodeName.Set(pcIn->mName);
  549. // POSITION keys
  550. if (pcIn->aPositionKeys.size() > 0)
  551. {
  552. nda->mNumPositionKeys = (unsigned int)pcIn->aPositionKeys.size();
  553. nda->mPositionKeys = new aiVectorKey[nda->mNumPositionKeys];
  554. ::memcpy(nda->mPositionKeys,&pcIn->aPositionKeys[0],
  555. sizeof(aiVectorKey)*nda->mNumPositionKeys);
  556. }
  557. // ROTATION keys
  558. if (pcIn->aRotationKeys.size() > 0)
  559. {
  560. nda->mNumRotationKeys = (unsigned int)pcIn->aRotationKeys.size();
  561. nda->mRotationKeys = new aiQuatKey[nda->mNumRotationKeys];
  562. // Rotations are quaternion offsets
  563. aiQuaternion abs1;
  564. for (unsigned int n = 0; n < nda->mNumRotationKeys;++n)
  565. {
  566. const aiQuatKey& q = pcIn->aRotationKeys[n];
  567. abs1 = (n ? abs1 * q.mValue : q.mValue);
  568. nda->mRotationKeys[n].mTime = q.mTime;
  569. nda->mRotationKeys[n].mValue = abs1.Normalize();
  570. }
  571. }
  572. // SCALING keys
  573. if (pcIn->aScalingKeys.size() > 0)
  574. {
  575. nda->mNumScalingKeys = (unsigned int)pcIn->aScalingKeys.size();
  576. nda->mScalingKeys = new aiVectorKey[nda->mNumScalingKeys];
  577. ::memcpy(nda->mScalingKeys,&pcIn->aScalingKeys[0],
  578. sizeof(aiVectorKey)*nda->mNumScalingKeys);
  579. }
  580. }
  581. // Allocate storage for children
  582. pcOut->mNumChildren = (unsigned int)pcIn->mChildren.size();
  583. pcOut->mChildren = new aiNode*[pcIn->mChildren.size()];
  584. // Recursively process all children
  585. const unsigned int size = static_cast<unsigned int>(pcIn->mChildren.size());
  586. for (unsigned int i = 0; i < size;++i)
  587. {
  588. pcOut->mChildren[i] = new aiNode();
  589. pcOut->mChildren[i]->mParent = pcOut;
  590. AddNodeToGraph(pcSOut,pcOut->mChildren[i],pcIn->mChildren[i],abs);
  591. }
  592. }
  593. // ------------------------------------------------------------------------------------------------
  594. // Find out how many node animation channels we'll have finally
  595. void CountTracks(D3DS::Node* node, unsigned int& cnt)
  596. {
  597. //////////////////////////////////////////////////////////////////////////////
  598. // We will never generate more than one channel for a node, so
  599. // this is rather easy here.
  600. if (node->aPositionKeys.size() > 1 || node->aRotationKeys.size() > 1 ||
  601. node->aScalingKeys.size() > 1 || node->aCameraRollKeys.size() > 1 ||
  602. node->aTargetPositionKeys.size() > 1)
  603. {
  604. ++cnt;
  605. // account for the additional channel for the camera/spotlight target position
  606. if (node->aTargetPositionKeys.size() > 1)++cnt;
  607. }
  608. // Recursively process all children
  609. for (unsigned int i = 0; i < node->mChildren.size();++i)
  610. CountTracks(node->mChildren[i],cnt);
  611. }
  612. // ------------------------------------------------------------------------------------------------
  613. // Generate the output node graph
  614. void Discreet3DSImporter::GenerateNodeGraph(aiScene* pcOut)
  615. {
  616. pcOut->mRootNode = new aiNode();
  617. if (0 == mRootNode->mChildren.size())
  618. {
  619. //////////////////////////////////////////////////////////////////////////////
  620. // It seems the file is so messed up that it has not even a hierarchy.
  621. // generate a flat hiearachy which looks like this:
  622. //
  623. // ROOT_NODE
  624. // |
  625. // ----------------------------------------
  626. // | | | | |
  627. // MESH_0 MESH_1 MESH_2 ... MESH_N CAMERA_0 ....
  628. //
  629. DefaultLogger::get()->warn("No hierarchy information has been found in the file. ");
  630. pcOut->mRootNode->mNumChildren = pcOut->mNumMeshes +
  631. static_cast<unsigned int>(mScene->mCameras.size() + mScene->mLights.size());
  632. pcOut->mRootNode->mChildren = new aiNode* [ pcOut->mRootNode->mNumChildren ];
  633. pcOut->mRootNode->mName.Set("<3DSDummyRoot>");
  634. // Build dummy nodes for all meshes
  635. unsigned int a = 0;
  636. for (unsigned int i = 0; i < pcOut->mNumMeshes;++i,++a)
  637. {
  638. aiNode* pcNode = pcOut->mRootNode->mChildren[a] = new aiNode();
  639. pcNode->mParent = pcOut->mRootNode;
  640. pcNode->mMeshes = new unsigned int[1];
  641. pcNode->mMeshes[0] = i;
  642. pcNode->mNumMeshes = 1;
  643. // Build a name for the node
  644. pcNode->mName.length = ai_snprintf(pcNode->mName.data, MAXLEN, "3DSMesh_%u",i);
  645. }
  646. // Build dummy nodes for all cameras
  647. for (unsigned int i = 0; i < (unsigned int )mScene->mCameras.size();++i,++a)
  648. {
  649. aiNode* pcNode = pcOut->mRootNode->mChildren[a] = new aiNode();
  650. pcNode->mParent = pcOut->mRootNode;
  651. // Build a name for the node
  652. pcNode->mName = mScene->mCameras[i]->mName;
  653. }
  654. // Build dummy nodes for all lights
  655. for (unsigned int i = 0; i < (unsigned int )mScene->mLights.size();++i,++a)
  656. {
  657. aiNode* pcNode = pcOut->mRootNode->mChildren[a] = new aiNode();
  658. pcNode->mParent = pcOut->mRootNode;
  659. // Build a name for the node
  660. pcNode->mName = mScene->mLights[i]->mName;
  661. }
  662. }
  663. else
  664. {
  665. // First of all: find out how many scaling, rotation and translation
  666. // animation tracks we'll have afterwards
  667. unsigned int numChannel = 0;
  668. CountTracks(mRootNode,numChannel);
  669. if (numChannel)
  670. {
  671. // Allocate a primary animation channel
  672. pcOut->mNumAnimations = 1;
  673. pcOut->mAnimations = new aiAnimation*[1];
  674. aiAnimation* anim = pcOut->mAnimations[0] = new aiAnimation();
  675. anim->mName.Set("3DSMasterAnim");
  676. // Allocate enough storage for all node animation channels,
  677. // but don't set the mNumChannels member - we'll use it to
  678. // index into the array
  679. anim->mChannels = new aiNodeAnim*[numChannel];
  680. }
  681. aiMatrix4x4 m;
  682. AddNodeToGraph(pcOut, pcOut->mRootNode, mRootNode,m);
  683. }
  684. // We used the first and second vertex color set to store some temporary values so we need to cleanup here
  685. for (unsigned int a = 0; a < pcOut->mNumMeshes; ++a)
  686. {
  687. pcOut->mMeshes[a]->mColors[0] = NULL;
  688. pcOut->mMeshes[a]->mColors[1] = NULL;
  689. }
  690. pcOut->mRootNode->mTransformation = aiMatrix4x4(
  691. 1.f,0.f,0.f,0.f,
  692. 0.f,0.f,1.f,0.f,
  693. 0.f,-1.f,0.f,0.f,
  694. 0.f,0.f,0.f,1.f) * pcOut->mRootNode->mTransformation;
  695. // If the root node is unnamed name it "<3DSRoot>"
  696. if (::strstr( pcOut->mRootNode->mName.data, "UNNAMED" ) ||
  697. (pcOut->mRootNode->mName.data[0] == '$' && pcOut->mRootNode->mName.data[1] == '$') )
  698. {
  699. pcOut->mRootNode->mName.Set("<3DSRoot>");
  700. }
  701. }
  702. // ------------------------------------------------------------------------------------------------
  703. // Convert all meshes in the scene and generate the final output scene.
  704. void Discreet3DSImporter::ConvertScene(aiScene* pcOut)
  705. {
  706. // Allocate enough storage for all output materials
  707. pcOut->mNumMaterials = (unsigned int)mScene->mMaterials.size();
  708. pcOut->mMaterials = new aiMaterial*[pcOut->mNumMaterials];
  709. // ... and convert the 3DS materials to aiMaterial's
  710. for (unsigned int i = 0; i < pcOut->mNumMaterials;++i)
  711. {
  712. aiMaterial* pcNew = new aiMaterial();
  713. ConvertMaterial(mScene->mMaterials[i],*pcNew);
  714. pcOut->mMaterials[i] = pcNew;
  715. }
  716. // Generate the output mesh list
  717. ConvertMeshes(pcOut);
  718. // Now copy all light sources to the output scene
  719. pcOut->mNumLights = (unsigned int)mScene->mLights.size();
  720. if (pcOut->mNumLights)
  721. {
  722. pcOut->mLights = new aiLight*[pcOut->mNumLights];
  723. ::memcpy(pcOut->mLights,&mScene->mLights[0],sizeof(void*)*pcOut->mNumLights);
  724. }
  725. // Now copy all cameras to the output scene
  726. pcOut->mNumCameras = (unsigned int)mScene->mCameras.size();
  727. if (pcOut->mNumCameras)
  728. {
  729. pcOut->mCameras = new aiCamera*[pcOut->mNumCameras];
  730. ::memcpy(pcOut->mCameras,&mScene->mCameras[0],sizeof(void*)*pcOut->mNumCameras);
  731. }
  732. }
  733. #endif // !! ASSIMP_BUILD_NO_3DS_IMPORTER