Path.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. //#define ASTAR_POOL_DEBUG //@SHOWINEDITOR Enables debugging of path pooling. Will log warnings and info messages about paths not beeing pooled correctly.
  2. using UnityEngine;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. namespace Pathfinding {
  6. /// <summary>
  7. /// Provides additional traversal information to a path request.
  8. /// See: turnbased (view in online documentation for working links)
  9. /// </summary>
  10. public interface ITraversalProvider {
  11. bool CanTraverse (Path path, GraphNode node);
  12. uint GetTraversalCost (Path path, GraphNode node);
  13. }
  14. /// <summary>Convenience class to access the default implementation of the ITraversalProvider</summary>
  15. public static class DefaultITraversalProvider {
  16. public static bool CanTraverse (Path path, GraphNode node) {
  17. return node.Walkable && (path.enabledTags >> (int)node.Tag & 0x1) != 0;
  18. }
  19. public static uint GetTraversalCost (Path path, GraphNode node) {
  20. return path.GetTagPenalty((int)node.Tag) + node.Penalty;
  21. }
  22. }
  23. /// <summary>Base class for all path types</summary>
  24. public abstract class Path : IPathInternals {
  25. #if ASTAR_POOL_DEBUG
  26. private string pathTraceInfo = "";
  27. private List<string> claimInfo = new List<string>();
  28. ~Path() {
  29. Debug.Log("Destroying " + GetType().Name + " instance");
  30. if (claimed.Count > 0) {
  31. Debug.LogWarning("Pool Is Leaking. See list of claims:\n" +
  32. "Each message below will list what objects are currently claiming the path." +
  33. " These objects have removed their reference to the path object but has not called .Release on it (which is bad).\n" + pathTraceInfo+"\n");
  34. for (int i = 0; i < claimed.Count; i++) {
  35. Debug.LogWarning("- Claim "+ (i+1) + " is by a " + claimed[i].GetType().Name + "\n"+claimInfo[i]);
  36. }
  37. } else {
  38. Debug.Log("Some scripts are not using pooling.\n" + pathTraceInfo + "\n");
  39. }
  40. }
  41. #endif
  42. /// <summary>Data for the thread calculating this path</summary>
  43. protected PathHandler pathHandler;
  44. /// <summary>
  45. /// Callback to call when the path is complete.
  46. /// This is usually sent to the Seeker component which post processes the path and then calls a callback to the script which requested the path
  47. /// </summary>
  48. public OnPathDelegate callback;
  49. /// <summary>
  50. /// Immediate callback to call when the path is complete.
  51. /// Warning: This may be called from a separate thread. Usually you do not want to use this one.
  52. ///
  53. /// See: callback
  54. /// </summary>
  55. public OnPathDelegate immediateCallback;
  56. /// <summary>Returns the state of the path in the pathfinding pipeline</summary>
  57. public PathState PipelineState { get; private set; }
  58. System.Object stateLock = new object ();
  59. /// <summary>
  60. /// Provides additional traversal information to a path request.
  61. /// See: turnbased (view in online documentation for working links)
  62. /// </summary>
  63. public ITraversalProvider traversalProvider;
  64. /// <summary>Backing field for <see cref="CompleteState"/></summary>
  65. protected PathCompleteState completeState;
  66. /// <summary>
  67. /// Current state of the path.
  68. /// \bug This may currently be set to Complete before the path has actually been fully calculated. In particular the vectorPath and path lists may not have been fully constructed.
  69. /// This can lead to race conditions when using multithreading. Try to avoid using this method to check for if the path is calculated right now, use <see cref="IsDone"/> instead.
  70. /// </summary>
  71. public PathCompleteState CompleteState {
  72. get { return completeState; }
  73. protected set {
  74. // Locking is used to avoid multithreading race conditions
  75. // in which the error state is set on the main thread to cancel the path and then a pathfinding thread marks the path as
  76. // completed which would replace the error state (if a lock and check would not have been used).
  77. lock (stateLock) {
  78. // Once the path is put in the error state, it cannot be set to any other state
  79. if (completeState != PathCompleteState.Error) completeState = value;
  80. }
  81. }
  82. }
  83. /// <summary>
  84. /// If the path failed, this is true.
  85. /// See: <see cref="errorLog"/>
  86. /// See: This is equivalent to checking path.CompleteState == PathCompleteState.Error
  87. /// </summary>
  88. public bool error { get { return CompleteState == PathCompleteState.Error; } }
  89. /// <summary>
  90. /// Additional info on why a path failed.
  91. /// See: <see cref="AstarPath.logPathResults"/>
  92. /// </summary>
  93. public string errorLog { get; private set; }
  94. /// <summary>
  95. /// Holds the path as a Node array. All nodes the path traverses.
  96. /// This may not be the same nodes as the post processed path traverses.
  97. /// </summary>
  98. public List<GraphNode> path;
  99. /// <summary>Holds the (possibly post processed) path as a Vector3 list</summary>
  100. public List<Vector3> vectorPath;
  101. /// <summary>The node currently being processed</summary>
  102. protected PathNode currentR;
  103. /// <summary>How long it took to calculate this path in milliseconds</summary>
  104. public float duration;
  105. /// <summary>Number of nodes this path has searched</summary>
  106. internal int searchedNodes;
  107. /// <summary>
  108. /// True if the path is currently pooled.
  109. /// Do not set this value. Only read. It is used internally.
  110. ///
  111. /// See: PathPool
  112. /// Version: Was named 'recycled' in 3.7.5 and earlier.
  113. /// </summary>
  114. bool IPathInternals.Pooled { get; set; }
  115. /// <summary>
  116. /// True if the path is currently recycled (i.e in the path pool).
  117. /// Do not set this value. Only read. It is used internally.
  118. ///
  119. /// Deprecated: Has been renamed to 'pooled' to use more widely underestood terminology
  120. /// </summary>
  121. [System.Obsolete("Has been renamed to 'Pooled' to use more widely underestood terminology", true)]
  122. internal bool recycled { get { return false; } }
  123. /// <summary>
  124. /// True if the Reset function has been called.
  125. /// Used to alert users when they are doing something wrong.
  126. /// </summary>
  127. protected bool hasBeenReset;
  128. /// <summary>Constraint for how to search for nodes</summary>
  129. public NNConstraint nnConstraint = PathNNConstraint.Default;
  130. /// <summary>
  131. /// Internal linked list implementation.
  132. /// Warning: This is used internally by the system. You should never change this.
  133. /// </summary>
  134. internal Path next;
  135. /// <summary>Determines which heuristic to use</summary>
  136. public Heuristic heuristic;
  137. /// <summary>
  138. /// Scale of the heuristic values.
  139. /// See: AstarPath.heuristicScale
  140. /// </summary>
  141. public float heuristicScale = 1F;
  142. /// <summary>ID of this path. Used to distinguish between different paths</summary>
  143. public ushort pathID { get; private set; }
  144. /// <summary>Target to use for H score calculation. Used alongside <see cref="hTarget"/>.</summary>
  145. protected GraphNode hTargetNode;
  146. /// <summary>Target to use for H score calculations. See: Pathfinding.Node.H</summary>
  147. protected Int3 hTarget;
  148. /// <summary>
  149. /// Which graph tags are traversable.
  150. /// This is a bitmask so -1 = all bits set = all tags traversable.
  151. /// For example, to set bit 5 to true, you would do
  152. /// <code> myPath.enabledTags |= 1 << 5; </code>
  153. /// To set it to false, you would do
  154. /// <code> myPath.enabledTags &= ~(1 << 5); </code>
  155. ///
  156. /// The Seeker has a popup field where you can set which tags to use.
  157. /// Note: If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath.
  158. /// So you need to change the Seeker value via script, not set this value if you want to change it via script.
  159. ///
  160. /// See: CanTraverse
  161. /// </summary>
  162. public int enabledTags = -1;
  163. /// <summary>List of zeroes to use as default tag penalties</summary>
  164. static readonly int[] ZeroTagPenalties = new int[32];
  165. /// <summary>
  166. /// The tag penalties that are actually used.
  167. /// If manualTagPenalties is null, this will be ZeroTagPenalties
  168. /// See: tagPenalties
  169. /// </summary>
  170. protected int[] internalTagPenalties;
  171. /// <summary>
  172. /// Tag penalties set by other scripts
  173. /// See: tagPenalties
  174. /// </summary>
  175. protected int[] manualTagPenalties;
  176. /// <summary>
  177. /// Penalties for each tag.
  178. /// Tag 0 which is the default tag, will have added a penalty of tagPenalties[0].
  179. /// These should only be positive values since the A* algorithm cannot handle negative penalties.
  180. /// Note: This array will never be null. If you try to set it to null or with a length which is not 32. It will be set to "new int[0]".
  181. ///
  182. /// Note: If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath.
  183. /// So you need to change the Seeker value via script, not set this value if you want to change it via script.
  184. ///
  185. /// See: Seeker.tagPenalties
  186. /// </summary>
  187. public int[] tagPenalties {
  188. get {
  189. return manualTagPenalties;
  190. }
  191. set {
  192. if (value == null || value.Length != 32) {
  193. manualTagPenalties = null;
  194. internalTagPenalties = ZeroTagPenalties;
  195. } else {
  196. manualTagPenalties = value;
  197. internalTagPenalties = value;
  198. }
  199. }
  200. }
  201. /// <summary>
  202. /// True for paths that want to search all nodes and not jump over nodes as optimizations.
  203. /// This disables Jump Point Search when that is enabled to prevent e.g ConstantPath and FloodPath
  204. /// to become completely useless.
  205. /// </summary>
  206. internal virtual bool FloodingPath {
  207. get {
  208. return false;
  209. }
  210. }
  211. /// <summary>
  212. /// Total Length of the path.
  213. /// Calculates the total length of the <see cref="vectorPath"/>.
  214. /// Cache this rather than call this function every time since it will calculate the length every time, not just return a cached value.
  215. /// Returns: Total length of <see cref="vectorPath"/>, if <see cref="vectorPath"/> is null positive infinity is returned.
  216. /// </summary>
  217. public float GetTotalLength () {
  218. if (vectorPath == null) return float.PositiveInfinity;
  219. float tot = 0;
  220. for (int i = 0; i < vectorPath.Count-1; i++) tot += Vector3.Distance(vectorPath[i], vectorPath[i+1]);
  221. return tot;
  222. }
  223. /// <summary>
  224. /// Waits until this path has been calculated and returned.
  225. /// Allows for very easy scripting.
  226. /// <code>
  227. /// IEnumerator Start () {
  228. /// var path = seeker.StartPath(transform.position, transform.position + transform.forward*10, null);
  229. /// yield return StartCoroutine(path.WaitForPath());
  230. /// // The path is calculated now
  231. /// }
  232. /// </code>
  233. ///
  234. /// Note: Do not confuse this with AstarPath.WaitForPath. This one will wait using yield until it has been calculated
  235. /// while AstarPath.WaitForPath will halt all operations until the path has been calculated.
  236. ///
  237. /// \throws System.InvalidOperationException if the path is not started. Send the path to Seeker.StartPath or AstarPath.StartPath before calling this function.
  238. ///
  239. /// See: <see cref="BlockUntilCalculated"/>
  240. /// See: https://docs.unity3d.com/Manual/Coroutines.html
  241. /// </summary>
  242. public IEnumerator WaitForPath () {
  243. if (PipelineState == PathState.Created) throw new System.InvalidOperationException("This path has not been started yet");
  244. while (PipelineState != PathState.Returned) yield return null;
  245. }
  246. /// <summary>
  247. /// Blocks until this path has been calculated and returned.
  248. /// Normally it takes a few frames for a path to be calculated and returned.
  249. /// This function will ensure that the path will be calculated when this function returns
  250. /// and that the callback for that path has been called.
  251. ///
  252. /// Use this function only if you really need to.
  253. /// There is a point to spreading path calculations out over several frames.
  254. /// It smoothes out the framerate and makes sure requesting a large
  255. /// number of paths at the same time does not cause lag.
  256. ///
  257. /// Note: Graph updates and other callbacks might get called during the execution of this function.
  258. ///
  259. /// <code>
  260. /// Path p = seeker.StartPath (transform.position, transform.position + Vector3.forward * 10);
  261. /// p.BlockUntilCalculated();
  262. /// // The path is calculated now
  263. /// </code>
  264. ///
  265. /// See: This is equivalent to calling AstarPath.BlockUntilCalculated(Path)
  266. /// See: WaitForPath
  267. /// </summary>
  268. public void BlockUntilCalculated () {
  269. AstarPath.BlockUntilCalculated(this);
  270. }
  271. /// <summary>
  272. /// Estimated cost from the specified node to the target.
  273. /// See: https://en.wikipedia.org/wiki/A*_search_algorithm
  274. /// </summary>
  275. internal uint CalculateHScore (GraphNode node) {
  276. uint h;
  277. switch (heuristic) {
  278. case Heuristic.Euclidean:
  279. h = (uint)(((GetHTarget() - node.position).costMagnitude)*heuristicScale);
  280. return h;
  281. case Heuristic.Manhattan:
  282. Int3 p2 = node.position;
  283. h = (uint)((System.Math.Abs(hTarget.x-p2.x) + System.Math.Abs(hTarget.y-p2.y) + System.Math.Abs(hTarget.z-p2.z))*heuristicScale);
  284. return h;
  285. case Heuristic.DiagonalManhattan:
  286. Int3 p = GetHTarget() - node.position;
  287. p.x = System.Math.Abs(p.x);
  288. p.y = System.Math.Abs(p.y);
  289. p.z = System.Math.Abs(p.z);
  290. int diag = System.Math.Min(p.x, p.z);
  291. int diag2 = System.Math.Max(p.x, p.z);
  292. h = (uint)((((14*diag)/10) + (diag2-diag) + p.y) * heuristicScale);
  293. return h;
  294. }
  295. return 0U;
  296. }
  297. /// <summary>Returns penalty for the given tag.</summary>
  298. /// <param name="tag">A value between 0 (inclusive) and 32 (exclusive).</param>
  299. public uint GetTagPenalty (int tag) {
  300. return (uint)internalTagPenalties[tag];
  301. }
  302. internal Int3 GetHTarget () {
  303. return hTarget;
  304. }
  305. /// <summary>
  306. /// Returns if the node can be traversed.
  307. /// This per default equals to if the node is walkable and if the node's tag is included in <see cref="enabledTags"/>
  308. /// </summary>
  309. internal bool CanTraverse (GraphNode node) {
  310. // Use traversal provider if set, otherwise fall back on default behaviour
  311. // This method is hot, but this branch is extremely well predicted so it
  312. // doesn't affect performance much (profiling indicates it is just above
  313. // the noise level, somewhere around 0%-0.3%)
  314. if (traversalProvider != null)
  315. return traversalProvider.CanTraverse(this, node);
  316. unchecked { return node.Walkable && (enabledTags >> (int)node.Tag & 0x1) != 0; }
  317. }
  318. internal uint GetTraversalCost (GraphNode node) {
  319. #if ASTAR_NO_TRAVERSAL_COST
  320. return 0;
  321. #else
  322. // Use traversal provider if set, otherwise fall back on default behaviour
  323. if (traversalProvider != null)
  324. return traversalProvider.GetTraversalCost(this, node);
  325. unchecked { return GetTagPenalty((int)node.Tag) + node.Penalty; }
  326. #endif
  327. }
  328. /// <summary>
  329. /// May be called by graph nodes to get a special cost for some connections.
  330. /// Nodes may call it when PathNode.flag2 is set to true, for example mesh nodes, which have
  331. /// a very large area can be marked on the start and end nodes, this method will be called
  332. /// to get the actual cost for moving from the start position to its neighbours instead
  333. /// of as would otherwise be the case, from the start node's position to its neighbours.
  334. /// The position of a node and the actual start point on the node can vary quite a lot.
  335. ///
  336. /// The default behaviour of this method is to return the previous cost of the connection,
  337. /// essentiall making no change at all.
  338. ///
  339. /// This method should return the same regardless of the order of a and b.
  340. /// That is f(a,b) == f(b,a) should hold.
  341. /// </summary>
  342. /// <param name="a">Moving from this node</param>
  343. /// <param name="b">Moving to this node</param>
  344. /// <param name="currentCost">The cost of moving between the nodes. Return this value if there is no meaningful special cost to return.</param>
  345. internal virtual uint GetConnectionSpecialCost (GraphNode a, GraphNode b, uint currentCost) {
  346. return currentCost;
  347. }
  348. /// <summary>
  349. /// Returns if this path is done calculating.
  350. ///
  351. /// Note: The callback for the path might not have been called yet.
  352. ///
  353. /// \since Added in 3.0.8
  354. ///
  355. /// See: <see cref="Seeker.IsDone"/> which also takes into account if the %path %callback has been called and had modifiers applied.
  356. /// </summary>
  357. public bool IsDone () {
  358. return PipelineState > PathState.Processing;
  359. }
  360. /// <summary>Threadsafe increment of the state</summary>
  361. void IPathInternals.AdvanceState (PathState s) {
  362. lock (stateLock) {
  363. PipelineState = (PathState)System.Math.Max((int)PipelineState, (int)s);
  364. }
  365. }
  366. /// <summary>
  367. /// Returns the state of the path in the pathfinding pipeline.
  368. /// Deprecated: Use the <see cref="Pathfinding.Path.PipelineState"/> property instead
  369. /// </summary>
  370. [System.Obsolete("Use the 'PipelineState' property instead")]
  371. public PathState GetState () {
  372. return PipelineState;
  373. }
  374. /// <summary>Causes the path to fail and sets <see cref="errorLog"/> to msg</summary>
  375. internal void FailWithError (string msg) {
  376. Error();
  377. if (errorLog != "") errorLog += "\n" + msg;
  378. else errorLog = msg;
  379. }
  380. /// <summary>
  381. /// Logs an error.
  382. /// Deprecated: Use <see cref="FailWithError"/> instead
  383. /// </summary>
  384. [System.Obsolete("Use FailWithError instead")]
  385. internal void LogError (string msg) {
  386. Log(msg);
  387. }
  388. /// <summary>
  389. /// Appends a message to the <see cref="errorLog"/>.
  390. /// Nothing is logged to the console.
  391. ///
  392. /// Note: If AstarPath.logPathResults is PathLog.None and this is a standalone player, nothing will be logged as an optimization.
  393. ///
  394. /// Deprecated: Use <see cref="FailWithError"/> instead
  395. /// </summary>
  396. [System.Obsolete("Use FailWithError instead")]
  397. internal void Log (string msg) {
  398. errorLog += msg;
  399. }
  400. /// <summary>
  401. /// Aborts the path because of an error.
  402. /// Sets <see cref="error"/> to true.
  403. /// This function is called when an error has occurred (e.g a valid path could not be found).
  404. /// See: <see cref="FailWithError"/>
  405. /// </summary>
  406. public void Error () {
  407. CompleteState = PathCompleteState.Error;
  408. }
  409. /// <summary>
  410. /// Performs some error checking.
  411. /// Makes sure the user isn't using old code paths and that no major errors have been made.
  412. ///
  413. /// Causes the path to fail if any errors are found.
  414. /// </summary>
  415. private void ErrorCheck () {
  416. if (!hasBeenReset) FailWithError("Please use the static Construct function for creating paths, do not use the normal constructors.");
  417. if (((IPathInternals)this).Pooled) FailWithError("The path is currently in a path pool. Are you sending the path for calculation twice?");
  418. if (pathHandler == null) FailWithError("Field pathHandler is not set. Please report this bug.");
  419. if (PipelineState > PathState.Processing) FailWithError("This path has already been processed. Do not request a path with the same path object twice.");
  420. }
  421. /// <summary>
  422. /// Called when the path enters the pool.
  423. /// This method should release e.g pooled lists and other pooled resources
  424. /// The base version of this method releases vectorPath and path lists.
  425. /// Reset() will be called after this function, not before.
  426. /// Warning: Do not call this function manually.
  427. /// </summary>
  428. protected virtual void OnEnterPool () {
  429. if (vectorPath != null) Pathfinding.Util.ListPool<Vector3>.Release(ref vectorPath);
  430. if (path != null) Pathfinding.Util.ListPool<GraphNode>.Release(ref path);
  431. // Clear the callback to remove a potential memory leak
  432. // while the path is in the pool (which it could be for a long time).
  433. callback = null;
  434. immediateCallback = null;
  435. traversalProvider = null;
  436. }
  437. /// <summary>
  438. /// Reset all values to their default values.
  439. ///
  440. /// Note: All inheriting path types (e.g ConstantPath, RandomPath, etc.) which declare their own variables need to
  441. /// override this function, resetting ALL their variables to enable pooling of paths.
  442. /// If this is not done, trying to use that path type for pooling could result in weird behaviour.
  443. /// The best way is to reset to default values the variables declared in the extended path type and then
  444. /// call the base function in inheriting types with base.Reset().
  445. /// </summary>
  446. protected virtual void Reset () {
  447. #if ASTAR_POOL_DEBUG
  448. pathTraceInfo = "This path was got from the pool or created from here (stacktrace):\n";
  449. pathTraceInfo += System.Environment.StackTrace;
  450. #endif
  451. if (System.Object.ReferenceEquals(AstarPath.active, null))
  452. throw new System.NullReferenceException("No AstarPath object found in the scene. " +
  453. "Make sure there is one or do not create paths in Awake");
  454. hasBeenReset = true;
  455. PipelineState = (int)PathState.Created;
  456. releasedNotSilent = false;
  457. pathHandler = null;
  458. callback = null;
  459. immediateCallback = null;
  460. errorLog = "";
  461. completeState = PathCompleteState.NotCalculated;
  462. path = Pathfinding.Util.ListPool<GraphNode>.Claim();
  463. vectorPath = Pathfinding.Util.ListPool<Vector3>.Claim();
  464. currentR = null;
  465. duration = 0;
  466. searchedNodes = 0;
  467. nnConstraint = PathNNConstraint.Default;
  468. next = null;
  469. heuristic = AstarPath.active.heuristic;
  470. heuristicScale = AstarPath.active.heuristicScale;
  471. enabledTags = -1;
  472. tagPenalties = null;
  473. pathID = AstarPath.active.GetNextPathID();
  474. hTarget = Int3.zero;
  475. hTargetNode = null;
  476. traversalProvider = null;
  477. }
  478. /// <summary>List of claims on this path with reference objects</summary>
  479. private List<System.Object> claimed = new List<System.Object>();
  480. /// <summary>
  481. /// True if the path has been released with a non-silent call yet.
  482. ///
  483. /// See: Release
  484. /// See: Claim
  485. /// </summary>
  486. private bool releasedNotSilent;
  487. /// <summary>
  488. /// Claim this path (pooling).
  489. /// A claim on a path will ensure that it is not pooled.
  490. /// If you are using a path, you will want to claim it when you first get it and then release it when you will not
  491. /// use it anymore. When there are no claims on the path, it will be reset and put in a pool.
  492. ///
  493. /// This is essentially just reference counting.
  494. ///
  495. /// The object passed to this method is merely used as a way to more easily detect when pooling is not done correctly.
  496. /// It can be any object, when used from a movement script you can just pass "this". This class will throw an exception
  497. /// if you try to call Claim on the same path twice with the same object (which is usually not what you want) or
  498. /// if you try to call Release with an object that has not been used in a Claim call for that path.
  499. /// The object passed to the Claim method needs to be the same as the one you pass to this method.
  500. ///
  501. /// See: Release
  502. /// See: Pool
  503. /// See: pooling (view in online documentation for working links)
  504. /// See: https://en.wikipedia.org/wiki/Reference_counting
  505. /// </summary>
  506. public void Claim (System.Object o) {
  507. if (System.Object.ReferenceEquals(o, null)) throw new System.ArgumentNullException("o");
  508. for (int i = 0; i < claimed.Count; i++) {
  509. // Need to use ReferenceEquals because it might be called from another thread
  510. if (System.Object.ReferenceEquals(claimed[i], o))
  511. throw new System.ArgumentException("You have already claimed the path with that object ("+o+"). Are you claiming the path with the same object twice?");
  512. }
  513. claimed.Add(o);
  514. #if ASTAR_POOL_DEBUG
  515. claimInfo.Add(o.ToString() + "\n\nClaimed from:\n" + System.Environment.StackTrace);
  516. #endif
  517. }
  518. /// <summary>
  519. /// Releases the path silently (pooling).
  520. /// Deprecated: Use Release(o, true) instead
  521. /// </summary>
  522. [System.Obsolete("Use Release(o, true) instead")]
  523. internal void ReleaseSilent (System.Object o) {
  524. Release(o, true);
  525. }
  526. /// <summary>
  527. /// Releases a path claim (pooling).
  528. /// Removes the claim of the path by the specified object.
  529. /// When the claim count reaches zero, the path will be pooled, all variables will be cleared and the path will be put in a pool to be used again.
  530. /// This is great for performance since fewer allocations are made.
  531. ///
  532. /// If the silent parameter is true, this method will remove the claim by the specified object
  533. /// but the path will not be pooled if the claim count reches zero unless a Release call (not silent) has been made earlier.
  534. /// This is used by the internal pathfinding components such as Seeker and AstarPath so that they will not cause paths to be pooled.
  535. /// This enables users to skip the claim/release calls if they want without the path being pooled by the Seeker or AstarPath and
  536. /// thus causing strange bugs.
  537. ///
  538. /// See: Claim
  539. /// See: PathPool
  540. /// </summary>
  541. public void Release (System.Object o, bool silent = false) {
  542. if (o == null) throw new System.ArgumentNullException("o");
  543. for (int i = 0; i < claimed.Count; i++) {
  544. // Need to use ReferenceEquals because it might be called from another thread
  545. if (System.Object.ReferenceEquals(claimed[i], o)) {
  546. claimed.RemoveAt(i);
  547. #if ASTAR_POOL_DEBUG
  548. claimInfo.RemoveAt(i);
  549. #endif
  550. if (!silent) {
  551. releasedNotSilent = true;
  552. }
  553. if (claimed.Count == 0 && releasedNotSilent) {
  554. PathPool.Pool(this);
  555. }
  556. return;
  557. }
  558. }
  559. if (claimed.Count == 0) {
  560. throw new System.ArgumentException("You are releasing a path which is not claimed at all (most likely it has been pooled already). " +
  561. "Are you releasing the path with the same object ("+o+") twice?" +
  562. "\nCheck out the documentation on path pooling for help.");
  563. }
  564. throw new System.ArgumentException("You are releasing a path which has not been claimed with this object ("+o+"). " +
  565. "Are you releasing the path with the same object twice?\n" +
  566. "Check out the documentation on path pooling for help.");
  567. }
  568. /// <summary>
  569. /// Traces the calculated path from the end node to the start.
  570. /// This will build an array (<see cref="path)"/> of the nodes this path will pass through and also set the <see cref="vectorPath"/> array to the <see cref="path"/> arrays positions.
  571. /// Assumes the <see cref="vectorPath"/> and <see cref="path"/> are empty and not null (which will be the case for a correctly initialized path).
  572. /// </summary>
  573. protected virtual void Trace (PathNode from) {
  574. // Current node we are processing
  575. PathNode c = from;
  576. int count = 0;
  577. while (c != null) {
  578. c = c.parent;
  579. count++;
  580. if (count > 2048) {
  581. Debug.LogWarning("Infinite loop? >2048 node path. Remove this message if you really have that long paths (Path.cs, Trace method)");
  582. break;
  583. }
  584. }
  585. // Ensure capacities for lists
  586. AstarProfiler.StartProfile("Check List Capacities");
  587. if (path.Capacity < count) path.Capacity = count;
  588. if (vectorPath.Capacity < count) vectorPath.Capacity = count;
  589. AstarProfiler.EndProfile();
  590. c = from;
  591. for (int i = 0; i < count; i++) {
  592. path.Add(c.node);
  593. c = c.parent;
  594. }
  595. // Reverse
  596. int half = count/2;
  597. for (int i = 0; i < half; i++) {
  598. var tmp = path[i];
  599. path[i] = path[count-i-1];
  600. path[count - i - 1] = tmp;
  601. }
  602. for (int i = 0; i < count; i++) {
  603. vectorPath.Add((Vector3)path[i].position);
  604. }
  605. }
  606. /// <summary>
  607. /// Writes text shared for all overrides of DebugString to the string builder.
  608. /// See: DebugString
  609. /// </summary>
  610. protected void DebugStringPrefix (PathLog logMode, System.Text.StringBuilder text) {
  611. text.Append(error ? "Path Failed : " : "Path Completed : ");
  612. text.Append("Computation Time ");
  613. text.Append(duration.ToString(logMode == PathLog.Heavy ? "0.000 ms " : "0.00 ms "));
  614. text.Append("Searched Nodes ").Append(searchedNodes);
  615. if (!error) {
  616. text.Append(" Path Length ");
  617. text.Append(path == null ? "Null" : path.Count.ToString());
  618. }
  619. }
  620. /// <summary>
  621. /// Writes text shared for all overrides of DebugString to the string builder.
  622. /// See: DebugString
  623. /// </summary>
  624. protected void DebugStringSuffix (PathLog logMode, System.Text.StringBuilder text) {
  625. if (error) {
  626. text.Append("\nError: ").Append(errorLog);
  627. }
  628. // Can only print this from the Unity thread
  629. // since otherwise an exception might be thrown
  630. if (logMode == PathLog.Heavy && !AstarPath.active.IsUsingMultithreading) {
  631. text.Append("\nCallback references ");
  632. if (callback != null) text.Append(callback.Target.GetType().FullName).AppendLine();
  633. else text.AppendLine("NULL");
  634. }
  635. text.Append("\nPath Number ").Append(pathID).Append(" (unique id)");
  636. }
  637. /// <summary>
  638. /// Returns a string with information about it.
  639. /// More information is emitted when logMode == Heavy.
  640. /// An empty string is returned if logMode == None
  641. /// or logMode == OnlyErrors and this path did not fail.
  642. /// </summary>
  643. internal virtual string DebugString (PathLog logMode) {
  644. if (logMode == PathLog.None || (!error && logMode == PathLog.OnlyErrors)) {
  645. return "";
  646. }
  647. // Get a cached string builder for this thread
  648. System.Text.StringBuilder text = pathHandler.DebugStringBuilder;
  649. text.Length = 0;
  650. DebugStringPrefix(logMode, text);
  651. DebugStringSuffix(logMode, text);
  652. return text.ToString();
  653. }
  654. /// <summary>Calls callback to return the calculated path. See: <see cref="callback"/></summary>
  655. protected virtual void ReturnPath () {
  656. if (callback != null) {
  657. callback(this);
  658. }
  659. }
  660. /// <summary>
  661. /// Prepares low level path variables for calculation.
  662. /// Called before a path search will take place.
  663. /// Always called before the Prepare, Initialize and CalculateStep functions
  664. /// </summary>
  665. protected void PrepareBase (PathHandler pathHandler) {
  666. //Path IDs have overflowed 65K, cleanup is needed
  667. //Since pathIDs are handed out sequentially, we can do this
  668. if (pathHandler.PathID > pathID) {
  669. pathHandler.ClearPathIDs();
  670. }
  671. //Make sure the path has a reference to the pathHandler
  672. this.pathHandler = pathHandler;
  673. //Assign relevant path data to the pathHandler
  674. pathHandler.InitializeForPath(this);
  675. // Make sure that internalTagPenalties is an array which has the length 32
  676. if (internalTagPenalties == null || internalTagPenalties.Length != 32)
  677. internalTagPenalties = ZeroTagPenalties;
  678. try {
  679. ErrorCheck();
  680. } catch (System.Exception e) {
  681. FailWithError(e.Message);
  682. }
  683. }
  684. /// <summary>
  685. /// Called before the path is started.
  686. /// Called right before Initialize
  687. /// </summary>
  688. protected abstract void Prepare ();
  689. /// <summary>
  690. /// Always called after the path has been calculated.
  691. /// Guaranteed to be called before other paths have been calculated on
  692. /// the same thread.
  693. /// Use for cleaning up things like node tagging and similar.
  694. /// </summary>
  695. protected virtual void Cleanup () {}
  696. /// <summary>
  697. /// Initializes the path.
  698. /// Sets up the open list and adds the first node to it
  699. /// </summary>
  700. protected abstract void Initialize ();
  701. /// <summary>Calculates the until it is complete or the time has progressed past targetTick</summary>
  702. protected abstract void CalculateStep (long targetTick);
  703. PathHandler IPathInternals.PathHandler { get { return pathHandler; } }
  704. void IPathInternals.OnEnterPool () { OnEnterPool(); }
  705. void IPathInternals.Reset () { Reset(); }
  706. void IPathInternals.ReturnPath () { ReturnPath(); }
  707. void IPathInternals.PrepareBase (PathHandler handler) { PrepareBase(handler); }
  708. void IPathInternals.Prepare () { Prepare(); }
  709. void IPathInternals.Cleanup () { Cleanup(); }
  710. void IPathInternals.Initialize () { Initialize(); }
  711. void IPathInternals.CalculateStep (long targetTick) { CalculateStep(targetTick); }
  712. }
  713. /// <summary>Used for hiding internal methods of the Path class</summary>
  714. internal interface IPathInternals {
  715. PathHandler PathHandler { get; }
  716. bool Pooled { get; set; }
  717. void AdvanceState (PathState s);
  718. void OnEnterPool ();
  719. void Reset ();
  720. void ReturnPath ();
  721. void PrepareBase (PathHandler handler);
  722. void Prepare ();
  723. void Initialize ();
  724. void Cleanup ();
  725. void CalculateStep (long targetTick);
  726. }
  727. }