public List <ASNode> GetNodeNeighbors(ASNode node) { List <ASNode> neighbours = new List <ASNode>(); for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { if (x == 0 && y == 0) //exclude center node { continue; } if (x != 0 && y != 0) // exclude diagonal nodes. Comment the statement to take them in { continue; } int checkX = node.x + x; int checkY = node.y + y; if (checkX >= 0 && checkX < gridSizeX && checkY >= 0 && checkY < gridSizeY) { neighbours.Add(grid[checkX, checkY]); } } } return(neighbours); }
public void Find(ASMap map, ASNode start, ASNode end) { openList.Clear(); closeList.Clear(); //path.Clear(); _start = start; _end = end; _map = map; _start.g = _start.h = _start.f = 0; _start.pre = null; AddOpen(_start); bool hasPath = false; while(openList.Count > 0) { ASNode cur = GetMinNode(); //Debug.Log("cur find : (" + cur.pos.x + "," + cur.pos.y + ")"); AddClose(cur); if (cur == _end) { EndSearch(cur); hasPath = true; break; } Near(cur); } if (!hasPath)Debug.Log("No Path"); }
public HexAstar(Vector2 start, Vector2 end, HexCell[,] hexMap) { this.hexMap = hexMap; this.pathway = new List <Vector2>(); openList = new ASNode[hexMap.GetLength(0), hexMap.GetLength(1)]; closedList = new ASNode[hexMap.GetLength(0), hexMap.GetLength(1)]; selectedCoords = new Vector2[(int)HexDirections.Total]; this.start = start; this.end = end; // Assign starting node. float startF, startG, startH; startG = 0.0f; startH = heuristicDerivative(start, end); startF = startG + startH; ASNode startNode = new ASNode(start, new Vector2(-1, -1), startF, startG, startH); openList[(int)start.Y, (int)start.X] = startNode; AStarBitch(startNode, (int)startNode.coordinates.Y, (int)startNode.coordinates.X); }
int GetManhattanDistance(ASNode nodeA, ASNode nodeB) { int dstX = Mathf.Abs(nodeA.x - nodeB.x); int dstY = Mathf.Abs(nodeA.y - nodeB.y); if (dstX > dstY) { return(manhattanKD * dstY + manhattanKD * (dstX - dstY)); } return(manhattanKD * dstX + manhattanKN * (dstY - dstX)); }
void RetracePath(ASNode startNode, ASNode endNode) { pathNodes = new List <ASNode>(); ASNode currentNode = endNode; while (currentNode != startNode) { pathNodes.Add(currentNode); currentNode = currentNode.parentNode; } pathNodes.Reverse(); path = pathNodes.Select(node => node.worldPos).ToList(); }
public void GenerateGrid(GameGrid gameGrid) { grid = new ASNode[gameGrid.Nodes.GetLength(0), gameGrid.Nodes.GetLength(1)]; for (int x = 0; x < gameGrid.Nodes.GetLength(0); x++) { for (int y = 0; y < gameGrid.Nodes.GetLength(1); y++) { Vector3 worldPoint = gameGrid.Nodes[x, y].transform.position; bool obstacleCollision = !(Physics.CheckSphere(worldPoint, nodeD * 0.4f, unwalkableMask)); grid[x, y] = new ASNode(x, y, worldPoint, obstacleCollision); } } }
private void Start() { terrainMask = LayerMask.GetMask("Terrain"); nodeGrid = new ASNode[(int)gridSize.y, (int)gridSize.x]; for (int x = 0; x < gridSize.x; x++) { for (int y = 0; y < gridSize.y; y++) { Vector2 worldPos = new Vector2((0.5f + x - gridSize.x / 2) * nodeSize, (0.5f + y - gridSize.y / 2) * nodeSize); nodeGrid[y, x] = new ASNode(worldPos, x, y, !Physics2D.OverlapBox(worldPos, Vector2.one, 0f, terrainMask)); } } }
public ASMap(int row, int col) { r = row; c = col; map = new ASNode[row,col]; Debug.Log("map : " + map.ToString()); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { map[i,j] = new ASNode(); map[i,j].pos = new nodepos(0,0); } } }
public void GenerateGrid() { Vector3 gridLeftBottomInWorld = gridCenterPosition - Vector3.right * gridWorldSize.x * 0.5f - Vector3.forward * gridWorldSize.y * 0.5f; for (int x = 0; x < gridSizeX; x++) { for (int y = 0; y < gridSizeY; y++) { Vector3 worldPoint = gridLeftBottomInWorld + Vector3.right * (x * nodeD + nodeD * 0.5f) + Vector3.forward * (y * nodeD + nodeD * 0.5f); bool obstacleCollision = !(Physics.CheckSphere(worldPoint, nodeD * 0.5f, unwalkableMask)); grid[x, y] = new ASNode(x, y, worldPoint, obstacleCollision); } } }
void EndSearch(ASNode node) { Debug.Log("Search end : Success!"); ASNode tempNode = node.pre; while(true) { if (tempNode != null) { if (tempNode.pre == null)break; tempNode.obj.GetComponent<SpriteRenderer>().color = Color.blue; tempNode = tempNode.pre; } else break; } }
void RemoveOpen(ASNode node) { node.ls = ListState.NULL; openList.Remove(node); }
void AddOpen(ASNode node) { if (node != _start && node != _end) { node.obj.GetComponent<SpriteRenderer>().color = Color.gray; } node.ls = ListState.OPEN; openList.Add(node); }
void AddClose(ASNode node) { node.ls = ListState.CLOSE; closeList.Add(node); }
static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("USAGE:"); Console.WriteLine("mono TestingApplication.exe -bulk <input file> <dest1> ... <dstN> -q <src1> <dst1> ... <srcN> <dstN>"); Console.WriteLine("mono TestingApplication.exe -serverPORT <input file> <precomp file> <cache file>"); Console.WriteLine("mono TestingApplication.exe -cmd"); return; } if ("-cmd" == args[0]) { TestingClass test = new TestingClass(); test.CLI(false); return; } // Graph initialization //NetworkGraph g = new NetworkGraph(); // E.g., input Cyclops_caida.txt if (File.Exists(args[1])) { InputFileReader iFR = new InputFileReader(args[1], g); iFR.ProcessFile(); Int32 p2pEdges = 0; Int32 c2pEdges = 0; foreach (var ASNode in g.GetAllNodes()) { p2pEdges += ASNode.GetNeighborTypeCount(RelationshipType.PeerOf); c2pEdges += ASNode.GetNeighborTypeCount(RelationshipType.CustomerOf); c2pEdges += ASNode.GetNeighborTypeCount(RelationshipType.ProviderTo); } //Console.WriteLine("Read in the graph, it has " + g.NodeCount + " nodes and " + g.EdgeCount + " edges."); //Console.WriteLine("P2P: " + p2pEdges + " C2P: " + c2pEdges); } else { Console.WriteLine("The file " + args[1] + " does not exist."); return; } if ("-bulk" == args[0]) { // Setting destinations //HashSet<string> dests = new HashSet<string>(); //List<Destination> d = new List<Destination>(); int i = 1; for (i = 1; i < args.Length; ++i) { if ("-q" == args[i]) { break; } if (dests.Contains(args[i])) { continue; } dests.Add(args[i]); Destination newD = new Destination(); if (initDestination(ref g, ref newD, args[i])) { d.Add(args[i], newD); Console.WriteLine("Initialized and added " + newD.destination); } } Console.WriteLine("DESTS " + dests.Count); // Approaching queries for (i = i + 1; i < args.Length; i += 2) { //StringBuilder res = new StringBuilder(); //int l = getPath(ref d, args[i], args[i+1]); //getAllPathsOfLength(ref d, l, args[i], args[i+1], ref res); List <List <UInt32> > allPaths = new List <List <UInt32> >(); if (d.ContainsKey(args[i + 1])) { UInt32 src; UInt32 dst; if (UInt32.TryParse(args[i], out src) && UInt32.TryParse(args[i + 1], out dst)) { Console.WriteLine("ASes from " + src + " to " + dst); d[args[i + 1]].GetAllBestPaths(src, dst, ref allPaths); } } foreach (List <UInt32> path in allPaths) { for (int j = 0; j < path.Count; ++j) { Console.WriteLine(path[j]); } Console.WriteLine("-"); } } return; } if (args[0].StartsWith("-server")) { if (args.Length > 2) { loadPrecomputation(args[2]); cacheDestinations(args[3]); } String port = args[0].Replace("-server", ""); StartListening(port); } }
void RemoveClose(ASNode node) { node.ls = ListState.NULL; closeList.Remove(node); }
private static void edgeIterationSummarize(resultObject Result, int iteration, StreamWriter output, char sep) { if (iteration == 0) { return; } bool[] lastIteration = Result.state[iteration - 1]; bool[] currIteration = Result.state[iteration]; var ASNodes = Result.g.GetAllNodes(); int totalEdges = 0; int customerEdges = 0; int peerEdges = 0; int providerEdges = 0; int totalNonStubEdges = 0; int customerNonStubEdges = 0; int peerNonStubEdges = 0; int providerNonStubEdges = 0; var nonStubs = Result.g.getNonStubs(); foreach (var ASNode in ASNodes) { //this AS has flipped. if (currIteration[ASNode.NodeNum] != lastIteration[ASNode.NodeNum]) { var customers = ASNode.GetNeighborsByType(RelationshipType.ProviderTo); var peers = ASNode.GetNeighborsByType(RelationshipType.PeerOf); var providers = ASNode.GetNeighborsByType(RelationshipType.CustomerOf); foreach (var c in customers) { if (lastIteration[c.NodeNum]) { customerEdges++; totalEdges++; if (nonStubs.Contains(c.NodeNum)) { customerNonStubEdges++; totalNonStubEdges++; } } } foreach (var p in peers) { if (lastIteration[p.NodeNum]) { peerEdges++; totalEdges++; if (nonStubs.Contains(p.NodeNum)) { peerNonStubEdges++; totalNonStubEdges++; } } } foreach (var p in providers) { if (lastIteration[p.NodeNum]) { providerEdges++; totalEdges++; if (nonStubs.Contains(p.NodeNum)) { providerNonStubEdges++; totalNonStubEdges++; } } } } } output.WriteLine("{0}" + sep + "{1}" + sep + "{2}" + sep + "{3}" + sep + "{4}" + sep + "{5}" + sep + "{6}" + sep + "{7}" + sep + "{8}", iteration, totalEdges, customerEdges, peerEdges, providerEdges, totalNonStubEdges, customerNonStubEdges, peerNonStubEdges, providerNonStubEdges); }
public void FindPathFromAtoB(PathRequestData pathRequest) { ASNode startNode = grid.GetNodeFromWorldPoint(pathRequest.startPos); ASNode finishNode = grid.GetNodeFromWorldPoint(pathRequest.finishPos); if (finishNode.walkable == false) { return; } List <ASNode> openNodes = new List <ASNode>(); HashSet <ASNode> closedNodes = new HashSet <ASNode>(); openNodes.Add(startNode); while (openNodes.Count > 0) { ASNode currentNode = openNodes[0]; for (int i = 1; i < openNodes.Count; i++) { if (openNodes[i].FCost < currentNode.FCost || openNodes[i].FCost == currentNode.FCost && openNodes[i].hCost < currentNode.hCost) { if (openNodes[i].hCost < currentNode.hCost) { currentNode = openNodes[i]; } } } openNodes.Remove(currentNode); closedNodes.Add(currentNode); if (currentNode == finishNode) { RetracePath(startNode, finishNode); pathRequest.pathGetter(path); return; } foreach (ASNode neighbour in grid.GetNodeNeighbors(currentNode)) { if (!neighbour.walkable || closedNodes.Contains(neighbour)) { continue; } int newGCostToNeighbour = currentNode.gCost + GetManhattanDistance(currentNode, neighbour); if (newGCostToNeighbour < neighbour.gCost || !openNodes.Contains(neighbour)) { neighbour.gCost = newGCostToNeighbour; neighbour.hCost = GetManhattanDistance(neighbour, finishNode); neighbour.parentNode = currentNode; if (!openNodes.Contains(neighbour)) { openNodes.Add(neighbour); } } } } }
public void CleanPathData() { f = g = h = 0; ls = ListState.NULL; pre = null; }
/// <summary> /// Returns the shortest traversable route for AI from supplied start point to target /// </summary> /// <param name="start"></param> /// <param name="target"></param> /// <returns></returns> Vector3[] ASPath(Vector3 start, Vector3 target) { // Creates both the start node and end node for the algorithm ASNode node_start = new ASNode(start); ASNode node_target = new ASNode(target); // Creates two empty list of nodes one for avalible nodes to cover and one for nodes already checked List <ASNode> OpenNodes = new List <ASNode>(); List <ASNode> ClosedNodes = new List <ASNode>(); // Sets the first nodes F values (its distance score) to zero as its the starting point node_start.F = 0.0f; OpenNodes.Add(node_start); int count = 0; // Cycles through all nodes until target is found or no more nodes to check while (OpenNodes.Count > 0) { ASNode node_current = OpenNodes[0]; int index = 0; // Finds the node and sets the current node to the node with the lowest F value for (int i = 0; i < OpenNodes.Count; i++) { if (OpenNodes[i].F < node_current.F) { // Updates current node and current index node_current = OpenNodes[i]; index = i; } } //Console.WriteLine(node_current.Position); // Remove from availble nodes and add to closed nodes list OpenNodes.RemoveAt(index); ClosedNodes.Add(node_current); // Check if current node is the target if (node_current.Position.Xz == node_target.Position.Xz) { // Backtrack through parent of each node and add to list List <Vector3> path = new List <Vector3>(); while (node_current.Parent != null) { // Add node position to list then set to parent node path.Add(node_current.Position); node_current = node_current.Parent; } // Reverse the list and return as path is found path.Reverse(); return(path.ToArray()); } // Check surround nodes around current node List <ASNode> children = new List <ASNode>(); // Creates array of all the directions to check Vector3[] direction = new Vector3[] { new Vector3(node_current.Position.X, 0.0f, node_current.Position.Z + 1.0f), // Forward new Vector3(node_current.Position.X, 0.0f, node_current.Position.Z - 1.0f), // Back new Vector3(node_current.Position.X + 1.0f, 0.0f, node_current.Position.Z), // Right new Vector3(node_current.Position.X - 1.0f, 0.0f, node_current.Position.Z), // Left new Vector3(node_current.Position.X - 1.0f, 0.0f, node_current.Position.Z + 1.0f), // TopLeft new Vector3(node_current.Position.X + 1.0f, 0.0f, node_current.Position.Z + 1.0f), // TopRight new Vector3(node_current.Position.X - 1.0f, 0.0f, node_current.Position.Z - 1.0f), // BottomLeft new Vector3(node_current.Position.X + 1.0f, 0.0f, node_current.Position.Z - 1.0f) // BottomLeft }; // Checks all directions and if its traversable/within boundaries then creates new child for (int i = 0; i < direction.Length; i++) { // Offset to go from world coords to 2d array coords int xOffset = mWidth / 2; int zOffset = mHeight / 2; // Checks if the direction would be out of map boundaries if (direction[i].X + xOffset >= Traversable.GetLength(1) - 1 || direction[i].X + xOffset < 0 || direction[i].Z + zOffset >= Traversable.GetLength(0) - 1 || direction[i].Z + zOffset < 0) { continue; } // Checks if that direction would hit a rigid collider (created using CalculateTraversableTiles()) if (!Traversable[(int)direction[i].Z + xOffset, (int)direction[i].X + zOffset]) { continue; } // At this point this child should have a traversable position so add to list ASNode node_newChild = new ASNode(node_current, direction[i]); children.Add(node_newChild); } // Compare all the available children to find child with best F score for (int child = 0; child < children.Count; child++) { // Checks if this child has been checked before for (int i = 0; i < ClosedNodes.Count; i++) { if (ClosedNodes[i].Position == children[child].Position) { goto NewChild; } } // Calculate childs F score children[child].G = node_current.G + 1.0f; // Calculate H using pythagoris float x = (float)Math.Pow(children[child].Position.X - node_target.Position.X, 2); float z = (float)Math.Pow(children[child].Position.Z - node_target.Position.Z, 2); children[child].H = x + z; // Childs score children[child].F = children[child].G + children[child].H; // Checks if child is already in OpenNodes before adding foreach (ASNode openChild in OpenNodes) { if (children[child].Position == openChild.Position && children[child].G > openChild.G) { goto NewChild; } } // Child is valid so add to OpenNodes OpenNodes.Add(children[child]); NewChild :; } // Failsafe to stop endless loop incase of bugs // Checks to see if the loop count has exceeded the total number of tiles count++; if (count > Traversable.Length * 4) { break; } } // Should never hit this but if it does then AI's path with be nothing return(null); }
public void AStarBitch(ASNode parentNode, int y, int x) { // Reset sensitive variables. lowestF = 65535.0f; lowestNode = new ASNode(new Vector2(-1, -1), new Vector2(-1, -1), 65535.0f, 0.0f, 0.0f); lowestSelection = -1; if (y % 2 == 0) { oddRow = false; } else { oddRow = true; } for (int idx = 0; idx < (int)HexDirections.Total; idx++) { switch (idx) { case (int)HexDirections.TopRight: if (oddRow) { selectedCoords[idx] = new Vector2(x + 1, y + 1); } else { selectedCoords[idx] = new Vector2(x, y + 1); } break; case (int)HexDirections.Right: selectedCoords[idx] = new Vector2(x + 1, y); break; case (int)HexDirections.BottomRight: if (oddRow) { selectedCoords[idx] = new Vector2(x + 1, y - 1); } else { selectedCoords[idx] = new Vector2(x, y - 1); } break; case (int)HexDirections.BottomLeft: if (oddRow) { selectedCoords[idx] = new Vector2(x, y - 1); } else { selectedCoords[idx] = new Vector2(x - 1, y - 1); } break; case (int)HexDirections.Left: selectedCoords[idx] = new Vector2(x - 1, y); break; case (int)HexDirections.TopLeft: if (oddRow) { selectedCoords[idx] = new Vector2(x, y + 1); } else { selectedCoords[idx] = new Vector2(x - 1, y + 1); } break; } // Ensure selected coordinates are in bounds... if (selectedCoords[idx].X >= 0 && selectedCoords[idx].X < openList.GetLength(1)) { if (selectedCoords[idx].Y >= 0 && selectedCoords[idx].Y < openList.GetLength(0)) { // ...have no impassables (unless the target is an impassable)... if (((selectedCoords[idx].Y == end.Y && selectedCoords[idx].X == end.X) && hexMap[(int)end.Y, (int)end.X].hasShip) || !hexMap[(int)selectedCoords[idx].Y, (int)selectedCoords[idx].X].hasShip) { // ...and not in the closed list and then add to the open list. if (!closedList[(int)selectedCoords[idx].Y, (int)selectedCoords[idx].X].active) { float G = parentNode.G + 1.0f; float H = heuristicDerivative(hexMap[(int)selectedCoords[idx].Y, (int)selectedCoords[idx].X].GetCoordinates(), end); float F = G + H; ASNode newNode = new ASNode(selectedCoords[idx], parentNode.coordinates, F, G, H); openList[(int)selectedCoords[idx].Y, (int)selectedCoords[idx].X] = newNode; } } } } } // Drop this parent node from open list and transfer to closed list. closedList[(int)parentNode.coordinates.Y, (int)parentNode.coordinates.X] = openList[(int)parentNode.coordinates.Y, (int)parentNode.coordinates.X]; openList[(int)parentNode.coordinates.Y, (int)parentNode.coordinates.X].active = false; // Find best cost path. for (int idx = 0; idx < (int)HexDirections.Total; idx++) { // Discard indices out of bounds. if (selectedCoords[idx].X < 0 || selectedCoords[idx].Y < 0) { continue; } if (selectedCoords[idx].X >= openList.GetLength(1) || selectedCoords[idx].Y >= openList.GetLength(0)) { continue; } if (openList[(int)selectedCoords[idx].Y, (int)selectedCoords[idx].X].active == true && openList[(int)selectedCoords[idx].Y, (int)selectedCoords[idx].X].F < lowestF) { lowestF = openList[(int)selectedCoords[idx].Y, (int)selectedCoords[idx].X].F; lowestNode = openList[(int)selectedCoords[idx].Y, (int)selectedCoords[idx].X]; lowestSelection = idx; } } if (lowestSelection != -1) { // Mark this best cost as a pathway. if (!hexMap[(int)selectedCoords[lowestSelection].Y, (int)selectedCoords[lowestSelection].X].hasShip) { openList[(int)lowestNode.coordinates.Y, (int)lowestNode.coordinates.X].path = true; pathway.Add(lowestNode.coordinates); } } else { // There is no path! } // Put all other nodes in the closed list. for (int idx = 0; idx < (int)HexDirections.Total; idx++) { // Discard indices out of bounds. if (selectedCoords[idx].X < 0 || selectedCoords[idx].Y < 0) { continue; } if (selectedCoords[idx].X >= openList.GetLength(1) || selectedCoords[idx].Y >= openList.GetLength(0)) { continue; } // Skip if we hit the open list winner. if (idx == lowestSelection) { continue; } openList[(int)selectedCoords[idx].Y, (int)selectedCoords[idx].X] = closedList[(int)selectedCoords[idx].Y, (int)selectedCoords[idx].X]; openList[(int)selectedCoords[idx].Y, (int)selectedCoords[idx].X].active = false; } // If we haven't reached our destination and the next move isn't an impassable, iterate through again. if (lowestSelection != -1) { if (lowestNode.coordinates != end && !hexMap[(int)selectedCoords[lowestSelection].Y, (int)selectedCoords[lowestSelection].X].hasShip) { AStarBitch(lowestNode, (int)lowestNode.coordinates.Y, (int)lowestNode.coordinates.X); } } }
// the near node of the node, add near node to open void Near(ASNode node) { RandSwapList(); foreach (nodepos pos in poslist) { ASNode n = _map.GetNode(node.pos.x + pos.x, node.pos.y + pos.y); if (n == null || n.ls == ListState.CLOSE)continue; // 没有点,在close中 if (n.walkable) // 可走 { if (n.ls == ListState.NULL) // 没处理的点 { n.g = node.g + 1; n.h = H(node.pos.x + pos.x, node.pos.y - pos.y); n.f = n.g + n.h; n.pre = node; AddOpen(n); } else if (n.ls == ListState.OPEN) // 在open中 { if (n.g > node.g + 1) // 当前的计算比open中的更优 { n.g = node.g + 1; n.h = node.h; n.f = node.f; n.pre = node; //SortOpen(); // 重新排列open } } } } }
void GridClick(GridClick grid) { Debug.Log("Grid Click (" + grid.node.pos.x + "," + grid.node.pos.y + ")"); switch(state) { case ClickState.START: node_start = grid.node; UpdateMap(); break; case ClickState.END: node_end = grid.node; UpdateMap(); break; default : break; } state = ClickState.NULL; }
public void SetNode(int row, int col, ASNode node) { map[row, col] = node; }