DynamicNavMesh.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. /*
  2. recast4j copyright (c) 2021 Piotr Piastucki piotr@jtilia.org
  3. DotRecast Copyright (c) 2023 Choi Ikpil ikpil@naver.com
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. using System;
  19. using System.Collections.Concurrent;
  20. using System.Collections.Generic;
  21. using System.Collections.ObjectModel;
  22. using System.Linq;
  23. using System.Threading.Tasks;
  24. using DotRecast.Core;
  25. using DotRecast.Detour.Dynamic.Colliders;
  26. using DotRecast.Detour.Dynamic.Io;
  27. using DotRecast.Recast;
  28. namespace DotRecast.Detour.Dynamic
  29. {
  30. public class DynamicNavMesh
  31. {
  32. public const int MAX_VERTS_PER_POLY = 6;
  33. public readonly DynamicNavMeshConfig config;
  34. private readonly RecastBuilder builder;
  35. private readonly Dictionary<long, DynamicTile> _tiles = new Dictionary<long, DynamicTile>();
  36. private readonly RcTelemetry telemetry;
  37. private readonly DtNavMeshParams navMeshParams;
  38. private readonly BlockingCollection<IUpdateQueueItem> updateQueue = new BlockingCollection<IUpdateQueueItem>();
  39. private readonly RcAtomicLong currentColliderId = new RcAtomicLong(0);
  40. private DtNavMesh _navMesh;
  41. private bool dirty = true;
  42. public DynamicNavMesh(VoxelFile voxelFile)
  43. {
  44. config = new DynamicNavMeshConfig(voxelFile.useTiles, voxelFile.tileSizeX, voxelFile.tileSizeZ, voxelFile.cellSize);
  45. config.walkableHeight = voxelFile.walkableHeight;
  46. config.walkableRadius = voxelFile.walkableRadius;
  47. config.walkableClimb = voxelFile.walkableClimb;
  48. config.walkableSlopeAngle = voxelFile.walkableSlopeAngle;
  49. config.maxSimplificationError = voxelFile.maxSimplificationError;
  50. config.maxEdgeLen = voxelFile.maxEdgeLen;
  51. config.minRegionArea = voxelFile.minRegionArea;
  52. config.regionMergeArea = voxelFile.regionMergeArea;
  53. config.vertsPerPoly = voxelFile.vertsPerPoly;
  54. config.buildDetailMesh = voxelFile.buildMeshDetail;
  55. config.detailSampleDistance = voxelFile.detailSampleDistance;
  56. config.detailSampleMaxError = voxelFile.detailSampleMaxError;
  57. builder = new RecastBuilder();
  58. navMeshParams = new DtNavMeshParams();
  59. navMeshParams.orig.x = voxelFile.bounds[0];
  60. navMeshParams.orig.y = voxelFile.bounds[1];
  61. navMeshParams.orig.z = voxelFile.bounds[2];
  62. navMeshParams.tileWidth = voxelFile.cellSize * voxelFile.tileSizeX;
  63. navMeshParams.tileHeight = voxelFile.cellSize * voxelFile.tileSizeZ;
  64. navMeshParams.maxTiles = voxelFile.tiles.Count;
  65. navMeshParams.maxPolys = 0x8000;
  66. foreach (var t in voxelFile.tiles)
  67. {
  68. _tiles.Add(LookupKey(t.tileX, t.tileZ), new DynamicTile(t));
  69. }
  70. ;
  71. telemetry = new RcTelemetry();
  72. }
  73. public DtNavMesh NavMesh()
  74. {
  75. return _navMesh;
  76. }
  77. /**
  78. * Voxel queries require checkpoints to be enabled in {@link DynamicNavMeshConfig}
  79. */
  80. public VoxelQuery VoxelQuery()
  81. {
  82. return new VoxelQuery(navMeshParams.orig, navMeshParams.tileWidth, navMeshParams.tileHeight, LookupHeightfield);
  83. }
  84. private RcHeightfield LookupHeightfield(int x, int z)
  85. {
  86. return GetTileAt(x, z)?.checkpoint.heightfield;
  87. }
  88. public long AddCollider(ICollider collider)
  89. {
  90. long cid = currentColliderId.IncrementAndGet();
  91. updateQueue.Add(new AddColliderQueueItem(cid, collider, GetTiles(collider.Bounds())));
  92. return cid;
  93. }
  94. public void RemoveCollider(long colliderId)
  95. {
  96. updateQueue.Add(new RemoveColliderQueueItem(colliderId, GetTilesByCollider(colliderId)));
  97. }
  98. /**
  99. * Perform full build of the nav mesh
  100. */
  101. public void Build()
  102. {
  103. ProcessQueue();
  104. Rebuild(_tiles.Values);
  105. }
  106. /**
  107. * Perform incremental update of the nav mesh
  108. */
  109. public bool Update()
  110. {
  111. return Rebuild(ProcessQueue());
  112. }
  113. private bool Rebuild(ICollection<DynamicTile> stream)
  114. {
  115. foreach (var dynamicTile in stream)
  116. Rebuild(dynamicTile);
  117. return UpdateNavMesh();
  118. }
  119. private HashSet<DynamicTile> ProcessQueue()
  120. {
  121. var items = ConsumeQueue();
  122. foreach (var item in items)
  123. {
  124. Process(item);
  125. }
  126. return items.SelectMany(i => i.AffectedTiles()).ToHashSet();
  127. }
  128. private List<IUpdateQueueItem> ConsumeQueue()
  129. {
  130. List<IUpdateQueueItem> items = new List<IUpdateQueueItem>();
  131. while (updateQueue.TryTake(out var item))
  132. {
  133. items.Add(item);
  134. }
  135. return items;
  136. }
  137. private void Process(IUpdateQueueItem item)
  138. {
  139. foreach (var tile in item.AffectedTiles())
  140. {
  141. item.Process(tile);
  142. }
  143. }
  144. /**
  145. * Perform full build concurrently using the given {@link ExecutorService}
  146. */
  147. public Task<bool> Build(TaskFactory executor)
  148. {
  149. ProcessQueue();
  150. return Rebuild(_tiles.Values, executor);
  151. }
  152. /**
  153. * Perform incremental update concurrently using the given {@link ExecutorService}
  154. */
  155. public Task<bool> Update(TaskFactory executor)
  156. {
  157. return Rebuild(ProcessQueue(), executor);
  158. }
  159. private Task<bool> Rebuild(ICollection<DynamicTile> tiles, TaskFactory executor)
  160. {
  161. var tasks = tiles.Select(tile => executor.StartNew(() => Rebuild(tile))).ToArray();
  162. return Task.WhenAll(tasks).ContinueWith(k => UpdateNavMesh());
  163. }
  164. private ICollection<DynamicTile> GetTiles(float[] bounds)
  165. {
  166. if (bounds == null)
  167. {
  168. return _tiles.Values;
  169. }
  170. int minx = (int)Math.Floor((bounds[0] - navMeshParams.orig.x) / navMeshParams.tileWidth);
  171. int minz = (int)Math.Floor((bounds[2] - navMeshParams.orig.z) / navMeshParams.tileHeight);
  172. int maxx = (int)Math.Floor((bounds[3] - navMeshParams.orig.x) / navMeshParams.tileWidth);
  173. int maxz = (int)Math.Floor((bounds[5] - navMeshParams.orig.z) / navMeshParams.tileHeight);
  174. List<DynamicTile> tiles = new List<DynamicTile>();
  175. for (int z = minz; z <= maxz; ++z)
  176. {
  177. for (int x = minx; x <= maxx; ++x)
  178. {
  179. DynamicTile tile = GetTileAt(x, z);
  180. if (tile != null)
  181. {
  182. tiles.Add(tile);
  183. }
  184. }
  185. }
  186. return tiles;
  187. }
  188. private List<DynamicTile> GetTilesByCollider(long cid)
  189. {
  190. return _tiles.Values.Where(t => t.ContainsCollider(cid)).ToList();
  191. }
  192. private void Rebuild(DynamicTile tile)
  193. {
  194. DtNavMeshCreateParams option = new DtNavMeshCreateParams();
  195. option.walkableHeight = config.walkableHeight;
  196. dirty = dirty | tile.Build(builder, config, telemetry);
  197. }
  198. private bool UpdateNavMesh()
  199. {
  200. if (dirty)
  201. {
  202. DtNavMesh navMesh = new DtNavMesh(navMeshParams, MAX_VERTS_PER_POLY);
  203. foreach (var t in _tiles.Values)
  204. t.AddTo(navMesh);
  205. this._navMesh = navMesh;
  206. dirty = false;
  207. return true;
  208. }
  209. return false;
  210. }
  211. private DynamicTile GetTileAt(int x, int z)
  212. {
  213. return _tiles.TryGetValue(LookupKey(x, z), out var tile)
  214. ? tile
  215. : null;
  216. }
  217. private long LookupKey(long x, long z)
  218. {
  219. return (z << 32) | x;
  220. }
  221. public List<VoxelTile> VoxelTiles()
  222. {
  223. return _tiles.Values.Select(t => t.voxelTile).ToList();
  224. }
  225. public List<RecastBuilderResult> RecastResults()
  226. {
  227. return _tiles.Values.Select(t => t.recastResult).ToList();
  228. }
  229. }
  230. }