3DSConverter.cpp 31 KB

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