NavMeshAssetManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. using System.Collections.Generic;
  2. using System.IO;
  3. using UnityEditor.Experimental.SceneManagement;
  4. using UnityEditor.SceneManagement;
  5. using UnityEngine.AI;
  6. using UnityEngine;
  7. namespace UnityEditor.AI
  8. {
  9. public class NavMeshAssetManager : ScriptableSingleton<NavMeshAssetManager>
  10. {
  11. internal struct AsyncBakeOperation
  12. {
  13. public NavMeshSurface surface;
  14. public NavMeshData bakeData;
  15. public AsyncOperation bakeOperation;
  16. }
  17. List<AsyncBakeOperation> m_BakeOperations = new List<AsyncBakeOperation>();
  18. internal List<AsyncBakeOperation> GetBakeOperations() { return m_BakeOperations; }
  19. struct SavedPrefabNavMeshData
  20. {
  21. public NavMeshSurface surface;
  22. public NavMeshData navMeshData;
  23. }
  24. List<SavedPrefabNavMeshData> m_PrefabNavMeshDataAssets = new List<SavedPrefabNavMeshData>();
  25. static string GetAndEnsureTargetPath(NavMeshSurface surface)
  26. {
  27. // Create directory for the asset if it does not exist yet.
  28. var activeScenePath = surface.gameObject.scene.path;
  29. var targetPath = "Assets";
  30. if (!string.IsNullOrEmpty(activeScenePath))
  31. {
  32. targetPath = Path.Combine(Path.GetDirectoryName(activeScenePath), Path.GetFileNameWithoutExtension(activeScenePath));
  33. }
  34. else
  35. {
  36. var prefabStage = PrefabStageUtility.GetPrefabStage(surface.gameObject);
  37. var isPartOfPrefab = prefabStage != null && prefabStage.IsPartOfPrefabContents(surface.gameObject);
  38. if (isPartOfPrefab && !string.IsNullOrEmpty(prefabStage.prefabAssetPath))
  39. {
  40. var prefabDirectoryName = Path.GetDirectoryName(prefabStage.prefabAssetPath);
  41. if (!string.IsNullOrEmpty(prefabDirectoryName))
  42. targetPath = prefabDirectoryName;
  43. }
  44. }
  45. if (!Directory.Exists(targetPath))
  46. Directory.CreateDirectory(targetPath);
  47. return targetPath;
  48. }
  49. static void CreateNavMeshAsset(NavMeshSurface surface)
  50. {
  51. var targetPath = GetAndEnsureTargetPath(surface);
  52. var combinedAssetPath = Path.Combine(targetPath, "NavMesh-" + surface.name + ".asset");
  53. combinedAssetPath = AssetDatabase.GenerateUniqueAssetPath(combinedAssetPath);
  54. AssetDatabase.CreateAsset(surface.navMeshData, combinedAssetPath);
  55. }
  56. NavMeshData GetNavMeshAssetToDelete(NavMeshSurface navSurface)
  57. {
  58. if (PrefabUtility.IsPartOfPrefabInstance(navSurface) && !PrefabUtility.IsPartOfModelPrefab(navSurface))
  59. {
  60. // Don't allow deleting the asset belonging to the prefab parent
  61. var parentSurface = PrefabUtility.GetCorrespondingObjectFromSource(navSurface) as NavMeshSurface;
  62. if (parentSurface && navSurface.navMeshData == parentSurface.navMeshData)
  63. return null;
  64. }
  65. // Do not delete the NavMeshData asset referenced from a prefab until the prefab is saved
  66. var prefabStage = PrefabStageUtility.GetPrefabStage(navSurface.gameObject);
  67. var isPartOfPrefab = prefabStage != null && prefabStage.IsPartOfPrefabContents(navSurface.gameObject);
  68. if (isPartOfPrefab && IsCurrentPrefabNavMeshDataStored(navSurface))
  69. return null;
  70. return navSurface.navMeshData;
  71. }
  72. void ClearSurface(NavMeshSurface navSurface)
  73. {
  74. var hasNavMeshData = navSurface.navMeshData != null;
  75. StoreNavMeshDataIfInPrefab(navSurface);
  76. var assetToDelete = GetNavMeshAssetToDelete(navSurface);
  77. navSurface.RemoveData();
  78. if (hasNavMeshData)
  79. {
  80. SetNavMeshData(navSurface, null);
  81. EditorSceneManager.MarkSceneDirty(navSurface.gameObject.scene);
  82. }
  83. if (assetToDelete)
  84. AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(assetToDelete));
  85. }
  86. public void StartBakingSurfaces(UnityEngine.Object[] surfaces)
  87. {
  88. // Remove first to avoid double registration of the callback
  89. EditorApplication.update -= UpdateAsyncBuildOperations;
  90. EditorApplication.update += UpdateAsyncBuildOperations;
  91. foreach (NavMeshSurface surf in surfaces)
  92. {
  93. StoreNavMeshDataIfInPrefab(surf);
  94. var oper = new AsyncBakeOperation();
  95. oper.bakeData = InitializeBakeData(surf);
  96. oper.bakeOperation = surf.UpdateNavMesh(oper.bakeData);
  97. oper.surface = surf;
  98. m_BakeOperations.Add(oper);
  99. }
  100. }
  101. static NavMeshData InitializeBakeData(NavMeshSurface surface)
  102. {
  103. var emptySources = new List<NavMeshBuildSource>();
  104. var emptyBounds = new Bounds();
  105. return UnityEngine.AI.NavMeshBuilder.BuildNavMeshData(surface.GetBuildSettings(), emptySources, emptyBounds
  106. , surface.transform.position, surface.transform.rotation);
  107. }
  108. void UpdateAsyncBuildOperations()
  109. {
  110. foreach (var oper in m_BakeOperations)
  111. {
  112. if (oper.surface == null || oper.bakeOperation == null)
  113. continue;
  114. if (oper.bakeOperation.isDone)
  115. {
  116. var surface = oper.surface;
  117. var delete = GetNavMeshAssetToDelete(surface);
  118. if (delete != null)
  119. AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(delete));
  120. surface.RemoveData();
  121. SetNavMeshData(surface, oper.bakeData);
  122. if (surface.isActiveAndEnabled)
  123. surface.AddData();
  124. CreateNavMeshAsset(surface);
  125. EditorSceneManager.MarkSceneDirty(surface.gameObject.scene);
  126. }
  127. }
  128. m_BakeOperations.RemoveAll(o => o.bakeOperation == null || o.bakeOperation.isDone);
  129. if (m_BakeOperations.Count == 0)
  130. EditorApplication.update -= UpdateAsyncBuildOperations;
  131. }
  132. public bool IsSurfaceBaking(NavMeshSurface surface)
  133. {
  134. if (surface == null)
  135. return false;
  136. foreach (var oper in m_BakeOperations)
  137. {
  138. if (oper.surface == null || oper.bakeOperation == null)
  139. continue;
  140. if (oper.surface == surface)
  141. return true;
  142. }
  143. return false;
  144. }
  145. public void ClearSurfaces(UnityEngine.Object[] surfaces)
  146. {
  147. foreach (NavMeshSurface s in surfaces)
  148. ClearSurface(s);
  149. }
  150. static void SetNavMeshData(NavMeshSurface navSurface, NavMeshData navMeshData)
  151. {
  152. var so = new SerializedObject(navSurface);
  153. var navMeshDataProperty = so.FindProperty("m_NavMeshData");
  154. navMeshDataProperty.objectReferenceValue = navMeshData;
  155. so.ApplyModifiedPropertiesWithoutUndo();
  156. }
  157. void StoreNavMeshDataIfInPrefab(NavMeshSurface surfaceToStore)
  158. {
  159. var prefabStage = PrefabStageUtility.GetPrefabStage(surfaceToStore.gameObject);
  160. var isPartOfPrefab = prefabStage != null && prefabStage.IsPartOfPrefabContents(surfaceToStore.gameObject);
  161. if (!isPartOfPrefab)
  162. return;
  163. // check if data has already been stored for this surface
  164. foreach (var storedAssetInfo in m_PrefabNavMeshDataAssets)
  165. if (storedAssetInfo.surface == surfaceToStore)
  166. return;
  167. if (m_PrefabNavMeshDataAssets.Count == 0)
  168. {
  169. PrefabStage.prefabSaving -= DeleteStoredNavMeshDataAssetsForOwnedSurfaces;
  170. PrefabStage.prefabSaving += DeleteStoredNavMeshDataAssetsForOwnedSurfaces;
  171. PrefabStage.prefabStageClosing -= ForgetUnsavedNavMeshDataChanges;
  172. PrefabStage.prefabStageClosing += ForgetUnsavedNavMeshDataChanges;
  173. }
  174. var isDataOwner = true;
  175. if (PrefabUtility.IsPartOfPrefabInstance(surfaceToStore) && !PrefabUtility.IsPartOfModelPrefab(surfaceToStore))
  176. {
  177. var basePrefabSurface = PrefabUtility.GetCorrespondingObjectFromSource(surfaceToStore) as NavMeshSurface;
  178. isDataOwner = basePrefabSurface == null || surfaceToStore.navMeshData != basePrefabSurface.navMeshData;
  179. }
  180. m_PrefabNavMeshDataAssets.Add(new SavedPrefabNavMeshData { surface = surfaceToStore, navMeshData = isDataOwner ? surfaceToStore.navMeshData : null });
  181. }
  182. bool IsCurrentPrefabNavMeshDataStored(NavMeshSurface surface)
  183. {
  184. if (surface == null)
  185. return false;
  186. foreach (var storedAssetInfo in m_PrefabNavMeshDataAssets)
  187. {
  188. if (storedAssetInfo.surface == surface)
  189. return storedAssetInfo.navMeshData == surface.navMeshData;
  190. }
  191. return false;
  192. }
  193. void DeleteStoredNavMeshDataAssetsForOwnedSurfaces(GameObject gameObjectInPrefab)
  194. {
  195. // Debug.LogFormat("DeleteStoredNavMeshDataAsset() when saving prefab {0}", gameObjectInPrefab.name);
  196. var surfaces = gameObjectInPrefab.GetComponentsInChildren<NavMeshSurface>(true);
  197. foreach (var surface in surfaces)
  198. DeleteStoredPrefabNavMeshDataAsset(surface);
  199. }
  200. void DeleteStoredPrefabNavMeshDataAsset(NavMeshSurface surface)
  201. {
  202. for (var i = m_PrefabNavMeshDataAssets.Count - 1; i >= 0; i--)
  203. {
  204. var storedAssetInfo = m_PrefabNavMeshDataAssets[i];
  205. if (storedAssetInfo.surface == surface)
  206. {
  207. var storedNavMeshData = storedAssetInfo.navMeshData;
  208. if (storedNavMeshData != null && storedNavMeshData != surface.navMeshData)
  209. {
  210. var assetPath = AssetDatabase.GetAssetPath(storedNavMeshData);
  211. AssetDatabase.DeleteAsset(assetPath);
  212. }
  213. m_PrefabNavMeshDataAssets.RemoveAt(i);
  214. break;
  215. }
  216. }
  217. if (m_PrefabNavMeshDataAssets.Count == 0)
  218. {
  219. PrefabStage.prefabSaving -= DeleteStoredNavMeshDataAssetsForOwnedSurfaces;
  220. PrefabStage.prefabStageClosing -= ForgetUnsavedNavMeshDataChanges;
  221. }
  222. }
  223. void ForgetUnsavedNavMeshDataChanges(PrefabStage prefabStage)
  224. {
  225. // Debug.Log("On prefab closing - forget about this object's surfaces and stop caring about prefab saving");
  226. if (prefabStage == null)
  227. return;
  228. var allSurfacesInPrefab = prefabStage.prefabContentsRoot.GetComponentsInChildren<NavMeshSurface>(true);
  229. NavMeshSurface surfaceInPrefab = null;
  230. var index = 0;
  231. do
  232. {
  233. if (allSurfacesInPrefab.Length > 0)
  234. surfaceInPrefab = allSurfacesInPrefab[index];
  235. for (var i = m_PrefabNavMeshDataAssets.Count - 1; i >= 0; i--)
  236. {
  237. var storedPrefabInfo = m_PrefabNavMeshDataAssets[i];
  238. if (storedPrefabInfo.surface == null)
  239. {
  240. // Debug.LogFormat("A surface from the prefab got deleted after it has baked a new NavMesh but it hasn't saved it. Now the unsaved asset gets deleted. ({0})", storedPrefabInfo.navMeshData);
  241. // surface got deleted, thus delete its initial NavMeshData asset
  242. if (storedPrefabInfo.navMeshData != null)
  243. {
  244. var assetPath = AssetDatabase.GetAssetPath(storedPrefabInfo.navMeshData);
  245. AssetDatabase.DeleteAsset(assetPath);
  246. }
  247. m_PrefabNavMeshDataAssets.RemoveAt(i);
  248. }
  249. else if (surfaceInPrefab != null && storedPrefabInfo.surface == surfaceInPrefab)
  250. {
  251. //Debug.LogFormat("The surface {0} from the prefab was storing the original navmesh data and now will be forgotten", surfaceInPrefab);
  252. var baseSurface = PrefabUtility.GetCorrespondingObjectFromSource(surfaceInPrefab) as NavMeshSurface;
  253. if (baseSurface == null || surfaceInPrefab.navMeshData != baseSurface.navMeshData)
  254. {
  255. var assetPath = AssetDatabase.GetAssetPath(surfaceInPrefab.navMeshData);
  256. AssetDatabase.DeleteAsset(assetPath);
  257. //Debug.LogFormat("The surface {0} from the prefab has baked new NavMeshData but did not save this change so the asset has been now deleted. ({1})",
  258. // surfaceInPrefab, assetPath);
  259. }
  260. m_PrefabNavMeshDataAssets.RemoveAt(i);
  261. }
  262. }
  263. } while (++index < allSurfacesInPrefab.Length);
  264. if (m_PrefabNavMeshDataAssets.Count == 0)
  265. {
  266. PrefabStage.prefabSaving -= DeleteStoredNavMeshDataAssetsForOwnedSurfaces;
  267. PrefabStage.prefabStageClosing -= ForgetUnsavedNavMeshDataChanges;
  268. }
  269. }
  270. }
  271. }