ImproveCacheLocality.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2022, 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. ---------------------------------------------------------------------------
  18. Open Asset Import Library (assimp)
  19. ---------------------------------------------------------------------------
  20. Copyright (c) 2006-2023, assimp team
  21. All rights reserved.
  22. Redistribution and use of this software in source and binary forms,
  23. with or without modification, are permitted provided that the following
  24. conditions are met:
  25. * Redistributions of source code must retain the above
  26. copyright notice, this list of conditions and the
  27. following disclaimer.
  28. * Redistributions in binary form must reproduce the above
  29. copyright notice, this list of conditions and the
  30. following disclaimer in the documentation and/or other
  31. materials provided with the distribution.
  32. * Neither the name of the assimp team, nor the names of its
  33. contributors may be used to endorse or promote products
  34. derived from this software without specific prior
  35. written permission of the assimp team.
  36. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  37. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  38. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  39. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  40. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  42. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  43. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  44. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  45. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  46. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  47. ---------------------------------------------------------------------------
  48. */
  49. /** @file Implementation of the post processing step to improve the cache locality of a mesh.
  50. * <br>
  51. * The algorithm is roughly basing on this paper:
  52. * http://www.cs.princeton.edu/gfx/pubs/Sander_2007_%3ETR/tipsy.pdf
  53. * .. although overdraw reduction isn't implemented yet ...
  54. */
  55. // internal headers
  56. #include "PostProcessing/ImproveCacheLocality.h"
  57. #include "Common/VertexTriangleAdjacency.h"
  58. #include <assimp/StringUtils.h>
  59. #include <assimp/postprocess.h>
  60. #include <assimp/scene.h>
  61. #include <assimp/DefaultLogger.hpp>
  62. #include <stdio.h>
  63. #include <stack>
  64. namespace Assimp {
  65. // ------------------------------------------------------------------------------------------------
  66. // Constructor to be privately used by Importer
  67. ImproveCacheLocalityProcess::ImproveCacheLocalityProcess() :
  68. mConfigCacheDepth(PP_ICL_PTCACHE_SIZE) {
  69. // empty
  70. }
  71. // ------------------------------------------------------------------------------------------------
  72. // Returns whether the processing step is present in the given flag field.
  73. bool ImproveCacheLocalityProcess::IsActive(unsigned int pFlags) const {
  74. return (pFlags & aiProcess_ImproveCacheLocality) != 0;
  75. }
  76. // ------------------------------------------------------------------------------------------------
  77. // Setup configuration
  78. void ImproveCacheLocalityProcess::SetupProperties(const Importer *pImp) {
  79. // AI_CONFIG_PP_ICL_PTCACHE_SIZE controls the target cache size for the optimizer
  80. mConfigCacheDepth = pImp->GetPropertyInteger(AI_CONFIG_PP_ICL_PTCACHE_SIZE, PP_ICL_PTCACHE_SIZE);
  81. }
  82. // ------------------------------------------------------------------------------------------------
  83. // Executes the post processing step on the given imported data.
  84. void ImproveCacheLocalityProcess::Execute(aiScene *pScene) {
  85. if (!pScene->mNumMeshes) {
  86. ASSIMP_LOG_DEBUG("ImproveCacheLocalityProcess skipped; there are no meshes");
  87. return;
  88. }
  89. ASSIMP_LOG_DEBUG("ImproveCacheLocalityProcess begin");
  90. float out = 0.f;
  91. unsigned int numf = 0, numm = 0;
  92. for (unsigned int a = 0; a < pScene->mNumMeshes; ++a) {
  93. const float res = ProcessMesh(pScene->mMeshes[a], a);
  94. if (res) {
  95. numf += pScene->mMeshes[a]->mNumFaces;
  96. out += res;
  97. ++numm;
  98. }
  99. }
  100. if (!DefaultLogger::isNullLogger()) {
  101. if (numf > 0) {
  102. ASSIMP_LOG_INFO("Cache relevant are ", numm, " meshes (", numf, " faces). Average output ACMR is ", out / numf);
  103. }
  104. ASSIMP_LOG_DEBUG("ImproveCacheLocalityProcess finished. ");
  105. }
  106. }
  107. // ------------------------------------------------------------------------------------------------
  108. static ai_real calculateInputACMR(aiMesh *pMesh, const aiFace *const pcEnd,
  109. unsigned int configCacheDepth, unsigned int meshNum) {
  110. ai_real fACMR = 0.0f;
  111. unsigned int *piFIFOStack = new unsigned int[configCacheDepth];
  112. memset(piFIFOStack, 0xff, configCacheDepth * sizeof(unsigned int));
  113. unsigned int *piCur = piFIFOStack;
  114. const unsigned int *const piCurEnd = piFIFOStack + configCacheDepth;
  115. // count the number of cache misses
  116. unsigned int iCacheMisses = 0;
  117. for (const aiFace *pcFace = pMesh->mFaces; pcFace != pcEnd; ++pcFace) {
  118. for (unsigned int qq = 0; qq < 3; ++qq) {
  119. bool bInCache = false;
  120. for (unsigned int *pp = piFIFOStack; pp < piCurEnd; ++pp) {
  121. if (*pp == pcFace->mIndices[qq]) {
  122. // the vertex is in cache
  123. bInCache = true;
  124. break;
  125. }
  126. }
  127. if (!bInCache) {
  128. ++iCacheMisses;
  129. if (piCurEnd == piCur) {
  130. piCur = piFIFOStack;
  131. }
  132. *piCur++ = pcFace->mIndices[qq];
  133. }
  134. }
  135. }
  136. delete[] piFIFOStack;
  137. fACMR = (ai_real)iCacheMisses / pMesh->mNumFaces;
  138. if (3.0 == fACMR) {
  139. char szBuff[128]; // should be sufficiently large in every case
  140. // the JoinIdenticalVertices process has not been executed on this
  141. // mesh, otherwise this value would normally be at least minimally
  142. // smaller than 3.0 ...
  143. ai_snprintf(szBuff, 128, "Mesh %u: Not suitable for vcache optimization", meshNum);
  144. ASSIMP_LOG_WARN(szBuff);
  145. return static_cast<ai_real>(0.f);
  146. }
  147. return fACMR;
  148. }
  149. // ------------------------------------------------------------------------------------------------
  150. // Improves the cache coherency of a specific mesh
  151. ai_real ImproveCacheLocalityProcess::ProcessMesh(aiMesh *pMesh, unsigned int meshNum) {
  152. // TODO: rewrite this to use std::vector or boost::shared_array
  153. ai_assert(nullptr != pMesh);
  154. // Check whether the input data is valid
  155. // - there must be vertices and faces
  156. // - all faces must be triangulated or we can't operate on them
  157. if (!pMesh->HasFaces() || !pMesh->HasPositions())
  158. return static_cast<ai_real>(0.f);
  159. if (pMesh->mPrimitiveTypes != aiPrimitiveType_TRIANGLE) {
  160. ASSIMP_LOG_ERROR("This algorithm works on triangle meshes only");
  161. return static_cast<ai_real>(0.f);
  162. }
  163. if (pMesh->mNumVertices <= mConfigCacheDepth) {
  164. return static_cast<ai_real>(0.f);
  165. }
  166. ai_real fACMR = 3.f;
  167. const aiFace *const pcEnd = pMesh->mFaces + pMesh->mNumFaces;
  168. // Input ACMR is for logging purposes only
  169. if (!DefaultLogger::isNullLogger()) {
  170. fACMR = calculateInputACMR(pMesh, pcEnd, mConfigCacheDepth, meshNum);
  171. }
  172. // first we need to build a vertex-triangle adjacency list
  173. VertexTriangleAdjacency adj(pMesh->mFaces, pMesh->mNumFaces, pMesh->mNumVertices, true);
  174. // build a list to store per-vertex caching time stamps
  175. std::vector<unsigned int> piCachingStamps;
  176. piCachingStamps.resize(pMesh->mNumVertices);
  177. memset(&piCachingStamps[0], 0x0, pMesh->mNumVertices * sizeof(unsigned int));
  178. // allocate an empty output index buffer. We store the output indices in one large array.
  179. // Since the number of triangles won't change the input faces can be reused. This is how
  180. // we save thousands of redundant mini allocations for aiFace::mIndices
  181. const unsigned int iIdxCnt = pMesh->mNumFaces * 3;
  182. std::vector<unsigned int> piIBOutput;
  183. piIBOutput.resize(iIdxCnt);
  184. std::vector<unsigned int>::iterator piCSIter = piIBOutput.begin();
  185. // allocate the flag array to hold the information
  186. // whether a face has already been emitted or not
  187. std::vector<bool> abEmitted(pMesh->mNumFaces, false);
  188. // dead-end vertex index stack
  189. std::stack<unsigned int, std::vector<unsigned int>> sDeadEndVStack;
  190. // create a copy of the piNumTriPtr buffer
  191. unsigned int *const piNumTriPtr = adj.mLiveTriangles;
  192. const std::vector<unsigned int> piNumTriPtrNoModify(piNumTriPtr, piNumTriPtr + pMesh->mNumVertices);
  193. // get the largest number of referenced triangles and allocate the "candidate buffer"
  194. unsigned int iMaxRefTris = 0;
  195. {
  196. const unsigned int *piCur = adj.mLiveTriangles;
  197. const unsigned int *const piCurEnd = adj.mLiveTriangles + pMesh->mNumVertices;
  198. for (; piCur != piCurEnd; ++piCur) {
  199. iMaxRefTris = std::max(iMaxRefTris, *piCur);
  200. }
  201. }
  202. ai_assert(iMaxRefTris > 0);
  203. std::vector<unsigned int> piCandidates;
  204. piCandidates.resize(iMaxRefTris * 3);
  205. unsigned int iCacheMisses = 0;
  206. // ...................................................................................
  207. /** PSEUDOCODE for the algorithm
  208. A = Build-Adjacency(I) Vertex-triangle adjacency
  209. L = Get-Triangle-Counts(A) Per-vertex live triangle counts
  210. C = Zero(Vertex-Count(I)) Per-vertex caching time stamps
  211. D = Empty-Stack() Dead-end vertex stack
  212. E = False(Triangle-Count(I)) Per triangle emitted flag
  213. O = Empty-Index-Buffer() Empty output buffer
  214. f = 0 Arbitrary starting vertex
  215. s = k+1, i = 1 Time stamp and cursor
  216. while f >= 0 For all valid fanning vertices
  217. N = Empty-Set() 1-ring of next candidates
  218. for each Triangle t in Neighbors(A, f)
  219. if !Emitted(E,t)
  220. for each Vertex v in t
  221. Append(O,v) Output vertex
  222. Push(D,v) Add to dead-end stack
  223. Insert(N,v) Register as candidate
  224. L[v] = L[v]-1 Decrease live triangle count
  225. if s-C[v] > k If not in cache
  226. C[v] = s Set time stamp
  227. s = s+1 Increment time stamp
  228. E[t] = true Flag triangle as emitted
  229. Select next fanning vertex
  230. f = Get-Next-Vertex(I,i,k,N,C,s,L,D)
  231. return O
  232. */
  233. // ...................................................................................
  234. int ivdx = 0;
  235. int ics = 1;
  236. int iStampCnt = mConfigCacheDepth + 1;
  237. while (ivdx >= 0) {
  238. unsigned int icnt = piNumTriPtrNoModify[ivdx];
  239. unsigned int *piList = adj.GetAdjacentTriangles(ivdx);
  240. std::vector<unsigned int>::iterator piCurCandidate = piCandidates.begin();
  241. // get all triangles in the neighborhood
  242. for (unsigned int tri = 0; tri < icnt; ++tri) {
  243. // if they have not yet been emitted, add them to the output IB
  244. const unsigned int fidx = *piList++;
  245. if (!abEmitted[fidx]) {
  246. // so iterate through all vertices of the current triangle
  247. const aiFace *pcFace = &pMesh->mFaces[fidx];
  248. const unsigned nind = pcFace->mNumIndices;
  249. for (unsigned ind = 0; ind < nind; ind++) {
  250. unsigned dp = pcFace->mIndices[ind];
  251. // the current vertex won't have any free triangles after this step
  252. if (ivdx != (int)dp) {
  253. // append the vertex to the dead-end stack
  254. sDeadEndVStack.push(dp);
  255. // register as candidate for the next step
  256. *piCurCandidate++ = dp;
  257. // decrease the per-vertex triangle counts
  258. piNumTriPtr[dp]--;
  259. }
  260. // append the vertex to the output index buffer
  261. *piCSIter++ = dp;
  262. // if the vertex is not yet in cache, set its cache count
  263. if (iStampCnt - piCachingStamps[dp] > mConfigCacheDepth) {
  264. piCachingStamps[dp] = iStampCnt++;
  265. ++iCacheMisses;
  266. }
  267. }
  268. // flag triangle as emitted
  269. abEmitted[fidx] = true;
  270. }
  271. }
  272. // the vertex has now no living adjacent triangles anymore
  273. piNumTriPtr[ivdx] = 0;
  274. // get next fanning vertex
  275. ivdx = -1;
  276. int max_priority = -1;
  277. for (std::vector<unsigned int>::iterator piCur = piCandidates.begin(); piCur != piCurCandidate; ++piCur) {
  278. const unsigned int dp = *piCur;
  279. // must have live triangles
  280. if (piNumTriPtr[dp] > 0) {
  281. int priority = 0;
  282. // will the vertex be in cache, even after fanning occurs?
  283. unsigned int tmp;
  284. if ((tmp = iStampCnt - piCachingStamps[dp]) + 2 * piNumTriPtr[dp] <= mConfigCacheDepth) {
  285. priority = tmp;
  286. }
  287. // keep best candidate
  288. if (priority > max_priority) {
  289. max_priority = priority;
  290. ivdx = dp;
  291. }
  292. }
  293. }
  294. // did we reach a dead end?
  295. if (-1 == ivdx) {
  296. // need to get a non-local vertex for which we have a good chance that it is still
  297. // in the cache ...
  298. while (!sDeadEndVStack.empty()) {
  299. unsigned int iCachedIdx = sDeadEndVStack.top();
  300. sDeadEndVStack.pop();
  301. if (piNumTriPtr[iCachedIdx] > 0) {
  302. ivdx = iCachedIdx;
  303. break;
  304. }
  305. }
  306. if (-1 == ivdx) {
  307. // well, there isn't such a vertex. Simply get the next vertex in input order and
  308. // hope it is not too bad ...
  309. while (ics < (int)pMesh->mNumVertices) {
  310. ++ics;
  311. if (piNumTriPtr[ics] > 0) {
  312. ivdx = ics;
  313. break;
  314. }
  315. }
  316. }
  317. }
  318. }
  319. ai_real fACMR2 = 0.0f;
  320. if (!DefaultLogger::isNullLogger()) {
  321. fACMR2 = static_cast<ai_real>(iCacheMisses / pMesh->mNumFaces);
  322. const ai_real averageACMR = ((fACMR - fACMR2) / fACMR) * 100.f;
  323. // very intense verbose logging ... prepare for much text if there are many meshes
  324. if (DefaultLogger::get()->getLogSeverity() == Logger::VERBOSE) {
  325. ASSIMP_LOG_VERBOSE_DEBUG("Mesh ", meshNum, "| ACMR in: ", fACMR, " out: ", fACMR2, " | average ACMR ", averageACMR);
  326. }
  327. fACMR2 *= pMesh->mNumFaces;
  328. }
  329. // sort the output index buffer back to the input array
  330. piCSIter = piIBOutput.begin();
  331. for (aiFace *pcFace = pMesh->mFaces; pcFace != pcEnd; ++pcFace) {
  332. unsigned nind = pcFace->mNumIndices;
  333. unsigned *ind = pcFace->mIndices;
  334. if (nind > 0)
  335. ind[0] = *piCSIter++;
  336. if (nind > 1)
  337. ind[1] = *piCSIter++;
  338. if (nind > 2)
  339. ind[2] = *piCSIter++;
  340. }
  341. return fACMR2;
  342. }
  343. } // namespace Assimp