Ejemplo n.º 1
0
 public void CheckPathList()
 {
     aStar.Search(graph, 0, 2);
     Assert.AreEqual(2, aStar.GetPath().GetListOfCoordinates().Count);
     aStar.Search(graph, 1, 5);
     Assert.AreEqual(3, aStar.GetPath().GetListOfCoordinates().Count);
 }
Ejemplo n.º 2
0
    public static List <Node> GetPath(Vector2Int startPosition, Vector2Int targetPosition)
    {
        var startNode  = PathGrid.NodeAt(startPosition.x, startPosition.y);
        var targetNode = PathGrid.NodeAt(targetPosition.x, targetPosition.y);
        var path       = AStarSearch.GetPath(startNode, targetNode);

        return(path);
    }
Ejemplo n.º 3
0
    private void benchmark(object parameter)
    {
        var benchmarkParameter = (BenchmarkParameter)parameter;
        var grid = benchmarkParameter.grid;

        float astarTime = 0;
        float jpsTime   = 0;

        var stopwatch = new System.Diagnostics.Stopwatch();
        var astar     = new AStarSearch();

        astar.showDebug = false;
        var jps = new JumpPointSearch();

        jps.showDebug = false;
        var r    = new System.Random(100);
        var size = benchmarkParameter.grid.GetSize();

        for (var i = 0; i < benchmarkParameter.iterations; i++)
        {
            Vector3Int start;
            Vector3Int end;
            do
            {
                start = new Vector3Int(r.Next(0, size.x), r.Next(0, size.y), 0);
                end   = new Vector3Int(r.Next(0, size.x), r.Next(0, size.y), 0);
            } while (!grid.IsWalkable(start.x, start.y) || !grid.IsWalkable(end.x, end.y));

            // Run A* Search
            stopwatch.Restart();
            if (astar.GetPath(grid, new Vector2Int(start.x, start.y), new Vector2Int(end.x, end.y)) == null)
            {
                Debug.Log("Astar didn't find path");
            }
            astarTime += stopwatch.ElapsedMilliseconds;

            // Run Jump Point Search
            stopwatch.Restart();
            if (jps.GetPath(grid, new Vector2Int(start.x, start.y), new Vector2Int(end.x, end.y)) == null)
            {
                Debug.Log("JPS didn't find path");
            }
            jpsTime += stopwatch.ElapsedMilliseconds;

            if (i % 100 == 0)
            {
                Debug.Log("Processed " + i + " iterations");
            }
        }

        Debug.Log("Benchmark result (" + benchmarkParameter.iterations + " iterations): AStar took " + astarTime + "ms and JPS took " + jpsTime + "ms");
    }
Ejemplo n.º 4
0
        public ReturnedPath GetPath(Vector2D startNode, Vector2D endNode)
        {
            var indexStart = pathfinding.GetClosestNode(startNode);
            var indexEnd   = pathfinding.GetClosestNode(endNode);
            var aStar      = new AStarSearch();
            var path       = new ReturnedPath();

            if (aStar.Search(pathfinding, indexStart, indexEnd))
            {
                path = aStar.GetPath();
            }
            return(path);
        }
Ejemplo n.º 5
0
    private List <Coord> GetPath(Coord A, Coord B, MapGrid mapGrid, bool isVisualize)
    {
        switch (AppConfig.searchAlgorithm)
        {
        case Algorithm.DFS: return(DepthFirstSearch.GetPath(A, B, mapGrid, isVisualize));

        case Algorithm.BFS: return(BreadthFirstSearch.GetPath(A, B, mapGrid, isVisualize));

        case Algorithm.Dijkstra: return(DijkstraSearch.GetPath(A, B, mapGrid, isVisualize));

        case Algorithm.AStar: return(AStarSearch.GetPath(A, B, mapGrid, isVisualize));

        default: return(AStarSearch.GetPath(A, B, mapGrid, isVisualize));
        }
    }
Ejemplo n.º 6
0
    public void Search(int algrithm)
    {
        ClearPath();
        SearchAlgrithm ag = (SearchAlgrithm)algrithm;
        PathFind       pathFind;

        switch (ag)
        {
        case SearchAlgrithm.BFS:
            pathFind = new BreadthFirstSearch();
            break;

        case SearchAlgrithm.DFS:
            pathFind = new DeepFirstSearch();
            break;

        case SearchAlgrithm.Dijkstra:
            pathFind = new DijkstraSearch();
            break;

        case SearchAlgrithm.Greedy:
            pathFind = new GreedyBestFirstSearch();
            break;

        case SearchAlgrithm.AStar:
            pathFind = new AStarSearch();
            break;

        default:
            pathFind = new AStarSearch();
            break;
        }
        Node start = graph.GetNode((int)mapView.startPos.x, (int)mapView.startPos.y);
        Node end   = graph.GetNode((int)mapView.endPos.x, (int)mapView.endPos.y);

        if (pathFind.Find(graph, start, end))
        {
            path = pathFind.GetPath();
            Queue <Node> searchSteps = pathFind.GetSearchSteps();
            mainUI.labelSearchDesc.text = pathFind.Name() + " " + pathFind.SearchResultDesc();
            mainUI.SearchConsoleTxt     = "";
            StartCoroutine(DrawSearchSteps(searchSteps, path));
        }
        else
        {
            mainUI.labelConsole.text = "no path to the target point from the start point";
        }
    }
Ejemplo n.º 7
0
    public static void TestTime(Vector2Int startPosition, Vector2Int targetPosition, int testCount)
    {
        var startNode  = PathGrid.NodeAt(startPosition.x, startPosition.y);
        var targetNode = PathGrid.NodeAt(targetPosition.x, targetPosition.y);

        string AlgoName = "A* Region HashSet";
        float  T        = 0;

        for (int i = 0; i < testCount; i++)
        {
            float startTime = Time.realtimeSinceStartup;
            AStarSearch.GetPath(startNode, targetNode);
            T += (Time.realtimeSinceStartup - startTime) * 1000 / testCount;
        }
        Debug.Log($"{AlgoName}: {T} ms.");
    }
Ejemplo n.º 8
0
    public void FindAStarRegionUpgrade()
    {
        _aStarRegionUpgrade.Reset();
        AStarSearch.HandleAddToPath      += _aStarRegionUpgrade.AddToPath;
        AStarSearch.HandleAddToClosedSet += _aStarRegionUpgrade.AddToClosedSet;

        float startTime = Time.realtimeSinceStartup;

        AStarSearch.GetPath(PathGrid.NodeAt(Actor.x, Actor.y), PathGrid.NodeAt(Target.x, Target.y));
        float resultTime = (Time.realtimeSinceStartup - startTime) * 1000;

        AStarRegionUpgradeTimeValue.text  = resultTime.ToString();
        AStarRegionUpgradePathLength.text = _aStarRegionUpgrade.Path.Count.ToString();

        AStarSearch.HandleAddToPath      -= _aStarRegionUpgrade.AddToPath;
        AStarSearch.HandleAddToClosedSet -= _aStarRegionUpgrade.AddToClosedSet;
    }
Ejemplo n.º 9
0
        void AStar_RunOnStable3On3Filed_ReturnCorrectPath()
        {
            /* The way
             * |F.W|
             * |W..|
             * |WWF|
             */

            var matrix       = new MatrixField();
            var search       = new AStarSearch(matrix.Start, matrix.Goal);
            var expectedPath = "s.W\nW..\nWWg\n";

            search.Run();
            var foundPath = matrix.Print(search.GetPath());

            foundPath.Should().Be(expectedPath);
        }
        public static BTStatus AmphibiousMovement(Animal agent, Vector2 generalDirection, float speed, AnimalAnimationState state, float minDistance = 2f, float maxDistance = 20f)
        {
            var start = agent.Position.WorldPosition3i;
            if (!World.World.IsUnderwater(start))
                start = RouteManager.NearestWalkableY(agent.Position.WorldPosition3i);

            if (!start.IsValid)
                return LandMovement(agent, generalDirection, speed, state, minDistance, maxDistance);

            if (generalDirection == Vector2.zero)
                generalDirection = Vector2.right.Rotate(RandomUtil.Range(0f, 360));
            else
                generalDirection = generalDirection.Normalized;

            var target = (agent.Position + (generalDirection * RandomUtil.Range(minDistance, maxDistance)).X_Z()).WorldPosition3i;
            if (World.World.IsUnderwater(target))
                target.y = World.World.MaxWaterHeight[target];
            else
                target = RouteManager.NearestWalkableXYZ(target, 5);

            // This is a low-effort search that includes water surface and should occasionally fail, just pick a semi-random node that was visited when it fails
            var allowWaterSearch = new AStarSearch(RouteCacheData.NeighborsIncludeWater, start, target, 30);
            if (allowWaterSearch.Status != SearchStatus.PathFound)
            {
                target = allowWaterSearch.Nodes.Last().Key;
                allowWaterSearch.GetPath(target);
            }

            if (allowWaterSearch.Path.Count < 2)
                return BTStatus.Failure;
            else if (allowWaterSearch.Status == SearchStatus.Unpathable && allowWaterSearch.Nodes.Count < RouteRegions.MinimumRegionSize && !World.World.IsUnderwater(agent.Position.WorldPosition3i))
            {
                // Search region was unexpectedly small and agent is on land, might be trapped by player construction. 
                // Try regular land movement so region checks can apply & the agent can get unstuck (or die)
                return LandMovement(agent, generalDirection, speed, state, minDistance, maxDistance);
            }

            var smoothed = allowWaterSearch.LineOfSightSmooth(agent.Position);
            PiecewiseLinearFunction route = AIUtilities.ProjectRoute(smoothed, speed);
            agent.AnimationState = state;
            agent.NextTick = WorldTime.Seconds + route.EndTime;
            agent.Target.SetPath(route);

            return BTStatus.Success;
        }
Ejemplo n.º 11
0
    public void FindPath(bool astar)
    {
        DebugDrawer.Clear();

        // Convert visible grid to memory grid
        var grid     = GridController.Ground;
        var pathGrid = GridController.Path;

        var sizeX = GridController.active.size.x;
        var sizeY = GridController.active.size.y;

        var memoryGrid = createGraph();
        // Set grid weights
        var start = new Vector2Int(-1, -1);
        var end   = new Vector2Int(-1, -1);

        for (var x = 0; x < sizeX; x++)
        {
            for (var y = 0; y < sizeY; y++)
            {
                var pathTile = pathGrid.GetTile(new Vector3Int(x, y, 0));
                if (pathTile != null)
                {
                    if (pathTile == GridController.active.start)
                    {
                        start = new Vector2Int(x, y);
                    }
                    else if (pathTile == GridController.active.end)
                    {
                        end = new Vector2Int(x, y);
                    }
                }
            }
        }

        if (start.x == -1 || end.x == -1)
        {
            Debug.Log("Couldn't find any start or end position");
            return;
        }

        List <Node> path;

        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        if (astar)
        {
            var asearch = new AStarSearch();
            sw.Start();
            path = asearch.GetPath(memoryGrid, start, end);
            UnityEngine.Debug.Log("A* Path - Path" + (path == null ? " not " : " ") + "found in : " + sw.ElapsedMilliseconds + " ms");
        }
        else
        {
            var jpsearch = new JumpPointSearch();
            sw.Start();
            path = jpsearch.GetPath(memoryGrid, start, end);
            UnityEngine.Debug.Log("JPS Path - Path" + (path == null ? " not " : " ") + "found in : " + sw.ElapsedMilliseconds + " ms");
        }

        if (path != null)
        {
            foreach (var pathTile in path)
            {
                if (pathTile.x == start.x && pathTile.y == start.y)
                {
                    continue;
                }
                if (pathTile.x == end.x && pathTile.y == end.y)
                {
                    continue;
                }

                if (pathTile.parent != null)
                {
                    DebugDrawer.Draw(new Vector2Int(pathTile.parent.x, pathTile.parent.y), new Vector2Int(pathTile.x, pathTile.y), Color.blue);
                }
                DebugDrawer.DrawCube(new Vector2Int(pathTile.x, pathTile.y), Vector2Int.one, Color.blue);
            }
        }
    }