-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTriangulate.py
352 lines (247 loc) · 8.36 KB
/
Triangulate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# Triangulate.py - Python script for triangulating polygons
#
# This script specializes in triangulating polygons using two techniques:
# - Fan method for convex polygons
# - Earcut technique for concave polygons
#
# Copyright (c) 2023 by FalconCoding
# Author: Stefan Johnsen
# Email: stefan.johnsen@outlook.com
#
# This software is released under the MIT License.
import math
from enum import Enum
epsilon = 1e-6
class TurnDirection(Enum):
Right = 1
Left = -1
NoTurn = 0
class Point:
def __init__(self, x=0.0, y=0.0, z=0.0, i=None):
self.x = x
self.y = y
self.z = z
self.i = i
def __add__(self, other):
if isinstance(other, Point):
return Point(self.x + other.x, self.y + other.y, self.z + other.z)
else:
raise ValueError("Addition is only supported between Point objects.")
def __sub__(self, other):
if isinstance(other, Point):
return Point(self.x - other.x, self.y - other.y, self.z - other.z)
else:
raise ValueError("Subtraction is only supported between Point objects.")
def __mul__(self, scalar):
if isinstance(scalar, float):
return Point(self.x * scalar, self.y * scalar, self.z * scalar)
else:
raise ValueError("Multiplication is only supported with scalar values.")
def __truediv__(self, scalar):
if isinstance(scalar, float):
if scalar == 0.0:
return Point.zero()
return Point(self.x / scalar, self.y / scalar, self.z / scalar)
else:
raise ValueError("Division is only supported with scalar values.")
def __eq__(self, other):
if other is None: return False
if abs(self.x - other.x) > epsilon: return False
if abs(self.y - other.y) > epsilon: return False
if abs(self.z - other.z) > epsilon: return False
return True
def copy(self):
return Point(self.x, self.y, self.z, self.i)
@classmethod
def zero(cls):
return cls(0.0, 0.0, 0.0)
def dot(u, v):
return u.x * v.x + u.y * v.y + u.z * v.z
def cross(u, v):
x = u.y * v.z - u.z * v.y
y = u.z * v.x - u.x * v.z
z = u.x * v.y - u.y * v.x
return Point(x, y, z)
def length(u):
return math.sqrt(u.x * u.x + u.y * u.y + u.z * u.z)
class Triangle:
def __init__(self, p0, p1, p2):
self.p0 = p0
self.p1 = p1
self.p2 = p2
def turn(p, u, n, q):
v = cross(q - p, u)
d = dot(v, n)
if d > +epsilon: return TurnDirection.Right
if d < -epsilon: return TurnDirection.Left
return TurnDirection.NoTurn
def triangleAreaSquared(a, b, c):
c = cross(b - a, c - a)
return length(c)**2.0 / 4.0
def normalize(v):
return v/length(v)
def normal(polygon):
n = len(polygon)
v = Point.zero()
if n < 3: return v
for index in range(n):
item = polygon[index % n]
next = polygon[(index + 1) % n]
v.x += (next.y - item.y) * (next.z + item.z);
v.y += (next.z - item.z) * (next.x + item.x);
v.z += (next.x - item.x) * (next.y + item.y);
return normalize(v)
def pointInsideOrEdgeTriangle(a, b, c, p):
zero = 1e-15 # A small value close to zero for comparisons
# Initialize edge to False
edge = False
# Vectors from point p to vertices of the triangle
v0 = c - a
v1 = b - a
v2 = p - a
dot00 = dot(v0, v0)
dot01 = dot(v0, v1)
dot02 = dot(v0, v2)
dot11 = dot(v1, v1)
dot12 = dot(v1, v2)
# Check for degenerate triangle
denom = dot00 * dot11 - dot01 * dot01
if abs(denom) < zero:
# The triangle is degenerate (i.e., has no area)
return (False, edge)
# Compute barycentric coordinates
invDenom = 1.0 / denom
u = (dot11 * dot02 - dot01 * dot12) * invDenom
v = (dot00 * dot12 - dot01 * dot02) * invDenom
# Check for edge condition
if abs(u) < zero or abs(v) < zero or abs(u + v - 1) < zero:
edge = True
# Check if point is inside the triangle (including edges)
return (u >= 0.0 and v >= 0.0 and u + v < 1.0, edge)
def isEar(index, polygon, normal):
n = len(polygon)
if n < 3: return False
if n == 3: return True
prevIndex = (index - 1 + n) % n
itemIndex = index % n
nextIndex = (index + 1) % n
prev = polygon[prevIndex]
item = polygon[itemIndex]
next = polygon[nextIndex]
u = normalize(item - prev)
if turn(prev, u, normal, next) != TurnDirection.Right:
return False
for i in range(n):
if i in (prevIndex, itemIndex, nextIndex):
continue
p = polygon[i]
inside, _ = pointInsideOrEdgeTriangle(prev, item, next, p)
if inside: return False
return True
def getBiggestEar(polygon, normal):
n = len(polygon)
if n == 3: return 0
if n == 0: return -1
maxIndex = -1
maxArea = float("-inf")
for index in range(n):
if isEar(index, polygon, normal):
prev = polygon[(index - 1 + n) % n]
item = polygon[index % n]
next = polygon[(index + 1) % n]
area = triangleAreaSquared(prev, item, next)
if area > maxArea:
maxIndex = index
maxArea = area
return maxIndex
def getOverlappingEar(polygon, normal):
n = len(polygon)
if n == 3: return 0
if n == 0: return -1
for index in range(n):
prev = polygon[(index - 1 + n) % n]
item = polygon[index % n]
next = polygon[(index + 1) % n]
u = normalize(item - prev)
if turn(prev, u, normal, next) != TurnDirection.NoTurn:
continue
v = normalize(next - item)
if dot(u, v) < 0.0:
return index
return -1
def convex(polygon, normal):
n = len(polygon)
if n < 3: return False
if n == 3: return True
polygonTurn = TurnDirection.NoTurn
for index in range(n):
prev = polygon[(index - 1 + n) % n]
item = polygon[index % n]
next = polygon[(index + 1) % n]
u = normalize(item - prev)
item_turn = turn(prev, u, normal, next)
if item_turn == TurnDirection.NoTurn:
continue
if polygonTurn == TurnDirection.NoTurn:
polygonTurn = item_turn
if polygonTurn != item_turn:
return False
return True
def clockwiseOriented(polygon, normal):
n = len(polygon)
if n < 3: return False
orientationSum = 0.0
for index in range(n):
prev = polygon[(index - 1 + n) % n]
item = polygon[index % n]
next = polygon[(index + 1) % n]
edge = item - prev
toNextPoint = next - item
v = cross(edge, toNextPoint)
orientationSum += dot(v, normal)
return orientationSum < 0.0
def makeClockwiseOrientation(polygon, normal):
if len(polygon) < 3:
return
if not clockwiseOriented(polygon, normal):
polygon.reverse()
def fanTriangulation(polygon):
triangles = []
for index in range(1, len(polygon) - 1):
triangles.append(Triangle(polygon[0], polygon[index], polygon[index + 1]))
return triangles
def cutTriangulation(polygon, normal):
triangles = []
makeClockwiseOrientation(polygon, normal)
while polygon:
index = getBiggestEar(polygon, normal)
if index == -1:
index = getOverlappingEar(polygon, normal)
if index == -1: return []
n = len(polygon)
prev = polygon[(index - 1 + n) % n]
item = polygon[index % n]
next = polygon[(index + 1) % n]
triangles.append(Triangle(prev, item, next))
del polygon[index]
if len(polygon) < 3: break
return triangles if len(polygon) < 3 else []
def removeConsecutiveEqualPoints(polygon):
uniquePolygon = []
n = len(polygon)
for index in range(n):
item = polygon[index % n]
next = polygon[(index + 1) % n]
if item.i == next.i: continue
uniquePolygon.append(item)
return uniquePolygon
def triangulate(polygon):
polygon = removeConsecutiveEqualPoints(polygon)
n = normal(polygon)
if len(polygon) < 3: return [], n
if len(polygon) == 3:
t = Triangle(polygon[0], polygon[1], polygon[2])
return [t], n
if convex(polygon, n):
return fanTriangulation(polygon), n
return cutTriangulation(polygon, n), n