GraphUpdateScene.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. using UnityEngine;
  2. namespace Pathfinding {
  3. [AddComponentMenu("Pathfinding/GraphUpdateScene")]
  4. /// <summary>
  5. /// Helper class for easily updating graphs.
  6. ///
  7. /// The GraphUpdateScene component is really easy to use. Create a new empty GameObject and add the component to it, it can be found in Components-->Pathfinding-->GraphUpdateScene.\n
  8. /// When you have added the component, you should see something like the image below.
  9. /// [Open online documentation to see images]
  10. /// The region which the component will affect is defined by creating a polygon in the scene.
  11. /// If you make sure you have the Position tool enabled (top-left corner of the Unity window) you can shift+click in the scene view to add more points to the polygon.
  12. /// You can remove points using shift+alt+click.
  13. /// By clicking on the points you can bring up a positioning tool. You can also open the "points" array in the inspector to set each point's coordinates manually.
  14. /// [Open online documentation to see images]
  15. /// In the inspector there are a number of variables. The first one is named "Convex", it sets if the convex hull of the points should be calculated or if the polygon should be used as-is.
  16. /// Using the convex hull is faster when applying the changes to the graph, but with a non-convex polygon you can specify more complicated areas.\n
  17. /// The next two variables, called "Apply On Start" and "Apply On Scan" determine when to apply the changes. If the object is in the scene from the beginning, both can be left on, it doesn't
  18. /// matter since the graph is also scanned at start. However if you instantiate it later in the game, you can make it apply it's setting directly, or wait until the next scan (if any).
  19. /// If the graph is rescanned, all GraphUpdateScene components which have the Apply On Scan variable toggled will apply their settings again to the graph since rescanning clears all previous changes.\n
  20. /// You can also make it apply it's changes using scripting.
  21. /// <code> GetComponent<GraphUpdateScene>().Apply (); </code>
  22. /// The above code will make it apply its changes to the graph (assuming a GraphUpdateScene component is attached to the same GameObject).
  23. ///
  24. /// Next there is "Modify Walkability" and "Set Walkability" (which appears when "Modify Walkability" is toggled).
  25. /// If Modify Walkability is set, then all nodes inside the area will either be set to walkable or unwalkable depending on the value of the "Set Walkability" variable.
  26. ///
  27. /// Penalty can also be applied to the nodes. A higher penalty (aka weight) makes the nodes harder to traverse so it will try to avoid those areas.
  28. ///
  29. /// The tagging variables can be read more about on this page: tags (view in online documentation for working links) "Working with tags".
  30. ///
  31. /// Note: The Y (up) axis of the transform that this component is attached to should be in the same direction as the up direction of the graph.
  32. /// So if you for example have a grid in the XY plane then the transform should have the rotation (-90,0,0).
  33. /// </summary>
  34. [HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_graph_update_scene.php")]
  35. public class GraphUpdateScene : GraphModifier {
  36. /// <summary>Points which define the region to update</summary>
  37. public Vector3[] points;
  38. /// <summary>Private cached convex hull of the <see cref="points"/></summary>
  39. private Vector3[] convexPoints;
  40. /// <summary>
  41. /// Use the convex hull of the points instead of the original polygon.
  42. ///
  43. /// See: https://en.wikipedia.org/wiki/Convex_hull
  44. /// </summary>
  45. public bool convex = true;
  46. /// <summary>
  47. /// Minumum height of the bounds of the resulting Graph Update Object.
  48. /// Useful when all points are laid out on a plane but you still need a bounds with a height greater than zero since a
  49. /// zero height graph update object would usually result in no nodes being updated.
  50. /// </summary>
  51. public float minBoundsHeight = 1;
  52. /// <summary>
  53. /// Penalty to add to nodes.
  54. /// Usually you need quite large values, at least 1000-10000. A higher penalty means that agents will try to avoid those nodes more.
  55. ///
  56. /// Be careful when setting negative values since if a node gets a negative penalty it will underflow and instead get
  57. /// really large. In most cases a warning will be logged if that happens.
  58. ///
  59. /// See: tags (view in online documentation for working links) for another way of applying penalties.
  60. /// </summary>
  61. public int penaltyDelta;
  62. /// <summary>If true, then all affected nodes will be made walkable or unwalkable according to <see cref="setWalkability"/></summary>
  63. public bool modifyWalkability;
  64. /// <summary>Nodes will be made walkable or unwalkable according to this value if <see cref="modifyWalkability"/> is true</summary>
  65. public bool setWalkability;
  66. /// <summary>Apply this graph update object on start</summary>
  67. public bool applyOnStart = true;
  68. /// <summary>Apply this graph update object whenever a graph is rescanned</summary>
  69. public bool applyOnScan = true;
  70. /// <summary>
  71. /// Update node's walkability and connectivity using physics functions.
  72. /// For grid graphs, this will update the node's position and walkability exactly like when doing a scan of the graph.
  73. /// If enabled for grid graphs, <see cref="modifyWalkability"/> will be ignored.
  74. ///
  75. /// For Point Graphs, this will recalculate all connections which passes through the bounds of the resulting Graph Update Object
  76. /// using raycasts (if enabled).
  77. /// </summary>
  78. public bool updatePhysics;
  79. /// <summary>\copydoc Pathfinding::GraphUpdateObject::resetPenaltyOnPhysics</summary>
  80. public bool resetPenaltyOnPhysics = true;
  81. /// <summary>\copydoc Pathfinding::GraphUpdateObject::updateErosion</summary>
  82. public bool updateErosion = true;
  83. /// <summary>
  84. /// Should the tags of the nodes be modified.
  85. /// If enabled, set all nodes' tags to <see cref="setTag"/>
  86. /// </summary>
  87. public bool modifyTag;
  88. /// <summary>If <see cref="modifyTag"/> is enabled, set all nodes' tags to this value</summary>
  89. public int setTag;
  90. /// <summary>Emulates behavior from before version 4.0</summary>
  91. [HideInInspector]
  92. public bool legacyMode = false;
  93. /// <summary>
  94. /// Private cached inversion of <see cref="setTag"/>.
  95. /// Used for InvertSettings()
  96. /// </summary>
  97. private int setTagInvert;
  98. /// <summary>
  99. /// Has apply been called yet.
  100. /// Used to prevent applying twice when both applyOnScan and applyOnStart are enabled
  101. /// </summary>
  102. private bool firstApplied;
  103. [SerializeField]
  104. private int serializedVersion = 0;
  105. /// <summary>
  106. /// Use world space for coordinates.
  107. /// If true, the shape will not follow when moving around the transform.
  108. ///
  109. /// See: <see cref="ToggleUseWorldSpace"/>
  110. /// </summary>
  111. [SerializeField]
  112. [UnityEngine.Serialization.FormerlySerializedAs("useWorldSpace")]
  113. private bool legacyUseWorldSpace;
  114. /// <summary>Do some stuff at start</summary>
  115. public void Start () {
  116. if (!Application.isPlaying) return;
  117. // If firstApplied is true, that means the graph was scanned during Awake.
  118. // So we shouldn't apply it again because then we would end up applying it two times
  119. if (!firstApplied && applyOnStart) {
  120. Apply();
  121. }
  122. }
  123. public override void OnPostScan () {
  124. if (applyOnScan) Apply();
  125. }
  126. /// <summary>
  127. /// Inverts all invertable settings for this GUS.
  128. /// Namely: penalty delta, walkability, tags.
  129. ///
  130. /// Penalty delta will be changed to negative penalty delta.\n
  131. /// <see cref="setWalkability"/> will be inverted.\n
  132. /// <see cref="setTag"/> will be stored in a private variable, and the new value will be 0. When calling this function again, the saved
  133. /// value will be the new value.
  134. ///
  135. /// Calling this function an even number of times without changing any settings in between will be identical to no change in settings.
  136. /// </summary>
  137. public virtual void InvertSettings () {
  138. setWalkability = !setWalkability;
  139. penaltyDelta = -penaltyDelta;
  140. if (setTagInvert == 0) {
  141. setTagInvert = setTag;
  142. setTag = 0;
  143. } else {
  144. setTag = setTagInvert;
  145. setTagInvert = 0;
  146. }
  147. }
  148. /// <summary>
  149. /// Recalculate convex hull.
  150. /// Will not do anything if <see cref="convex"/> is disabled.
  151. /// </summary>
  152. public void RecalcConvex () {
  153. convexPoints = convex ? Polygon.ConvexHullXZ(points) : null;
  154. }
  155. /// <summary>
  156. /// Switches between using world space and using local space.
  157. /// Deprecated: World space can no longer be used as it does not work well with rotated graphs. Use transform.InverseTransformPoint to transform points to local space.
  158. /// </summary>
  159. [System.ObsoleteAttribute("World space can no longer be used as it does not work well with rotated graphs. Use transform.InverseTransformPoint to transform points to local space.", true)]
  160. void ToggleUseWorldSpace () {
  161. }
  162. /// <summary>
  163. /// Lock all points to a specific Y value.
  164. /// Deprecated: The Y coordinate is no longer important. Use the position of the object instead.
  165. /// </summary>
  166. [System.ObsoleteAttribute("The Y coordinate is no longer important. Use the position of the object instead", true)]
  167. public void LockToY () {
  168. }
  169. /// <summary>
  170. /// Calculates the bounds for this component.
  171. /// This is a relatively expensive operation, it needs to go through all points and
  172. /// run matrix multiplications.
  173. /// </summary>
  174. public Bounds GetBounds () {
  175. if (points == null || points.Length == 0) {
  176. Bounds bounds;
  177. var coll = GetComponent<Collider>();
  178. var coll2D = GetComponent<Collider2D>();
  179. var rend = GetComponent<Renderer>();
  180. if (coll != null) bounds = coll.bounds;
  181. else if (coll2D != null) {
  182. bounds = coll2D.bounds;
  183. bounds.size = new Vector3(bounds.size.x, bounds.size.y, Mathf.Max(bounds.size.z, 1f));
  184. } else if (rend != null) {
  185. bounds = rend.bounds;
  186. } else {
  187. return new Bounds(Vector3.zero, Vector3.zero);
  188. }
  189. if (legacyMode && bounds.size.y < minBoundsHeight) bounds.size = new Vector3(bounds.size.x, minBoundsHeight, bounds.size.z);
  190. return bounds;
  191. } else {
  192. return GraphUpdateShape.GetBounds(convex ? convexPoints : points, legacyMode && legacyUseWorldSpace ? Matrix4x4.identity : transform.localToWorldMatrix, minBoundsHeight);
  193. }
  194. }
  195. /// <summary>
  196. /// Updates graphs with a created GUO.
  197. /// Creates a Pathfinding.GraphUpdateObject with a Pathfinding.GraphUpdateShape
  198. /// representing the polygon of this object and update all graphs using AstarPath.UpdateGraphs.
  199. /// This will not update graphs immediately. See AstarPath.UpdateGraph for more info.
  200. /// </summary>
  201. public void Apply () {
  202. if (AstarPath.active == null) {
  203. Debug.LogError("There is no AstarPath object in the scene", this);
  204. return;
  205. }
  206. GraphUpdateObject guo;
  207. if (points == null || points.Length == 0) {
  208. var polygonCollider = GetComponent<PolygonCollider2D>();
  209. if (polygonCollider != null) {
  210. var points2D = polygonCollider.points;
  211. Vector3[] pts = new Vector3[points2D.Length];
  212. for (int i = 0; i < pts.Length; i++) {
  213. var p = points2D[i] + polygonCollider.offset;
  214. pts[i] = new Vector3(p.x, 0, p.y);
  215. }
  216. var mat = transform.localToWorldMatrix * Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(-90, 0, 0), Vector3.one);
  217. var shape = new GraphUpdateShape(points, convex, mat, minBoundsHeight);
  218. guo = new GraphUpdateObject(GetBounds());
  219. guo.shape = shape;
  220. } else {
  221. var bounds = GetBounds();
  222. if (bounds.center == Vector3.zero && bounds.size == Vector3.zero) {
  223. Debug.LogError("Cannot apply GraphUpdateScene, no points defined and no renderer or collider attached", this);
  224. return;
  225. }
  226. guo = new GraphUpdateObject(bounds);
  227. }
  228. } else {
  229. GraphUpdateShape shape;
  230. if (legacyMode && !legacyUseWorldSpace) {
  231. // Used for compatibility with older versions
  232. var worldPoints = new Vector3[points.Length];
  233. for (int i = 0; i < points.Length; i++) worldPoints[i] = transform.TransformPoint(points[i]);
  234. shape = new GraphUpdateShape(worldPoints, convex, Matrix4x4.identity, minBoundsHeight);
  235. } else {
  236. shape = new GraphUpdateShape(points, convex, legacyMode && legacyUseWorldSpace ? Matrix4x4.identity : transform.localToWorldMatrix, minBoundsHeight);
  237. }
  238. var bounds = shape.GetBounds();
  239. guo = new GraphUpdateObject(bounds);
  240. guo.shape = shape;
  241. }
  242. firstApplied = true;
  243. guo.modifyWalkability = modifyWalkability;
  244. guo.setWalkability = setWalkability;
  245. guo.addPenalty = penaltyDelta;
  246. guo.updatePhysics = updatePhysics;
  247. guo.updateErosion = updateErosion;
  248. guo.resetPenaltyOnPhysics = resetPenaltyOnPhysics;
  249. guo.modifyTag = modifyTag;
  250. guo.setTag = setTag;
  251. AstarPath.active.UpdateGraphs(guo);
  252. }
  253. /// <summary>Draws some gizmos</summary>
  254. void OnDrawGizmos () {
  255. OnDrawGizmos(false);
  256. }
  257. /// <summary>Draws some gizmos</summary>
  258. void OnDrawGizmosSelected () {
  259. OnDrawGizmos(true);
  260. }
  261. /// <summary>Draws some gizmos</summary>
  262. void OnDrawGizmos (bool selected) {
  263. Color c = selected ? new Color(227/255f, 61/255f, 22/255f, 1.0f) : new Color(227/255f, 61/255f, 22/255f, 0.9f);
  264. if (selected) {
  265. Gizmos.color = Color.Lerp(c, new Color(1, 1, 1, 0.2f), 0.9f);
  266. Bounds b = GetBounds();
  267. Gizmos.DrawCube(b.center, b.size);
  268. Gizmos.DrawWireCube(b.center, b.size);
  269. }
  270. if (points == null) return;
  271. if (convex) c.a *= 0.5f;
  272. Gizmos.color = c;
  273. Matrix4x4 matrix = legacyMode && legacyUseWorldSpace ? Matrix4x4.identity : transform.localToWorldMatrix;
  274. if (convex) {
  275. c.r -= 0.1f;
  276. c.g -= 0.2f;
  277. c.b -= 0.1f;
  278. Gizmos.color = c;
  279. }
  280. if (selected || !convex) {
  281. for (int i = 0; i < points.Length; i++) {
  282. Gizmos.DrawLine(matrix.MultiplyPoint3x4(points[i]), matrix.MultiplyPoint3x4(points[(i+1)%points.Length]));
  283. }
  284. }
  285. if (convex) {
  286. if (convexPoints == null) RecalcConvex();
  287. Gizmos.color = selected ? new Color(227/255f, 61/255f, 22/255f, 1.0f) : new Color(227/255f, 61/255f, 22/255f, 0.9f);
  288. for (int i = 0; i < convexPoints.Length; i++) {
  289. Gizmos.DrawLine(matrix.MultiplyPoint3x4(convexPoints[i]), matrix.MultiplyPoint3x4(convexPoints[(i+1)%convexPoints.Length]));
  290. }
  291. }
  292. // Draw the full 3D shape
  293. var pts = convex ? convexPoints : points;
  294. if (selected && pts != null && pts.Length > 0) {
  295. Gizmos.color = new Color(1, 1, 1, 0.2f);
  296. float miny = pts[0].y, maxy = pts[0].y;
  297. for (int i = 0; i < pts.Length; i++) {
  298. miny = Mathf.Min(miny, pts[i].y);
  299. maxy = Mathf.Max(maxy, pts[i].y);
  300. }
  301. var extraHeight = Mathf.Max(minBoundsHeight - (maxy - miny), 0) * 0.5f;
  302. miny -= extraHeight;
  303. maxy += extraHeight;
  304. for (int i = 0; i < pts.Length; i++) {
  305. var next = (i+1) % pts.Length;
  306. var p1 = matrix.MultiplyPoint3x4(pts[i] + Vector3.up*(miny - pts[i].y));
  307. var p2 = matrix.MultiplyPoint3x4(pts[i] + Vector3.up*(maxy - pts[i].y));
  308. var p1n = matrix.MultiplyPoint3x4(pts[next] + Vector3.up*(miny - pts[next].y));
  309. var p2n = matrix.MultiplyPoint3x4(pts[next] + Vector3.up*(maxy - pts[next].y));
  310. Gizmos.DrawLine(p1, p2);
  311. Gizmos.DrawLine(p1, p1n);
  312. Gizmos.DrawLine(p2, p2n);
  313. }
  314. }
  315. }
  316. /// <summary>
  317. /// Disables legacy mode if it is enabled.
  318. /// Legacy mode is automatically enabled for components when upgrading from an earlier version than 3.8.6.
  319. /// </summary>
  320. public void DisableLegacyMode () {
  321. if (legacyMode) {
  322. legacyMode = false;
  323. if (legacyUseWorldSpace) {
  324. legacyUseWorldSpace = false;
  325. for (int i = 0; i < points.Length; i++) {
  326. points[i] = transform.InverseTransformPoint(points[i]);
  327. }
  328. RecalcConvex();
  329. }
  330. }
  331. }
  332. protected override void Awake () {
  333. if (serializedVersion == 0) {
  334. // Use the old behavior if some points are already set
  335. if (points != null && points.Length > 0) legacyMode = true;
  336. serializedVersion = 1;
  337. }
  338. base.Awake();
  339. }
  340. }
  341. }