VisPyTesselators.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. from OpenGL import GLU
  2. class GLUTess:
  3. def __init__(self):
  4. """
  5. OpenGL GLU triangulation class
  6. """
  7. self.tris = []
  8. self.pts = []
  9. self.vertex_index = 0
  10. def _on_begin_primitive(self, type):
  11. pass
  12. def _on_new_vertex(self, vertex):
  13. self.tris.append(vertex)
  14. # Force GLU to return separate triangles (GLU_TRIANGLES)
  15. def _on_edge_flag(self, flag):
  16. pass
  17. def _on_combine(self, coords, data, weight):
  18. return (coords[0], coords[1], coords[2])
  19. def _on_error(self, errno):
  20. print("GLUTess error:", errno)
  21. def _on_end_primitive(self):
  22. pass
  23. def triangulate(self, polygon):
  24. """
  25. Triangulates polygon
  26. :param polygon: shapely.geometry.polygon
  27. Polygon to tessellate
  28. :return: list, list
  29. Array of triangle vertex indices [t0i0, t0i1, t0i2, t1i0, t1i1, ... ]
  30. Array of polygon points [(x0, y0), (x1, y1), ... ]
  31. """
  32. # Create tessellation object
  33. tess = GLU.gluNewTess()
  34. # Setup callbacks
  35. GLU.gluTessCallback(tess, GLU.GLU_TESS_BEGIN, self._on_begin_primitive)
  36. GLU.gluTessCallback(tess, GLU.GLU_TESS_VERTEX, self._on_new_vertex)
  37. GLU.gluTessCallback(tess, GLU.GLU_TESS_EDGE_FLAG, self._on_edge_flag)
  38. GLU.gluTessCallback(tess, GLU.GLU_TESS_COMBINE, self._on_combine)
  39. GLU.gluTessCallback(tess, GLU.GLU_TESS_ERROR, self._on_error)
  40. GLU.gluTessCallback(tess, GLU.GLU_TESS_END, self._on_end_primitive)
  41. # Reset data
  42. del self.tris[:]
  43. del self.pts[:]
  44. self.vertex_index = 0
  45. # Define polygon
  46. GLU.gluTessBeginPolygon(tess, None)
  47. def define_contour(contour):
  48. vertices = list(contour.coords) # Get vertices coordinates
  49. if vertices[0] == vertices[-1]: # Open ring
  50. vertices = vertices[:-1]
  51. self.pts += vertices
  52. GLU.gluTessBeginContour(tess) # Start contour
  53. # Set vertices
  54. for vertex in vertices:
  55. point = (vertex[0], vertex[1], 0)
  56. GLU.gluTessVertex(tess, point, self.vertex_index)
  57. self.vertex_index += 1
  58. GLU.gluTessEndContour(tess) # End contour
  59. # Polygon exterior
  60. define_contour(polygon.exterior)
  61. # Interiors
  62. for interior in polygon.interiors:
  63. define_contour(interior)
  64. # Start tessellation
  65. GLU.gluTessEndPolygon(tess)
  66. # Free resources
  67. GLU.gluDeleteTess(tess)
  68. return self.tris, self.pts