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
|
# File 'lib/polylabel.rb', line 8
def self.compute(polygon, precision = 1.0)
first_item = polygon[0][0]
min_x = first_item[0]
min_y = first_item[1]
max_x = first_item[0]
max_y = first_item[1]
polygon[0].each do |p|
min_x = p[0] if p[0] < min_x
min_y = p[1] if p[1] < min_y
max_x = p[0] if p[0] > max_x
max_y = p[1] if p[1] > max_y
end
width = max_x - min_x
height = max_y - min_y
cell_size = [width, height].min
h = cell_size / 2.0
return { x: min_x, y: min_y, distance: 0 } if cell_size.zero?
cell_queue = PQueue.new { |a, b| a.max > b.max }
x = min_x
while x < max_x
y = min_y
while y < max_y
cell_queue.push Cell.new(x + h, y + h, h, polygon)
y += cell_size
end
x += cell_size
end
best_cell = get_centroid_cell(polygon)
bbox_cell = Cell.new(min_x + width / 2, min_y + height / 2, 0, polygon)
best_cell = bbox_cell if bbox_cell.d > best_cell.d
num_probes = cell_queue.length
until cell_queue.empty?
cell = cell_queue.pop
best_cell = cell if cell.d > best_cell.d
next if cell.max - best_cell.d <= precision
h = cell.h / 2
cell_queue.push(Cell.new(cell.x - h, cell.y - h, h, polygon))
cell_queue.push(Cell.new(cell.x + h, cell.y - h, h, polygon))
cell_queue.push(Cell.new(cell.x - h, cell.y + h, h, polygon))
cell_queue.push(Cell.new(cell.x + h, cell.y + h, h, polygon))
num_probes += 4
end
{
x: best_cell.x,
y: best_cell.y,
distance: best_cell.d
}
end
|