I am looking for a fast polygon triangulation algorithm that can triangulate not very complex 2D concave polygons (without holes) into triangle strips ready to be sent to OpenGL ES for drawing using GL_TRIANGLE_STRIP
.
I am aware of some algorithms but I couldn't find one that will fit my needs:
- http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
- this algorithm works ok but the problem is it returns simple triangles which you can't draw with
GL_TRIANGLE_STRIP
, you need to useGL_TRIANGLES
which isn't very efficient on a large number of vertices.
- this algorithm works ok but the problem is it returns simple triangles which you can't draw with
- http://code.google.com/p/iphone-glu/
- it doesn't have any example associated and I couldn't find anyone that has successfully used it on iOS with OpenGL ES 2.0
- I don't know what it returns and it seems like it also calls the corresponding OpenGL commands which I don't want - I only need the triangles back
- it leaks memory
The platform I am developing for is: iOS, OpenGL ES 2.0, cocos2d 2.0.
Can anyone help me with such an algorithm? Or any other advice will be greatly appreciated.
In 2D and without holes, this is fairly easy. First, you need to break your polygon to one or more monotone polygons.
The monotone polygons are pretty simple to turn into tristrips, just sort the values by
y
, find the top-most and bottom-most vertex, and then you have lists of vertices to the right and to the left (because vertices come in some defined, say clockwise, order). Then you start with top-most vertex and add vertices from the left and from the right sides in alternating manner.This technique will work for any 2D polygons without self-intersecting edges, which includes some cases of polygons with holes (the holes must be correctly wound though).
You can try and play with this code:
This code is not optimal, but it should be easy to understand. At the beginnig, a concave polygon is created. Then a "working set" of vertices is created. On that working set, a permutation is calculated which sorts the vertices by their
y
coordinate. That permutation is then looped through, looking for split points. Once a split point is found, a new monotone polygon is created. Then, the vertices used in the new polygon are removed from the working set and the whole process repeats. Finally, the working set contains the last polygon which could not be split. At the end, the monotone polygons are rendered, along with triangle strip ordering. It is a little bit messy, but I'm sure you will figure it out (this is C++ code, just put it inside a GLUT window and see what it does).Hope this helps ...