-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpath.go
More file actions
383 lines (323 loc) · 8.23 KB
/
path.go
File metadata and controls
383 lines (323 loc) · 8.23 KB
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// Cobbled together from https://github.com/sperre/astar.
package rog
import (
"container/heap"
"image"
)
type GridMove interface {
MoveBlocked(x, y int) bool
}
func Path(g GridMove, this image.Rectangle, start, end image.Point) []image.Point {
data := NewMapData(this.Dx(), this.Dy())
for y := this.Min.Y; y < this.Dy(); y++ {
for x := this.Min.X; x < this.Dx(); x++ {
if g.MoveBlocked(x, y) {
data[x][y] = WALL
} else {
data[x][y] = LAND
}
}
}
nodes := Astar(data, start.X, start.Y, end.X, end.Y, true)
points := make([]image.Point, len(nodes))
for i := 0; i < len(nodes); i++ {
points[i] = image.Pt(nodes[i].X, nodes[i].Y)
}
return points
}
// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Node
/* sort.Interface */
func (pq PriorityQueue) Len() int {
return len(pq)
}
func (pq PriorityQueue) Less(i, j int) bool {
// We want Pop to give us the lowest, not highest, priority so we use smaller than here.
return pq[i].f < pq[j].f
}
func (pq PriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].heap_index = i
pq[j].heap_index = j
}
/* heap.interface */
func (pq *PriorityQueue) Push(x interface{}) {
// Push and Pop use pointer receivers because they modify the slice's length,
// not just its contents.
// To simplify indexing expressions in these methods, we save a copy of the
// slice object. We could instead write (*pq)[i].
a := *pq
n := len(a)
a = a[0 : n+1]
item := x.(*Node)
item.heap_index = n
a[n] = item
*pq = a
}
func (pq *PriorityQueue) Pop() interface{} {
a := *pq
n := len(a)
item := a[n-1]
item.heap_index = -1 // for safety
*pq = a[0 : n-1]
return item
}
/* Node */
func (pq *PriorityQueue) PushNode(n *Node) {
heap.Push(pq, n)
}
func (pq *PriorityQueue) PopNode() *Node {
return heap.Pop(pq).(*Node)
}
func (pq *PriorityQueue) RemoveNode(n *Node) {
heap.Remove(pq, n.heap_index)
}
/*** Helper functions ***/
func abs(a int) int {
if a < 0 {
return -a
}
return a
}
/*** MapData type and related consts ***/
// Tile information
const (
LAND = 1 << iota
WALL
)
// Tile movement costs
const (
COST_STRAIGHT = 1000
COST_DIAGONAL = 1414
)
type MapData [][]int
// Return a new MapData by value given some dimensions
func NewMapData(rows, cols int) MapData {
result := make([]([]int), rows)
for i := 0; i < rows; i++ {
result[i] = make([]int, cols)
}
return result
}
func (m MapData) Clone() MapData {
rows := len(m)
cols := len(m[0])
result := make([]([]int), rows)
for i := 0; i < rows; i++ {
result[i] = make([]int, cols)
copy(result[i], m[i])
}
return result
}
func str_map(data MapData, nodes []*Node) string {
var result string
for i, row := range data {
for j, cell := range row {
added := false
for _, node := range nodes {
if node.X == i && node.Y == j {
result += "o"
added = true
break
}
}
if !added {
switch cell {
case LAND:
result += "."
case WALL:
result += "#"
default: //Unknown
result += "?"
}
}
}
result += "\n"
}
return result
}
/*** Node type ***/
// X and Y are coordinates, parent is a link to where we came from. cost are the
// estimated cost from start along the best known path. h is the heuristic value
// (air line distance to goal).
type Node struct {
X, Y int
parent *Node
f, g, h int
heap_index int // only used and maintained by pqueue
}
// Create a new Node
func NewNode(x, y int) *Node {
node := &Node{
X: x,
Y: y,
parent: nil,
f: 0, // f = g + h
g: 0, // Cost from node to start
h: 0, // Estimated cost from node to finish
}
return node
}
// Return string representation of the node
func (n *Node) String() string {
return ""
// return fmt.Sprintf("<Node x:%d y:%d addr:%d>", n.X, n.Y, &n)
}
/*** nodeList type ***/
type nodeList struct {
nodes map[int]*Node
rows, cols int
}
func newNodeList(rows, cols int) *nodeList {
return &nodeList{
nodes: make(map[int]*Node, rows*cols),
rows: rows,
cols: cols,
}
}
func (n *nodeList) addNode(node *Node) {
n.nodes[node.X+node.Y*n.rows] = node
}
func (n *nodeList) getNode(x, y int) *Node {
return n.nodes[x+y*n.rows]
}
func (n *nodeList) removeNode(node *Node) {
delete(n.nodes, node.X+node.Y*n.rows)
}
func (n *nodeList) hasNode(node *Node) bool {
if n.getNode(node.X, node.Y) != nil {
return true
}
return false
}
/*** Graph type ***/
// Start, stop nodes and a slice of nodes
type Graph struct {
nodes *nodeList // Used to avoid duplicated nodes!
data MapData
}
// Return a Graph from a map of coordinates (those that are passible)
func NewGraph(map_data MapData) *Graph {
//var start, stop *Node
return &Graph{
nodes: newNodeList(len(map_data), len(map_data[0])),
data: map_data,
}
}
// Get or create a *Node based on x, y coordinates. Avoids duplicated nodes!
func (g *Graph) Node(x, y int) *Node {
//Check if node is already in the graph
var node *Node
node = g.nodes.getNode(x, y)
if node == nil && (g.data[x][y] != WALL) {
//Create a new node and add it to the graph
node = NewNode(x, y)
g.nodes.addNode(node)
}
return node
}
/* Astar func */
func retracePath(current_node *Node) []*Node {
var path []*Node
path = append(path, current_node)
for current_node.parent != nil {
path = append(path, current_node.parent)
current_node = current_node.parent
}
//Reverse path
for i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 {
path[i], path[j] = path[j], path[i]
}
return path
}
// Diagonal/Chebyshev distance is used.
func Heuristic(tile, stop *Node) (h int) {
h_diag := min(abs(tile.X-stop.X), abs(tile.Y-stop.Y))
h_stra := abs(tile.X-stop.X) + abs(tile.Y-stop.Y)
h = COST_DIAGONAL*h_diag + COST_STRAIGHT*(h_stra-2*h_diag)
/* TODO: Breaking ties:
dx1 := tile.X - stop.X
dy1 := tile.Y - stop.Y
dx2 := start.X - stop.X
dy2 := start.Y - stop.Y
cross := abs(dx1*dy2 - dx2*dy1)
h += cross * COST_DIAGONAL/100
*/
return
}
// 8 directions adjecentDirs and costs
var adjecentDirs8 = [][3]int{
{-1, -1, COST_DIAGONAL}, {-1, 0, COST_STRAIGHT}, {-1, 1, COST_DIAGONAL},
{0, -1, COST_STRAIGHT}, {0, 1, COST_STRAIGHT},
{1, -1, COST_DIAGONAL}, {1, 0, COST_STRAIGHT}, {1, 1, COST_DIAGONAL},
}
// 4 directions adjecentDirs and costs
var adjecentDirs4 = [][3]int{
{-1, 0, COST_STRAIGHT},
{0, -1, COST_STRAIGHT}, {0, 1, COST_STRAIGHT},
{1, 0, COST_STRAIGHT},
}
// A* search algorithm. See http://en.wikipedia.org/wiki/A*_search_algorithm
func Astar(map_data MapData, startx, starty, stopx, stopy int, dir8 bool) []*Node {
graph := NewGraph(map_data)
rows, cols := len(graph.data), len(graph.data[0])
// Create lists
closedSet := newNodeList(rows, cols)
openSet := newNodeList(rows, cols)
pq := make(PriorityQueue, 0, rows*cols) // heap, used to find minF
// Move in 8 or 4 directions?
var adjecentDirs [][3]int
if dir8 {
adjecentDirs = adjecentDirs8
} else {
adjecentDirs = adjecentDirs4
}
// TODO: GUARD: startx... stopy inside array range?
// Add start node to the task list
start := NewNode(startx, starty)
stop := NewNode(stopx, stopy)
openSet.addNode(start)
pq.PushNode(start)
for len(openSet.nodes) != 0 {
// Get the node with the min H
//current := openSet.minF()
current := pq.PopNode()
openSet.removeNode(current)
closedSet.addNode(current)
if current.X == stop.X && current.Y == stop.Y {
// Finished, return shortest path
//fmt.Println(str_map(map_data, retracePath(current)))
return retracePath(current)
}
for _, adir := range adjecentDirs {
x, y := (current.X + adir[0]), (current.Y + adir[1])
// Check if x, y is inside the map:
if (x < 0) || (x >= rows) || (y < 0) || (y >= cols) {
continue
}
neighbor := graph.Node(x, y)
if neighbor == nil || closedSet.hasNode(neighbor) {
// Wall, or old node
continue
}
g_score := current.g + adir[2]
if !openSet.hasNode(neighbor) {
// Add new interesting node
neighbor.parent = current
neighbor.g = g_score
neighbor.f = neighbor.g + Heuristic(neighbor, stop)
openSet.addNode(neighbor)
pq.PushNode(neighbor)
} else if g_score < neighbor.g {
// Update, old node
pq.RemoveNode(neighbor)
neighbor.parent = current
neighbor.g = g_score
neighbor.f = neighbor.g + Heuristic(neighbor, stop)
pq.PushNode(neighbor)
}
}
}
return nil
}
// ----