| 336 | |
| 337 | |
| 338 | static int triangulate(int n, const int* verts, int* indices, int* tris) |
| 339 | { |
| 340 | int ntris = 0; |
| 341 | int* dst = tris; |
| 342 | |
| 343 | // The last bit of the index is used to indicate if the vertex can be removed. |
| 344 | for (int i = 0; i < n; i++) |
| 345 | { |
| 346 | int i1 = next(i, n); |
| 347 | int i2 = next(i1, n); |
| 348 | if (diagonal(i, i2, n, verts, indices)) |
| 349 | indices[i1] |= 0x80000000; |
| 350 | } |
| 351 | |
| 352 | while (n > 3) |
| 353 | { |
| 354 | int minLen = -1; |
| 355 | int mini = -1; |
| 356 | for (int i = 0; i < n; i++) |
| 357 | { |
| 358 | int i1 = next(i, n); |
| 359 | if (indices[i1] & 0x80000000) |
| 360 | { |
| 361 | const int* p0 = &verts[(indices[i] & 0x0fffffff) * 4]; |
| 362 | const int* p2 = &verts[(indices[next(i1, n)] & 0x0fffffff) * 4]; |
| 363 | |
| 364 | int dx = p2[0] - p0[0]; |
| 365 | int dy = p2[2] - p0[2]; |
| 366 | int len = dx*dx + dy*dy; |
| 367 | |
| 368 | if (minLen < 0 || len < minLen) |
| 369 | { |
| 370 | minLen = len; |
| 371 | mini = i; |
| 372 | } |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | if (mini == -1) |
| 377 | { |
| 378 | // We might get here because the contour has overlapping segments, like this: |
| 379 | // |
| 380 | // A o-o=====o---o B |
| 381 | // / |C D| \. |
| 382 | // o o o o |
| 383 | // : : : : |
| 384 | // We'll try to recover by loosing up the inCone test a bit so that a diagonal |
| 385 | // like A-B or C-D can be found and we can continue. |
| 386 | minLen = -1; |
| 387 | mini = -1; |
| 388 | for (int i = 0; i < n; i++) |
| 389 | { |
| 390 | int i1 = next(i, n); |
| 391 | int i2 = next(i1, n); |
| 392 | if (diagonalLoose(i, i2, n, verts, indices)) |
| 393 | { |
| 394 | const int* p0 = &verts[(indices[i] & 0x0fffffff) * 4]; |
| 395 | const int* p2 = &verts[(indices[next(i2, n)] & 0x0fffffff) * 4]; |
no test coverage detected