Beispiel #1
0
        public IList <Point2D> GetPath(int[][] grid, Point2D start, Point2D end, GameDiagonalMovement type)
        {
            var width  = grid.Length;
            var height = grid[0].Length;

            bool[][] movableMatrix = new bool[width][];
            for (int widthTrav = 0; widthTrav < width; widthTrav++)
            {
                movableMatrix[widthTrav] = new bool[height];
                for (int heightTrav = 0; heightTrav < height; heightTrav++)
                {
                    movableMatrix[widthTrav][heightTrav] = grid[widthTrav][heightTrav] == 0;
                }
            }

            Board    = new StaticGrid(width, height, movableMatrix);
            StartPos = new GridPos(start.X, start.Y);
            EndPos   = new GridPos(end.X, end.Y);
            JumpPointParam jpParam = new JumpPointParam(Board, StartPos, EndPos, EndNodeUnWalkableTreatment.DISALLOW,
                                                        type == GameDiagonalMovement.Never ? DiagonalMovement.Never : DiagonalMovement.Always,
                                                        HeuristicMode.EUCLIDEAN);
            List <GridPos> resultPathList = JumpPointFinder.FindPath(jpParam);


            return(resultPathList.Select(x => new Point2D(x.x, x.y)).ToList());
        }
Beispiel #2
0
    public List <GridPos> FindPath(Vector2 p1, Vector2 p2)
    {
        var jpParam = new JumpPointParam(grids, new GridPos(Convert.ToInt32(p1.x), Convert.ToInt32(p1.y)), new GridPos(Convert.ToInt32(p2.x), Convert.ToInt32(p2.y)));
        var path    = JumpPointFinder.FindPath(jpParam);

        return(path);
    }
Beispiel #3
0
        private IList <GridPos> GetJumpPointsFromJumpPointFinder(Vector2Int startPoint, Vector2Int targetPoint)
        {
            if (!_gridInfoProvider.IsWalkable(targetPoint))
            {
                return(new GridPos[0]);
            }

            GridPos startPosition  = ZeroBasedPosition(startPoint);
            GridPos targetPosition = ZeroBasedPosition(targetPoint);

            // todo: when iAllowEndNodeUnWalkable is set to false, it seems that search is performed anyway — it just finishes with failure. Fix!
            JumpPointParam jumpPointsParams
                = new JumpPointParam(_navigationGrid, startPosition, targetPosition, iAllowEndNodeUnWalkable: false, iMode: HeuristicMode.MANHATTAN);

            // todo: note that resetting the grid causes all the nodes to be created again,
            // which probably causes bad performance (5-30 ms for 30x50 grid).
            // Possible solutions: use DynamicGridWPool instead of StaticGrid; refactor the library; use other library.
            jumpPointsParams.Reset(startPosition, targetPosition);
            IList <GridPos> resultPathList = JumpPointFinder.FindPath(jumpPointsParams);

            if (!resultPathList.Any())
            {
                return(new GridPos[0]);
            }
            return(resultPathList);
        }
Beispiel #4
0
        public IEnumerable <Vector2D> Find(Vector2D origin, Vector2D destination)
        {
            BaseGrid searchGrid = new StaticGrid(map.Width, map.Height, matrix);
            var      jp         = new JumpPointParam(searchGrid, new GridPos(origin.X, origin.Y), new GridPos(destination.X, destination.Y), EndNodeUnWalkableTreatment.Allow);

            return(JumpPointFinder.FindPath(jp).Select(x => new Vector2D(x.X, x.Y)));
        }
Beispiel #5
0
        public List <MapCell> JPSPlus(MapCell cell1, MapCell cell2)
        {
            List <MapCell> path  = new List <MapCell>();
            List <GridPos> lpath = new List <GridPos>();

            if (cell1.MapId != cell2.MapId)
            {
                return(path);
            }
            JumpPointParameters.Reset(new GridPos(cell1.X, cell1.Y), new GridPos(cell2.X, cell2.Y));
            List <GridPos> resultPathList = JumpPointFinder.FindPath(JumpPointParameters);

            lpath = JumpPointFinder.GetFullPath(resultPathList);
            Debug.WriteLine($"From X: {cell1.X} Y: {cell1.Y}, To X: {cell2.X} Y: {cell2.Y}, Paths: {resultPathList.Count}, LPath: {lpath.Count}");
            if (lpath.Count > 0)
            {
                foreach (GridPos item in lpath)
                {
                    path.Add(new MapCell {
                        X = Convert.ToInt16(item.x), Y = Convert.ToInt16(item.y), MapId = cell1.MapId
                    });
                }
            }
            return(path);
        }
Beispiel #6
0
        public static List <GridPos> GetPath(Point2D start, Point2D end)
        {
            for (int i = 0; i < MovableMatrix.Length; i++)
            {
                var row = MovableMatrix[i];
                for (int index = 0; index < row.Length; index++)
                {
                    MovableMatrix[i][index] = true;
                }
            }

            List <CircularUnit> circularUnits = new List <CircularUnit>(Tick.World.Minions);

            circularUnits.AddRange(Tick.World.Buildings);
            circularUnits.AddRange(Tick.World.Wizards.Where(x => !x.IsMe));
            circularUnits.AddRange(Tick.World.Trees);
            circularUnits = circularUnits.Where(x => Tick.Self.GetDistanceTo(x) < Tick.Self.VisionRange).ToList();
            foreach (var nearestMinion in circularUnits)
            {
                var p1 = (int)nearestMinion.X / gridStep;
                var p2 = (int)nearestMinion.Y / gridStep;
                FillMovableCircle(p1, p2, (int)(nearestMinion.Radius + Tick.Self.Radius * 1.2) / gridStep, gridSize, MovableMatrix, false);
            }

            var startGridPos = GetGridPosByPoint2d(start, gridStep);
            var endGridPos   = GetGridPosByPoint2d(end, gridStep);

            MovableMatrix[startGridPos.x][startGridPos.y] = true;
            FillMovableCircle(endGridPos.x, endGridPos.y, (int)(Tick.Self.Radius * 2) / gridStep, gridSize, MovableMatrix, true);

            BaseGrid searchGrid = new StaticGrid(gridSize, gridSize, MovableMatrix);

            JumpPointParam jpParam = new JumpPointParam(searchGrid, startGridPos, endGridPos);
            var            result  = JumpPointFinder.FindPath(jpParam);

            //result = JumpPointFinder.GetFullPath(result);

            //var clmnIdx = 0;
            //foreach (var row in MovableMatrix)
            //{
            //    var rowIdx = 0;
            //    foreach (var b in row)
            //    {
            //        if (!b)
            //        {
            //            VisualClientHelper.Rect(new Point2D(clmnIdx * gridStep, rowIdx * gridStep),
            //                new Point2D((clmnIdx + 1) * gridStep, (rowIdx + 1) * gridStep), new VisualClientColor(0, 0, 1));
            //        }

            //        rowIdx++;
            //    }

            //    clmnIdx++;
            //}

            DrawPath(result, gridStep);

            return(result);
        }
Beispiel #7
0
 public static List <GridPos> JPSPlus(JumpPointParam JumpPointParameters, GridPos cell1, GridPos cell2)
 {
     if (JumpPointParameters != null)
     {
         JumpPointParameters.Reset(cell1, cell2);
         return(JumpPointFinder.GetFullPath(JumpPointFinder.FindPath(JumpPointParameters)));
     }
     return(new List <GridPos>());
 }
        public void FindPath_Trivial()
        {
            var grid = new StaticGrid(3, 3);
            //grid.SetWalkableAll(true);
            var param = new JumpPointParam(grid, new GridPos(0, 0), new GridPos(2, 2));
            var path  = JumpPointFinder.FindPath(param);

            Assert.Contains(new GridPos(0, 0), path);
            Assert.Contains(new GridPos(2, 2), path);
        }
Beispiel #9
0
        public List <GridPos> GetNodes()
        {
            myGrid.Reset(myCurrent, myDestination);
            List <GridPos> resultPathList = JumpPointFinder.FindPath(myGrid);

            Convert        convert  = new Convert();
            List <GridPos> realList = convert.Points(resultPathList);

            return(realList);
        }
Beispiel #10
0
        public List <GridPos> JPSPlus(GridPos cell1, GridPos cell2)
        {
            List <GridPos> lpath = new List <GridPos>();

            JumpPointParameters.Reset(cell1, cell2);
            List <GridPos> resultPathList = JumpPointFinder.FindPath(JumpPointParameters);

            lpath = JumpPointFinder.GetFullPath(resultPathList);
            Debug.WriteLine($"From X: {cell1.x} Y: {cell1.y}, To X: {cell2.x} Y: {cell2.y}, Paths: {resultPathList.Count}, LPath: {lpath.Count}");
            return(lpath);
        }
Beispiel #11
0
        public List <GridPos> JPSPlus(JumpPointParam JumpPointParameters, GridPos cell1, GridPos cell2)
        {
            List <GridPos> lpath = new List <GridPos>();

            if (JumpPointParameters != null)
            {
                JumpPointParameters.Reset(cell1, cell2);
                List <GridPos> resultPathList = JumpPointFinder.FindPath(JumpPointParameters);
                lpath = JumpPointFinder.GetFullPath(resultPathList);
            }
            return(lpath);
        }
Beispiel #12
0
 private void findPath()
 {
     m_jumpParam.CurIterationType = m_tRecursive.isOn ? IterationType.RECURSIVE : IterationType.LOOP;
     m_jumpParam.DiagonalMovement = (DiagonalMovement)m_ddDiagonalMode.value;
     foreach (Testbed i in m_testbedList)
     {
         m_jumpParam.Reset(i.start, i.end);
         i.result = JumpPointFinder.FindPath(m_jumpParam);
         getOpenClose(i);
         drawResult(i);
     }
 }
Beispiel #13
0
 public List<GridPos> findPath(BaseGrid grid, DiagonalMovement move, GridPos startPos, GridPos endPos){
     JumpPointParam jpParam = new JumpPointParam(
         grid, 
         startPos, 
         endPos, 
         true,
         move, 
         HeuristicMode.EUCLIDEAN
     );
     List<GridPos> result = JumpPointFinder.FindPath(jpParam); 
     if (debug) Console.WriteLine("found path");
     return result;
 }
Beispiel #14
0
        /// <summary>
        /// Keep in mind this method returns the start end and turn points of the path, and not all movement steps.
        /// </summary>
        private List <GridPos> FindPath(int fromX, int fromZ, int toX, int toZ)
        {
            JumpPointParam jpParam = GetJumpPointParam();

            GridPos from = new GridPos(fromX, fromZ);
            GridPos to   = new GridPos(toX, toZ);

            jpParam.Reset(from, to);

            List <GridPos> routeFound = JumpPointFinder.FindPath(jpParam);

            return(routeFound);
        }
Beispiel #15
0
        public void OkEmptyGridTest()
        {
            GridPos        startPos = new GridPos(10, 10);
            GridPos        endPos   = new GridPos(20, 10);
            JumpPointParam jpParam  = new JumpPointParam(_searchGrid, startPos, endPos);

            List <GridPos> resultPathList = JumpPointFinder.FindPath(jpParam);

            Assert.AreEqual(2, resultPathList.Count);
            Assert.AreEqual(startPos.x, resultPathList.First().x);
            Assert.AreEqual(startPos.y, resultPathList.First().y);
            Assert.AreEqual(endPos.x, resultPathList.Last().x);
            Assert.AreEqual(endPos.y, resultPathList.Last().y);
        }
Beispiel #16
0
        public IEnumerable <Point> FindPath(Point startPos, Point endPos)
        {
            var start = new GridPos(startPos.X, startPos.Y);
            var end   = new GridPos(endPos.X, endPos.Y);

            var param = new JumpPointParam(_staticGrid, start, end, EndNodeUnWalkableTreatment.Allow);

            var listPositions = JumpPointFinder.FindPath(param);

            return(listPositions.Select(z => new Point()
            {
                X = z.x,
                Y = z.y
            }));
        }
        /// <summary>
        /// Finds a path between 2 position on a map
        /// </summary>
        /// <param name="startPosition">Starting position</param>
        /// <param name="endPosition">Destination</param>
        /// <param name="map">Game map currently being used</param>
        /// <param name="endNodeUnWalkable"></param>
        /// <returns>A list of Vector2 waypoints that the object must traverse to get to its destination</returns>
        internal Stack <Vector2> FindPath(Vector2 startPosition, Vector2 endPosition, ref Map.Map map, EndNodeUnWalkableTreatment endNodeUnWalkable = EndNodeUnWalkableTreatment.DISALLOW)
        {
            if (!Map.Map.IsOnTop(endPosition) || !map.GetCollisionMap().GetWalkabilityGrid().IsWalkableAt(VectorToGridPos(endPosition)))
            {
                return(new Stack <Vector2>());
            }

            var startGridPos = VectorToGridPos(startPosition);
            var endGridPos   = VectorToGridPos(endPosition);

            if (ClearDirectPath(startGridPos.x, startGridPos.y, endGridPos.x, endGridPos.y, ref map))
            {
                var pathVector = new Stack <Vector2>(1);
                pathVector.Push(endPosition);
                return(pathVector);
            }
            else
            {
                if (mJpParam != null)
                {
                    mJpParam.Reset(VectorToGridPos(startPosition), VectorToGridPos(endPosition));
                }
                else
                {
                    mJpParam = new JumpPointParam(map.GetCollisionMap().GetWalkabilityGrid(),
                                                  startGridPos,
                                                  iDiagonalMovement: DiagonalMovement.OnlyWhenNoObstacles,
                                                  iEndPos: endGridPos,
                                                  iAllowEndNodeUnWalkable: endNodeUnWalkable,
                                                  iMode: HeuristicMode.MANHATTAN);
                }

                var pathGrid = JumpPointFinder.FindPath(mJpParam);

                var pathVector = new Stack <Vector2>(pathGrid.Count);

                pathVector.Push(endPosition);


                for (var i = pathGrid.Count - 1; i > 0; i--)
                {
                    var gridPos = GridPosToVector2(pathGrid[i]);
                    pathVector.Push(gridPos);
                }

                return(pathVector);
            }
        }
Beispiel #18
0
    public List <Vector3> FindPath(GridPos startPos, GridPos endPos)
    {
        BaseGrid searchGrid = CreateMovableGrid();

        JumpPointParam jpParam = new JumpPointParam(searchGrid, startPos, endPos, EndNodeUnWalkableTreatment.ALLOW, DiagonalMovement.Always, HeuristicMode.MANHATTAN);

        List <GridPos> resultPathList = JumpPointFinder.FindPath(jpParam);
        List <Vector3> worldPath      = new List <Vector3>();

        for (int i = 0; i < resultPathList.Count; i++)
        {
            worldPath.Add(GridPosToWorld(resultPathList[i].x, resultPathList[i].y));
        }

        return(worldPath);
    }
Beispiel #19
0
        public void OkObstacleTest()
        {
            _searchGrid.SetWalkableAt(15, 10, false);

            GridPos        startPos = new GridPos(10, 10);
            GridPos        endPos   = new GridPos(20, 10);
            JumpPointParam jpParam  = new JumpPointParam(_searchGrid, startPos, endPos);

            List <GridPos> resultPathList = JumpPointFinder.FindPath(jpParam);

            Assert.Greater(resultPathList.Count, 2);
            Assert.AreEqual(startPos.x, resultPathList.First().x);
            Assert.AreEqual(startPos.y, resultPathList.First().y);
            Assert.AreEqual(endPos.x, resultPathList.Last().x);
            Assert.AreEqual(endPos.y, resultPathList.Last().y);
        }
Beispiel #20
0
        public static List <GridPos> GetPath(Point2D start, Point2D end)
        {
            BaseGrid searchGrid = new StaticGrid(gridSize, gridSize, MovableMatrix);

            var startGridPos = GetGridPosByPoint2d(start, gridStep);
            var endGridPos   = GetGridPosByPoint2d(end, gridStep);


            JumpPointParam jpParam = new JumpPointParam(searchGrid, startGridPos, endGridPos);
            var            result  = JumpPointFinder.FindPath(jpParam);

            result = JumpPointFinder.GetFullPath(result);

            DrawPath(result, gridStep);

            return(result);
        }
Beispiel #21
0
        public List <Vector2> FindPath(Vector2 start, Vector2 end)
        {
            GridPos s = new GridPos((int)(start.x * 2), (int)(start.y * 2));
            GridPos e = new GridPos((int)(end.x * 2), (int)(end.y * 2));

            if (s.x < 0 || s.x >= mSearchGrid.width || s.y < 0 || s.y >= mSearchGrid.height ||
                e.x < 0 || e.x >= mSearchGrid.width || e.y < 0 || e.y >= mSearchGrid.height)
            {
                return(EmptyPath);
            }

            mParam.Reset(s, e, mSearchGrid);

            var path = JumpPointFinder.FindPath(mParam);

            return(path.Select(item => new Vector2(item.x / 2.0f, item.y / 2.0f)).Skip(1).ToList());
        }
Beispiel #22
0
    public void GetPath(Vector3 targetPos)
    {
        if (nextPath > Time.time)
        {
            return;
        }

        nextPath = Time.time + 0.2f;

        targetNode = 0;

        GridPos startPos = new GridPos(Mathf.RoundToInt(transform.position.x), Mathf.RoundToInt(transform.position.z));
        GridPos endPos   = new GridPos(Mathf.RoundToInt(targetPos.x), Mathf.RoundToInt(targetPos.z));

        jpParam.Reset(startPos, endPos);

        JumpPointFinder.FindPath(jpParam, out targetPath);
    }
Beispiel #23
0
        public void ErrorUnrecheableTest()
        {
            _searchGrid.SetWalkableAt(19, 9, false);
            _searchGrid.SetWalkableAt(20, 9, false);
            _searchGrid.SetWalkableAt(21, 9, false);
            _searchGrid.SetWalkableAt(21, 10, false);
            _searchGrid.SetWalkableAt(21, 11, false);
            _searchGrid.SetWalkableAt(20, 11, false);
            _searchGrid.SetWalkableAt(19, 11, false);
            _searchGrid.SetWalkableAt(19, 10, false);

            GridPos        startPos = new GridPos(10, 10);
            GridPos        endPos   = new GridPos(20, 10);
            JumpPointParam jpParam  = new JumpPointParam(_searchGrid, startPos, endPos);

            List <GridPos> resultPathList = JumpPointFinder.FindPath(jpParam);

            Assert.IsEmpty(resultPathList);
        }
 private void monsterUpdate(object sender, MonsterUpdateEventArgs e)
 {
     PlayerSeen = canSeePlayer(e.engine.map.mGrid, e.playerPos);
     if (moves.Count == 0)
     {
         if (PlayerSeen)
         {
             JumpPointParam jParam = new JumpPointParam(e.engine.searchgrid, false, false);
             jParam.Reset(new GridPos(pos.X, pos.Y), new GridPos(e.playerPos.X, e.playerPos.Y));
             List <GridPos> resultPathList = JumpPointFinder.FindPath(jParam);
             resultPathList = JumpPointFinder.GetFullPath(resultPathList);
             if (moves.Count != 0)
             {
                 moves.Clear();
             }
             for (int i = 0; i < resultPathList.Count; i++)
             {
                 moves.Enqueue(new Vector2(resultPathList[i].x, resultPathList[i].y));
             }
         }
     }
     if (moves.Count != 0)
     {
         var dxdy = e.engine.map.getDxDy(pos, moves.Dequeue());
         if (!e.engine.checkEntity(pos, e.playerPos, dxdy.X, dxdy.Y))
         {
             move(dxdy.X, dxdy.Y);
         }
     }
     if (PlayerSeen == false)
     {
         Vector2 a = rndMoves[rnd.Next(rndMoves.Count)];
         if (e.engine.map.canMove(pos, a.X, a.Y))
         {
             move(a.X, a.Y);
         }
     }
     if (isPlayerNear(e.playerPos))
     {
         attack(e.engine.player);
     }
 }
Beispiel #25
0
        public List <Tile> FindPath(int sX, int sY, int eX, int eY)
        {
            GridPos start = new GridPos(sX, sY);
            GridPos end   = new GridPos(eX, eY);

            if (!_searchGrid.IsWalkableAt(end))
            {
                return(new List <Tile>());
            }
            jpParam.Reset(start, end, _searchGrid);
            List <GridPos> result  = JumpPointFinder.FindPath(jpParam);
            List <Tile>    result2 = new List <Tile>();

            foreach (GridPos gp in result)
            {
                result2.Add(_mapLayout[gp.x, gp.y]);
            }



            return(result2);
        }
    public List <Vector3> GetPath(Vector3 startLocation)
    {
        startPos = new GridPos((int)Mathf.Floor(startLocation.x), (int)Mathf.Floor(startLocation.y), (int)Mathf.Floor(startLocation.z));
        if (jpParam != null)
        {
            jpParam.Reset(startPos, endPos);
        }
        else
        {
            jpParam = new JumpPointParam(searchGrid, startPos, endPos, EndNodeUnWalkableTreatment.ALLOW, DiagonalMovement.IfAtLeastOneWalkable, HeuristicMode.EUCLIDEAN);
        }

        resultPathList = JumpPointFinder.FindPath(jpParam);
        List <Vector3> posList = new List <Vector3>();

        foreach (GridPos pos in resultPathList)
        {
            posList.Add(new Vector3(pos.x, pos.y, pos.z));
        }

        return(posList);
    }
Beispiel #27
0
        public static double CalculateFitness(Chromosome chromosome)
        {
            double fitness = 0;

            var board = chromosome2Board(chromosome);

            if (board[0, 0] != 2)
            {
                return(0);
            }
            if (board[boardSize / 2 - 1, boardSize / 2 - 1] != 0)
            {
                return(0);
            }



            BaseGrid searchGrid = new StaticGrid(boardSize, boardSize);

            searchGrid.SetWalkableAt(0, 0, true);

            for (var i = 0; i < boardSize; i++)
            {
                for (var j = 0; j < boardSize; j++)
                {
                    if (board[i, j] != 1)
                    {
                        searchGrid.SetWalkableAt(i, j, true);
                    }
                }
            }

            GridPos        startPos = new GridPos(0, 0);
            GridPos        endPos;
            JumpPointParam jpParam;
            var            resultPathLists = new List <List <GridPos> >();


            for (var i = 0; i < boardSize; i++)
            {
                for (var j = 0; j < boardSize; j++)
                {
                    if (board[i, j] != 1)
                    {
                        endPos  = new GridPos(i, j);
                        jpParam = new JumpPointParam(searchGrid, startPos, endPos);
                        resultPathLists.Add(JumpPointFinder.FindPath(jpParam));
                    }
                }
            }

            var counter = 0;

            foreach (var list in resultPathLists)
            {
                if (list.Count > 0)
                {
                    counter++;
                }
            }

            fitness = ((double)counter) / ((double)resultPathLists.Count);

            if (!fieldProportions(board) && (fitness > 0.9)) // && (fitness > 0.75))
            {
                fitness = fitness / 2;                       // fitness/2;// fitness *3/4;
            }
            return(fitness);
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            for (int resultTrav = 0; resultTrav < m_resultLine.Count; resultTrav++)
            {
                m_resultLine[resultTrav].Dispose();
            }
            m_resultLine.Clear();
            for (int resultTrav = 0; resultTrav < m_resultBox.Count; resultTrav++)
            {
                m_resultBox[resultTrav].Dispose();
            }
            m_resultBox.Clear();

            GridPos startPos = new GridPos();
            GridPos endPos   = new GridPos();

            for (int widthTrav = 0; widthTrav < width; widthTrav++)
            {
                for (int heightTrav = 0; heightTrav < height; heightTrav++)
                {
                    if (m_rectangles[widthTrav][heightTrav].boxType != BoxType.Wall)
                    {
                        searchGrid.SetWalkableAt(new GridPos(widthTrav, heightTrav), true);
                    }
                    else
                    {
                        searchGrid.SetWalkableAt(new GridPos(widthTrav, heightTrav), false);
                    }
                    if (m_rectangles[widthTrav][heightTrav].boxType == BoxType.Start)
                    {
                        startPos.x = widthTrav;
                        startPos.y = heightTrav;
                    }
                    if (m_rectangles[widthTrav][heightTrav].boxType == BoxType.End)
                    {
                        endPos.x = widthTrav;
                        endPos.y = heightTrav;
                    }
                }
            }
            jumpParam.DiagonalMovement = (DiagonalMovement)cbbJumpType.SelectedIndex;
            jumpParam.UseRecursive     = cbUseRecursive.Checked;
            jumpParam.Reset(startPos, endPos);
            List <GridPos> resultList = JumpPointFinder.FindPath(jumpParam);

            for (int resultTrav = 0; resultTrav < resultList.Count - 1; resultTrav++)
            {
                m_resultLine.Add(new GridLine(m_rectangles[resultList[resultTrav].x][resultList[resultTrav].y], m_rectangles[resultList[resultTrav + 1].x][resultList[resultTrav + 1].y]));
            }
            for (int widthTrav = 0; widthTrav < jumpParam.SearchGrid.width; widthTrav++)
            {
                for (int heightTrav = 0; heightTrav < jumpParam.SearchGrid.height; heightTrav++)
                {
                    if (jumpParam.SearchGrid.GetNodeAt(widthTrav, heightTrav) == null)
                    {
                        continue;
                    }
                    if (jumpParam.SearchGrid.GetNodeAt(widthTrav, heightTrav).isOpened)
                    {
                        ResultBox resultBox = new ResultBox(widthTrav * 20, heightTrav * 20 + 50, ResultBoxType.Opened);
                        m_resultBox.Add(resultBox);
                    }
                    if (jumpParam.SearchGrid.GetNodeAt(widthTrav, heightTrav).isClosed)
                    {
                        ResultBox resultBox = new ResultBox(widthTrav * 20, heightTrav * 20 + 50, ResultBoxType.Closed);
                        m_resultBox.Add(resultBox);
                    }
                }
            }
            this.Invalidate();
        }
        public static Path generatePath(Dimension _Dimension, Vector2 _StartPosition, Vector2 _EndPosition)
        {
            try
            {
                int var_SizeX = 20; //(int)Math.Abs(_StartPosition.X - _EndPosition.X)/16 + 2;//20;
                int var_SizeY = 20; //(int)Math.Abs(_StartPosition.Y - _EndPosition.Y)/16 + 2;//20;

                int var_StartX = (int)((_StartPosition.X % (Region.regionSizeX * Chunk.chunkSizeX * Block.BlockSize)) % (Chunk.chunkSizeX * Block.BlockSize) / Block.BlockSize);
                int var_StartY = (int)((_StartPosition.Y % (Region.regionSizeY * Chunk.chunkSizeY * Block.BlockSize)) % (Chunk.chunkSizeY * Block.BlockSize) / Block.BlockSize);

                int var_TargetX = (int)((_EndPosition.X % (Region.regionSizeX * Chunk.chunkSizeX * Block.BlockSize)) % (Chunk.chunkSizeX * Block.BlockSize) / Block.BlockSize);
                int var_TargetY = (int)((_EndPosition.Y % (Region.regionSizeY * Chunk.chunkSizeY * Block.BlockSize)) % (Chunk.chunkSizeY * Block.BlockSize) / Block.BlockSize);

                var_TargetX = var_TargetX - var_StartX + var_SizeX / 2;
                var_TargetY = var_TargetY - var_StartY + var_SizeY / 2;

                BaseGrid       searchGrid = new DynamicGridWPool(SingletonHolder <NodePool> .Instance);
                JumpPointParam jumpParam  = new JumpPointParam(searchGrid, true, true, false, HeuristicMode.EUCLIDEAN);

                GridPos startPos = new GridPos(var_SizeX / 2, var_SizeX / 2);
                GridPos endPos   = new GridPos(var_TargetX, var_TargetY);
                for (int x = 0; x < var_SizeX; x++)
                {
                    for (int y = 0; y < var_SizeY; y++)
                    {
                        int var_X = (int)_StartPosition.X + (-var_SizeX / 2 + x) * Block.BlockSize;
                        int var_Y = (int)_StartPosition.Y + (-var_SizeX / 2 + y) * Block.BlockSize;

                        Block var_Block      = _Dimension.getBlockAtCoordinate(new Vector3(var_X, var_Y, 0));
                        bool  var_IsWalkAble = false;
                        if (var_Block != null)
                        {
                            if (var_Block.IsWalkAble)
                            {
                                var_IsWalkAble = true;
                            }
                            else if (var_Block.Objects.Count > 0)
                            {
                                if (x == var_SizeX / 2 && y == var_SizeY / 2)
                                {
                                    var_IsWalkAble = true;
                                }
                                if (x == var_TargetX && y == var_TargetY)
                                {
                                    var_IsWalkAble = true;
                                }
                            }
                        }

                        searchGrid.SetWalkableAt(new GridPos(x, y), var_IsWalkAble);
                    }
                }
                jumpParam.CrossCorner        = true;
                jumpParam.CrossAdjacentPoint = false;
                jumpParam.UseRecursive       = false; // KP ;D
                jumpParam.Reset(startPos, endPos);
                List <GridPos> resultList = JumpPointFinder.FindPath(jumpParam);


                LinkedList <PathNode> var_PathNodes = new LinkedList <PathNode>();

                foreach (GridPos var_GridPos in resultList)
                {
                    PathNode var_PathNode = new PathNode();
                    var_PathNode.X = var_GridPos.x;
                    var_PathNode.Y = var_GridPos.y;

                    int var_X = (int)_StartPosition.X + (-var_SizeX / 2 + var_PathNode.X) * Block.BlockSize;
                    int var_Y = (int)_StartPosition.Y + (-var_SizeX / 2 + var_PathNode.Y) * Block.BlockSize;

                    Block var_Block = _Dimension.getBlockAtCoordinate(new Vector3(var_X, var_Y, 0));

                    var_PathNode.block = var_Block;

                    var_PathNodes.AddLast(var_PathNode);
                }


                /*for (int y = 0; y < var_SizeY; y++)
                 * {
                 *  for (int x = 0; x < var_SizeY; x++)
                 *  {
                 *      Console.ForegroundColor = ConsoleColor.White;
                 *      if (x == 10 && y == 10)
                 *      {
                 *          Console.ForegroundColor = ConsoleColor.Green;
                 *      }
                 *      foreach (PathNode var_PathNode in var_PathNodes)
                 *      {
                 *          if (var_PathNode.X == x && var_PathNode.Y == y)
                 *          {
                 *              Console.ForegroundColor = ConsoleColor.Red;
                 *          }
                 *      }
                 *      if (!searchGrid.IsWalkableAt(x,y))
                 *      {
                 *          Console.Write("x");
                 *      }
                 *      else
                 *      {
                 *          Console.Write("-");
                 *      }
                 *  }
                 *  Console.WriteLine();
                 * }*/

                Path var_Result = new Path(var_PathNodes);
                return(var_Result);
            }
            catch (Exception ex)
            {
                Logger.Logger.LogErr(ex.ToString());
            }

            return(null);
        }
Beispiel #30
0
        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (!IsValid())
            {
                return;
            }
            line_end_ = new Point(e.X, e.Y);
            CellPos end = new CellPos();

            cell_manager_.GetCell(new Vector3(e.X, 0, map_height_ - e.Y), out end.row, out end.col);
            CellPos start = new CellPos();

            cell_manager_.GetCell(new Vector3(line_start_.X, 0, map_height_ - line_start_.Y), out start.row, out start.col);

            if (e.Button == MouseButtons.Left)
            {
                switch (left_button_function_)
                {
                case FunctionType.kSetStaticBlock:
                {
                    int  row         = end.row;
                    int  col         = end.col;
                    byte obstacle    = byte.Parse(obstacleType.Text);
                    byte oldObstacle = cell_manager_.GetCellStatus(row, col);
                    cell_manager_.SetCellStatus(row, col, obstacle);

                    if (map_patch_parser_.Exist(row, col))
                    {
                        map_patch_parser_.Update(row, col, obstacle);
                    }
                    else
                    {
                        map_patch_parser_.Update(row, col, obstacle, oldObstacle);
                    }

                    UpdateObstacleGraph();
                }
                break;

                case FunctionType.kHitPoint:
                {
                    long           stTime = TimeUtility.Instance.GetElapsedTimeUs();
                    List <CellPos> result = cell_manager_.GetCellsCrossByLine(new Vector3(line_start_.X, 0, map_height_ - line_start_.Y),
                                                                              new Vector3(line_end_.X, 0, map_height_ - line_end_.Y));
                    long edTime = TimeUtility.Instance.GetElapsedTimeUs();
                    this.Text = "pos(" + line_start_.X + "," + line_start_.Y + "->" + line_end_.X + "," + line_end_.Y + ") GetCellsCrossByLine consume " + (edTime - stTime) + "us";
                    hit_points_.Clear();
                    foreach (CellPos pos in result)
                    {
                        hit_points_.Add(pos);
                    }
                }
                break;

                case FunctionType.kGetCell:
                {
                    byte obstacle = cell_manager_.GetCellStatus(end.row, end.col);
                    obstacleType.Text = obstacle.ToString();
                    this.Text         = "pos(" + e.X + "," + e.Y + ") cell(" + end.row + "," + end.col + ") obstacle:" + obstacle;
                }
                break;

                case FunctionType.kAddObj:
                {
                    TestSpaceObject obj = new TestSpaceObject(next_space_objid_);
                    ++next_space_objid_;
                    obj.SetPosition(new Vector3(e.X, 0, e.Y));
                    space_objs_.Add(obj);

                    prkdtree_.Clear();
                    kdtree_.Clear();
                    int objCt = space_objs_.Count;
                    if (objCt > 0)
                    {
                        ISpaceObject[] temp = new ISpaceObject[objCt];
                        for (int i = 0; i < objCt; ++i)
                        {
                            temp[i] = space_objs_[i];
                        }
                        long stTime1 = TimeUtility.Instance.GetElapsedTimeUs();
                        prkdtree_.Build(temp);
                        long edTime1 = TimeUtility.Instance.GetElapsedTimeUs();

                        long stTime2 = TimeUtility.Instance.GetElapsedTimeUs();
                        kdtree_.Build(temp);
                        long edTime2 = TimeUtility.Instance.GetElapsedTimeUs();

                        System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
                        stopWatch.Start();
                        cell_manager_.ClearDynamic();
                        foreach (ISpaceObject spaceObj in space_objs_)
                        {
                            List <CellPos> cells = cell_manager_.GetCellsInCircle(Transform(spaceObj.GetPosition()), 20);
                            foreach (CellPos cellpos in cells)
                            {
                                cell_manager_.SetCellStatus(cellpos.row, cellpos.col, BlockType.DYNAMIC_BLOCK);
                            }
                        }
                        stopWatch.Stop();


                        this.Text = "obj num " + objCt + " prkdtree consume " + (edTime1 - stTime1) + "us kdtree consume " + (edTime2 - stTime1) + "us dynmic consume " + (stopWatch.ElapsedTicks) + "ticks";
                    }
                }
                break;

                case FunctionType.kQueryObj:
                {
                    Vector3 pos   = new Vector3(e.X, 0, e.Y);
                    int     objCt = space_objs_.Count;
                    if (objCt > 0)
                    {
                        float radius  = float.Parse(queryRadius.Text);
                        long  stTime1 = TimeUtility.Instance.GetElapsedTimeUs();
                        selected_objs_.Clear();
                        prkdtree_.Query(pos, radius * scale, (float distSqr, PrKdTreeObject treeObj) =>
                            {
                                selected_objs_.Add(treeObj.SpaceObject as TestSpaceObject);
                            });
                        long edTime1 = TimeUtility.Instance.GetElapsedTimeUs();

                        long stTime2 = TimeUtility.Instance.GetElapsedTimeUs();
                        selected_objs2_.Clear();
                        kdtree_.Query(pos, radius * scale, (float distSqr, KdTreeObject treeObj) =>
                            {
                                selected_objs2_.Add(treeObj.SpaceObject as TestSpaceObject);
                            });
                        long edTime2 = TimeUtility.Instance.GetElapsedTimeUs();

                        this.Text = "obj num " + objCt + " query prkdtree " + selected_objs_.Count + " consume " + (edTime1 - stTime1) + "us query kdtree " + selected_objs2_.Count + " consume " + (edTime2 - stTime2) + "us";
                    }
                }
                break;
                }
            }
            else
            {
                if (e.Button == MouseButtons.Right && left_button_function_ == FunctionType.kSetStaticBlock)
                {
                    int row, col;
                    cell_manager_.GetCell(new Vector3(e.X, 0, e.Y), out row, out col);
                    byte oldObstacle = cell_manager_.GetCellStatus(row, col);
                    byte obstacle    = BlockType.NOT_BLOCK;
                    cell_manager_.SetCellStatus(end.row, end.col, obstacle);

                    if (map_patch_parser_.Exist(row, col))
                    {
                        map_patch_parser_.Update(row, col, obstacle);
                    }
                    else
                    {
                        map_patch_parser_.Update(row, col, obstacle, oldObstacle);
                    }

                    UpdateObstacleGraph();
                }
                else
                {
                    long stTime = TimeUtility.Instance.GetElapsedTimeUs();
                    found_path_ = spatial_system_.FindPathWithCellMap(new Vector3(line_start_.X, 0, map_height_ - line_start_.Y), new Vector3(line_end_.X, 0, map_height_ - line_end_.Y));
                    long edTime = TimeUtility.Instance.GetElapsedTimeUs();

                    long stTime2 = TimeUtility.Instance.GetElapsedTimeUs();
                    int  stRow, stCol, edRow, edCol;
                    spatial_system_.GetCell(new Vector3(line_start_.X, 0, map_height_ - line_start_.Y), out stRow, out stCol);
                    spatial_system_.GetCell(new Vector3(line_end_.X, 0, map_height_ - line_end_.Y), out edRow, out edCol);
                    //List<CellPos> path = new List<CellPos>();
                    //tree_cache_finder_.GetPath(new CellPos(stRow, stCol), new CellPos(edRow, edCol), path);
                    found_path_ = jump_point_finder_.FindPath(new CellPos(stRow, stCol), new CellPos(edRow, edCol));
                    long edTime2 = TimeUtility.Instance.GetElapsedTimeUs();

                    long stTime3 = TimeUtility.Instance.GetElapsedTimeUs();
                    found_path_ = spatial_system_.FindPath(new Vector3(line_start_.X, 0, map_height_ - line_start_.Y), new Vector3(line_end_.X, 0, map_height_ - line_end_.Y));
                    long edTime3 = TimeUtility.Instance.GetElapsedTimeUs();

                    /*//
                     * found_path_.Clear();
                     * if (path.Count > 0) {
                     * foreach (CellPos p in path) {
                     * found_path_.Add(spatial_system_.GetCellCenter(p.row, p.col));
                     * }
                     * }
                     * ///*/
                    this.Text = "findpath:" + new Vector2(line_start_.X, map_height_ - line_start_.Y).ToString() + " to " + new Vector2(line_end_.X, map_height_ - line_end_.Y).ToString() + " consume " + (edTime - stTime) / 1000.0f + "ms no preprocess consume " + (edTime2 - stTime2) / 1000.0f + "ms triangulation network consume " + (edTime3 - stTime3) / 1000.0f + "ms";
                }
            }
            is_mouse_down_ = false;
            key_hit_       = 0;
        }