3DSConverter.cpp 28 KB

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