Пример #1
0
 private void ApplyNow(Path somePath)
 {
     object obj = this.lockObject;
     lock (obj)
     {
         this.waitingForApply = false;
         AstarPath.OnPathPreSearch = (OnPathDelegate)Delegate.Remove(AstarPath.OnPathPreSearch, new OnPathDelegate(this.ApplyNow));
         this.InversePrevious();
         if (!this.destroyed)
         {
             int seed = this.seedGenerator.Next();
             this.rnd = new System.Random(seed);
             if (this.toBeApplied != null)
             {
                 int num = this.rnd.Next(this.randomStep);
                 for (int i = num; i < this.toBeApplied.Length; i += this.rnd.Next(1, this.randomStep))
                 {
                     this.toBeApplied[i].Penalty = (uint)((ulong)this.toBeApplied[i].Penalty + (ulong)((long)this.penalty));
                 }
             }
             this.prevPenalty = this.penalty;
             this.prevSeed = seed;
             this.prevNodes = this.toBeApplied;
         }
     }
 }
Пример #2
0
 void OnCaculate(Pathfinding.Path path)
 {
     Debug.Log(Time.frameCount);
     caculated = true;
     list.Clear();
     ReflectionCaculator.CaculateReflectionPoints(path as FixedABPath, list);
 }
Пример #3
0
		void ClearOnDestroy (Path p) {
			lock (lockObject) {
				AstarPath.OnPathPreSearch -= ClearOnDestroy;
				waitingForApply = false;
				InversePrevious();
			}
		}
 public void CalculatePath()
 {
     var pos = (target == null) ? targetPosition : (target.transform.position + targetPosition);
     p = ABPath.Construct (go.transform.position , pos , OnPathComplete); // create path from current position to closest/first node
     AstarPath.StartPath (p); //make the actual vector3 path which we'll use lateron.
     pUpdate = 0;
 }
Пример #5
0
		public override void Apply (Path _p) {
			var p = _p as ABPath;

			// This modifier only supports ABPaths (doesn't make much sense for other paths anyway)
			if (p == null || p.vectorPath.Count == 0) return;

			if (p.vectorPath.Count == 1 && !addPoints) {
				// Duplicate first point
				p.vectorPath.Add(p.vectorPath[0]);
			}

			// Add instead of replacing points
			bool forceAddStartPoint, forceAddEndPoint;

			Vector3 pStart = Snap(p, exactStartPoint, true, out forceAddStartPoint);
			Vector3 pEnd = Snap(p, exactEndPoint, false, out forceAddEndPoint);

			// Add or replace the start point
			// Disable adding of points if the mode is SnapToNode since then
			// the first item in vectorPath will very likely be the same as the
			// position of the first node
			if ((forceAddStartPoint || addPoints) && exactStartPoint != Exactness.SnapToNode) {
				p.vectorPath.Insert(0, pStart);
			} else {
				p.vectorPath[0] = pStart;
			}

			if ((forceAddEndPoint || addPoints) && exactEndPoint != Exactness.SnapToNode) {
				p.vectorPath.Add(pEnd);
			} else {
				p.vectorPath[p.vectorPath.Count-1] = pEnd;
			}
		}
		public void OnPathComplete (Path p) {
			//		Debug.Log ("Yay, we got a path back. Did it have an error? "+p.error);
			if (!p.error) {
				path = p;
				//Reset the waypoint counter
				currentWaypoint = 0;
			}
		}
Пример #7
0
 private void OnPathComplete(Pathfinding.Path p)
 {
     if (!p.error)
     {
         mPath            = p;
         mCurrentWayPoint = 0;
     }
 }
Пример #8
0
 private void OnPathComplete(Path path)
 {
     if (!path.error)
     {
         this.path       = path;
         currentWayPoint = 0;
     }
 }
Пример #9
0
 public PathEndingCondition(Path p)
 {
     if (p == null)
     {
         throw new ArgumentNullException("p");
     }
     this.path = p;
 }
Пример #10
0
 //La fin du chemin est atteinte
 void OnPathComplete(Path p)
 {
     if (!p.error)
     {
         path            = p;
         currentWaypoint = 0;
     }
 }
Пример #11
0
Файл: Unit.cs Проект: Tairos/PFP
 void CompletePath(Pathfinding.Path p)
 {
     if (!p.error) {
         path = p;
         currentWayPoint = 1;
         if (p.vectorPath.Count == 1) currentWayPoint = 0;
         if (!animator.GetBool("Running")) animator.SetBool("Run",true);
     }
 }
Пример #12
0
 public static bool InSearchTree(GraphNode node, Path path)
 {
     if (path == null || path.pathHandler == null)
     {
         return true;
     }
     PathNode pathNode = path.pathHandler.GetPathNode(node);
     return pathNode.pathID == path.pathID;
 }
Пример #13
0
		/** Initializes the NodeRunData for calculation of the specified path.
		 * Called by core pathfinding functions just before starting to calculate a path.
		 */
		public void Initialize (Path p) {
			path = p;
			
			pathID = p.pathID;
			
			//Resets the binary heap, don't clear everything because that takes an awful lot of time, instead we can just change the numberOfItems in it (which is just an int)
			//Binary heaps are just like a standard array but are always sorted so the node with the lowest F value can be retrieved faster
			open.Clear ();
		}
Пример #14
0
 //当寻路结束后调用这个函数
 public void OnPathComplete(Path p)
 {
     Debug.Log("FindThePath" + p.error);
     //如果找到了一条路径,保存下来,并且把第一个路点设置为当前路点
     if (!p.error)
     {
         path = p;
         currentWaypoint = 0;
     }
 }
Пример #15
0
 //When it is done calculating were it needs to be
 public void OnPathComplete(Pathfinding.Path p)
 {
     //Debug.Log("A path was calculated. Did it fail with an error? " + p.error);
     if (!p.error)
     {
         path = p;
         // Reset the waypoint counter so that we start to move towards the first point in the path
         currentWaypoint = 0;
     }
 }
 void OnPathComplete(Pathfinding.Path p)
 {
     //Runs when pathfinding is complete, if there are no errors the start of a new path will become the current waypoint when the RecalculatePath coroutine is running.
     //Based on the Brackeys tutorial.
     if (!p.error)
     {
         currentPath     = p;
         currentWaypoint = 0;
     }
 }
 private float GetTotalDistanceOfPath(Path path)
 {
     var totalDistance = 0.0f;
     for (var i = 1; i < path.vectorPath.Count; i++)
     {
         var previousPosition = path.vectorPath[i - 1];
         var nextPosition = path.vectorPath[i];
         totalDistance = Vector3.Distance(previousPosition, nextPosition);
     }
     return totalDistance;
 }
        void ChooseWaypoint()
        {
            if (waypoints.Length <= 2) {
                return;
            }

            destinationWaypoint = waypoints [UnityEngine.Random.Range (0, waypoints.Length - 1)];
            path = null;
            currentDirection = Vector3.zero;
            currentWaypointIndex = 0;
            seeker.StartPath (transform.position, destinationWaypoint.position, OnPathComplete);
        }
        private void PathFinishedDelegate(Path path)
        {
            if (path.error)
            {
                Error = path.errorLog;
                PathFailed();
                return;
            }

            GeneratedPath = (ConstantPath) path;
            PathGenerated();
        }
Пример #20
0
		public override void Apply (Path p) {
			if (this == null) return;

			lock (lockObject) {
				toBeApplied = p.path.ToArray();

				if (!waitingForApply) {
					waitingForApply = true;
					AstarPath.OnPathPreSearch += ApplyNow;
				}
			}
		}
Пример #21
0
		public override void Apply (Path p) {
			List<GraphNode> path = p.path;
			List<Vector3> vectorPath = p.vectorPath;

			if (path == null || path.Count == 0 || vectorPath == null || vectorPath.Count != path.Count) {
				return;
			}

			List<Vector3> funnelPath = ListPool<Vector3>.Claim();

			// Claim temporary lists and try to find lists with a high capacity
			List<Vector3> left = ListPool<Vector3>.Claim(path.Count+1);
			List<Vector3> right = ListPool<Vector3>.Claim(path.Count+1);

			AstarProfiler.StartProfile("Construct Funnel");

			// Add start point
			left.Add(vectorPath[0]);
			right.Add(vectorPath[0]);

			// Loop through all nodes in the path (except the last one)
			for (int i = 0; i < path.Count-1; i++) {
				// Get the portal between path[i] and path[i+1] and add it to the left and right lists
				bool portalWasAdded = path[i].GetPortal(path[i+1], left, right, false);

				if (!portalWasAdded) {
					// Fallback, just use the positions of the nodes
					left.Add((Vector3)path[i].position);
					right.Add((Vector3)path[i].position);

					left.Add((Vector3)path[i+1].position);
					right.Add((Vector3)path[i+1].position);
				}
			}

			// Add end point
			left.Add(vectorPath[vectorPath.Count-1]);
			right.Add(vectorPath[vectorPath.Count-1]);

			if (!RunFunnel(left, right, funnelPath)) {
				// If funnel algorithm failed, degrade to simple line
				funnelPath.Add(vectorPath[0]);
				funnelPath.Add(vectorPath[vectorPath.Count-1]);
			}

			// Release lists back to the pool
			ListPool<Vector3>.Release(p.vectorPath);
			p.vectorPath = funnelPath;

			ListPool<Vector3>.Release(left);
			ListPool<Vector3>.Release(right);
		}
Пример #22
0
		public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) {
			UpdateG (path,pathNode);
			
			handler.PushNode (pathNode);
			
			for (int i=0;i<connections.Length;i++) {
				GraphNode other = connections[i];
				PathNode otherPN = handler.GetPathNode (other);
				if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) {
					other.UpdateRecursiveG (path, otherPN,handler);
				}
			}
		}
		/**
		 * Returns all paths in the return stack.
		 * Paths which have been processed are put in the return stack.
		 * This function will pop all items from the stack and return them to e.g the Seeker requesting them.
		 *
		 * \param timeSlice Do not return all paths at once if it takes a long time, instead return some and wait until the next call.
		 */
		public void ReturnPaths (bool timeSlice) {

			// Pop all items from the stack
			Path p = pathReturnStack.PopAll ();

			if(pathReturnPop == null) {
				pathReturnPop = p;
			} else {
				Path tail = pathReturnPop;
				while (tail.next != null) tail = tail.next;
				tail.next = p;
			}

			// Hard coded limit on 1.0 ms
			long targetTick = timeSlice ? System.DateTime.UtcNow.Ticks + 1 * 10000 : 0;

			int counter = 0;
			// Loop through the linked list and return all paths
			while (pathReturnPop != null) {

				//Move to the next path
				Path prev = pathReturnPop;
				pathReturnPop = pathReturnPop.next;

				// Remove the reference to prevent possible memory leaks
				// If for example the first path computed was stored somewhere,
				// it would through the linked list contain references to all comming paths to be computed,
				// and thus the nodes those paths searched.
				// That adds up to a lot of memory not being released
				prev.next = null;

				//Return the path
				prev.ReturnPath ();

				// Will increment to Returned
				// However since multithreading is annoying, it might be set to ReturnQueue for a small time until the pathfinding calculation
				// thread advanced the state as well
				prev.AdvanceState (PathState.Returned);

				prev.ReleaseSilent (pathsClaimedSilentlyBy);

				counter++;
				// At least 5 paths will be returned, even if timeSlice is enabled
				if (counter > 5 && timeSlice) {
					counter = 0;
					if (System.DateTime.UtcNow.Ticks >= targetTick) {
						return;
					}
				}
			}
		}
 private void PathFinishedDeletate(Path path)
 {
     if (path.error)
     {
         Error = path.errorLog;
         PathFailed();
     }
     else
     {
         GeneratedPath = path;
         PathGenerated();
         PathGenerated();
     }
 }
Пример #25
0
		public override void Apply (Path p, ModifierData source) {
			var path = p.path;
			var vectorPath = p.vectorPath;
			
			if (path == null || path.Count == 0 || vectorPath == null || vectorPath.Count != path.Count) {
				return;
			}
			
			var funnelPath = ListPool<Vector3>.Claim ();
			
			//Claim temporary lists and try to find lists with a high capacity
			var left = ListPool<Vector3>.Claim (path.Count+1);
			var right = ListPool<Vector3>.Claim (path.Count+1);
			
			AstarProfiler.StartProfile ("Construct Funnel");
			
			left.Add (vectorPath[0]);
			right.Add (vectorPath[0]);
			
			for (var i=0;i<path.Count-1;i++) {
				var a = path[i].GetPortal (path[i+1], left, right, false);
				var b = false;//path[i+1].GetPortal (path[i], right, left, true);
				
				if (!a && !b) {
					left.Add ((Vector3)path[i].position);
					right.Add ((Vector3)path[i].position);
					
					left.Add ((Vector3)path[i+1].position);
					right.Add ((Vector3)path[i+1].position);
				}
			}
			
			left.Add (vectorPath[vectorPath.Count-1]);
			right.Add (vectorPath[vectorPath.Count-1]);
			
			if (!RunFunnel (left,right,funnelPath)) {
				//If funnel algorithm failed, degrade to simple line
				funnelPath.Add (vectorPath[0]);
				funnelPath.Add (vectorPath[vectorPath.Count-1]);
			}
			
			ListPool<Vector3>.Release (p.vectorPath);
			p.vectorPath = funnelPath;
			
			ListPool<Vector3>.Release (left);
			ListPool<Vector3>.Release (right);
		}
Пример #26
0
 public override void Apply(Path p, ModifierData source)
 {
     if (this == null)
     {
         return;
     }
     object obj = this.lockObject;
     lock (obj)
     {
         this.toBeApplied = p.path.ToArray();
         if (!this.waitingForApply)
         {
             this.waitingForApply = true;
             AstarPath.OnPathPreSearch = (OnPathDelegate)Delegate.Combine(AstarPath.OnPathPreSearch, new OnPathDelegate(this.ApplyNow));
         }
     }
 }
Пример #27
0
    public void OnDisable()
    {
        // Abort calculation of path
        if (seeker != null && !seeker.IsDone())
        {
            seeker.GetCurrentPath().Error();
        }

        // Release current path
        if (path != null)
        {
            path.Release(this);
        }
        path = null;

        //Make sure we receive callbacks when paths complete
        seeker.pathCallback -= OnPathComplete;
    }
Пример #28
0
    void FindRoute() {
        if (_routeFinding)
            return;

        position.y = Terrain.activeTerrain.SampleHeight(position);
        lastPosition = position;
        if ((transform.position - position).sqrMagnitude < 200) {
            _path = null;

            return;
        }
        _routeFinding = true;
        _seeker.StartPath(transform.position, position, (p) => {
            _currentPosition = 2;
            _path = p;
            _routeFinding = false;
        });
    }
Пример #29
0
    //寻路结束;
    public void OnPathComplete(Path p)
    {
        //UnityEngine.Debug.Log("OnPathComplete error = " + p.error);
        if (!p.error)
        {
            //currentWayPoint = 0;
            path = p;
            //stopMove = false;
            PositionsLog(p.vectorPath);
            //pathFindingTimes++;
        }

        StartCoroutine(NextPathfinding());

        /*for (int index = 0; index < path.vectorPath.Count; index++)
         * {
         *  //UnityEngine.Debug.Log(gameObject.name + "-path.vectorPath[" + index + "]=" + path.vectorPath[index]);
         * }*/
    }
Пример #30
0
    void OnpathEnd(Pathfinding.Path p)
    {
        if (p.error)
        {
            return;
        }
        Debug.Log(p.vectorPath.Count);

        path            = p;
        currentWaypoint = 0;
//		foreach(var one in path.vectorPath)
//		{
//			Debug.Log(one);
//
//		}

        //path.path[0].position;
        //Debug.Log(path.duration);
    }
Пример #31
0
 public override void Open(Path path, PathNode pathNode, PathHandler handler)
 {
     if (this.connections == null)
     {
         return;
     }
     for (int i = 0; i < this.connections.Length; i++)
     {
         GraphNode graphNode = this.connections[i];
         if (path.CanTraverse(graphNode))
         {
             PathNode pathNode2 = handler.GetPathNode(graphNode);
             if (pathNode2.pathID != handler.PathID)
             {
                 pathNode2.node = graphNode;
                 pathNode2.parent = pathNode;
                 pathNode2.pathID = handler.PathID;
                 pathNode2.cost = this.connectionCosts[i];
                 pathNode2.H = path.CalculateHScore(graphNode);
                 graphNode.UpdateG(path, pathNode2);
                 handler.PushNode(pathNode2);
             }
             else
             {
                 uint num = this.connectionCosts[i];
                 if (pathNode.G + num + path.GetTraversalCost(graphNode) < pathNode2.G)
                 {
                     pathNode2.cost = num;
                     pathNode2.parent = pathNode;
                     graphNode.UpdateRecursiveG(path, pathNode2, handler);
                 }
                 else if (pathNode2.G + num + path.GetTraversalCost(this) < pathNode.G && graphNode.ContainsConnection(this))
                 {
                     pathNode.parent = pathNode2;
                     pathNode.cost = num;
                     this.UpdateRecursiveG(path, pathNode, handler);
                 }
             }
         }
     }
 }
Пример #32
0
		/** Push a path to the front of the queue */
		public void PushFront (Path p) {
			//If termination is due, why add stuff to a queue which will not be read from anyway
			if (terminate) return;
			
			lock (lockObj) {
				if (tail == null) {// (tail == null) ==> (head == null)
					head = p;
					tail = p;
					
					if (starving && !blocked) {
						starving = false;
						block.Set();
					} else {
						starving = false;
					}
				} else {
					p.next = head;
					head = p;
				}
			}
		}
Пример #33
0
 public static ModifierData Convert(Path p, ModifierData input, ModifierData output)
 {
     if (!ModifierConverter.CanConvert(input, output))
     {
         Debug.LogError(string.Concat(new object[]
         {
             "Can't convert ",
             input,
             " to ",
             output
         }));
         return ModifierData.None;
     }
     if (ModifierConverter.AnyBits(input, output))
     {
         return input;
     }
     if (ModifierConverter.AnyBits(input, ModifierData.Nodes) && ModifierConverter.AnyBits(output, ModifierData.Vector))
     {
         p.vectorPath.Clear();
         for (int i = 0; i < p.vectorPath.Count; i++)
         {
             p.vectorPath.Add((Vector3)p.path[i].position);
         }
         return ModifierData.VectorPath | ((!ModifierConverter.AnyBits(input, ModifierData.StrictNodePath)) ? ModifierData.None : ModifierData.StrictVectorPath);
     }
     Debug.LogError(string.Concat(new object[]
     {
         "This part should not be reached - Error in ModifierConverted\nInput: ",
         input,
         " (",
         (int)input,
         ")\nOutput: ",
         output,
         " (",
         (int)output,
         ")"
     }));
     return ModifierData.None;
 }
Пример #34
0
    void FindRoute()
    {
        if (_routeFinding)
        {
            return;
        }

        position.y   = Terrain.activeTerrain.SampleHeight(position);
        lastPosition = position;
        if ((transform.position - position).sqrMagnitude < 200)
        {
            _path = null;

            return;
        }
        _routeFinding = true;
        _seeker.StartPath(transform.position, position, (p) => {
            _currentPosition = 2;
            _path            = p;
            _routeFinding    = false;
        });
    }
        public override void OnEnter()
        {
            var doo = InputPath.Value as FsmPath;
            a = doo.Value;

            if(a == null)
            {
                Finish();
                return;
            }

            var x = 0;
            while (x < a.path.Count)
            {
                //a.path[x].position.x += Vector.Value.x/a.path[x].position.PrecisionFactor;
                //a.path[x].position.y += Vector.Value.y/a.path[x].position.PrecisionFactor;
                //a.path[x].position.z += Vector.Value.z/a.path[x].position.PrecisionFactor;
                a.vectorPath[x] += Vector.Value;
                x++;
            }
            Finish();
        }
Пример #36
0
    //Called once when the path to the current target position has been calculated.
    public void OnPathCalculationComplete(Pathfinding.Path path)
    {
        //OnPathTravelStart() flag
        if (flagOnStart)
        {
            flagOnStart = false;
            rtsGameObject.OnPathTravelStart();
        }

        //Check for path calculation error
        if (!path.error)
        {
            //Reset variables
            this.path       = path;
            currentWaypoint = 0;

            rtsGameObject.OnPathTravelUpdate();
        }
        else
        {
            Debug.LogError("Path calculation error: " + path.error);
        }
    }
Пример #37
0
		public override void Open (Path path, PathNode pathNode, PathHandler handler) {
			
			if (connections == null) return;
			
			for (int i=0;i<connections.Length;i++) {
				GraphNode other = connections[i];
				
				if (path.CanTraverse (other)) {
					
					PathNode pathOther = handler.GetPathNode (other);
					
					if (pathOther.pathID != handler.PathID) {
						
						pathOther.parent = pathNode;
						pathOther.pathID = handler.PathID;
						
						pathOther.cost = connectionCosts[i];
						
						pathOther.H = path.CalculateHScore (other);
						other.UpdateG (path, pathOther);
						
						handler.PushNode (pathOther);
					} else {
						//If not we can test if the path from this node to the other one is a better one then the one already used
						uint tmpCost = connectionCosts[i];
						
						if (pathNode.G + tmpCost + path.GetTraversalCost(other) < pathOther.G) {
							
							pathOther.cost = tmpCost;
							pathOther.parent = pathNode;
							
							other.UpdateRecursiveG (path, pathOther,handler);
							
							//handler.PushNode (pathOther);
						}
						else if (pathOther.G+tmpCost+path.GetTraversalCost(this) < pathNode.G && other.ContainsConnection (this)) {
							//Or if the path from the other node to this one is better
							
							pathNode.parent = pathOther;
							pathNode.cost = tmpCost;
							
							UpdateRecursiveG (path, pathNode,handler);
							
							//handler.PushNode (pathNode);
						}
					}
				}
			}
		}
Пример #38
0
		public override void Open (Path path, PathNode pathNode, PathHandler handler) {
			GridGraph gg = GetGridGraph(GraphIndex);

			ushort pid = handler.PathID;

			{
				int[] neighbourOffsets = gg.neighbourOffsets;
				uint[] neighbourCosts = gg.neighbourCosts;
				GridNode[] nodes = gg.nodes;
				var index = NodeInGridIndex;

				for (int i = 0; i < 8; i++) {
					if (HasConnectionInDirection(i)) {
						GridNode other = nodes[index + neighbourOffsets[i]];
						if (!path.CanTraverse(other)) continue;

						PathNode otherPN = handler.GetPathNode(other);

						uint tmpCost = neighbourCosts[i];

						if (otherPN.pathID != pid) {
							otherPN.parent = pathNode;
							otherPN.pathID = pid;

							otherPN.cost = tmpCost;

							otherPN.H = path.CalculateHScore(other);
							other.UpdateG(path, otherPN);

							//Debug.Log ("G " + otherPN.G + " F " + otherPN.F);
							handler.heap.Add(otherPN);
							//Debug.DrawRay ((Vector3)otherPN.node.Position, Vector3.up,Color.blue);
						} else {
							// Sorry for the huge number of #ifs

							//If not we can test if the path from the current node to this one is a better one then the one already used

#if ASTAR_NO_TRAVERSAL_COST
							if (pathNode.G+tmpCost < otherPN.G)
#else
							if (pathNode.G+tmpCost+path.GetTraversalCost(other) < otherPN.G)
#endif
							{
								//Debug.Log ("Path better from " + NodeIndex + " to " + otherPN.node.NodeIndex + " " + (pathNode.G+tmpCost+path.GetTraversalCost(other)) + " < " + otherPN.G);
								otherPN.cost = tmpCost;

								otherPN.parent = pathNode;

								other.UpdateRecursiveG(path, otherPN, handler);

								//Or if the path from this node ("other") to the current ("current") is better
							}
#if ASTAR_NO_TRAVERSAL_COST
							else if (otherPN.G+tmpCost < pathNode.G)
#else
							else if (otherPN.G+tmpCost+path.GetTraversalCost(this) < pathNode.G)
#endif
							{
								//Debug.Log ("Path better from " + otherPN.node.NodeIndex + " to " + NodeIndex + " " + (otherPN.G+tmpCost+path.GetTraversalCost (this)) + " < " + pathNode.G);
								pathNode.parent = otherPN;
								pathNode.cost = tmpCost;

								UpdateRecursiveG(path, pathNode, handler);
							}
						}
					}
				}
			}

#if !ASTAR_GRID_NO_CUSTOM_CONNECTIONS
			base.Open(path, pathNode, handler);
#endif
		}
Пример #39
0
		public void InitializeForPath (Path p) {
			pathID = p.pathID;
			heap.Clear ();
		}
		public override void Apply (Path p, ModifierData source) {
			
			//This should never trigger unless some other modifier has messed stuff up
			if (p.vectorPath == null) {
				Debug.LogWarning ("Can't process NULL path (has another modifier logged an error?)");
				return;
			}
			
			List<Vector3> path = null;
			
			switch (smoothType) {
				case SmoothType.Simple:
					path = SmoothSimple (p.vectorPath); break;
				case SmoothType.Bezier:
					path = SmoothBezier (p.vectorPath); break;
				case SmoothType.OffsetSimple:
					path = SmoothOffsetSimple (p.vectorPath); break;
				case SmoothType.CurvedNonuniform:
					path = CurvedNonuniform (p.vectorPath); break;
			}
			
			if (path != p.vectorPath) {
				ListPool<Vector3>.Release (p.vectorPath);
				p.vectorPath = path;
			}
			//.vectorPath.Clear ();
			//p.vectorPath.AddRange (path);
		}
Пример #41
0
        public new override void Open(NodeRunData nodeRunData, NodeRun nodeR, Int3 targetPosition, Path path)
        {
            BaseOpen (nodeRunData, nodeR, targetPosition, path);

            LayerGridGraph graph = gridGraphs[indices >> 24];
            int[] neighbourOffsets = graph.neighbourOffsets;
            int[] neighbourCosts = graph.neighbourCosts;
            Node[] nodes = graph.nodes;

            int index = GetIndex();//indices & 0xFFFFFF;

            for (int i=0;i<4;i++) {
                int conn = GetConnectionValue(i);//(gridConnections >> i*4) & 0xF;
                if (conn != LevelGridNode.NoConnection) {

                    Node node = nodes[index+neighbourOffsets[i] + graph.width*graph.depth*conn];

                    if (!path.CanTraverse (node)) {
                        continue;
                    }

                    NodeRun nodeR2 = node.GetNodeRun (nodeRunData);

                    if (nodeR2.pathID != nodeRunData.pathID) {

                        nodeR2.parent = nodeR;
                        nodeR2.pathID = nodeRunData.pathID;

                        nodeR2.cost = (uint)neighbourCosts[i];

                        node.UpdateH (targetPosition, path.heuristic, path.heuristicScale, nodeR2);
                        node.UpdateG (nodeR2, nodeRunData);

                        nodeRunData.open.Add (nodeR2);

                    } else {
                        //If not we can test if the path from the current node to this one is a better one then the one already used
                        uint tmpCost = (uint)neighbourCosts[i];

                        if (nodeR.g+tmpCost+node.penalty
            #if !NoTagPenalty
                    + path.GetTagPenalty(node.tags)
            #endif
                                < nodeR2.g) {

                            nodeR2.cost = tmpCost;
                            nodeR2.parent = nodeR;

                            //TODO!!!!! ??
                            node.UpdateAllG (nodeR2,nodeRunData);

                            nodeRunData.open.Add (nodeR2);
                        }

                         else if (nodeR2.g+tmpCost+penalty
            #if !NoTagPenalty
                    + path.GetTagPenalty(tags)
            #endif
                                 < nodeR.g) {//Or if the path from this node ("node") to the current ("current") is better

                            bool contains = node.ContainsConnection (this);

                            //Make sure we don't travel along the wrong direction of a one way link now, make sure the Current node can be moved to from the other Node.
                            /*if (node.connections != null) {
                                for (int y=0;y<node.connections.Length;y++) {
                                    if (node.connections[y] == this) {
                                        contains = true;
                                        break;
                                    }
                                }
                            }*/

                            if (!contains) {
                                continue;
                            }

                            nodeR.parent = nodeR2;
                            nodeR.cost = tmpCost;

                            //TODO!!!!!!! ??
                            UpdateAllG (nodeR,nodeRunData);

                            nodeRunData.open.Add (nodeR);
                        }
                    }
                }
            }
        }
Пример #42
0
    public void OnPathComplete(Pathfinding.Path p)
    {
        Debug.Log("A path was calculated. Did it fail with an error? " + p.error);

        if (!p.error)
        {
            path = p;
            // Reset the waypoint counter so that we start to move towards the first point in the path
            currentWaypoint = 0;
        }
        // Debug.Log("Get a path: \n" + path);
        // Debug.Log("duration: " + path.heuristic);
        // Debug.Log("duration: " + path.vectorPath);
        // Debug.Log("GetTotalLength: " + path.GetTotalLength());
        // Debug.Log("GetTraversalCost: " + path.GetTraversalCost);
        // Debug.Log("duration: " + path.duration);
        // break;
        // var stream = System.IO.File.CreateText(file_path);
        // var w = new StreamWriter(file_path);

        for (int i = 0; i < path.vectorPath.Count; i++)
        {
            string x = path.vectorPath[i][0].ToString();
            string y = path.vectorPath[i][1].ToString();
            string z = path.vectorPath[i][2].ToString();
            // File.WriteAllText(file_path, path.vectorPath[i][0].ToString());
            // System.IO.File.WriteAllText(file_path, path.vectorPath[i][0].ToString());
            // System.IO.File.AppendAllText(file_path, path.ToString());
            // Debug.Log("path x: " + i + " " + path.vectorPath[i][0].ToString());
            // Debug.Log("path y: " + i + " " + path.vectorPath[i][1].ToString());
            // Debug.Log("path z: " + i + " " + path.vectorPath[i][2].ToString());
            string csvRow = string.Format("{0},{1},{2},{3},{4},{5},\n", i, x, y, z, path.GetTotalLength(), "");
            // stream.WriteLine(csvRow);
            // Debug.Log("Log to file" + i + " " + csvRow);
            // System.IO.File.AppendAllText(file_path, csvRow);
            // System.IO.File.AppendAllLines(file_path, csvRow);
            // Debug.Log("Path info 1: " + path.path.Count);
            // Debug.Log("Path info 2: " + path.searchedNodes());
            // Debug.Log("Path info 3: " + path.GetTotalLength());
            // Debug.Log("Path info 4: " + path.GetTraversalCost());
            // Debug.Log("Path info 5: " + path.GetState());
            // Debug.Log("Path info 6: " + path.GetHTarget());
            // Debug.Log("Path info 7: " + path.duration);
            // Debug.Log("Path info 8: " + path.pathID);
            // Debug.Log("Path info 9: " + path.path);

            // Node
            // if (pathHandler == null) FailWithError("Field pathHandler is not set. Please report this bug.");
            // PathNode nodeR = pathHandler.GetPathNode(path.path[8]);
            // Debug.Log("Path info 9: " + path.path[i].H);
            // Debug.Log("H: " + nodeR.H);

            // Mark nodes to enable special connection costs for start and end nodes
            // See GetConnectionSpecialCost
            // if (startNode != null) pathHandler.GetPathNode(startNode).flag2 = true;
            // if (endNode != null) pathHandler.GetPathNode(endNode).flag2 = true;

            // Zero out the properties on the start node
            // PathNode startRNode = pathHandler.GetPathNode(startNode);
            // startRNode.node = startNode;
            // startRNode.pathID = pathHandler.PathID;
            // startRNode.parent = null;
            // startRNode.cost = 0;
            // startRNode.G = GetTraversalCost(startNode);
            // startRNode.H = CalculateHScore(startNode);
        }

        // pathHandler = new PathHandler(0,0);
        // pathHandler.InitializeForPath(path);
        // Debug.Log("pathHandler: " + pathHandler.PathID);
        // Debug.Log("node: " + pathHandler.GetPathNode(path.path[0]));

        // pathHandler.InitializeForPath(path);
        // System.IO.File.WriteAllText(file_path, csvRow);
        Debug.Log("Path node count: " + path.path.Count);

        for (int j = 0; j < path.path.Count; j++)
        {
            Debug.Log("Path Node index: " + j + " " + path.path[j].NodeIndex);
            Debug.Log("Path Node position: " + j + " " + path.path[j].position);
            Debug.Log("Path Node Penalty: " + j + " " + path.path[j].Penalty);
            Debug.Log("Path Node: " + j + " " + path.path[j]);
            // Debug.Log("Path Node position: " + j + " " + path.path[j].position);

            // pn = pathHandler.GetPathNode(path.path[j].NodeIndex);
            // pn = pathHandler.GetPathNode(path.path[j]);
            // pathHandler.startNode

            // Debug.Log("pathHandler" + pathHandler.threadID);
            // Debug.Log("pathHandler" + pathHandler.totalThreadCount);
            // Debug.Log("pathHandler" + pathHandler.heap);
        }
    }
Пример #43
0
 void OnpathEnd(Pathfinding.Path path)
 {
     Debug.Log(path.vectorPath.Count);
 }
Пример #44
0
 public override void Apply(Path p, ModifierData source)
 {
     List<GraphNode> path = p.path;
     List<Vector3> vectorPath = p.vectorPath;
     if (path == null || path.Count == 0 || vectorPath == null || vectorPath.Count != path.Count)
     {
         return;
     }
     List<Vector3> list = ListPool<Vector3>.Claim();
     List<Vector3> list2 = ListPool<Vector3>.Claim(path.Count + 1);
     List<Vector3> list3 = ListPool<Vector3>.Claim(path.Count + 1);
     list2.Add(vectorPath[0]);
     list3.Add(vectorPath[0]);
     for (int i = 0; i < path.Count - 1; i++)
     {
         if (!path[i].GetPortal(path[i + 1], list2, list3, false))
         {
             list2.Add((Vector3)path[i].position);
             list3.Add((Vector3)path[i].position);
             list2.Add((Vector3)path[i + 1].position);
             list3.Add((Vector3)path[i + 1].position);
         }
     }
     list2.Add(vectorPath[vectorPath.Count - 1]);
     list3.Add(vectorPath[vectorPath.Count - 1]);
     if (!FunnelModifier.RunFunnel(list2, list3, list))
     {
         list.Add(vectorPath[0]);
         list.Add(vectorPath[vectorPath.Count - 1]);
     }
     ListPool<Vector3>.Release(p.vectorPath);
     p.vectorPath = list;
     ListPool<Vector3>.Release(list2);
     ListPool<Vector3>.Release(list3);
 }
Пример #45
0
 public void OnPathComplete(Pathfinding.Path p)
 {
     Debug.Log("Yay, we got a path back. Did it have an error? " + p.error);
 }
Пример #46
0
        /** Use this for initialization.
         *
         * \param s Optionally provide in order to take tag penalties into account. May be null if you do not use a Seeker\
         * \param p Path to follow
         * \param mergePartEndpoints If true, then adjacent parts that the path is split up in will
         * try to use the same start/end points. For example when using a link on a navmesh graph
         * Instead of first following the path to the center of the node where the link is and then
         * follow the link, the path will be adjusted to go to the exact point where the link starts
         * which usually makes more sense.
         * \param simplificationMode The path can optionally be simplified. This can be a bit expensive for long paths.
         */
        public void Initialize(Seeker s, Path p, bool mergePartEndpoints, bool simplificationMode)
        {
            if (p.error)
            {
                throw new System.ArgumentException("Path has an error");
            }

            List <GraphNode> nodes = p.path;

            if (nodes.Count == 0)
            {
                throw new System.ArgumentException("Path traverses no nodes");
            }

            seeker = s;
            // Release objects back to object pool
            // Yeah, I know, it's casting... but this won't be called much
            for (int i = 0; i < parts.Count; i++)
            {
                var funnelPart  = parts[i] as RichFunnel;
                var specialPart = parts[i] as RichSpecial;
                if (funnelPart != null)
                {
                    ObjectPool <RichFunnel> .Release(ref funnelPart);
                }
                else if (specialPart != null)
                {
                    ObjectPool <RichSpecial> .Release(ref specialPart);
                }
            }

            parts.Clear();
            currentPart = 0;

            // Initialize new

            //Break path into parts
            for (int i = 0; i < nodes.Count; i++)
            {
                if (nodes[i] is TriangleMeshNode)
                {
                    var        graph = AstarData.GetGraph(nodes[i]);
                    RichFunnel f     = ObjectPool <RichFunnel> .Claim().Initialize(this, graph);

                    f.funnelSimplification = simplificationMode;

                    int  sIndex            = i;
                    uint currentGraphIndex = nodes[sIndex].GraphIndex;


                    for (; i < nodes.Count; i++)
                    {
                        if (nodes[i].GraphIndex != currentGraphIndex && !(nodes[i] is NodeLink3Node))
                        {
                            break;
                        }
                    }
                    i--;

                    if (sIndex == 0)
                    {
                        f.exactStart = p.vectorPath[0];
                    }
                    else
                    {
                        f.exactStart = (Vector3)nodes[mergePartEndpoints ? sIndex - 1 : sIndex].position;
                    }

                    if (i == nodes.Count - 1)
                    {
                        f.exactEnd = p.vectorPath[p.vectorPath.Count - 1];
                    }
                    else
                    {
                        f.exactEnd = (Vector3)nodes[mergePartEndpoints ? i + 1 : i].position;
                    }

                    f.BuildFunnelCorridor(nodes, sIndex, i);

                    parts.Add(f);
                }
                else if (NodeLink2.GetNodeLink(nodes[i]) != null)
                {
                    NodeLink2 nl = NodeLink2.GetNodeLink(nodes[i]);

                    int  sIndex            = i;
                    uint currentGraphIndex = nodes[sIndex].GraphIndex;

                    for (i++; i < nodes.Count; i++)
                    {
                        if (nodes[i].GraphIndex != currentGraphIndex)
                        {
                            break;
                        }
                    }
                    i--;

                    if (i - sIndex > 1)
                    {
                        throw new System.Exception("NodeLink2 path length greater than two (2) nodes. " + (i - sIndex));
                    }
                    else if (i - sIndex == 0)
                    {
                        //Just continue, it might be the case that a NodeLink was the closest node
                        continue;
                    }

                    RichSpecial rps = ObjectPool <RichSpecial> .Claim().Initialize(nl, nodes[sIndex]);

                    parts.Add(rps);
                }
            }
        }
Пример #47
0
    /** Called when a requested path has finished calculation.
     * A path is first requested by #SearchPath, it is then calculated, probably in the same or the next frame.
     * Finally it is returned to the seeker which forwards it to this function.\n
     */
    public virtual void OnPathComplete(Pathfinding.Path _p)
    {
        ABPath p = _p as ABPath;

        if (p == null)
        {
            throw new System.Exception("This function only handles ABPaths, do not use special path types");
        }

        canSearchAgain = true;

        //Claim the new path
        p.Claim(this);

        // Path couldn't be calculated of some reason.
        // More info in p.errorLog (debug string)
        if (p.error)
        {
            p.Release(this);
            return;
        }

        //Release the previous path
        if (path != null)
        {
            path.Release(this);
        }

        //Replace the old path
        path = p;

        //Reset some variables
        currentWaypointIndex = 0;
        targetReached        = false;

        //The next row can be used to find out if the path could be found or not
        //If it couldn't (error == true), then a message has probably been logged to the console
        //however it can also be got using p.errorLog
        //if (p.error)

        if (closestOnPathCheck)
        {
            // Simulate movement from the point where the path was requested
            // to where we are right now. This reduces the risk that the agent
            // gets confused because the first point in the path is far away
            // from the current position (possibly behind it which could cause
            // the agent to turn around, and that looks pretty bad).
            Vector3 p1   = Time.time - lastFoundWaypointTime < 0.3f ? lastFoundWaypointPosition : p.originalStartPoint;
            Vector3 p2   = GetFeetPosition();
            Vector3 dir  = p2 - p1;
            float   magn = dir.magnitude;
            dir /= magn;
            int steps = (int)(magn / pickNextWaypointDist);


            for (int i = 0; i <= steps; i++)
            {
                CalculateVelocity(p1);
                p1 += dir;
            }
        }
    }