TriangleMeshNode.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. using UnityEngine;
  2. using Pathfinding.Serialization;
  3. namespace Pathfinding {
  4. /// <summary>Interface for something that holds a triangle based navmesh</summary>
  5. public interface INavmeshHolder : ITransformedGraph, INavmesh {
  6. /// <summary>Position of vertex number i in the world</summary>
  7. Int3 GetVertex(int i);
  8. /// <summary>
  9. /// Position of vertex number i in coordinates local to the graph.
  10. /// The up direction is always the +Y axis for these coordinates.
  11. /// </summary>
  12. Int3 GetVertexInGraphSpace(int i);
  13. int GetVertexArrayIndex(int index);
  14. /// <summary>Transforms coordinates from graph space to world space</summary>
  15. void GetTileCoordinates(int tileIndex, out int x, out int z);
  16. }
  17. /// <summary>Node represented by a triangle</summary>
  18. public class TriangleMeshNode : MeshNode {
  19. public TriangleMeshNode (AstarPath astar) : base(astar) {}
  20. /// <summary>Internal vertex index for the first vertex</summary>
  21. public int v0;
  22. /// <summary>Internal vertex index for the second vertex</summary>
  23. public int v1;
  24. /// <summary>Internal vertex index for the third vertex</summary>
  25. public int v2;
  26. /// <summary>Holds INavmeshHolder references for all graph indices to be able to access them in a performant manner</summary>
  27. protected static INavmeshHolder[] _navmeshHolders = new INavmeshHolder[0];
  28. /// <summary>Used for synchronised access to the <see cref="_navmeshHolders"/> array</summary>
  29. protected static readonly System.Object lockObject = new System.Object();
  30. public static INavmeshHolder GetNavmeshHolder (uint graphIndex) {
  31. return _navmeshHolders[(int)graphIndex];
  32. }
  33. /// <summary>
  34. /// Sets the internal navmesh holder for a given graph index.
  35. /// Warning: Internal method
  36. /// </summary>
  37. public static void SetNavmeshHolder (int graphIndex, INavmeshHolder graph) {
  38. // We need to lock to make sure that
  39. // the resize operation is thread safe
  40. lock (lockObject) {
  41. if (graphIndex >= _navmeshHolders.Length) {
  42. var gg = new INavmeshHolder[graphIndex+1];
  43. _navmeshHolders.CopyTo(gg, 0);
  44. _navmeshHolders = gg;
  45. }
  46. _navmeshHolders[graphIndex] = graph;
  47. }
  48. }
  49. /// <summary>Set the position of this node to the average of its 3 vertices</summary>
  50. public void UpdatePositionFromVertices () {
  51. Int3 a, b, c;
  52. GetVertices(out a, out b, out c);
  53. position = (a + b + c) * 0.333333f;
  54. }
  55. /// <summary>
  56. /// Return a number identifying a vertex.
  57. /// This number does not necessarily need to be a index in an array but two different vertices (in the same graph) should
  58. /// not have the same vertex numbers.
  59. /// </summary>
  60. public int GetVertexIndex (int i) {
  61. return i == 0 ? v0 : (i == 1 ? v1 : v2);
  62. }
  63. /// <summary>
  64. /// Return a number specifying an index in the source vertex array.
  65. /// The vertex array can for example be contained in a recast tile, or be a navmesh graph, that is graph dependant.
  66. /// This is slower than GetVertexIndex, if you only need to compare vertices, use GetVertexIndex.
  67. /// </summary>
  68. public int GetVertexArrayIndex (int i) {
  69. return GetNavmeshHolder(GraphIndex).GetVertexArrayIndex(i == 0 ? v0 : (i == 1 ? v1 : v2));
  70. }
  71. /// <summary>Returns all 3 vertices of this node in world space</summary>
  72. public void GetVertices (out Int3 v0, out Int3 v1, out Int3 v2) {
  73. // Get the object holding the vertex data for this node
  74. // This is usually a graph or a recast graph tile
  75. var holder = GetNavmeshHolder(GraphIndex);
  76. v0 = holder.GetVertex(this.v0);
  77. v1 = holder.GetVertex(this.v1);
  78. v2 = holder.GetVertex(this.v2);
  79. }
  80. /// <summary>Returns all 3 vertices of this node in graph space</summary>
  81. public void GetVerticesInGraphSpace (out Int3 v0, out Int3 v1, out Int3 v2) {
  82. // Get the object holding the vertex data for this node
  83. // This is usually a graph or a recast graph tile
  84. var holder = GetNavmeshHolder(GraphIndex);
  85. v0 = holder.GetVertexInGraphSpace(this.v0);
  86. v1 = holder.GetVertexInGraphSpace(this.v1);
  87. v2 = holder.GetVertexInGraphSpace(this.v2);
  88. }
  89. public override Int3 GetVertex (int i) {
  90. return GetNavmeshHolder(GraphIndex).GetVertex(GetVertexIndex(i));
  91. }
  92. public Int3 GetVertexInGraphSpace (int i) {
  93. return GetNavmeshHolder(GraphIndex).GetVertexInGraphSpace(GetVertexIndex(i));
  94. }
  95. public override int GetVertexCount () {
  96. // A triangle has 3 vertices
  97. return 3;
  98. }
  99. public override Vector3 ClosestPointOnNode (Vector3 p) {
  100. Int3 a, b, c;
  101. GetVertices(out a, out b, out c);
  102. return Pathfinding.Polygon.ClosestPointOnTriangle((Vector3)a, (Vector3)b, (Vector3)c, p);
  103. }
  104. /// <summary>
  105. /// Closest point on the node when seen from above.
  106. /// This method is mostly for internal use as the <see cref="Pathfinding.NavmeshBase.Linecast"/> methods use it.
  107. ///
  108. /// - The returned point is the closest one on the node to p when seen from above (relative to the graph).
  109. /// This is important mostly for sloped surfaces.
  110. /// - The returned point is an Int3 point in graph space.
  111. /// - It is guaranteed to be inside the node, so if you call <see cref="ContainsPointInGraphSpace"/> with the return value from this method the result is guaranteed to be true.
  112. ///
  113. /// This method is slower than e.g <see cref="ClosestPointOnNode"/> or <see cref="ClosestPointOnNodeXZ"/>.
  114. /// However they do not have the same guarantees as this method has.
  115. /// </summary>
  116. internal Int3 ClosestPointOnNodeXZInGraphSpace (Vector3 p) {
  117. // Get the vertices that make up the triangle
  118. Int3 a, b, c;
  119. GetVerticesInGraphSpace(out a, out b, out c);
  120. // Convert p to graph space
  121. p = GetNavmeshHolder(GraphIndex).transform.InverseTransform(p);
  122. // Find the closest point on the triangle to p when looking at the triangle from above (relative to the graph)
  123. var closest = Pathfinding.Polygon.ClosestPointOnTriangleXZ((Vector3)a, (Vector3)b, (Vector3)c, p);
  124. // Make sure the point is actually inside the node
  125. var i3closest = (Int3)closest;
  126. if (ContainsPointInGraphSpace(i3closest)) {
  127. // Common case
  128. return i3closest;
  129. } else {
  130. // Annoying...
  131. // The closest point when converted from floating point coordinates to integer coordinates
  132. // is not actually inside the node. It needs to be inside the node for some methods
  133. // (like for example Linecast) to work properly.
  134. // Try the 8 integer coordinates around the closest point
  135. // and check if any one of them are completely inside the node.
  136. // This will most likely succeed as it should be very close.
  137. for (int dx = -1; dx <= 1; dx++) {
  138. for (int dz = -1; dz <= 1; dz++) {
  139. if ((dx != 0 || dz != 0)) {
  140. var candidate = new Int3(i3closest.x + dx, i3closest.y, i3closest.z + dz);
  141. if (ContainsPointInGraphSpace(candidate)) return candidate;
  142. }
  143. }
  144. }
  145. // Happens veery rarely.
  146. // Pick the closest vertex of the triangle.
  147. // The vertex is guaranteed to be inside the triangle.
  148. var da = (a - i3closest).sqrMagnitudeLong;
  149. var db = (b - i3closest).sqrMagnitudeLong;
  150. var dc = (c - i3closest).sqrMagnitudeLong;
  151. return da < db ? (da < dc ? a : c) : (db < dc ? b : c);
  152. }
  153. }
  154. public override Vector3 ClosestPointOnNodeXZ (Vector3 p) {
  155. // Get all 3 vertices for this node
  156. Int3 tp1, tp2, tp3;
  157. GetVertices(out tp1, out tp2, out tp3);
  158. return Polygon.ClosestPointOnTriangleXZ((Vector3)tp1, (Vector3)tp2, (Vector3)tp3, p);
  159. }
  160. public override bool ContainsPoint (Vector3 p) {
  161. return ContainsPointInGraphSpace((Int3)GetNavmeshHolder(GraphIndex).transform.InverseTransform(p));
  162. }
  163. public override bool ContainsPointInGraphSpace (Int3 p) {
  164. // Get all 3 vertices for this node
  165. Int3 a, b, c;
  166. GetVerticesInGraphSpace(out a, out b, out c);
  167. if ((long)(b.x - a.x) * (long)(p.z - a.z) - (long)(p.x - a.x) * (long)(b.z - a.z) > 0) return false;
  168. if ((long)(c.x - b.x) * (long)(p.z - b.z) - (long)(p.x - b.x) * (long)(c.z - b.z) > 0) return false;
  169. if ((long)(a.x - c.x) * (long)(p.z - c.z) - (long)(p.x - c.x) * (long)(a.z - c.z) > 0) return false;
  170. return true;
  171. // Equivalent code, but the above code is faster
  172. //return Polygon.IsClockwiseMargin (a,b, p) && Polygon.IsClockwiseMargin (b,c, p) && Polygon.IsClockwiseMargin (c,a, p);
  173. //return Polygon.ContainsPoint(g.GetVertex(v0),g.GetVertex(v1),g.GetVertex(v2),p);
  174. }
  175. public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) {
  176. pathNode.UpdateG(path);
  177. handler.heap.Add(pathNode);
  178. if (connections == null) return;
  179. for (int i = 0; i < connections.Length; i++) {
  180. GraphNode other = connections[i].node;
  181. PathNode otherPN = handler.GetPathNode(other);
  182. if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) other.UpdateRecursiveG(path, otherPN, handler);
  183. }
  184. }
  185. public override void Open (Path path, PathNode pathNode, PathHandler handler) {
  186. if (connections == null) return;
  187. // Flag2 indicates if this node needs special treatment
  188. // with regard to connection costs
  189. bool flag2 = pathNode.flag2;
  190. // Loop through all connections
  191. for (int i = connections.Length-1; i >= 0; i--) {
  192. var conn = connections[i];
  193. var other = conn.node;
  194. // Make sure we can traverse the neighbour
  195. if (path.CanTraverse(conn.node)) {
  196. PathNode pathOther = handler.GetPathNode(conn.node);
  197. // Fast path out, worth it for triangle mesh nodes since they usually have degree 2 or 3
  198. if (pathOther == pathNode.parent) {
  199. continue;
  200. }
  201. uint cost = conn.cost;
  202. if (flag2 || pathOther.flag2) {
  203. // Get special connection cost from the path
  204. // This is used by the start and end nodes
  205. cost = path.GetConnectionSpecialCost(this, conn.node, cost);
  206. }
  207. // Test if we have seen the other node before
  208. if (pathOther.pathID != handler.PathID) {
  209. // We have not seen the other node before
  210. // So the path from the start through this node to the other node
  211. // must be the shortest one so far
  212. // Might not be assigned
  213. pathOther.node = conn.node;
  214. pathOther.parent = pathNode;
  215. pathOther.pathID = handler.PathID;
  216. pathOther.cost = cost;
  217. pathOther.H = path.CalculateHScore(other);
  218. pathOther.UpdateG(path);
  219. handler.heap.Add(pathOther);
  220. } else {
  221. // If not we can test if the path from this node to the other one is a better one than the one already used
  222. if (pathNode.G + cost + path.GetTraversalCost(other) < pathOther.G) {
  223. pathOther.cost = cost;
  224. pathOther.parent = pathNode;
  225. other.UpdateRecursiveG(path, pathOther, handler);
  226. }
  227. }
  228. }
  229. }
  230. }
  231. /// <summary>
  232. /// Returns the edge which is shared with other.
  233. /// If no edge is shared, -1 is returned.
  234. /// If there is a connection with the other node, but the connection is not marked as using a particular edge of the shape of the node
  235. /// then Connection.NoSharedEdge will be returned.
  236. ///
  237. /// The vertices in the edge can be retrieved using
  238. /// <code>
  239. /// var edge = node.SharedEdge(other);
  240. /// var a = node.GetVertex(edge);
  241. /// var b = node.GetVertex((edge+1) % node.GetVertexCount());
  242. /// </code>
  243. ///
  244. /// See: <see cref="GetPortal"/> which also handles edges that are shared over tile borders and some types of node links
  245. /// </summary>
  246. public int SharedEdge (GraphNode other) {
  247. var edge = -1;
  248. if (connections != null) {
  249. for (int i = 0; i < connections.Length; i++) {
  250. if (connections[i].node == other) edge = connections[i].shapeEdge;
  251. }
  252. }
  253. return edge;
  254. }
  255. public override bool GetPortal (GraphNode toNode, System.Collections.Generic.List<Vector3> left, System.Collections.Generic.List<Vector3> right, bool backwards) {
  256. int aIndex, bIndex;
  257. return GetPortal(toNode, left, right, backwards, out aIndex, out bIndex);
  258. }
  259. public bool GetPortal (GraphNode toNode, System.Collections.Generic.List<Vector3> left, System.Collections.Generic.List<Vector3> right, bool backwards, out int aIndex, out int bIndex) {
  260. aIndex = -1;
  261. bIndex = -1;
  262. //If the nodes are in different graphs, this function has no idea on how to find a shared edge.
  263. if (backwards || toNode.GraphIndex != GraphIndex) return false;
  264. // Since the nodes are in the same graph, they are both TriangleMeshNodes
  265. // So we don't need to care about other types of nodes
  266. var toTriNode = toNode as TriangleMeshNode;
  267. var edge = SharedEdge(toTriNode);
  268. // A connection was found, but it specifically didn't use an edge
  269. if (edge == Connection.NoSharedEdge) return false;
  270. // No connection was found between the nodes
  271. // Check if there is a node link that connects them
  272. if (edge == -1) {
  273. #if !ASTAR_NO_POINT_GRAPH
  274. if (connections != null) {
  275. for (int i = 0; i < connections.Length; i++) {
  276. if (connections[i].node.GraphIndex != GraphIndex) {
  277. var mid = connections[i].node as NodeLink3Node;
  278. if (mid != null && mid.GetOther(this) == toTriNode) {
  279. // We have found a node which is connected through a NodeLink3Node
  280. mid.GetPortal(toTriNode, left, right, false);
  281. return true;
  282. }
  283. }
  284. }
  285. }
  286. #endif
  287. return false;
  288. }
  289. aIndex = edge;
  290. bIndex = (edge + 1) % GetVertexCount();
  291. // Get the vertices of the shared edge for the first node
  292. Int3 v1a = GetVertex(edge);
  293. Int3 v1b = GetVertex((edge+1) % GetVertexCount());
  294. // Get tile indices
  295. int tileIndex1 = (GetVertexIndex(0) >> NavmeshBase.TileIndexOffset) & NavmeshBase.TileIndexMask;
  296. int tileIndex2 = (toTriNode.GetVertexIndex(0) >> NavmeshBase.TileIndexOffset) & NavmeshBase.TileIndexMask;
  297. if (tileIndex1 != tileIndex2) {
  298. // When the nodes are in different tiles, the edges might not be completely identical
  299. // so another technique is needed.
  300. // Get the tile coordinates, from them we can figure out which edge is going to be shared
  301. int x1, x2, z1, z2, coord;
  302. INavmeshHolder nm = GetNavmeshHolder(GraphIndex);
  303. nm.GetTileCoordinates(tileIndex1, out x1, out z1);
  304. nm.GetTileCoordinates(tileIndex2, out x2, out z2);
  305. if (System.Math.Abs(x1-x2) == 1) coord = 2;
  306. else if (System.Math.Abs(z1-z2) == 1) coord = 0;
  307. else return false; // Tiles are not adjacent. This is likely a custom connection between two nodes.
  308. var otherEdge = toTriNode.SharedEdge(this);
  309. // A connection was found, but it specifically didn't use an edge. This is odd since the connection in the other direction did use an edge
  310. if (otherEdge == Connection.NoSharedEdge) throw new System.Exception("Connection used edge in one direction, but not in the other direction. Has the wrong overload of AddConnection been used?");
  311. // If it is -1 then it must be a one-way connection. Fall back to using the whole edge
  312. if (otherEdge != -1) {
  313. // When the nodes are in different tiles, they might not share exactly the same edge
  314. // so we clamp the portal to the segment of the edges which they both have.
  315. int mincoord = System.Math.Min(v1a[coord], v1b[coord]);
  316. int maxcoord = System.Math.Max(v1a[coord], v1b[coord]);
  317. // Get the vertices of the shared edge for the second node
  318. Int3 v2a = toTriNode.GetVertex(otherEdge);
  319. Int3 v2b = toTriNode.GetVertex((otherEdge+1) % toTriNode.GetVertexCount());
  320. mincoord = System.Math.Max(mincoord, System.Math.Min(v2a[coord], v2b[coord]));
  321. maxcoord = System.Math.Min(maxcoord, System.Math.Max(v2a[coord], v2b[coord]));
  322. if (v1a[coord] < v1b[coord]) {
  323. v1a[coord] = mincoord;
  324. v1b[coord] = maxcoord;
  325. } else {
  326. v1a[coord] = maxcoord;
  327. v1b[coord] = mincoord;
  328. }
  329. }
  330. }
  331. if (left != null) {
  332. // All triangles should be laid out in clockwise order so v1b is the rightmost vertex (seen from this node)
  333. left.Add((Vector3)v1a);
  334. right.Add((Vector3)v1b);
  335. }
  336. return true;
  337. }
  338. /// <summary>TODO: This is the area in XZ space, use full 3D space for higher correctness maybe?</summary>
  339. public override float SurfaceArea () {
  340. var holder = GetNavmeshHolder(GraphIndex);
  341. return System.Math.Abs(VectorMath.SignedTriangleAreaTimes2XZ(holder.GetVertex(v0), holder.GetVertex(v1), holder.GetVertex(v2))) * 0.5f;
  342. }
  343. public override Vector3 RandomPointOnSurface () {
  344. // Find a random point inside the triangle
  345. // This generates uniformly distributed trilinear coordinates
  346. // See http://mathworld.wolfram.com/TrianglePointPicking.html
  347. float r1;
  348. float r2;
  349. do {
  350. r1 = Random.value;
  351. r2 = Random.value;
  352. } while (r1+r2 > 1);
  353. var holder = GetNavmeshHolder(GraphIndex);
  354. // Pick the point corresponding to the trilinear coordinate
  355. return ((Vector3)(holder.GetVertex(v1)-holder.GetVertex(v0)))*r1 + ((Vector3)(holder.GetVertex(v2)-holder.GetVertex(v0)))*r2 + (Vector3)holder.GetVertex(v0);
  356. }
  357. public override void SerializeNode (GraphSerializationContext ctx) {
  358. base.SerializeNode(ctx);
  359. ctx.writer.Write(v0);
  360. ctx.writer.Write(v1);
  361. ctx.writer.Write(v2);
  362. }
  363. public override void DeserializeNode (GraphSerializationContext ctx) {
  364. base.DeserializeNode(ctx);
  365. v0 = ctx.reader.ReadInt32();
  366. v1 = ctx.reader.ReadInt32();
  367. v2 = ctx.reader.ReadInt32();
  368. }
  369. }
  370. }