TriangulateProcess.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2025, 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. * DEBUG SWITCHES - do not enable any of them in release builds:
  44. *
  45. * AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
  46. * - generates vertex colors to represent the face winding order.
  47. * the first vertex of a polygon becomes red, the last blue.
  48. * AI_BUILD_TRIANGULATE_DEBUG_POLYS
  49. * - dump all polygons and their triangulation sequences to
  50. * a file
  51. */
  52. #ifndef ASSIMP_BUILD_NO_TRIANGULATE_PROCESS
  53. #include "PostProcessing/TriangulateProcess.h"
  54. #include "PostProcessing/ProcessHelper.h"
  55. #include "Common/PolyTools.h"
  56. #include "contrib/earcut-hpp/earcut.hpp"
  57. #include <memory>
  58. #include <cstdint>
  59. //#define AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
  60. //#define AI_BUILD_TRIANGULATE_DEBUG_POLYS
  61. #define POLY_GRID_Y 40
  62. #define POLY_GRID_X 70
  63. #define POLY_GRID_XPAD 20
  64. #define POLY_OUTPUT_FILE "assimp_polygons_debug.txt"
  65. namespace mapbox::util {
  66. template <>
  67. struct nth<0, aiVector2D> {
  68. inline static auto get(const aiVector2D& t) {
  69. return t.x;
  70. }
  71. };
  72. template <>
  73. struct nth<1, aiVector2D> {
  74. inline static auto get(const aiVector2D& t) {
  75. return t.y;
  76. }
  77. };
  78. } // namespace mapbox::util
  79. using namespace Assimp;
  80. namespace {
  81. /**
  82. * @brief Helper struct used to simplify NGON encoding functions.
  83. */
  84. struct NGONEncoder {
  85. NGONEncoder() : mLastNGONFirstIndex((unsigned int)-1) {}
  86. /**
  87. * @brief Encode the current triangle, and make sure it is recognized as a triangle.
  88. *
  89. * This method will rotate indices in tri if needed in order to avoid tri to be considered
  90. * part of the previous ngon. This method is to be used whenever you want to emit a real triangle,
  91. * and make sure it is seen as a triangle.
  92. *
  93. * @param tri Triangle to encode.
  94. */
  95. void ngonEncodeTriangle(aiFace * tri) {
  96. ai_assert(tri->mNumIndices == 3);
  97. // Rotate indices in new triangle to avoid ngon encoding false ngons
  98. // Otherwise, the new triangle would be considered part of the previous NGON.
  99. if (isConsideredSameAsLastNgon(tri)) {
  100. std::swap(tri->mIndices[0], tri->mIndices[2]);
  101. std::swap(tri->mIndices[1], tri->mIndices[2]);
  102. }
  103. mLastNGONFirstIndex = tri->mIndices[0];
  104. }
  105. /**
  106. * @brief Encode a quad (2 triangles) in ngon encoding, and make sure they are seen as a single ngon.
  107. *
  108. * @param tri1 First quad triangle
  109. * @param tri2 Second quad triangle
  110. *
  111. * @pre Triangles must be properly fanned from the most appropriate vertex.
  112. */
  113. void ngonEncodeQuad(aiFace *tri1, aiFace *tri2) {
  114. ai_assert(tri1->mNumIndices == 3);
  115. ai_assert(tri2->mNumIndices == 3);
  116. ai_assert(tri1->mIndices[0] == tri2->mIndices[0]);
  117. // If the selected fanning vertex is the same as the previously
  118. // emitted ngon, we use the opposite vertex which also happens to work
  119. // for tri-fanning a concave quad.
  120. // ref: https://github.com/assimp/assimp/pull/3695#issuecomment-805999760
  121. if (isConsideredSameAsLastNgon(tri1)) {
  122. // Right-rotate indices for tri1 (index 2 becomes the new fanning vertex)
  123. std::swap(tri1->mIndices[0], tri1->mIndices[2]);
  124. std::swap(tri1->mIndices[1], tri1->mIndices[2]);
  125. // Left-rotate indices for tri2 (index 2 becomes the new fanning vertex)
  126. std::swap(tri2->mIndices[1], tri2->mIndices[2]);
  127. std::swap(tri2->mIndices[0], tri2->mIndices[2]);
  128. ai_assert(tri1->mIndices[0] == tri2->mIndices[0]);
  129. }
  130. mLastNGONFirstIndex = tri1->mIndices[0];
  131. }
  132. /**
  133. * @brief Check whether this triangle would be considered part of the lastly emitted ngon or not.
  134. *
  135. * @param tri Current triangle.
  136. * @return true If used as is, this triangle will be part of last ngon.
  137. * @return false If used as is, this triangle is not considered part of the last ngon.
  138. */
  139. bool isConsideredSameAsLastNgon(const aiFace * tri) const {
  140. ai_assert(tri->mNumIndices == 3);
  141. return tri->mIndices[0] == mLastNGONFirstIndex;
  142. }
  143. private:
  144. unsigned int mLastNGONFirstIndex;
  145. };
  146. }
  147. // ------------------------------------------------------------------------------------------------
  148. // Returns whether the processing step is present in the given flag field.
  149. bool TriangulateProcess::IsActive( unsigned int pFlags) const {
  150. return (pFlags & aiProcess_Triangulate) != 0;
  151. }
  152. // ------------------------------------------------------------------------------------------------
  153. // Executes the post processing step on the given imported data.
  154. void TriangulateProcess::Execute( aiScene* pScene) {
  155. ASSIMP_LOG_DEBUG("TriangulateProcess begin");
  156. bool bHas = false;
  157. for( unsigned int a = 0; a < pScene->mNumMeshes; a++)
  158. {
  159. if (pScene->mMeshes[ a ]) {
  160. if ( TriangulateMesh( pScene->mMeshes[ a ] ) ) {
  161. bHas = true;
  162. }
  163. }
  164. }
  165. if ( bHas ) {
  166. ASSIMP_LOG_INFO( "TriangulateProcess finished. All polygons have been triangulated." );
  167. } else {
  168. ASSIMP_LOG_DEBUG( "TriangulateProcess finished. There was nothing to be done." );
  169. }
  170. }
  171. // ------------------------------------------------------------------------------------------------
  172. // Triangulates the given mesh.
  173. bool TriangulateProcess::TriangulateMesh( aiMesh* pMesh) {
  174. // Now we have aiMesh::mPrimitiveTypes, so this is only here for test cases
  175. if (!pMesh->mPrimitiveTypes) {
  176. bool bNeed = false;
  177. for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  178. const aiFace& face = pMesh->mFaces[a];
  179. if( face.mNumIndices != 3) {
  180. bNeed = true;
  181. }
  182. }
  183. if (!bNeed) {
  184. return false;
  185. }
  186. }
  187. else if (!(pMesh->mPrimitiveTypes & aiPrimitiveType_POLYGON)) {
  188. return false;
  189. }
  190. // Find out how many output faces we'll get
  191. uint32_t numOut = 0, max_out = 0;
  192. bool get_normals = true;
  193. for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  194. aiFace& face = pMesh->mFaces[a];
  195. if (face.mNumIndices <= 4) {
  196. get_normals = false;
  197. }
  198. if( face.mNumIndices <= 3) {
  199. ++numOut;
  200. } else {
  201. numOut += face.mNumIndices-2;
  202. max_out = std::max(max_out,face.mNumIndices);
  203. }
  204. }
  205. // Just another check whether aiMesh::mPrimitiveTypes is correct
  206. if (numOut == pMesh->mNumFaces) {
  207. ASSIMP_LOG_ERROR( "Invalidation detected in the number of indices: does not fit to the primitive type." );
  208. return false;
  209. }
  210. aiVector3D *nor_out = nullptr;
  211. // if we don't have normals yet, but expect them to be a cheap side
  212. // product of triangulation anyway, allocate storage for them.
  213. if (!pMesh->mNormals && get_normals) {
  214. // XXX need a mechanism to inform the GenVertexNormals process to treat these normals as preprocessed per-face normals
  215. // nor_out = pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  216. }
  217. // the output mesh will contain triangles, but no polys anymore
  218. pMesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  219. pMesh->mPrimitiveTypes &= ~aiPrimitiveType_POLYGON;
  220. // The mesh becomes NGON encoded now, during the triangulation process.
  221. pMesh->mPrimitiveTypes |= aiPrimitiveType_NGONEncodingFlag;
  222. aiFace* out = new aiFace[numOut](), *curOut = out;
  223. std::vector<aiVector3D> temp_verts3d(max_out+2); /* temporary storage for vertices */
  224. std::vector<std::vector<aiVector2D>> temp_poly(1); /* temporary storage for earcut.hpp */
  225. std::vector<aiVector2D>& temp_verts = temp_poly[0];
  226. temp_verts.reserve(max_out + 2);
  227. NGONEncoder ngonEncoder;
  228. // Apply vertex colors to represent the face winding?
  229. #ifdef AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
  230. if (!pMesh->mColors[0])
  231. pMesh->mColors[0] = new aiColor4D[pMesh->mNumVertices];
  232. else
  233. new(pMesh->mColors[0]) aiColor4D[pMesh->mNumVertices];
  234. aiColor4D* clr = pMesh->mColors[0];
  235. #endif
  236. #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
  237. FILE* fout = fopen(POLY_OUTPUT_FILE,"a");
  238. #endif
  239. const aiVector3D* verts = pMesh->mVertices;
  240. for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  241. aiFace& face = pMesh->mFaces[a];
  242. unsigned int* idx = face.mIndices;
  243. unsigned int num = face.mNumIndices;
  244. // Apply vertex colors to represent the face winding?
  245. #ifdef AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
  246. for (unsigned int i = 0; i < face.mNumIndices; ++i) {
  247. aiColor4D& c = clr[idx[i]];
  248. c.r = (i+1) / (float)max;
  249. c.b = 1.f - c.r;
  250. }
  251. #endif
  252. aiFace* const last_face = curOut;
  253. // if it's a simple point,line or triangle: just copy it
  254. if( face.mNumIndices <= 3)
  255. {
  256. aiFace& nface = *curOut++;
  257. nface.mNumIndices = face.mNumIndices;
  258. nface.mIndices = face.mIndices;
  259. face.mIndices = nullptr;
  260. // points and lines don't require ngon encoding (and are not supported either!)
  261. if (nface.mNumIndices == 3) ngonEncoder.ngonEncodeTriangle(&nface);
  262. continue;
  263. }
  264. // optimized code for quadrilaterals
  265. else if ( face.mNumIndices == 4) {
  266. // quads can have at maximum one concave vertex. Determine
  267. // this vertex (if it exists) and start tri-fanning from
  268. // it.
  269. unsigned int start_vertex = 0;
  270. for (unsigned int i = 0; i < 4; ++i) {
  271. const aiVector3D& v0 = verts[face.mIndices[(i+3) % 4]];
  272. const aiVector3D& v1 = verts[face.mIndices[(i+2) % 4]];
  273. const aiVector3D& v2 = verts[face.mIndices[(i+1) % 4]];
  274. const aiVector3D& v = verts[face.mIndices[i]];
  275. aiVector3D left = (v0-v);
  276. aiVector3D diag = (v1-v);
  277. aiVector3D right = (v2-v);
  278. left.Normalize();
  279. diag.Normalize();
  280. right.Normalize();
  281. const float angle = std::acos(left*diag) + std::acos(right*diag);
  282. if (angle > AI_MATH_PI_F) {
  283. // this is the concave point
  284. start_vertex = i;
  285. break;
  286. }
  287. }
  288. const unsigned int temp[] = {face.mIndices[0], face.mIndices[1], face.mIndices[2], face.mIndices[3]};
  289. aiFace& nface = *curOut++;
  290. nface.mNumIndices = 3;
  291. nface.mIndices = face.mIndices;
  292. nface.mIndices[0] = temp[start_vertex];
  293. nface.mIndices[1] = temp[(start_vertex + 1) % 4];
  294. nface.mIndices[2] = temp[(start_vertex + 2) % 4];
  295. aiFace& sface = *curOut++;
  296. sface.mNumIndices = 3;
  297. sface.mIndices = new unsigned int[3];
  298. sface.mIndices[0] = temp[start_vertex];
  299. sface.mIndices[1] = temp[(start_vertex + 2) % 4];
  300. sface.mIndices[2] = temp[(start_vertex + 3) % 4];
  301. // prevent double deletion of the indices field
  302. face.mIndices = nullptr;
  303. ngonEncoder.ngonEncodeQuad(&nface, &sface);
  304. continue;
  305. }
  306. else
  307. {
  308. // A polygon with more than 3 vertices can be either concave or convex.
  309. // Usually everything we're getting is convex and we could easily
  310. // triangulate by tri-fanning. However, LightWave is probably the only
  311. // modeling suite to make extensive use of highly concave, monster polygons ...
  312. // so we need to apply the full 'ear cutting' algorithm to get it right.
  313. // REQUIREMENT: polygon is expected to be simple and *nearly* planar.
  314. // We project it onto a plane to get a 2d triangle.
  315. // Collect all vertices of of the polygon.
  316. for (unsigned int tmp = 0; tmp < num; ++tmp) {
  317. temp_verts3d[tmp] = verts[idx[tmp]];
  318. }
  319. // Get newell normal of the polygon. Store it for future use if it's a polygon-only mesh
  320. aiVector3D n;
  321. NewellNormal<3, 3, 3>(n, num, &temp_verts3d.front().x, &temp_verts3d.front().y, &temp_verts3d.front().z);
  322. if (nor_out) {
  323. for (unsigned int tmp = 0; tmp < num; ++tmp)
  324. nor_out[idx[tmp]] = n;
  325. }
  326. // Select largest normal coordinate to ignore for projection
  327. const float ax = (n.x>0 ? n.x : -n.x);
  328. const float ay = (n.y>0 ? n.y : -n.y);
  329. const float az = (n.z>0 ? n.z : -n.z);
  330. unsigned int ac = 0, bc = 1; /* no z coord. projection to xy */
  331. float inv = n.z;
  332. if (ax > ay) {
  333. if (ax > az) { /* no x coord. projection to yz */
  334. ac = 1; bc = 2;
  335. inv = n.x;
  336. }
  337. }
  338. else if (ay > az) { /* no y coord. projection to zy */
  339. ac = 2; bc = 0;
  340. inv = n.y;
  341. }
  342. // Swap projection axes to take the negated projection vector into account
  343. if (inv < 0.f) {
  344. std::swap(ac,bc);
  345. }
  346. temp_verts.resize(num);
  347. for (unsigned int tmp = 0; tmp < num; ++tmp) {
  348. temp_verts[tmp].x = verts[idx[tmp]][ac];
  349. temp_verts[tmp].y = verts[idx[tmp]][bc];
  350. }
  351. auto indices = mapbox::earcut(temp_poly);
  352. for (size_t i = 0; i < indices.size(); i += 3) {
  353. aiFace& nface = *curOut++;
  354. nface.mIndices = new unsigned int[3];
  355. nface.mNumIndices = 3;
  356. nface.mIndices[0] = indices[i];
  357. nface.mIndices[1] = indices[i + 1];
  358. nface.mIndices[2] = indices[i + 2];
  359. }
  360. #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
  361. // plot the plane onto which we mapped the polygon to a 2D ASCII pic
  362. aiVector2D bmin,bmax;
  363. ArrayBounds(&temp_verts[0],max,bmin,bmax);
  364. char grid[POLY_GRID_Y][POLY_GRID_X+POLY_GRID_XPAD];
  365. std::fill_n((char*)grid,POLY_GRID_Y*(POLY_GRID_X+POLY_GRID_XPAD),' ');
  366. for (int i =0; i < max; ++i) {
  367. const aiVector2D& v = (temp_verts[i] - bmin) / (bmax-bmin);
  368. const size_t x = static_cast<size_t>(v.x*(POLY_GRID_X-1)), y = static_cast<size_t>(v.y*(POLY_GRID_Y-1));
  369. char* loc = grid[y]+x;
  370. if (grid[y][x] != ' ') {
  371. for(;*loc != ' '; ++loc);
  372. *loc++ = '_';
  373. }
  374. *(loc+::ai_snprintf(loc, POLY_GRID_XPAD,"%i",i)) = ' ';
  375. }
  376. for(size_t y = 0; y < POLY_GRID_Y; ++y) {
  377. grid[y][POLY_GRID_X+POLY_GRID_XPAD-1] = '\0';
  378. fprintf(fout,"%s\n",grid[y]);
  379. }
  380. fprintf(fout,"\ntriangulation sequence: ");
  381. #endif
  382. }
  383. #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
  384. for(aiFace* f = last_face; f != curOut; ++f) {
  385. unsigned int* i = f->mIndices;
  386. fprintf(fout," (%i %i %i)",i[0],i[1],i[2]);
  387. }
  388. fprintf(fout,"\n*********************************************************************\n");
  389. fflush(fout);
  390. #endif
  391. for(aiFace* f = last_face; f != curOut; ) {
  392. unsigned int* i = f->mIndices;
  393. i[0] = idx[i[0]];
  394. i[1] = idx[i[1]];
  395. i[2] = idx[i[2]];
  396. // IMPROVEMENT: Polygons are not supported yet by this ngon encoding + triangulation step.
  397. // So we encode polygons as regular triangles. No way to reconstruct the original
  398. // polygon in this case.
  399. ngonEncoder.ngonEncodeTriangle(f);
  400. ++f;
  401. }
  402. delete[] face.mIndices;
  403. face.mIndices = nullptr;
  404. }
  405. #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
  406. fclose(fout);
  407. #endif
  408. // kill the old faces
  409. delete [] pMesh->mFaces;
  410. // ... and store the new ones
  411. pMesh->mFaces = out;
  412. pMesh->mNumFaces = (unsigned int)(curOut-out); /* not necessarily equal to numOut */
  413. return true;
  414. }
  415. #endif // !! ASSIMP_BUILD_NO_TRIANGULATE_PROCESS