コード例 #1
0
        public static MemberInfo GetMemberInfo(this PathToken token, object source)
        {
            IPathNode node     = token.Current;
            var       typeNode = node as TypeNode;

            if (typeNode != null)
            {
                return(null);
            }

            var indexedNode = node as IndexedNode;

            if (indexedNode != null)
            {
                return(source.GetType().GetProperty("Item"));
            }

            var memberNode = node as MemberNode;

            if (memberNode == null)
            {
                return(null);
            }

            var memberInfo = memberNode.MemberInfo;

            if (memberInfo == null)
            {
                memberInfo = source.GetType().FindFirstMemberInfo(memberNode.Name);
            }

            return(memberInfo);
        }
コード例 #2
0
ファイル: PathingAStar.cs プロジェクト: andrewstarnes/wwtd2
        /// <summary>
        /// Called when a request is about to be processed.
        /// </summary>
        /// <param name="start">The start node.</param>
        /// <param name="actualStart">The actual start node in case actual start is blocked.</param>
        protected override void OnStart(IPathNode start, IPathNode actualStart)
        {
            _openSet.Clear();

            //Reset all g's on all nodes marking them not expanded
            _expandedSet.Apply(c => c.g = 0);
            _expandedSet.Clear();
            _closestNode = start;

            //Initialize and add the start node. Since no expanded set is used start g must be initialized to a small > 0  value to mark it as expanded
            //Since the start node will never reenter the open set, there is no need to initialize the h and f values.
            start.g = 1;
            start.h = this.costProvider.GetHeuristic(start, this.goal);
            start.predecessor = actualStart;

            _openSet.Add(start);
            _expandedSet.Add(start);

            if (actualStart != null)
            {
                actualStart.g = 1;
                actualStart.predecessor = null;
                _expandedSet.Add(actualStart);
            }

            _unitProps = this.currentRequest.requesterProperties;
            _unitAttributes = _unitProps.attributes;
            _preventDiagonalMoves = this.currentRequest.pathFinderOptions.preventDiagonalMoves;
            _cutCorners = this.currentRequest.pathFinderOptions.allowCornerCutting;
        }
コード例 #3
0
        public void Update(IPathNode node, float priority)
        {
            if (node.HeapIndex == NotInHeap)
            {
                return;
            }

            bool flag = node.Priority > priority;

            node.Priority = priority;
            if (node.HeapIndex == Count)
            {
                AdjustUp(node);
            }

            int parent = node.HeapIndex >> 1;

            if (!flag)
            {
                AdjustDown(node);
            }
            else
            {
                AdjustUp(node);
            }
        }
コード例 #4
0
        public IPathNode Dequeue()
        {
            if (m_FirstFree <= 1)
            {
                return(null);
            }

            IPathNode retMe = m_Nodes[1];

            if (m_FirstFree == 2)
            {
                m_Nodes[--m_FirstFree] = null;
                return(retMe);
            }

            IPathNode formerLastNode = m_Nodes[--m_FirstFree];

            m_Nodes[1] = formerLastNode;
            formerLastNode.HeapIndex = 1;
            m_Nodes[m_FirstFree]     = null;

            AdjustDown(formerLastNode);

            return(retMe);
        }
コード例 #5
0
        /// <summary>
        /// Protected constructor for the abstract class.
        /// </summary>
        /// <param name="httpClientUtil">A configured <see cref="HttpClientUtil"/> instance for performing web requests</param>
        /// <param name="featureTypeInfo">A <see cref="WfsFeatureTypeInfo"/> instance providing metadata of the featuretype to query</param>
        protected GeometryFactory(HttpClientUtil httpClientUtil, WfsFeatureTypeInfo featureTypeInfo)
        {
            FeatureTypeInfo = featureTypeInfo;
            _httpClientUtil = httpClientUtil;
            CreateReader(httpClientUtil);

            try
            {
                if (featureTypeInfo.LabelFields != null)
                {
                    var pathNodes = new IPathNode[featureTypeInfo.LabelFields.Count];
                    for (var i = 0; i < pathNodes.Length; i++)
                    {
                        pathNodes[i] = new PathNode(FeatureTypeInfo.FeatureTypeNamespace, featureTypeInfo.LabelFields[i], (NameTable)XmlReader.NameTable);
                    }
                    LabelNode = new AlternativePathNodesCollection(pathNodes);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("An exception occured while initializing the label path node! " + ex.Message);
                throw;
            }

            InitializePathNodes();
            InitializeSeparators();
        }
コード例 #6
0
ファイル: Cell.cs プロジェクト: rmcmrz/unity-rl
 void IPathNode.UnregisterVirtualNeighbour(IPathNode neighbour)
 {
     if (_virtualNeighbours != null)
     {
         _virtualNeighbours.Remove(neighbour);
     }
 }
コード例 #7
0
ファイル: Unit.cs プロジェクト: v-free/hexMap
    protected IEnumerator MoveWaiter(IEnumerable <IPathNode <HexNode> > path, IReady controller)
    {
        if (path == null)
        {
            Debug.Log("Can't find path!!");
            yield break;
        }

        IEnumerator <IPathNode <HexNode> > enumerator = path.GetEnumerator();

        enumerator.MoveNext(); // Skips first;
        IPathNode <HexNode> lastNode = enumerator.Current;

        while (enumerator.MoveNext())
        {
            IPathNode <HexNode> node = enumerator.Current;
            float cost = node.GetCost();

            if (cost <= currentActionPoints)
            {
                yield return(Step(node));
            }
            else
            {
                break;
            }

            lastNode = enumerator.Current;
        }

        currentActionPoints -= lastNode.GetCost();

        controller.Ready();
    }
コード例 #8
0
    public List <TransportRouteElement> FindPath(TransportVehicleData transportVehicleData,
                                                 List <TransportRouteElement> transportRouteElements)
    {
        AbstractPathFindingAlgorithm _pathFinder = _pathFindingAlgorithms[transportVehicleData.PathType];

        foreach (TransportRouteElement transportRouteElement in transportRouteElements)
        {
            IPathNode pathNode = transportRouteElement.FromNode as IPathNode;
            Path      path;
            if (pathNode != null)
            {
                path = pathNode.PathTo(transportRouteElement.ToNode);
                if (path == null)
                {
                    path = _pathFinder.FindPath(transportRouteElement.FromNode, transportRouteElement.ToNode);
                    pathNode.AddPath(transportRouteElement.ToNode, path);
                }
            }
            else
            {
                path = _pathFinder.FindPath(transportRouteElement.FromNode, transportRouteElement.ToNode);
            }
            transportRouteElement.Path = path;
        }
        return(transportRouteElements);
    }
コード例 #9
0
        /// <summary>
        /// Return a list of path nodes from the start tile to the end tile ( Use RpgMapHelper class to get the tile index )
        /// </summary>
        /// <param name="startIdx"></param>
        /// <param name="endIdx"></param>
        /// <returns></returns>
        public IEnumerator GetRouteFromToAsync(int startIdx, int endIdx)
        {
            IPathNode start = GetMapTileNode(startIdx);

            EndNode = GetMapTileNode(endIdx);
            return(m_pathFinding.ComputePathAsync(start, EndNode));
        }
コード例 #10
0
        /// <summary>
        /// Protected constructor for the abstract class.
        /// </summary>
        /// <param name="httpClientUtil">A configured <see cref="HttpClientUtil"/> instance for performing web requests</param>
        /// <param name="featureTypeInfo">A <see cref="WfsFeatureTypeInfo"/> instance providing metadata of the featuretype to query</param>
        /// <param name="labelInfo">A FeatureDataTable for labels</param>
        protected GeometryFactory(HttpClientUtil httpClientUtil, WfsFeatureTypeInfo featureTypeInfo,
            IFeatureCollection labelInfo)
        {
            _FeatureTypeInfo = featureTypeInfo;
            Factory = featureTypeInfo.Factory;
            _HttpClientUtil = httpClientUtil;
            createReader(httpClientUtil);

            try
            {
                if (labelInfo != null)
                {
                    _LabelInfo = labelInfo;
                    _LabelNode = new PathNode(_FeatureTypeInfo.FeatureTypeNamespace, _LabelInfo.AttributesDefinition[0].AttributeName,
                                              (NameTable) _XmlReader.NameTable);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("An exception occured while initializing the label path node!");
                throw ex;
            }

            initializePathNodes();
            initializeSeparators();
        }
コード例 #11
0
        /// <summary>
        /// Return a list of path nodes from the start tile to the end tile ( Use RpgMapHelper class to get the tile index )
        /// </summary>
        /// <param name="startIdx"></param>
        /// <param name="endIdx"></param>
        /// <returns></returns>
        public IEnumerator GetRouteFromToAsync(Vector2 startPos, Vector2 endPos)
        {
            IPathNode start = GetMapTileNode(startPos);

            EndNode = GetMapTileNode(endPos);
            return(m_pathFinding.ComputePathAsync(start, EndNode, AllowBlockedDestination));
        }
コード例 #12
0
        private int GetHeuristic(IPathNode n, IPathNode current)
        {
            var portal = n as IPortalNode;

            if (portal != null)
            {
                //Since portals are co-positioned with the nodes from which they are accessed, they simply have the same h as their predecessor
                //But since portals.predecessor.h is error prone (predecessor must have been set before calling this) we pass in current.
                return(current.h);
            }

            var best = this.costProvider.GetHeuristic(n, this.goal);

            //iterate over relevant portals to see if that gets a better score
            var portals = n.parent.shortcutPortals;

            for (int i = 0; i < portals.Count; i++)
            {
                var p = portals[i];
                if (p.IsWalkableWithClearance(_unitProps))
                {
                    var h = p.GetHeuristic(n, this.goal, this.costProvider);
                    if (h < best)
                    {
                        best = h;
                    }
                }
            }

            return(best);
        }
コード例 #13
0
        /// <summary>
        /// Return a list of path nodes from the start tile to the end tile
        /// </summary>
        /// <param name="startIdx"></param>
        /// <param name="endIdx"></param>
        /// <returns></returns>
        public IEnumerator GetRouteFromToAsync(Vector2 startPos, Vector2 endPos)
        {
            IPathNode start = GetMapTileNode(startPos);

            EndNode = GetMapTileNode(endPos);
            return(m_pathFinding.ComputePathAsync(start, EndNode, MaxDistance > 0? MaxDistance : int.MaxValue));
        }
コード例 #14
0
ファイル: UnitController.cs プロジェクト: v-free/hexMap
    private void HighlightPath(IEnumerable <IPathNode <HexNode> > path)
    {
        if (path == null)
        {
            return;
        }

        Dictionary <ITile, bool> tiles = new Dictionary <ITile, bool>();

        IEnumerator <IPathNode <HexNode> > enumerator = path.GetEnumerator();

        //enumerator.MoveNext(); // Skips first //
        //tiles.Add(enumerator.Current.GetNode().Tile, true);

        while (enumerator.MoveNext())
        {
            IPathNode <HexNode> node    = enumerator.Current;
            HexNode             hexNode = node.GetNode();
            ITile tile = hexNode.Tile;

            if (tiles.ContainsKey(tile))
            {
                continue;
            }
            tiles.Add(tile, true);

            Vector3    position = new Vector3(tile.PosX, tile.PosY + 0.05f, tile.PosZ);
            Quaternion rotation = Quaternion.Euler(90, hexNode.Direction.DirectionRotation() - 90, 0);

            GameObject highlight = Instantiate(pathArrowPrefab, position, rotation, transform);
            highlightedPath.Add(highlight);
            lastPathArrowRotation = rotation;
        }
    }
コード例 #15
0
ファイル: GeometryFactories.cs プロジェクト: lishxi/_SharpMap
        /// <summary>
        /// Protected constructor for the abstract class.
        /// </summary>
        /// <param name="httpClientUtil">A configured <see cref="HttpClientUtil"/> instance for performing web requests</param>
        /// <param name="featureTypeInfo">A <see cref="WfsFeatureTypeInfo"/> instance providing metadata of the featuretype to query</param>
        /// <param name="labelInfo">A FeatureDataTable for labels</param>
        protected GeometryFactory(HttpClientUtil httpClientUtil, WfsFeatureTypeInfo featureTypeInfo,
                                  FeatureDataTable labelInfo)
        {
            _FeatureTypeInfo = featureTypeInfo;
            Factory = featureTypeInfo.Factory;
            _httpClientUtil = httpClientUtil;
            createReader(httpClientUtil);

            try
            {
                if (labelInfo != null)
                {
                    _LabelInfo = labelInfo;
                    var pathNodes = new IPathNode[labelInfo.Columns.Count];
                    for (var i = 0; i < pathNodes.Length; i++)
                    {
                        pathNodes[i] = new PathNode(_FeatureTypeInfo.FeatureTypeNamespace, _LabelInfo.Columns[i].ColumnName, (NameTable)_XmlReader.NameTable);
                    }
                    _LabelNode = new AlternativePathNodesCollection(pathNodes);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("An exception occured while initializing the label path node!");
                throw ex;
            }

            initializePathNodes();
            initializeSeparators();
        }
コード例 #16
0
ファイル: AStarPath.cs プロジェクト: CJRutter/LudumDare45
        public void Start(IPathNode start, IPathNode goal, object state, bool cacheGoalNodes)
        {
            this.start          = start;
            this.goal           = goal;
            this.state          = state;
            this.cacheGoalNodes = cacheGoalNodes;
            SearchSteps         = 0;
            MaxCostReached      = false;

            Clear();

            if (!cacheGoalNodes || this.goal != goal)
            {
                goalNodeCache.Clear();
            }

            currentNode = GetPathNodeWrapper(start);

            if (start.NodeId == goal.NodeId)
            {
                Complete  = true;
                GoalFound = true;
                return;
            }

            currentNode.HeuristicValue = heuristic(ref currentNode.Node, ref goal);

            Complete  = false;
            GoalFound = false;
        }
コード例 #17
0
        /// <summary>
        /// Called when a request is about to be processed.
        /// </summary>
        /// <param name="start">The start node.</param>
        /// <param name="actualStart">The actual start node in case actual start is blocked.</param>
        protected override void OnStart(IPathNode start, IPathNode actualStart)
        {
            _openSet.Clear();

            //Reset all g's on all nodes marking them not expanded
            _expandedSet.Apply(c => c.g = 0);
            _expandedSet.Clear();
            _closestNode = start;

            //Initialize and add the start node. Since no expanded set is used start g must be initialized to a small > 0  value to mark it as expanded
            //Since the start node will never reenter the open set, there is no need to initialize the h and f values.
            start.g           = 1;
            start.h           = this.costProvider.GetHeuristic(start, this.goal);
            start.predecessor = actualStart;

            _openSet.Add(start);
            _expandedSet.Add(start);

            if (actualStart != null)
            {
                actualStart.g           = 1;
                actualStart.predecessor = null;
                _expandedSet.Add(actualStart);
            }

            _unitProps            = this.currentRequest.requesterProperties;
            _unitAttributes       = _unitProps.attributes;
            _preventDiagonalMoves = this.currentRequest.pathFinderOptions.preventDiagonalMoves;
            _cutCorners           = this.currentRequest.pathFinderOptions.allowCornerCutting;
        }
コード例 #18
0
        /// <summary>
        /// 経路探索を行う
        /// 結果はRouteに入る
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        public void SearchRoute(IPathNode from, IPathNode to)
        {
            Route = new List <IPathNode>();
            if (from == to)
            {
                Completed = true;
                return;
            }

            AStarNode root = new AStarNode(from, null, 0, to);


            AStarNode goal = SearchProcess(root);

            if (goal == null)
            {
                Completed = true;
                return;
            }


            AStarNode parent = goal;

            while (parent != null)
            {
                Route.Add(parent.Node);
                // Debug.Log(parent);
                parent = parent.Parent;
            }
            Route.Reverse();

            Completed = true;
        }
コード例 #19
0
ファイル: Provider.cs プロジェクト: peter-hoch/studioshell
 private void WritePathNode(string nodeContainerPath, IPathNode node)
 {
     if (null != node)
     {
         WriteItemObject(node.Item, MakePath(nodeContainerPath, node.Name), node.IsCollection);
     }
 }
コード例 #20
0
ファイル: Provider.cs プロジェクト: peter-hoch/studioshell
        void CopyItem(string path, INodeFactory sourceNode, string copyPath, bool recurse)
        {
            ICopyItem copyItem = GetCopyItem(sourceNode);

            if (null == copyItem)
            {
                WriteCmdletNotSupportedAtNodeError(path, ProviderCmdlet.CopyItem, CopyItemNotSupportedErrorID);
                return;
            }

            if (!ShouldProcess(path, ProviderCmdlet.CopyItem))
            {
                return;
            }

            try
            {
                IPathNode node = DoCopyItem(path, copyPath, recurse, copyItem);
                WritePathNode(copyPath, node);
            }
            catch (Exception e)
            {
                WriteGeneralCmdletError(e, CopyItemInvokeErrorID, path);
            }
        }
コード例 #21
0
        /// <summary>
        /// Protected constructor for the abstract class.
        /// </summary>
        /// <param name="httpClientUtil">A configured <see cref="HttpClientUtil"/> instance for performing web requests</param>
        /// <param name="featureTypeInfo">A <see cref="WfsFeatureTypeInfo"/> instance providing metadata of the featuretype to query</param>
        /// <param name="labelInfo">A FeatureDataTable for labels</param>
        protected GeometryFactory(HttpClientUtil httpClientUtil, WfsFeatureTypeInfo featureTypeInfo,
                                  FeatureDataTable labelInfo)
        {
            _FeatureTypeInfo = featureTypeInfo;
            Factory          = featureTypeInfo.Factory;
            _httpClientUtil  = httpClientUtil;
            createReader(httpClientUtil);

            try
            {
                if (labelInfo != null)
                {
                    _LabelInfo = labelInfo;
                    var pathNodes = new IPathNode[labelInfo.Columns.Count];
                    for (var i = 0; i < pathNodes.Length; i++)
                    {
                        pathNodes[i] = new PathNode(_FeatureTypeInfo.FeatureTypeNamespace, _LabelInfo.Columns[i].ColumnName, (NameTable)_XmlReader.NameTable);
                    }
                    _LabelNode = new AlternativePathNodesCollection(pathNodes);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("An exception occured while initializing the label path node!");
                throw ex;
            }

            initializePathNodes();
            initializeSeparators();
        }
コード例 #22
0
        public override void InitPath()
        {
            //Setup Startnode's Info
            IPathNode startPNode = Handler.GetPathnode(m_StartNode);

            startPNode.Node   = m_StartNode;
            startPNode.PathID = Handler.PathID;
            startPNode.Parent = null;
            startPNode.Cost   = 0;
            startPNode.G      = 0;
            startPNode.H      = CalculateHScore(m_StartNode);

            startPNode.Open(this, Handler);
            m_SearchIndex++;

            PartialBestNode = startPNode;

            if (Handler.Heap.IsEmpty)
            {
                if (CalculatePartial)
                {
                    CompleteState = PathCompleteState.PartialComplete;
                    Trace(PartialBestNode);
                }
                else
                {
                    //Todo: Error
                }
            }

            CurNode = Handler.Heap.Dequeue();
        }
コード例 #23
0
        /// <inheritdoc/>
        protected override void PerformExecute(IModel model, IPathNode item)
        {
            ArgumentValidator.EnsureArgumentNotNull(item, "item");
            var node = (Node)item;

            node.Remove();
        }
コード例 #24
0
 /// <inheritdoc/>
 protected override void PerformExecute(IModel model, IPathNode item)
 {
     foreach (var action in actions)
     {
         action.Execute(model);
     }
 }
コード例 #25
0
        /// <summary>
        /// Protected constructor for the abstract class.
        /// </summary>
        /// <param name="httpClientUtil">A configured <see cref="HttpClientUtil"/> instance for performing web requests</param>
        /// <param name="featureTypeInfo">A <see cref="WfsFeatureTypeInfo"/> instance providing metadata of the featuretype to query</param>
        /// <param name="labelInfo">A FeatureDataTable for labels</param>
        protected GeometryFactory(HttpClientUtil httpClientUtil, WfsFeatureTypeInfo featureTypeInfo,
                                  FeatureDataTable labelInfo)
        {
            _FeatureTypeInfo = featureTypeInfo;
            _HttpClientUtil  = httpClientUtil;
            createReader(httpClientUtil);

            try
            {
                if (labelInfo != null)
                {
                    _LabelInfo = labelInfo;
                    _LabelNode = new PathNode(_FeatureTypeInfo.FeatureTypeNamespace, _LabelInfo.Columns[0].ColumnName,
                                              (NameTable)_XmlReader.NameTable);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("An exception occured while initializing the label path node!");
                throw ex;
            }

            initializePathNodes();
            initializeSeparators();
        }
コード例 #26
0
ファイル: PathNodeInfo.cs プロジェクト: yurko7/SHiPS
 internal void Set(string path, IPathNode node, List <IPathNode> children)
 {
     Path = path;
     PathWithNoEndSlash = path?.TrimEnd('/', '\\');
     NodeObject         = node;
     Children           = children;
 }
コード例 #27
0
 public virtual void Reset()
 {
     g      = 0;
     h      = 0;
     PathID = 0;
     Parent = null;
     Node   = null;
 }
コード例 #28
0
ファイル: PathRouteNode.cs プロジェクト: GQBrendel/heroes
        private bool isWithinDistanceOfNode(IPathNode node, Transform transform)
        {
            // Calculate the distance to the node
            float distance = Vector3.Distance(transform.position, node.WorldPosition);

            // Check if we are within tolerance
            return(distance < distanceTolerance);
        }
コード例 #29
0
ファイル: DiagonalDistance.cs プロジェクト: jdeter14/game1
        /// <summary>
        /// Gets the heuristic.
        /// </summary>
        /// <param name="current">The current node.</param>
        /// <param name="goal">The goal node.</param>
        /// <returns>
        /// The heuristic
        /// </returns>
        public override int GetHeuristic(IPathNode current, IPathNode goal)
        {
            var dx = (int)Math.Abs(current.position.x - goal.position.x);
            var dz = (int)Math.Abs(current.position.z - goal.position.z);
            var dy = (int)Math.Abs(current.position.y - goal.position.y);

            return (this.baseMoveCost * (dx + dz + dy)) + ((this.diagonalMoveCost - (2 * this.baseMoveCost)) * Math.Min(dx, dz));
        }
コード例 #30
0
        private bool isWithinDistanceOfNode(IPathNode node, Vector2 position)
        {
            // Calculate the distance to the node
            float distance = Vector2.DistanceSquare(position, node.WorldPosition);

            // Check if we are within tolerance
            return(distance < distanceTolerance * distanceTolerance);
        }
コード例 #31
0
ファイル: EuclideanDistance.cs プロジェクト: jdeter14/game1
        /// <summary>
        /// Gets the move cost.
        /// </summary>
        /// <param name="current">The current node.</param>
        /// <param name="other">The other node.</param>
        /// <returns>
        /// The move cost
        /// </returns>
        public override int GetMoveCost(IPathNode current, IPathNode other)
        {
            var dx = (int)(current.position.x - other.position.x);
            var dz = (int)(current.position.z - other.position.z);
            var dy = (int)(current.position.y - other.position.y);

            return this.baseMoveCost * (int)Math.Sqrt((dx * dx) + (dz * dz) + (dy * dy));
        }
コード例 #32
0
ファイル: EuclideanDistance.cs プロジェクト: jdeter14/game1
        /// <summary>
        /// Gets the heuristic.
        /// </summary>
        /// <param name="current">The current node.</param>
        /// <param name="goal">The goal node.</param>
        /// <returns>
        /// The heuristic
        /// </returns>
        public override int GetHeuristic(IPathNode current, IPathNode goal)
        {
            var dx = (int)(current.position.x - goal.position.x);
            var dz = (int)(current.position.z - goal.position.z);
            var dy = (int)(current.position.y - goal.position.y);

            return this.baseMoveCost * (int)Math.Sqrt((dx * dx) + (dz * dz) + (dy * dy));
        }
コード例 #33
0
ファイル: AStarNode.cs プロジェクト: tyotsu/AntDiary
        // public AStarNodeStatus status;

        public AStarNode(IPathNode node, AStarNode parent, float cost, IPathNode to)
        {
            Node          = node;
            Parent        = parent;
            Cost          = cost;
            DestNode      = to;
            HeuristicCost = Vector2.Distance(node.WorldPosition, to.WorldPosition);
        }
コード例 #34
0
ファイル: ManhattanDistance.cs プロジェクト: jdeter14/game1
        /// <summary>
        /// Gets the heuristic.
        /// </summary>
        /// <param name="current">The current.</param>
        /// <param name="goal">The goal.</param>
        /// <returns>The heuristic</returns>
        public override int GetHeuristic(IPathNode current, IPathNode goal)
        {
            var dx = (int)Math.Abs(current.position.x - goal.position.x);
            var dz = (int)Math.Abs(current.position.z - goal.position.z);
            var dy = (int)Math.Abs(current.position.y - goal.position.y);

            return this.baseMoveCost * (dx + dz + dy);
        }
コード例 #35
0
ファイル: ManhattanDistance.cs プロジェクト: jdeter14/game1
        /// <summary>
        /// Gets the move cost.
        /// </summary>
        /// <param name="current">The current node.</param>
        /// <param name="other">The other node.</param>
        /// <returns>
        /// The move cost
        /// </returns>
        public override int GetMoveCost(IPathNode current, IPathNode other)
        {
            var dx = (int)Math.Abs(current.position.x - other.position.x);
            var dz = (int)Math.Abs(current.position.z - other.position.z);
            var dy = (int)Math.Abs(current.position.y - other.position.y);

            return this.baseMoveCost * (dx + dz + dy);
        }
コード例 #36
0
ファイル: MapPathFinding.cs プロジェクト: FrankOrtiz/ProtoRun
        /// <summary>
        /// Return a list of path nodes from the start tile to the end tile ( Use RpgMapHelper class to get the tile index )
        /// </summary>
        /// <param name="startIdx"></param>
        /// <param name="endIdx"></param>
        /// <returns></returns>
        public IEnumerator GetRouteFromToAsync(Vector2 startPos, Vector2 endPos)
        {
            ClearNodeDictionary();
            IPathNode start = GetMapTileNode(startPos);

            EndNode = GetMapTileNode(endPos);
            return(m_pathFinding.ComputePathAsync(start, EndNode));
        }
コード例 #37
0
ファイル: Provider.cs プロジェクト: wangzq/bips
 private void WritePathNode(string nodeContainerPath, IPathNode node)
 {
     if (null != node)
     {
         nodeContainerPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(nodeContainerPath);
         WriteItemObject(node.Item, MakePath(nodeContainerPath, node.Name), node.IsCollection);
     }
 }
コード例 #38
0
ファイル: AStarPath.cs プロジェクト: CJRutter/LudumDare45
 private PathNodeWrapper GetPathNodeWrapper(IPathNode node)
 {
     if (nodes.ContainsKey(node.NodeId))
     {
         return(nodes[node.NodeId]);
     }
     return(WrapPathNode(node));
 }
コード例 #39
0
        /// <summary>
        /// Gets the move cost.
        /// </summary>
        /// <param name="current">The current node.</param>
        /// <param name="other">The other node.</param>
        /// <returns>
        /// The move cost
        /// </returns>
        public virtual int GetMoveCost(IPathNode current, IPathNode other)
        {
            var dx = (int)Math.Abs(current.position.x - other.position.x);
            var dz = (int)Math.Abs(current.position.z - other.position.z);
            var dy = (int)Math.Abs(current.position.y - other.position.y);

            //Its not accurate to account for the height difference by simply adding it, but it's faster and since it is the same for all it's fine.
            if (dx > 0 && dz > 0)
            {
                return (dx * _cellDiagonalMoveCost) + (dy * _cellMoveCost);
            }

            return (Math.Max(dx, dz) + dy) * _cellMoveCost;
        }
コード例 #40
0
        private IPathNode Jump(IPathNode current, VectorXZ direction)
        {
            var next = current.GetNeighbour(direction.x, direction.z);

            if (next == null || !next.isWalkableFrom(current, _unitProps))
            {
                return null;
            }

            if (next == this.goal)
            {
                return next;
            }

            if (HasForcedNeighbour(next, direction))
            {
                return next;
            }

            if (direction.x != 0 && direction.z != 0)
            {
                if (Jump(next, new VectorXZ(direction.x, 0)) != null || Jump(next, new VectorXZ(0, direction.z)) != null)
                {
                    return next;
                }

                //If both or either neighbours (depending on cut corner setting) in a diagonal move are blocked, the diagonal neighbour is not reachable since the passage is blocked
                var n1 = next.GetNeighbour(direction.x, 0);
                var n2 = next.GetNeighbour(0, direction.z);

                bool jumpOn = _cutCorners ? ((n1 != null && n1.isWalkableFrom(current, _unitProps)) || (n2 != null && n2.isWalkableFrom(current, _unitProps))) : ((n1 != null && n1.isWalkableFrom(current, _unitProps)) && (n2 != null && n2.isWalkableFrom(current, _unitProps)));
                if (jumpOn)
                {
                    return Jump(next, direction);
                }
            }
            else
            {
                return Jump(next, direction);
            }

            return null;
        }
コード例 #41
0
        /// <summary>
        /// Protected constructor for the abstract class.
        /// </summary>
        /// <param name="httpClientUtil">A configured <see cref="HttpClientUtil"/> instance for performing web requests</param>
        /// <param name="featureTypeInfo">A <see cref="WfsFeatureTypeInfo"/> instance providing metadata of the featuretype to query</param>
        protected GeometryFactory(HttpClientUtil httpClientUtil, WfsFeatureTypeInfo featureTypeInfo)
        {
            FeatureTypeInfo = featureTypeInfo;
            _httpClientUtil = httpClientUtil;
            CreateReader(httpClientUtil);

            try
            {
                if (featureTypeInfo.LableField != null)
                {
                    LabelNode = new PathNode(FeatureTypeInfo.FeatureTypeNamespace, featureTypeInfo.LableField, 
                                              (NameTable) XmlReader.NameTable);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("An exception occured while initializing the label path node! " + ex.Message);
                throw;
            }

            InitializePathNodes();
            InitializeSeparators();
        }
コード例 #42
0
ファイル: GeometryFactories.cs プロジェクト: lishxi/_SharpMap
 /// <summary>
 /// Protected constructor for the abstract class.
 /// </summary>
 /// <param name="httpClientUtil">A configured <see cref="HttpClientUtil"/> instance for performing web requests</param>
 /// <param name="featureTypeInfo">A <see cref="WfsFeatureTypeInfo"/> instance providing metadata of the featuretype to query</param>
 /// <param name="labelInfo">A FeatureDataTable for labels</param>
 protected GeometryFactory(HttpClientUtil httpClientUtil, WfsFeatureTypeInfo featureTypeInfo, FeatureDataTable labelInfo)
 {
     _FeatureTypeInfo = featureTypeInfo;
     _HttpClientUtil = httpClientUtil;
     createReader(httpClientUtil);
     
     try
     {
         if (labelInfo != null)
         {
             _LabelInfo = labelInfo;
             _LabelNode = new PathNode(_FeatureTypeInfo.FeatureTypeNamespace, _LabelInfo.Columns[0].ColumnName, (NameTable)_XmlReader.NameTable);
         }
     }
     catch(Exception ex)
     {
         System.Diagnostics.Trace.TraceError("An exception occured while initializing the label path node!");
         throw ex;
     }
    
     initializePathNodes();
     initializeSeparators();
 }
コード例 #43
0
        /// <summary>
        /// Gets the walkable successors of the specified node.
        /// </summary>
        /// <param name="current">The current node.</param>
        /// <param name="successorArray">The array to fill with successors.</param>
        /// <returns>
        /// All walkable successors of the node.
        /// </returns>
        protected override void GetWalkableSuccessors(IPathNode current, DynamicArray<IPathNode> successorArray)
        {
            _neighbours.Clear();

            if (current.predecessor == null)
            {
                current.GetWalkableNeighbours(_neighbours, _unitProps, _cutCorners, false);
            }
            else if (current is IPortalNode)
            {
                current.GetWalkableNeighbours(successorArray, _unitProps, _cutCorners, false);
                return;
            }
            else
            {
                var dirFromPredecessor = current.predecessor.GetDirectionTo(current);
                PruneNeighbours(current, dirFromPredecessor);
            }

            var neighbourCount = _neighbours.count;
            for (int i = 0; i < neighbourCount; i++)
            {
                var n = _neighbours[i];
                if (n == null)
                {
                    break;
                }

                var dirToNeighbour = current.GetDirectionTo(n);
                var jp = Jump(current, dirToNeighbour);
                if (jp != null)
                {
                    successorArray.Add(jp);
                }
            }
        }
コード例 #44
0
        private void PruneNeighbours(IPathNode current, VectorXZ direction)
        {
            if (direction.x != 0)
            {
                if (direction.z != 0)
                {
                    //Natural neighbours
                    var nTop = current.TryGetWalkableNeighbour(0, direction.z, _unitProps, _neighbours);
                    var nRight = current.TryGetWalkableNeighbour(direction.x, 0, _unitProps, _neighbours);

                    if (_cutCorners)
                    {
                        if (nTop || nRight)
                        {
                            current.TryGetWalkableNeighbour(direction.x, direction.z, _unitProps, _neighbours);
                        }

                        //Forced neighbours? The left/down is as seen from a normal view of the grid, i.e. not seen from the direction of movement (well direction left corner diagonal)
                        var nLeft = current.GetNeighbour(-direction.x, 0);
                        if (nLeft != null && !nLeft.isWalkableFromAllDirections(_unitProps))
                        {
                            current.TryGetWalkableNeighbour(-direction.x, direction.z, _unitProps, _neighbours);
                        }

                        var nDown = current.GetNeighbour(0, -direction.z);
                        if (nDown != null && !nDown.isWalkableFromAllDirections(_unitProps))
                        {
                            current.TryGetWalkableNeighbour(direction.x, -direction.z, _unitProps, _neighbours);
                        }
                    }
                    else
                    {
                        if (nTop && nRight)
                        {
                            current.TryGetWalkableNeighbour(direction.x, direction.z, _unitProps, _neighbours);
                        }
                    }
                }
                else
                {
                    //Natural neighbour
                    current.TryGetWalkableNeighbour(direction.x, 0, _unitProps, _neighbours);

                    //Forced neighbours?
                    if (_cutCorners)
                    {
                        var nUp = current.GetNeighbour(0, 1);
                        if (nUp != null && !nUp.isWalkableFromAllDirections(_unitProps))
                        {
                            current.TryGetWalkableNeighbour(direction.x, 1, _unitProps, _neighbours);
                        }

                        var nDown = current.GetNeighbour(0, -1);
                        if (nDown != null && !nDown.isWalkableFromAllDirections(_unitProps))
                        {
                            current.TryGetWalkableNeighbour(direction.x, -1, _unitProps, _neighbours);
                        }
                    }
                    else
                    {
                        var nUpBack = current.GetNeighbour(-direction.x, 1);
                        if (nUpBack != null && !nUpBack.isWalkableFromAllDirections(_unitProps))
                        {
                            current.TryGetWalkableNeighbour(0, 1, _unitProps, _neighbours);
                            current.TryGetWalkableNeighbour(direction.x, 1, _unitProps, _neighbours);
                        }

                        var nDownBack = current.GetNeighbour(-direction.x, -1);
                        if (nDownBack != null && !nDownBack.isWalkableFromAllDirections(_unitProps))
                        {
                            current.TryGetWalkableNeighbour(0, -1, _unitProps, _neighbours);
                            current.TryGetWalkableNeighbour(direction.x, -1, _unitProps, _neighbours);
                        }
                    }
                }
            }
            else
            {
                //Portals return Vector3.zero as the direction, and for those we need to start over on the new grid.
                if (direction.z == 0)
                {
                    current.GetWalkableNeighbours(_neighbours, _unitProps, _cutCorners, false);
                    return;
                }

                //Natural neighbour
                current.TryGetWalkableNeighbour(0, direction.z, _unitProps, _neighbours);

                //Forced neighbours? The left/right is as seen from a normal view of the grid, i.e. not seen from the direction of movement (well direction bottom up)
                if (_cutCorners)
                {
                    var nLeft = current.GetNeighbour(-1, 0);
                    if (nLeft != null && !nLeft.isWalkableFromAllDirections(_unitProps))
                    {
                        current.TryGetWalkableNeighbour(-1, direction.z, _unitProps, _neighbours);
                    }

                    var nRight = current.GetNeighbour(1, 0);
                    if (nRight != null && !nRight.isWalkableFromAllDirections(_unitProps))
                    {
                        current.TryGetWalkableNeighbour(1, direction.z, _unitProps, _neighbours);
                    }
                }
                else
                {
                    var nLeftDown = current.GetNeighbour(-1, -direction.z);
                    if (nLeftDown != null && !nLeftDown.isWalkableFromAllDirections(_unitProps))
                    {
                        current.TryGetWalkableNeighbour(-1, 0, _unitProps, _neighbours);
                        current.TryGetWalkableNeighbour(-1, direction.z, _unitProps, _neighbours);
                    }

                    var nRightDown = current.GetNeighbour(1, -direction.z);
                    if (nRightDown != null && !nRightDown.isWalkableFromAllDirections(_unitProps))
                    {
                        current.TryGetWalkableNeighbour(1, 0, _unitProps, _neighbours);
                        current.TryGetWalkableNeighbour(1, direction.z, _unitProps, _neighbours);
                    }
                }
            }
        }
コード例 #45
0
ファイル: PathSmoother.cs プロジェクト: andrewstarnes/wwtd2
        /// <summary>
        /// Smooths a path.
        /// </summary>
        /// <param name="goal">The goal node of the calculated path.</param>
        /// <param name="maxPathLength">Maximum length of the path.</param>
        /// <param name="request">The path request.</param>
        /// <param name="costStrategy">The cell cost provider.</param>
        /// <returns>
        /// The path in smoothed form
        /// </returns>
        public Path Smooth(IPathNode goal, int maxPathLength, IPathRequest request, ICellCostStrategy costStrategy)
        {
            var unitProps = request.requesterProperties;

            //Next prune superfluous path nodes
            var reversePath = new List<IPositioned>(maxPathLength);

            var current = goal;
            var next = current.predecessor;

            int bends = -1;
            var prevDir = Vector3.zero;

            while (next != null)
            {
                var dir = next.position - current.position;

                if ((dir != prevDir) || (next is IPortalNode))
                {
                    reversePath.Add(current);
                    prevDir = dir;
                    bends++;
                }

                current = next;
                next = current.predecessor;
            }

            //Correct the end nodes and inject a mid point if too much was pruned (can happen on straight paths with no direction change, which can lead to obstacle collision if the unit is offset)
            if (reversePath.Count == 0)
            {
                reversePath.Add(new Position(request.to));
            }
            else
            {
                reversePath[0] = new Position(request.to);
            }

            if (reversePath.Count == 1 && bends <= 0)
            {
                reversePath.Add(goal.predecessor);
            }

            reversePath.Add(new Position(request.from));
            int pathLength = reversePath.Count;

            //Next see if we can reduce the path further by excluding unnecessary bends
            if (!request.pathFinderOptions.preventDiagonalMoves)
            {
                var matrix = goal.parent;

                int indexLimit = reversePath.Count - 2;
                for (int i = 0; i < indexLimit; i++)
                {
                    var c1 = reversePath[i];
                    var c2 = reversePath[i + 1];
                    var c3 = reversePath[i + 2];

                    var skip = AdjustIfPortal(c1, c2, c3);

                    if (skip > -1)
                    {
                        //One of the candidate nodes is a portal so skip to the node following the portal and resolve the grid at the other end of the portal.
                        //Since a portal node will never be the last node we can safely do this here. Since we are moving in the reverse direction here the portal will be on the other side.
                        i += skip;
                        matrix = ((IPortalNode)reversePath[i]).parent;
                        continue;
                    }

                    while (CanReducePath(c1, c3, unitProps, matrix, costStrategy))
                    {
                        reversePath[i + 1] = null;
                        pathLength--;
                        i++;

                        if (i >= indexLimit)
                        {
                            break;
                        }

                        c3 = reversePath[i + 2];
                        if (c3 is IPortalNode)
                        {
                            break;
                        }
                    }
                }
            }

            //Construct the final path
            var path = new Path(pathLength);

            var count = reversePath.Count;
            for (int i = 0; i < count; i++)
            {
                var node = reversePath[i];
                if (node != null)
                {
                    path.Push(node);
                }
            }

            return path;
        }
コード例 #46
0
 public PathResolver(IPathNode root)
 {
     _root = root;
 }
コード例 #47
0
        /// <summary>
        /// This method initializes path nodes needed by the derived classes.
        /// </summary>
        private void initializePathNodes()
        {
            IPathNode coordinatesNode = new PathNode("http://www.opengis.net/gml", "coordinates",
                                                        (NameTable)_xmlReader.NameTable);
            IPathNode posListNode = new PathNode("http://www.opengis.net/gml", "posList",
                                                    (NameTable)_xmlReader.NameTable);
            IPathNode ogcServiceExceptionNode = new PathNode("http://www.opengis.net/ogc", "ServiceException",
                                                                (NameTable)_xmlReader.NameTable);
            IPathNode serviceExceptionNode = new PathNode("", "ServiceException", (NameTable)_xmlReader.NameTable);
            //ServiceExceptions without ogc prefix are returned by deegree. PDD.
            IPathNode exceptionTextNode = new PathNode("http://www.opengis.net/ows", "ExceptionText",
                                                        (NameTable)_xmlReader.NameTable);
            _CoordinatesNode = new AlternativePathNodesCollection(coordinatesNode, posListNode);
            _serviceExceptionNode = new AlternativePathNodesCollection(ogcServiceExceptionNode, exceptionTextNode,
                                                                        serviceExceptionNode);
            _featureNode = new PathNode(_featureTypeInfo.FeatureTypeNamespace, _featureTypeInfo.Name,
                                        (NameTable)_xmlReader.NameTable);

            _propertyNode = new PathNode("http://www.itacasoft.com/GML", "PROPERTIES",
                                                        (NameTable)_xmlReader.NameTable);

            _boundedByNode = new PathNode("http://www.opengis.net/gml", "boundedBy",
                                                        (NameTable)_xmlReader.NameTable);
        }
コード例 #48
0
ファイル: PortalCell.cs プロジェクト: jdeter14/game1
 void IPathNode.UnregisterVirtualNeighbour(IPathNode neighbour)
 {
     /* Currently not supported */
 }
コード例 #49
0
ファイル: Provider.cs プロジェクト: modulexcite/EntityShell
 private void WritePathNode(string nodeContainerPath, IPathNode node)
 {
     if (null != node)
     {
         WriteItemObject(node.Item, MakePath( nodeContainerPath, node.Name ), node.IsCollection);
     }
 }
コード例 #50
0
 /// <summary>
 /// This method initializes path nodes needed by the derived classes.
 /// </summary>
 private void initializePathNodes()
 {
     IPathNode coordinatesNode = new PathNode("http://www.opengis.net/gml", "coordinates",
                                              (NameTable) _XmlReader.NameTable);
     IPathNode posListNode = new PathNode("http://www.opengis.net/gml", "posList",
                                          (NameTable) _XmlReader.NameTable);
     IPathNode posNode = new PathNode("http://www.opengis.net/gml", "pos",
                                          (NameTable)_XmlReader.NameTable);
     IPathNode ogcServiceExceptionNode = new PathNode("http://www.opengis.net/ogc", "ServiceException",
                                                      (NameTable) _XmlReader.NameTable);
     IPathNode serviceExceptionNode = new PathNode("", "ServiceException", (NameTable) _XmlReader.NameTable);
         //ServiceExceptions without ogc prefix are returned by deegree. PDD.
     IPathNode exceptionTextNode = new PathNode("http://www.opengis.net/ows", "ExceptionText",
                                                (NameTable) _XmlReader.NameTable);
     _CoordinatesNode = new AlternativePathNodesCollection(coordinatesNode, posListNode, posNode);
     _ServiceExceptionNode = new AlternativePathNodesCollection(ogcServiceExceptionNode, exceptionTextNode,
                                                                serviceExceptionNode);
     _FeatureNode = new PathNode(_FeatureTypeInfo.FeatureTypeNamespace, _FeatureTypeInfo.Name,
                                 (NameTable) _XmlReader.NameTable);
 }
コード例 #51
0
 /// <summary>
 /// Called when a request is about to be processed.
 /// </summary>
 /// <param name="start">The start node.</param>
 /// <param name="actualStart">The actual start node in case actual start is blocked.</param>
 protected virtual void OnStart(IPathNode start, IPathNode actualStart)
 {
 }
コード例 #52
0
        private bool HasForcedNeighbour(IPathNode current, VectorXZ direction)
        {
            if (current.hasVirtualNeighbour)
            {
                return true;
            }

            bool hasForced = false;

            if (direction.x != 0)
            {
                if (direction.z != 0)
                {
                    if (_cutCorners)
                    {
                        var nLeft = current.GetNeighbour(-direction.x, 0);
                        if (nLeft != null && !nLeft.isWalkableFromAllDirections(_unitProps))
                        {
                            var fn = current.GetNeighbour(-direction.x, direction.z);
                            hasForced |= (fn != null && fn.isWalkableFrom(current, _unitProps));
                        }

                        var nDown = current.GetNeighbour(0, -direction.z);
                        if (nDown != null && !nDown.isWalkableFromAllDirections(_unitProps))
                        {
                            var fn = current.GetNeighbour(direction.x, -direction.z);
                            hasForced |= (fn != null && fn.isWalkableFrom(current, _unitProps));
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    if (_cutCorners)
                    {
                        var nUp = current.GetNeighbour(0, 1);
                        if (nUp != null && !nUp.isWalkableFromAllDirections(_unitProps))
                        {
                            var fn = current.GetNeighbour(direction.x, 1);
                            hasForced |= (fn != null && fn.isWalkableFrom(current, _unitProps));
                        }

                        var nDown = current.GetNeighbour(0, -1);
                        if (nDown != null && !nDown.isWalkableFromAllDirections(_unitProps))
                        {
                            var fn = current.GetNeighbour(direction.x, -1);
                            hasForced |= (fn != null && fn.isWalkableFrom(current, _unitProps));
                        }
                    }
                    else
                    {
                        var nUpBack = current.GetNeighbour(-direction.x, 1);
                        if (nUpBack != null && !nUpBack.isWalkableFromAllDirections(_unitProps))
                        {
                            var fn = current.GetNeighbour(0, 1);
                            hasForced |= (fn != null && fn.isWalkableFrom(current, _unitProps));
                        }

                        var nDownBack = current.GetNeighbour(-direction.x, -1);
                        if (nDownBack != null && !nDownBack.isWalkableFromAllDirections(_unitProps))
                        {
                            var fn = current.GetNeighbour(0, -1);
                            hasForced |= (fn != null && fn.isWalkableFrom(current, _unitProps));
                        }
                    }
                }
            }
            else
            {
                if (_cutCorners)
                {
                    var nLeft = current.GetNeighbour(-1, 0);
                    if (nLeft != null && !nLeft.isWalkableFromAllDirections(_unitProps))
                    {
                        var fn = current.GetNeighbour(-1, direction.z);
                        hasForced |= (fn != null && fn.isWalkableFrom(current, _unitProps));
                    }

                    var nRight = current.GetNeighbour(1, 0);
                    if (nRight != null && !nRight.isWalkableFromAllDirections(_unitProps))
                    {
                        var fn = current.GetNeighbour(1, direction.z);
                        hasForced |= (fn != null && fn.isWalkableFrom(current, _unitProps));
                    }
                }
                else
                {
                    var nLeftDown = current.GetNeighbour(-1, -direction.z);
                    if (nLeftDown != null && !nLeftDown.isWalkableFromAllDirections(_unitProps))
                    {
                        var fn = current.GetNeighbour(-1, 0);
                        hasForced |= (fn != null && fn.isWalkableFrom(current, _unitProps));
                    }

                    var nRightDown = current.GetNeighbour(1, -direction.z);
                    if (nRightDown != null && !nRightDown.isWalkableFromAllDirections(_unitProps))
                    {
                        var fn = current.GetNeighbour(1, 0);
                        hasForced |= (fn != null && fn.isWalkableFrom(current, _unitProps));
                    }
                }
            }

            return hasForced;
        }
コード例 #53
0
ファイル: AStarStack.cs プロジェクト: substans/Pathfinding
 public void Push(IPathNode pNode)
 {
     _nodes[pNode.GetUniqueID()] = pNode;
 }
コード例 #54
0
 /// <summary>
 /// Updates the goal to a new value.
 /// </summary>
 /// <param name="newGoal">The new goal.</param>
 protected void UpdateGoal(IPathNode newGoal)
 {
     _goal = newGoal;
     _segmentRequest.to = newGoal.position;
 }
コード例 #55
0
        private bool StartRequest(IPathRequest request)
        {
            Ensure.ArgumentNotNull(request, "request");

            if (!request.isValid)
            {
                throw new ArgumentException("The request is invalid.", "request");
            }

            if (_currentRequest != null)
            {
                throw new InvalidOperationException("A new request cannot be started while another request is being processed.");
            }

            _currentRequest = request;

            var start = request.fromGrid.GetCell(request.from, false) as IPathNode;
            _goal = request.toGrid.GetCell(request.to, false) as IPathNode;

            if (start == null)
            {
                CompleteRequest(PathingStatus.StartOutsideGrid);
                return false;
            }

            if (_goal == null)
            {
                if (_currentRequest.pathFinderOptions.navigateToNearestIfBlocked)
                {
                    _goal = request.toGrid.GetCell(request.to, true) as IPathNode;
                    request.to = _goal.position;
                }
                else
                {
                    CompleteRequest(PathingStatus.EndOutsideGrid);
                    return false;
                }
            }

            if (!_goal.isWalkable(_currentRequest.requesterProperties.attributes) && !_currentRequest.pathFinderOptions.navigateToNearestIfBlocked)
            {
                CompleteRequest(PathingStatus.DestinationBlocked);
                return false;
            }

            OnStart(start);

            return true;
        }
コード例 #56
0
        /// <summary>
        /// Gets the heuristic for a node in relation to this portal. This is only used for Shortcut portals, but is valid for all types.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <param name="goal">The goal.</param>
        /// <param name="moveCostProvider">The move cost provider.</param>
        /// <returns>The heuristic</returns>
        public int GetHeuristic(IPathNode node, IPathNode goal, IMoveCost moveCostProvider)
        {
            //The logic here is that we want to shortest possible distance from the node to this portal cell,
            //combined with the shortest possible distance from our partner portal cell to the goal, again combined with the
            // cost of making the portal move using those two entry points.
            int mx = _matrixBounds.AdjustColumnToBounds(node.matrixPosX);
            int mz = _matrixBounds.AdjustRowToBounds(node.matrixPosZ);
            var closestCellToNode = this.parent.rawMatrix[mx, mz];

            mx = _partner._matrixBounds.AdjustColumnToBounds(goal.matrixPosX);
            mz = _partner._matrixBounds.AdjustRowToBounds(goal.matrixPosZ);
            var closestCellToGoal = _partner.parent.rawMatrix[mx, mz];

            return moveCostProvider.GetHeuristic(node, closestCellToNode) + _action.GetActionCost(closestCellToNode, closestCellToGoal, moveCostProvider) + moveCostProvider.GetHeuristic(closestCellToGoal, goal);
        }
コード例 #57
0
ファイル: TileNode.cs プロジェクト: substans/Pathfinding
        public PathLink GetLinkTo(IPathNode pNode)
        {
            if (_links != null) {
                foreach (PathLink p in _links) {
                    if (p.Contains(pNode)) {
                        return p;
                    }
                }
            }

            return null;
        }
コード例 #58
0
ファイル: PortalCell.cs プロジェクト: jdeter14/game1
 /// <summary>
 /// Gets the heuristic for a node in relation to this portal.
 /// </summary>
 /// <param name="node">The node.</param>
 /// <param name="goal">The goal.</param>
 /// <param name="moveCostProvider">The move cost provider.</param>
 /// <returns>The heuristic</returns>
 public int GetHeuristic(IPathNode node, IPathNode goal, IMoveCost moveCostProvider)
 {
     return moveCostProvider.GetHeuristic(node, this) + moveCostProvider.GetHeuristic(_partner, goal);
 }
コード例 #59
0
 private void WritePathNode(string path, IPathNode node)
 {
     if (null != node)
     {
         WriteItemObject(node.Item, path, node.IsCollection);
     }
 }
コード例 #60
0
        private PathingStatus StartPathSegment()
        {
            var fromGrid = GridManager.instance.GetGrid(_segmentRequest.from);
            var toGrid = GridManager.instance.GetGrid(_segmentRequest.to);
            if (toGrid == null)
            {
                //Just treat the to grid as the from grid in this case so the destination can be closest point on from grid
                if (toGrid == null)
                {
                    toGrid = fromGrid;
                }
            }

            //If no grids were resolved for this request it means the request involves two points outside the grid(s) that do not cross any grid(s), so we can move directly between them
            if (fromGrid == null && toGrid == null)
            {
                var pathSegment = new Path(2);
                pathSegment.Push(new Position(_segmentRequest.to));
                pathSegment.Push(new Position(_segmentRequest.from));
                _segments.Add(pathSegment);
                return PathingStatus.Complete;
            }
            else if (fromGrid == null)
            {
                return PathingStatus.StartOutsideGrid;
            }

            //Get a reference to the start and end cells
            var start = fromGrid.GetCell(_segmentRequest.from, false) as IPathNode;
            _goal = toGrid.GetCell(_segmentRequest.to, false) as IPathNode;

            //Ensure that the end cell is valid
            if (_goal == null)
            {
                if (_segmentRequest.pathFinderOptions.navigateToNearestIfBlocked)
                {
                    _goal = toGrid.GetCell(_segmentRequest.to, true) as IPathNode;
                    _segmentRequest.to = _goal.position;
                }
                else
                {
                    return PathingStatus.EndOutsideGrid;
                }
            }

            if (!_goal.isWalkable(_segmentRequest.requesterProperties.attributes) && !_segmentRequest.pathFinderOptions.navigateToNearestIfBlocked)
            {
                return PathingStatus.DestinationBlocked;
            }

            //Ensure that the start cell is valid
            IPathNode actualStart = null;
            if (!start.isWalkable(_segmentRequest.requesterProperties.attributes))
            {
                actualStart = start;
                start = fromGrid.GetNearestWalkableCell(start.position, _goal.position, true, _segmentRequest.pathFinderOptions.maxEscapeCellDistanceIfOriginBlocked, _segmentRequest.requesterProperties);
                if (start == null)
                {
                    return PathingStatus.NoRouteExists;
                }
            }

            OnStart(start, actualStart);

            return PathingStatus.Running;
        }