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
|
# File 'lib/geom/ear_trim.rb', line 6
def self.triangulate(poly)
result = Array.new
points = poly.vertices.dup
num = points.length
count = num*2
indices = Hash.new
return [ [0,1,2] ] if num == 3
points.reverse! if poly.winding == Polygon::WINDING_CW
points.each_with_index do |p,i|
indices[p] = i
end
while num > 2
return nil if count > num*2 count += 1
i = 0
while i < num
j = (i+num-1) % num
k = (i+1) % num
if is_ear(points,j,i,k)
result.push([indices[points[j]],indices[points[i]],indices[points[k]]])
points.delete_at(i)
num = points.length
count = 0
end
i += 1
end
end
result
end
|