forked from bgrins/javascript-astar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.js
More file actions
313 lines (275 loc) · 9.28 KB
/
graph.js
File metadata and controls
313 lines (275 loc) · 9.28 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
/**
* This file is part of the javascript-astar library.
* javascript-astar is freely distributable under the MIT License.
* See LICENSE for details.
*/
var GraphNodeType = {
OPEN: 1,
WALL: 0
};
/**
* Creates a Graph class used in the astar search algorithm.
* @param grid Array of hex tile objects.
* @param xFunc Function that returns a tile's x coordinate.
* @param yFunc Function that returns a tile's y coordinate.
* @param typeFunc Function that returns a tile's GraphNodeType.
* @param costFunc Function that returns a tile's cost.
* @param neighborsFunc Function that returns a tile's neighbors. If undefined, default function is used.
* @param mapSize Object{ width: int, height: int }
*/
function Graph(tiles, xFunc, yFunc, typeFunc, costFunc, neighborsFunc, mapSize) {
var nodes = [];
for (var i = 0; i < tiles.length; i++) {
var tile = tiles[i];
var node = new GraphNode(xFunc(tile), yFunc(tile), typeFunc(tile), costFunc(tile));
node.data = tile; // keep reference to caller's tile object
nodes[i] = node;
}
this.nodes = nodes;
this.mapSize = mapSize;
for (i = 0; i < nodes.length; i++) {
if (neighborsFunc) {
// call user-defined neighbors function with user-data as argument (tile)
var dataNeighbors = neighborsFunc(nodes[i].data);
var nodeNeighbors = [];
for (var j = 0; j < dataNeighbors.length; j++) {
var dataNeighbor = dataNeighbors[j];
// get a temporary internal node from for the user-returned tile
var neighborNode = new GraphNode(xFunc(dataNeighbor), yFunc(dataNeighbor), typeFunc(dataNeighbor), costFunc(dataNeighbor));
// assign the permanent node with the same coordinates as the temporary node
nodeNeighbors.push(this.getNode(neighborNode.x, neighborNode.y));
}
nodes[i].neighbors = nodeNeighbors;
} else {
nodes[i].neighbors = this.getNeighbors(this, nodes[i]);
}
}
}
Graph.prototype.toString = function() {
var graphString = "\n";
var nodes = this.nodes;
for (var i = 0, len = nodes.length; i < len; i++) {
graphString = graphString + nodes[i].toString() + " ";
}
return graphString;
};
/**
* @return True, if the tile with coordinates x, y
* is in the valid map area, false otherwise.
*/
Graph.prototype.isOnMap = function(x, y) {
var mapSize = this.mapSize;
return (
/** (-x - y) == z due to x + y + z == 0 */
(-x - y) >= 0 // top of map
&& (-x - y) < mapSize.height // bottom of map
&& x >= y // left of map; for each step to top left (y), go at least equal to top right (x)
&& Math.ceil((x - y) / 2) < mapSize.width // right of map; the sum of x and y steps must be less than map width
);
}
/**
* @return The GraphNode object with coordinates x,y or null
* if no node at such coordinates.
*/
Graph.prototype.getNode = function(x, y) {
if (!this.isOnMap(x, y)) {
return null;
}
var tileIndex = this.index(x, y);
var node = this.nodes[tileIndex];
if (node) {
return node;
} else {
return null;
}
}
/**
* @return Array index number of tile with coordinates x, y.
*/
Graph.prototype.index = function(x, y) {
return this.mapSize.width * (-x - y) + x; // mapWidth * z + x // with x + y + z == 0
}
/**
* Calculate the distance between two map points.
* @param posStart Point object {x: int, y: int, z: int}
* @param posEnd Point object {x: int, y: int, z: int}
*/
Graph.prototype.getDistanceDirect = function(posStart, posEnd) {
return (Math.abs(posStart.x - posEnd.x)
+ Math.abs(posStart.y - posEnd.y)
+ Math.abs(posStart.z - posEnd.z))
/ 2;
}
/**
* Default function to determine a node's neighbors.
* @param graph Graph The complete initialized graph.
* @param node GraphNode Node to determine neighbors for.
* @return array[GraphNode]
*/
Graph.prototype.getNeighbors = function(graph, node) {
var ret = [];
var x = node.x;
var y = node.y;
var neighbor = null;
// North-East
neighbor = graph.getNode(x + 1, y);
if(neighbor) {
ret.push(neighbor);
}
// East
neighbor = graph.getNode(x + 1, y - 1);
if(neighbor) {
ret.push(neighbor);
}
// South-East
neighbor = graph.getNode(x, y - 1);
if(neighbor) {
ret.push(neighbor);
}
// South-West
neighbor = graph.getNode(x - 1, y);
if(neighbor) {
ret.push(neighbor);
}
// West
neighbor = graph.getNode(x - 1, y + 1);
if(neighbor) {
ret.push(neighbor);
}
// North-West
neighbor = graph.getNode(x, y + 1);
if(neighbor) {
ret.push(neighbor);
}
return ret;
}
/**
* @param x int X coordinate of node.
* @param y int Y coordinate of node.
* @param type int|bool Set to non-falsy value if traversable, or falsy value otherwise.
* @param cost int Cost of node traversal, if traversable.
*/
function GraphNode(x,y,type,cost) {
this.x = x;
this.y = y;
this.pos = {
x: x,
y: y,
z: -x - y // x + y + z == 0
};
this.type = (type) ? GraphNodeType.OPEN : GraphNodeType.WALL;
this.cost = cost;
}
GraphNode.prototype.toString = function() {
return "[" + this.x + " " + this.y + "]";
};
GraphNode.prototype.isWall = function() {
return this.type == GraphNodeType.WALL;
};
function BinaryHeap(scoreFunction){
this.content = [];
this.scoreFunction = scoreFunction;
}
BinaryHeap.prototype = {
push: function(element) {
// Add the new element to the end of the array.
this.content.push(element);
// Allow it to sink down.
this.sinkDown(this.content.length - 1);
},
pop: function() {
// Store the first element so we can return it later.
var result = this.content[0];
// Get the element at the end of the array.
var end = this.content.pop();
// If there are any elements left, put the end element at the
// start, and let it bubble up.
if (this.content.length > 0) {
this.content[0] = end;
this.bubbleUp(0);
}
return result;
},
remove: function(node) {
var i = this.content.indexOf(node);
// When it is found, the process seen in 'pop' is repeated
// to fill up the hole.
var end = this.content.pop();
if (i !== this.content.length - 1) {
this.content[i] = end;
if (this.scoreFunction(end) < this.scoreFunction(node)) {
this.sinkDown(i);
}
else {
this.bubbleUp(i);
}
}
},
size: function() {
return this.content.length;
},
rescoreElement: function(node) {
this.sinkDown(this.content.indexOf(node));
},
sinkDown: function(n) {
// Fetch the element that has to be sunk.
var element = this.content[n];
// When at 0, an element can not sink any further.
while (n > 0) {
// Compute the parent element's index, and fetch it.
var parentN = ((n + 1) >> 1) - 1,
parent = this.content[parentN];
// Swap the elements if the parent is greater.
if (this.scoreFunction(element) < this.scoreFunction(parent)) {
this.content[parentN] = element;
this.content[n] = parent;
// Update 'n' to continue at the new position.
n = parentN;
}
// Found a parent that is less, no need to sink any further.
else {
break;
}
}
},
bubbleUp: function(n) {
// Look up the target element and its score.
var length = this.content.length,
element = this.content[n],
elemScore = this.scoreFunction(element);
while(true) {
// Compute the indices of the child elements.
var child2N = (n + 1) << 1, child1N = child2N - 1;
// This is used to store the new position of the element,
// if any.
var swap = null;
// If the first child exists (is inside the array)...
if (child1N < length) {
// Look it up and compute its score.
var child1 = this.content[child1N],
child1Score = this.scoreFunction(child1);
// If the score is less than our element's, we need to swap.
if (child1Score < elemScore)
swap = child1N;
}
// Do the same checks for the other child.
if (child2N < length) {
var child2 = this.content[child2N],
child2Score = this.scoreFunction(child2);
if (child2Score < (swap === null ? elemScore : child1Score)) {
swap = child2N;
}
}
// If the element needs to be moved, swap it, and continue.
if (swap !== null) {
this.content[n] = this.content[swap];
this.content[swap] = element;
n = swap;
}
// Otherwise, we are done.
else {
break;
}
}
}
};