Skip to content

Commit 0742c22

Browse files
authored
Merge pull request #11 from oguzeroglu/find-shortest-path-cost-modifier
Add cost modifier to AStar#findShortestPath API
2 parents dbf7336 + 92c2f3f commit 0742c22

2 files changed

Lines changed: 32 additions & 1 deletion

File tree

js/core/AStar.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ AStar.prototype.isNodeClosed = function(node, searchID){
114114
return node.closedTag === searchID;
115115
}
116116

117-
AStar.prototype.findShortestPath = function(fromVector, toVector){
117+
AStar.prototype.findShortestPath = function(fromVector, toVector, costModifier){
118118

119119
var heapNodes = this.heapNodes;
120120

@@ -159,6 +159,9 @@ AStar.prototype.findShortestPath = function(fromVector, toVector){
159159
var neighborHeapNode = getHeapNode(neighborVec.x, neighborVec.y, neighborVec.z, heapNodes);
160160

161161
var heuristicCost = totalCost;
162+
if (costModifier){
163+
heuristicCost += costModifier(vec.x, vec.y, vec.z, neighborVec.x, neighborVec.y, neighborVec.z);
164+
}
162165

163166
if (!isNodeClosed(neighborHeapNode, searchID)){
164167
neighborHeapNode.priority = cost + heuristicCost;

test/core/AStarTest.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,34 @@ describe("AStar", function(){
325325
aStar.findShortestPath(vertex3, vertex1);
326326
expect(called).to.eql(false);
327327
});
328+
329+
it("should consider costModifier if passed", function(){
330+
var v1 = new Kompute.Vector3D(0, 0, 0);
331+
var v2 = new Kompute.Vector3D(10, 0, 0);
332+
var v3 = new Kompute.Vector3D(0 -50, 0);
333+
var graph = new Kompute.Graph();
334+
graph.addVertex(v1);
335+
graph.addVertex(v2);
336+
graph.addVertex(v3);
337+
graph.addEdge(v1, v2); // v1 --- v2
338+
graph.addEdge(v1, v3); // | |
339+
graph.addEdge(v3, v2); // v3 -----
340+
var aStar = new Kompute.AStar(graph);
341+
var path = aStar.findShortestPath(v1, v2, function(x1, y1, z1, x2, y2, z2){
342+
if (new Kompute.Vector3D(x1, y1, z1).eql(v1) && new Kompute.Vector3D(x2, y2, z2).eql(v2)) {
343+
return Infinity;
344+
}
345+
346+
return 0;
347+
});
348+
expect(path.getCurrentWaypoint()).to.eql(v1);
349+
path.next();
350+
expect(path.getCurrentWaypoint()).to.eql(v3);
351+
path.next();
352+
expect(path.getCurrentWaypoint()).to.eql(v2);
353+
path.next();
354+
expect(path.getCurrentWaypoint()).to.eql(false);
355+
});
328356
});
329357

330358
describe("AStar - Integration", function(){

0 commit comments

Comments
 (0)