AstarPathEditor.cs 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  1. using UnityEngine;
  2. using UnityEditor;
  3. using System.Collections.Generic;
  4. using System.Reflection;
  5. namespace Pathfinding {
  6. [CustomEditor(typeof(AstarPath))]
  7. public class AstarPathEditor : Editor {
  8. /// <summary>List of all graph editors available (e.g GridGraphEditor)</summary>
  9. static Dictionary<string, CustomGraphEditorAttribute> graphEditorTypes = new Dictionary<string, CustomGraphEditorAttribute>();
  10. /// <summary>
  11. /// Holds node counts for each graph to avoid calculating it every frame.
  12. /// Only used for visualization purposes
  13. /// </summary>
  14. static Dictionary<NavGraph, KeyValuePair<float, KeyValuePair<int, int> > > graphNodeCounts;
  15. /// <summary>List of all graph editors for the graphs</summary>
  16. GraphEditor[] graphEditors;
  17. System.Type[] graphTypes {
  18. get {
  19. return script.data.graphTypes;
  20. }
  21. }
  22. static int lastUndoGroup = -1000;
  23. /// <summary>Used to make sure correct behaviour when handling undos</summary>
  24. static uint ignoredChecksum;
  25. const string scriptsFolder = "Assets/AstarPathfindingProject";
  26. #region SectionFlags
  27. static bool showSettings;
  28. static bool customAreaColorsOpen;
  29. static bool editTags;
  30. FadeArea settingsArea;
  31. FadeArea colorSettingsArea;
  32. FadeArea editorSettingsArea;
  33. FadeArea aboutArea;
  34. FadeArea optimizationSettingsArea;
  35. FadeArea serializationSettingsArea;
  36. FadeArea tagsArea;
  37. FadeArea graphsArea;
  38. FadeArea addGraphsArea;
  39. FadeArea alwaysVisibleArea;
  40. #endregion
  41. /// <summary>AstarPath instance that is being inspected</summary>
  42. public AstarPath script { get; private set; }
  43. #region Styles
  44. static bool stylesLoaded;
  45. public static GUISkin astarSkin { get; private set; }
  46. static GUIStyle level0AreaStyle, level0LabelStyle;
  47. static GUIStyle level1AreaStyle, level1LabelStyle;
  48. static GUIStyle graphDeleteButtonStyle, graphInfoButtonStyle, graphGizmoButtonStyle, graphEditNameButtonStyle;
  49. public static GUIStyle helpBox { get; private set; }
  50. public static GUIStyle thinHelpBox { get; private set; }
  51. #endregion
  52. /// <summary>Holds defines found in script files, used for optimizations.</summary>
  53. List<OptimizationHandler.DefineDefinition> defines;
  54. /// <summary>Enables editor stuff. Loads graphs, reads settings and sets everything up</summary>
  55. public void OnEnable () {
  56. script = target as AstarPath;
  57. // Make sure all references are set up to avoid NullReferenceExceptions
  58. script.ConfigureReferencesInternal();
  59. Undo.undoRedoPerformed += OnUndoRedoPerformed;
  60. // Search the assembly for graph types and graph editors
  61. if (graphEditorTypes == null || graphEditorTypes.Count == 0)
  62. FindGraphTypes();
  63. try {
  64. GetAstarEditorSettings();
  65. } catch (System.Exception e) {
  66. Debug.LogException(e);
  67. }
  68. LoadStyles();
  69. // Load graphs only when not playing, or in extreme cases, when data.graphs is null
  70. if ((!Application.isPlaying && (script.data == null || script.data.graphs == null || script.data.graphs.Length == 0)) || script.data.graphs == null) {
  71. LoadGraphs();
  72. }
  73. CreateFadeAreas();
  74. }
  75. void CreateFadeAreas () {
  76. if (settingsArea == null) {
  77. aboutArea = new FadeArea(false, this, level0AreaStyle, level0LabelStyle);
  78. optimizationSettingsArea = new FadeArea(false, this, level0AreaStyle, level0LabelStyle);
  79. graphsArea = new FadeArea(false, this, level0AreaStyle, level0LabelStyle);
  80. serializationSettingsArea = new FadeArea(false, this, level0AreaStyle, level0LabelStyle);
  81. settingsArea = new FadeArea(showSettings, this, level0AreaStyle, level0LabelStyle);
  82. addGraphsArea = new FadeArea(false, this, level1AreaStyle, level1LabelStyle);
  83. colorSettingsArea = new FadeArea(false, this, level1AreaStyle, level1LabelStyle);
  84. editorSettingsArea = new FadeArea(false, this, level1AreaStyle, level1LabelStyle);
  85. alwaysVisibleArea = new FadeArea(true, this, level1AreaStyle, level1LabelStyle);
  86. tagsArea = new FadeArea(editTags, this, level1AreaStyle, level1LabelStyle);
  87. }
  88. }
  89. /// <summary>Cleans up editor stuff</summary>
  90. public void OnDisable () {
  91. Undo.undoRedoPerformed -= OnUndoRedoPerformed;
  92. if (target == null) {
  93. return;
  94. }
  95. SetAstarEditorSettings();
  96. CheckGraphEditors();
  97. SaveGraphsAndUndo();
  98. script = null;
  99. }
  100. /// <summary>Reads settings frome EditorPrefs</summary>
  101. void GetAstarEditorSettings () {
  102. FadeArea.fancyEffects = EditorPrefs.GetBool("EditorGUILayoutx.fancyEffects", true);
  103. }
  104. void SetAstarEditorSettings () {
  105. EditorPrefs.SetBool("EditorGUILayoutx.fancyEffects", FadeArea.fancyEffects);
  106. }
  107. /// <summary>
  108. /// Repaints Scene View.
  109. /// Warning: Uses Undocumented Unity Calls (should be safe for Unity 3.x though)
  110. /// </summary>
  111. void RepaintSceneView () {
  112. if (!Application.isPlaying || EditorApplication.isPaused) SceneView.RepaintAll();
  113. }
  114. /// <summary>Tell Unity that we want to use the whole inspector width</summary>
  115. public override bool UseDefaultMargins () {
  116. return false;
  117. }
  118. public override void OnInspectorGUI () {
  119. // Do some loading and checking
  120. if (!LoadStyles()) {
  121. EditorGUILayout.HelpBox("The GUISkin 'AstarEditorSkin.guiskin' in the folder "+EditorResourceHelper.editorAssets+"/ was not found or some custom styles in it does not exist.\n"+
  122. "This file is required for the A* Pathfinding Project editor.\n\n"+
  123. "If you are trying to add A* to a new project, please do not copy the files outside Unity, "+
  124. "export them as a UnityPackage and import them to this project or download the package from the Asset Store"+
  125. "or the 'scripts only' package from the A* Pathfinding Project website.\n\n\n"+
  126. "Skin loading is done in the AstarPathEditor.cs --> LoadStyles method", MessageType.Error);
  127. return;
  128. }
  129. #if UNITY_2020_1_OR_NEWER
  130. if (UnityEditor.EditorSettings.enterPlayModeOptionsEnabled && (UnityEditor.EditorSettings.enterPlayModeOptions & EnterPlayModeOptions.DisableSceneReload) != 0) {
  131. EditorGUILayout.HelpBox("The enter play mode option 'Scene Reload' must be enabled. This package does not support it being disabled. Disabling domain reload is supported however.", MessageType.Error);
  132. if (GUILayout.Button("Enable the Scene Reload option")) {
  133. UnityEditor.EditorSettings.enterPlayModeOptions &= ~EnterPlayModeOptions.DisableSceneReload;
  134. }
  135. EditorGUILayout.Separator();
  136. }
  137. #endif
  138. #if ASTAR_ATAVISM
  139. EditorGUILayout.HelpBox("This is a special version of the A* Pathfinding Project for Atavism. This version only supports scanning recast graphs and exporting them, but no pathfinding during runtime.", MessageType.Info);
  140. #endif
  141. EditorGUI.BeginChangeCheck();
  142. Undo.RecordObject(script, "A* inspector");
  143. CheckGraphEditors();
  144. // End loading and checking
  145. EditorGUI.indentLevel = 1;
  146. // Apparently these can sometimes get eaten by unity components
  147. // so I catch them here for later use
  148. EventType storedEventType = Event.current.type;
  149. string storedEventCommand = Event.current.commandName;
  150. DrawMainArea();
  151. GUILayout.Space(5);
  152. if (GUILayout.Button(new GUIContent("Scan", "Recalculate all graphs. Shortcut cmd+alt+s ( ctrl+alt+s on windows )"))) {
  153. MenuScan();
  154. }
  155. #if ProfileAstar
  156. if (GUILayout.Button("Log Profiles")) {
  157. AstarProfiler.PrintResults();
  158. AstarProfiler.PrintFastResults();
  159. AstarProfiler.Reset();
  160. }
  161. #endif
  162. // Handle undo
  163. SaveGraphsAndUndo(storedEventType, storedEventCommand);
  164. if (EditorGUI.EndChangeCheck()) {
  165. RepaintSceneView();
  166. EditorUtility.SetDirty(script);
  167. }
  168. }
  169. /// <summary>
  170. /// Loads GUISkin and sets up styles.
  171. /// See: EditorResourceHelper.LocateEditorAssets
  172. /// Returns: True if all styles were found, false if there was an error somewhere
  173. /// </summary>
  174. static bool LoadStyles () {
  175. if (stylesLoaded) return true;
  176. // Dummy styles in case the loading fails
  177. var inspectorSkin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector);
  178. if (!EditorResourceHelper.LocateEditorAssets()) {
  179. return false;
  180. }
  181. var skinPath = EditorResourceHelper.editorAssets + "/AstarEditorSkin" + (EditorGUIUtility.isProSkin ? "Dark" : "Light") + ".guiskin";
  182. astarSkin = AssetDatabase.LoadAssetAtPath(skinPath, typeof(GUISkin)) as GUISkin;
  183. if (astarSkin != null) {
  184. astarSkin.button = inspectorSkin.button;
  185. } else {
  186. Debug.LogWarning("Could not load editor skin at '" + skinPath + "'");
  187. return false;
  188. }
  189. level0AreaStyle = astarSkin.FindStyle("PixelBox");
  190. // If the first style is null, then the rest are likely corrupted as well
  191. // Probably due to the user not copying meta files
  192. if (level0AreaStyle == null) {
  193. return false;
  194. }
  195. level1LabelStyle = astarSkin.FindStyle("BoxHeader");
  196. level0LabelStyle = astarSkin.FindStyle("TopBoxHeader");
  197. level1AreaStyle = astarSkin.FindStyle("PixelBox3");
  198. graphDeleteButtonStyle = astarSkin.FindStyle("PixelButton");
  199. graphInfoButtonStyle = astarSkin.FindStyle("InfoButton");
  200. graphGizmoButtonStyle = astarSkin.FindStyle("GizmoButton");
  201. graphEditNameButtonStyle = astarSkin.FindStyle("EditButton");
  202. helpBox = inspectorSkin.FindStyle("HelpBox") ?? inspectorSkin.box;
  203. thinHelpBox = new GUIStyle(helpBox);
  204. thinHelpBox.stretchWidth = false;
  205. thinHelpBox.clipping = TextClipping.Overflow;
  206. thinHelpBox.overflow.bottom += 2;
  207. stylesLoaded = true;
  208. return true;
  209. }
  210. /// <summary>Draws the main area in the inspector</summary>
  211. void DrawMainArea () {
  212. CheckGraphEditors();
  213. graphsArea.Begin();
  214. graphsArea.Header("Graphs", ref script.showGraphs);
  215. if (graphsArea.BeginFade()) {
  216. bool anyNonNull = false;
  217. for (int i = 0; i < script.graphs.Length; i++) {
  218. if (script.graphs[i] != null) {
  219. anyNonNull = true;
  220. DrawGraph(graphEditors[i]);
  221. }
  222. }
  223. // Draw the Add Graph button
  224. addGraphsArea.Begin();
  225. addGraphsArea.open |= !anyNonNull;
  226. addGraphsArea.Header("Add New Graph");
  227. if (addGraphsArea.BeginFade()) {
  228. if (graphTypes == null) script.data.FindGraphTypes();
  229. for (int i = 0; i < graphTypes.Length; i++) {
  230. if (graphEditorTypes.ContainsKey(graphTypes[i].Name)) {
  231. if (GUILayout.Button(graphEditorTypes[graphTypes[i].Name].displayName)) {
  232. addGraphsArea.open = false;
  233. AddGraph(graphTypes[i]);
  234. }
  235. } else if (!graphTypes[i].Name.Contains("Base")) {
  236. EditorGUI.BeginDisabledGroup(true);
  237. GUILayout.Label(graphTypes[i].Name + " (no editor found)", "Button");
  238. EditorGUI.EndDisabledGroup();
  239. }
  240. }
  241. }
  242. addGraphsArea.End();
  243. }
  244. graphsArea.End();
  245. DrawSettings();
  246. DrawSerializationSettings();
  247. DrawOptimizationSettings();
  248. DrawAboutArea();
  249. bool showNavGraphs = EditorGUILayout.Toggle("Show Graphs", script.showNavGraphs);
  250. if (script.showNavGraphs != showNavGraphs) {
  251. script.showNavGraphs = showNavGraphs;
  252. RepaintSceneView();
  253. }
  254. }
  255. /// <summary>Draws optimizations settings.</summary>
  256. void DrawOptimizationSettings () {
  257. optimizationSettingsArea.Begin();
  258. optimizationSettingsArea.Header("Optimization");
  259. if (optimizationSettingsArea.BeginFade()) {
  260. defines = defines ?? OptimizationHandler.FindDefines();
  261. EditorGUILayout.HelpBox("Using C# pre-processor directives, performance and memory usage can be improved by disabling features that you don't use in the project.\n" +
  262. "Every change to these settings requires recompiling the scripts", MessageType.Info);
  263. foreach (var define in defines) {
  264. EditorGUILayout.Separator();
  265. var label = new GUIContent(ObjectNames.NicifyVariableName(define.name), define.description);
  266. define.enabled = EditorGUILayout.Toggle(label, define.enabled);
  267. EditorGUILayout.HelpBox(define.description, MessageType.None);
  268. if (!define.consistent) {
  269. GUIUtilityx.PushTint(Color.red);
  270. EditorGUILayout.HelpBox("This define is not consistent for all build targets, some have it enabled enabled some have it disabled. Press Apply to change them to the same value", MessageType.Error);
  271. GUIUtilityx.PopTint();
  272. }
  273. }
  274. EditorGUILayout.Separator();
  275. GUILayout.BeginHorizontal();
  276. GUILayout.FlexibleSpace();
  277. if (GUILayout.Button("Apply", GUILayout.Width(150))) {
  278. if (EditorUtility.DisplayDialog("Apply Optimizations", "Applying optimizations requires (in case anything changed) a recompilation of the scripts. The inspector also has to be reloaded. Do you want to continue?", "Ok", "Cancel")) {
  279. OptimizationHandler.ApplyDefines(defines);
  280. AssetDatabase.Refresh();
  281. defines = null;
  282. }
  283. }
  284. GUILayout.FlexibleSpace();
  285. GUILayout.EndHorizontal();
  286. }
  287. optimizationSettingsArea.End();
  288. }
  289. /// <summary>
  290. /// Returns a version with all fields fully defined.
  291. /// This is used because by default new Version(3,0,0) > new Version(3,0).
  292. /// This is not the desired behaviour so we make sure that all fields are defined here
  293. /// </summary>
  294. public static System.Version FullyDefinedVersion (System.Version v) {
  295. return new System.Version(Mathf.Max(v.Major, 0), Mathf.Max(v.Minor, 0), Mathf.Max(v.Build, 0), Mathf.Max(v.Revision, 0));
  296. }
  297. void DrawAboutArea () {
  298. aboutArea.Begin();
  299. GUILayout.BeginHorizontal();
  300. if (GUILayout.Button("About", level0LabelStyle)) {
  301. aboutArea.open = !aboutArea.open;
  302. GUI.changed = true;
  303. }
  304. #if !ASTAR_ATAVISM
  305. System.Version newVersion = AstarUpdateChecker.latestVersion;
  306. bool beta = false;
  307. // Check if either the latest release version or the latest beta version is newer than this version
  308. if (FullyDefinedVersion(AstarUpdateChecker.latestVersion) > FullyDefinedVersion(AstarPath.Version) || FullyDefinedVersion(AstarUpdateChecker.latestBetaVersion) > FullyDefinedVersion(AstarPath.Version)) {
  309. if (FullyDefinedVersion(AstarUpdateChecker.latestVersion) <= FullyDefinedVersion(AstarPath.Version)) {
  310. newVersion = AstarUpdateChecker.latestBetaVersion;
  311. beta = true;
  312. }
  313. }
  314. // Check if the latest version is newer than this version
  315. if (FullyDefinedVersion(newVersion) > FullyDefinedVersion(AstarPath.Version)) {
  316. GUIUtilityx.PushTint(Color.green);
  317. if (GUILayout.Button((beta ? "Beta" : "New") + " Version Available! "+newVersion, thinHelpBox, GUILayout.Height(15))) {
  318. Application.OpenURL(AstarUpdateChecker.GetURL("download"));
  319. }
  320. GUIUtilityx.PopTint();
  321. GUILayout.Space(20);
  322. }
  323. #endif
  324. GUILayout.EndHorizontal();
  325. if (aboutArea.BeginFade()) {
  326. GUILayout.Label("The A* Pathfinding Project was made by Aron Granberg\nYour current version is "+AstarPath.Version);
  327. #if !ASTAR_ATAVISM
  328. if (FullyDefinedVersion(newVersion) > FullyDefinedVersion(AstarPath.Version)) {
  329. EditorGUILayout.HelpBox("A new "+(beta ? "beta " : "")+"version of the A* Pathfinding Project is available, the new version is "+
  330. newVersion, MessageType.Info);
  331. if (GUILayout.Button("What's new?")) {
  332. Application.OpenURL(AstarUpdateChecker.GetURL(beta ? "beta_changelog" : "changelog"));
  333. }
  334. if (GUILayout.Button("Click here to find out more")) {
  335. Application.OpenURL(AstarUpdateChecker.GetURL("findoutmore"));
  336. }
  337. GUIUtilityx.PushTint(new Color(0.3F, 0.9F, 0.3F));
  338. if (GUILayout.Button("Download new version")) {
  339. Application.OpenURL(AstarUpdateChecker.GetURL("download"));
  340. }
  341. GUIUtilityx.PopTint();
  342. }
  343. #endif
  344. if (GUILayout.Button(new GUIContent("Documentation", "Open the documentation for the A* Pathfinding Project"))) {
  345. Application.OpenURL(AstarUpdateChecker.GetURL("documentation"));
  346. }
  347. if (GUILayout.Button(new GUIContent("Project Homepage", "Open the homepage for the A* Pathfinding Project"))) {
  348. Application.OpenURL(AstarUpdateChecker.GetURL("homepage"));
  349. }
  350. }
  351. aboutArea.End();
  352. }
  353. /// <summary>Graph editor which has its 'name' field focused</summary>
  354. GraphEditor graphNameFocused;
  355. void DrawGraphHeader (GraphEditor graphEditor) {
  356. var graph = graphEditor.target;
  357. // Graph guid, just used to get a unique value
  358. string graphGUIDString = graph.guid.ToString();
  359. GUILayout.BeginHorizontal();
  360. if (graphNameFocused == graphEditor) {
  361. GUI.SetNextControlName(graphGUIDString);
  362. graph.name = GUILayout.TextField(graph.name ?? "", level1LabelStyle, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(false));
  363. // Mark the name field as deselected when it has been deselected or when the user presses Return or Escape
  364. if ((Event.current.type == EventType.Repaint && GUI.GetNameOfFocusedControl() != graphGUIDString) || (Event.current.type == EventType.KeyUp && (Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.Escape))) {
  365. if (Event.current.type == EventType.KeyUp) Event.current.Use();
  366. graphNameFocused = null;
  367. }
  368. } else {
  369. // If the graph name text field is not focused and the graph name is empty, then fill it in
  370. if (graph.name == null || graph.name == "") graph.name = graphEditorTypes[graph.GetType().Name].displayName;
  371. if (GUILayout.Button(graph.name, level1LabelStyle)) {
  372. graphEditor.fadeArea.open = graph.open = !graph.open;
  373. if (!graph.open) {
  374. graph.infoScreenOpen = false;
  375. }
  376. RepaintSceneView();
  377. }
  378. }
  379. #pragma warning disable 0618
  380. if (script.prioritizeGraphs) {
  381. #pragma warning restore 0618
  382. var moveUp = GUILayout.Button(new GUIContent("Up", "Increase the graph priority"), GUILayout.Width(40));
  383. var moveDown = GUILayout.Button(new GUIContent("Down", "Decrease the graph priority"), GUILayout.Width(40));
  384. if (moveUp || moveDown) {
  385. int index = script.data.GetGraphIndex(graph);
  386. int next;
  387. if (moveUp) {
  388. // Find the previous non null graph
  389. next = index-1;
  390. for (; next >= 0; next--) if (script.graphs[next] != null) break;
  391. } else {
  392. // Find the next non null graph
  393. next = index+1;
  394. for (; next < script.graphs.Length; next++) if (script.graphs[next] != null) break;
  395. }
  396. if (next >= 0 && next < script.graphs.Length) {
  397. NavGraph tmp = script.graphs[next];
  398. script.graphs[next] = graph;
  399. script.graphs[index] = tmp;
  400. GraphEditor tmpEditor = graphEditors[next];
  401. graphEditors[next] = graphEditors[index];
  402. graphEditors[index] = tmpEditor;
  403. }
  404. CheckGraphEditors();
  405. Repaint();
  406. }
  407. }
  408. // The OnInspectorGUI method ensures that the scene view is repainted when gizmos are toggled on or off by checking for EndChangeCheck
  409. graph.drawGizmos = GUILayout.Toggle(graph.drawGizmos, new GUIContent("Draw Gizmos", "Draw Gizmos"), graphGizmoButtonStyle);
  410. if (GUILayout.Button(new GUIContent("", "Edit Name"), graphEditNameButtonStyle)) {
  411. graphNameFocused = graphEditor;
  412. GUI.FocusControl(graphGUIDString);
  413. }
  414. if (GUILayout.Toggle(graph.infoScreenOpen, new GUIContent("Info", "Info"), graphInfoButtonStyle)) {
  415. if (!graph.infoScreenOpen) {
  416. graphEditor.infoFadeArea.open = graph.infoScreenOpen = true;
  417. graphEditor.fadeArea.open = graph.open = true;
  418. }
  419. } else {
  420. graphEditor.infoFadeArea.open = graph.infoScreenOpen = false;
  421. }
  422. if (GUILayout.Button(new GUIContent("Delete", "Delete"), graphDeleteButtonStyle)) {
  423. RemoveGraph(graph);
  424. }
  425. GUILayout.EndHorizontal();
  426. }
  427. void DrawGraphInfoArea (GraphEditor graphEditor) {
  428. graphEditor.infoFadeArea.Begin();
  429. if (graphEditor.infoFadeArea.BeginFade()) {
  430. bool anyNodesNull = false;
  431. int total = 0;
  432. int numWalkable = 0;
  433. // Calculate number of nodes in the graph
  434. KeyValuePair<float, KeyValuePair<int, int> > pair;
  435. graphNodeCounts = graphNodeCounts ?? new Dictionary<NavGraph, KeyValuePair<float, KeyValuePair<int, int> > >();
  436. if (!graphNodeCounts.TryGetValue(graphEditor.target, out pair) || (Time.realtimeSinceStartup-pair.Key) > 2) {
  437. graphEditor.target.GetNodes(node => {
  438. if (node == null) {
  439. anyNodesNull = true;
  440. } else {
  441. total++;
  442. if (node.Walkable) numWalkable++;
  443. }
  444. });
  445. pair = new KeyValuePair<float, KeyValuePair<int, int> >(Time.realtimeSinceStartup, new KeyValuePair<int, int>(total, numWalkable));
  446. graphNodeCounts[graphEditor.target] = pair;
  447. }
  448. total = pair.Value.Key;
  449. numWalkable = pair.Value.Value;
  450. EditorGUI.indentLevel++;
  451. if (anyNodesNull) {
  452. Debug.LogError("Some nodes in the graph are null. Please report this error.");
  453. }
  454. EditorGUILayout.LabelField("Nodes", total.ToString());
  455. EditorGUILayout.LabelField("Walkable", numWalkable.ToString());
  456. EditorGUILayout.LabelField("Unwalkable", (total-numWalkable).ToString());
  457. if (total == 0) EditorGUILayout.HelpBox("The number of nodes in the graph is zero. The graph might not be scanned", MessageType.Info);
  458. EditorGUI.indentLevel--;
  459. }
  460. graphEditor.infoFadeArea.End();
  461. }
  462. /// <summary>Draws the inspector for the given graph with the given graph editor</summary>
  463. void DrawGraph (GraphEditor graphEditor) {
  464. graphEditor.fadeArea.Begin();
  465. DrawGraphHeader(graphEditor);
  466. if (graphEditor.fadeArea.BeginFade()) {
  467. DrawGraphInfoArea(graphEditor);
  468. graphEditor.OnInspectorGUI(graphEditor.target);
  469. graphEditor.OnBaseInspectorGUI(graphEditor.target);
  470. }
  471. graphEditor.fadeArea.End();
  472. }
  473. public void OnSceneGUI () {
  474. script = target as AstarPath;
  475. DrawSceneGUISettings();
  476. // OnSceneGUI may be called from EditorUtility.DisplayProgressBar
  477. // which is called repeatedly while the graphs are scanned in the
  478. // editor. However running the OnSceneGUI method while the graphs
  479. // are being scanned is a bad idea since it can interfere with
  480. // scanning, especially by serializing changes
  481. if (script.isScanning) {
  482. return;
  483. }
  484. script.ConfigureReferencesInternal();
  485. EditorGUI.BeginChangeCheck();
  486. if (!LoadStyles()) return;
  487. // Some GUI controls might change this to Used, so we need to grab it here
  488. EventType et = Event.current.type;
  489. CheckGraphEditors();
  490. for (int i = 0; i < script.graphs.Length; i++) {
  491. NavGraph graph = script.graphs[i];
  492. if (graph != null) {
  493. graphEditors[i].OnSceneGUI(graph);
  494. }
  495. }
  496. SaveGraphsAndUndo(et);
  497. if (EditorGUI.EndChangeCheck()) {
  498. EditorUtility.SetDirty(target);
  499. }
  500. }
  501. void DrawSceneGUISettings () {
  502. var darkSkin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Scene);
  503. Handles.BeginGUI();
  504. float width = 180;
  505. float height = 76;
  506. float margin = 10;
  507. var origWidth = EditorGUIUtility.labelWidth;
  508. EditorGUIUtility.labelWidth = 144;
  509. GUILayout.BeginArea(new Rect(Camera.current.pixelWidth - width, Camera.current.pixelHeight - height, width - margin, height - margin), "Graph Display", astarSkin.FindStyle("SceneBoxDark"));
  510. EditorGUILayout.BeginHorizontal();
  511. EditorGUILayout.PrefixLabel("Show Graphs", darkSkin.toggle, astarSkin.FindStyle("ScenePrefixLabel"));
  512. script.showNavGraphs = EditorGUILayout.Toggle(script.showNavGraphs, darkSkin.toggle);
  513. EditorGUILayout.EndHorizontal();
  514. if (GUILayout.Button("Scan", darkSkin.button)) {
  515. MenuScan();
  516. }
  517. // Invisible button to capture clicks. This prevents a click inside the box from causing some other GameObject to be selected.
  518. GUI.Button(new Rect(0, 0, width - margin, height - margin), "", GUIStyle.none);
  519. GUILayout.EndArea();
  520. EditorGUIUtility.labelWidth = origWidth;
  521. Handles.EndGUI();
  522. }
  523. TextAsset SaveGraphData (byte[] bytes, TextAsset target = null) {
  524. string projectPath = System.IO.Path.GetDirectoryName(Application.dataPath) + "/";
  525. string path;
  526. if (target != null) {
  527. path = AssetDatabase.GetAssetPath(target);
  528. } else {
  529. // Find a valid file name
  530. int i = 0;
  531. do {
  532. path = "Assets/GraphCaches/GraphCache" + (i == 0 ? "" : i.ToString()) + ".bytes";
  533. i++;
  534. } while (System.IO.File.Exists(projectPath+path));
  535. }
  536. string fullPath = projectPath + path;
  537. System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(fullPath));
  538. var fileInfo = new System.IO.FileInfo(fullPath);
  539. // Make sure we can write to the file
  540. if (fileInfo.Exists && fileInfo.IsReadOnly)
  541. fileInfo.IsReadOnly = false;
  542. System.IO.File.WriteAllBytes(fullPath, bytes);
  543. AssetDatabase.Refresh();
  544. return AssetDatabase.LoadAssetAtPath<TextAsset>(path);
  545. }
  546. void DrawSerializationSettings () {
  547. serializationSettingsArea.Begin();
  548. GUILayout.BeginHorizontal();
  549. if (GUILayout.Button("Save & Load", level0LabelStyle)) {
  550. serializationSettingsArea.open = !serializationSettingsArea.open;
  551. }
  552. if (script.data.cacheStartup && script.data.file_cachedStartup != null) {
  553. GUIUtilityx.PushTint(Color.yellow);
  554. GUILayout.Label("Startup cached", thinHelpBox, GUILayout.Height(15));
  555. GUILayout.Space(20);
  556. GUIUtilityx.PopTint();
  557. }
  558. GUILayout.EndHorizontal();
  559. // This displays the serialization settings
  560. if (serializationSettingsArea.BeginFade()) {
  561. script.data.cacheStartup = EditorGUILayout.Toggle(new GUIContent("Cache startup", "If enabled, will cache the graphs so they don't have to be scanned at startup"), script.data.cacheStartup);
  562. script.data.file_cachedStartup = EditorGUILayout.ObjectField(script.data.file_cachedStartup, typeof(TextAsset), false) as TextAsset;
  563. if (script.data.cacheStartup && script.data.file_cachedStartup == null) {
  564. EditorGUILayout.HelpBox("No cache has been generated", MessageType.Error);
  565. }
  566. if (script.data.cacheStartup && script.data.file_cachedStartup != null) {
  567. EditorGUILayout.HelpBox("All graph settings will be replaced with the ones from the cache when the game starts", MessageType.Info);
  568. }
  569. GUILayout.BeginHorizontal();
  570. if (GUILayout.Button("Generate cache")) {
  571. var serializationSettings = new Pathfinding.Serialization.SerializeSettings();
  572. serializationSettings.nodes = true;
  573. if (EditorUtility.DisplayDialog("Scan before generating cache?", "Do you want to scan the graphs before saving the cache.\n" +
  574. "If the graphs have not been scanned then the cache may not contain node data and then the graphs will have to be scanned at startup anyway.", "Scan", "Don't scan")) {
  575. MenuScan();
  576. }
  577. // Save graphs
  578. var bytes = script.data.SerializeGraphs(serializationSettings);
  579. // Store it in a file
  580. script.data.file_cachedStartup = SaveGraphData(bytes, script.data.file_cachedStartup);
  581. script.data.cacheStartup = true;
  582. }
  583. if (GUILayout.Button("Load from cache")) {
  584. if (EditorUtility.DisplayDialog("Are you sure you want to load from cache?", "Are you sure you want to load graphs from the cache, this will replace your current graphs?", "Yes", "Cancel")) {
  585. script.data.LoadFromCache();
  586. }
  587. }
  588. GUILayout.EndHorizontal();
  589. if (script.data.data_cachedStartup != null && script.data.data_cachedStartup.Length > 0) {
  590. EditorGUILayout.HelpBox("Storing the cached starup data on the AstarPath object has been deprecated. It is now stored " +
  591. "in a separate file.", MessageType.Error);
  592. if (GUILayout.Button("Transfer cache data to separate file")) {
  593. script.data.file_cachedStartup = SaveGraphData(script.data.data_cachedStartup);
  594. script.data.data_cachedStartup = null;
  595. }
  596. }
  597. GUILayout.Space(5);
  598. GUILayout.BeginHorizontal();
  599. if (GUILayout.Button("Save to file")) {
  600. string path = EditorUtility.SaveFilePanel("Save Graphs", "", "graph.bytes", "bytes");
  601. if (path != "") {
  602. var serializationSettings = Pathfinding.Serialization.SerializeSettings.Settings;
  603. if (EditorUtility.DisplayDialog("Include node data?", "Do you want to include node data in the save file. " +
  604. "If node data is included the graph can be restored completely without having to scan it first.", "Include node data", "Only settings")) {
  605. serializationSettings.nodes = true;
  606. }
  607. if (serializationSettings.nodes && EditorUtility.DisplayDialog("Scan before saving?", "Do you want to scan the graphs before saving? " +
  608. "\nNot scanning can cause node data to be omitted from the file if the graph is not yet scanned.", "Scan", "Don't scan")) {
  609. MenuScan();
  610. }
  611. uint checksum;
  612. var bytes = SerializeGraphs(serializationSettings, out checksum);
  613. Pathfinding.Serialization.AstarSerializer.SaveToFile(path, bytes);
  614. EditorUtility.DisplayDialog("Done Saving", "Done saving graph data.", "Ok");
  615. }
  616. }
  617. if (GUILayout.Button("Load from file")) {
  618. string path = EditorUtility.OpenFilePanel("Load Graphs", "", "");
  619. if (path != "") {
  620. try {
  621. byte[] bytes = Pathfinding.Serialization.AstarSerializer.LoadFromFile(path);
  622. DeserializeGraphs(bytes);
  623. } catch (System.Exception e) {
  624. Debug.LogError("Could not load from file at '"+path+"'\n"+e);
  625. }
  626. }
  627. }
  628. GUILayout.EndHorizontal();
  629. }
  630. serializationSettingsArea.End();
  631. }
  632. void DrawSettings () {
  633. settingsArea.Begin();
  634. settingsArea.Header("Settings", ref showSettings);
  635. if (settingsArea.BeginFade()) {
  636. DrawPathfindingSettings();
  637. DrawDebugSettings();
  638. DrawColorSettings();
  639. DrawTagSettings();
  640. DrawEditorSettings();
  641. }
  642. settingsArea.End();
  643. }
  644. void DrawPathfindingSettings () {
  645. alwaysVisibleArea.Begin();
  646. alwaysVisibleArea.HeaderLabel("Pathfinding");
  647. alwaysVisibleArea.BeginFade();
  648. #if !ASTAR_ATAVISM
  649. EditorGUI.BeginDisabledGroup(Application.isPlaying);
  650. script.threadCount = (ThreadCount)EditorGUILayout.EnumPopup(new GUIContent("Thread Count", "Number of threads to run the pathfinding in (if any). More threads " +
  651. "can boost performance on multi core systems. \n" +
  652. "Use None for debugging or if you dont use pathfinding that much.\n " +
  653. "See docs for more info"), script.threadCount);
  654. EditorGUI.EndDisabledGroup();
  655. int threads = AstarPath.CalculateThreadCount(script.threadCount);
  656. if (threads > 0) EditorGUILayout.HelpBox("Using " + threads +" thread(s)" + (script.threadCount < 0 ? " on your machine" : ""), MessageType.None);
  657. else EditorGUILayout.HelpBox("Using a single coroutine (no threads)" + (script.threadCount < 0 ? " on your machine" : ""), MessageType.None);
  658. if (threads > SystemInfo.processorCount) EditorGUILayout.HelpBox("Using more threads than there are CPU cores may not have a positive effect on performance", MessageType.Warning);
  659. if (script.threadCount == ThreadCount.None) {
  660. script.maxFrameTime = EditorGUILayout.FloatField(new GUIContent("Max Frame Time", "Max number of milliseconds to use for path calculation per frame"), script.maxFrameTime);
  661. } else {
  662. script.maxFrameTime = 10;
  663. }
  664. script.maxNearestNodeDistance = EditorGUILayout.FloatField(new GUIContent("Max Nearest Node Distance",
  665. "Normally, if the nearest node to e.g the start point of a path was not walkable" +
  666. " a search will be done for the nearest node which is walkble. This is the maximum distance (world units) which it will search"),
  667. script.maxNearestNodeDistance);
  668. script.heuristic = (Heuristic)EditorGUILayout.EnumPopup("Heuristic", script.heuristic);
  669. if (script.heuristic == Heuristic.Manhattan || script.heuristic == Heuristic.Euclidean || script.heuristic == Heuristic.DiagonalManhattan) {
  670. EditorGUI.indentLevel++;
  671. script.heuristicScale = EditorGUILayout.FloatField("Heuristic Scale", script.heuristicScale);
  672. EditorGUI.indentLevel--;
  673. }
  674. GUILayout.Label(new GUIContent("Advanced"), EditorStyles.boldLabel);
  675. DrawHeuristicOptimizationSettings();
  676. script.batchGraphUpdates = EditorGUILayout.Toggle(new GUIContent("Batch Graph Updates", "Limit graph updates to only run every x seconds. Can have positive impact on performance if many graph updates are done"), script.batchGraphUpdates);
  677. if (script.batchGraphUpdates) {
  678. EditorGUI.indentLevel++;
  679. script.graphUpdateBatchingInterval = EditorGUILayout.FloatField(new GUIContent("Update Interval (s)", "Minimum number of seconds between each batch of graph updates"), script.graphUpdateBatchingInterval);
  680. EditorGUI.indentLevel--;
  681. }
  682. // Only show if there is actually a navmesh/recast graph in the scene
  683. // to help reduce clutter for other users.
  684. if (script.data.FindGraphWhichInheritsFrom(typeof(NavmeshBase)) != null) {
  685. script.navmeshUpdates.updateInterval = EditorGUILayout.FloatField(new GUIContent("Navmesh Cutting Update Interval (s)", "How often to check if any navmesh cut has changed."), script.navmeshUpdates.updateInterval);
  686. }
  687. #pragma warning disable 0618
  688. script.prioritizeGraphs = EditorGUILayout.Toggle(new GUIContent("Prioritize Graphs", "Normally, the system will search for the closest node in all graphs and choose the closest one" +
  689. "but if Prioritize Graphs is enabled, the first graph which has a node closer than Priority Limit will be chosen and additional search (e.g for the closest WALKABLE node) will be carried out on that graph only"),
  690. script.prioritizeGraphs);
  691. if (script.prioritizeGraphs) {
  692. EditorGUI.indentLevel++;
  693. script.prioritizeGraphsLimit = EditorGUILayout.FloatField("Priority Limit", script.prioritizeGraphsLimit);
  694. EditorGUI.indentLevel--;
  695. }
  696. #pragma warning restore 0618
  697. script.fullGetNearestSearch = EditorGUILayout.Toggle(new GUIContent("Full Get Nearest Node Search", "Forces more accurate searches on all graphs. " +
  698. "Normally only the closest graph in the initial fast check will perform additional searches, " +
  699. "if this is toggled, all graphs will do additional searches. Slower, but more accurate"), script.fullGetNearestSearch);
  700. #endif
  701. script.scanOnStartup = EditorGUILayout.Toggle(new GUIContent("Scan on Awake", "Scan all graphs on Awake. If this is false, you must call AstarPath.active.Scan () yourself. Useful if you want to make changes to the graphs with code."), script.scanOnStartup);
  702. alwaysVisibleArea.End();
  703. }
  704. void DrawHeuristicOptimizationSettings () {
  705. script.euclideanEmbedding.mode = (HeuristicOptimizationMode)EditorGUILayout.EnumPopup(new GUIContent("Heuristic Optimization"), script.euclideanEmbedding.mode);
  706. EditorGUI.indentLevel++;
  707. if (script.euclideanEmbedding.mode == HeuristicOptimizationMode.Random) {
  708. script.euclideanEmbedding.spreadOutCount = EditorGUILayout.IntField(new GUIContent("Count", "Number of optimization points, higher numbers give better heuristics and could make it faster, " +
  709. "but too many could make the overhead too great and slow it down. Try to find the optimal value for your map. Recommended value < 100"), script.euclideanEmbedding.spreadOutCount);
  710. } else if (script.euclideanEmbedding.mode == HeuristicOptimizationMode.Custom) {
  711. script.euclideanEmbedding.pivotPointRoot = EditorGUILayout.ObjectField(new GUIContent("Pivot point root",
  712. "All children of this transform are going to be used as pivot points. " +
  713. "Recommended count < 100"), script.euclideanEmbedding.pivotPointRoot, typeof(Transform), true) as Transform;
  714. if (script.euclideanEmbedding.pivotPointRoot == null) {
  715. EditorGUILayout.HelpBox("Please assign an object", MessageType.Error);
  716. }
  717. } else if (script.euclideanEmbedding.mode == HeuristicOptimizationMode.RandomSpreadOut) {
  718. script.euclideanEmbedding.pivotPointRoot = EditorGUILayout.ObjectField(new GUIContent("Pivot point root",
  719. "All children of this transform are going to be used as pivot points. " +
  720. "They will seed the calculation of more pivot points. " +
  721. "Recommended count < 100"), script.euclideanEmbedding.pivotPointRoot, typeof(Transform), true) as Transform;
  722. if (script.euclideanEmbedding.pivotPointRoot == null) {
  723. EditorGUILayout.HelpBox("No root is assigned. A random node will be choosen as the seed.", MessageType.Info);
  724. }
  725. script.euclideanEmbedding.spreadOutCount = EditorGUILayout.IntField(new GUIContent("Count", "Number of optimization points, higher numbers give better heuristics and could make it faster, " +
  726. "but too many could make the overhead too great and slow it down. Try to find the optimal value for your map. Recommended value < 100"), script.euclideanEmbedding.spreadOutCount);
  727. }
  728. if (script.euclideanEmbedding.mode != HeuristicOptimizationMode.None) {
  729. EditorGUILayout.HelpBox("Heuristic optimization assumes the graph remains static. No graph updates, dynamic obstacles or similar should be applied to the graph " +
  730. "when using heuristic optimization.", MessageType.Info);
  731. }
  732. EditorGUI.indentLevel--;
  733. }
  734. /// <summary>Opens the A* Inspector and shows the section for editing tags</summary>
  735. public static void EditTags () {
  736. AstarPath astar = GameObject.FindObjectOfType<AstarPath>();
  737. if (astar != null) {
  738. editTags = true;
  739. showSettings = true;
  740. Selection.activeGameObject = astar.gameObject;
  741. } else {
  742. Debug.LogWarning("No AstarPath component in the scene");
  743. }
  744. }
  745. void DrawTagSettings () {
  746. tagsArea.Begin();
  747. tagsArea.Header("Tag Names", ref editTags);
  748. if (tagsArea.BeginFade()) {
  749. string[] tagNames = script.GetTagNames();
  750. for (int i = 0; i < tagNames.Length; i++) {
  751. tagNames[i] = EditorGUILayout.TextField(new GUIContent("Tag "+i, "Name for tag "+i), tagNames[i]);
  752. if (tagNames[i] == "") tagNames[i] = ""+i;
  753. }
  754. }
  755. tagsArea.End();
  756. }
  757. void DrawEditorSettings () {
  758. editorSettingsArea.Begin();
  759. editorSettingsArea.Header("Editor");
  760. if (editorSettingsArea.BeginFade()) {
  761. FadeArea.fancyEffects = EditorGUILayout.Toggle("Smooth Transitions", FadeArea.fancyEffects);
  762. }
  763. editorSettingsArea.End();
  764. }
  765. static void DrawColorSlider (ref float left, ref float right, bool editable) {
  766. GUILayout.BeginHorizontal();
  767. GUILayout.Space(20);
  768. GUILayout.BeginVertical();
  769. GUILayout.Box("", astarSkin.GetStyle("ColorInterpolationBox"));
  770. GUILayout.BeginHorizontal();
  771. if (editable) {
  772. left = EditorGUILayout.IntField((int)left);
  773. } else {
  774. GUILayout.Label(left.ToString("0"));
  775. }
  776. GUILayout.FlexibleSpace();
  777. if (editable) {
  778. right = EditorGUILayout.IntField((int)right);
  779. } else {
  780. GUILayout.Label(right.ToString("0"));
  781. }
  782. GUILayout.EndHorizontal();
  783. GUILayout.EndVertical();
  784. GUILayout.Space(4);
  785. GUILayout.EndHorizontal();
  786. }
  787. void DrawDebugSettings () {
  788. alwaysVisibleArea.Begin();
  789. alwaysVisibleArea.HeaderLabel("Debug");
  790. alwaysVisibleArea.BeginFade();
  791. script.logPathResults = (PathLog)EditorGUILayout.EnumPopup("Path Logging", script.logPathResults);
  792. script.debugMode = (GraphDebugMode)EditorGUILayout.EnumPopup("Graph Coloring", script.debugMode);
  793. if (script.debugMode == GraphDebugMode.SolidColor) {
  794. EditorGUI.BeginChangeCheck();
  795. script.colorSettings._SolidColor = EditorGUILayout.ColorField(new GUIContent("Color", "Color used for the graph when 'Graph Coloring'='Solid Color'"), script.colorSettings._SolidColor);
  796. if (EditorGUI.EndChangeCheck()) {
  797. script.colorSettings.PushToStatic(script);
  798. }
  799. }
  800. if (script.debugMode == GraphDebugMode.G || script.debugMode == GraphDebugMode.H || script.debugMode == GraphDebugMode.F || script.debugMode == GraphDebugMode.Penalty) {
  801. script.manualDebugFloorRoof = !EditorGUILayout.Toggle("Automatic Limits", !script.manualDebugFloorRoof);
  802. DrawColorSlider(ref script.debugFloor, ref script.debugRoof, script.manualDebugFloorRoof);
  803. }
  804. script.showSearchTree = EditorGUILayout.Toggle("Show Search Tree", script.showSearchTree);
  805. if (script.showSearchTree) {
  806. EditorGUILayout.HelpBox("Show Search Tree is enabled, you may see rendering glitches in the graph rendering" +
  807. " while the game is running. This is nothing to worry about and is simply due to the paths being calculated at the same time as the gizmos" +
  808. " are being rendered. You can pause the game to see an accurate rendering.", MessageType.Info);
  809. }
  810. script.showUnwalkableNodes = EditorGUILayout.Toggle("Show Unwalkable Nodes", script.showUnwalkableNodes);
  811. if (script.showUnwalkableNodes) {
  812. EditorGUI.indentLevel++;
  813. script.unwalkableNodeDebugSize = EditorGUILayout.FloatField("Size", script.unwalkableNodeDebugSize);
  814. EditorGUI.indentLevel--;
  815. }
  816. alwaysVisibleArea.End();
  817. }
  818. void DrawColorSettings () {
  819. colorSettingsArea.Begin();
  820. colorSettingsArea.Header("Colors");
  821. if (colorSettingsArea.BeginFade()) {
  822. // Make sure the object is not null
  823. AstarColor colors = script.colorSettings = script.colorSettings ?? new AstarColor();
  824. colors._SolidColor = EditorGUILayout.ColorField(new GUIContent("Solid Color", "Color used for the graph when 'Graph Coloring'='Solid Color'"), colors._SolidColor);
  825. colors._UnwalkableNode = EditorGUILayout.ColorField("Unwalkable Node", colors._UnwalkableNode);
  826. colors._BoundsHandles = EditorGUILayout.ColorField("Bounds Handles", colors._BoundsHandles);
  827. colors._ConnectionLowLerp = EditorGUILayout.ColorField("Connection Gradient (low)", colors._ConnectionLowLerp);
  828. colors._ConnectionHighLerp = EditorGUILayout.ColorField("Connection Gradient (high)", colors._ConnectionHighLerp);
  829. colors._MeshEdgeColor = EditorGUILayout.ColorField("Mesh Edge", colors._MeshEdgeColor);
  830. if (EditorResourceHelper.GizmoSurfaceMaterial != null && EditorResourceHelper.GizmoLineMaterial != null) {
  831. EditorGUI.BeginChangeCheck();
  832. var col1 = EditorResourceHelper.GizmoSurfaceMaterial.color;
  833. col1.a = EditorGUILayout.Slider("Navmesh Surface Opacity", col1.a, 0, 1);
  834. var col2 = EditorResourceHelper.GizmoLineMaterial.color;
  835. col2.a = EditorGUILayout.Slider("Navmesh Outline Opacity", col2.a, 0, 1);
  836. var fade = EditorResourceHelper.GizmoSurfaceMaterial.GetColor("_FadeColor");
  837. fade.a = EditorGUILayout.Slider("Opacity Behind Objects", fade.a, 0, 1);
  838. if (EditorGUI.EndChangeCheck()) {
  839. Undo.RecordObjects(new [] { EditorResourceHelper.GizmoSurfaceMaterial, EditorResourceHelper.GizmoLineMaterial }, "Change navmesh transparency");
  840. EditorResourceHelper.GizmoSurfaceMaterial.color = col1;
  841. EditorResourceHelper.GizmoLineMaterial.color = col2;
  842. EditorResourceHelper.GizmoSurfaceMaterial.SetColor("_FadeColor", fade);
  843. EditorResourceHelper.GizmoLineMaterial.SetColor("_FadeColor", fade * new Color(1, 1, 1, 0.7f));
  844. }
  845. }
  846. colors._AreaColors = colors._AreaColors ?? new Color[0];
  847. // Custom Area Colors
  848. customAreaColorsOpen = EditorGUILayout.Foldout(customAreaColorsOpen, "Custom Area Colors");
  849. if (customAreaColorsOpen) {
  850. EditorGUI.indentLevel += 2;
  851. for (int i = 0; i < colors._AreaColors.Length; i++) {
  852. GUILayout.BeginHorizontal();
  853. colors._AreaColors[i] = EditorGUILayout.ColorField("Area "+i+(i == 0 ? " (not used usually)" : ""), colors._AreaColors[i]);
  854. if (GUILayout.Button(new GUIContent("", "Reset to the default color"), astarSkin.FindStyle("SmallReset"), GUILayout.Width(20))) {
  855. colors._AreaColors[i] = AstarMath.IntToColor(i, 1F);
  856. }
  857. GUILayout.EndHorizontal();
  858. }
  859. GUILayout.BeginHorizontal();
  860. EditorGUI.BeginDisabledGroup(colors._AreaColors.Length > 255);
  861. if (GUILayout.Button("Add New")) {
  862. var newcols = new Color[colors._AreaColors.Length+1];
  863. colors._AreaColors.CopyTo(newcols, 0);
  864. newcols[newcols.Length-1] = AstarMath.IntToColor(newcols.Length-1, 1F);
  865. colors._AreaColors = newcols;
  866. }
  867. EditorGUI.EndDisabledGroup();
  868. EditorGUI.BeginDisabledGroup(colors._AreaColors.Length == 0);
  869. if (GUILayout.Button("Remove last") && colors._AreaColors.Length > 0) {
  870. var newcols = new Color[colors._AreaColors.Length-1];
  871. for (int i = 0; i < colors._AreaColors.Length-1; i++) {
  872. newcols[i] = colors._AreaColors[i];
  873. }
  874. colors._AreaColors = newcols;
  875. }
  876. EditorGUI.EndDisabledGroup();
  877. GUILayout.EndHorizontal();
  878. EditorGUI.indentLevel -= 2;
  879. }
  880. if (GUI.changed) {
  881. colors.PushToStatic(script);
  882. }
  883. }
  884. colorSettingsArea.End();
  885. }
  886. /// <summary>Make sure every graph has a graph editor</summary>
  887. void CheckGraphEditors (bool forceRebuild = false) {
  888. if (forceRebuild || graphEditors == null || script.graphs == null || script.graphs.Length != graphEditors.Length) {
  889. if (script.data.graphs == null) {
  890. script.data.graphs = new NavGraph[0];
  891. }
  892. graphEditors = new GraphEditor[script.graphs.Length];
  893. for (int i = 0; i < script.graphs.Length; i++) {
  894. NavGraph graph = script.graphs[i];
  895. if (graph == null) continue;
  896. if (graph.guid == new Pathfinding.Util.Guid()) {
  897. graph.guid = Pathfinding.Util.Guid.NewGuid();
  898. }
  899. graphEditors[i] = CreateGraphEditor(graph);
  900. }
  901. } else {
  902. for (int i = 0; i < script.graphs.Length; i++) {
  903. if (script.graphs[i] == null) continue;
  904. if (graphEditors[i] == null || graphEditorTypes[script.graphs[i].GetType().Name].editorType != graphEditors[i].GetType()) {
  905. CheckGraphEditors(true);
  906. return;
  907. }
  908. if (script.graphs[i].guid == new Pathfinding.Util.Guid()) {
  909. script.graphs[i].guid = Pathfinding.Util.Guid.NewGuid();
  910. }
  911. graphEditors[i].target = script.graphs[i];
  912. }
  913. }
  914. }
  915. void RemoveGraph (NavGraph graph) {
  916. script.data.RemoveGraph(graph);
  917. CheckGraphEditors(true);
  918. GUI.changed = true;
  919. Repaint();
  920. }
  921. void AddGraph (System.Type type) {
  922. script.data.AddGraph(type);
  923. CheckGraphEditors();
  924. GUI.changed = true;
  925. }
  926. /// <summary>Creates a GraphEditor for a graph</summary>
  927. GraphEditor CreateGraphEditor (NavGraph graph) {
  928. var graphType = graph.GetType().Name;
  929. GraphEditor result;
  930. if (graphEditorTypes.ContainsKey(graphType)) {
  931. result = System.Activator.CreateInstance(graphEditorTypes[graphType].editorType) as GraphEditor;
  932. } else {
  933. Debug.LogError("Couldn't find an editor for the graph type '" + graphType + "' There are " + graphEditorTypes.Count + " available graph editors");
  934. result = new GraphEditor();
  935. }
  936. result.editor = this;
  937. result.fadeArea = new FadeArea(graph.open, this, level1AreaStyle, level1LabelStyle);
  938. result.infoFadeArea = new FadeArea(graph.infoScreenOpen, this, null, null);
  939. result.target = graph;
  940. result.OnEnable();
  941. return result;
  942. }
  943. bool HandleUndo () {
  944. // The user has tried to undo something, apply that
  945. if (script.data.GetData() == null) {
  946. script.data.SetData(new byte[0]);
  947. } else {
  948. LoadGraphs();
  949. return true;
  950. }
  951. return false;
  952. }
  953. /// <summary>Hashes the contents of a byte array</summary>
  954. static int ByteArrayHash (byte[] arr) {
  955. if (arr == null) return -1;
  956. int hash = -1;
  957. for (int i = 0; i < arr.Length; i++) {
  958. hash ^= (arr[i]^i)*3221;
  959. }
  960. return hash;
  961. }
  962. void SerializeIfDataChanged () {
  963. uint checksum;
  964. byte[] bytes = SerializeGraphs(out checksum);
  965. int byteHash = ByteArrayHash(bytes);
  966. int dataHash = ByteArrayHash(script.data.GetData());
  967. //Check if the data is different than the previous data, use checksums
  968. bool isDifferent = checksum != ignoredChecksum && dataHash != byteHash;
  969. //Only save undo if the data was different from the last saved undo
  970. if (isDifferent) {
  971. //Assign the new data
  972. script.data.SetData(bytes);
  973. EditorUtility.SetDirty(script);
  974. Undo.IncrementCurrentGroup();
  975. Undo.RegisterCompleteObjectUndo(script, "A* Graph Settings");
  976. }
  977. }
  978. /// <summary>Called when an undo or redo operation has been performed</summary>
  979. void OnUndoRedoPerformed () {
  980. if (!this) return;
  981. uint checksum;
  982. byte[] bytes = SerializeGraphs(out checksum);
  983. //Check if the data is different than the previous data, use checksums
  984. bool isDifferent = ByteArrayHash(script.data.GetData()) != ByteArrayHash(bytes);
  985. if (isDifferent) {
  986. HandleUndo();
  987. }
  988. CheckGraphEditors();
  989. // Deserializing a graph does not necessarily yield the same hash as the data loaded from
  990. // this is (probably) because editor settings are not saved all the time
  991. // so we explicitly ignore the new hash
  992. SerializeGraphs(out checksum);
  993. ignoredChecksum = checksum;
  994. }
  995. public void SaveGraphsAndUndo (EventType et = EventType.Used, string eventCommand = "") {
  996. // Serialize the settings of the graphs
  997. // Dont process undo events in editor, we don't want to reset graphs
  998. // Also don't do this if the graph is being updated as serializing the graph
  999. // might interfere with that (in particular it might unblock the path queue)
  1000. if (Application.isPlaying || script.isScanning || script.IsAnyWorkItemInProgress) {
  1001. return;
  1002. }
  1003. if ((Undo.GetCurrentGroup() != lastUndoGroup || et == EventType.MouseUp) && eventCommand != "UndoRedoPerformed") {
  1004. SerializeIfDataChanged();
  1005. lastUndoGroup = Undo.GetCurrentGroup();
  1006. }
  1007. if (Event.current == null || script.data.GetData() == null) {
  1008. SerializeIfDataChanged();
  1009. return;
  1010. }
  1011. }
  1012. /// <summary>Load graphs from serialized data</summary>
  1013. public void LoadGraphs () {
  1014. DeserializeGraphs();
  1015. }
  1016. public byte[] SerializeGraphs (out uint checksum) {
  1017. var settings = Pathfinding.Serialization.SerializeSettings.Settings;
  1018. settings.editorSettings = true;
  1019. return SerializeGraphs(settings, out checksum);
  1020. }
  1021. public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings, out uint checksum) {
  1022. byte[] bytes = null;
  1023. uint tmpChecksum = 0;
  1024. // Serialize all graph editors
  1025. var output = new System.Text.StringBuilder();
  1026. for (int i = 0; i < graphEditors.Length; i++) {
  1027. if (graphEditors[i] == null) continue;
  1028. output.Length = 0;
  1029. Pathfinding.Serialization.TinyJsonSerializer.Serialize(graphEditors[i], output);
  1030. (graphEditors[i].target as IGraphInternals).SerializedEditorSettings = output.ToString();
  1031. }
  1032. // Serialize all graphs (including serialized editor data)
  1033. bytes = script.data.SerializeGraphs(settings, out tmpChecksum);
  1034. // Make sure the above work item is executed immediately
  1035. AstarPath.active.FlushWorkItems();
  1036. checksum = tmpChecksum;
  1037. return bytes;
  1038. }
  1039. void DeserializeGraphs () {
  1040. if (script.data.GetData() == null || script.data.GetData().Length == 0) {
  1041. script.data.graphs = new NavGraph[0];
  1042. } else {
  1043. DeserializeGraphs(script.data.GetData());
  1044. }
  1045. }
  1046. void DeserializeGraphs (byte[] bytes) {
  1047. try {
  1048. script.data.DeserializeGraphs(bytes);
  1049. // Make sure every graph has a graph editor
  1050. CheckGraphEditors();
  1051. // Deserialize editor settings
  1052. for (int i = 0; i < graphEditors.Length; i++) {
  1053. var data = (graphEditors[i].target as IGraphInternals).SerializedEditorSettings;
  1054. if (data != null) Pathfinding.Serialization.TinyJsonDeserializer.Deserialize(data, graphEditors[i].GetType(), graphEditors[i], script.gameObject);
  1055. }
  1056. } catch (System.Exception e) {
  1057. Debug.LogError("Failed to deserialize graphs");
  1058. Debug.LogException(e);
  1059. script.data.SetData(null);
  1060. }
  1061. }
  1062. [MenuItem("Edit/Pathfinding/Scan All Graphs %&s")]
  1063. public static void MenuScan () {
  1064. if (AstarPath.active == null) {
  1065. AstarPath.active = FindObjectOfType<AstarPath>();
  1066. if (AstarPath.active == null) {
  1067. return;
  1068. }
  1069. }
  1070. if (!Application.isPlaying && (AstarPath.active.data.graphs == null || AstarPath.active.data.graphTypes == null)) {
  1071. EditorUtility.DisplayProgressBar("Scanning", "Deserializing", 0);
  1072. AstarPath.active.data.DeserializeGraphs();
  1073. }
  1074. try {
  1075. var lastMessageTime = Time.realtimeSinceStartup;
  1076. foreach (var p in AstarPath.active.ScanAsync()) {
  1077. // Displaying the progress bar is pretty slow, so don't do it too often
  1078. if (Time.realtimeSinceStartup - lastMessageTime > 0.2f) {
  1079. // Display a progress bar of the scan
  1080. UnityEditor.EditorUtility.DisplayProgressBar("Scanning", p.description, p.progress);
  1081. lastMessageTime = Time.realtimeSinceStartup;
  1082. }
  1083. }
  1084. // Repaint the game view in addition to just the scene view.
  1085. // In case the user only has the game view open it's nice to refresh it so they can see the graph.
  1086. UnityEditorInternal.InternalEditorUtility.RepaintAllViews();
  1087. } catch (System.Exception e) {
  1088. Debug.LogError("There was an error generating the graphs:\n"+e+"\n\nIf you think this is a bug, please contact me on forum.arongranberg.com (post a new thread)\n");
  1089. EditorUtility.DisplayDialog("Error Generating Graphs", "There was an error when generating graphs, check the console for more info", "Ok");
  1090. throw e;
  1091. } finally {
  1092. EditorUtility.ClearProgressBar();
  1093. }
  1094. }
  1095. /// <summary>Searches in the current assembly for GraphEditor and NavGraph types</summary>
  1096. void FindGraphTypes () {
  1097. graphEditorTypes = new Dictionary<string, CustomGraphEditorAttribute>();
  1098. var graphList = new List<System.Type>();
  1099. foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) {
  1100. System.Type[] types = null;
  1101. try {
  1102. types = assembly.GetTypes();
  1103. } catch {
  1104. // Ignore type load exceptions and things like that.
  1105. // We might not be able to read all assemblies for some reason, but hopefully the relevant types exist in the assemblies that we can read
  1106. continue;
  1107. }
  1108. // Iterate through the assembly for classes which inherit from GraphEditor
  1109. foreach (var type in types) {
  1110. System.Type baseType = type.BaseType;
  1111. while (!System.Type.Equals(baseType, null)) {
  1112. if (System.Type.Equals(baseType, typeof(GraphEditor))) {
  1113. System.Object[] att = type.GetCustomAttributes(false);
  1114. // Loop through the attributes for the CustomGraphEditorAttribute attribute
  1115. foreach (System.Object attribute in att) {
  1116. var cge = attribute as CustomGraphEditorAttribute;
  1117. if (cge != null && !System.Type.Equals(cge.graphType, null)) {
  1118. cge.editorType = type;
  1119. graphList.Add(cge.graphType);
  1120. graphEditorTypes.Add(cge.graphType.Name, cge);
  1121. }
  1122. }
  1123. break;
  1124. }
  1125. baseType = baseType.BaseType;
  1126. }
  1127. }
  1128. }
  1129. // Make sure graph types (not graph editor types) are also up to date
  1130. script.data.FindGraphTypes();
  1131. }
  1132. }
  1133. }