void Update() { if (results.Count > 0) { for (int i = 0; i < results.Count; i++) { PathResult result = results.Dequeue(); result.callback(result.path, result.success); } } }
public void ConsumePathResult(PathResult result) { Debug.Log("Pathing complete, result: " + result.status); if (result.status == PathingStatus.Failed) { Debug.Log(result.errorInfo); } else { Debug.Log("Path length: " + result.path.length); } }
/// <summary> /// Flee away from a set of foes, starting on a given cell /// * REVERSED PATH FINDING * /// </summary> public bool FleeFromFoes(short MyCell, short[] FoeCells, int distance) { // Set all Foes as starting points, Exit cell as exit (not used anyway in part 1 of PathFinding) short[] ExitCells = new short[] { MyCell }; FindPath(FoeCells, ExitCells, false, true); // Step 2 ExitCell = ExitCells[0]; short CurrentCell = ExitCell; PathResult.Add(ExitCell); _cells[ExitCell].IsInPath = true; int NbStepLeft = distance; while (NbStepLeft-- > 0) { // Look through each MapNeighbour and find the square // with the lowest number of steps marked. short highestPoint = CellInfo.CELL_ERROR; int PreviousDistance = _cells[CurrentCell].DistanceSteps; int highest = PreviousDistance; foreach (CellInfo NewCell in ValidMoves(_cells[CurrentCell], false)) { int count = NewCell.DistanceSteps; if (count > highest) { highest = count; highestPoint = NewCell.CellId; } } if (highest != PreviousDistance) { // Mark the square as part of the path if it is the lowest // number. Set the current position as the square with // that number of steps. PathResult.Add(highestPoint); _cells[highestPoint].IsInPath = true; CurrentCell = highestPoint; if (PathResult.Count > _cells.Length) { Debug.Assert(false, "PathFinder can't find a path - overflow"); break; } } else { // Can't find a longer path => stop now :( break; } } //PathResult.Reverse(); // Reverse the path, as we started from exit return(PathResult.Count > 0); }
private void StopInternal() { lock (_syncLock) { _stopped = true; _wayPoints.Clear(); _currentPath = null; _pendingPathRequest = null; _currentDestination = null; _pendingResult = null; _manualReplan = null; } }
public void notifyMovement(PathResult pr) { // if within draw range, animate move if (playerWithinDrawRange()) { StartCoroutine(animatePlayerMove(pr)); } else // else just set position { Vector3 destination = pr.getTilesOnPath()[0].getPos(); transform.position = destination; } }
/// <summary> /// Finds the cheapest path leading from start to the closest reachable Tile to target using Dijkstra's. /// </summary> /// <remarks> /// The cheapest path is selected. The most appealing path is selected. /// </remarks> /// <param name="start">Starting Tile</param> /// <param name="target">Target Tile</param> /// <param name="result">Object containing the results.</param> /// <param name="pather">Determines if you can move over an Edge.</param> /// <param name="costCalculator">Calculates the cost to move over an Edge.</param> /// <returns>True if target was reached.</returns> public static bool CheapestPath(Tile start, Tile target, out PathResult result, Pather pather = null, CostCalculator costCalculator = null) { pather ??= Pathers.Phased; costCalculator ??= CostCalculators.MoveCost; var minDist = Game.grid.Distance(start, target); var minCost = float.PositiveInfinity; var closest = start; var tiles = new Dictionary <Tile, FieldItem>() { { start, new FieldItem(0, 0, null) } }; var frontier = new ComparisonPriorityQueue <DoublePriorityNode>(Game.grid.tiles.Count, new DoubleComparer()); frontier.Enqueue(new DoublePriorityNode(start, 0), start.moveCost.current); if (start != target) { while (frontier.Count != 0) { var tile = frontier.Dequeue().tile; foreach (var(neighbor, edge) in tile.NeighborsWithEdges()) { var cost = tiles[tile].cost + costCalculator(tile, edge, neighbor); var appeal = tiles[tile].appeal + tile.appeal.current; if (pather(tile, edge, neighbor) && (!tiles.TryGetValue(neighbor, out var other) || other.cost > cost || (other.cost == cost && other.appeal < appeal))) { tiles[neighbor] = new FieldItem(cost, appeal, tile); if (cost < minCost || closest != target) { float priority = cost; frontier.Enqueue(new DoublePriorityNode(neighbor, -neighbor.appeal.current), priority); var dist = Game.grid.Distance(neighbor, target); if (dist < minDist) { minDist = dist; closest = neighbor; if (closest == target) { minCost = cost; } } } } } } } result = new PathResult(start, tiles, closest); return(closest == target); }
private void attackHumanPlayer() { // get move range PathResult pr = longDistancePathFinder.pathFromTo( this.player.getTilePos(), GameControl.gameSession.humanPlayer.getTilePos(), playersCanBlockPath: true ); int rand = UnityEngine.Random.Range(0, pr.getTilesOnPathStartFirst().Count); string message; GameControl.gameSession.playerAttemptMove(this.player, pr.getTilesOnPathStartFirst()[rand], out message, movePlayer: true); }
//void TryProcessNext() //{ // if(!isProcessingPath && pathRequestQueue.Count > 0) // { // currentPathRequest = pathRequestQueue.Dequeue(); // isProcessingPath = true; // pathfinding.StartFindPath(currentPathRequest.pathStart, currentPathRequest.pathEnd); // } //} //public void FinishedProcessingPath(Vector3[] path, bool success, PathRequest originalRequest) public void FinishedProcessingPath(PathResult result) { //currentPathRequest.callback(path, success); //isProcessingPath = false; //TryProcessNext(); //PathResult result = new PathResult(path, success, originalRequest.callback); //originalRequest.callback(path, success); lock (results) { results.Enqueue(result); } }
public void Update() { if (results.Count > 0) { int queuelength = results.Count; lock (results){ for (int i = 0; i < queuelength; i++) { PathResult result = results.Dequeue(); result.callback(result.path, result.success); } } } }
private void Update() { if (results.Count > 0) { int itemsInQueue = results.Count; lock (results){ for (int i = 0; i < itemsInQueue; i++) { PathResult result = results.Dequeue(); result.callback(result.path, result.success); } } } }
private bool ConsumeResult() { //Since result processing may actually repath and consequently a new result may arrive we need to operate on locals and null the pending result PathResult result; lock (_syncLock) { result = _pendingResult; _pendingResult = null; } var req = result.originalRequest as InternalPathRequest; //Consume way points if appropriate. This must be done prior to the processing of the result, since if the request was a way point request, the first item in line is the one the result concerns. if (req.pathType == InternalPathRequest.Type.Waypoint) { _wayPoints.Dequeue(); } else if (req.pathType == InternalPathRequest.Type.PathboundWaypoint) { _pathboundWayPoints.Dequeue(); } //Reset current destination and path no matter what _previousDestination = _transform.position; _currentDestination = null; _currentPath = null; //Process the result if (!ProcessAndValidateResult(result)) { return(false); } //Consume the result _onFinalApproach = false; _currentPath = result.path; _currentGrid = req.fromGrid; _remainingSquaredDistance = _currentPath.CalculateSquaredLength(); _endOfResolvedPath = _currentPath.Last().position; _endOfPath = _endOfResolvedPath; //Update pending way points UpdatePathboundWaypoints(result.pendingWaypoints); //Pop the first node as our next destination. _unit.hasArrivedAtDestination = false; _currentDestination = _currentPath.Pop(); return(true); }
void Update() { if (pathResQueue.Count > 0) { int queueCount = pathResQueue.Count; lock (pathResQueue) { for (int i = 0; i < queueCount; i++) { PathResult newResult = pathResQueue.Dequeue(); newResult.callback(newResult.path, newResult.success); } } } }
//Note this may be called from another thread if the PathService is running asynchronously void INeedPath.ConsumePathResult(PathResult result) { lock (_syncLock) { //If we have stooped or get back the result of a request other than the one we currently expect, just toss it as it will be outdated. if (_stopped || result.originalRequest != _pendingPathRequest) { return; } _pendingResult = result; _pendingPathRequest = null; } }
// Function that's called every frame void Update() { if (results.Count > 0) // If there are results paths to give back to their specific askers { int itemsInQueue = results.Count; // Get the number of responses lock (results) // Locks them { for (int i = 0; i < itemsInQueue; i++) // Iterates through the results { PathResult result = results.Dequeue(); // Dequeues it result.callback(result.path, result.success); // Callbaks the results } } } }
void INeedPath.ConsumePathResult(PathResult result) { // Execute on the main thread to avoid multi-threading issues or the need for using a lock or Monitor NavLoadBalancer.marshaller.ExecuteOnMainThread(() => { // If we have stopped or get back the result of a request other than the one we currently expect, just toss it as it will be outdated. if (result.originalRequest != _pendingPathRequest) { return; } _pendingResult = result; _pendingPathRequest = null; }); }
void Update() { if (results.Count > 0) { int itemsCount = results.Count; lock (results) { for (int i = 0; i < itemsCount; i++) { PathResult res = results.Dequeue(); res.callback(res.path, res.pathSucces); } } } }
private void Update() { if (_resultQueue.Count > 0) { int itemsCount = _resultQueue.Count; lock (_resultQueue) { for (int i = 0; i < itemsCount; i++) { PathResult result = _resultQueue.Dequeue(); result.callback(result.path, result.success); } } } }
void Update() { if (results.Count > 0) { print("results:" + results.Count); int count = results.Count; lock (results) { for (int i = 0; i < count; i++) { PathResult result = results.Dequeue(); result.callback(result.path, result.success); } } } }
void Update() { if (results.Count > 0) //if we have results(we found a path) ready then { int itemsInQueue = results.Count; //save the amount of results lock (results) //only one thread at a time { for (int i = 0; i < itemsInQueue; i++) //go on all the results { PathResult result = results.Dequeue(); //Dequeue the first results result.callback(result.path, result.success); //call the method callback with the result.path and result.success (OnPathFound in PatrolLog and GralandChase) } } } }
void Update() { if (ResultsQueue.Count > 0) { int ItemsinQueue = ResultsQueue.Count; lock (ResultsQueue) { for (int i = 0; i < ItemsinQueue; i++) { PathResult result = ResultsQueue.Dequeue(); result.callback(result.path, result.success); } } } }
private void wander() { // get move range PathResult pr = DijsktraPF.pathFromTo( this.player.getTilePos(), new HexTile(new Vector3(float.MaxValue, float.MaxValue, float.MaxValue), new Vector2(float.MaxValue, float.MaxValue)), playersCanBlockPath: true ); int rand = UnityEngine.Random.Range(0, pr.getExploredTiles().Count); string message; GameControl.gameSession.playerAttemptMove(this.player, pr.getExploredTiles()[rand], out message, movePlayer: true); }
void Update() { if (results.Count > 0) { int itemsInQueue = results.Count; lock (results) { for (int i = 0; i < itemsInQueue; i++) { PathResult result = results.Dequeue(); Debug.Log("result update request manager = " + result.success); result.callback(result.path, result.success); } } } }
public void Tick() { // Items are in queue if (results.Count > 0) { int itemsInQueue = results.Count; lock (results) { for (int i = 0; i < itemsInQueue; i++) { PathResult result = results.Dequeue(); result.callback(result.path, result.success); } } } }
public void ClearAdjacencyGraph_InvalidatesOldNodes() { var solver = new PathSolver <Point, PathTestOption>(_testMap); // Build a graph based on all three points. solver.BuildAdjacencyGraph(new Point[] { _startPt, _reachableEndPt, _unreachableEndPt }); // Clear the graph, and then rebuild it with just one point. solver.ClearAdjacencyGraph(); solver.BuildAdjacencyGraph(_startPt); // Try to find a path to _unreachableEndPt. PathSolver should complain that it doesn't know about that point. PathResult <Point> pathResult = null; Assert.ThrowsException <PathfindingException>(() => pathResult = solver.FindPath(_startPt, _unreachableEndPt, PathTestOption.Normal)); }
public Dictionary <ElementType, PathResult> SearchPaths() { Dictionary <ElementType, PathResult> results = new Dictionary <ElementType, PathResult>(); Dictionary <Node, Node> map = GetMap(); Node[] nodes = map.Keys.ToArray(); for (int i = 0; i < nodes.Length; i++) { Node node = nodes[i]; PathResult result = new PathResult(node.element, node.givenCost, BuildPath(node)); results.Add(node.element, result); } return(results); }
/// <summary> /// Finds the first path leading from start to the closest reachable Tile to target using optimism. Computationally less intensive. /// </summary> /// <remarks> /// Tiles closer to the target are favored. /// </remarks> /// <param name="start">Starting Tile</param> /// <param name="target">Target Tile</param> /// <param name="result">Object containing the results.</param> /// <param name="pather">Determines if you can move over an Edge.</param> /// <returns>True if target was reached</returns> public static bool FirstPath(Tile start, Tile target, out PathResult result, Pather pather = null) { pather ??= Pathers.Phased; var minDist = Game.grid.Distance(start, target); var closest = start; var tiles = new Dictionary <Tile, FieldItem>() { { start, new FieldItem(0, 0, null) } }; var frontier = new FastPriorityQueue <SinglePriorityNode>(Game.grid.tiles.Count); frontier.Enqueue(new SinglePriorityNode(start), 1); if (start != target) { while (frontier.Count != 0) { var tile = frontier.Dequeue().tile; foreach (var(neighbor, edge) in tile.NeighborsWithEdges()) { var cost = tiles[tile].cost + 1; if (pather(tile, edge, neighbor) && (!tiles.TryGetValue(neighbor, out var other))) { tiles[neighbor] = new FieldItem(cost, 0, tile); var dist = Game.grid.Distance(neighbor, target); var priority = dist; frontier.Enqueue(new SinglePriorityNode(neighbor), priority); if (dist < minDist) { minDist = dist; closest = neighbor; if (closest == target) { result = new PathResult(start, tiles, closest); return(true); } } } } } } result = new PathResult(start, tiles, closest); return(closest == target); }
private int EvaluatePosition(Board position) { evaluations++; // Check the hash table to see if we already calculated this path for this board if (enableHash) { int?saved = hash.Get(position); if (saved != null) { hashHits++; return((int)saved); } hashMisses++; } // For each tile, figure out how long it'll take to get to it's antipode PathResult[] playerOnePaths = new PathResult[80]; PathResult[] playerTwoPaths = new PathResult[80]; for (int i = 0; i < 80; i++) { if (position.Tiles[i] > 0) { playerOnePaths[i] = pathFinder.FindPath(position, i, Constants.Antipodes[i]); } if (position.Tiles[i] < 0) { playerTwoPaths[i] = pathFinder.FindPath(position, i, Constants.Antipodes[i]); } } // Find the best paths for each player PathResult one = playerOnePaths.Where(x => x != null).OrderBy(x => x.Distance).FirstOrDefault(); PathResult two = playerTwoPaths.Where(x => x != null).OrderBy(x => x.Distance).FirstOrDefault(); // Positive scores are good for player one and negative are good for player two int score = (two?.Distance - one?.Distance) ?? 0; if (enableHash) { // Save the hash to speed up future evaluations hash.Set(position, score); } return(score); }
public void Update() { //if the results queue is not empty.. if (results.Count > 0) { int count = results.Count; lock (results) { for (int i = 0; i < count; i++) { //... remove the next request from the queue and process it PathResult result = results.Dequeue(); result.callback(result.path, result.success); } } } }
PathResult IsPossibleToDash(AIHeroClient target, int jumpcount) { var result = new PathResult(); var dist = Yasuo.Distance(target); var pos = Yasuo.ServerPosition.To2D(); var minionsinbw = ObjectManager.Get <Obj_AI_Minion>() .Where(x => x.Distance(target) <= dist && x.Distance(Yasuo) < dist) .OrderBy(x => x.Distance(Yasuo)); result.foundPath = false; foreach (var minion in minionsinbw) { if (result.numberOfHops > jumpcount) { result.foundPath = false; return(result); } if (pos.Distance(target) <= Yasuo.AttackRange || (target.IsDashable() && pos.Distance(target) <= Spells[E].Range)) { result.foundPath = true; return(result); } if (pos.Distance(minion) > Spells[E].Range) { continue; } if (minion.IsDashable(40000)) { result.numberOfHops++; result.minionPath.Add(minion); pos = GetDashPos(minion); } else { continue; } } return(result); }
/// Check if we have a path, if not try to get one. Then move towards the destination, tile by tile. public void Move(Task task) { if (this._hasDestination == false) { PathResult pathResult = AI.PathFinder.GetPath(this.position, task.targets.currentPosition); if (pathResult.success == false) { task.state = TaskState.Failed; // Maybe a special failed condition; this.ResetMovement(); return; } this._hasDestination = true; this._path = new Queue <Vector2Int>(pathResult.path); this.destination = task.targets.currentPosition; } // Are we on our final destination if (this.destination == this.position) { this.ResetMovement(); return; } if (this.position == this._nextPosition) { this._nextPosition = this._path.Dequeue(); this.UpdateLookingAt(this._nextPosition); } float distance = Utils.Distance(this.position, this._nextPosition); float distanceThisFrame = this._speed * Loki.map[this.position].pathCost; this._movementPercent += distanceThisFrame / distance; if (this._movementPercent >= 1f) { Loki.map[this.position].characters.Remove(this._character); Loki.map[this._nextPosition].characters.Add(this._character); this.position = this._nextPosition; this._movementPercent = 0f; } }
public void TestB() { string[] node = "A B C D E F G H".Split(' '); var links = new List<Link>() { new Link("A", "B", 10), new Link("A", "C", 15), new Link("C", "H", 20), new Link("B", "H", 15), new Link("C", "D", 5), new Link("D", "G", 25), }; PathsManager manager = new PathsManager(node, links); var expectedResut = new PathResult(new List<string> { "A", "C", "D"}, 20); var result = manager.GetLeastWeightedPath("A", "D"); Assert.AreEqual(true, expectedResut.Equals(result)); }
private static Exception GetInvalidPathException(PathResult result, string path) { switch (result) { default: case PathResult.Correct: return null; case PathResult.Empty: // Name cannot be empty. return new InvalidPathException(EmptyNameMessage); case PathResult.TooLong: // Path too long. Max length is {0}. return new InvalidPathException(string.Format(PathTooLongMessage, Data.DataProvider.Current.PathMaxLength)); case PathResult.InvalidPathChar: // Content path may only contain alphanumeric characters or '.', '(', ')', '[', ']', '/'! return new InvalidPathException(String.Concat(InvalidPathMessage, ". Path: ", path)); case PathResult.InvalidNameChar: // Content name may only contain alphanumeric characters or '.', '(', ')', '[', ']'! return new InvalidPathException(String.Concat(InvalidNameMessage, ". Path: ", path)); case PathResult.StartsWithSpace: // Name cannot start with whitespace. return new InvalidPathException(NameStartsWithWhitespaceMessage); case PathResult.EndsWithSpace: // Name cannot end with whitespace. return new InvalidPathException(NameEndsWithWhitespaceMessage); case PathResult.InvalidFirstChar: // Path must start with '/' character. return new InvalidPathException(PathFirstCharMessage); case PathResult.EndsWithDot: // Path cannot end with '.' character. return new InvalidPathException(PathEndsWithDotMessage); } }