PointGenerator.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using Pathfinding.Serialization;
  4. namespace Pathfinding {
  5. /// <summary>
  6. /// Basic point graph.
  7. ///
  8. /// The point graph is the most basic graph structure, it consists of a number of interconnected points in space called nodes or waypoints.
  9. /// The point graph takes a Transform object as "root", this Transform will be searched for child objects, every child object will be treated as a node.
  10. /// If <see cref="recursive"/> is enabled, it will also search the child objects of the children recursively.
  11. /// It will then check if any connections between the nodes can be made, first it will check if the distance between the nodes isn't too large (<see cref="maxDistance)"/>
  12. /// and then it will check if the axis aligned distance isn't too high. The axis aligned distance, named <see cref="limits"/>,
  13. /// is useful because usually an AI cannot climb very high, but linking nodes far away from each other,
  14. /// but on the same Y level should still be possible. <see cref="limits"/> and <see cref="maxDistance"/> are treated as being set to infinity if they are set to 0 (zero).
  15. /// Lastly it will check if there are any obstructions between the nodes using
  16. /// <a href="http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html">raycasting</a> which can optionally be thick.
  17. /// One thing to think about when using raycasting is to either place the nodes a small
  18. /// distance above the ground in your scene or to make sure that the ground is not in the raycast mask to avoid the raycast from hitting the ground.
  19. ///
  20. /// Alternatively, a tag can be used to search for nodes.
  21. /// See: http://docs.unity3d.com/Manual/Tags.html
  22. ///
  23. /// For larger graphs, it can take quite some time to scan the graph with the default settings.
  24. /// If you have the pro version you can enable <see cref="optimizeForSparseGraph"/> which will in most cases reduce the calculation times
  25. /// drastically.
  26. ///
  27. /// Note: Does not support linecast because of obvious reasons.
  28. ///
  29. /// [Open online documentation to see images]
  30. /// [Open online documentation to see images]
  31. /// </summary>
  32. [JsonOptIn]
  33. [Pathfinding.Util.Preserve]
  34. public class PointGraph : NavGraph
  35. , IUpdatableGraph {
  36. /// <summary>Childs of this transform are treated as nodes</summary>
  37. [JsonMember]
  38. public Transform root;
  39. /// <summary>If no <see cref="root"/> is set, all nodes with the tag is used as nodes</summary>
  40. [JsonMember]
  41. public string searchTag;
  42. /// <summary>
  43. /// Max distance for a connection to be valid.
  44. /// The value 0 (zero) will be read as infinity and thus all nodes not restricted by
  45. /// other constraints will be added as connections.
  46. ///
  47. /// A negative value will disable any neighbours to be added.
  48. /// It will completely stop the connection processing to be done, so it can save you processing
  49. /// power if you don't these connections.
  50. /// </summary>
  51. [JsonMember]
  52. public float maxDistance;
  53. /// <summary>Max distance along the axis for a connection to be valid. 0 = infinity</summary>
  54. [JsonMember]
  55. public Vector3 limits;
  56. /// <summary>Use raycasts to check connections</summary>
  57. [JsonMember]
  58. public bool raycast = true;
  59. /// <summary>Use the 2D Physics API</summary>
  60. [JsonMember]
  61. public bool use2DPhysics;
  62. /// <summary>Use thick raycast</summary>
  63. [JsonMember]
  64. public bool thickRaycast;
  65. /// <summary>Thick raycast radius</summary>
  66. [JsonMember]
  67. public float thickRaycastRadius = 1;
  68. /// <summary>Recursively search for child nodes to the <see cref="root"/></summary>
  69. [JsonMember]
  70. public bool recursive = true;
  71. /// <summary>Layer mask to use for raycast</summary>
  72. [JsonMember]
  73. public LayerMask mask;
  74. /// <summary>
  75. /// Optimizes the graph for sparse graphs.
  76. ///
  77. /// This can reduce calculation times for both scanning and for normal path requests by huge amounts.
  78. /// It reduces the number of node-node checks that need to be done during scan, and can also optimize getting the nearest node from the graph (such as when querying for a path).
  79. ///
  80. /// Try enabling and disabling this option, check the scan times logged when you scan the graph to see if your graph is suited for this optimization
  81. /// or if it makes it slower.
  82. ///
  83. /// The gain of using this optimization increases with larger graphs, the default scan algorithm is brute force and requires O(n^2) checks, this optimization
  84. /// along with a graph suited for it, requires only O(n) checks during scan (assuming the connection distance limits are reasonable).
  85. ///
  86. /// Warning:
  87. /// When you have this enabled, you will not be able to move nodes around using scripting unless you recalculate the lookup structure at the same time.
  88. /// See: <see cref="RebuildNodeLookup"/>
  89. ///
  90. /// If you enable this during runtime, you will need to call <see cref="RebuildNodeLookup"/> to make sure any existing nodes are added to the lookup structure.
  91. /// If the graph doesn't have any nodes yet or if you are going to scan the graph afterwards then you do not need to do this.
  92. /// </summary>
  93. [JsonMember]
  94. public bool optimizeForSparseGraph;
  95. PointKDTree lookupTree = new PointKDTree();
  96. /// <summary>
  97. /// Longest known connection.
  98. /// In squared Int3 units.
  99. ///
  100. /// See: <see cref="RegisterConnectionLength"/>
  101. /// </summary>
  102. long maximumConnectionLength = 0;
  103. /// <summary>
  104. /// All nodes in this graph.
  105. /// Note that only the first <see cref="nodeCount"/> will be non-null.
  106. ///
  107. /// You can also use the GetNodes method to get all nodes.
  108. /// </summary>
  109. public PointNode[] nodes;
  110. /// <summary>
  111. /// \copydoc Pathfinding::PointGraph::NodeDistanceMode
  112. ///
  113. /// See: <see cref="NodeDistanceMode"/>
  114. ///
  115. /// If you enable this during runtime, you will need to call <see cref="RebuildConnectionDistanceLookup"/> to make sure some cache data is properly recalculated.
  116. /// If the graph doesn't have any nodes yet or if you are going to scan the graph afterwards then you do not need to do this.
  117. /// </summary>
  118. [JsonMember]
  119. public NodeDistanceMode nearestNodeDistanceMode;
  120. /// <summary>Number of nodes in this graph</summary>
  121. public int nodeCount { get; protected set; }
  122. /// <summary>
  123. /// Distance query mode.
  124. /// [Open online documentation to see images]
  125. ///
  126. /// In the image above there are a few red nodes. Assume the agent is the orange circle. Using the Node mode the closest point on the graph that would be found would be the node at the bottom center which
  127. /// may not be what you want. Using the Connection mode it will find the closest point on the connection between the two nodes in the top half of the image.
  128. ///
  129. /// When using the Connection option you may also want to use the Connection option for the Seeker's Start End Modifier snapping options.
  130. /// This is not strictly necessary, but it most cases it is what you want.
  131. ///
  132. /// See: <see cref="Pathfinding.StartEndModifier.exactEndPoint"/>
  133. /// </summary>
  134. public enum NodeDistanceMode {
  135. /// <summary>
  136. /// All nearest node queries find the closest node center.
  137. /// This is the fastest option but it may not be what you want if you have long connections.
  138. /// </summary>
  139. Node,
  140. /// <summary>
  141. /// All nearest node queries find the closest point on edges between nodes.
  142. /// This is useful if you have long connections where the agent might be closer to some unrelated node if it is standing on a long connection between two nodes.
  143. /// This mode is however slower than the Node mode.
  144. /// </summary>
  145. Connection,
  146. }
  147. public override int CountNodes () {
  148. return nodeCount;
  149. }
  150. public override void GetNodes (System.Action<GraphNode> action) {
  151. if (nodes == null) return;
  152. var count = nodeCount;
  153. for (int i = 0; i < count; i++) action(nodes[i]);
  154. }
  155. public override NNInfoInternal GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint) {
  156. return GetNearestInternal(position, constraint, true);
  157. }
  158. public override NNInfoInternal GetNearestForce (Vector3 position, NNConstraint constraint) {
  159. return GetNearestInternal(position, constraint, false);
  160. }
  161. NNInfoInternal GetNearestInternal (Vector3 position, NNConstraint constraint, bool fastCheck) {
  162. if (nodes == null) return new NNInfoInternal();
  163. var iposition = (Int3)position;
  164. if (optimizeForSparseGraph) {
  165. if (nearestNodeDistanceMode == NodeDistanceMode.Node) {
  166. return new NNInfoInternal(lookupTree.GetNearest(iposition, fastCheck ? null : constraint));
  167. } else {
  168. var closestNode = lookupTree.GetNearestConnection(iposition, fastCheck ? null : constraint, maximumConnectionLength);
  169. if (closestNode == null) return new NNInfoInternal();
  170. return FindClosestConnectionPoint(closestNode as PointNode, position);
  171. }
  172. }
  173. float maxDistSqr = constraint == null || constraint.constrainDistance ? AstarPath.active.maxNearestNodeDistanceSqr : float.PositiveInfinity;
  174. maxDistSqr *= Int3.FloatPrecision * Int3.FloatPrecision;
  175. var nnInfo = new NNInfoInternal(null);
  176. long minDist = long.MaxValue;
  177. long minConstDist = long.MaxValue;
  178. for (int i = 0; i < nodeCount; i++) {
  179. PointNode node = nodes[i];
  180. long dist = (iposition - node.position).sqrMagnitudeLong;
  181. if (dist < minDist) {
  182. minDist = dist;
  183. nnInfo.node = node;
  184. }
  185. if (dist < minConstDist && (float)dist < maxDistSqr && (constraint == null || constraint.Suitable(node))) {
  186. minConstDist = dist;
  187. nnInfo.constrainedNode = node;
  188. }
  189. }
  190. if (!fastCheck) nnInfo.node = nnInfo.constrainedNode;
  191. nnInfo.UpdateInfo();
  192. return nnInfo;
  193. }
  194. NNInfoInternal FindClosestConnectionPoint (PointNode node, Vector3 position) {
  195. var closestConnectionPoint = (Vector3)node.position;
  196. var conns = node.connections;
  197. var nodePos = (Vector3)node.position;
  198. var bestDist = float.PositiveInfinity;
  199. if (conns != null) {
  200. for (int i = 0; i < conns.Length; i++) {
  201. var connectionMidpoint = ((UnityEngine.Vector3)conns[i].node.position + nodePos) * 0.5f;
  202. var closestPoint = VectorMath.ClosestPointOnSegment(nodePos, connectionMidpoint, position);
  203. var dist = (closestPoint - position).sqrMagnitude;
  204. if (dist < bestDist) {
  205. bestDist = dist;
  206. closestConnectionPoint = closestPoint;
  207. }
  208. }
  209. }
  210. var result = new NNInfoInternal();
  211. result.node = node;
  212. result.clampedPosition = closestConnectionPoint;
  213. return result;
  214. }
  215. /// <summary>
  216. /// Add a node to the graph at the specified position.
  217. /// Note: Vector3 can be casted to Int3 using (Int3)myVector.
  218. ///
  219. /// Note: This needs to be called when it is safe to update nodes, which is
  220. /// - when scanning
  221. /// - during a graph update
  222. /// - inside a callback registered using AstarPath.AddWorkItem
  223. ///
  224. /// <code>
  225. /// AstarPath.active.AddWorkItem(new AstarWorkItem(ctx => {
  226. /// var graph = AstarPath.active.data.pointGraph;
  227. /// // Add 2 nodes and connect them
  228. /// var node1 = graph.AddNode((Int3)transform.position);
  229. /// var node2 = graph.AddNode((Int3)(transform.position + Vector3.right));
  230. /// var cost = (uint)(node2.position - node1.position).costMagnitude;
  231. /// node1.AddConnection(node2, cost);
  232. /// node2.AddConnection(node1, cost);
  233. /// }));
  234. /// </code>
  235. ///
  236. /// See: runtime-graphs (view in online documentation for working links)
  237. /// </summary>
  238. public PointNode AddNode (Int3 position) {
  239. return AddNode(new PointNode(active), position);
  240. }
  241. /// <summary>
  242. /// Add a node with the specified type to the graph at the specified position.
  243. ///
  244. /// Note: Vector3 can be casted to Int3 using (Int3)myVector.
  245. ///
  246. /// Note: This needs to be called when it is safe to update nodes, which is
  247. /// - when scanning
  248. /// - during a graph update
  249. /// - inside a callback registered using AstarPath.AddWorkItem
  250. ///
  251. /// See: <see cref="AstarPath.AddWorkItem"/>
  252. /// See: runtime-graphs (view in online documentation for working links)
  253. /// </summary>
  254. /// <param name="node">This must be a node created using T(AstarPath.active) right before the call to this method.
  255. /// The node parameter is only there because there is no new(AstarPath) constraint on
  256. /// generic type parameters.</param>
  257. /// <param name="position">The node will be set to this position.</param>
  258. public T AddNode<T>(T node, Int3 position) where T : PointNode {
  259. if (nodes == null || nodeCount == nodes.Length) {
  260. var newNodes = new PointNode[nodes != null ? System.Math.Max(nodes.Length+4, nodes.Length*2) : 4];
  261. if (nodes != null) nodes.CopyTo(newNodes, 0);
  262. nodes = newNodes;
  263. }
  264. node.SetPosition(position);
  265. node.GraphIndex = graphIndex;
  266. node.Walkable = true;
  267. nodes[nodeCount] = node;
  268. nodeCount++;
  269. if (optimizeForSparseGraph) AddToLookup(node);
  270. return node;
  271. }
  272. /// <summary>Recursively counds children of a transform</summary>
  273. protected static int CountChildren (Transform tr) {
  274. int c = 0;
  275. foreach (Transform child in tr) {
  276. c++;
  277. c += CountChildren(child);
  278. }
  279. return c;
  280. }
  281. /// <summary>Recursively adds childrens of a transform as nodes</summary>
  282. protected void AddChildren (ref int c, Transform tr) {
  283. foreach (Transform child in tr) {
  284. nodes[c].position = (Int3)child.position;
  285. nodes[c].Walkable = true;
  286. nodes[c].gameObject = child.gameObject;
  287. c++;
  288. AddChildren(ref c, child);
  289. }
  290. }
  291. /// <summary>
  292. /// Rebuilds the lookup structure for nodes.
  293. ///
  294. /// This is used when <see cref="optimizeForSparseGraph"/> is enabled.
  295. ///
  296. /// You should call this method every time you move a node in the graph manually and
  297. /// you are using <see cref="optimizeForSparseGraph"/>, otherwise pathfinding might not work correctly.
  298. ///
  299. /// You may also call this after you have added many nodes using the
  300. /// <see cref="AddNode"/> method. When adding nodes using the <see cref="AddNode"/> method they
  301. /// will be added to the lookup structure. The lookup structure will
  302. /// rebalance itself when it gets too unbalanced however if you are
  303. /// sure you won't be adding any more nodes in the short term, you can
  304. /// make sure it is perfectly balanced and thus squeeze out the last
  305. /// bit of performance by calling this method. This can improve the
  306. /// performance of the <see cref="GetNearest"/> method slightly. The improvements
  307. /// are on the order of 10-20%.
  308. /// </summary>
  309. public void RebuildNodeLookup () {
  310. if (!optimizeForSparseGraph || nodes == null) {
  311. lookupTree = new PointKDTree();
  312. } else {
  313. lookupTree.Rebuild(nodes, 0, nodeCount);
  314. }
  315. RebuildConnectionDistanceLookup();
  316. }
  317. /// <summary>Rebuilds a cache used when <see cref="nearestNodeDistanceMode"/> = <see cref="NodeDistanceMode.ToConnection"/></summary>
  318. public void RebuildConnectionDistanceLookup () {
  319. maximumConnectionLength = 0;
  320. if (nearestNodeDistanceMode == NodeDistanceMode.Connection) {
  321. for (int j = 0; j < nodeCount; j++) {
  322. var node = nodes[j];
  323. var conns = node.connections;
  324. if (conns != null) {
  325. for (int i = 0; i < conns.Length; i++) {
  326. var dist = (node.position - conns[i].node.position).sqrMagnitudeLong;
  327. RegisterConnectionLength(dist);
  328. }
  329. }
  330. }
  331. }
  332. }
  333. void AddToLookup (PointNode node) {
  334. lookupTree.Add(node);
  335. }
  336. /// <summary>
  337. /// Ensures the graph knows that there is a connection with this length.
  338. /// This is used when the nearest node distance mode is set to ToConnection.
  339. /// If you are modifying node connections yourself (i.e. manipulating the PointNode.connections array) then you must call this function
  340. /// when you add any connections.
  341. ///
  342. /// When using PointNode.AddConnection this is done automatically.
  343. /// It is also done for all nodes when <see cref="RebuildNodeLookup"/> is called.
  344. /// </summary>
  345. /// <param name="sqrLength">The length of the connection in squared Int3 units. This can be calculated using (node1.position - node2.position).sqrMagnitudeLong.</param>
  346. public void RegisterConnectionLength (long sqrLength) {
  347. maximumConnectionLength = System.Math.Max(maximumConnectionLength, sqrLength);
  348. }
  349. protected virtual PointNode[] CreateNodes (int count) {
  350. var nodes = new PointNode[count];
  351. for (int i = 0; i < nodeCount; i++) nodes[i] = new PointNode(active);
  352. return nodes;
  353. }
  354. protected override IEnumerable<Progress> ScanInternal () {
  355. yield return new Progress(0, "Searching for GameObjects");
  356. if (root == null) {
  357. // If there is no root object, try to find nodes with the specified tag instead
  358. GameObject[] gos = searchTag != null? GameObject.FindGameObjectsWithTag(searchTag) : null;
  359. if (gos == null) {
  360. nodes = new PointNode[0];
  361. nodeCount = 0;
  362. } else {
  363. yield return new Progress(0.1f, "Creating nodes");
  364. // Create all the nodes
  365. nodeCount = gos.Length;
  366. nodes = CreateNodes(nodeCount);
  367. for (int i = 0; i < gos.Length; i++) {
  368. nodes[i].position = (Int3)gos[i].transform.position;
  369. nodes[i].Walkable = true;
  370. nodes[i].gameObject = gos[i].gameObject;
  371. }
  372. }
  373. } else {
  374. // Search the root for children and create nodes for them
  375. if (!recursive) {
  376. nodeCount = root.childCount;
  377. nodes = CreateNodes(nodeCount);
  378. int c = 0;
  379. foreach (Transform child in root) {
  380. nodes[c].position = (Int3)child.position;
  381. nodes[c].Walkable = true;
  382. nodes[c].gameObject = child.gameObject;
  383. c++;
  384. }
  385. } else {
  386. nodeCount = CountChildren(root);
  387. nodes = CreateNodes(nodeCount);
  388. int startID = 0;
  389. AddChildren(ref startID, root);
  390. }
  391. }
  392. yield return new Progress(0.15f, "Building node lookup");
  393. // Note that this *must* run every scan
  394. RebuildNodeLookup();
  395. foreach (var progress in ConnectNodesAsync()) yield return progress.MapTo(0.15f, 0.95f);
  396. yield return new Progress(0.95f, "Building connection distances");
  397. // Note that this *must* run every scan
  398. RebuildConnectionDistanceLookup();
  399. }
  400. /// <summary>
  401. /// Recalculates connections for all nodes in the graph.
  402. /// This is useful if you have created nodes manually using <see cref="AddNode"/> and then want to connect them in the same way as the point graph normally connects nodes.
  403. /// </summary>
  404. public void ConnectNodes () {
  405. var ie = ConnectNodesAsync().GetEnumerator();
  406. while (ie.MoveNext()) {}
  407. RebuildConnectionDistanceLookup();
  408. }
  409. /// <summary>
  410. /// Calculates connections for all nodes in the graph.
  411. /// This is an IEnumerable, you can iterate through it using e.g foreach to get progress information.
  412. /// </summary>
  413. IEnumerable<Progress> ConnectNodesAsync () {
  414. if (maxDistance >= 0) {
  415. // To avoid too many allocations, these lists are reused for each node
  416. var connections = new List<Connection>();
  417. var candidateConnections = new List<GraphNode>();
  418. long maxSquaredRange;
  419. // Max possible squared length of a connection between two nodes
  420. // This is used to speed up the calculations by skipping a lot of nodes that do not need to be checked
  421. if (maxDistance == 0 && (limits.x == 0 || limits.y == 0 || limits.z == 0)) {
  422. maxSquaredRange = long.MaxValue;
  423. } else {
  424. maxSquaredRange = (long)(Mathf.Max(limits.x, Mathf.Max(limits.y, Mathf.Max(limits.z, maxDistance))) * Int3.Precision) + 1;
  425. maxSquaredRange *= maxSquaredRange;
  426. }
  427. // Report progress every N nodes
  428. const int YieldEveryNNodes = 512;
  429. // Loop through all nodes and add connections to other nodes
  430. for (int i = 0; i < nodeCount; i++) {
  431. if (i % YieldEveryNNodes == 0) {
  432. yield return new Progress(i/(float)nodeCount, "Connecting nodes");
  433. }
  434. connections.Clear();
  435. var node = nodes[i];
  436. if (optimizeForSparseGraph) {
  437. candidateConnections.Clear();
  438. lookupTree.GetInRange(node.position, maxSquaredRange, candidateConnections);
  439. for (int j = 0; j < candidateConnections.Count; j++) {
  440. var other = candidateConnections[j] as PointNode;
  441. float dist;
  442. if (other != node && IsValidConnection(node, other, out dist)) {
  443. connections.Add(new Connection(
  444. other,
  445. /// <summary>TODO: Is this equal to .costMagnitude</summary>
  446. (uint)Mathf.RoundToInt(dist*Int3.FloatPrecision)
  447. ));
  448. }
  449. }
  450. } else {
  451. // Only brute force is available in the free version
  452. for (int j = 0; j < nodeCount; j++) {
  453. if (i == j) continue;
  454. PointNode other = nodes[j];
  455. float dist;
  456. if (IsValidConnection(node, other, out dist)) {
  457. connections.Add(new Connection(
  458. other,
  459. /// <summary>TODO: Is this equal to .costMagnitude</summary>
  460. (uint)Mathf.RoundToInt(dist*Int3.FloatPrecision)
  461. ));
  462. }
  463. }
  464. }
  465. node.connections = connections.ToArray();
  466. node.SetConnectivityDirty();
  467. }
  468. }
  469. }
  470. /// <summary>
  471. /// Returns if the connection between a and b is valid.
  472. /// Checks for obstructions using raycasts (if enabled) and checks for height differences.
  473. /// As a bonus, it outputs the distance between the nodes too if the connection is valid.
  474. ///
  475. /// Note: This is not the same as checking if node a is connected to node b.
  476. /// That should be done using a.ContainsConnection(b)
  477. /// </summary>
  478. public virtual bool IsValidConnection (GraphNode a, GraphNode b, out float dist) {
  479. dist = 0;
  480. if (!a.Walkable || !b.Walkable) return false;
  481. var dir = (Vector3)(b.position-a.position);
  482. if (
  483. (!Mathf.Approximately(limits.x, 0) && Mathf.Abs(dir.x) > limits.x) ||
  484. (!Mathf.Approximately(limits.y, 0) && Mathf.Abs(dir.y) > limits.y) ||
  485. (!Mathf.Approximately(limits.z, 0) && Mathf.Abs(dir.z) > limits.z)) {
  486. return false;
  487. }
  488. dist = dir.magnitude;
  489. if (maxDistance == 0 || dist < maxDistance) {
  490. if (raycast) {
  491. var ray = new Ray((Vector3)a.position, dir);
  492. var invertRay = new Ray((Vector3)b.position, -dir);
  493. if (use2DPhysics) {
  494. if (thickRaycast) {
  495. return !Physics2D.CircleCast(ray.origin, thickRaycastRadius, ray.direction, dist, mask) && !Physics2D.CircleCast(invertRay.origin, thickRaycastRadius, invertRay.direction, dist, mask);
  496. } else {
  497. return !Physics2D.Linecast((Vector2)(Vector3)a.position, (Vector2)(Vector3)b.position, mask) && !Physics2D.Linecast((Vector2)(Vector3)b.position, (Vector2)(Vector3)a.position, mask);
  498. }
  499. } else {
  500. if (thickRaycast) {
  501. return !Physics.SphereCast(ray, thickRaycastRadius, dist, mask) && !Physics.SphereCast(invertRay, thickRaycastRadius, dist, mask);
  502. } else {
  503. return !Physics.Linecast((Vector3)a.position, (Vector3)b.position, mask) && !Physics.Linecast((Vector3)b.position, (Vector3)a.position, mask);
  504. }
  505. }
  506. } else {
  507. return true;
  508. }
  509. }
  510. return false;
  511. }
  512. GraphUpdateThreading IUpdatableGraph.CanUpdateAsync (GraphUpdateObject o) {
  513. return GraphUpdateThreading.UnityThread;
  514. }
  515. void IUpdatableGraph.UpdateAreaInit (GraphUpdateObject o) {}
  516. void IUpdatableGraph.UpdateAreaPost (GraphUpdateObject o) {}
  517. /// <summary>
  518. /// Updates an area in the list graph.
  519. /// Recalculates possibly affected connections, i.e all connectionlines passing trough the bounds of the guo will be recalculated
  520. /// </summary>
  521. void IUpdatableGraph.UpdateArea (GraphUpdateObject guo) {
  522. if (nodes == null) return;
  523. for (int i = 0; i < nodeCount; i++) {
  524. var node = nodes[i];
  525. if (guo.bounds.Contains((Vector3)node.position)) {
  526. guo.WillUpdateNode(node);
  527. guo.Apply(node);
  528. }
  529. }
  530. if (guo.updatePhysics) {
  531. // Use a copy of the bounding box, we should not change the GUO's bounding box since it might be used for other graph updates
  532. Bounds bounds = guo.bounds;
  533. if (thickRaycast) {
  534. // Expand the bounding box to account for the thick raycast
  535. bounds.Expand(thickRaycastRadius*2);
  536. }
  537. // Create a temporary list used for holding connection data
  538. List<Connection> tmpList = Pathfinding.Util.ListPool<Connection>.Claim();
  539. for (int i = 0; i < nodeCount; i++) {
  540. PointNode node = nodes[i];
  541. var nodePos = (Vector3)node.position;
  542. List<Connection> conn = null;
  543. for (int j = 0; j < nodeCount; j++) {
  544. if (j == i) continue;
  545. var otherNodePos = (Vector3)nodes[j].position;
  546. // Check if this connection intersects the bounding box.
  547. // If it does we need to recalculate that connection.
  548. if (VectorMath.SegmentIntersectsBounds(bounds, nodePos, otherNodePos)) {
  549. float dist;
  550. PointNode other = nodes[j];
  551. bool contains = node.ContainsConnection(other);
  552. bool validConnection = IsValidConnection(node, other, out dist);
  553. // Fill the 'conn' list when we need to change a connection
  554. if (conn == null && (contains != validConnection)) {
  555. tmpList.Clear();
  556. conn = tmpList;
  557. conn.AddRange(node.connections);
  558. }
  559. if (!contains && validConnection) {
  560. // A new connection should be added
  561. uint cost = (uint)Mathf.RoundToInt(dist*Int3.FloatPrecision);
  562. conn.Add(new Connection(other, cost));
  563. RegisterConnectionLength((other.position - node.position).sqrMagnitudeLong);
  564. } else if (contains && !validConnection) {
  565. // A connection should be removed
  566. for (int q = 0; q < conn.Count; q++) {
  567. if (conn[q].node == other) {
  568. conn.RemoveAt(q);
  569. break;
  570. }
  571. }
  572. }
  573. }
  574. }
  575. // Save the new connections if any were changed
  576. if (conn != null) {
  577. node.connections = conn.ToArray();
  578. node.SetConnectivityDirty();
  579. }
  580. }
  581. // Release buffers back to the pool
  582. Pathfinding.Util.ListPool<Connection>.Release(ref tmpList);
  583. }
  584. }
  585. #if UNITY_EDITOR
  586. public override void OnDrawGizmos (Pathfinding.Util.RetainedGizmos gizmos, bool drawNodes) {
  587. base.OnDrawGizmos(gizmos, drawNodes);
  588. if (!drawNodes) return;
  589. Gizmos.color = new Color(0.161f, 0.341f, 1f, 0.5f);
  590. if (root != null) {
  591. DrawChildren(this, root);
  592. } else if (!string.IsNullOrEmpty(searchTag)) {
  593. GameObject[] gos = GameObject.FindGameObjectsWithTag(searchTag);
  594. for (int i = 0; i < gos.Length; i++) {
  595. Gizmos.DrawCube(gos[i].transform.position, Vector3.one*UnityEditor.HandleUtility.GetHandleSize(gos[i].transform.position)*0.1F);
  596. }
  597. }
  598. }
  599. static void DrawChildren (PointGraph graph, Transform tr) {
  600. foreach (Transform child in tr) {
  601. Gizmos.DrawCube(child.position, Vector3.one*UnityEditor.HandleUtility.GetHandleSize(child.position)*0.1F);
  602. if (graph.recursive) DrawChildren(graph, child);
  603. }
  604. }
  605. #endif
  606. protected override void PostDeserialization (GraphSerializationContext ctx) {
  607. RebuildNodeLookup();
  608. }
  609. public override void RelocateNodes (Matrix4x4 deltaMatrix) {
  610. base.RelocateNodes(deltaMatrix);
  611. RebuildNodeLookup();
  612. }
  613. protected override void DeserializeSettingsCompatibility (GraphSerializationContext ctx) {
  614. base.DeserializeSettingsCompatibility(ctx);
  615. root = ctx.DeserializeUnityObject() as Transform;
  616. searchTag = ctx.reader.ReadString();
  617. maxDistance = ctx.reader.ReadSingle();
  618. limits = ctx.DeserializeVector3();
  619. raycast = ctx.reader.ReadBoolean();
  620. use2DPhysics = ctx.reader.ReadBoolean();
  621. thickRaycast = ctx.reader.ReadBoolean();
  622. thickRaycastRadius = ctx.reader.ReadSingle();
  623. recursive = ctx.reader.ReadBoolean();
  624. ctx.reader.ReadBoolean(); // Deprecated field
  625. mask = (LayerMask)ctx.reader.ReadInt32();
  626. optimizeForSparseGraph = ctx.reader.ReadBoolean();
  627. ctx.reader.ReadBoolean(); // Deprecated field
  628. }
  629. protected override void SerializeExtraInfo (GraphSerializationContext ctx) {
  630. // Serialize node data
  631. if (nodes == null) ctx.writer.Write(-1);
  632. // Length prefixed array of nodes
  633. ctx.writer.Write(nodeCount);
  634. for (int i = 0; i < nodeCount; i++) {
  635. // -1 indicates a null field
  636. if (nodes[i] == null) ctx.writer.Write(-1);
  637. else {
  638. ctx.writer.Write(0);
  639. nodes[i].SerializeNode(ctx);
  640. }
  641. }
  642. }
  643. protected override void DeserializeExtraInfo (GraphSerializationContext ctx) {
  644. int count = ctx.reader.ReadInt32();
  645. if (count == -1) {
  646. nodes = null;
  647. return;
  648. }
  649. nodes = new PointNode[count];
  650. nodeCount = count;
  651. for (int i = 0; i < nodes.Length; i++) {
  652. if (ctx.reader.ReadInt32() == -1) continue;
  653. nodes[i] = new PointNode(active);
  654. nodes[i].DeserializeNode(ctx);
  655. }
  656. }
  657. }
  658. }