JoinVerticesProcess.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2008, 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 <vector>
  38. #include "JoinVerticesProcess.h"
  39. #include "SpatialSort.h"
  40. #include "../include/DefaultLogger.h"
  41. #include "../include/aiPostProcess.h"
  42. #include "../include/aiMesh.h"
  43. #include "../include/aiScene.h"
  44. using namespace Assimp;
  45. #if _MSC_VER >= 1400
  46. # define sprintf sprintf_s
  47. #endif
  48. // ------------------------------------------------------------------------------------------------
  49. // Constructor to be privately used by Importer
  50. JoinVerticesProcess::JoinVerticesProcess()
  51. {
  52. // nothing to do here
  53. }
  54. // ------------------------------------------------------------------------------------------------
  55. // Destructor, private as well
  56. JoinVerticesProcess::~JoinVerticesProcess()
  57. {
  58. // nothing to do here
  59. }
  60. // ------------------------------------------------------------------------------------------------
  61. // Returns whether the processing step is present in the given flag field.
  62. bool JoinVerticesProcess::IsActive( unsigned int pFlags) const
  63. {
  64. return (pFlags & aiProcess_JoinIdenticalVertices) != 0;
  65. }
  66. // ------------------------------------------------------------------------------------------------
  67. // Executes the post processing step on the given imported data.
  68. void JoinVerticesProcess::Execute( aiScene* pScene)
  69. {
  70. DefaultLogger::get()->debug("JoinVerticesProcess begin");
  71. // get the total number of vertices BEFORE the step is executed
  72. int iNumOldVertices = 0;
  73. for( unsigned int a = 0; a < pScene->mNumMeshes; a++)
  74. {
  75. iNumOldVertices += pScene->mMeshes[a]->mNumVertices;
  76. }
  77. // execute the step
  78. int iNumVertices = 0;
  79. for( unsigned int a = 0; a < pScene->mNumMeshes; a++)
  80. {
  81. iNumVertices += this->ProcessMesh( pScene->mMeshes[a],a);
  82. }
  83. // if logging is active, print detailled statistics
  84. if (!DefaultLogger::isNullLogger())
  85. {
  86. if (iNumOldVertices == iNumVertices)DefaultLogger::get()->debug("JoinVerticesProcess finished ");
  87. else
  88. {
  89. char szBuff[128]; // should be sufficiently large in every case
  90. sprintf(szBuff,"JoinVerticesProcess finished | Verts in: %i out: %i | ~%.1f%%",
  91. iNumOldVertices,
  92. iNumVertices,
  93. ((iNumOldVertices - iNumVertices) / (float)iNumOldVertices) * 100.f);
  94. DefaultLogger::get()->info(szBuff);
  95. }
  96. }
  97. }
  98. // ------------------------------------------------------------------------------------------------
  99. // Unites identical vertices in the given mesh
  100. int JoinVerticesProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshIndex)
  101. {
  102. // helper structure to hold all the data a single vertex can possibly have
  103. typedef struct Vertex vertex;
  104. if (!pMesh->HasPositions() || !pMesh->HasFaces())
  105. return 0;
  106. struct Vertex
  107. {
  108. aiVector3D mPosition;
  109. aiVector3D mNormal;
  110. aiVector3D mTangent, mBitangent;
  111. aiColor4D mColors[AI_MAX_NUMBER_OF_COLOR_SETS];
  112. aiVector3D mTexCoords[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  113. };
  114. std::vector<Vertex> uniqueVertices;
  115. uniqueVertices.reserve( pMesh->mNumVertices);
  116. unsigned int iOldVerts = pMesh->mNumVertices;
  117. // For each vertex the index of the vertex it was replaced by.
  118. std::vector<unsigned int> replaceIndex( pMesh->mNumVertices, 0xffffffff);
  119. // for each vertex whether it was replaced by an existing unique vertex (true) or a new vertex was created for it (false)
  120. std::vector<bool> isVertexUnique( pMesh->mNumVertices, false);
  121. // calculate the position bounds so we have a reliable epsilon to check position differences against
  122. aiVector3D minVec( 1e10f, 1e10f, 1e10f), maxVec( -1e10f, -1e10f, -1e10f);
  123. for( unsigned int a = 0; a < pMesh->mNumVertices; a++)
  124. {
  125. minVec.x = std::min( minVec.x, pMesh->mVertices[a].x);
  126. minVec.y = std::min( minVec.y, pMesh->mVertices[a].y);
  127. minVec.z = std::min( minVec.z, pMesh->mVertices[a].z);
  128. maxVec.x = std::max( maxVec.x, pMesh->mVertices[a].x);
  129. maxVec.y = std::max( maxVec.y, pMesh->mVertices[a].y);
  130. maxVec.z = std::max( maxVec.z, pMesh->mVertices[a].z);
  131. }
  132. // squared because we check against squared length of the vector difference
  133. const float epsilon = 1e-5f;
  134. const float posEpsilon = (maxVec - minVec).Length() * epsilon;
  135. const float squareEpsilon = epsilon * epsilon;
  136. // a little helper to find locally close vertices faster
  137. SpatialSort vertexFinder( pMesh->mVertices, pMesh->mNumVertices, sizeof( aiVector3D));
  138. std::vector<unsigned int> verticesFound;
  139. // now check each vertex if it brings something new to the table
  140. for( unsigned int a = 0; a < pMesh->mNumVertices; a++)
  141. {
  142. // collect the vertex data
  143. Vertex v;
  144. v.mPosition = pMesh->mVertices[a];
  145. v.mNormal = (pMesh->mNormals != NULL) ? pMesh->mNormals[a] : aiVector3D( 0, 0, 0);
  146. v.mTangent = (pMesh->mTangents != NULL) ? pMesh->mTangents[a] : aiVector3D( 0, 0, 0);
  147. v.mBitangent = (pMesh->mBitangents != NULL) ? pMesh->mBitangents[a] : aiVector3D( 0, 0, 0);
  148. for( unsigned int b = 0; b < AI_MAX_NUMBER_OF_COLOR_SETS; b++)
  149. v.mColors[b] = (pMesh->mColors[b] != NULL) ? pMesh->mColors[b][a] : aiColor4D( 0, 0, 0, 0);
  150. for( unsigned int b = 0; b < AI_MAX_NUMBER_OF_TEXTURECOORDS; b++)
  151. v.mTexCoords[b] = (pMesh->mTextureCoords[b] != NULL) ? pMesh->mTextureCoords[b][a] : aiVector3D( 0, 0, 0);
  152. // collect all vertices that are close enough to the given position
  153. vertexFinder.FindPositions( v.mPosition, posEpsilon, verticesFound);
  154. unsigned int matchIndex = 0xffffffff;
  155. // check all unique vertices close to the position if this vertex is already present among them
  156. for( unsigned int b = 0; b < verticesFound.size(); b++)
  157. {
  158. unsigned int vidx = verticesFound[b];
  159. unsigned int uidx = replaceIndex[ vidx];
  160. if( uidx == 0xffffffff || !isVertexUnique[ vidx])
  161. continue;
  162. const Vertex& uv = uniqueVertices[ uidx];
  163. // Position mismatch is impossible - the vertex finder already discarded all non-matching positions
  164. // We just test the other attributes even if they're not present in the mesh.
  165. // In this case they're initialized to 0 so the comparision succeeds.
  166. // By this method the non-present attributes are effectively ignored in the comparision.
  167. if( (uv.mNormal - v.mNormal).SquareLength() > squareEpsilon)
  168. continue;
  169. if( (uv.mTangent - v.mTangent).SquareLength() > squareEpsilon)
  170. continue;
  171. if( (uv.mBitangent - v.mBitangent).SquareLength() > squareEpsilon)
  172. continue;
  173. // manually unrolled because continue wouldn't work as desired in an inner loop
  174. ai_assert( AI_MAX_NUMBER_OF_COLOR_SETS == 4);
  175. if( GetColorDifference( uv.mColors[0], v.mColors[0]) > squareEpsilon)
  176. continue;
  177. if( GetColorDifference( uv.mColors[1], v.mColors[1]) > squareEpsilon)
  178. continue;
  179. if( GetColorDifference( uv.mColors[2], v.mColors[2]) > squareEpsilon)
  180. continue;
  181. if( GetColorDifference( uv.mColors[3], v.mColors[3]) > squareEpsilon)
  182. continue;
  183. // texture coord matching manually unrolled as well
  184. ai_assert( AI_MAX_NUMBER_OF_TEXTURECOORDS == 4);
  185. if( (uv.mTexCoords[0] - v.mTexCoords[0]).SquareLength() > squareEpsilon)
  186. continue;
  187. if( (uv.mTexCoords[1] - v.mTexCoords[1]).SquareLength() > squareEpsilon)
  188. continue;
  189. if( (uv.mTexCoords[2] - v.mTexCoords[2]).SquareLength() > squareEpsilon)
  190. continue;
  191. if( (uv.mTexCoords[3] - v.mTexCoords[3]).SquareLength() > squareEpsilon)
  192. continue;
  193. // we're still here -> this vertex perfectly matches our given vertex
  194. matchIndex = uidx;
  195. break;
  196. }
  197. // found a replacement vertex among the uniques?
  198. if( matchIndex != 0xffffffff)
  199. {
  200. // store where to found the matching unique vertex
  201. replaceIndex[a] = matchIndex;
  202. isVertexUnique[a] = false;
  203. } else
  204. {
  205. // no unique vertex matches it upto now -> so add it
  206. replaceIndex[a] = (unsigned int)uniqueVertices.size();
  207. uniqueVertices.push_back( v);
  208. isVertexUnique[a] = true;
  209. }
  210. }
  211. if (!DefaultLogger::isNullLogger())
  212. {
  213. char szBuff[128]; // should be sufficiently large in every case
  214. sprintf(szBuff,"Mesh %i | Verts in: %i out: %i | ~%.1f%%",
  215. meshIndex,
  216. pMesh->mNumVertices,
  217. uniqueVertices.size(),
  218. ((pMesh->mNumVertices - uniqueVertices.size()) / (float)pMesh->mNumVertices) * 100.f);
  219. DefaultLogger::get()->info(szBuff);
  220. }
  221. // replace vertex data with the unique data sets
  222. pMesh->mNumVertices = (unsigned int)uniqueVertices.size();
  223. // Position
  224. delete [] pMesh->mVertices;
  225. pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  226. for( unsigned int a = 0; a < pMesh->mNumVertices; a++)
  227. pMesh->mVertices[a] = uniqueVertices[a].mPosition;
  228. // Normals, if present
  229. if( pMesh->mNormals)
  230. {
  231. delete [] pMesh->mNormals;
  232. pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  233. for( unsigned int a = 0; a < pMesh->mNumVertices; a++)
  234. pMesh->mNormals[a] = uniqueVertices[a].mNormal;
  235. }
  236. // Tangents, if present
  237. if( pMesh->mTangents)
  238. {
  239. delete [] pMesh->mTangents;
  240. pMesh->mTangents = new aiVector3D[pMesh->mNumVertices];
  241. for( unsigned int a = 0; a < pMesh->mNumVertices; a++)
  242. pMesh->mTangents[a] = uniqueVertices[a].mTangent;
  243. }
  244. // Bitangents as well
  245. if( pMesh->mBitangents)
  246. {
  247. delete [] pMesh->mBitangents;
  248. pMesh->mBitangents = new aiVector3D[pMesh->mNumVertices];
  249. for( unsigned int a = 0; a < pMesh->mNumVertices; a++)
  250. pMesh->mBitangents[a] = uniqueVertices[a].mBitangent;
  251. }
  252. // Vertex colors
  253. for( unsigned int a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; a++)
  254. {
  255. if( !pMesh->mColors[a])
  256. continue;
  257. delete [] pMesh->mColors[a];
  258. pMesh->mColors[a] = new aiColor4D[pMesh->mNumVertices];
  259. for( unsigned int b = 0; b < pMesh->mNumVertices; b++)
  260. pMesh->mColors[a][b] = uniqueVertices[b].mColors[a];
  261. }
  262. // Texture coords
  263. for( unsigned int a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; a++)
  264. {
  265. if( !pMesh->mTextureCoords[a])
  266. continue;
  267. delete [] pMesh->mTextureCoords[a];
  268. pMesh->mTextureCoords[a] = new aiVector3D[pMesh->mNumVertices];
  269. for( unsigned int b = 0; b < pMesh->mNumVertices; b++)
  270. pMesh->mTextureCoords[a][b] = uniqueVertices[b].mTexCoords[a];
  271. }
  272. // adjust the indices in all faces
  273. for( unsigned int a = 0; a < pMesh->mNumFaces; a++)
  274. {
  275. aiFace& face = pMesh->mFaces[a];
  276. for( unsigned int b = 0; b < face.mNumIndices; b++)
  277. {
  278. const size_t index = face.mIndices[b];
  279. face.mIndices[b] = replaceIndex[face.mIndices[b]];
  280. }
  281. }
  282. // adjust bone vertex weights.
  283. for( unsigned int a = 0; a < pMesh->mNumBones; a++)
  284. {
  285. aiBone* bone = pMesh->mBones[a];
  286. std::vector<aiVertexWeight> newWeights;
  287. newWeights.reserve( bone->mNumWeights);
  288. for( unsigned int b = 0; b < bone->mNumWeights; b++)
  289. {
  290. const aiVertexWeight& ow = bone->mWeights[b];
  291. // if the vertex is a unique one, translate it
  292. if( isVertexUnique[ow.mVertexId])
  293. {
  294. aiVertexWeight nw;
  295. nw.mVertexId = replaceIndex[ow.mVertexId];
  296. nw.mWeight = ow.mWeight;
  297. newWeights.push_back( nw);
  298. }
  299. }
  300. // there should be some. At least I think there should be some
  301. ai_assert( newWeights.size() > 0);
  302. // kill the old and replace them with the translated weights
  303. delete [] bone->mWeights;
  304. bone->mNumWeights = (unsigned int)newWeights.size();
  305. bone->mWeights = new aiVertexWeight[bone->mNumWeights];
  306. memcpy( bone->mWeights, &newWeights[0], bone->mNumWeights * sizeof( aiVertexWeight));
  307. }
  308. return pMesh->mNumVertices;
  309. }