TriangulateProcess.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2020, 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 TriangulateProcess.cpp
  35. * @brief Implementation of the post processing step to split up
  36. * all faces with more than three indices into triangles.
  37. *
  38. *
  39. * The triangulation algorithm will handle concave or convex polygons.
  40. * Self-intersecting or non-planar polygons are not rejected, but
  41. * they're probably not triangulated correctly.
  42. */
  43. #ifndef ASSIMP_BUILD_NO_TRIANGULATE_PROCESS
  44. #include "PostProcessing/TriangulateProcess.h"
  45. #include "Common/PolyTools.h"
  46. #include "PostProcessing/ProcessHelper.h"
  47. #include "contrib/poly2tri/poly2tri/poly2tri.h"
  48. #include <cstdint>
  49. #include <memory>
  50. namespace Assimp {
  51. // ------------------------------------------------------------------------------------------------
  52. // Constructor to be privately used by Importer
  53. TriangulateProcess::TriangulateProcess() {
  54. // nothing to do here
  55. }
  56. // ------------------------------------------------------------------------------------------------
  57. // Destructor, private as well
  58. TriangulateProcess::~TriangulateProcess() {
  59. // nothing to do here
  60. }
  61. // ------------------------------------------------------------------------------------------------
  62. // Returns whether the processing step is present in the given flag field.
  63. bool TriangulateProcess::IsActive(unsigned int pFlags) const {
  64. return (pFlags & aiProcess_Triangulate) != 0;
  65. }
  66. // ------------------------------------------------------------------------------------------------
  67. // Executes the post processing step on the given imported data.
  68. void TriangulateProcess::Execute(aiScene *pScene) {
  69. ASSIMP_LOG_DEBUG("TriangulateProcess begin");
  70. bool bHas = false;
  71. for (unsigned int a = 0; a < pScene->mNumMeshes; a++) {
  72. if (pScene->mMeshes[a]) {
  73. if (TriangulateMesh(pScene->mMeshes[a])) {
  74. bHas = true;
  75. }
  76. }
  77. }
  78. if (bHas) {
  79. ASSIMP_LOG_INFO("TriangulateProcess finished. All polygons have been triangulated.");
  80. } else {
  81. ASSIMP_LOG_DEBUG("TriangulateProcess finished. There was nothing to be done.");
  82. }
  83. }
  84. // ------------------------------------------------------------------------------------------------
  85. static bool validateNumIndices(aiMesh *mesh) {
  86. bool bNeed = false;
  87. for (unsigned int a = 0; a < mesh->mNumFaces; a++) {
  88. const aiFace &face = mesh->mFaces[a];
  89. if (face.mNumIndices != 3) {
  90. bNeed = true;
  91. break;
  92. }
  93. }
  94. return bNeed;
  95. }
  96. // ------------------------------------------------------------------------------------------------
  97. static void calulateNumOutputFaces(aiMesh *mesh, size_t &numOut, size_t &maxOut, bool &getNormals) {
  98. numOut = maxOut = 0;
  99. getNormals = true;
  100. for (unsigned int a = 0; a < mesh->mNumFaces; a++) {
  101. aiFace &face = mesh->mFaces[a];
  102. if (face.mNumIndices <= 4) {
  103. getNormals = false;
  104. }
  105. if (face.mNumIndices <= 3) {
  106. numOut++;
  107. } else {
  108. numOut += face.mNumIndices - 2;
  109. maxOut = std::max(maxOut, static_cast<size_t>(face.mNumIndices));
  110. }
  111. }
  112. }
  113. // ------------------------------------------------------------------------------------------------
  114. static void quad2Triangles(const aiFace &face, const aiVector3D *verts, aiFace *curOut) {
  115. // quads can have at maximum one concave vertex. Determine
  116. // this vertex (if it exists) and start tri-fanning from
  117. // it.
  118. unsigned int start_vertex = 0;
  119. for (unsigned int i = 0; i < 4; ++i) {
  120. const aiVector3D &v0 = verts[face.mIndices[(i + 3) % 4]];
  121. const aiVector3D &v1 = verts[face.mIndices[(i + 2) % 4]];
  122. const aiVector3D &v2 = verts[face.mIndices[(i + 1) % 4]];
  123. const aiVector3D &v = verts[face.mIndices[i]];
  124. aiVector3D left = (v0 - v);
  125. aiVector3D diag = (v1 - v);
  126. aiVector3D right = (v2 - v);
  127. left.Normalize();
  128. diag.Normalize();
  129. right.Normalize();
  130. const float angle = std::acos(left * diag) + std::acos(right * diag);
  131. if (angle > AI_MATH_PI_F) {
  132. // this is the concave point
  133. start_vertex = i;
  134. break;
  135. }
  136. }
  137. const unsigned int temp[] = { face.mIndices[0], face.mIndices[1], face.mIndices[2], face.mIndices[3] };
  138. aiFace &nface = *curOut++;
  139. nface.mNumIndices = 3;
  140. nface.mIndices = face.mIndices;
  141. nface.mIndices[0] = temp[start_vertex];
  142. nface.mIndices[1] = temp[(start_vertex + 1) % 4];
  143. nface.mIndices[2] = temp[(start_vertex + 2) % 4];
  144. aiFace &sface = *curOut++;
  145. sface.mNumIndices = 3;
  146. sface.mIndices = new unsigned int[3];
  147. sface.mIndices[0] = temp[start_vertex];
  148. sface.mIndices[1] = temp[(start_vertex + 2) % 4];
  149. sface.mIndices[2] = temp[(start_vertex + 3) % 4];
  150. }
  151. // ------------------------------------------------------------------------------------------------
  152. bool getContourFromePolyline(aiFace &face, aiMesh *pMesh, std::vector<p2t::Point *> &contour,
  153. aiMatrix4x4 &m, aiVector3D &vmin, aiVector3D &vmax, ai_real &zcoord) {
  154. aiVector3D normal;
  155. bool ok = true;
  156. m = DerivePlaneCoordinateSpace<ai_real>(pMesh->mVertices, pMesh->mNumVertices, ok, normal);
  157. if (!ok) {
  158. false;
  159. }
  160. for (unsigned int i = 0; i < face.mNumIndices; ++i) {
  161. unsigned int index = face.mIndices[i];
  162. const aiVector3D vv = m * pMesh->mVertices[index];
  163. // keep Z offset in the plane coordinate system. Ignoring precision issues
  164. // (which are present, of course), this should be the same value for
  165. // all polygon vertices (assuming the polygon is planar).
  166. // XXX this should be guarded, but we somehow need to pick a suitable
  167. // epsilon
  168. // if(coord != -1.0f) {
  169. // assert(std::fabs(coord - vv.z) < 1e-3f);
  170. // }
  171. zcoord += vv.z;
  172. vmin = std::min(vv, vmin);
  173. vmax = std::max(vv, vmax);
  174. contour.push_back(new p2t::Point(vv.x, vv.y));
  175. }
  176. zcoord /= pMesh->mNumVertices;
  177. // Further improve the projection by mapping the entire working set into
  178. // [0,1] range. This gives us a consistent data range so all epsilons
  179. // used below can be constants.
  180. vmax -= vmin;
  181. const aiVector2D one_vec(1, 1);
  182. for (p2t::Point* &vv : contour) {
  183. vv->x = (vv->x - vmin.x) / vmax.x;
  184. vv->y = (vv->y - vmin.y) / vmax.y;
  185. // sanity rounding
  186. aiVector2D cur_vv((ai_real) vv->x, (ai_real)vv->y);
  187. cur_vv = std::max(cur_vv, aiVector2D());
  188. cur_vv = std::min(cur_vv, one_vec);
  189. }
  190. aiMatrix4x4 mult;
  191. mult.a1 = static_cast<ai_real>(1.0) / vmax.x;
  192. mult.b2 = static_cast<ai_real>(1.0) / vmax.y;
  193. mult.a4 = -vmin.x * mult.a1;
  194. mult.b4 = -vmin.y * mult.b2;
  195. mult.c4 = -zcoord;
  196. m = mult * m;
  197. return true;
  198. }
  199. // ------------------------------------------------------------------------------------------------
  200. // Triangulates the given mesh.
  201. bool TriangulateProcess::TriangulateMesh(aiMesh *pMesh) {
  202. // Now we have aiMesh::mPrimitiveTypes, so this is only here for test cases
  203. if (!pMesh->mPrimitiveTypes) {
  204. if (!validateNumIndices(pMesh)) {
  205. ASSIMP_LOG_DEBUG("Error while validating number of indices.");
  206. return false;
  207. }
  208. } else if (!(pMesh->mPrimitiveTypes & aiPrimitiveType_POLYGON)) {
  209. ASSIMP_LOG_DEBUG("???!");
  210. return false;
  211. }
  212. // Find out how many output faces we'll get
  213. size_t numOut = 0, max_out = 0;
  214. bool getNormals = true;
  215. calulateNumOutputFaces(pMesh, numOut, max_out, getNormals);
  216. if (numOut == pMesh->mNumFaces) {
  217. ASSIMP_LOG_DEBUG("Error while generating contour.");
  218. return false;
  219. }
  220. // the output mesh will contain triangles, but no polys anymore
  221. pMesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  222. pMesh->mPrimitiveTypes &= ~aiPrimitiveType_POLYGON;
  223. aiFace *out = new aiFace[numOut](), *curOut = out;
  224. const size_t Capa = max_out + 2;
  225. std::vector<aiVector3D> temp_verts3d(max_out + 2); /* temporary storage for vertices */
  226. std::vector<aiVector2D> temp_verts(max_out + 2);
  227. // Apply vertex colors to represent the face winding?
  228. const aiVector3D *verts = pMesh->mVertices;
  229. // use std::unique_ptr to avoid slow std::vector<bool> specialiations
  230. std::unique_ptr<bool[]> done(new bool[max_out]);
  231. for (unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  232. aiFace &face = pMesh->mFaces[a];
  233. // if it's a simple point,line or triangle: just copy it
  234. if (face.mNumIndices <= 3) {
  235. aiFace &nface = *curOut++;
  236. nface.mNumIndices = face.mNumIndices;
  237. nface.mIndices = face.mIndices;
  238. face.mIndices = nullptr;
  239. } else if (face.mNumIndices == 4) {
  240. // optimized code for quadrilaterals
  241. quad2Triangles(face, verts, curOut);
  242. face.mIndices = nullptr;
  243. } else {
  244. std::vector<p2t::Point *> contour;
  245. aiMatrix4x4 m;
  246. aiVector3D vmin, vmax;
  247. ai_real zcoord = -1;
  248. if (!getContourFromePolyline(face, pMesh, contour, m, vmin, vmax, zcoord)) {
  249. ASSIMP_LOG_DEBUG("Error while generating contour.");
  250. continue;
  251. }
  252. p2t::CDT cdt(contour);
  253. cdt.Triangulate();
  254. const std::vector<p2t::Triangle *> tris = cdt.GetTriangles();
  255. const aiMatrix4x4 matInv = m.Inverse();
  256. for (p2t::Triangle *tri : tris) {
  257. curOut->mNumIndices = 3;
  258. curOut->mIndices = new unsigned int[curOut->mNumIndices];
  259. for (int i = 0; i < 3; ++i) {
  260. const aiVector2D v = aiVector2D(static_cast<ai_real>(tri->GetPoint(i)->x), static_cast<ai_real>(tri->GetPoint(i)->y));
  261. // ai_assert(v.x <= 1.0 && v.x >= 0.0 && v.y <= 1.0 && v.y >= 0.0);
  262. const aiVector3D v3 = matInv * aiVector3D(vmin.x + v.x * vmax.x, vmin.y + v.y * vmax.y, zcoord);
  263. temp_verts3d.emplace_back(v3);
  264. curOut->mIndices[i] = (unsigned int) temp_verts3d.size()-1;
  265. }
  266. curOut++;
  267. }
  268. face.mIndices = nullptr;
  269. }
  270. }
  271. delete[] pMesh->mFaces;
  272. pMesh->mFaces = out;
  273. pMesh->mNumVertices = (unsigned int)temp_verts3d.size();
  274. delete[] pMesh->mVertices;
  275. pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  276. for (size_t i = 0; i < temp_verts3d.size(); ++i) {
  277. pMesh->mVertices[i] = temp_verts3d[i];
  278. }
  279. pMesh->mNumFaces = (unsigned int)(curOut - out); /* not necessarily equal to numOut */
  280. return true;
  281. }
  282. } // namespace Assimp
  283. #endif // !! ASSIMP_BUILD_NO_TRIANGULATE_PROCESS