TriangulateProcess.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. * 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 <memory>
  57. //#define AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
  58. //#define AI_BUILD_TRIANGULATE_DEBUG_POLYS
  59. #define POLY_GRID_Y 40
  60. #define POLY_GRID_X 70
  61. #define POLY_GRID_XPAD 20
  62. #define POLY_OUTPUT_FILE "assimp_polygons_debug.txt"
  63. using namespace Assimp;
  64. // ------------------------------------------------------------------------------------------------
  65. // Constructor to be privately used by Importer
  66. TriangulateProcess::TriangulateProcess()
  67. {
  68. // nothing to do here
  69. }
  70. // ------------------------------------------------------------------------------------------------
  71. // Destructor, private as well
  72. TriangulateProcess::~TriangulateProcess()
  73. {
  74. // nothing to do here
  75. }
  76. // ------------------------------------------------------------------------------------------------
  77. // Returns whether the processing step is present in the given flag field.
  78. bool TriangulateProcess::IsActive( unsigned int pFlags) const
  79. {
  80. return (pFlags & aiProcess_Triangulate) != 0;
  81. }
  82. // ------------------------------------------------------------------------------------------------
  83. // Executes the post processing step on the given imported data.
  84. void TriangulateProcess::Execute( aiScene* pScene)
  85. {
  86. ASSIMP_LOG_DEBUG("TriangulateProcess begin");
  87. bool bHas = false;
  88. for( unsigned int a = 0; a < pScene->mNumMeshes; a++)
  89. {
  90. if (pScene->mMeshes[ a ]) {
  91. if ( TriangulateMesh( pScene->mMeshes[ a ] ) ) {
  92. bHas = true;
  93. }
  94. }
  95. }
  96. if ( bHas ) {
  97. ASSIMP_LOG_INFO( "TriangulateProcess finished. All polygons have been triangulated." );
  98. } else {
  99. ASSIMP_LOG_DEBUG( "TriangulateProcess finished. There was nothing to be done." );
  100. }
  101. }
  102. // ------------------------------------------------------------------------------------------------
  103. // Triangulates the given mesh.
  104. bool TriangulateProcess::TriangulateMesh( aiMesh* pMesh)
  105. {
  106. // Now we have aiMesh::mPrimitiveTypes, so this is only here for test cases
  107. if (!pMesh->mPrimitiveTypes) {
  108. bool bNeed = false;
  109. for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  110. const aiFace& face = pMesh->mFaces[a];
  111. if( face.mNumIndices != 3) {
  112. bNeed = true;
  113. }
  114. }
  115. if (!bNeed)
  116. return false;
  117. }
  118. else if (!(pMesh->mPrimitiveTypes & aiPrimitiveType_POLYGON)) {
  119. return false;
  120. }
  121. // Find out how many output faces we'll get
  122. unsigned int numOut = 0, max_out = 0;
  123. bool get_normals = true;
  124. for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  125. aiFace& face = pMesh->mFaces[a];
  126. if (face.mNumIndices <= 4) {
  127. get_normals = false;
  128. }
  129. if( face.mNumIndices <= 3) {
  130. numOut++;
  131. }
  132. else {
  133. numOut += face.mNumIndices-2;
  134. max_out = std::max(max_out,face.mNumIndices);
  135. }
  136. }
  137. // Just another check whether aiMesh::mPrimitiveTypes is correct
  138. ai_assert(numOut != pMesh->mNumFaces);
  139. aiVector3D *nor_out = nullptr;
  140. // if we don't have normals yet, but expect them to be a cheap side
  141. // product of triangulation anyway, allocate storage for them.
  142. if (!pMesh->mNormals && get_normals) {
  143. // XXX need a mechanism to inform the GenVertexNormals process to treat these normals as preprocessed per-face normals
  144. // nor_out = pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  145. }
  146. // the output mesh will contain triangles, but no polys anymore
  147. pMesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  148. pMesh->mPrimitiveTypes &= ~aiPrimitiveType_POLYGON;
  149. aiFace* out = new aiFace[numOut](), *curOut = out;
  150. std::vector<aiVector3D> temp_verts3d(max_out+2); /* temporary storage for vertices */
  151. std::vector<aiVector2D> temp_verts(max_out+2);
  152. // Apply vertex colors to represent the face winding?
  153. #ifdef AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
  154. if (!pMesh->mColors[0])
  155. pMesh->mColors[0] = new aiColor4D[pMesh->mNumVertices];
  156. else
  157. new(pMesh->mColors[0]) aiColor4D[pMesh->mNumVertices];
  158. aiColor4D* clr = pMesh->mColors[0];
  159. #endif
  160. #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
  161. FILE* fout = fopen(POLY_OUTPUT_FILE,"a");
  162. #endif
  163. const aiVector3D* verts = pMesh->mVertices;
  164. // use std::unique_ptr to avoid slow std::vector<bool> specialiations
  165. std::unique_ptr<bool[]> done(new bool[max_out]);
  166. for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  167. aiFace& face = pMesh->mFaces[a];
  168. unsigned int* idx = face.mIndices;
  169. int num = (int)face.mNumIndices, ear = 0, tmp, prev = num-1, next = 0, max = num;
  170. // Apply vertex colors to represent the face winding?
  171. #ifdef AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
  172. for (unsigned int i = 0; i < face.mNumIndices; ++i) {
  173. aiColor4D& c = clr[idx[i]];
  174. c.r = (i+1) / (float)max;
  175. c.b = 1.f - c.r;
  176. }
  177. #endif
  178. aiFace* const last_face = curOut;
  179. // if it's a simple point,line or triangle: just copy it
  180. if( face.mNumIndices <= 3)
  181. {
  182. aiFace& nface = *curOut++;
  183. nface.mNumIndices = face.mNumIndices;
  184. nface.mIndices = face.mIndices;
  185. face.mIndices = nullptr;
  186. continue;
  187. }
  188. // optimized code for quadrilaterals
  189. else if ( face.mNumIndices == 4) {
  190. // quads can have at maximum one concave vertex. Determine
  191. // this vertex (if it exists) and start tri-fanning from
  192. // it.
  193. unsigned int start_vertex = 0;
  194. for (unsigned int i = 0; i < 4; ++i) {
  195. const aiVector3D& v0 = verts[face.mIndices[(i+3) % 4]];
  196. const aiVector3D& v1 = verts[face.mIndices[(i+2) % 4]];
  197. const aiVector3D& v2 = verts[face.mIndices[(i+1) % 4]];
  198. const aiVector3D& v = verts[face.mIndices[i]];
  199. aiVector3D left = (v0-v);
  200. aiVector3D diag = (v1-v);
  201. aiVector3D right = (v2-v);
  202. left.Normalize();
  203. diag.Normalize();
  204. right.Normalize();
  205. const float angle = std::acos(left*diag) + std::acos(right*diag);
  206. if (angle > AI_MATH_PI_F) {
  207. // this is the concave point
  208. start_vertex = i;
  209. break;
  210. }
  211. }
  212. const unsigned int temp[] = {face.mIndices[0], face.mIndices[1], face.mIndices[2], face.mIndices[3]};
  213. aiFace& nface = *curOut++;
  214. nface.mNumIndices = 3;
  215. nface.mIndices = face.mIndices;
  216. nface.mIndices[0] = temp[start_vertex];
  217. nface.mIndices[1] = temp[(start_vertex + 1) % 4];
  218. nface.mIndices[2] = temp[(start_vertex + 2) % 4];
  219. aiFace& sface = *curOut++;
  220. sface.mNumIndices = 3;
  221. sface.mIndices = new unsigned int[3];
  222. sface.mIndices[0] = temp[start_vertex];
  223. sface.mIndices[1] = temp[(start_vertex + 2) % 4];
  224. sface.mIndices[2] = temp[(start_vertex + 3) % 4];
  225. // prevent double deletion of the indices field
  226. face.mIndices = nullptr;
  227. continue;
  228. }
  229. else
  230. {
  231. // A polygon with more than 3 vertices can be either concave or convex.
  232. // Usually everything we're getting is convex and we could easily
  233. // triangulate by tri-fanning. However, LightWave is probably the only
  234. // modeling suite to make extensive use of highly concave, monster polygons ...
  235. // so we need to apply the full 'ear cutting' algorithm to get it right.
  236. // RERQUIREMENT: polygon is expected to be simple and *nearly* planar.
  237. // We project it onto a plane to get a 2d triangle.
  238. // Collect all vertices of of the polygon.
  239. for (tmp = 0; tmp < max; ++tmp) {
  240. temp_verts3d[tmp] = verts[idx[tmp]];
  241. }
  242. // Get newell normal of the polygon. Store it for future use if it's a polygon-only mesh
  243. aiVector3D n;
  244. NewellNormal<3,3,3>(n,max,&temp_verts3d.front().x,&temp_verts3d.front().y,&temp_verts3d.front().z);
  245. if (nor_out) {
  246. for (tmp = 0; tmp < max; ++tmp)
  247. nor_out[idx[tmp]] = n;
  248. }
  249. // Select largest normal coordinate to ignore for projection
  250. const float ax = (n.x>0 ? n.x : -n.x);
  251. const float ay = (n.y>0 ? n.y : -n.y);
  252. const float az = (n.z>0 ? n.z : -n.z);
  253. unsigned int ac = 0, bc = 1; /* no z coord. projection to xy */
  254. float inv = n.z;
  255. if (ax > ay) {
  256. if (ax > az) { /* no x coord. projection to yz */
  257. ac = 1; bc = 2;
  258. inv = n.x;
  259. }
  260. }
  261. else if (ay > az) { /* no y coord. projection to zy */
  262. ac = 2; bc = 0;
  263. inv = n.y;
  264. }
  265. // Swap projection axes to take the negated projection vector into account
  266. if (inv < 0.f) {
  267. std::swap(ac,bc);
  268. }
  269. for (tmp =0; tmp < max; ++tmp) {
  270. temp_verts[tmp].x = verts[idx[tmp]][ac];
  271. temp_verts[tmp].y = verts[idx[tmp]][bc];
  272. done[tmp] = false;
  273. }
  274. #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
  275. // plot the plane onto which we mapped the polygon to a 2D ASCII pic
  276. aiVector2D bmin,bmax;
  277. ArrayBounds(&temp_verts[0],max,bmin,bmax);
  278. char grid[POLY_GRID_Y][POLY_GRID_X+POLY_GRID_XPAD];
  279. std::fill_n((char*)grid,POLY_GRID_Y*(POLY_GRID_X+POLY_GRID_XPAD),' ');
  280. for (int i =0; i < max; ++i) {
  281. const aiVector2D& v = (temp_verts[i] - bmin) / (bmax-bmin);
  282. 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));
  283. char* loc = grid[y]+x;
  284. if (grid[y][x] != ' ') {
  285. for(;*loc != ' '; ++loc);
  286. *loc++ = '_';
  287. }
  288. *(loc+::ai_snprintf(loc, POLY_GRID_XPAD,"%i",i)) = ' ';
  289. }
  290. for(size_t y = 0; y < POLY_GRID_Y; ++y) {
  291. grid[y][POLY_GRID_X+POLY_GRID_XPAD-1] = '\0';
  292. fprintf(fout,"%s\n",grid[y]);
  293. }
  294. fprintf(fout,"\ntriangulation sequence: ");
  295. #endif
  296. //
  297. // FIXME: currently this is the slow O(kn) variant with a worst case
  298. // complexity of O(n^2) (I think). Can be done in O(n).
  299. while (num > 3) {
  300. // Find the next ear of the polygon
  301. int num_found = 0;
  302. for (ear = next;;prev = ear,ear = next) {
  303. // break after we looped two times without a positive match
  304. for (next=ear+1;done[(next>=max?next=0:next)];++next);
  305. if (next < ear) {
  306. if (++num_found == 2) {
  307. break;
  308. }
  309. }
  310. const aiVector2D* pnt1 = &temp_verts[ear],
  311. *pnt0 = &temp_verts[prev],
  312. *pnt2 = &temp_verts[next];
  313. // Must be a convex point. Assuming ccw winding, it must be on the right of the line between p-1 and p+1.
  314. if (OnLeftSideOfLine2D(*pnt0,*pnt2,*pnt1)) {
  315. continue;
  316. }
  317. // and no other point may be contained in this triangle
  318. for ( tmp = 0; tmp < max; ++tmp) {
  319. // We need to compare the actual values because it's possible that multiple indexes in
  320. // the polygon are referring to the same position. concave_polygon.obj is a sample
  321. //
  322. // FIXME: Use 'epsiloned' comparisons instead? Due to numeric inaccuracies in
  323. // PointInTriangle() I'm guessing that it's actually possible to construct
  324. // input data that would cause us to end up with no ears. The problem is,
  325. // which epsilon? If we chose a too large value, we'd get wrong results
  326. const aiVector2D& vtmp = temp_verts[tmp];
  327. if ( vtmp != *pnt1 && vtmp != *pnt2 && vtmp != *pnt0 && PointInTriangle2D(*pnt0,*pnt1,*pnt2,vtmp)) {
  328. break;
  329. }
  330. }
  331. if (tmp != max) {
  332. continue;
  333. }
  334. // this vertex is an ear
  335. break;
  336. }
  337. if (num_found == 2) {
  338. // Due to the 'two ear theorem', every simple polygon with more than three points must
  339. // have 2 'ears'. Here's definitely something wrong ... but we don't give up yet.
  340. //
  341. // Instead we're continuing with the standard tri-fanning algorithm which we'd
  342. // use if we had only convex polygons. That's life.
  343. ASSIMP_LOG_ERROR("Failed to triangulate polygon (no ear found). Probably not a simple polygon?");
  344. #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
  345. fprintf(fout,"critical error here, no ear found! ");
  346. #endif
  347. num = 0;
  348. break;
  349. /*curOut -= (max-num); // undo all previous work
  350. for (tmp = 0; tmp < max-2; ++tmp) {
  351. aiFace& nface = *curOut++;
  352. nface.mNumIndices = 3;
  353. if (!nface.mIndices)
  354. nface.mIndices = new unsigned int[3];
  355. nface.mIndices[0] = 0;
  356. nface.mIndices[1] = tmp+1;
  357. nface.mIndices[2] = tmp+2;
  358. }
  359. num = 0;
  360. break;*/
  361. }
  362. aiFace& nface = *curOut++;
  363. nface.mNumIndices = 3;
  364. if (!nface.mIndices) {
  365. nface.mIndices = new unsigned int[3];
  366. }
  367. // setup indices for the new triangle ...
  368. nface.mIndices[0] = prev;
  369. nface.mIndices[1] = ear;
  370. nface.mIndices[2] = next;
  371. // exclude the ear from most further processing
  372. done[ear] = true;
  373. --num;
  374. }
  375. if (num > 0) {
  376. // We have three indices forming the last 'ear' remaining. Collect them.
  377. aiFace& nface = *curOut++;
  378. nface.mNumIndices = 3;
  379. if (!nface.mIndices) {
  380. nface.mIndices = new unsigned int[3];
  381. }
  382. for (tmp = 0; done[tmp]; ++tmp);
  383. nface.mIndices[0] = tmp;
  384. for (++tmp; done[tmp]; ++tmp);
  385. nface.mIndices[1] = tmp;
  386. for (++tmp; done[tmp]; ++tmp);
  387. nface.mIndices[2] = tmp;
  388. }
  389. }
  390. #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
  391. for(aiFace* f = last_face; f != curOut; ++f) {
  392. unsigned int* i = f->mIndices;
  393. fprintf(fout," (%i %i %i)",i[0],i[1],i[2]);
  394. }
  395. fprintf(fout,"\n*********************************************************************\n");
  396. fflush(fout);
  397. #endif
  398. for(aiFace* f = last_face; f != curOut; ) {
  399. unsigned int* i = f->mIndices;
  400. // drop dumb 0-area triangles - deactivated for now:
  401. //FindDegenerates post processing step can do the same thing
  402. //if (std::fabs(GetArea2D(temp_verts[i[0]],temp_verts[i[1]],temp_verts[i[2]])) < 1e-5f) {
  403. // ASSIMP_LOG_VERBOSE_DEBUG("Dropping triangle with area 0");
  404. // --curOut;
  405. // delete[] f->mIndices;
  406. // f->mIndices = nullptr;
  407. // for(aiFace* ff = f; ff != curOut; ++ff) {
  408. // ff->mNumIndices = (ff+1)->mNumIndices;
  409. // ff->mIndices = (ff+1)->mIndices;
  410. // (ff+1)->mIndices = nullptr;
  411. // }
  412. // continue;
  413. //}
  414. i[0] = idx[i[0]];
  415. i[1] = idx[i[1]];
  416. i[2] = idx[i[2]];
  417. ++f;
  418. }
  419. delete[] face.mIndices;
  420. face.mIndices = nullptr;
  421. }
  422. #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
  423. fclose(fout);
  424. #endif
  425. // kill the old faces
  426. delete [] pMesh->mFaces;
  427. // ... and store the new ones
  428. pMesh->mFaces = out;
  429. pMesh->mNumFaces = (unsigned int)(curOut-out); /* not necessarily equal to numOut */
  430. return true;
  431. }
  432. #endif // !! ASSIMP_BUILD_NO_TRIANGULATE_PROCESS