JoinVerticesProcess.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2010, ASSIMP Development 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 Development 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. #include "AssimpPCH.h"
  38. #ifndef ASSIMP_BUILD_NO_JOINVERTICES_PROCESS
  39. #include "JoinVerticesProcess.h"
  40. #include "ProcessHelper.h"
  41. #include "Vertex.h"
  42. using namespace Assimp;
  43. // ------------------------------------------------------------------------------------------------
  44. // Constructor to be privately used by Importer
  45. JoinVerticesProcess::JoinVerticesProcess()
  46. {
  47. // nothing to do here
  48. }
  49. // ------------------------------------------------------------------------------------------------
  50. // Destructor, private as well
  51. JoinVerticesProcess::~JoinVerticesProcess()
  52. {
  53. // nothing to do here
  54. }
  55. // ------------------------------------------------------------------------------------------------
  56. // Returns whether the processing step is present in the given flag field.
  57. bool JoinVerticesProcess::IsActive( unsigned int pFlags) const
  58. {
  59. return (pFlags & aiProcess_JoinIdenticalVertices) != 0;
  60. }
  61. // ------------------------------------------------------------------------------------------------
  62. // Executes the post processing step on the given imported data.
  63. void JoinVerticesProcess::Execute( aiScene* pScene)
  64. {
  65. DefaultLogger::get()->debug("JoinVerticesProcess begin");
  66. // get the total number of vertices BEFORE the step is executed
  67. int iNumOldVertices = 0;
  68. if (!DefaultLogger::isNullLogger()) {
  69. for( unsigned int a = 0; a < pScene->mNumMeshes; a++) {
  70. iNumOldVertices += pScene->mMeshes[a]->mNumVertices;
  71. }
  72. }
  73. // execute the step
  74. int iNumVertices = 0;
  75. for( unsigned int a = 0; a < pScene->mNumMeshes; a++)
  76. iNumVertices += ProcessMesh( pScene->mMeshes[a],a);
  77. // if logging is active, print detailed statistics
  78. if (!DefaultLogger::isNullLogger())
  79. {
  80. if (iNumOldVertices == iNumVertices)
  81. {
  82. DefaultLogger::get()->debug("JoinVerticesProcess finished ");
  83. } else
  84. {
  85. char szBuff[128]; // should be sufficiently large in every case
  86. sprintf(szBuff,"JoinVerticesProcess finished | Verts in: %i out: %i | ~%.1f%%",
  87. iNumOldVertices,
  88. iNumVertices,
  89. ((iNumOldVertices - iNumVertices) / (float)iNumOldVertices) * 100.f);
  90. DefaultLogger::get()->info(szBuff);
  91. }
  92. }
  93. pScene->mFlags |= AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;
  94. }
  95. // ------------------------------------------------------------------------------------------------
  96. // Unites identical vertices in the given mesh
  97. int JoinVerticesProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshIndex)
  98. {
  99. BOOST_STATIC_ASSERT( AI_MAX_NUMBER_OF_COLOR_SETS == 4);
  100. BOOST_STATIC_ASSERT( AI_MAX_NUMBER_OF_TEXTURECOORDS == 4);
  101. // Return early if we don't have any positions
  102. if (!pMesh->HasPositions() || !pMesh->HasFaces()) {
  103. return 0;
  104. }
  105. // We'll never have more vertices afterwards.
  106. std::vector<Vertex> uniqueVertices;
  107. uniqueVertices.reserve( pMesh->mNumVertices);
  108. // For each vertex the index of the vertex it was replaced by.
  109. std::vector<unsigned int> replaceIndex( pMesh->mNumVertices, 0xffffffff);
  110. // for each vertex whether it was replaced by an existing unique vertex (true) or a new vertex was created for it (false)
  111. std::vector<bool> isVertexUnique( pMesh->mNumVertices, false);
  112. // A little helper to find locally close vertices faster.
  113. // Try to reuse the lookup table from the last step.
  114. const static float epsilon = 1e-5f;
  115. float posEpsilonSqr;
  116. SpatialSort* vertexFinder = NULL;
  117. SpatialSort _vertexFinder;
  118. typedef std::pair<SpatialSort,float> SpatPair;
  119. if (shared) {
  120. std::vector<SpatPair >* avf;
  121. shared->GetProperty(AI_SPP_SPATIAL_SORT,avf);
  122. if (avf) {
  123. SpatPair& blubb = (*avf)[meshIndex];
  124. vertexFinder = &blubb.first;
  125. posEpsilonSqr = blubb.second;
  126. }
  127. }
  128. if (!vertexFinder) {
  129. // bad, need to compute it.
  130. _vertexFinder.Fill(pMesh->mVertices, pMesh->mNumVertices, sizeof( aiVector3D));
  131. vertexFinder = &_vertexFinder;
  132. posEpsilonSqr = ComputePositionEpsilon(pMesh);
  133. }
  134. // Squared because we check against squared length of the vector difference
  135. static const float squareEpsilon = epsilon * epsilon;
  136. // Again, better waste some bytes than a realloc ...
  137. std::vector<unsigned int> verticesFound;
  138. verticesFound.reserve(10);
  139. // Run an optimized code path if we don't have multiple UVs or vertex colors.
  140. // This should yield false in more than 99% of all imports ...
  141. const bool complex = (
  142. pMesh->mTextureCoords[1] ||
  143. pMesh->mTextureCoords[2] ||
  144. pMesh->mTextureCoords[3] ||
  145. pMesh->mColors[0] ||
  146. pMesh->mColors[1] ||
  147. pMesh->mColors[2] ||
  148. pMesh->mColors[3] );
  149. // Now check each vertex if it brings something new to the table
  150. for( unsigned int a = 0; a < pMesh->mNumVertices; a++) {
  151. // collect the vertex data
  152. Vertex v(pMesh,a);
  153. // collect all vertices that are close enough to the given position
  154. vertexFinder->FindPositions( v.position, posEpsilonSqr, verticesFound);
  155. unsigned int matchIndex = 0xffffffff;
  156. // check all unique vertices close to the position if this vertex is already present among them
  157. for( unsigned int b = 0; b < verticesFound.size(); b++) {
  158. const unsigned int vidx = verticesFound[b];
  159. const unsigned int uidx = replaceIndex[ vidx];
  160. if( uidx == 0xffffffff || !isVertexUnique[ vidx]) {
  161. continue;
  162. }
  163. const Vertex& uv = uniqueVertices[ uidx];
  164. // Position mismatch is impossible - the vertex finder already discarded all non-matching positions
  165. // We just test the other attributes even if they're not present in the mesh.
  166. // In this case they're initialized to 0 so the comparision succeeds.
  167. // By this method the non-present attributes are effectively ignored in the comparision.
  168. if( (uv.normal - v.normal).SquareLength() > squareEpsilon)
  169. continue;
  170. if( (uv.texcoords[0] - v.texcoords[0]).SquareLength() > squareEpsilon)
  171. continue;
  172. if( (uv.tangent - v.tangent).SquareLength() > squareEpsilon)
  173. continue;
  174. if( (uv.bitangent - v.bitangent).SquareLength() > squareEpsilon)
  175. continue;
  176. // Usually we won't have vertex colors or multiple UVs, so we can skip from here
  177. // Actually this increases runtime performance slightly, at least if branch
  178. // prediction is on our side.
  179. if (complex){
  180. // manually unrolled because continue wouldn't work as desired in an inner loop
  181. if( GetColorDifference( uv.colors[0], v.colors[0]) > squareEpsilon)
  182. continue;
  183. if( GetColorDifference( uv.colors[1], v.colors[1]) > squareEpsilon)
  184. continue;
  185. if( GetColorDifference( uv.colors[2], v.colors[2]) > squareEpsilon)
  186. continue;
  187. if( GetColorDifference( uv.colors[3], v.colors[3]) > squareEpsilon)
  188. continue;
  189. // texture coord matching manually unrolled as well
  190. if( (uv.texcoords[1] - v.texcoords[1]).SquareLength() > squareEpsilon)
  191. continue;
  192. if( (uv.texcoords[2] - v.texcoords[2]).SquareLength() > squareEpsilon)
  193. continue;
  194. if( (uv.texcoords[3] - v.texcoords[3]).SquareLength() > squareEpsilon)
  195. continue;
  196. }
  197. // we're still here -> this vertex perfectly matches our given vertex
  198. matchIndex = uidx;
  199. break;
  200. }
  201. // found a replacement vertex among the uniques?
  202. if( matchIndex != 0xffffffff)
  203. {
  204. // store where to found the matching unique vertex
  205. replaceIndex[a] = matchIndex;
  206. isVertexUnique[a] = false;
  207. }
  208. else
  209. {
  210. // no unique vertex matches it upto now -> so add it
  211. replaceIndex[a] = (unsigned int)uniqueVertices.size();
  212. uniqueVertices.push_back( v);
  213. isVertexUnique[a] = true;
  214. }
  215. }
  216. if (!DefaultLogger::isNullLogger() && DefaultLogger::get()->getLogSeverity() == Logger::VERBOSE) {
  217. char szBuff[128]; // should be sufficiently large in every case
  218. ::sprintf(szBuff,"Mesh %i | Verts in: %i out: %i | ~%.1f%%",
  219. meshIndex,
  220. pMesh->mNumVertices,
  221. (int)uniqueVertices.size(),
  222. ((pMesh->mNumVertices - uniqueVertices.size()) / (float)pMesh->mNumVertices) * 100.f);
  223. DefaultLogger::get()->debug(szBuff);
  224. }
  225. // replace vertex data with the unique data sets
  226. pMesh->mNumVertices = (unsigned int)uniqueVertices.size();
  227. // ----------------------------------------------------------------------------
  228. // NOTE - we're *not* calling Vertex::SortBack() because it would check for
  229. // presence of every single vertex component once PER VERTEX. And our CPU
  230. // dislikes branches, even if they're easily predictable.
  231. // ----------------------------------------------------------------------------
  232. // Position
  233. delete [] pMesh->mVertices;
  234. pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  235. for( unsigned int a = 0; a < pMesh->mNumVertices; a++)
  236. pMesh->mVertices[a] = uniqueVertices[a].position;
  237. // Normals, if present
  238. if( pMesh->mNormals)
  239. {
  240. delete [] pMesh->mNormals;
  241. pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  242. for( unsigned int a = 0; a < pMesh->mNumVertices; a++) {
  243. pMesh->mNormals[a] = uniqueVertices[a].normal;
  244. }
  245. }
  246. // Tangents, if present
  247. if( pMesh->mTangents)
  248. {
  249. delete [] pMesh->mTangents;
  250. pMesh->mTangents = new aiVector3D[pMesh->mNumVertices];
  251. for( unsigned int a = 0; a < pMesh->mNumVertices; a++) {
  252. pMesh->mTangents[a] = uniqueVertices[a].tangent;
  253. }
  254. }
  255. // Bitangents as well
  256. if( pMesh->mBitangents)
  257. {
  258. delete [] pMesh->mBitangents;
  259. pMesh->mBitangents = new aiVector3D[pMesh->mNumVertices];
  260. for( unsigned int a = 0; a < pMesh->mNumVertices; a++) {
  261. pMesh->mBitangents[a] = uniqueVertices[a].bitangent;
  262. }
  263. }
  264. // Vertex colors
  265. for( unsigned int a = 0; pMesh->HasVertexColors(a); a++)
  266. {
  267. delete [] pMesh->mColors[a];
  268. pMesh->mColors[a] = new aiColor4D[pMesh->mNumVertices];
  269. for( unsigned int b = 0; b < pMesh->mNumVertices; b++) {
  270. pMesh->mColors[a][b] = uniqueVertices[b].colors[a];
  271. }
  272. }
  273. // Texture coords
  274. for( unsigned int a = 0; pMesh->HasTextureCoords(a); a++)
  275. {
  276. delete [] pMesh->mTextureCoords[a];
  277. pMesh->mTextureCoords[a] = new aiVector3D[pMesh->mNumVertices];
  278. for( unsigned int b = 0; b < pMesh->mNumVertices; b++) {
  279. pMesh->mTextureCoords[a][b] = uniqueVertices[b].texcoords[a];
  280. }
  281. }
  282. // adjust the indices in all faces
  283. for( unsigned int a = 0; a < pMesh->mNumFaces; a++)
  284. {
  285. aiFace& face = pMesh->mFaces[a];
  286. for( unsigned int b = 0; b < face.mNumIndices; b++) {
  287. face.mIndices[b] = replaceIndex[face.mIndices[b]];
  288. }
  289. }
  290. // adjust bone vertex weights.
  291. for( int a = 0; a < (int)pMesh->mNumBones; a++)
  292. {
  293. aiBone* bone = pMesh->mBones[a];
  294. std::vector<aiVertexWeight> newWeights;
  295. newWeights.reserve( bone->mNumWeights);
  296. for( unsigned int b = 0; b < bone->mNumWeights; b++)
  297. {
  298. const aiVertexWeight& ow = bone->mWeights[b];
  299. // if the vertex is a unique one, translate it
  300. if( isVertexUnique[ow.mVertexId])
  301. {
  302. aiVertexWeight nw;
  303. nw.mVertexId = replaceIndex[ow.mVertexId];
  304. nw.mWeight = ow.mWeight;
  305. newWeights.push_back( nw);
  306. }
  307. }
  308. if (newWeights.size() > 0) {
  309. // kill the old and replace them with the translated weights
  310. delete [] bone->mWeights;
  311. bone->mNumWeights = (unsigned int)newWeights.size();
  312. bone->mWeights = new aiVertexWeight[bone->mNumWeights];
  313. memcpy( bone->mWeights, &newWeights[0], bone->mNumWeights * sizeof( aiVertexWeight));
  314. }
  315. else {
  316. /* NOTE:
  317. *
  318. * In the algorithm above we're assuming that there are no vertices
  319. * with a different bone weight setup at the same position. That wouldn't
  320. * make sense, but it is not absolutely impossible. SkeletonMeshBuilder
  321. * for example generates such input data if two skeleton points
  322. * share the same position. Again this doesn't make sense but is
  323. * reality for some model formats (MD5 for example uses these special
  324. * nodes as attachment tags for its weapons).
  325. *
  326. * Then it is possible that a bone has no weights anymore .... as a quick
  327. * workaround, we're just removing these bones. If they're animated,
  328. * model geometry might be modified but at least there's no risk of a crash.
  329. */
  330. delete bone;
  331. --pMesh->mNumBones;
  332. for (unsigned int n = a; n < pMesh->mNumBones; ++n) {
  333. pMesh->mBones[n] = pMesh->mBones[n+1];
  334. }
  335. --a;
  336. DefaultLogger::get()->warn("Removing bone -> no weights remaining");
  337. }
  338. }
  339. return pMesh->mNumVertices;
  340. }
  341. #endif // !! ASSIMP_BUILD_NO_JOINVERTICES_PROCESS