-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy patheasystar.js
More file actions
executable file
·549 lines (487 loc) · 18.5 KB
/
Copy patheasystar.js
File metadata and controls
executable file
·549 lines (487 loc) · 18.5 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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
/**
* EasyStar.js
* github.com/prettymuchbryce/EasyStarJS
* Licensed under the MIT license.
*
* Implementation By Bryce Neal (@prettymuchbryce)
**/
var EasyStar = {}
var Instance = require('./instance');
var Node = require('./node');
var Heap = require('heap');
const CLOSED_LIST = 0;
const OPEN_LIST = 1;
module.exports = EasyStar;
var nextInstanceId = 1;
EasyStar.js = function() {
var STRAIGHT_COST = 1.0;
var DIAGONAL_COST = 1.4;
var syncEnabled = false;
var pointsToAvoid = {};
var collisionGrid;
var costMap = {};
var pointsToCost = {};
var directionalConditions = {};
var allowCornerCutting = true;
var iterationsSoFar;
var instances = {};
var instanceQueue = [];
var iterationsPerCalculation = Number.MAX_VALUE;
var acceptableTiles;
var diagonalsEnabled = false;
/**
* Sets the collision grid that EasyStar uses.
*
* @param {Array|Number} tiles An array of numbers that represent
* which tiles in your grid should be considered
* acceptable, or "walkable".
**/
this.setAcceptableTiles = function(tiles) {
if (tiles instanceof Array) {
// Array
acceptableTiles = tiles;
} else if (!isNaN(parseFloat(tiles)) && isFinite(tiles)) {
// Number
acceptableTiles = [tiles];
}
};
/**
* Enables sync mode for this EasyStar instance..
* if you're into that sort of thing.
**/
this.enableSync = function() {
syncEnabled = true;
};
/**
* Disables sync mode for this EasyStar instance.
**/
this.disableSync = function() {
syncEnabled = false;
};
/**
* Enable diagonal pathfinding.
*/
this.enableDiagonals = function() {
diagonalsEnabled = true;
}
/**
* Disable diagonal pathfinding.
*/
this.disableDiagonals = function() {
diagonalsEnabled = false;
}
/**
* Sets the collision grid that EasyStar uses.
*
* @param {Array} grid The collision grid that this EasyStar instance will read from.
* This should be a 2D Array of Numbers.
**/
this.setGrid = function(grid) {
collisionGrid = grid;
//Setup cost map
for (var y = 0; y < collisionGrid.length; y++) {
for (var x = 0; x < collisionGrid[0].length; x++) {
if (!costMap[collisionGrid[y][x]]) {
costMap[collisionGrid[y][x]] = 1
}
}
}
};
/**
* Sets the tile cost for a particular tile type.
*
* @param {Number} The tile type to set the cost for.
* @param {Number} The multiplicative cost associated with the given tile.
**/
this.setTileCost = function(tileType, cost) {
costMap[tileType] = cost;
};
/**
* Sets the an additional cost for a particular point.
* Overrides the cost from setTileCost.
*
* @param {Number} x The x value of the point to cost.
* @param {Number} y The y value of the point to cost.
* @param {Number} The multiplicative cost associated with the given point.
**/
this.setAdditionalPointCost = function(x, y, cost) {
if (pointsToCost[y] === undefined) {
pointsToCost[y] = {};
}
pointsToCost[y][x] = cost;
};
/**
* Remove the additional cost for a particular point.
*
* @param {Number} x The x value of the point to stop costing.
* @param {Number} y The y value of the point to stop costing.
**/
this.removeAdditionalPointCost = function(x, y) {
if (pointsToCost[y] !== undefined) {
delete pointsToCost[y][x];
}
}
/**
* Remove all additional point costs.
**/
this.removeAllAdditionalPointCosts = function() {
pointsToCost = {};
}
/**
* Sets a directional condition on a tile
*
* @param {Number} x The x value of the point.
* @param {Number} y The y value of the point.
* @param {Array.<String>} allowedDirections A list of all the allowed directions that can access
* the tile.
**/
this.setDirectionalCondition = function(x, y, allowedDirections) {
if (directionalConditions[y] === undefined) {
directionalConditions[y] = {};
}
directionalConditions[y][x] = allowedDirections
.map(function(c){return c|0}) // force integer
.reduce(function(p,c){return p|c},0);
};
/**
* Remove all directional conditions
**/
this.removeAllDirectionalConditions = function() {
directionalConditions = {};
};
/**
* Sets the number of search iterations per calculation.
* A lower number provides a slower result, but more practical if you
* have a large tile-map and don't want to block your thread while
* finding a path.
*
* @param {Number} iterations The number of searches to prefrom per calculate() call.
**/
this.setIterationsPerCalculation = function(iterations) {
iterationsPerCalculation = iterations;
};
/**
* Avoid a particular point on the grid,
* regardless of whether or not it is an acceptable tile.
*
* @param {Number} x The x value of the point to avoid.
* @param {Number} y The y value of the point to avoid.
**/
this.avoidAdditionalPoint = function(x, y) {
if (pointsToAvoid[y] === undefined) {
pointsToAvoid[y] = {};
}
pointsToAvoid[y][x] = 1;
};
/**
* Stop avoiding a particular point on the grid.
*
* @param {Number} x The x value of the point to stop avoiding.
* @param {Number} y The y value of the point to stop avoiding.
**/
this.stopAvoidingAdditionalPoint = function(x, y) {
if (pointsToAvoid[y] !== undefined) {
delete pointsToAvoid[y][x];
}
};
/**
* Enables corner cutting in diagonal movement.
**/
this.enableCornerCutting = function() {
allowCornerCutting = true;
};
/**
* Disables corner cutting in diagonal movement.
**/
this.disableCornerCutting = function() {
allowCornerCutting = false;
};
/**
* Stop avoiding all additional points on the grid.
**/
this.stopAvoidingAllAdditionalPoints = function() {
pointsToAvoid = {};
};
/**
* Find a path.
*
* @param {Number} startX The X position of the starting point.
* @param {Number} startY The Y position of the starting point.
* @param {Number} endX The X position of the ending point.
* @param {Number} endY The Y position of the ending point.
* @param {Function} callback A function that is called when your path
* is found, or no path is found.
* @return {Number} A numeric, non-zero value which identifies the created instance. This value can be passed to cancelPath to cancel the path calculation.
*
**/
this.findPath = function(startX, startY, endX, endY, callback) {
// Wraps the callback for sync vs async logic
var callbackWrapper = function(result) {
if (syncEnabled) {
callback(result);
} else {
setTimeout(function() {
callback(result);
});
}
}
// No acceptable tiles were set
if (acceptableTiles === undefined) {
throw new Error("You can't set a path without first calling setAcceptableTiles() on EasyStar.");
}
// No grid was set
if (collisionGrid === undefined) {
throw new Error("You can't set a path without first calling setGrid() on EasyStar.");
}
// Start or endpoint outside of scope.
if (startX < 0 || startY < 0 || endX < 0 || endY < 0 ||
startX > collisionGrid[0].length-1 || startY > collisionGrid.length-1 ||
endX > collisionGrid[0].length-1 || endY > collisionGrid.length-1) {
throw new Error("Your start or end point is outside the scope of your grid.");
}
// Start and end are the same tile.
if (startX===endX && startY===endY) {
callbackWrapper([]);
return;
}
// End point is not an acceptable tile.
var endTile = collisionGrid[endY][endX];
var isAcceptable = false;
for (var i = 0; i < acceptableTiles.length; i++) {
if (endTile === acceptableTiles[i]) {
isAcceptable = true;
break;
}
}
if (isAcceptable === false) {
callbackWrapper(null);
return;
}
// Create the instance
var instance = new Instance();
instance.openList = new Heap(function(nodeA, nodeB) {
return nodeA.bestGuessDistance() - nodeB.bestGuessDistance();
});
instance.isDoneCalculating = false;
instance.nodeHash = {};
instance.startX = startX;
instance.startY = startY;
instance.endX = endX;
instance.endY = endY;
instance.callback = callbackWrapper;
instance.openList.push(coordinateToNode(instance, instance.startX,
instance.startY, null, STRAIGHT_COST));
var instanceId = nextInstanceId ++;
instances[instanceId] = instance;
instanceQueue.push(instanceId);
return instanceId;
};
/**
* Cancel a path calculation.
*
* @param {Number} instanceId The instance ID of the path being calculated
* @return {Boolean} True if an instance was found and cancelled.
*
**/
this.cancelPath = function(instanceId) {
if (instanceId in instances) {
delete instances[instanceId];
// No need to remove it from instanceQueue
return true;
}
return false;
};
/**
* This method steps through the A* Algorithm in an attempt to
* find your path(s). It will search 4-8 tiles (depending on diagonals) for every calculation.
* You can change the number of calculations done in a call by using
* easystar.setIteratonsPerCalculation().
**/
this.calculate = function() {
if (instanceQueue.length === 0 || collisionGrid === undefined || acceptableTiles === undefined) {
return;
}
for (iterationsSoFar = 0; iterationsSoFar < iterationsPerCalculation; iterationsSoFar++) {
if (instanceQueue.length === 0) {
return;
}
if (syncEnabled) {
// If this is a sync instance, we want to make sure that it calculates synchronously.
iterationsSoFar = 0;
}
var instanceId = instanceQueue[0];
var instance = instances[instanceId];
if (typeof instance == 'undefined') {
// This instance was cancelled
instanceQueue.shift();
continue;
}
// Couldn't find a path.
if (instance.openList.size() === 0) {
instance.callback(null);
delete instances[instanceId];
instanceQueue.shift();
continue;
}
var searchNode = instance.openList.pop();
// Handles the case where we have found the destination
if (instance.endX === searchNode.x && instance.endY === searchNode.y) {
var path = [];
path.push({x: searchNode.x, y: searchNode.y});
var parent = searchNode.parent;
while (parent!=null) {
path.push({x: parent.x, y:parent.y});
parent = parent.parent;
}
path.reverse();
var ip = path;
instance.callback(ip);
delete instances[instanceId];
instanceQueue.shift();
continue;
}
searchNode.list = CLOSED_LIST;
if (searchNode.y > 0) {
checkAdjacentNode(instance, searchNode,
0, -1, STRAIGHT_COST * getTileCost(searchNode.x, searchNode.y-1));
}
if (searchNode.x < collisionGrid[0].length-1) {
checkAdjacentNode(instance, searchNode,
1, 0, STRAIGHT_COST * getTileCost(searchNode.x+1, searchNode.y));
}
if (searchNode.y < collisionGrid.length-1) {
checkAdjacentNode(instance, searchNode,
0, 1, STRAIGHT_COST * getTileCost(searchNode.x, searchNode.y+1));
}
if (searchNode.x > 0) {
checkAdjacentNode(instance, searchNode,
-1, 0, STRAIGHT_COST * getTileCost(searchNode.x-1, searchNode.y));
}
if (diagonalsEnabled) {
if (searchNode.x > 0 && searchNode.y > 0) {
if (allowCornerCutting ||
(isTileWalkable(collisionGrid, acceptableTiles, searchNode.x, searchNode.y-1, searchNode) &&
isTileWalkable(collisionGrid, acceptableTiles, searchNode.x-1, searchNode.y, searchNode))) {
checkAdjacentNode(instance, searchNode,
-1, -1, DIAGONAL_COST * getTileCost(searchNode.x-1, searchNode.y-1));
}
}
if (searchNode.x < collisionGrid[0].length-1 && searchNode.y < collisionGrid.length-1) {
if (allowCornerCutting ||
(isTileWalkable(collisionGrid, acceptableTiles, searchNode.x, searchNode.y+1, searchNode) &&
isTileWalkable(collisionGrid, acceptableTiles, searchNode.x+1, searchNode.y, searchNode))) {
checkAdjacentNode(instance, searchNode,
1, 1, DIAGONAL_COST * getTileCost(searchNode.x+1, searchNode.y+1));
}
}
if (searchNode.x < collisionGrid[0].length-1 && searchNode.y > 0) {
if (allowCornerCutting ||
(isTileWalkable(collisionGrid, acceptableTiles, searchNode.x, searchNode.y-1, searchNode) &&
isTileWalkable(collisionGrid, acceptableTiles, searchNode.x+1, searchNode.y, searchNode))) {
checkAdjacentNode(instance, searchNode,
1, -1, DIAGONAL_COST * getTileCost(searchNode.x+1, searchNode.y-1));
}
}
if (searchNode.x > 0 && searchNode.y < collisionGrid.length-1) {
if (allowCornerCutting ||
(isTileWalkable(collisionGrid, acceptableTiles, searchNode.x, searchNode.y+1, searchNode) &&
isTileWalkable(collisionGrid, acceptableTiles, searchNode.x-1, searchNode.y, searchNode))) {
checkAdjacentNode(instance, searchNode,
-1, 1, DIAGONAL_COST * getTileCost(searchNode.x-1, searchNode.y+1));
}
}
}
}
};
// Private methods follow
var checkAdjacentNode = function(instance, searchNode, x, y, cost) {
var adjacentCoordinateX = searchNode.x+x;
var adjacentCoordinateY = searchNode.y+y;
if ((pointsToAvoid[adjacentCoordinateY] === undefined ||
pointsToAvoid[adjacentCoordinateY][adjacentCoordinateX] === undefined) &&
isTileWalkable(collisionGrid, acceptableTiles, adjacentCoordinateX, adjacentCoordinateY, searchNode)) {
var node = coordinateToNode(instance, adjacentCoordinateX,
adjacentCoordinateY, searchNode, cost);
if (node.list === undefined) {
node.list = OPEN_LIST;
instance.openList.push(node);
} else if (searchNode.costSoFar + cost < node.costSoFar) {
node.costSoFar = searchNode.costSoFar + cost;
node.parent = searchNode;
instance.openList.updateItem(node);
}
}
};
// Helpers
var isTileWalkable = function(collisionGrid, acceptableTiles, x, y, sourceNode) {
var directionalCondition = directionalConditions[y] && directionalConditions[y][x];
if (directionalCondition !== undefined) {
var direction = calculateDirection(sourceNode.x - x, sourceNode.y - y)
return (direction&directionalCondition) > 0;
}
return acceptableTiles.indexOf(collisionGrid[y][x]) != -1
//return true;
};
/**
* -1, -1 | 0, -1 | 1, -1
* -1, 0 | SOURCE | 1, 0
* -1, 1 | 0, 1 | 1, 1
*/
var calculateDirection = function (diffX, diffY) {
if (diffX === 0 && diffY === -1) return EasyStar.TOP
else if (diffX === 1 && diffY === -1) return EasyStar.TOP_RIGHT
else if (diffX === 1 && diffY === 0) return EasyStar.RIGHT
else if (diffX === 1 && diffY === 1) return EasyStar.BOTTOM_RIGHT
else if (diffX === 0 && diffY === 1) return EasyStar.BOTTOM
else if (diffX === -1 && diffY === 1) return EasyStar.BOTTOM_LEFT
else if (diffX === -1 && diffY === 0) return EasyStar.LEFT
else if (diffX === -1 && diffY === -1) return EasyStar.TOP_LEFT
throw new Error('These differences are not valid: ' + diffX + ', ' + diffY)
};
var getTileCost = function(x, y) {
return (pointsToCost[y] && pointsToCost[y][x]) || costMap[collisionGrid[y][x]]
};
var coordinateToNode = function(instance, x, y, parent, cost) {
if (instance.nodeHash[y] !== undefined) {
if (instance.nodeHash[y][x] !== undefined) {
return instance.nodeHash[y][x];
}
} else {
instance.nodeHash[y] = {};
}
var simpleDistanceToTarget = getDistance(x, y, instance.endX, instance.endY);
if (parent!==null) {
var costSoFar = parent.costSoFar + cost;
} else {
costSoFar = 0;
}
var node = new Node(parent,x,y,costSoFar,simpleDistanceToTarget);
instance.nodeHash[y][x] = node;
return node;
};
var getDistance = function(x1,y1,x2,y2) {
if (diagonalsEnabled) {
// Octile distance
var dx = Math.abs(x1 - x2);
var dy = Math.abs(y1 - y2);
if (dx < dy) {
return DIAGONAL_COST * dx + dy;
} else {
return DIAGONAL_COST * dy + dx;
}
} else {
// Manhattan distance
var dx = Math.abs(x1 - x2);
var dy = Math.abs(y1 - y2);
return (dx + dy);
}
};
}
EasyStar.TOP = 1
EasyStar.TOP_RIGHT = 2
EasyStar.RIGHT = 4
EasyStar.BOTTOM_RIGHT = 8
EasyStar.BOTTOM = 16
EasyStar.BOTTOM_LEFT = 32
EasyStar.LEFT = 64
EasyStar.TOP_LEFT = 128