ImproveCacheLocality.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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 improve the cache locality of a mesh.
  35. * <br>
  36. * The algorithm is roughly basing on this paper:
  37. * http://www.cs.princeton.edu/gfx/pubs/Sander_2007_%3ETR/tipsy.pdf
  38. * .. although overdraw rduction isn't implemented yet ...
  39. */
  40. #include "AssimpPCH.h"
  41. // internal headers
  42. #include "ImproveCacheLocality.h"
  43. #include "VertexTriangleAdjacency.h"
  44. using namespace Assimp;
  45. // ------------------------------------------------------------------------------------------------
  46. // Constructor to be privately used by Importer
  47. ImproveCacheLocalityProcess::ImproveCacheLocalityProcess() {
  48. configCacheDepth = PP_ICL_PTCACHE_SIZE;
  49. }
  50. // ------------------------------------------------------------------------------------------------
  51. // Destructor, private as well
  52. ImproveCacheLocalityProcess::~ImproveCacheLocalityProcess()
  53. {
  54. // nothing to do here
  55. }
  56. // ------------------------------------------------------------------------------------------------
  57. // Returns whether the processing step is present in the given flag field.
  58. bool ImproveCacheLocalityProcess::IsActive( unsigned int pFlags) const
  59. {
  60. return (pFlags & aiProcess_ImproveCacheLocality) != 0;
  61. }
  62. // ------------------------------------------------------------------------------------------------
  63. // Setup configuration
  64. void ImproveCacheLocalityProcess::SetupProperties(const Importer* pImp)
  65. {
  66. // AI_CONFIG_PP_ICL_PTCACHE_SIZE controls the target cache size for the optimizer
  67. configCacheDepth = pImp->GetPropertyInteger(AI_CONFIG_PP_ICL_PTCACHE_SIZE,PP_ICL_PTCACHE_SIZE);
  68. }
  69. // ------------------------------------------------------------------------------------------------
  70. // Executes the post processing step on the given imported data.
  71. void ImproveCacheLocalityProcess::Execute( aiScene* pScene)
  72. {
  73. if (!pScene->mNumMeshes) {
  74. DefaultLogger::get()->debug("ImproveCacheLocalityProcess skipped; there are no meshes");
  75. return;
  76. }
  77. DefaultLogger::get()->debug("ImproveCacheLocalityProcess begin");
  78. float out = 0.f;
  79. unsigned int numf = 0, numm = 0;
  80. for( unsigned int a = 0; a < pScene->mNumMeshes; a++){
  81. const float res = ProcessMesh( pScene->mMeshes[a],a);
  82. if (res) {
  83. numf += pScene->mMeshes[a]->mNumFaces;
  84. out += res;
  85. ++numm;
  86. }
  87. }
  88. if (!DefaultLogger::isNullLogger()) {
  89. char szBuff[128]; // should be sufficiently large in every case
  90. ::sprintf(szBuff,"Cache relevant are %i meshes (%i faces). Average output ACMR is %f",
  91. numm,numf,out/numf);
  92. DefaultLogger::get()->info(szBuff);
  93. DefaultLogger::get()->debug("ImproveCacheLocalityProcess finished. ");
  94. }
  95. }
  96. // ------------------------------------------------------------------------------------------------
  97. // Improves the cache coherency of a specific mesh
  98. float ImproveCacheLocalityProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshNum)
  99. {
  100. // TODO: rewrite this to use std::vector or boost::shared_array
  101. ai_assert(NULL != pMesh);
  102. // Check whether the input data is valid
  103. // - there must be vertices and faces
  104. // - all faces must be triangulated or we can't operate on them
  105. if (!pMesh->HasFaces() || !pMesh->HasPositions())
  106. return 0.f;
  107. if (pMesh->mPrimitiveTypes != aiPrimitiveType_TRIANGLE) {
  108. DefaultLogger::get()->error("This algorithm works on triangle meshes only");
  109. return 0.f;
  110. }
  111. float fACMR = 3.f;
  112. const aiFace* const pcEnd = pMesh->mFaces+pMesh->mNumFaces;
  113. // Input ACMR is for logging purposes only
  114. if (!DefaultLogger::isNullLogger()) {
  115. unsigned int* piFIFOStack = new unsigned int[configCacheDepth];
  116. memset(piFIFOStack,0xff,configCacheDepth*sizeof(unsigned int));
  117. unsigned int* piCur = piFIFOStack;
  118. const unsigned int* const piCurEnd = piFIFOStack + configCacheDepth;
  119. // count the number of cache misses
  120. unsigned int iCacheMisses = 0;
  121. for (const aiFace* pcFace = pMesh->mFaces;pcFace != pcEnd;++pcFace) {
  122. for (unsigned int qq = 0; qq < 3;++qq) {
  123. bool bInCache = false;
  124. for (unsigned int* pp = piFIFOStack;pp < piCurEnd;++pp) {
  125. if (*pp == pcFace->mIndices[qq]) {
  126. // the vertex is in cache
  127. bInCache = true;
  128. break;
  129. }
  130. }
  131. if (!bInCache) {
  132. ++iCacheMisses;
  133. if (piCurEnd == piCur) {
  134. piCur = piFIFOStack;
  135. }
  136. *piCur++ = pcFace->mIndices[qq];
  137. }
  138. }
  139. }
  140. delete[] piFIFOStack;
  141. fACMR = (float)iCacheMisses / pMesh->mNumFaces;
  142. if (3.0 == fACMR) {
  143. char szBuff[128]; // should be sufficiently large in every case
  144. // the JoinIdenticalVertices process has not been executed on this
  145. // mesh, otherwise this value would normally be at least minimally
  146. // smaller than 3.0 ...
  147. sprintf(szBuff,"Mesh %i: Not suitable for vcache optimization",meshNum);
  148. DefaultLogger::get()->warn(szBuff);
  149. return 0.f;
  150. }
  151. }
  152. // first we need to build a vertex-triangle adjacency list
  153. VertexTriangleAdjacency adj(pMesh->mFaces,pMesh->mNumFaces, pMesh->mNumVertices,true);
  154. // build a list to store per-vertex caching time stamps
  155. unsigned int* const piCachingStamps = new unsigned int[pMesh->mNumVertices];
  156. memset(piCachingStamps,0x0,pMesh->mNumVertices*sizeof(unsigned int));
  157. // allocate an empty output index buffer. We store the output indices in one large array.
  158. // Since the number of triangles won't change the input faces can be reused. This is how
  159. // we save thousands of redundant mini allocations for aiFace::mIndices
  160. const unsigned int iIdxCnt = pMesh->mNumFaces*3;
  161. unsigned int* const piIBOutput = new unsigned int[iIdxCnt];
  162. unsigned int* piCSIter = piIBOutput;
  163. // allocate the flag array to hold the information
  164. // whether a face has already been emitted or not
  165. std::vector<bool> abEmitted(pMesh->mNumFaces,false);
  166. // dead-end vertex index stack
  167. std::stack<unsigned int> sDeadEndVStack;
  168. // create a copy of the piNumTriPtr buffer
  169. unsigned int* const piNumTriPtr = adj.mLiveTriangles;
  170. const unsigned int* const piNumTriPtrNoModify = new unsigned int[pMesh->mNumVertices];
  171. memcpy(const_cast<unsigned int* const> (piNumTriPtrNoModify),piNumTriPtr,
  172. pMesh->mNumVertices * sizeof(unsigned int));
  173. // get the largest number of referenced triangles and allocate the "candidate buffer"
  174. unsigned int iMaxRefTris = 0; {
  175. const unsigned int* piCur = adj.mLiveTriangles;
  176. const unsigned int* const piCurEnd = adj.mLiveTriangles+pMesh->mNumVertices;
  177. for (;piCur != piCurEnd;++piCur) {
  178. iMaxRefTris = std::max(iMaxRefTris,*piCur);
  179. }
  180. }
  181. unsigned int* piCandidates = new unsigned int[iMaxRefTris*3];
  182. unsigned int iCacheMisses = 0;
  183. // ...................................................................................
  184. /** PSEUDOCODE for the algorithm
  185. A = Build-Adjacency(I) Vertex-triangle adjacency
  186. L = Get-Triangle-Counts(A) Per-vertex live triangle counts
  187. C = Zero(Vertex-Count(I)) Per-vertex caching time stamps
  188. D = Empty-Stack() Dead-end vertex stack
  189. E = False(Triangle-Count(I)) Per triangle emitted flag
  190. O = Empty-Index-Buffer() Empty output buffer
  191. f = 0 Arbitrary starting vertex
  192. s = k+1, i = 1 Time stamp and cursor
  193. while f >= 0 For all valid fanning vertices
  194. N = Empty-Set() 1-ring of next candidates
  195. for each Triangle t in Neighbors(A, f)
  196. if !Emitted(E,t)
  197. for each Vertex v in t
  198. Append(O,v) Output vertex
  199. Push(D,v) Add to dead-end stack
  200. Insert(N,v) Register as candidate
  201. L[v] = L[v]-1 Decrease live triangle count
  202. if s-C[v] > k If not in cache
  203. C[v] = s Set time stamp
  204. s = s+1 Increment time stamp
  205. E[t] = true Flag triangle as emitted
  206. Select next fanning vertex
  207. f = Get-Next-Vertex(I,i,k,N,C,s,L,D)
  208. return O
  209. */
  210. // ...................................................................................
  211. int ivdx = 0;
  212. int ics = 1;
  213. int iStampCnt = configCacheDepth+1;
  214. while (ivdx >= 0) {
  215. unsigned int icnt = piNumTriPtrNoModify[ivdx];
  216. unsigned int* piList = adj.GetAdjacentTriangles(ivdx);
  217. unsigned int* piCurCandidate = piCandidates;
  218. // get all triangles in the neighborhood
  219. for (unsigned int tri = 0; tri < icnt;++tri) {
  220. // if they have not yet been emitted, add them to the output IB
  221. const unsigned int fidx = *piList++;
  222. if (!abEmitted[fidx]) {
  223. // so iterate through all vertices of the current triangle
  224. const aiFace* pcFace = &pMesh->mFaces[ fidx ];
  225. for (unsigned int* p = pcFace->mIndices, *p2 = pcFace->mIndices+3;p != p2;++p) {
  226. const unsigned int dp = *p;
  227. // the current vertex won't have any free triangles after this step
  228. if (ivdx != (int)dp) {
  229. // append the vertex to the dead-end stack
  230. sDeadEndVStack.push(dp);
  231. // register as candidate for the next step
  232. *piCurCandidate++ = dp;
  233. // decrease the per-vertex triangle counts
  234. piNumTriPtr[dp]--;
  235. }
  236. // append the vertex to the output index buffer
  237. *piCSIter++ = dp;
  238. // if the vertex is not yet in cache, set its cache count
  239. if (iStampCnt-piCachingStamps[dp] > configCacheDepth) {
  240. piCachingStamps[dp] = iStampCnt++;
  241. ++iCacheMisses;
  242. }
  243. }
  244. // flag triangle as emitted
  245. abEmitted[fidx] = true;
  246. }
  247. }
  248. // the vertex has now no living adjacent triangles anymore
  249. piNumTriPtr[ivdx] = 0;
  250. // get next fanning vertex
  251. ivdx = -1;
  252. int max_priority = -1;
  253. for (unsigned int* piCur = piCandidates;piCur != piCurCandidate;++piCur) {
  254. register const unsigned int dp = *piCur;
  255. // must have live triangles
  256. if (piNumTriPtr[dp] > 0) {
  257. int priority = 0;
  258. // will the vertex be in cache, even after fanning occurs?
  259. unsigned int tmp;
  260. if ((tmp = iStampCnt-piCachingStamps[dp]) + 2*piNumTriPtr[dp] <= configCacheDepth) {
  261. priority = tmp;
  262. }
  263. // keep best candidate
  264. if (priority > max_priority) {
  265. max_priority = priority;
  266. ivdx = dp;
  267. }
  268. }
  269. }
  270. // did we reach a dead end?
  271. if (-1 == ivdx) {
  272. // need to get a non-local vertex for which we have a good chance that it is still
  273. // in the cache ...
  274. while (!sDeadEndVStack.empty()) {
  275. unsigned int iCachedIdx = sDeadEndVStack.top();
  276. sDeadEndVStack.pop();
  277. if (piNumTriPtr[ iCachedIdx ] > 0) {
  278. ivdx = iCachedIdx;
  279. break;
  280. }
  281. }
  282. if (-1 == ivdx) {
  283. // well, there isn't such a vertex. Simply get the next vertex in input order and
  284. // hope it is not too bad ...
  285. while (ics < (int)pMesh->mNumVertices) {
  286. ++ics;
  287. if (piNumTriPtr[ics] > 0) {
  288. ivdx = ics;
  289. break;
  290. }
  291. }
  292. }
  293. }
  294. }
  295. float fACMR2 = 0.0f;
  296. if (!DefaultLogger::isNullLogger()) {
  297. fACMR2 = (float)iCacheMisses / pMesh->mNumFaces;
  298. // very intense verbose logging ... prepare for much text if there are many meshes
  299. if ( DefaultLogger::get()->getLogSeverity() == Logger::VERBOSE) {
  300. char szBuff[128]; // should be sufficiently large in every case
  301. ::sprintf(szBuff,"Mesh %i | ACMR in: %f out: %f | ~%.1f%%",meshNum,fACMR,fACMR2,
  302. ((fACMR - fACMR2) / fACMR) * 100.f);
  303. DefaultLogger::get()->debug(szBuff);
  304. }
  305. fACMR2 *= pMesh->mNumFaces;
  306. }
  307. // sort the output index buffer back to the input array
  308. piCSIter = piIBOutput;
  309. for (aiFace* pcFace = pMesh->mFaces; pcFace != pcEnd;++pcFace) {
  310. pcFace->mIndices[0] = *piCSIter++;
  311. pcFace->mIndices[1] = *piCSIter++;
  312. pcFace->mIndices[2] = *piCSIter++;
  313. }
  314. // delete temporary storage
  315. delete[] piCachingStamps;
  316. delete[] piIBOutput;
  317. delete[] piCandidates;
  318. delete[] piNumTriPtrNoModify;
  319. return fACMR2;
  320. }