JoinVerticesProcess.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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 Implementation of the post processing step to join identical vertices
  35. * for all imported meshes
  36. */
  37. #ifndef ASSIMP_BUILD_NO_JOINVERTICES_PROCESS
  38. #include "JoinVerticesProcess.h"
  39. #include "ProcessHelper.h"
  40. #include <assimp/Vertex.h>
  41. #include <assimp/TinyFormatter.h>
  42. #include <stdio.h>
  43. #include <unordered_set>
  44. #include <unordered_map>
  45. #include <memory>
  46. using namespace Assimp;
  47. // ------------------------------------------------------------------------------------------------
  48. // Returns whether the processing step is present in the given flag field.
  49. bool JoinVerticesProcess::IsActive( unsigned int pFlags) const {
  50. return (pFlags & aiProcess_JoinIdenticalVertices) != 0;
  51. }
  52. // ------------------------------------------------------------------------------------------------
  53. // Executes the post processing step on the given imported data.
  54. void JoinVerticesProcess::Execute( aiScene* pScene) {
  55. ASSIMP_LOG_DEBUG("JoinVerticesProcess begin");
  56. // get the total number of vertices BEFORE the step is executed
  57. int iNumOldVertices = 0;
  58. if (!DefaultLogger::isNullLogger()) {
  59. for( unsigned int a = 0; a < pScene->mNumMeshes; a++) {
  60. iNumOldVertices += pScene->mMeshes[a]->mNumVertices;
  61. }
  62. }
  63. // execute the step
  64. int iNumVertices = 0;
  65. for( unsigned int a = 0; a < pScene->mNumMeshes; a++) {
  66. iNumVertices += ProcessMesh( pScene->mMeshes[a],a);
  67. }
  68. pScene->mFlags |= AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;
  69. // if logging is active, print detailed statistics
  70. if (!DefaultLogger::isNullLogger()) {
  71. if (iNumOldVertices == iNumVertices) {
  72. ASSIMP_LOG_DEBUG("JoinVerticesProcess finished ");
  73. return;
  74. }
  75. // Show statistics
  76. ASSIMP_LOG_INFO("JoinVerticesProcess finished | Verts in: ", iNumOldVertices,
  77. " out: ", iNumVertices, " | ~",
  78. ((iNumOldVertices - iNumVertices) / (float)iNumOldVertices) * 100.f );
  79. }
  80. }
  81. namespace {
  82. bool areVerticesEqual(
  83. const Vertex &lhs,
  84. const Vertex &rhs,
  85. unsigned numUVChannels,
  86. unsigned numColorChannels) {
  87. // A little helper to find locally close vertices faster.
  88. // Try to reuse the lookup table from the last step.
  89. const static float epsilon = 1e-5f;
  90. // Squared because we check against squared length of the vector difference
  91. static const float squareEpsilon = epsilon * epsilon;
  92. // Square compare is useful for animeshes vertices compare
  93. if ((lhs.position - rhs.position).SquareLength() > squareEpsilon) {
  94. return false;
  95. }
  96. // We just test the other attributes even if they're not present in the mesh.
  97. // In this case they're initialized to 0 so the comparison succeeds.
  98. // By this method the non-present attributes are effectively ignored in the comparison.
  99. if ((lhs.normal - rhs.normal).SquareLength() > squareEpsilon) {
  100. return false;
  101. }
  102. if ((lhs.tangent - rhs.tangent).SquareLength() > squareEpsilon) {
  103. return false;
  104. }
  105. if ((lhs.bitangent - rhs.bitangent).SquareLength() > squareEpsilon) {
  106. return false;
  107. }
  108. for (unsigned i = 0; i < numUVChannels; i++) {
  109. if ((lhs.texcoords[i] - rhs.texcoords[i]).SquareLength() > squareEpsilon) {
  110. return false;
  111. }
  112. }
  113. for (unsigned i = 0; i < numColorChannels; i++) {
  114. if (GetColorDifference(lhs.colors[i], rhs.colors[i]) > squareEpsilon) {
  115. return false;
  116. }
  117. }
  118. return true;
  119. }
  120. template<class XMesh>
  121. void updateXMeshVertices(XMesh *pMesh, std::vector<int> &uniqueVertices) {
  122. // replace vertex data with the unique data sets
  123. pMesh->mNumVertices = (unsigned int)uniqueVertices.size();
  124. // ----------------------------------------------------------------------------
  125. // NOTE - we're *not* calling Vertex::SortBack() because it would check for
  126. // presence of every single vertex component once PER VERTEX. And our CPU
  127. // dislikes branches, even if they're easily predictable.
  128. // ----------------------------------------------------------------------------
  129. // Position, if present (check made for aiAnimMesh)
  130. if (pMesh->mVertices) {
  131. std::unique_ptr<aiVector3D[]> oldVertices(pMesh->mVertices);
  132. pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  133. for (unsigned int a = 0; a < pMesh->mNumVertices; a++)
  134. pMesh->mVertices[a] = oldVertices[uniqueVertices[a]];
  135. }
  136. // Normals, if present
  137. if (pMesh->mNormals) {
  138. std::unique_ptr<aiVector3D[]> oldNormals(pMesh->mNormals);
  139. pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  140. for (unsigned int a = 0; a < pMesh->mNumVertices; a++)
  141. pMesh->mNormals[a] = oldNormals[uniqueVertices[a]];
  142. }
  143. // Tangents, if present
  144. if (pMesh->mTangents) {
  145. std::unique_ptr<aiVector3D[]> oldTangents(pMesh->mTangents);
  146. pMesh->mTangents = new aiVector3D[pMesh->mNumVertices];
  147. for (unsigned int a = 0; a < pMesh->mNumVertices; a++)
  148. pMesh->mTangents[a] = oldTangents[uniqueVertices[a]];
  149. }
  150. // Bitangents as well
  151. if (pMesh->mBitangents) {
  152. std::unique_ptr<aiVector3D[]> oldBitangents(pMesh->mBitangents);
  153. pMesh->mBitangents = new aiVector3D[pMesh->mNumVertices];
  154. for (unsigned int a = 0; a < pMesh->mNumVertices; a++)
  155. pMesh->mBitangents[a] = oldBitangents[uniqueVertices[a]];
  156. }
  157. // Vertex colors
  158. for (unsigned int a = 0; pMesh->HasVertexColors(a); a++) {
  159. std::unique_ptr<aiColor4D[]> oldColors(pMesh->mColors[a]);
  160. pMesh->mColors[a] = new aiColor4D[pMesh->mNumVertices];
  161. for (unsigned int b = 0; b < pMesh->mNumVertices; b++)
  162. pMesh->mColors[a][b] = oldColors[uniqueVertices[b]];
  163. }
  164. // Texture coords
  165. for (unsigned int a = 0; pMesh->HasTextureCoords(a); a++) {
  166. std::unique_ptr<aiVector3D[]> oldTextureCoords(pMesh->mTextureCoords[a]);
  167. pMesh->mTextureCoords[a] = new aiVector3D[pMesh->mNumVertices];
  168. for (unsigned int b = 0; b < pMesh->mNumVertices; b++)
  169. pMesh->mTextureCoords[a][b] = oldTextureCoords[uniqueVertices[b]];
  170. }
  171. }
  172. } // namespace
  173. // ------------------------------------------------------------------------------------------------
  174. // Unites identical vertices in the given mesh
  175. // combine hashes
  176. inline void hash_combine(std::size_t &) {
  177. // empty
  178. }
  179. template <typename T, typename... Rest>
  180. inline void hash_combine(std::size_t& seed, const T& v, Rest... rest) {
  181. std::hash<T> hasher;
  182. seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
  183. hash_combine(seed, rest...);
  184. }
  185. //template specialization for std::hash for Vertex
  186. template<>
  187. struct std::hash<Vertex> {
  188. std::size_t operator()(Vertex const& v) const noexcept {
  189. size_t seed = 0;
  190. hash_combine(seed, v.position.x ,v.position.y,v.position.z);
  191. return seed;
  192. }
  193. };
  194. //template specialization for std::equal_to for Vertex
  195. template<>
  196. struct std::equal_to<Vertex> {
  197. equal_to(unsigned numUVChannels, unsigned numColorChannels) :
  198. mNumUVChannels(numUVChannels),
  199. mNumColorChannels(numColorChannels) {}
  200. bool operator()(const Vertex &lhs, const Vertex &rhs) const {
  201. return areVerticesEqual(lhs, rhs, mNumUVChannels, mNumColorChannels);
  202. }
  203. private:
  204. unsigned mNumUVChannels;
  205. unsigned mNumColorChannels;
  206. };
  207. static constexpr size_t JOINED_VERTICES_MARK = 0x80000000u;
  208. // now start the JoinVerticesProcess
  209. int JoinVerticesProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshIndex) {
  210. static_assert( AI_MAX_NUMBER_OF_COLOR_SETS == 8, "AI_MAX_NUMBER_OF_COLOR_SETS == 8");
  211. static_assert( AI_MAX_NUMBER_OF_TEXTURECOORDS == 8, "AI_MAX_NUMBER_OF_TEXTURECOORDS == 8");
  212. // Return early if we don't have any positions
  213. if (!pMesh->HasPositions() || !pMesh->HasFaces()) {
  214. return 0;
  215. }
  216. // We should care only about used vertices, not all of them
  217. // (this can happen due to original file vertices buffer being used by
  218. // multiple meshes)
  219. std::vector<bool> usedVertexIndicesMask;
  220. usedVertexIndicesMask.resize(pMesh->mNumVertices, false);
  221. for (unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  222. aiFace& face = pMesh->mFaces[a];
  223. for (unsigned int b = 0; b < face.mNumIndices; b++) {
  224. usedVertexIndicesMask[face.mIndices[b]] = true;
  225. }
  226. }
  227. // We'll never have more vertices afterwards.
  228. std::vector<int> uniqueVertices;
  229. uniqueVertices.reserve( pMesh->mNumVertices);
  230. // For each vertex the index of the vertex it was replaced by.
  231. // Since the maximal number of vertices is 2^31-1, the most significand bit can be used to mark
  232. // whether a new vertex was created for the index (true) or if it was replaced by an existing
  233. // unique vertex (false). This saves an additional std::vector<bool> and greatly enhances
  234. // branching performance.
  235. static_assert(AI_MAX_VERTICES == 0x7fffffff, "AI_MAX_VERTICES == 0x7fffffff");
  236. std::vector<unsigned int> replaceIndex( pMesh->mNumVertices, 0xffffffff);
  237. // float posEpsilonSqr;
  238. SpatialSort *vertexFinder = nullptr;
  239. SpatialSort _vertexFinder;
  240. typedef std::pair<SpatialSort,float> SpatPair;
  241. if (shared) {
  242. std::vector<SpatPair >* avf;
  243. shared->GetProperty(AI_SPP_SPATIAL_SORT,avf);
  244. if (avf) {
  245. SpatPair& blubb = (*avf)[meshIndex];
  246. vertexFinder = &blubb.first;
  247. // posEpsilonSqr = blubb.second;
  248. }
  249. }
  250. if (!vertexFinder) {
  251. // bad, need to compute it.
  252. _vertexFinder.Fill(pMesh->mVertices, pMesh->mNumVertices, sizeof( aiVector3D));
  253. vertexFinder = &_vertexFinder;
  254. // posEpsilonSqr = ComputePositionEpsilon(pMesh);
  255. }
  256. // Again, better waste some bytes than a realloc ...
  257. std::vector<unsigned int> verticesFound;
  258. verticesFound.reserve(10);
  259. // Run an optimized code path if we don't have multiple UVs or vertex colors.
  260. // This should yield false in more than 99% of all imports ...
  261. const bool hasAnimMeshes = pMesh->mNumAnimMeshes > 0;
  262. // We'll never have more vertices afterwards.
  263. std::vector<std::vector<int>> uniqueAnimatedVertices;
  264. if (hasAnimMeshes) {
  265. uniqueAnimatedVertices.resize(pMesh->mNumAnimMeshes);
  266. for (unsigned int animMeshIndex = 0; animMeshIndex < pMesh->mNumAnimMeshes; animMeshIndex++) {
  267. uniqueAnimatedVertices[animMeshIndex].reserve(pMesh->mNumVertices);
  268. }
  269. }
  270. // a map that maps a vertex to its new index
  271. const auto numBuckets = pMesh->mNumVertices;
  272. const auto hasher = std::hash<Vertex>();
  273. const auto comparator = std::equal_to<Vertex>(
  274. pMesh->GetNumUVChannels(),
  275. pMesh->GetNumColorChannels());
  276. std::unordered_map<Vertex, int> vertex2Index(numBuckets, hasher, comparator);
  277. // we can not end up with more vertices than we started with
  278. vertex2Index.reserve(pMesh->mNumVertices);
  279. // Now check each vertex if it brings something new to the table
  280. int newIndex = 0;
  281. for( unsigned int a = 0; a < pMesh->mNumVertices; a++) {
  282. // if the vertex is unused Do nothing
  283. if (!usedVertexIndicesMask[a]) {
  284. continue;
  285. }
  286. // collect the vertex data
  287. Vertex v(pMesh,a);
  288. // is the vertex already in the map?
  289. auto it = vertex2Index.find(v);
  290. // if the vertex is not in the map then it is a new vertex add it.
  291. if (it == vertex2Index.end()) {
  292. // this is a new vertex give it a new index
  293. vertex2Index[v] = newIndex;
  294. //keep track of its index and increment 1
  295. replaceIndex[a] = newIndex++;
  296. // add the vertex to the unique vertices
  297. uniqueVertices.push_back(a);
  298. if (hasAnimMeshes) {
  299. for (unsigned int animMeshIndex = 0; animMeshIndex < pMesh->mNumAnimMeshes; animMeshIndex++) {
  300. uniqueAnimatedVertices[animMeshIndex].emplace_back(a);
  301. }
  302. }
  303. } else{
  304. // if the vertex is already there just find the replace index that is appropriate to it
  305. // mark it with JOINED_VERTICES_MARK
  306. replaceIndex[a] = it->second | JOINED_VERTICES_MARK;
  307. }
  308. }
  309. if (!DefaultLogger::isNullLogger() && DefaultLogger::get()->getLogSeverity() == Logger::VERBOSE) {
  310. ASSIMP_LOG_VERBOSE_DEBUG(
  311. "Mesh ",meshIndex,
  312. " (",
  313. (pMesh->mName.length ? pMesh->mName.data : "unnamed"),
  314. ") | Verts in: ",pMesh->mNumVertices,
  315. " out: ",
  316. uniqueVertices.size(),
  317. " | ~",
  318. ((pMesh->mNumVertices - uniqueVertices.size()) / (float)pMesh->mNumVertices) * 100.f,
  319. "%"
  320. );
  321. }
  322. updateXMeshVertices(pMesh, uniqueVertices);
  323. if (hasAnimMeshes) {
  324. for (unsigned int animMeshIndex = 0; animMeshIndex < pMesh->mNumAnimMeshes; animMeshIndex++) {
  325. updateXMeshVertices(pMesh->mAnimMeshes[animMeshIndex], uniqueAnimatedVertices[animMeshIndex]);
  326. }
  327. }
  328. // adjust the indices in all faces
  329. for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  330. aiFace& face = pMesh->mFaces[a];
  331. for( unsigned int b = 0; b < face.mNumIndices; b++) {
  332. face.mIndices[b] = replaceIndex[face.mIndices[b]] & ~JOINED_VERTICES_MARK;
  333. }
  334. }
  335. // adjust bone vertex weights.
  336. for( int a = 0; a < (int)pMesh->mNumBones; a++) {
  337. aiBone* bone = pMesh->mBones[a];
  338. std::vector<aiVertexWeight> newWeights;
  339. newWeights.reserve( bone->mNumWeights);
  340. if (nullptr != bone->mWeights) {
  341. for ( unsigned int b = 0; b < bone->mNumWeights; b++ ) {
  342. const aiVertexWeight& ow = bone->mWeights[ b ];
  343. // if the vertex is a unique one, translate it
  344. // filter out joined vertices by JOINED_VERTICES_MARK.
  345. if ( !( replaceIndex[ ow.mVertexId ] & JOINED_VERTICES_MARK ) ) {
  346. aiVertexWeight nw;
  347. nw.mVertexId = replaceIndex[ ow.mVertexId ];
  348. nw.mWeight = ow.mWeight;
  349. newWeights.push_back( nw );
  350. }
  351. }
  352. } else {
  353. ASSIMP_LOG_ERROR( "X-Export: aiBone shall contain weights, but pointer to them is nullptr." );
  354. }
  355. if (newWeights.size() > 0) {
  356. // kill the old and replace them with the translated weights
  357. delete [] bone->mWeights;
  358. bone->mNumWeights = (unsigned int)newWeights.size();
  359. bone->mWeights = new aiVertexWeight[bone->mNumWeights];
  360. memcpy( bone->mWeights, &newWeights[0], bone->mNumWeights * sizeof( aiVertexWeight));
  361. }
  362. }
  363. return pMesh->mNumVertices;
  364. }
  365. #endif // !! ASSIMP_BUILD_NO_JOINVERTICES_PROCESS