FindInstancesProcess.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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 FindInstancesProcess.cpp
  35. * @brief Implementation of the aiProcess_FindInstances postprocessing step
  36. */
  37. #include "FindInstancesProcess.h"
  38. #include <memory>
  39. #include <stdio.h>
  40. using namespace Assimp;
  41. // ------------------------------------------------------------------------------------------------
  42. // Constructor to be privately used by Importer
  43. FindInstancesProcess::FindInstancesProcess()
  44. : configSpeedFlag (false)
  45. {}
  46. // ------------------------------------------------------------------------------------------------
  47. // Returns whether the processing step is present in the given flag field.
  48. bool FindInstancesProcess::IsActive( unsigned int pFlags) const
  49. {
  50. // FindInstances makes absolutely no sense together with PreTransformVertices
  51. // fixme: spawn error message somewhere else?
  52. return 0 != (pFlags & aiProcess_FindInstances) && 0 == (pFlags & aiProcess_PreTransformVertices);
  53. }
  54. // ------------------------------------------------------------------------------------------------
  55. // Setup properties for the step
  56. void FindInstancesProcess::SetupProperties(const Importer* pImp)
  57. {
  58. // AI_CONFIG_FAVOUR_SPEED
  59. configSpeedFlag = (0 != pImp->GetPropertyInteger(AI_CONFIG_FAVOUR_SPEED,0));
  60. }
  61. // ------------------------------------------------------------------------------------------------
  62. // Compare the bones of two meshes
  63. bool CompareBones(const aiMesh* orig, const aiMesh* inst)
  64. {
  65. for (unsigned int i = 0; i < orig->mNumBones;++i) {
  66. aiBone* aha = orig->mBones[i];
  67. aiBone* oha = inst->mBones[i];
  68. if (aha->mNumWeights != oha->mNumWeights ||
  69. aha->mOffsetMatrix != oha->mOffsetMatrix) {
  70. return false;
  71. }
  72. // compare weight per weight ---
  73. for (unsigned int n = 0; n < aha->mNumWeights;++n) {
  74. if (aha->mWeights[n].mVertexId != oha->mWeights[n].mVertexId ||
  75. (aha->mWeights[n].mWeight - oha->mWeights[n].mWeight) < 10e-3f) {
  76. return false;
  77. }
  78. }
  79. }
  80. return true;
  81. }
  82. // ------------------------------------------------------------------------------------------------
  83. // Update mesh indices in the node graph
  84. void UpdateMeshIndices(aiNode* node, unsigned int* lookup)
  85. {
  86. for (unsigned int n = 0; n < node->mNumMeshes;++n)
  87. node->mMeshes[n] = lookup[node->mMeshes[n]];
  88. for (unsigned int n = 0; n < node->mNumChildren;++n)
  89. UpdateMeshIndices(node->mChildren[n],lookup);
  90. }
  91. // ------------------------------------------------------------------------------------------------
  92. // Executes the post processing step on the given imported data.
  93. void FindInstancesProcess::Execute( aiScene* pScene)
  94. {
  95. ASSIMP_LOG_DEBUG("FindInstancesProcess begin");
  96. if (pScene->mNumMeshes) {
  97. // use a pseudo hash for all meshes in the scene to quickly find
  98. // the ones which are possibly equal. This step is executed early
  99. // in the pipeline, so we could, depending on the file format,
  100. // have several thousand small meshes. That's too much for a brute
  101. // everyone-against-everyone check involving up to 10 comparisons
  102. // each.
  103. std::unique_ptr<uint64_t[]> hashes (new uint64_t[pScene->mNumMeshes]);
  104. std::unique_ptr<unsigned int[]> remapping (new unsigned int[pScene->mNumMeshes]);
  105. unsigned int numMeshesOut = 0;
  106. for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) {
  107. aiMesh* inst = pScene->mMeshes[i];
  108. hashes[i] = GetMeshHash(inst);
  109. // Find an appropriate epsilon
  110. // to compare position differences against
  111. float epsilon = ComputePositionEpsilon(inst);
  112. epsilon *= epsilon;
  113. for (int a = i-1; a >= 0; --a) {
  114. if (hashes[i] == hashes[a])
  115. {
  116. aiMesh* orig = pScene->mMeshes[a];
  117. if (!orig)
  118. continue;
  119. // check for hash collision .. we needn't check
  120. // the vertex format, it *must* match due to the
  121. // (brilliant) construction of the hash
  122. if (orig->mNumBones != inst->mNumBones ||
  123. orig->mNumFaces != inst->mNumFaces ||
  124. orig->mNumVertices != inst->mNumVertices ||
  125. orig->mMaterialIndex != inst->mMaterialIndex ||
  126. orig->mPrimitiveTypes != inst->mPrimitiveTypes)
  127. continue;
  128. // up to now the meshes are equal. Now compare vertex positions, normals,
  129. // tangents and bitangents using this epsilon.
  130. if (orig->HasPositions()) {
  131. if(!CompareArrays(orig->mVertices,inst->mVertices,orig->mNumVertices,epsilon))
  132. continue;
  133. }
  134. if (orig->HasNormals()) {
  135. if(!CompareArrays(orig->mNormals,inst->mNormals,orig->mNumVertices,epsilon))
  136. continue;
  137. }
  138. if (orig->HasTangentsAndBitangents()) {
  139. if (!CompareArrays(orig->mTangents,inst->mTangents,orig->mNumVertices,epsilon) ||
  140. !CompareArrays(orig->mBitangents,inst->mBitangents,orig->mNumVertices,epsilon))
  141. continue;
  142. }
  143. // use a constant epsilon for colors and UV coordinates
  144. static const float uvEpsilon = 10e-4f;
  145. {
  146. unsigned int j, end = orig->GetNumUVChannels();
  147. for(j = 0; j < end; ++j) {
  148. if (!orig->mTextureCoords[j]) {
  149. continue;
  150. }
  151. if(!CompareArrays(orig->mTextureCoords[j],inst->mTextureCoords[j],orig->mNumVertices,uvEpsilon)) {
  152. break;
  153. }
  154. }
  155. if (j != end) {
  156. continue;
  157. }
  158. }
  159. {
  160. unsigned int j, end = orig->GetNumColorChannels();
  161. for(j = 0; j < end; ++j) {
  162. if (!orig->mColors[j]) {
  163. continue;
  164. }
  165. if(!CompareArrays(orig->mColors[j],inst->mColors[j],orig->mNumVertices,uvEpsilon)) {
  166. break;
  167. }
  168. }
  169. if (j != end) {
  170. continue;
  171. }
  172. }
  173. // These two checks are actually quite expensive and almost *never* required.
  174. // Almost. That's why they're still here. But there's no reason to do them
  175. // in speed-targeted imports.
  176. if (!configSpeedFlag) {
  177. // It seems to be strange, but we really need to check whether the
  178. // bones are identical too. Although it's extremely unprobable
  179. // that they're not if control reaches here, we need to deal
  180. // with unprobable cases, too. It could still be that there are
  181. // equal shapes which are deformed differently.
  182. if (!CompareBones(orig,inst))
  183. continue;
  184. // For completeness ... compare even the index buffers for equality
  185. // face order & winding order doesn't care. Input data is in verbose format.
  186. std::unique_ptr<unsigned int[]> ftbl_orig(new unsigned int[orig->mNumVertices]);
  187. std::unique_ptr<unsigned int[]> ftbl_inst(new unsigned int[orig->mNumVertices]);
  188. for (unsigned int tt = 0; tt < orig->mNumFaces;++tt) {
  189. aiFace& f = orig->mFaces[tt];
  190. for (unsigned int nn = 0; nn < f.mNumIndices;++nn)
  191. ftbl_orig[f.mIndices[nn]] = tt;
  192. aiFace& f2 = inst->mFaces[tt];
  193. for (unsigned int nn = 0; nn < f2.mNumIndices;++nn)
  194. ftbl_inst[f2.mIndices[nn]] = tt;
  195. }
  196. if (0 != ::memcmp(ftbl_inst.get(),ftbl_orig.get(),orig->mNumVertices*sizeof(unsigned int)))
  197. continue;
  198. }
  199. // We're still here. Or in other words: 'inst' is an instance of 'orig'.
  200. // Place a marker in our list that we can easily update mesh indices.
  201. remapping[i] = remapping[a];
  202. // Delete the instanced mesh, we don't need it anymore
  203. delete inst;
  204. pScene->mMeshes[i] = nullptr;
  205. break;
  206. }
  207. }
  208. // If we didn't find a match for the current mesh: keep it
  209. if (pScene->mMeshes[i]) {
  210. remapping[i] = numMeshesOut++;
  211. }
  212. }
  213. ai_assert(0 != numMeshesOut);
  214. if (numMeshesOut != pScene->mNumMeshes) {
  215. // Collapse the meshes array by removing all nullptr entries
  216. for (unsigned int real = 0, i = 0; real < numMeshesOut; ++i) {
  217. if (pScene->mMeshes[i])
  218. pScene->mMeshes[real++] = pScene->mMeshes[i];
  219. }
  220. // And update the node graph with our nice lookup table
  221. UpdateMeshIndices(pScene->mRootNode,remapping.get());
  222. // write to log
  223. if (!DefaultLogger::isNullLogger()) {
  224. ASSIMP_LOG_INFO( "FindInstancesProcess finished. Found ", (pScene->mNumMeshes - numMeshesOut), " instances" );
  225. }
  226. pScene->mNumMeshes = numMeshesOut;
  227. } else {
  228. ASSIMP_LOG_DEBUG("FindInstancesProcess finished. No instanced meshes found");
  229. }
  230. }
  231. }