public void TestHeapSort() { Heap<int> h = new Heap<int>(); h.Insert(500); h.Insert(100); h.Insert(200); h.Insert(50); h.Insert(1); h.Insert(420); h.Insert(3); h.Insert(250); h.Insert(5); h.Insert(499); int[] sortedItems = h.HeapSort(); Assert.AreEqual(1, sortedItems[0]); Assert.AreEqual(3, sortedItems[1]); Assert.AreEqual(5, sortedItems[2]); Assert.AreEqual(50, sortedItems[3]); Assert.AreEqual(100, sortedItems[4]); Assert.AreEqual(200, sortedItems[5]); Assert.AreEqual(250, sortedItems[6]); Assert.AreEqual(420, sortedItems[7]); Assert.AreEqual(499, sortedItems[8]); Assert.AreEqual(500, sortedItems[9]); }
public void ContainsMaxHeapTest() { Heap<int> actual = new Heap<int>(Strategy.Max) {23, 45, 1, 9, 12}; Assert.IsTrue(actual.Contains(12)); Assert.IsFalse(actual.Contains(99)); }
IEnumerator FindPath(Vector3 startPos, Vector3 targetPos) { Stopwatch sw = new Stopwatch(); sw.Start(); Vector3[] waypoints = new Vector3[0]; bool pathSuccess = false; Node startNode = grid.NodeFromWorldPoint(startPos); Node targetNode = grid.NodeFromWorldPoint(targetPos); if (startNode.walkable && targetNode.walkable) { Heap<Node> openSet = new Heap<Node>(grid.MaxSize); HashSet<Node> closedSet = new HashSet<Node>(); openSet.Add(startNode); while (openSet.Count > 0) { Node currentNode = openSet.RemoveFirst(); closedSet.Add(currentNode); if (currentNode == targetNode) { sw.Stop(); print ("Path found: " + sw.ElapsedMilliseconds + " ms"); pathSuccess = true; break; } foreach (Node neighbour in grid.GetNeighbours(currentNode)) { if (!neighbour.walkable || closedSet.Contains(neighbour)) { continue; } int newMovementCostToNeighbour = currentNode.gCost + GetDistance(currentNode, neighbour) + neighbour.movementPenalty; if (newMovementCostToNeighbour < neighbour.gCost || !openSet.Contains(neighbour)) { neighbour.gCost = newMovementCostToNeighbour; neighbour.hCost = GetDistance(neighbour, targetNode); neighbour.parent = currentNode; if (!openSet.Contains(neighbour)) openSet.Add(neighbour); else openSet.UpdateItem (neighbour); } } } } yield return null; if (pathSuccess) { waypoints = RetracePath(startNode,targetNode); } requestManager.FinishedProcessingPath(waypoints,pathSuccess); }
public void ContainsMinHeapTest() { Heap<char> actual = new Heap<char> {'g', 'r', 'a', 'n', 'v'}; Assert.IsTrue(actual.Contains('a')); Assert.IsFalse(actual.Contains('l')); }
public void CopyConstructorWithStrategyTest() { List<string> collection = new List<string> { "Granville", "Barnett", "Luca", "Del", "Tongo" }; Heap<string> actual = new Heap<string>(collection, Strategy.Max); Assert.AreEqual(5, actual.Count); }
public void Simple() { var heap = new Heap<int>(HeapType.Maximum); Assert.AreEqual(heap.Type, HeapType.Maximum); Assert.AreEqual(heap.Count, 0); Assert.IsTrue(heap.IsEmpty); heap = new Heap<int>(HeapType.Maximum, Comparer<int>.Default); Assert.AreEqual(heap.Type, HeapType.Maximum); Assert.AreEqual(heap.Count, 0); Assert.IsTrue(heap.IsEmpty); heap = new Heap<int>(HeapType.Maximum, 50); Assert.AreEqual(heap.Type, HeapType.Maximum); Assert.AreEqual(heap.Count, 0); Assert.IsTrue(heap.IsEmpty); heap = new Heap<int>(HeapType.Maximum, 50, Comparer<int>.Default); Assert.AreEqual(heap.Type, HeapType.Maximum); Assert.AreEqual(heap.Count, 0); Assert.IsTrue(heap.IsEmpty); }
public void FindPath(Grid _grid) { Node start = _grid.StartNode; Node end = _grid.EndNode; open = new Heap<Node>(_grid.GridMaxSize); close = new HashSet<Node>(); open.Add(start); while (open.Count > 0) { Node current = open.GetFirst(); if (current.GridBlock.Equals(end.GridBlock)) return; foreach(Node p in _grid.GetNeighbours(current)) { if (p.GridBlock.Type != GridBlock.BlockType.Obstacle || close.Contains(p)) continue; int gCost = current.gCost + GetDistance(current, p); if(gCost < current.gCost || !open.Contains(p)) { p.gCost = gCost; p.hCost = GetDistance(current, p); p.Parent = current; if (!open.Contains(p)) open.Add(p); } } } }
public int NthSuperUglyNumber(int n, int[] primes) { if(n == 1){ return 1; } if(primes == null || !primes.Any()){ return 1;} if(primes.Length == 1){ return (int)Math.Pow(primes[0],(n-1)); } var uglies = new int[n]; uglies[0] = 1; var c = 1; var minHeap = new Heap(primes); while(c < n){ var m = minHeap.GetMin(); var prime = m.GetPrime(uglies); var index = m.UglyIndex; var possibility = m.Value; if(possibility != uglies[c-1]){ uglies[c++] = possibility; } minHeap.ReplaceMin(uglies[index+1] * prime, index+1); } return uglies.Last(); }
public TNodeMatrixAssign(TNode Parent, Heap<CellMatrix> Heap, int Ref, MNode Expression) : base(Parent) { this._expression = Expression; this._ref = Ref; this._mat = Heap; }
public AStar() { FOpenList = new Heap(); FClosedList = new Heap(); FSuccessors = new ArrayList(); FSolution = new ArrayList(); }
/* 1 Implement a class PriorityQueue<T> based * on the data structure "binary heap". * */ static void Main(string[] args) { var heap = new Heap<int>(); heap.Add(1); heap.Add(2); heap.Add(3); Debug.Assert(heap.SameContents(new[] { 1, 2, 3 })); Console.WriteLine(string.Join(",", heap)); Debug.Assert(heap.ChopHead() == 3); Debug.Assert(heap.ChopHead() == 2); Debug.Assert(heap.ChopHead() == 1); Debug.Assert(heap.IsEmpty); // higher string means lower priority var pqueue = new PriorityQueue<string, string>((s1, s2) => -s1.CompareTo(s2)); pqueue.Enqueue("18:00", "Buy food"); pqueue.Enqueue("06:00", "Walk dog"); pqueue.Enqueue("21:00", "Do homework"); pqueue.Enqueue("09:00", "Go to work"); pqueue.Enqueue("21:00", "Drink beer"); Debug.Assert(pqueue.Count == 5); Debug.Assert(pqueue.Dequeue() == "Walk dog"); Debug.Assert(pqueue.Dequeue() == "Go to work"); Debug.Assert(pqueue.Dequeue() == "Buy food"); Debug.Assert(new[] { "Do homework", "Drink beer" }.Contains(pqueue.Dequeue())); Debug.Assert(new[] { "Do homework", "Drink beer" }.Contains(pqueue.Dequeue())); }
public static void Dijkstra(List<Tuple<int, int>>[] adj, int source, out int[] dist, out int[] pred) { int inf = int.MaxValue; int N = adj.Length; dist = new int[N]; pred = new int[N]; for (int i = 0; i < N; i++) dist[i] = inf; dist[source] = 0; Heap<int, int> heap = new Heap<int, int>(N, true); heap.Push(source, 0); while (!heap.IsEmpty()) { int u = heap.PeekData(); if (dist[u] != heap.Pop().Priority) continue; foreach (var tuple in adj[u]) { int v = tuple.Item1; int uvWeight = tuple.Item2; if (dist[v] > dist[u] + uvWeight) { dist[v] = dist[u] + uvWeight; pred[v] = u; heap.Push(v, dist[v]); } } } }
public void Simple() { var heap = new Heap<int>(HeapType.Minimum) { 5 }; Assert.AreEqual(heap.Count, 1); Assert.IsFalse(heap.IsEmpty); Assert.AreEqual(heap.Root, 5); heap.Add(2); Assert.AreEqual(heap.Count, 2); Assert.IsFalse(heap.IsEmpty); Assert.AreEqual(heap.Root, 2); heap.Add(3); Assert.AreEqual(heap.Count, 3); Assert.IsFalse(heap.IsEmpty); Assert.AreEqual(heap.Root, 2); Assert.AreEqual(heap.RemoveRoot(), 2); heap.Add(1); Assert.AreEqual(heap.Count, 3); Assert.IsFalse(heap.IsEmpty); Assert.AreEqual(heap.Root, 1); }
static void Main(string[] args) { StreamReader reader = new StreamReader(@"C:\Users\Darsh\Documents\Visual Studio 2013\Projects\ProjectThree\ProjectThree\input.txt"); Student student; Heap<Student> theHeap = new Heap<Student>(); string sr = reader.ReadLine();//raid Student[] records = new Student[sr.Length]; while (sr != null)// while there is still text { string[] delimiter = { ",", " " }; string[] info = sr.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); student = new Student(Convert.ToInt32(info[0]), Convert.ToDouble(info[1])); theHeap.Insert(student);//insert all data into the Heap sr = reader.ReadLine(); } Console.WriteLine("Empty? {0}",theHeap.IsEmpty()); //false Console.WriteLine("Root: {0}",theHeap.GetRoot()); theHeap.RemoveRoot(); theHeap.Print(); //Prints out student id and gpa as min heap Console.WriteLine(); Console.WriteLine("HEAPSORT!!"); theHeap.HeapSort();//prints out the heap sort going from high to low Console.ReadKey(); }
/// <summary> /// De hoofdfunctie van de pathfinding. /// </summary> /// <param name="a">Start positie als AstarObject</param> /// <param name="b">Eind positie als AstarObject</param> /// <param name="T"> Het type weg waarin hij moet zoeken</param> /// <returns></returns> List<Point> FindRoadPath(Road a, Road b, RoadType T) { AstarObject[,] Set = new AstarObject[14, 9]; for (int x = 0; x < 14; x++) { for (int y = 0; y < 9; y++) { Set[x, y] = new AstarObject(x, y, this); } } Heap<AstarObject> OpenSet = new Heap<AstarObject>(14 * 9); HashSet<AstarObject> ClosedSet = new HashSet<AstarObject>(); AstarObject Start = Set[a.X, a.Y]; AstarObject End = Set[b.X, b.Y]; OpenSet.Add(Start); while (OpenSet.Count > 0) { AstarObject CurrentLocation = OpenSet.RemoveFirst(); ClosedSet.Add(CurrentLocation); if (CurrentLocation == End) { return RetracePath(Start, End); //Retracepath and stuff. } List<AstarObject> Neighbours = GetNeighbours(CurrentLocation, ref Set, NeighbourhoodType.Neumann, MapsizeXR, MapsizeYR); foreach (AstarObject neighbour in Neighbours) { if (neighbour.RType != T || ClosedSet.Contains(neighbour)) { continue; } int newMovementCostToNeighbour = CurrentLocation.gCost + GetDistance(CurrentLocation, neighbour); if (newMovementCostToNeighbour < neighbour.gCost || !OpenSet.Contains(neighbour)) { neighbour.gCost = newMovementCostToNeighbour; neighbour.hCost = GetDistance(neighbour, End); neighbour.parent = CurrentLocation; if (!OpenSet.Contains(neighbour)) { OpenSet.Add(neighbour); } else { OpenSet.UpdateItem(neighbour); } } } } return new List<Point>(); }
public void Insert_MultipleBubbleToRoot() { Heap<int> heap = new Heap<int>(HeapType.Max) { List = new List<int>() { 150, // root 50, // left child 100, // right child 45, // left child of 50 40, // right child of 50 95, // left child of 100 90, // right child of 100 } }; heap.Insert(200); Assert.AreEqual<int>(200, heap.List[0]); Assert.AreEqual<int>(150, heap.List[1]); Assert.AreEqual<int>(100, heap.List[2]); Assert.AreEqual<int>(50, heap.List[3]); Assert.AreEqual<int>(40, heap.List[4]); Assert.AreEqual<int>(95, heap.List[5]); Assert.AreEqual<int>(90, heap.List[6]); Assert.AreEqual<int>(45, heap.List[7]); }
public void BuildMaxHeap_AllSameNumber() { int[] array = {5, 5, 5, 5, 5, 5}; Heap heap = new Heap(array); Assert.IsTrue(IsMaxHeap(heap.Queue, 0)); }
public void HeapifyDown_SwapLeft() { Heap<int> heap = new Heap<int>(HeapType.Max) { List = new List<int>() { 25, 50, 10 } }; using (ShimsContext.Create()) { int swappedChildIx = int.MinValue; int swappedParentIx = int.MinValue; ShimHeap<int>.AllInstances.SwapInt32Int32 = (h, childIx, parentIx) => { swappedChildIx = childIx; swappedParentIx = parentIx; }; heap.HeapifyDown(); Assert.AreEqual<int>(1, swappedChildIx); Assert.AreEqual<int>(0, swappedParentIx); } }
void FindPath(Vector3 startPos, Vector3 targetPos) { // performs A* search on the grid to find a path startPos = new Vector3(startPos.x + 8.0f, 0, startPos.z - 2.0f); // offsets targetPos = new Vector3(targetPos.x + 8.0f, 0, targetPos.z - 2.0f); // offsets Node startNode = grid.GetNodeFromWorldPoint(startPos); Node targetNode = grid.GetNodeFromWorldPoint(targetPos); if (targetNode.walkable == false) return; // don't try to path find if we're on an unwalkable area Heap<Node> openSet = new Heap<Node>(grid.MaxSize); HashSet<Node> closedSet = new HashSet<Node>(); openSet.Add(startNode); while(openSet.Count > 0) { // we still have nodes Node currentNode = openSet.pop(); closedSet.Add(currentNode); if(currentNode == targetNode) { // we've found exit RetracePath(startNode, targetNode); path = backTrackPath(startNode, targetNode); return; } foreach(Node n in grid.GetNeighbours(currentNode)) { if (!n.walkable || closedSet.Contains(n)) continue; int newMovementCostToNeighbour = currentNode.gCost + GetDistance(currentNode, n); if(newMovementCostToNeighbour < n.gCost || !openSet.contains(n)) { n.gCost = newMovementCostToNeighbour; n.hCost = GetDistance(n, targetNode); n.parent = currentNode; if (!openSet.contains(n)) openSet.Add(n); // add our neighbour into open set else openSet.UpdateItem(n); } } } }
void calc() { Scanner cin = new Scanner(); int n = cin.nextInt(); int[] r = new int[n]; int i, j; Dictionary<int, int> dic = new Dictionary<int, int>(); for (i = 0; i < n; i++) { r[i] = cin.nextInt(); if (!dic.ContainsKey(r[i])) dic[r[i]] = 0; dic[r[i]]++; } if (dic.Count < 3) { Console.WriteLine(0); return; } long MAX = (long)1e10; Heap h = new Heap(0); foreach (var item in dic) { h = meld(h, new Heap(MAX * item.Value + item.Key)); } int[,] ret = new int[n, 3]; int retnum = 0; for (j = 0; ; j++) { long[] num = new long[3]; for (i = 0; i < 3; i++) { num[i] = h.val; h = meld(h.r, h.l); } if (num[2] < MAX) break; int[] nums = new int[3]; for (i = 0; i < 3; i++) { nums[i] = (int)(num[i] % MAX); num[i] -= MAX; } for (i = 0; i < 3; i++) { h = meld(h, new Heap(num[i])); } Array.Sort(nums); Array.Reverse(nums); for (i = 0; i < 3; i++) { ret[j, i] = nums[i]; } retnum++; } Console.WriteLine(retnum); for (i = 0; i < retnum; i++) { Console.WriteLine("{0} {1} {2}", ret[i, 0], ret[i, 1], ret[i, 2]); } }
public void InitHeap() { _heap = new MinHeap<int>(); for (int i = 100; i >0; i--) { _heap.Insert(i); } }
public void BuildMaxHeap_ScrambledArray_Unbalanced() { int[] array = { 39, 58, 31, 56, 38, 70, 43, 69, 8, 2, 5, 6, 9 }; Heap heap = new Heap(array); Assert.IsTrue(IsMaxHeap(heap.Queue, 0)); }
public void ClearTest() { Heap<int> actual = new Heap<int> {12, 3, 21, 0}; actual.Clear(); Assert.AreEqual(0, actual.Count); }
public void Simple() { var heap = new Heap<int>(HeapType.Maximum); Assert.IsFalse(heap.IsReadOnly); heap = GetTestHeap(); Assert.IsFalse(heap.IsReadOnly); }
public AStar(AStarCost aStarCost, int fromX, int fromY, int toX, int toY) { openList = new Heap(); closedList = new Heap(); _solution = new List<AStarNode>(); AStarNode2D goalNode = new AStarNode2D(aStarCost, 0, toX, toY); startNode = new AStarNode2D(aStarCost, 0, fromX, fromY, goalNode); }
public void ExceptionEmpty() { var heap = new Heap<int>(HeapType.Minimum); Assert.AreEqual(heap.Count, 0); heap.RemoveRoot(); }
public void BuildMaxHeap_AlreadyCorrectHeap() { int[] array = { 16, 14, 10, 8, 7, 9, 3}; Heap heap = new Heap(array); Assert.IsTrue(IsMaxHeap(heap.Queue, 0)); }
public PathfindingAlgorithm(Map map) { walkableCellTypes = new List<string>(); _map = map; _world = _map.cellsOnMap; _openList = new Heap<Cell>(); _closedList = new List<Cell>(); }
public void BuildMaxHeap_ScrambledArray_Balance() { int[] array = { 300, 15, 205, 25, 457, 3, 5 }; Heap heap = new Heap(array); Assert.IsTrue(IsMaxHeap(heap.Queue, 0)); }
public void aStar(Vector3 startPos, Vector3 endPos) { Stopwatch watch = new Stopwatch(); watch.Start(); //List<Node_K> openSet = new List<Node_K>(); Heap<Node_K> openSet = new Heap<Node_K>(AIarea.GetMaxSize); HashSet<Node_K> closedSet = new HashSet<Node_K>(); Node_K sourceNode = AIarea.getNodeAtPos(startPos); Node_K targetNode = AIarea.getNodeAtPos(endPos); openSet.Add(sourceNode); while(openSet.Count > 0) { Node_K currentNode = openSet.RemoveFirst(); //Node_K currentNode = openSet[0]; //for (int i = 1; i < openSet.Count; i++) //{ // if (openSet[i].fCost < currentNode.fCost || openSet[i].fCost == currentNode.fCost && openSet[i].hCost < currentNode.hCost) // { // currentNode = openSet[i]; // } //} //openSet.Remove(currentNode); closedSet.Add(currentNode); if(currentNode == targetNode) { reversePath(sourceNode, targetNode); watch.Stop(); time = watch.ElapsedMilliseconds.ToString(); print("Astar " + watch.ElapsedMilliseconds + "ms"); return; } List<Node_K> neighbors = new List<Node_K>(); neighbors = AIarea.neighbors(currentNode); for (int i = 0; i < neighbors.Count; i++) { if (neighbors[i].walkable == false || closedSet.Contains(neighbors[i])) continue; int cost = currentNode.gCost + moveCost(currentNode, neighbors[i]); if (!openSet.Contains(neighbors[i]) || (cost < neighbors[i].gCost)) { neighbors[i].gCost = cost; neighbors[i].hCost = moveCost(neighbors[i], targetNode); neighbors[i].parent = currentNode; if (!openSet.Contains(neighbors[i])) openSet.Add(neighbors[i]); else openSet.UpdateItem(neighbors[i]); } } } }
public string GetStringValue(StackValue val, Heap heap, int langblock, int maxArraySize, int maxOutputDepth, bool forPrint = false) { if (formatParams == null) { formatParams = new OutputFormatParameters(maxArraySize, maxOutputDepth); } if (val.IsInteger) { return(val.IntegerValue.ToString()); } else if (val.IsDouble) { return(val.DoubleValue.ToString("F6")); } else if (val.IsNull) { return("null"); } else if (val.IsPointer) { return(GetClassTrace(val, heap, langblock, forPrint)); } else if (val.IsArray) { HashSet <int> pointers = new HashSet <int> { val.ArrayPointer }; string arrTrace = GetArrayTrace(val, heap, langblock, pointers, forPrint); if (forPrint) { return("{" + arrTrace + "}"); } else { return("{ " + arrTrace + " }"); } } else if (val.IsFunctionPointer) { ProcedureNode procNode; if (runtimeCore.DSExecutable.FuncPointerTable.TryGetFunction(val, runtimeCore, out procNode)) { string className = String.Empty; if (procNode.ClassID != Constants.kGlobalScope) { className = runtimeCore.DSExecutable.classTable.GetTypeName(procNode.ClassID).Split('.').Last() + "."; } return("function: " + className + procNode.Name); } return("function: " + val.FunctionPointer.ToString()); } else if (val.IsBoolean) { return(val.BooleanValue ? "true" : "false"); } else if (val.IsString) { if (forPrint) { return(heap.ToHeapObject <DSString>(val).Value); } else { return("\"" + heap.ToHeapObject <DSString>(val).Value + "\""); } } else if (val.IsChar) { Char character = Convert.ToChar(val.CharValue); if (forPrint) { return(character.ToString()); } else { return("'" + character + "'"); } } else { return("null"); // "Value not yet supported for tracing"; } }
private void HeapSortBtn_Click(object sender, EventArgs e) { var heap = new Heap <SortedItem>(items); BtnClick(heap); }
public HeapTests() { Instance = new Heap <int>(); }
/// <summary> /// Cleans the thread context /// </summary> public void Cleanup() { Heap.Free(m_FPUContext); Heap.Free(m_kernelStackStart); }
List <Vector2> FindPath(Vector3 _startPos, Vector3 _targetPos) { Stopwatch sw = new Stopwatch(); sw.Start(); //new empty list of vector2 that will be filled with path waypoints List <Vector2> waypoints = new List <Vector2>(); bool pathFound = false; //Get start and goal nodes Node start = grid.NodeFromWorldCoord(_startPos); Node target = grid.NodeFromWorldCoord(_targetPos); //check for a path only if start and end nodes are driveable if (start.driveable != 2 && target.driveable != 2) { //create an empty heap of nodes of grid size that will be used for searching the path Heap <Node> openSet = new Heap <Node>(grid.GetMaxSize); //create a closed hash set that consists of already checked nodes HashSet <Node> closedSet = new HashSet <Node>(); openSet.Add(start); //add start node to open set //while there are still nodes in the open set while (openSet.Count > 0) { Node currentNode = openSet.RemoveFirst(); //remove first node (lowest f score) from the open set and set it as current closedSet.Add(currentNode); //add current node to the closed set if (currentNode == target) //if current node equals the goal node then path is found { sw.Stop(); print("Path found: " + sw.ElapsedMilliseconds + " ms"); pathFound = true; break; } foreach (Node neighbour in grid.GetNeighbours(currentNode)) //for each neighbour of the current node { if (neighbour.driveable == 2 || closedSet.Contains(neighbour)) //find whether neighbour is not driveable or alrady in the closed set { continue; } int movementCost = currentNode.gCost + GetDistance(currentNode, neighbour); //calculate movement cost to neighbour node //if movement cost to neighbour is lower than neighbour g cost or openset does not contain neighbour (gCost == 0) then... if (movementCost < neighbour.gCost || !openSet.Contains(neighbour)) { bool thinPath = false; if (neighbour.driveable == 1) //if neighbour being checked is semi-driveable then check whether it can be a part of thin passage { thinPath = grid.CalculateThinPath(currentNode, neighbour); } if (neighbour.driveable == 0 || thinPath == true) //if neighbour is driveable or a part of thin passage way then add and sort it { neighbour.gCost = movementCost; //current neighbour g cost equals previously calculated g cost neighbour.hCost = GetDistance(neighbour, target); //h cost equals calculated distance (node amount) between goal and neighbour neighbour.parent = currentNode; //parent of neighbour equals current node if (!openSet.Contains(neighbour)) //if neighbour is not in the open set then add it to open set { openSet.Add(neighbour); } else //if it is in open set then sort heap nodes { openSet.UpdateItem(neighbour); //sort up items in the heap based on their f score, so that the item with lowest f score will be checked first } } else { continue; } } } } } if (pathFound) //retrace waypoints back to the start with the use of parent nodes { waypoints = Retrace(start, target); } return(waypoints); //return simplified path }
// returns true if the path ends at the goal, flase if a partial path. Stores the path in the global path variable public bool decidePath(bool prof) { // Reset the nodelists Vector2 goal = new Vector2(destx, desty); pathing = true; nodelist = new Heap <Node>(searchnodes); closed = new HashSet <Vector2> (); // add the current position at time and cost 0 to openlist nodelist.Add(new Node(0, currentx, currenty, 0, 0)); Node end = null; while (nodelist.Count > 0) { // Gets the node with the best cost from the heap Node n = nodelist.RemoveFirst(); timecounter = n.time; // ignores this node if it is swapping positions with another one (the turn before they were in each other's positions) if (timecounter >= 1) { if (timecounter < game.timeslices) { if (game.grids [timecounter - 1].getgrid((int)n.index.x, (int)n.index.y) >= 3) { int num = game.grids [timecounter - 1].getgrid((int)n.index.x, (int)n.index.y); Node p = n.parent; if (num == game.grids [timecounter].getgrid((int)p.index.x, (int)p.index.y)) { continue; } } } } // If a student is idling the node space, ignore this node if (game.blocked [(int)n.index.x, (int)n.index.y] >= timecounter + 1) { continue; } // nodes is travelled closed.Add(n.index); // get valid children for this node ArrayList children = getChildren(n, prof); foreach (Node child in children) { try { nodelist.Add(child); } catch (System.Exception e) { // This occurs when the algorithm has searched through too many nodes (probably means no path to goal exists) foreach (Node tempnode in nodelist.items) { // checks for best end node if (tempnode.time == n.time && getDist(tempnode.index, new Vector2(destx, desty)) <= getDist(n.index, new Vector2(destx, desty))) { n = tempnode; } } end = n; break; } } // get the goal node if found if (checkGoal(n, goal)) { end = n; break; } // get the next best node if not end = n; } // follow the tree from goal leaf to root and set the path path = new List <Vector2>(); path.Insert(path.Count, end.index); Node curr = end; while ((curr = curr.parent) != null) { path.Insert(0, curr.index); } // add a second goal node path.Add(path [path.Count - 1]); // if bigger than the timing window, cut the path off to be the size of the timing window if (path.Count >= game.timeslices) { path = path.GetRange(0, game.timeslices); } // If second goal was not cut off if (path [path.Count - 1] == goal && path[path.Count - 2] == goal) { // change goal for professor to spot in front of them if (prof) { path.RemoveAt(path.Count - 1); path.RemoveAt(path.Count - 1); path.Add(path[path.Count - 1]); } // for each timing window on the map, set the reservation for the path for (int i = 0; i < path.Count; i++) { game.grids [i].add((int)path[i].x, (int)path[i].y, label); } return(true); } // for each timing window on the map, set the reservation for the path for (int i = 0; i < path.Count; i++) { game.grids [i].add((int)path[i].x, (int)path[i].y, label); } return(false); }
public byte *NewBlockArray(ulong aBlockCount) { return((byte *)Heap.alloc((uint)(aBlockCount * BlockSize))); }
public AIenumertor(Heap <T> inst) { this.instance = inst; }
IEnumerator FindPath(Vector3 startPos, Vector3 targetPos, bool noticeOccupied) { Vector3[] waypoints = new Vector3[0]; bool pathSuccess = false; Node startNode = grid.NodeFromWorldPoint(startPos); Node targetNode = grid.NodeFromWorldPoint(targetPos); bool abortPF = false; if (!targetNode.walkable) { Node[] neighbours = grid.GetNeighbours(targetNode); for (int i = 0; i < neighbours.Length; ++i) { if (neighbours[i] == null) { continue; } else if (neighbours[i].walkable) { abortPF = false; targetNode = neighbours[i]; break; } abortPF = true; } } Heap <Node> openSet = new Heap <Node>(grid.MaxSize); HashSet <Node> closedSet = new HashSet <Node>(); openSet.Add(startNode); int nodeCount = -1; while (openSet.Count > 0) { ++nodeCount; if (nodeCount > maximumNodes) { break; } else if (abortPF) { break; } Node currentNode = openSet.RemoveFirst(); closedSet.Add(currentNode); if (currentNode == targetNode) { pathSuccess = true; break; } Node[] neighbours = grid.GetNeighbours(currentNode); for (int i = 0; i < neighbours.Length; ++i) { if (neighbours[i] == null) { continue; } if (!neighbours[i].walkable || closedSet.Contains(neighbours[i])) { continue; } if (noticeOccupied && neighbours[i].occupied) { continue; } int newMovementCostToNeighbour = currentNode.gCost + GetDistance(currentNode, neighbours[i]); if (newMovementCostToNeighbour < neighbours[i].gCost || !openSet.Contains(neighbours[i])) { neighbours[i].gCost = newMovementCostToNeighbour; neighbours[i].hCost = GetDistance(neighbours[i], targetNode); neighbours[i].parent = currentNode; if (!openSet.Contains(neighbours[i])) { openSet.Add(neighbours[i]); } } } } yield return(null); if (pathSuccess) { waypoints = RetracePath(startNode, targetNode, noticeOccupied); requestManager.FinishedProcessingPath(waypoints, pathSuccess); } else { requestManager.FinishedProcessingPath(waypoints, pathSuccess); } }
internal static void Start(uint magic, uint address, uint KernelDirectory, uint InitialHeap) { /* Kernel Logger init */ Debug.Init(); /* Initalize Heap */ Heap.Init(InitialHeap); /* Multiboot Info Parsing */ Multiboot.Setup(magic, address); /* Setup Paging */ Paging.Setup(KernelDirectory); /* Setup GDT */ GDT.Setup(); /* Remap PIC */ PIC.Setup(); /* Setup IDT */ IDT.Setup(); /* Enable Interrupt */ Native.Sti(); /* Setup Scheduler */ Scheduler.Init(KernelDirectory); /* Setup System Timer */ Timer.Setup(); /* Install SHM */ SHM.Install(); /* Initialise VBE 2.0 Driver */ VBE.Init(); /* Initialise Virtual File system */ VirtualFileSystem.Setup(); /* Setup Syscall */ Syscall.Setup(); /* Initialise C library */ Libc.Init(); try { Boot.Init(); } catch (Exception e) { Debug.Write("[@SystemThread] => [EXIT]: %s\n", e.Message); } while (true) { ; } }
/// <summary> /// FindPath With Threading Support /// </summary> /// <param name="grid"></param> /// <param name="request"></param> /// <param name="callback"></param> public static void FindPath(this Tilemap grid, PathRequest request, Action <PathResult> callback) { Vector3[] wayPoints = new Vector3[0]; bool bPathFound = false; Tile startTile = grid.GetTileFromWorldPosition(request.startPosition); Tile targetTile = grid.GetTileFromWorldPosition(request.endPosition); //TODO : Add startTile is Walkable //if (targetTile.walkable) if (targetTile.walkable && GridUtility.GetDistanceBetweenTiles(startTile, targetTile) <= request.agent.range && grid.IsTileWalkableByAgent(targetTile, request.agent)) { Heap <Tile> openSet = new Heap <Tile>(grid.Columns * grid.Rows); HashSet <Tile> closedSet = new HashSet <Tile>(); int newMovementCost, tempDistance; //Add the Start Tile to the Open Set openSet.Add(startTile); while (openSet.Count > 0) { Tile currentTile = openSet.RemoveFirst(); closedSet.Add(currentTile); if (currentTile == targetTile) { bPathFound = true; break; } List <Tile> neighbours = grid.GetNeighbouringTiles(currentTile); foreach (var neighbourTile in neighbours) { //if (!neighbourTile.walkable || closedSet.Contains(neighbourTile)) if (!grid.IsTileWalkableByAgent(neighbourTile, request.agent) || closedSet.Contains(neighbourTile)) { continue; } //TODO: Incase of Agents that Span multiple Tiles, //Instead of adding neighbourTile.penalty, add the average of penalties of tiles that the Agent Spans tempDistance = GridUtility.GetDistanceBetweenTiles(currentTile, neighbourTile) + neighbourTile.penalty; newMovementCost = currentTile.gCost + tempDistance; if (newMovementCost < neighbourTile.gCost || !openSet.Contains(neighbourTile)) { neighbourTile.gCost = newMovementCost; neighbourTile.hCost = GridUtility.GetDistanceBetweenTiles(neighbourTile, targetTile); neighbourTile.parent = currentTile; if (!openSet.Contains(neighbourTile)) { openSet.Add(neighbourTile); } else { openSet.Update(neighbourTile); } } } } int distanceCovered = 0; if (bPathFound) { wayPoints = RetracePath(startTile, targetTile, out distanceCovered); bPathFound = wayPoints.Length > 0 && distanceCovered <= request.agent.range; } callback(new PathResult(wayPoints, distanceCovered, bPathFound, request.callback)); } }
public void FindPath(PathRequest request, Action <PathResult> callback) { Stopwatch sw = new Stopwatch(); sw.Start(); Vector3[] waypoints = new Vector3[0]; bool pathSuccess = false; Node startNode = grid.NodeFromWorldPoint(request.pathStart); Node targetNode = grid.NodeFromWorldPoint(request.pathEnd); if (startNode.walkable && targetNode.walkable) { Heap <Node> openSet = new Heap <Node>(grid.MaxSize); HashSet <Node> closedSet = new HashSet <Node>(); openSet.Add(startNode); while (openSet.Count() > 0) { Node currentNode = openSet.RemoveFirst(); closedSet.Add(currentNode); if (currentNode == targetNode) { sw.Stop(); print("Path found in " + sw.ElapsedMilliseconds + " ms."); pathSuccess = true; break; } foreach (Node neighbor in grid.GetNeighbors(currentNode)) { if (!neighbor.walkable || closedSet.Contains(neighbor)) { continue; } int newMovementCostToNeighbor = currentNode.gCost + GetDistance(currentNode, neighbor) + neighbor.movementPenalty; if (newMovementCostToNeighbor < neighbor.gCost || !openSet.Contains(neighbor)) { neighbor.gCost = newMovementCostToNeighbor; neighbor.hCost = GetDistance(neighbor, targetNode); neighbor.parent = currentNode; if (!openSet.Contains(neighbor)) { openSet.Add(neighbor); } else { openSet.UpdateItem(neighbor); } } } } } if (pathSuccess) { waypoints = RetracePath(startNode, targetNode); pathSuccess = waypoints.Length > 0; } callback(new PathResult(waypoints, pathSuccess, request.callback)); }
IEnumerator FindPath(Vector3 starPosition, Vector3 targetPosition) { Vector3[] waypoints = new Vector3[0]; bool pathSuccess = false; Node startNode = grid.NodeFromWorldPoint(starPosition); Node targetNode = grid.NodeFromWorldPoint(targetPosition); if (startNode.walkable && targetNode.walkable) { Heap <Node> openSet = new Heap <Node>(grid.MaxSize); HashSet <Node> closedSet = new HashSet <Node>(); openSet.Add(startNode); while (openSet.Count > 0) { Node currentNode = openSet.RemoveFirst(); closedSet.Add(currentNode); if (currentNode == targetNode) { pathSuccess = true; break; } foreach (Node neighbour in grid.GetNeighbours(currentNode)) { if (!neighbour.walkable || closedSet.Contains(neighbour)) { continue; } int newMovementCostToNeighbour = currentNode.gCost + GetDistance(currentNode, neighbour); if (newMovementCostToNeighbour < neighbour.gCost || !openSet.Contains(neighbour)) { neighbour.gCost = newMovementCostToNeighbour; neighbour.hCost = GetDistance(neighbour, targetNode); neighbour.parent = currentNode; if (!openSet.Contains(neighbour)) { openSet.Add(neighbour); } else { openSet.UpdateItem(neighbour); } } } } } yield return(null); if (pathSuccess) { waypoints = RetracePath(startNode, targetNode); } pathRequestManager.FinishedProcessingPath(waypoints, pathSuccess); }
public TwoPassCounters(int k, Double p) : base(k, p) { _examples = new Heap <Info>((info1, info2) => info1.Score > info2.Score); }
//@TODO(Luke): Add in the methods here that correspond to each of the internal datastructures in use by the executive //@TODO(Jun): if this method stays static, then the Heap needs to be referenced from a parameter /// <summary> /// Do the recursive unpacking of the data structure into mirror objects /// </summary> /// <param name="val"></param> /// <returns></returns> public static Obj Unpack(StackValue val, Heap heap, RuntimeCore runtimeCore, int type = (int)PrimitiveType.Pointer) { Executable exe = runtimeCore.DSExecutable; switch (val.optype) { case AddressType.ArrayPointer: { DsasmArray ret = new DsasmArray(); //Pull the item out of the heap var array = heap.ToHeapObject <DSArray>(val); StackValue[] nodes = array.Values.ToArray(); ret.members = new Obj[array.Count]; for (int i = 0; i < ret.members.Length; i++) { ret.members[i] = Unpack(nodes[i], heap, runtimeCore, type); } // TODO Jun: ret.members[0] is hardcoded and means we are assuming a homogenous collection // How to handle mixed-type arrays? Obj retO = new Obj(val) { Payload = ret, }; return(retO); } case AddressType.String: { string str = heap.ToHeapObject <DSString>(val).Value; Obj o = new Obj(val) { Payload = str, }; return(o); } case AddressType.Int: { Obj o = new Obj(val) { Payload = val.IntegerValue, }; return(o); } case AddressType.Boolean: { Obj o = new Obj(val) { Payload = val.BooleanValue, }; return(o); } case AddressType.Null: { Obj o = new Obj(val) { Payload = null, }; return(o); } case AddressType.Char: { Obj o = new Obj(val) { Payload = val.CharValue, }; return(o); } case AddressType.Double: { Obj o = new Obj(val) { Payload = val.DoubleValue, }; return(o); } case AddressType.Pointer: { Obj o = new Obj(val) { Payload = val.Pointer, }; return(o); } case AddressType.FunctionPointer: { Obj o = new Obj(val) { Payload = val.FunctionPointer, }; return(o); } case AddressType.Invalid: { return(new Obj(val) { Payload = null }); } default: { throw new NotImplementedException(string.Format("unknown datatype {0}", val.optype.ToString())); } } }
public static List <HexCell> FindPath(HexCoordinates startPos, HexCoordinates targetPos, bool canWaterTravel, bool canLandTravel, int tilesPerTurn, Civilization unitCiv, bool isMilitary) //A* Algorithm { //Debug.Log(targetPos.ToString()); HexCell startNode = grid.cells[startPos.X, startPos.Z]; HexCell targetNode = grid.cells[targetPos.X, targetPos.Z]; Heap <HexCell> openSet = new Heap <HexCell>(grid.MaxSize); HashSet <HexCell> closedSet = new HashSet <HexCell>(); openSet.Add(startNode); while (openSet.Count > 0) { HexCell currentNode = openSet.RemoveFirst(); closedSet.Add(currentNode); if (currentNode == targetNode) { List <HexCell> path = RetracePath(startNode, targetNode); return(path); } foreach (HexCoordinates neighbourCoords in (HexCoordinates.GetNeighbours(currentNode.coordinates))) { //Debug.Log("Neighbour: " + neighbourCoords.ToString()); HexCoordinates neighbourOffsetCoords = (HexCoordinates.ToOffsetCoordinates(neighbourCoords)); //Debug.Log(neighbourCoords.ToString() + " ==> " + neighbourOffsetCoords.ToString()); if (neighbourOffsetCoords.Z >= grid.height || neighbourOffsetCoords.Z < 0) { continue; } int xOffset = neighbourOffsetCoords.X; if (xOffset >= grid.width) { xOffset -= grid.width; } else if (xOffset < 0) { xOffset += grid.width; } HexCell neighbour = grid.cells[xOffset, neighbourOffsetCoords.Z]; if (((!canWaterTravel && neighbour.Type.isWater || !canLandTravel && !neighbour.Type.isWater) && !(neighbour.Type == HexType.types[HexType.typeKeys.city])) || (neighbour.unitCiv != null && neighbour.unitCiv != unitCiv) || (isMilitary && neighbour.militaryUnit != null) || (!isMilitary && neighbour.passiveUnit != null) || closedSet.Contains(neighbour)) { continue; } float newMovementCost = currentNode.gCost + neighbour.Type.movementCost; if (currentNode.Type.isWater != neighbour.Type.isWater) { newMovementCost += tilesPerTurn - (newMovementCost % tilesPerTurn); //End turn when crossing to land from water or vice versa } if (newMovementCost < neighbour.gCost || !openSet.Contains(neighbour)) { neighbour.gCost = newMovementCost; neighbour.hCost = GetDistance(neighbour.coordinates, targetPos); neighbour.parent = currentNode; if (!openSet.Contains(neighbour)) { openSet.Add(neighbour); } else { openSet.UpdateItem(neighbour); } } } } return(null); //If no path found }
IEnumerator FindPath(Vector3 startPos, Vector3 targetPos) { Vector3[] waypoints = new Vector3[0]; bool pathSuccess = false; Node startNode = grid.NodeFromWorldPoint(startPos); Node targetNode = grid.NodeFromWorldPoint(targetPos); if (!targetNode.walkable) { List <Node> neighbours = new List <Node>(); neighbours = grid.GetNeighbours(targetNode); foreach (Node n in neighbours) { if (n.walkable) { targetNode = n; break; } } if (!targetNode.walkable) { Debug.Log("couldn't find walkable target node"); } } if (!startNode.walkable) { List <Node> neighbours = new List <Node>(); neighbours = grid.GetNeighbours(startNode); foreach (Node n in neighbours) { if (n.walkable) { startNode = n; break; } } if (!startNode.walkable) { Debug.Log("couldn't find walkable start node"); } } if (startNode.walkable && targetNode.walkable) { Heap <Node> openSet = new Heap <Node>(grid.MaxSize); HashSet <Node> closedSet = new HashSet <Node>(); openSet.Add(startNode); while (openSet.Count > 0) { Node node = openSet.RemoveFirst(); //start with first node of the open set closedSet.Add(node); // add the node with the lowest f cost to the closed set if (node == targetNode) { pathSuccess = true; break; } foreach (Node neighbour in grid.GetNeighbours(node)) //explore the neighbours of the node and if not added to open set add with their specific costs { if (!neighbour.walkable || closedSet.Contains(neighbour)) { continue; } int newCostToNeighbour = node.gCost + GetDistance(node, neighbour); if (newCostToNeighbour < neighbour.gCost || !openSet.Contains(neighbour)) { neighbour.gCost = newCostToNeighbour; neighbour.hCost = GetDistance(neighbour, targetNode); neighbour.parent = node; if (!openSet.Contains(neighbour)) { openSet.Add(neighbour); } else { openSet.UpdateItem(neighbour); } } } } } yield return(null); if (pathSuccess) { waypoints = RetracePath(startNode, targetNode); } requestManager.FinishedProcessingPath(waypoints, pathSuccess); }
public string GetStringValue(StackValue val, Heap heap, int langblock, bool forPrint = false) { return(GetStringValue(val, heap, langblock, -1, -1, forPrint)); }
public virtual void Link(Heap heap) { this.heap = heap; View(heap.Image(), heap.Glowing()); Place(heap.Pos); }
private string GetArrayTrace(StackValue svArray, Heap heap, int langblock, HashSet <int> pointers, bool forPrint) { if (!formatParams.ContinueOutputTrace()) { return("..."); } StringBuilder arrayElements = new StringBuilder(); var array = heap.ToHeapObject <DSArray>(svArray); int halfArraySize = -1; if (formatParams.MaxArraySize > 0) // If the caller did specify a max value... { // And our array is larger than that max value... if (array.Count > formatParams.MaxArraySize) { halfArraySize = (int)Math.Floor(formatParams.MaxArraySize * 0.5); } } int totalElementCount = array.Count; if (svArray.IsArray) { totalElementCount = heap.ToHeapObject <DSArray>(svArray).Values.Count(); } for (int n = 0; n < array.Count; ++n) { // As we try to output the next element in the array, there // should be a comma if there were previously output element. if (arrayElements.Length > 0) { if (forPrint) { arrayElements.Append(","); } else { arrayElements.Append(", "); } } StackValue sv = array.GetValueFromIndex(n, runtimeCore); if (sv.IsArray) { arrayElements.Append(GetPointerTrace(sv, heap, langblock, pointers, forPrint)); } else { arrayElements.Append(GetStringValue(array.GetValueFromIndex(n, runtimeCore), heap, langblock, forPrint)); } // If we need to truncate this array (halfArraySize > 0), and we have // already reached the first half of it, then offset the loop counter // to the next half of the array. if (halfArraySize > 0 && (n == halfArraySize - 1)) { arrayElements.Append(", ..."); n = totalElementCount - halfArraySize - 1; } } formatParams.RestoreOutputTraceDepth(); return(arrayElements.ToString()); }
public static List <Node> GetPath(Node startNode, Node targetNode) { if (startNode == targetNode) { return(new List <Node>()); } if (startNode.Region != targetNode.Region) { return(null); } List <Subregion> subregions = AStarSubregionSearch.GetPath(startNode.subregion, targetNode.subregion); Node[] possibleNodes = new Node[Pathfinder.MapWidth * Pathfinder.MapHeight]; foreach (Subregion s in subregions) { foreach (Node n in s.nodes) { possibleNodes[n.X + n.Y * Pathfinder.MapHeight] = n; } } Heap <Node> openSet = new Heap <Node>(Pathfinder.MapWidth * Pathfinder.MapHeight); HashSet <Node> closedSet = new HashSet <Node>(); openSet.Add(startNode); while (openSet.Count > 0) { Node currentNode = openSet.RemoveFirst(); closedSet.Add(currentNode); HandleAddToClosedSet?.Invoke(currentNode); if (currentNode == targetNode) { var path = RetracePath(startNode, targetNode); return(path); } foreach (var neighbour in GetNeighbours(currentNode)) { if (closedSet.Contains(neighbour) || possibleNodes[neighbour.X + neighbour.Y * Pathfinder.MapHeight] == null) { continue; } int newCostToNeighbour = currentNode.gCost + GetDistance(currentNode, neighbour); if (openSet.Contains(neighbour)) { if (newCostToNeighbour < neighbour.gCost) { neighbour.gCost = newCostToNeighbour; neighbour.hCost = Heuristic(neighbour, targetNode); neighbour.rCost = 0; neighbour.parent = currentNode; openSet.UpdateItem(neighbour); } } else { neighbour.gCost = newCostToNeighbour; neighbour.hCost = Heuristic(neighbour, targetNode); neighbour.rCost = 0; neighbour.parent = currentNode; openSet.Add(neighbour); } } } return(null); }
public string GetClassTrace(StackValue val, Heap heap, int langblock, bool forPrint) { if (!formatParams.ContinueOutputTrace()) { return("..."); } RuntimeMemory rmem = MirrorTarget.rmem; Executable exe = MirrorTarget.exe; ClassTable classTable = MirrorTarget.RuntimeCore.DSExecutable.classTable; int classtype = val.metaData.type; if (classtype < 0 || (classtype >= classTable.ClassNodes.Count)) { formatParams.RestoreOutputTraceDepth(); return(string.Empty); } ClassNode classnode = classTable.ClassNodes[classtype]; if (classnode.IsImportedClass) { var helper = DLLFFIHandler.GetModuleHelper(FFILanguage.CSharp); var marshaller = helper.GetMarshaler(runtimeCore); var strRep = marshaller.GetStringValue(val); formatParams.RestoreOutputTraceDepth(); return(strRep); } else { var obj = heap.ToHeapObject <DSObject>(val); StringBuilder classtrace = new StringBuilder(); if (classnode.Symbols != null && classnode.Symbols.symbolList.Count > 0) { if (!classnode.Name.Equals("Function")) { bool firstPropertyDisplayed = false; for (int n = 0; n < obj.Count; ++n) { SymbolNode symbol = classnode.Symbols.symbolList[n]; string propName = symbol.name; if (firstPropertyDisplayed) { classtrace.Append(", "); } string propValue = ""; if (symbol.isStatic) { var staticSymbol = exe.runtimeSymbols[langblock].symbolList[symbol.symbolTableIndex]; StackValue staticProp = rmem.GetSymbolValue(staticSymbol); propValue = GetStringValue(staticProp, heap, langblock, forPrint); } else { propValue = GetStringValue(obj.GetValueFromIndex(symbol.index, runtimeCore), heap, langblock, forPrint); } classtrace.Append(string.Format("{0} = {1}", propName, propValue)); firstPropertyDisplayed = true; } } } else { var stringValues = obj.Values.Select(x => GetStringValue(x, heap, langblock, forPrint)) .ToList(); for (int n = 0; n < stringValues.Count(); ++n) { if (0 != n) { classtrace.Append(", "); } classtrace.Append(stringValues[n]); } } formatParams.RestoreOutputTraceDepth(); if (classtype >= (int)ProtoCore.PrimitiveType.MaxPrimitive) { if (forPrint) { return(string.Format("{0}{{{1}}}", classnode.Name, classtrace.ToString())); } else { string tempstr = (string.Format("{0}({1})", classnode.Name, classtrace.ToString())); return(tempstr); } } return(classtrace.ToString()); } }
public void FindPath(PathRequest request, Action <PathResult> callback) { if (gv.playing) { Node startNode = grid.NodeFromWorldPoint(request.pathStart); Node targetNode = grid.NodeFromWorldPoint(request.pathEnd); Vector3[] waypoints = new Vector3[0]; bool pathSuccess = false; startNode.parent = startNode; if (startNode.isWalkable && targetNode.isWalkable) { Heap <Node> openSet = new Heap <Node>(grid.BoxSize); HashSet <Node> closedSet = new HashSet <Node>(); openSet.Add(startNode); while (openSet.Count > 0) { Node currentNode = openSet.RemoveFirst(); closedSet.Add(currentNode); if (currentNode == targetNode) { pathSuccess = true; break; } foreach (Node n in grid.GetNeighbors(currentNode)) { if (!n.isWalkable || closedSet.Contains(n)) { continue; } int newCost = currentNode.GCost + DistanceOfNodes(currentNode, n); if (newCost < n.GCost || !openSet.Contains(n)) { n.GCost = newCost; n.HCost = DistanceOfNodes(n, targetNode); n.parent = currentNode; if (!openSet.Contains(n)) { openSet.Add(n); } else { openSet.UpdateItem(n); } } } } } if (pathSuccess) { waypoints = RetracePath(startNode, targetNode); pathSuccess = waypoints.Length > 0; } callback(new PathResult(waypoints, pathSuccess, request.callback)); } }
Vector2[] FindPath(Vector2 from, Vector2 to) { Stopwatch sw = new Stopwatch(); sw.Start(); Vector2[] waypoints = new Vector2[0]; bool pathSuccess = false; Node startNode = grid.NodeFromWorldPoint(from); Node targetNode = grid.NodeFromWorldPoint(to); startNode.parent = startNode; if (startNode.walkable && targetNode.walkable) { Heap <Node> openSet = new Heap <Node>(grid.MaxSize); HashSet <Node> closedSet = new HashSet <Node>(); openSet.Add(startNode); while (openSet.Count > 0) { Node currentNode = openSet.RemoveFirst(); closedSet.Add(currentNode); if (currentNode == targetNode) { sw.Stop(); print("Path found: " + sw.ElapsedMilliseconds + " ms"); pathSuccess = true; break; } foreach (Node neighbour in grid.GetNeighbours(currentNode)) { if (!neighbour.walkable || closedSet.Contains(neighbour)) { continue; } int newMovementCostToNeighbour = currentNode.gCost + GetDistance(currentNode, neighbour) + TurningCost(currentNode, neighbour); if (newMovementCostToNeighbour < neighbour.gCost || !openSet.Contains(neighbour)) { neighbour.gCost = newMovementCostToNeighbour; neighbour.hCost = GetDistance(neighbour, targetNode); neighbour.parent = currentNode; if (!openSet.Contains(neighbour)) { openSet.Add(neighbour); } else { openSet.UpdateItem(neighbour); } } } } } if (pathSuccess) { waypoints = RetracePath(startNode, targetNode); } return(waypoints); }
IEnumerator FindPath(Vector3 startPos, Vector3 targetPos) { Vector3[] waypoints = new Vector3[0]; bool pathSuccess = false; // Get their actual position Nodes startNode = grid.NodeFromWorldPoint(startPos); Nodes targetNode = grid.NodeFromWorldPoint(targetPos); if (!startNode.walkable) { print("Will fail because the start node is on an unwalkable node"); float lowest = 90000000000000; Nodes newStart = startNode; foreach (Nodes neighbour in grid.getNeighbors(startNode, true)) { if (!neighbour.walkable) { continue; } float dist = Vector3.Distance(neighbour.worldPosition, targetPos); if (lowest > dist) { newStart = neighbour; lowest = dist; } } startNode = newStart; if (!startNode.walkable) { Debug.Log("We've failed boiz"); } } if (!targetNode.walkable) { print("Will fail because the target is on an unwalkable node"); float lowest = 90000000000000; Nodes newEnd = targetNode; foreach (Nodes neighbour in grid.getNeighbors(targetNode, true)) { if (!neighbour.walkable) { continue; } float dist = Vector3.Distance(neighbour.worldPosition, startPos); if (lowest > dist) { newEnd = neighbour; lowest = dist; } } targetNode = newEnd; if (!startNode.walkable) { Debug.Log("We've failed (end) boiz"); } } if (startNode.walkable && targetNode.walkable) { // Start the process // We'll be using lists Heap <Nodes> openSet = new Heap <Nodes>(grid.MaxSize); HashSet <Nodes> closedSet = new HashSet <Nodes>(); // Start at the start openSet.Add(startNode); while (openSet.Count > 0) { // Find the node in the open set with the lowest fCost Nodes currentNode = openSet.RemoveFirst(); closedSet.Add(currentNode); // Have we found the exit yet? if (currentNode == targetNode) { pathSuccess = true; break; } // Start comparing foreach (Nodes neighbour in grid.getNeighbors(currentNode, true)) { // if the neighbor isn't walkable or is already in the closed set then ignore it if (!neighbour.walkable || closedSet.Contains(neighbour)) { continue; } int newMovementCostToNeighbour = currentNode.gCost + GetDistance(currentNode, neighbour); // if the new movement cost is less then the cost to actually move towards the exit or if the open set dooesn't already have the neighbor if (newMovementCostToNeighbour < neighbour.gCost || !openSet.Contains(neighbour)) { // Add the neighbor neighbour.gCost = newMovementCostToNeighbour; neighbour.hCost = GetDistance(neighbour, targetNode); neighbour.parent = currentNode; if (!openSet.Contains(neighbour)) { openSet.Add(neighbour); } else { openSet.UpdateItem(neighbour); } } } } } yield return(null); if (pathSuccess) { waypoints = RetracePath(startNode, targetNode); } requestManager.FinishedProcessingPath(waypoints, pathSuccess); }
public IEnumerator FindPath(Vector3 startPosition, Vector3 targetPosition) { Stopwatch sw = new Stopwatch(); sw.Start(); Vector3[] waypoints = new Vector3[0]; bool success = false; Node startNode = grid.GetNodeFromWorldPoint(startPosition); Node targetNode = grid.GetNodeFromWorldPoint(targetPosition); if (startNode.walkable && targetNode.walkable) { Heap <Node> openSet = new Heap <Node>(grid.MaxSize); HashSet <Node> cloasedSet = new HashSet <Node>(); openSet.Add(startNode); while (openSet.Count > 0) { Node currentNode = openSet.RemoveFirst(); cloasedSet.Add(currentNode); if (currentNode == targetNode) { sw.Stop(); print("Path found: " + sw.ElapsedMilliseconds + " ms"); success = true; break; } foreach (Node neighbor in grid.GetNeighbors(currentNode)) { if (!neighbor.walkable || cloasedSet.Contains(neighbor)) { continue; } int newMovementCostToNeighbor = currentNode.gCost + GetDistance(currentNode, neighbor); if (newMovementCostToNeighbor < neighbor.gCost || !openSet.Contains(neighbor)) { neighbor.gCost = newMovementCostToNeighbor; neighbor.hCost = GetDistance(neighbor, targetNode); neighbor.parent = currentNode; if (!openSet.Contains(neighbor)) { openSet.Add(neighbor); } } } } } yield return(null); if (success) { waypoints = RetracePath(startNode, targetNode); } requestManager.FinishedProcessingPath(waypoints, success); }
public List <GridTile> FindPath(GridTile startPosition, GridTile targetPosition) { _pathFound = false; GridTile startTile = startPosition; GridTile targetTile = targetPosition; if (startTile != null && targetTile != null) { _openSet = new Heap <GridTile>(_levelTiles.Count); _closedSet = new Heap <GridTile>(_levelTiles.Count); _openSet.AddItem(startTile); while (_openSet.Count > 0) { GridTile currentTile = _openSet.RemoveFirstItem(); _closedSet.AddItem(currentTile); if (currentTile == targetTile) { _pathFound = true; break; } foreach (GridTile neighbour in GetNeighbourTiles(currentTile)) { if (_closedSet.Contains(neighbour)) { continue; } if (neighbour.Walkable == false || (neighbour.IsLocked == true && neighbour != targetTile)) { _closedSet.AddItem(neighbour); continue; } int newMovementCostToNeighbour = currentTile.GCost + GetDistance(currentTile, neighbour); if (newMovementCostToNeighbour < neighbour.GCost || !_openSet.Contains(neighbour)) { neighbour.GCost = newMovementCostToNeighbour; neighbour.HCost = GetDistance(neighbour, targetTile); neighbour.Parent = currentTile; if (!_openSet.Contains(neighbour)) { _openSet.AddItem(neighbour); } else { _openSet.UpdateItem(neighbour); } } } } } if (_pathFound) { _waypoints = RetracePath(startTile, targetTile); return(_waypoints); } return(new List <GridTile>()); }
//Pathfinding function- finds paths and attempts to move between walkable nodes and to add them to the closed list public void FindPath(PathRequest request, Action <PathResult> callback) { Stopwatch sw = new Stopwatch(); sw.Start(); Vector3[] waypoints = new Vector3[0]; bool pathSuccess = false; Node startNode = grid.NodeFromWorldPoint(request.pathStart); Node targetNode = grid.NodeFromWorldPoint(request.pathEnd); startNode.parent = startNode; if (startNode.walkable && targetNode.walkable) { Heap <Node> openSet = new Heap <Node>(grid.MaxSize); HashSet <Node> closedSet = new HashSet <Node>(); openSet.Add(startNode); while (openSet.Count > 0) { Node currentNode = openSet.RemoveFirst(); closedSet.Add(currentNode); if (currentNode == targetNode) { sw.Stop(); pathSuccess = true; break; } //checking if neighbouring node are walkabe foreach (Node neighbour in grid.GetNeighbours(currentNode)) { if (!neighbour.walkable || closedSet.Contains(neighbour)) { continue; } //calculating distance and movement penalties int newMovementCostToNeighbour = currentNode.gCost + GetDistance(currentNode, neighbour) + neighbour.movementPenalty; if (newMovementCostToNeighbour < neighbour.gCost || !openSet.Contains(neighbour)) { neighbour.gCost = newMovementCostToNeighbour; neighbour.hCost = GetDistance(neighbour, targetNode); neighbour.parent = currentNode; if (!openSet.Contains(neighbour)) { openSet.Add(neighbour); } else { openSet.UpdateItem(neighbour); } } } } } //if the path is successful retrace the path/callback if (pathSuccess) { waypoints = RetracePath(startNode, targetNode); pathSuccess = waypoints.Length > 0; } callback(new PathResult(waypoints, pathSuccess, request.callback)); }
IEnumerator FindPath(Vector3 StartPos, Vector3 TargetPos) { Stopwatch MyStopwatch = new Stopwatch(); MyStopwatch.Start(); Vector3[] Waypoints = new Vector3[0]; bool PathSuccess = false; Node StartNode = grid.NodeFromWorldPoint(StartPos); Node TargetNode = grid.NodeFromWorldPoint(TargetPos); if (StartNode.IsWalkable && TargetNode.IsWalkable) { Heap <Node> OpenSet = new Heap <Node>(grid.MaxSize); HashSet <Node> ClosedSet = new HashSet <Node>(); OpenSet.Add(StartNode); while (OpenSet.Count > 0) { Node CurrentNode = OpenSet.RemoveFirstItem(); ClosedSet.Add(CurrentNode); if (CurrentNode == TargetNode) { MyStopwatch.Stop(); print("Path Found " + MyStopwatch.ElapsedMilliseconds + " Milliseconds"); PathSuccess = true; break; } foreach (Node Neighbour in grid.GetNeighbours(CurrentNode)) { if (!Neighbour.IsWalkable || ClosedSet.Contains(Neighbour)) { continue; } int NewMovementCostToNeighbour = CurrentNode.GCost + GetDistance(CurrentNode, Neighbour) + Neighbour.MovementPenalty; if (NewMovementCostToNeighbour < Neighbour.GCost || !OpenSet.Contains(Neighbour)) { Neighbour.GCost = NewMovementCostToNeighbour; Neighbour.HCost = GetDistance(Neighbour, TargetNode); Neighbour.Parent = CurrentNode; if (!OpenSet.Contains(Neighbour)) { OpenSet.Add(Neighbour); OpenSet.UpdateItem(Neighbour); } else { OpenSet.UpdateItem(Neighbour); } } } } } yield return(null); if (PathSuccess) { Waypoints = RetracePath(StartNode, TargetNode); } RequestManager.FinishedProcessingPath(Waypoints, PathSuccess); }
public void ExceptionEmpty() { var heap = new Heap <int>(HeapType.Minimum); var i = heap.Root; }