3DSConverter.cpp 31 KB

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