2
0

3DSConverter.cpp 32 KB

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