FindInstancesProcess.cpp 12 KB

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