PretransformVertices.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2024, 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 PretransformVertices.cpp
  35. /// @brief Implementation of the "PretransformVertices" post processing step
  36. #include "PretransformVertices.h"
  37. #include "ConvertToLHProcess.h"
  38. #include "ProcessHelper.h"
  39. #include <assimp/Exceptional.h>
  40. #include <assimp/SceneCombiner.h>
  41. using namespace Assimp;
  42. // some array offsets
  43. #define AI_PTVS_VERTEX 0x0
  44. #define AI_PTVS_FACE 0x1
  45. namespace {
  46. // Get a bitwise combination identifying the vertex format of a mesh
  47. static unsigned int GetMeshVFormat(aiMesh *pcMesh) {
  48. // the vertex format is stored in aiMesh::mBones for later retrieval.
  49. // there isn't a good reason to compute it a few hundred times
  50. // from scratch. The pointer is unused as animations are lost
  51. // during PretransformVertices.
  52. if (pcMesh->mBones)
  53. return (unsigned int)(uint64_t)pcMesh->mBones;
  54. const unsigned int iRet = GetMeshVFormatUnique(pcMesh);
  55. // store the value for later use
  56. pcMesh->mBones = (aiBone **)(uint64_t)iRet;
  57. return iRet;
  58. }
  59. // Get a list of all vertex formats that occur for a given material index
  60. // The output list contains duplicate elements
  61. static void GetVFormatList(const aiScene *pcScene, unsigned int iMat, std::list<unsigned int> &aiOut) {
  62. for (unsigned int i = 0; i < pcScene->mNumMeshes; ++i) {
  63. aiMesh *pcMesh = pcScene->mMeshes[i];
  64. if (iMat == pcMesh->mMaterialIndex) {
  65. aiOut.push_back(GetMeshVFormat(pcMesh));
  66. }
  67. }
  68. }
  69. }
  70. // ------------------------------------------------------------------------------------------------
  71. // Constructor to be privately used by Importer
  72. PretransformVertices::PretransformVertices() :
  73. mConfigKeepHierarchy(false),
  74. mConfigNormalize(false),
  75. mConfigTransform(false),
  76. mConfigTransformation(),
  77. mConfigPointCloud(false) {}
  78. // ------------------------------------------------------------------------------------------------
  79. // Returns whether the processing step is present in the given flag field.
  80. bool PretransformVertices::IsActive(unsigned int pFlags) const {
  81. return (pFlags & aiProcess_PreTransformVertices) != 0;
  82. }
  83. // ------------------------------------------------------------------------------------------------
  84. // Setup import configuration
  85. void PretransformVertices::SetupProperties(const Importer *pImp) {
  86. // Get the current value of AI_CONFIG_PP_PTV_KEEP_HIERARCHY, AI_CONFIG_PP_PTV_NORMALIZE,
  87. // AI_CONFIG_PP_PTV_ADD_ROOT_TRANSFORMATION and AI_CONFIG_PP_PTV_ROOT_TRANSFORMATION
  88. mConfigKeepHierarchy = (0 != pImp->GetPropertyInteger(AI_CONFIG_PP_PTV_KEEP_HIERARCHY, 0));
  89. mConfigNormalize = (0 != pImp->GetPropertyInteger(AI_CONFIG_PP_PTV_NORMALIZE, 0));
  90. mConfigTransform = (0 != pImp->GetPropertyInteger(AI_CONFIG_PP_PTV_ADD_ROOT_TRANSFORMATION, 0));
  91. mConfigTransformation = pImp->GetPropertyMatrix(AI_CONFIG_PP_PTV_ROOT_TRANSFORMATION, aiMatrix4x4());
  92. mConfigPointCloud = pImp->GetPropertyBool(AI_CONFIG_EXPORT_POINT_CLOUDS);
  93. }
  94. // ------------------------------------------------------------------------------------------------
  95. // Count the number of nodes
  96. unsigned int PretransformVertices::CountNodes(const aiNode *pcNode) const {
  97. unsigned int iRet = 1;
  98. for (unsigned int i = 0; i < pcNode->mNumChildren; ++i) {
  99. iRet += CountNodes(pcNode->mChildren[i]);
  100. }
  101. return iRet;
  102. }
  103. // ------------------------------------------------------------------------------------------------
  104. // Count the number of vertices in the whole scene and a given material index
  105. void PretransformVertices::CountVerticesAndFaces(const aiScene *pcScene, const aiNode *pcNode, unsigned int iMat,
  106. unsigned int iVFormat, unsigned int *piFaces, unsigned int *piVertices) const {
  107. for (unsigned int i = 0; i < pcNode->mNumMeshes; ++i) {
  108. aiMesh *pcMesh = pcScene->mMeshes[pcNode->mMeshes[i]];
  109. if (iMat == pcMesh->mMaterialIndex && iVFormat == GetMeshVFormat(pcMesh)) {
  110. *piVertices += pcMesh->mNumVertices;
  111. *piFaces += pcMesh->mNumFaces;
  112. }
  113. }
  114. for (unsigned int i = 0; i < pcNode->mNumChildren; ++i) {
  115. CountVerticesAndFaces(pcScene, pcNode->mChildren[i], iMat, iVFormat, piFaces, piVertices);
  116. }
  117. }
  118. // ------------------------------------------------------------------------------------------------
  119. // Collect vertex/face data
  120. void PretransformVertices::CollectData(const aiScene *pcScene, const aiNode *pcNode, unsigned int iMat,
  121. unsigned int iVFormat, aiMesh *pcMeshOut,
  122. unsigned int aiCurrent[2], unsigned int *num_refs) const {
  123. // No need to multiply if there's no transformation
  124. const bool identity = pcNode->mTransformation.IsIdentity();
  125. for (unsigned int i = 0; i < pcNode->mNumMeshes; ++i) {
  126. aiMesh *pcMesh = pcScene->mMeshes[pcNode->mMeshes[i]];
  127. if (iMat == pcMesh->mMaterialIndex && iVFormat == GetMeshVFormat(pcMesh)) {
  128. // Decrement mesh reference counter
  129. unsigned int &num_ref = num_refs[pcNode->mMeshes[i]];
  130. ai_assert(0 != num_ref);
  131. --num_ref;
  132. // Save the name of the last mesh
  133. if (num_ref == 0) {
  134. pcMeshOut->mName = pcMesh->mName;
  135. }
  136. if (identity) {
  137. // copy positions without modifying them
  138. ::memcpy(pcMeshOut->mVertices + aiCurrent[AI_PTVS_VERTEX],
  139. pcMesh->mVertices,
  140. pcMesh->mNumVertices * sizeof(aiVector3D));
  141. if (iVFormat & 0x2) {
  142. // copy normals without modifying them
  143. ::memcpy(pcMeshOut->mNormals + aiCurrent[AI_PTVS_VERTEX],
  144. pcMesh->mNormals,
  145. pcMesh->mNumVertices * sizeof(aiVector3D));
  146. }
  147. if (iVFormat & 0x4) {
  148. // copy tangents without modifying them
  149. ::memcpy(pcMeshOut->mTangents + aiCurrent[AI_PTVS_VERTEX],
  150. pcMesh->mTangents,
  151. pcMesh->mNumVertices * sizeof(aiVector3D));
  152. // copy bitangents without modifying them
  153. ::memcpy(pcMeshOut->mBitangents + aiCurrent[AI_PTVS_VERTEX],
  154. pcMesh->mBitangents,
  155. pcMesh->mNumVertices * sizeof(aiVector3D));
  156. }
  157. } else {
  158. // copy positions, transform them to worldspace
  159. for (unsigned int n = 0; n < pcMesh->mNumVertices; ++n) {
  160. pcMeshOut->mVertices[aiCurrent[AI_PTVS_VERTEX] + n] = pcNode->mTransformation * pcMesh->mVertices[n];
  161. }
  162. aiMatrix4x4 mWorldIT = pcNode->mTransformation;
  163. mWorldIT.Inverse().Transpose();
  164. // TODO: implement Inverse() for aiMatrix3x3
  165. aiMatrix3x3 m = aiMatrix3x3(mWorldIT);
  166. if (iVFormat & 0x2) {
  167. // copy normals, transform them to worldspace
  168. for (unsigned int n = 0; n < pcMesh->mNumVertices; ++n) {
  169. pcMeshOut->mNormals[aiCurrent[AI_PTVS_VERTEX] + n] =
  170. (m * pcMesh->mNormals[n]).Normalize();
  171. }
  172. }
  173. if (iVFormat & 0x4) {
  174. // copy tangents and bitangents, transform them to worldspace
  175. for (unsigned int n = 0; n < pcMesh->mNumVertices; ++n) {
  176. pcMeshOut->mTangents[aiCurrent[AI_PTVS_VERTEX] + n] = (m * pcMesh->mTangents[n]).Normalize();
  177. pcMeshOut->mBitangents[aiCurrent[AI_PTVS_VERTEX] + n] = (m * pcMesh->mBitangents[n]).Normalize();
  178. }
  179. }
  180. }
  181. unsigned int p = 0;
  182. while (iVFormat & (0x100 << p)) {
  183. // copy texture coordinates
  184. memcpy(pcMeshOut->mTextureCoords[p] + aiCurrent[AI_PTVS_VERTEX],
  185. pcMesh->mTextureCoords[p],
  186. pcMesh->mNumVertices * sizeof(aiVector3D));
  187. ++p;
  188. }
  189. p = 0;
  190. while (iVFormat & (0x1000000 << p)) {
  191. // copy vertex colors
  192. memcpy(pcMeshOut->mColors[p] + aiCurrent[AI_PTVS_VERTEX],
  193. pcMesh->mColors[p],
  194. pcMesh->mNumVertices * sizeof(aiColor4D));
  195. ++p;
  196. }
  197. // now we need to copy all faces. since we will delete the source mesh afterwards,
  198. // we don't need to reallocate the array of indices except if this mesh is
  199. // referenced multiple times.
  200. for (unsigned int planck = 0; planck < pcMesh->mNumFaces; ++planck) {
  201. aiFace &f_src = pcMesh->mFaces[planck];
  202. aiFace &f_dst = pcMeshOut->mFaces[aiCurrent[AI_PTVS_FACE] + planck];
  203. const unsigned int num_idx = f_src.mNumIndices;
  204. f_dst.mNumIndices = num_idx;
  205. unsigned int *pi;
  206. if (!num_ref) { /* if last time the mesh is referenced -> no reallocation */
  207. pi = f_dst.mIndices = f_src.mIndices;
  208. // offset all vertex indices
  209. for (unsigned int hahn = 0; hahn < num_idx; ++hahn) {
  210. pi[hahn] += aiCurrent[AI_PTVS_VERTEX];
  211. }
  212. } else {
  213. pi = f_dst.mIndices = new unsigned int[num_idx];
  214. // copy and offset all vertex indices
  215. for (unsigned int hahn = 0; hahn < num_idx; ++hahn) {
  216. pi[hahn] = f_src.mIndices[hahn] + aiCurrent[AI_PTVS_VERTEX];
  217. }
  218. }
  219. // Update the mPrimitiveTypes member of the mesh
  220. switch (pcMesh->mFaces[planck].mNumIndices) {
  221. case 0x1:
  222. pcMeshOut->mPrimitiveTypes |= aiPrimitiveType_POINT;
  223. break;
  224. case 0x2:
  225. pcMeshOut->mPrimitiveTypes |= aiPrimitiveType_LINE;
  226. break;
  227. case 0x3:
  228. pcMeshOut->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  229. break;
  230. default:
  231. pcMeshOut->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  232. break;
  233. };
  234. }
  235. aiCurrent[AI_PTVS_VERTEX] += pcMesh->mNumVertices;
  236. aiCurrent[AI_PTVS_FACE] += pcMesh->mNumFaces;
  237. }
  238. }
  239. // append all children of us
  240. for (unsigned int i = 0; i < pcNode->mNumChildren; ++i) {
  241. CollectData(pcScene, pcNode->mChildren[i], iMat,
  242. iVFormat, pcMeshOut, aiCurrent, num_refs);
  243. }
  244. }
  245. // ------------------------------------------------------------------------------------------------
  246. // Compute the absolute transformation matrices of each node
  247. void PretransformVertices::ComputeAbsoluteTransform(aiNode *pcNode) {
  248. if (pcNode->mParent) {
  249. pcNode->mTransformation = pcNode->mParent->mTransformation * pcNode->mTransformation;
  250. }
  251. for (unsigned int i = 0; i < pcNode->mNumChildren; ++i) {
  252. ComputeAbsoluteTransform(pcNode->mChildren[i]);
  253. }
  254. }
  255. // ------------------------------------------------------------------------------------------------
  256. // Apply the node transformation to a mesh
  257. void PretransformVertices::ApplyTransform(aiMesh *mesh, const aiMatrix4x4 &mat) const {
  258. // Check whether we need to transform the coordinates at all
  259. if (mat.IsIdentity()) {
  260. return;
  261. }
  262. // Check for odd negative scale (mirror)
  263. if (mesh->HasFaces() && mat.Determinant() < 0) {
  264. // Reverse the mesh face winding order
  265. FlipWindingOrderProcess::ProcessMesh(mesh);
  266. }
  267. // Update positions
  268. if (mesh->HasPositions()) {
  269. for (unsigned int i = 0; i < mesh->mNumVertices; ++i) {
  270. mesh->mVertices[i] = mat * mesh->mVertices[i];
  271. }
  272. }
  273. // Update normals and tangents
  274. if (mesh->HasNormals() || mesh->HasTangentsAndBitangents()) {
  275. const aiMatrix3x3 m = aiMatrix3x3(mat).Inverse().Transpose();
  276. if (mesh->HasNormals()) {
  277. for (unsigned int i = 0; i < mesh->mNumVertices; ++i) {
  278. mesh->mNormals[i] = (m * mesh->mNormals[i]).Normalize();
  279. }
  280. }
  281. if (mesh->HasTangentsAndBitangents()) {
  282. for (unsigned int i = 0; i < mesh->mNumVertices; ++i) {
  283. mesh->mTangents[i] = (m * mesh->mTangents[i]).Normalize();
  284. mesh->mBitangents[i] = (m * mesh->mBitangents[i]).Normalize();
  285. }
  286. }
  287. }
  288. }
  289. // ------------------------------------------------------------------------------------------------
  290. // Simple routine to build meshes in worldspace, no further optimization
  291. void PretransformVertices::BuildWCSMeshes(std::vector<aiMesh *> &out, aiMesh **in,
  292. unsigned int numIn, aiNode *node) const {
  293. // NOTE:
  294. // aiMesh::mNumBones store original source mesh, or UINT_MAX if not a copy
  295. // aiMesh::mBones store reference to abs. transform we multiplied with
  296. // process meshes
  297. for (unsigned int i = 0; i < node->mNumMeshes; ++i) {
  298. aiMesh *mesh = in[node->mMeshes[i]];
  299. // check whether we can operate on this mesh
  300. if (!mesh->mBones || *reinterpret_cast<aiMatrix4x4 *>(mesh->mBones) == node->mTransformation) {
  301. // yes, we can.
  302. mesh->mBones = reinterpret_cast<aiBone **>(&node->mTransformation);
  303. mesh->mNumBones = UINT_MAX;
  304. continue;
  305. }
  306. // try to find us in the list of newly created meshes
  307. for (unsigned int n = 0; n < out.size(); ++n) {
  308. aiMesh *ctz = out[n];
  309. if (ctz->mNumBones == node->mMeshes[i] && *reinterpret_cast<aiMatrix4x4 *>(ctz->mBones) == node->mTransformation) {
  310. // ok, use this one. Update node mesh index
  311. node->mMeshes[i] = numIn + n;
  312. }
  313. }
  314. if (node->mMeshes[i] < numIn) {
  315. // Worst case. Need to operate on a full copy of the mesh
  316. ASSIMP_LOG_INFO("PretransformVertices: Copying mesh due to mismatching transforms");
  317. aiMesh *ntz;
  318. const unsigned int cacheNumBones = mesh->mNumBones; //
  319. mesh->mNumBones = 0;
  320. SceneCombiner::Copy(&ntz, mesh);
  321. mesh->mNumBones = cacheNumBones;
  322. ntz->mNumBones = node->mMeshes[i];
  323. ntz->mBones = reinterpret_cast<aiBone **>(&node->mTransformation);
  324. out.push_back(ntz);
  325. node->mMeshes[i] = static_cast<unsigned int>(numIn + out.size() - 1);
  326. }
  327. }
  328. // call children
  329. for (unsigned int i = 0; i < node->mNumChildren; ++i) {
  330. BuildWCSMeshes(out, in, numIn, node->mChildren[i]);
  331. }
  332. }
  333. // ------------------------------------------------------------------------------------------------
  334. // Reset transformation matrices to identity
  335. void PretransformVertices::MakeIdentityTransform(aiNode *nd) const {
  336. nd->mTransformation = aiMatrix4x4();
  337. // call children
  338. for (unsigned int i = 0; i < nd->mNumChildren; ++i) {
  339. MakeIdentityTransform(nd->mChildren[i]);
  340. }
  341. }
  342. // ------------------------------------------------------------------------------------------------
  343. // Build reference counters for all meshes
  344. void PretransformVertices::BuildMeshRefCountArray(const aiNode *nd, unsigned int *refs) const {
  345. for (unsigned int i = 0; i < nd->mNumMeshes; ++i)
  346. refs[nd->mMeshes[i]]++;
  347. // call children
  348. for (unsigned int i = 0; i < nd->mNumChildren; ++i) {
  349. BuildMeshRefCountArray(nd->mChildren[i], refs);
  350. }
  351. }
  352. // ------------------------------------------------------------------------------------------------
  353. static void appendNewMeshesToScene(aiScene *pScene, std::vector<aiMesh*> &apcOutMeshes) {
  354. ai_assert(pScene != nullptr);
  355. if (apcOutMeshes.empty()) {
  356. return;
  357. }
  358. aiMesh **npp = new aiMesh *[pScene->mNumMeshes + apcOutMeshes.size()];
  359. ::memcpy(npp, pScene->mMeshes, sizeof(aiMesh *) * pScene->mNumMeshes);
  360. ::memcpy(npp + pScene->mNumMeshes, &apcOutMeshes[0], sizeof(aiMesh *) * apcOutMeshes.size());
  361. pScene->mNumMeshes += static_cast<unsigned int>(apcOutMeshes.size());
  362. delete[] pScene->mMeshes;
  363. pScene->mMeshes = npp;
  364. }
  365. // ------------------------------------------------------------------------------------------------
  366. // Executes the post processing step on the given imported data.
  367. void PretransformVertices::Execute(aiScene *pScene) {
  368. ASSIMP_LOG_DEBUG("PretransformVerticesProcess begin");
  369. // Return immediately if we have no meshes
  370. if (!pScene->mNumMeshes)
  371. return;
  372. const unsigned int oldMeshes = pScene->mNumMeshes;
  373. const unsigned int oldAnimationChannels = pScene->mNumAnimations;
  374. const unsigned int oldNodes = CountNodes(pScene->mRootNode);
  375. if (mConfigTransform) {
  376. pScene->mRootNode->mTransformation = mConfigTransformation * pScene->mRootNode->mTransformation;
  377. }
  378. // first compute absolute transformation matrices for all nodes
  379. ComputeAbsoluteTransform(pScene->mRootNode);
  380. // Delete aiMesh::mBones for all meshes. The bones are
  381. // removed during this step and we need the pointer as
  382. // temporary storage
  383. for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) {
  384. aiMesh *mesh = pScene->mMeshes[i];
  385. for (unsigned int a = 0; a < mesh->mNumBones; ++a)
  386. delete mesh->mBones[a];
  387. delete[] mesh->mBones;
  388. mesh->mBones = nullptr;
  389. }
  390. // now build a list of output meshes
  391. std::vector<aiMesh *> apcOutMeshes;
  392. // Keep scene hierarchy? It's an easy job in this case ...
  393. // we go on and transform all meshes, if one is referenced by nodes
  394. // with different absolute transformations a depth copy of the mesh
  395. // is required.
  396. if (mConfigKeepHierarchy) {
  397. // Hack: store the matrix we're transforming a mesh with in aiMesh::mBones
  398. BuildWCSMeshes(apcOutMeshes, pScene->mMeshes, pScene->mNumMeshes, pScene->mRootNode);
  399. // ... if new meshes have been generated, append them to the end of the scene
  400. appendNewMeshesToScene(pScene, apcOutMeshes);
  401. // now iterate through all meshes and transform them to world-space
  402. for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) {
  403. ApplyTransform(pScene->mMeshes[i], *reinterpret_cast<aiMatrix4x4 *>(pScene->mMeshes[i]->mBones));
  404. // prevent improper destruction
  405. pScene->mMeshes[i]->mBones = nullptr;
  406. pScene->mMeshes[i]->mNumBones = 0;
  407. }
  408. } else {
  409. apcOutMeshes.reserve(static_cast<size_t>(pScene->mNumMaterials) << 1u);
  410. std::list<unsigned int> aiVFormats;
  411. std::vector<unsigned int> s(pScene->mNumMeshes, 0);
  412. BuildMeshRefCountArray(pScene->mRootNode, &s[0]);
  413. for (unsigned int i = 0; i < pScene->mNumMaterials; ++i) {
  414. // get the list of all vertex formats for this material
  415. aiVFormats.clear();
  416. GetVFormatList(pScene, i, aiVFormats);
  417. aiVFormats.sort();
  418. aiVFormats.unique();
  419. for (std::list<unsigned int>::const_iterator j = aiVFormats.begin(); j != aiVFormats.end(); ++j) {
  420. unsigned int numVertices = 0u;
  421. unsigned int numFaces = 0u;
  422. CountVerticesAndFaces(pScene, pScene->mRootNode, i, *j, &numFaces, &numVertices);
  423. if (0 != numFaces && 0 != numVertices) {
  424. apcOutMeshes.push_back(new aiMesh());
  425. aiMesh *pcMesh = apcOutMeshes.back();
  426. pcMesh->mNumFaces = numFaces;
  427. pcMesh->mNumVertices = numVertices;
  428. pcMesh->mFaces = new aiFace[numFaces];
  429. pcMesh->mVertices = new aiVector3D[numVertices];
  430. pcMesh->mMaterialIndex = i;
  431. if ((*j) & 0x2) pcMesh->mNormals = new aiVector3D[numVertices];
  432. if ((*j) & 0x4) {
  433. pcMesh->mTangents = new aiVector3D[numVertices];
  434. pcMesh->mBitangents = new aiVector3D[numVertices];
  435. }
  436. numFaces = 0;
  437. while ((*j) & (0x100 << numFaces)) {
  438. pcMesh->mTextureCoords[numFaces] = new aiVector3D[numVertices];
  439. if ((*j) & (0x10000 << numFaces)) {
  440. pcMesh->mNumUVComponents[numFaces] = 3;
  441. } else {
  442. pcMesh->mNumUVComponents[numFaces] = 2;
  443. }
  444. ++numFaces;
  445. }
  446. numFaces = 0;
  447. while ((*j) & (0x1000000 << numFaces))
  448. pcMesh->mColors[numFaces++] = new aiColor4D[numVertices];
  449. // fill the mesh ...
  450. unsigned int aiTemp[2] = { 0, 0 };
  451. CollectData(pScene, pScene->mRootNode, i, *j, pcMesh, aiTemp, &s[0]);
  452. }
  453. }
  454. }
  455. // If no meshes are referenced in the node graph it is possible that we get no output meshes.
  456. if (apcOutMeshes.empty()) {
  457. throw DeadlyImportError("No output meshes: all meshes are orphaned and are not referenced by any nodes");
  458. } else {
  459. // now delete all meshes in the scene and build a new mesh list
  460. for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) {
  461. aiMesh *mesh = pScene->mMeshes[i];
  462. mesh->mNumBones = 0;
  463. mesh->mBones = nullptr;
  464. // we're reusing the face index arrays. avoid destruction
  465. for (unsigned int a = 0; a < mesh->mNumFaces; ++a) {
  466. mesh->mFaces[a].mNumIndices = 0;
  467. mesh->mFaces[a].mIndices = nullptr;
  468. }
  469. delete mesh;
  470. // Invalidate the contents of the old mesh array. We will most
  471. // likely have less output meshes now, so the last entries of
  472. // the mesh array are not overridden. We set them to nullptr to
  473. // make sure the developer gets notified when his application
  474. // attempts to access these fields ...
  475. mesh = nullptr;
  476. }
  477. // It is impossible that we have more output meshes than
  478. // input meshes, so we can easily reuse the old mesh array
  479. pScene->mNumMeshes = (unsigned int)apcOutMeshes.size();
  480. for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) {
  481. pScene->mMeshes[i] = apcOutMeshes[i];
  482. }
  483. }
  484. }
  485. // remove all animations from the scene
  486. for (unsigned int i = 0; i < pScene->mNumAnimations; ++i)
  487. delete pScene->mAnimations[i];
  488. delete[] pScene->mAnimations;
  489. pScene->mAnimations = nullptr;
  490. pScene->mNumAnimations = 0;
  491. // --- we need to keep all cameras and lights
  492. for (unsigned int i = 0; i < pScene->mNumCameras; ++i) {
  493. aiCamera *cam = pScene->mCameras[i];
  494. const aiNode *nd = pScene->mRootNode->FindNode(cam->mName);
  495. ai_assert(nullptr != nd);
  496. // multiply all properties of the camera with the absolute
  497. // transformation of the corresponding node
  498. cam->mPosition = nd->mTransformation * cam->mPosition;
  499. cam->mLookAt = nd->mTransformation * cam->mLookAt;
  500. cam->mUp = aiMatrix3x3(nd->mTransformation) * cam->mUp;
  501. }
  502. for (unsigned int i = 0; i < pScene->mNumLights; ++i) {
  503. aiLight *l = pScene->mLights[i];
  504. const aiNode *nd = pScene->mRootNode->FindNode(l->mName);
  505. ai_assert(nullptr != nd);
  506. // multiply all properties of the camera with the absolute
  507. // transformation of the corresponding node
  508. l->mPosition = nd->mTransformation * l->mPosition;
  509. l->mDirection = aiMatrix3x3(nd->mTransformation) * l->mDirection;
  510. l->mUp = aiMatrix3x3(nd->mTransformation) * l->mUp;
  511. }
  512. if (!mConfigKeepHierarchy) {
  513. // now delete all nodes in the scene and build a new
  514. // flat node graph with a root node and some level 1 children
  515. aiNode *newRoot = new aiNode();
  516. newRoot->mName = pScene->mRootNode->mName;
  517. delete pScene->mRootNode;
  518. pScene->mRootNode = newRoot;
  519. if (1 == pScene->mNumMeshes && !pScene->mNumLights && !pScene->mNumCameras) {
  520. pScene->mRootNode->mNumMeshes = 1;
  521. pScene->mRootNode->mMeshes = new unsigned int[1];
  522. pScene->mRootNode->mMeshes[0] = 0;
  523. } else {
  524. pScene->mRootNode->mNumChildren = pScene->mNumMeshes + pScene->mNumLights + pScene->mNumCameras;
  525. aiNode **nodes = pScene->mRootNode->mChildren = new aiNode *[pScene->mRootNode->mNumChildren];
  526. // generate mesh nodes
  527. for (unsigned int i = 0; i < pScene->mNumMeshes; ++i, ++nodes) {
  528. aiNode *pcNode = new aiNode();
  529. *nodes = pcNode;
  530. pcNode->mParent = pScene->mRootNode;
  531. pcNode->mName = pScene->mMeshes[i]->mName;
  532. // setup mesh indices
  533. pcNode->mNumMeshes = 1;
  534. pcNode->mMeshes = new unsigned int[1];
  535. pcNode->mMeshes[0] = i;
  536. }
  537. // generate light nodes
  538. for (unsigned int i = 0; i < pScene->mNumLights; ++i, ++nodes) {
  539. aiNode *pcNode = new aiNode();
  540. *nodes = pcNode;
  541. pcNode->mParent = pScene->mRootNode;
  542. pcNode->mName.length = ai_snprintf(pcNode->mName.data, MAXLEN, "light_%u", i);
  543. pScene->mLights[i]->mName = pcNode->mName;
  544. }
  545. // generate camera nodes
  546. for (unsigned int i = 0; i < pScene->mNumCameras; ++i, ++nodes) {
  547. aiNode *pcNode = new aiNode();
  548. *nodes = pcNode;
  549. pcNode->mParent = pScene->mRootNode;
  550. pcNode->mName.length = ::ai_snprintf(pcNode->mName.data, MAXLEN, "cam_%u", i);
  551. pScene->mCameras[i]->mName = pcNode->mName;
  552. }
  553. }
  554. } else {
  555. // ... and finally set the transformation matrix of all nodes to identity
  556. MakeIdentityTransform(pScene->mRootNode);
  557. }
  558. if (mConfigNormalize) {
  559. // compute the boundary of all meshes
  560. aiVector3D min, max;
  561. MinMaxChooser<aiVector3D>()(min, max);
  562. for (unsigned int a = 0; a < pScene->mNumMeshes; ++a) {
  563. aiMesh *m = pScene->mMeshes[a];
  564. for (unsigned int i = 0; i < m->mNumVertices; ++i) {
  565. min = std::min(m->mVertices[i], min);
  566. max = std::max(m->mVertices[i], max);
  567. }
  568. }
  569. // find the dominant axis
  570. aiVector3D d = max - min;
  571. const ai_real div = std::max(d.x, std::max(d.y, d.z)) * ai_real(0.5);
  572. d = min + d * (ai_real)0.5;
  573. for (unsigned int a = 0; a < pScene->mNumMeshes; ++a) {
  574. aiMesh *m = pScene->mMeshes[a];
  575. for (unsigned int i = 0; i < m->mNumVertices; ++i) {
  576. m->mVertices[i] = (m->mVertices[i] - d) / div;
  577. }
  578. }
  579. }
  580. // print statistics
  581. if (!DefaultLogger::isNullLogger()) {
  582. ASSIMP_LOG_DEBUG("PretransformVerticesProcess finished");
  583. ASSIMP_LOG_INFO("Removed ", oldNodes, " nodes and ", oldAnimationChannels, " animation channels (",
  584. CountNodes(pScene->mRootNode), " output nodes)");
  585. ASSIMP_LOG_INFO("Kept ", pScene->mNumLights, " lights and ", pScene->mNumCameras, " cameras.");
  586. ASSIMP_LOG_INFO("Moved ", oldMeshes, " meshes to WCS (number of output meshes: ", pScene->mNumMeshes, ")");
  587. }
  588. }