vrshoot

view libs/assimp/TriangulateProcess.cpp @ 0:b2f14e535253

initial commit
author John Tsiombikas <nuclear@member.fsf.org>
date Sat, 01 Feb 2014 19:58:19 +0200
parents
children
line source
1 /*
2 ---------------------------------------------------------------------------
3 Open Asset Import Library (assimp)
4 ---------------------------------------------------------------------------
6 Copyright (c) 2006-2012, assimp team
8 All rights reserved.
10 Redistribution and use of this software in source and binary forms,
11 with or without modification, are permitted provided that the following
12 conditions are met:
14 * Redistributions of source code must retain the above
15 copyright notice, this list of conditions and the
16 following disclaimer.
18 * Redistributions in binary form must reproduce the above
19 copyright notice, this list of conditions and the
20 following disclaimer in the documentation and/or other
21 materials provided with the distribution.
23 * Neither the name of the assimp team, nor the names of its
24 contributors may be used to endorse or promote products
25 derived from this software without specific prior
26 written permission of the assimp team.
28 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 ---------------------------------------------------------------------------
40 */
42 /** @file TriangulateProcess.cpp
43 * @brief Implementation of the post processing step to split up
44 * all faces with more than three indices into triangles.
45 *
46 *
47 * The triangulation algorithm will handle concave or convex polygons.
48 * Self-intersecting or non-planar polygons are not rejected, but
49 * they're probably not triangulated correctly.
50 *
51 * DEBUG SWITCHES - do not enable any of them in release builds:
52 *
53 * AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
54 * - generates vertex colors to represent the face winding order.
55 * the first vertex of a polygon becomes red, the last blue.
56 * AI_BUILD_TRIANGULATE_DEBUG_POLYS
57 * - dump all polygons and their triangulation sequences to
58 * a file
59 */
61 #include "AssimpPCH.h"
63 #ifndef ASSIMP_BUILD_NO_TRIANGULATE_PROCESS
64 #include "TriangulateProcess.h"
65 #include "ProcessHelper.h"
66 #include "PolyTools.h"
68 //#define AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
69 //#define AI_BUILD_TRIANGULATE_DEBUG_POLYS
71 #define POLY_GRID_Y 40
72 #define POLY_GRID_X 70
73 #define POLY_GRID_XPAD 20
74 #define POLY_OUTPUT_FILE "assimp_polygons_debug.txt"
76 using namespace Assimp;
78 // ------------------------------------------------------------------------------------------------
79 // Constructor to be privately used by Importer
80 TriangulateProcess::TriangulateProcess()
81 {
82 // nothing to do here
83 }
85 // ------------------------------------------------------------------------------------------------
86 // Destructor, private as well
87 TriangulateProcess::~TriangulateProcess()
88 {
89 // nothing to do here
90 }
92 // ------------------------------------------------------------------------------------------------
93 // Returns whether the processing step is present in the given flag field.
94 bool TriangulateProcess::IsActive( unsigned int pFlags) const
95 {
96 return (pFlags & aiProcess_Triangulate) != 0;
97 }
99 // ------------------------------------------------------------------------------------------------
100 // Executes the post processing step on the given imported data.
101 void TriangulateProcess::Execute( aiScene* pScene)
102 {
103 DefaultLogger::get()->debug("TriangulateProcess begin");
105 bool bHas = false;
106 for( unsigned int a = 0; a < pScene->mNumMeshes; a++)
107 {
108 if( TriangulateMesh( pScene->mMeshes[a]))
109 bHas = true;
110 }
111 if (bHas)DefaultLogger::get()->info ("TriangulateProcess finished. All polygons have been triangulated.");
112 else DefaultLogger::get()->debug("TriangulateProcess finished. There was nothing to be done.");
113 }
116 // ------------------------------------------------------------------------------------------------
117 // Triangulates the given mesh.
118 bool TriangulateProcess::TriangulateMesh( aiMesh* pMesh)
119 {
120 // Now we have aiMesh::mPrimitiveTypes, so this is only here for test cases
121 if (!pMesh->mPrimitiveTypes) {
122 bool bNeed = false;
124 for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
125 const aiFace& face = pMesh->mFaces[a];
127 if( face.mNumIndices != 3) {
128 bNeed = true;
129 }
130 }
131 if (!bNeed)
132 return false;
133 }
134 else if (!(pMesh->mPrimitiveTypes & aiPrimitiveType_POLYGON)) {
135 return false;
136 }
138 // Find out how many output faces we'll get
139 unsigned int numOut = 0, max_out = 0;
140 bool get_normals = true;
141 for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
142 aiFace& face = pMesh->mFaces[a];
143 if (face.mNumIndices <= 4) {
144 get_normals = false;
145 }
146 if( face.mNumIndices <= 3) {
147 numOut++;
149 }
150 else {
151 numOut += face.mNumIndices-2;
152 max_out = std::max(max_out,face.mNumIndices);
153 }
154 }
156 // Just another check whether aiMesh::mPrimitiveTypes is correct
157 assert(numOut != pMesh->mNumFaces);
159 aiVector3D* nor_out = NULL;
161 // if we don't have normals yet, but expect them to be a cheap side
162 // product of triangulation anyway, allocate storage for them.
163 if (!pMesh->mNormals && get_normals) {
164 // XXX need a mechanism to inform the GenVertexNormals process to treat these normals as preprocessed per-face normals
165 // nor_out = pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
166 }
168 // the output mesh will contain triangles, but no polys anymore
169 pMesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
170 pMesh->mPrimitiveTypes &= ~aiPrimitiveType_POLYGON;
172 aiFace* out = new aiFace[numOut](), *curOut = out;
173 std::vector<aiVector3D> temp_verts3d(max_out+2); /* temporary storage for vertices */
174 std::vector<aiVector2D> temp_verts(max_out+2);
176 // Apply vertex colors to represent the face winding?
177 #ifdef AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
178 if (!pMesh->mColors[0])
179 pMesh->mColors[0] = new aiColor4D[pMesh->mNumVertices];
180 else
181 new(pMesh->mColors[0]) aiColor4D[pMesh->mNumVertices];
183 aiColor4D* clr = pMesh->mColors[0];
184 #endif
187 #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
188 FILE* fout = fopen(POLY_OUTPUT_FILE,"a");
189 #endif
191 const aiVector3D* verts = pMesh->mVertices;
193 // use boost::scoped_array to avoid slow std::vector<bool> specialiations
194 boost::scoped_array<bool> done(new bool[max_out]);
195 for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
196 aiFace& face = pMesh->mFaces[a];
198 unsigned int* idx = face.mIndices;
199 int num = (int)face.mNumIndices, ear = 0, tmp, prev = num-1, next = 0, max = num;
201 // Apply vertex colors to represent the face winding?
202 #ifdef AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
203 for (unsigned int i = 0; i < face.mNumIndices; ++i) {
204 aiColor4D& c = clr[idx[i]];
205 c.r = (i+1) / (float)max;
206 c.b = 1.f - c.r;
207 }
208 #endif
210 aiFace* const last_face = curOut;
212 // if it's a simple point,line or triangle: just copy it
213 if( face.mNumIndices <= 3)
214 {
215 aiFace& nface = *curOut++;
216 nface.mNumIndices = face.mNumIndices;
217 nface.mIndices = face.mIndices;
219 face.mIndices = NULL;
220 continue;
221 }
222 // optimized code for quadrilaterals
223 else if ( face.mNumIndices == 4) {
225 // quads can have at maximum one concave vertex. Determine
226 // this vertex (if it exists) and start tri-fanning from
227 // it.
228 unsigned int start_vertex = 0;
229 for (unsigned int i = 0; i < 4; ++i) {
230 const aiVector3D& v0 = verts[face.mIndices[(i+3) % 4]];
231 const aiVector3D& v1 = verts[face.mIndices[(i+2) % 4]];
232 const aiVector3D& v2 = verts[face.mIndices[(i+1) % 4]];
234 const aiVector3D& v = verts[face.mIndices[i]];
236 aiVector3D left = (v0-v);
237 aiVector3D diag = (v1-v);
238 aiVector3D right = (v2-v);
240 left.Normalize();
241 diag.Normalize();
242 right.Normalize();
244 const float angle = acos(left*diag) + acos(right*diag);
245 if (angle > AI_MATH_PI_F) {
246 // this is the concave point
247 start_vertex = i;
248 break;
249 }
250 }
252 const unsigned int temp[] = {face.mIndices[0], face.mIndices[1], face.mIndices[2], face.mIndices[3]};
254 aiFace& nface = *curOut++;
255 nface.mNumIndices = 3;
256 nface.mIndices = face.mIndices;
258 nface.mIndices[0] = temp[start_vertex];
259 nface.mIndices[1] = temp[(start_vertex + 1) % 4];
260 nface.mIndices[2] = temp[(start_vertex + 2) % 4];
262 aiFace& sface = *curOut++;
263 sface.mNumIndices = 3;
264 sface.mIndices = new unsigned int[3];
266 sface.mIndices[0] = temp[start_vertex];
267 sface.mIndices[1] = temp[(start_vertex + 2) % 4];
268 sface.mIndices[2] = temp[(start_vertex + 3) % 4];
270 // prevent double deletion of the indices field
271 face.mIndices = NULL;
272 continue;
273 }
274 else
275 {
276 // A polygon with more than 3 vertices can be either concave or convex.
277 // Usually everything we're getting is convex and we could easily
278 // triangulate by trifanning. However, LightWave is probably the only
279 // modeling suite to make extensive use of highly concave, monster polygons ...
280 // so we need to apply the full 'ear cutting' algorithm to get it right.
282 // RERQUIREMENT: polygon is expected to be simple and *nearly* planar.
283 // We project it onto a plane to get a 2d triangle.
285 // Collect all vertices of of the polygon.
286 for (tmp = 0; tmp < max; ++tmp) {
287 temp_verts3d[tmp] = verts[idx[tmp]];
288 }
290 // Get newell normal of the polygon. Store it for future use if it's a polygon-only mesh
291 aiVector3D n;
292 NewellNormal<3,3,3>(n,max,&temp_verts3d.front().x,&temp_verts3d.front().y,&temp_verts3d.front().z);
293 if (nor_out) {
294 for (tmp = 0; tmp < max; ++tmp)
295 nor_out[idx[tmp]] = n;
296 }
298 // Select largest normal coordinate to ignore for projection
299 const float ax = (n.x>0 ? n.x : -n.x);
300 const float ay = (n.y>0 ? n.y : -n.y);
301 const float az = (n.z>0 ? n.z : -n.z);
303 unsigned int ac = 0, bc = 1; /* no z coord. projection to xy */
304 float inv = n.z;
305 if (ax > ay) {
306 if (ax > az) { /* no x coord. projection to yz */
307 ac = 1; bc = 2;
308 inv = n.x;
309 }
310 }
311 else if (ay > az) { /* no y coord. projection to zy */
312 ac = 2; bc = 0;
313 inv = n.y;
314 }
316 // Swap projection axes to take the negated projection vector into account
317 if (inv < 0.f) {
318 std::swap(ac,bc);
319 }
321 for (tmp =0; tmp < max; ++tmp) {
322 temp_verts[tmp].x = verts[idx[tmp]][ac];
323 temp_verts[tmp].y = verts[idx[tmp]][bc];
324 done[tmp] = false;
325 }
328 #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
329 // plot the plane onto which we mapped the polygon to a 2D ASCII pic
330 aiVector2D bmin,bmax;
331 ArrayBounds(&temp_verts[0],max,bmin,bmax);
333 char grid[POLY_GRID_Y][POLY_GRID_X+POLY_GRID_XPAD];
334 std::fill_n((char*)grid,POLY_GRID_Y*(POLY_GRID_X+POLY_GRID_XPAD),' ');
336 for (int i =0; i < max; ++i) {
337 const aiVector2D& v = (temp_verts[i] - bmin) / (bmax-bmin);
338 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));
339 char* loc = grid[y]+x;
340 if (grid[y][x] != ' ') {
341 for(;*loc != ' '; ++loc);
342 *loc++ = '_';
343 }
344 *(loc+sprintf(loc,"%i",i)) = ' ';
345 }
348 for(size_t y = 0; y < POLY_GRID_Y; ++y) {
349 grid[y][POLY_GRID_X+POLY_GRID_XPAD-1] = '\0';
350 fprintf(fout,"%s\n",grid[y]);
351 }
353 fprintf(fout,"\ntriangulation sequence: ");
354 #endif
356 //
357 // FIXME: currently this is the slow O(kn) variant with a worst case
358 // complexity of O(n^2) (I think). Can be done in O(n).
359 while (num > 3) {
361 // Find the next ear of the polygon
362 int num_found = 0;
363 for (ear = next;;prev = ear,ear = next) {
365 // break after we looped two times without a positive match
366 for (next=ear+1;done[(next>=max?next=0:next)];++next);
367 if (next < ear) {
368 if (++num_found == 2) {
369 break;
370 }
371 }
372 const aiVector2D* pnt1 = &temp_verts[ear],
373 *pnt0 = &temp_verts[prev],
374 *pnt2 = &temp_verts[next];
376 // Must be a convex point. Assuming ccw winding, it must be on the right of the line between p-1 and p+1.
377 if (OnLeftSideOfLine2D(*pnt0,*pnt2,*pnt1)) {
378 continue;
379 }
381 // and no other point may be contained in this triangle
382 for ( tmp = 0; tmp < max; ++tmp) {
384 // We need to compare the actual values because it's possible that multiple indexes in
385 // the polygon are referring to the same position. concave_polygon.obj is a sample
386 //
387 // FIXME: Use 'epsiloned' comparisons instead? Due to numeric inaccuracies in
388 // PointInTriangle() I'm guessing that it's actually possible to construct
389 // input data that would cause us to end up with no ears. The problem is,
390 // which epsilon? If we chose a too large value, we'd get wrong results
391 const aiVector2D& vtmp = temp_verts[tmp];
392 if ( vtmp != *pnt1 && vtmp != *pnt2 && vtmp != *pnt0 && PointInTriangle2D(*pnt0,*pnt1,*pnt2,vtmp)) {
393 break;
394 }
395 }
396 if (tmp != max) {
397 continue;
398 }
400 // this vertex is an ear
401 break;
402 }
403 if (num_found == 2) {
405 // Due to the 'two ear theorem', every simple polygon with more than three points must
406 // have 2 'ears'. Here's definitely someting wrong ... but we don't give up yet.
407 //
409 // Instead we're continuting with the standard trifanning algorithm which we'd
410 // use if we had only convex polygons. That's life.
411 DefaultLogger::get()->error("Failed to triangulate polygon (no ear found). Probably not a simple polygon?");
414 #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
415 fprintf(fout,"critical error here, no ear found! ");
416 #endif
417 num = 0;
418 break;
420 curOut -= (max-num); /* undo all previous work */
421 for (tmp = 0; tmp < max-2; ++tmp) {
422 aiFace& nface = *curOut++;
424 nface.mNumIndices = 3;
425 if (!nface.mIndices)
426 nface.mIndices = new unsigned int[3];
428 nface.mIndices[0] = 0;
429 nface.mIndices[1] = tmp+1;
430 nface.mIndices[2] = tmp+2;
432 }
433 num = 0;
434 break;
435 }
437 aiFace& nface = *curOut++;
438 nface.mNumIndices = 3;
440 if (!nface.mIndices) {
441 nface.mIndices = new unsigned int[3];
442 }
444 // setup indices for the new triangle ...
445 nface.mIndices[0] = prev;
446 nface.mIndices[1] = ear;
447 nface.mIndices[2] = next;
449 // exclude the ear from most further processing
450 done[ear] = true;
451 --num;
452 }
453 if (num > 0) {
454 // We have three indices forming the last 'ear' remaining. Collect them.
455 aiFace& nface = *curOut++;
456 nface.mNumIndices = 3;
457 if (!nface.mIndices) {
458 nface.mIndices = new unsigned int[3];
459 }
461 for (tmp = 0; done[tmp]; ++tmp);
462 nface.mIndices[0] = tmp;
464 for (++tmp; done[tmp]; ++tmp);
465 nface.mIndices[1] = tmp;
467 for (++tmp; done[tmp]; ++tmp);
468 nface.mIndices[2] = tmp;
470 }
471 }
473 #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
475 for(aiFace* f = last_face; f != curOut; ++f) {
476 unsigned int* i = f->mIndices;
477 fprintf(fout," (%i %i %i)",i[0],i[1],i[2]);
478 }
480 fprintf(fout,"\n*********************************************************************\n");
481 fflush(fout);
483 #endif
485 for(aiFace* f = last_face; f != curOut; ) {
486 unsigned int* i = f->mIndices;
488 // drop dumb 0-area triangles
489 if (fabs(GetArea2D(temp_verts[i[0]],temp_verts[i[1]],temp_verts[i[2]])) < 1e-5f) {
490 DefaultLogger::get()->debug("Dropping triangle with area 0");
491 --curOut;
493 delete[] f->mIndices;
494 f->mIndices = NULL;
496 for(aiFace* ff = f; ff != curOut; ++ff) {
497 ff->mNumIndices = (ff+1)->mNumIndices;
498 ff->mIndices = (ff+1)->mIndices;
499 (ff+1)->mIndices = NULL;
500 }
501 continue;
502 }
504 i[0] = idx[i[0]];
505 i[1] = idx[i[1]];
506 i[2] = idx[i[2]];
507 ++f;
508 }
510 delete[] face.mIndices;
511 face.mIndices = NULL;
512 }
514 #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
515 fclose(fout);
516 #endif
518 // kill the old faces
519 delete [] pMesh->mFaces;
521 // ... and store the new ones
522 pMesh->mFaces = out;
523 pMesh->mNumFaces = (unsigned int)(curOut-out); /* not necessarily equal to numOut */
524 return true;
525 }
527 #endif // !! ASSIMP_BUILD_NO_TRIANGULATE_PROCESS