EditorApplication.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Runtime.CompilerServices;
  6. using System.IO;
  7. using bs;
  8. namespace bs.Editor
  9. {
  10. /** @addtogroup Editor-General
  11. * @{
  12. */
  13. /// <summary>
  14. /// Available tools in the scene view.
  15. /// </summary>
  16. public enum SceneViewTool
  17. {
  18. View,
  19. Move,
  20. Rotate,
  21. Scale
  22. }
  23. /// <summary>
  24. /// Pivot mode used by the scene view tools.
  25. /// </summary>
  26. public enum HandlePivotMode
  27. {
  28. Center,
  29. Pivot
  30. }
  31. /// <summary>
  32. /// Coordinate mode used by the scene view tools.
  33. /// </summary>
  34. public enum HandleCoordinateMode
  35. {
  36. Local,
  37. World
  38. }
  39. /// <summary>
  40. /// Manages various generic and global settings relating to the editor.
  41. /// </summary>
  42. public class EditorApplication
  43. {
  44. internal const string CutBinding = "Cut";
  45. internal const string CopyBinding = "Copy";
  46. internal const string RenameBinding = "Rename";
  47. internal const string DuplicateBinding = "Duplicate";
  48. internal const string DeleteBinding = "Delete";
  49. internal const string PasteBinding = "Paste";
  50. internal const string EditorSceneDataPrefix = "__EditorSceneData";
  51. /// <summary>
  52. /// Determines the active tool shown in the scene view.
  53. /// </summary>
  54. public static SceneViewTool ActiveSceneTool
  55. {
  56. get { return EditorSettings.ActiveSceneTool; }
  57. set { EditorSettings.ActiveSceneTool = value; }
  58. }
  59. /// <summary>
  60. /// Determines the coordinate mode used by the tools in the scene view.
  61. /// </summary>
  62. public static HandleCoordinateMode ActiveCoordinateMode
  63. {
  64. get { return EditorSettings.ActiveCoordinateMode; }
  65. set { EditorSettings.ActiveCoordinateMode = value; }
  66. }
  67. /// <summary>
  68. /// Determines the pivot mode used by the tools in the scene view.
  69. /// </summary>
  70. public static HandlePivotMode ActivePivotMode
  71. {
  72. get { return EditorSettings.ActivePivotMode; }
  73. set { EditorSettings.ActivePivotMode = value; }
  74. }
  75. /// <summary>
  76. /// Camera used for rendering the scene view.
  77. /// </summary>
  78. public static Camera SceneViewCamera
  79. {
  80. get
  81. {
  82. SceneWindow sceneWindow = EditorWindow.GetWindow<SceneWindow>();
  83. return sceneWindow?.Camera.Camera;
  84. }
  85. }
  86. /// <summary>
  87. /// Absolute path to the folder containing the currently open project.
  88. /// </summary>
  89. public static string ProjectPath { get { return Internal_GetProjectPath(); } }
  90. /// <summary>
  91. /// Name of the currently open project.
  92. /// </summary>
  93. public static string ProjectName { get { return Internal_GetProjectName(); } }
  94. /// <summary>
  95. /// Checks is any project currently loaded.
  96. /// </summary>
  97. public static bool IsProjectLoaded { get { return Internal_GetProjectLoaded(); } }
  98. /// <summary>
  99. /// Checks whether the editor currently has focus.
  100. /// </summary>
  101. public static bool HasFocus
  102. {
  103. get { return Internal_HasFocus(); }
  104. }
  105. /// <summary>
  106. /// Returns true if the editor is waiting on a scene to be asynchronously loaded.
  107. /// </summary>
  108. public static bool IsSceneLoading
  109. {
  110. get
  111. {
  112. if (lastLoadedScene != null)
  113. return !lastLoadedScene.IsLoaded;
  114. return false;
  115. }
  116. }
  117. /// <summary>
  118. /// Returns the load progress of the scene that's being asynchronously loaded
  119. /// </summary>
  120. public static float SceneLoadProgress
  121. {
  122. get
  123. {
  124. if (lastLoadedScene != null)
  125. return Resources.GetLoadProgress(lastLoadedScene);
  126. return 0.0f;
  127. }
  128. }
  129. /// <summary>
  130. /// Triggered right before the project is being saved.
  131. /// </summary>
  132. public static event Action OnProjectSave;
  133. /// <summary>
  134. /// Render target that the main camera in the scene (if any) will render its view to. This generally means the main
  135. /// game window when running standalone, or the Game viewport when running in editor.
  136. /// </summary>
  137. internal static RenderTarget MainRenderTarget
  138. {
  139. set
  140. {
  141. IntPtr rtPtr = IntPtr.Zero;
  142. if (value != null)
  143. rtPtr = value.GetCachedPtr();
  144. Internal_SetMainRenderTarget(rtPtr);
  145. }
  146. }
  147. /// <summary>
  148. /// Returns an object that can be used for storing data that persists throughout the entire editor session.
  149. /// </summary>
  150. internal static EditorPersistentData PersistentData => persistentData;
  151. /// <summary>
  152. /// Editor specific data for the currently loaded scene. Can be null if no scene is loaded.
  153. /// </summary>
  154. internal static EditorSceneData EditorSceneData
  155. {
  156. get => PersistentData.editorSceneData;
  157. private set => PersistentData.editorSceneData = value;
  158. }
  159. /// <summary>
  160. /// Returns the path where the script compiler is located at.
  161. /// </summary>
  162. internal static string CompilerPath { get { return Internal_GetCompilerPath(); } }
  163. /// <summary>
  164. /// Returns the absolute path to the executable capable of executing managed assemblies.
  165. /// </summary>
  166. internal static string MonoExecPath { get { return Internal_GetMonoExecPath(); } }
  167. /// <summary>
  168. /// Returns the path to the folder where the custom script assemblies are located at.
  169. /// </summary>
  170. internal static string ScriptAssemblyPath { get { return Internal_GetScriptAssemblyPath(); } }
  171. /// <summary>
  172. /// Returns the path to the folder where the .NET framework assemblies are located at.
  173. /// </summary>
  174. internal static string FrameworkAssemblyPath { get { return Internal_GetFrameworkAssemblyPath(); } }
  175. /// <summary>
  176. /// Name of the builtin assembly containing engine specific types.
  177. /// </summary>
  178. internal static string EngineAssemblyName { get { return Internal_GetEngineAssemblyName(); } }
  179. /// <summary>
  180. /// Name of the builtin assembly containing editor specific types.
  181. /// </summary>
  182. internal static string EditorAssemblyName { get { return Internal_GetEditorAssemblyName(); } }
  183. /// <summary>
  184. /// Name of the custom assembly compiled from non-editor scripts within the project.
  185. /// </summary>
  186. internal static string ScriptGameAssemblyName { get { return Internal_GetScriptGameAssemblyName(); } }
  187. /// <summary>
  188. /// Name of the custom assembly compiled from editor scripts within the project.
  189. /// </summary>
  190. internal static string ScriptEditorAssemblyName { get { return Internal_GetScriptEditorAssemblyName(); } }
  191. /// <summary>
  192. /// Returns the path to the folder where the builtin release script assemblies are located at.
  193. /// </summary>
  194. internal static string BuiltinReleaseAssemblyPath { get { return Internal_GetBuiltinReleaseAssemblyPath(); } }
  195. /// <summary>
  196. /// Returns the path to the folder where the builtin debug script assemblies are located at.
  197. /// </summary>
  198. internal static string BuiltinDebugAssemblyPath { get { return Internal_GetBuiltinDebugAssemblyPath(); } }
  199. internal static VirtualButton CutKey = new VirtualButton(CutBinding);
  200. internal static VirtualButton CopyKey = new VirtualButton(CopyBinding);
  201. internal static VirtualButton PasteKey = new VirtualButton(PasteBinding);
  202. internal static VirtualButton RenameKey = new VirtualButton(RenameBinding);
  203. internal static VirtualButton DuplicateKey = new VirtualButton(DuplicateBinding);
  204. internal static VirtualButton DeleteKey = new VirtualButton(DeleteBinding);
  205. private static FolderMonitor monitor;
  206. private static ScriptCodeManager codeManager;
  207. private static RRef<Prefab> lastLoadedScene;
  208. private static bool sceneDirty;
  209. private static bool unitTestsExecuted;
  210. private static EditorPersistentData persistentData;
  211. private static bool delayUnloadProject;
  212. private static Action delayUnloadCallback;
  213. #pragma warning disable 0414
  214. private static EditorApplication instance;
  215. #pragma warning restore 0414
  216. /// <summary>
  217. /// Constructs a new editor application. Called at editor start-up by the runtime, and any time assembly refresh
  218. /// occurs.
  219. /// </summary>
  220. internal EditorApplication()
  221. {
  222. instance = this;
  223. const string soName = "EditorPersistentData";
  224. SceneObject so = Scene.Root.FindChild(soName);
  225. if (so == null)
  226. so = new SceneObject(soName, true);
  227. persistentData = so.GetComponent<EditorPersistentData>();
  228. if (persistentData == null)
  229. persistentData = so.AddComponent<EditorPersistentData>();
  230. codeManager = new ScriptCodeManager();
  231. Scene.OnSceneLoad += OnSceneLoad;
  232. Scene.OnSceneUnload += OnSceneUnload;
  233. PlayInEditor.OnPlay += () =>
  234. {
  235. if (EditorSettings.GetBool(LogWindow.CLEAR_ON_PLAY_KEY, true))
  236. {
  237. Debug.Clear();
  238. LogWindow log = EditorWindow.GetWindow<LogWindow>();
  239. if (log != null)
  240. log.Refresh();
  241. }
  242. ToggleOnDemandDrawing(false);
  243. ToggleToolbarItem("Play", true);
  244. };
  245. PlayInEditor.OnStopped += () =>
  246. {
  247. ToggleOnDemandDrawing(true);
  248. ToggleToolbarItem("Play", false);
  249. };
  250. PlayInEditor.OnPaused += () =>
  251. {
  252. ToggleOnDemandDrawing(true);
  253. ToggleToolbarItem("Pause", true);
  254. };
  255. PlayInEditor.OnUnpaused += () =>
  256. {
  257. ToggleOnDemandDrawing(false);
  258. ToggleToolbarItem("Pause", false);
  259. };
  260. Selection.OnSelectionChanged += OnSelectionChanged;
  261. // Register controls
  262. InputConfiguration inputConfig = VirtualInput.KeyConfig;
  263. inputConfig.RegisterButton(SceneCamera.MoveForwardBinding, ButtonCode.W);
  264. inputConfig.RegisterButton(SceneCamera.MoveBackBinding, ButtonCode.S);
  265. inputConfig.RegisterButton(SceneCamera.MoveLeftBinding, ButtonCode.A);
  266. inputConfig.RegisterButton(SceneCamera.MoveRightBinding, ButtonCode.D);
  267. inputConfig.RegisterButton(SceneCamera.MoveUpBinding, ButtonCode.E);
  268. inputConfig.RegisterButton(SceneCamera.MoveDownBinding, ButtonCode.Q);
  269. inputConfig.RegisterButton(SceneCamera.MoveForwardBinding, ButtonCode.Up);
  270. inputConfig.RegisterButton(SceneCamera.MoveBackBinding, ButtonCode.Down);
  271. inputConfig.RegisterButton(SceneCamera.MoveLeftBinding, ButtonCode.Left);
  272. inputConfig.RegisterButton(SceneCamera.MoveRightBinding, ButtonCode.Right);
  273. inputConfig.RegisterButton(SceneCamera.FastMoveBinding, ButtonCode.LeftShift);
  274. inputConfig.RegisterButton(SceneCamera.RotateBinding, ButtonCode.MouseRight);
  275. inputConfig.RegisterButton(SceneCamera.PanBinding, ButtonCode.MouseMiddle);
  276. inputConfig.RegisterAxis(SceneCamera.HorizontalAxisBinding, InputAxis.MouseX);
  277. inputConfig.RegisterAxis(SceneCamera.VerticalAxisBinding, InputAxis.MouseY);
  278. inputConfig.RegisterAxis(SceneCamera.ScrollAxisBinding, InputAxis.MouseZ);
  279. inputConfig.RegisterButton(SceneWindow.ToggleProfilerOverlayBinding, ButtonCode.P, ButtonModifier.CtrlAlt);
  280. inputConfig.RegisterButton(SceneWindow.ViewToolBinding, ButtonCode.Q);
  281. inputConfig.RegisterButton(SceneWindow.FrameBinding, ButtonCode.F);
  282. inputConfig.RegisterButton(SceneWindow.MoveToolBinding, ButtonCode.W);
  283. inputConfig.RegisterButton(SceneWindow.RotateToolBinding, ButtonCode.E);
  284. inputConfig.RegisterButton(SceneWindow.ScaleToolBinding, ButtonCode.R);
  285. inputConfig.RegisterButton(CutBinding, ButtonCode.X, ButtonModifier.Ctrl);
  286. inputConfig.RegisterButton(CopyBinding, ButtonCode.C, ButtonModifier.Ctrl);
  287. inputConfig.RegisterButton(PasteBinding, ButtonCode.V, ButtonModifier.Ctrl);
  288. inputConfig.RegisterButton(DuplicateBinding, ButtonCode.D, ButtonModifier.Ctrl);
  289. inputConfig.RegisterButton(DeleteBinding, ButtonCode.Delete);
  290. inputConfig.RegisterButton(RenameBinding, ButtonCode.F2);
  291. if (IsProjectLoaded)
  292. {
  293. monitor = new FolderMonitor(ProjectLibrary.ResourceFolder);
  294. monitor.OnAdded += OnAssetModified;
  295. monitor.OnRemoved += OnAssetModified;
  296. monitor.OnModified += OnAssetModified;
  297. }
  298. }
  299. /// <summary>
  300. /// Updates <see cref="EditorSceneData"/> with the current state of the active scene.
  301. /// </summary>
  302. internal static void UpdateEditorSceneData()
  303. {
  304. if (EditorSceneData == null)
  305. EditorSceneData = EditorSceneData.FromScene(Scene.Root);
  306. else
  307. EditorSceneData.UpdateFromScene(Scene.Root);
  308. HierarchyWindow hierarcyWindow = EditorWindow.GetWindow<HierarchyWindow>();
  309. hierarcyWindow?.SaveHierarchyState(EditorSceneData);
  310. }
  311. /// <summary>
  312. /// Triggered whenever object or resource selection changes.
  313. /// </summary>
  314. private static void OnSelectionChanged(SceneObject[] sceneObjects, string[] resourcePaths)
  315. {
  316. NotifyNeedsRedraw();
  317. }
  318. /// <summary>
  319. /// Triggered when the scene has been loaded.
  320. /// </summary>
  321. /// <param name="uuid">UUID of the loaded scene.</param>
  322. private static void OnSceneUnload(UUID uuid)
  323. {
  324. UpdateEditorSceneData();
  325. string key = EditorSceneDataPrefix + uuid;
  326. ProjectSettings.SetObject(key, EditorSceneData);
  327. }
  328. /// <summary>
  329. /// Triggered when a scene is about to be unloaded.
  330. /// </summary>
  331. /// <param name="uuid">UUID of the scene to be unloaded.</param>
  332. private static void OnSceneLoad(UUID uuid)
  333. {
  334. string key = EditorSceneDataPrefix + uuid;
  335. EditorSceneData = ProjectSettings.GetObject<EditorSceneData>(key);
  336. if (EditorSceneData == null)
  337. EditorSceneData = EditorSceneData.FromScene(Scene.Root);
  338. }
  339. /// <summary>
  340. /// Triggered when the folder monitor detects an asset in the monitored folder was modified.
  341. /// </summary>
  342. /// <param name="path">Path to the modified file or folder.</param>
  343. private static void OnAssetModified(string path)
  344. {
  345. ProjectLibrary.Refresh(path);
  346. }
  347. /// <summary>
  348. /// Called every frame by the runtime.
  349. /// </summary>
  350. internal void OnEditorUpdate()
  351. {
  352. // Update managers
  353. ProjectLibrary.Update();
  354. codeManager.Update();
  355. if (delayUnloadProject)
  356. {
  357. delayUnloadProject = false;
  358. UnloadProject();
  359. delayUnloadCallback?.Invoke();
  360. delayUnloadCallback = null;
  361. }
  362. }
  363. /// <summary>
  364. /// Manually triggers a global shortcut.
  365. /// </summary>
  366. /// <param name="btn">Button for the shortcut. If this doesn't correspond to any shortcut, it is ignored.</param>
  367. internal static void TriggerGlobalShortcut(VirtualButton btn)
  368. {
  369. IGlobalShortcuts window = null;
  370. if (btn != PasteKey)
  371. {
  372. // The system ensures elsewhere that only either a resource or a scene object is selected, but not both
  373. if (Selection.ResourcePaths.Length > 0)
  374. {
  375. window = EditorWindow.GetWindow<LibraryWindow>();
  376. }
  377. else if (Selection.SceneObjects.Length > 0)
  378. {
  379. window = EditorWindow.GetWindow<HierarchyWindow>();
  380. if (window == null)
  381. window = EditorWindow.GetWindow<SceneWindow>();
  382. }
  383. if (window != null)
  384. {
  385. if (btn == CopyKey)
  386. window.OnCopyPressed();
  387. else if (btn == CutKey)
  388. window.OnCutPressed();
  389. else if (btn == PasteKey)
  390. window.OnPastePressed();
  391. else if (btn == DuplicateKey)
  392. window.OnDuplicatePressed();
  393. else if (btn == RenameKey)
  394. window.OnRenamePressed();
  395. else if (btn == DeleteKey)
  396. window.OnDeletePressed();
  397. }
  398. }
  399. else
  400. {
  401. HierarchyWindow hierarchy = EditorWindow.GetWindow<HierarchyWindow>();
  402. if (hierarchy != null && hierarchy.HasFocus)
  403. window = hierarchy;
  404. else
  405. {
  406. LibraryWindow library = EditorWindow.GetWindow<LibraryWindow>();
  407. if (library != null && library.HasFocus)
  408. window = library;
  409. }
  410. if (window != null)
  411. window.OnPastePressed();
  412. }
  413. }
  414. /// <summary>
  415. /// Creates a new empty scene.
  416. /// </summary>
  417. [MenuItem("File/New Scene", 10051, true)]
  418. private static void NewScene()
  419. {
  420. LoadScene(null);
  421. }
  422. /// <summary>
  423. /// Opens a dialog that allows the user to select a new prefab to load as the current scene. If current scene
  424. /// is modified the user is offered a chance to save it.
  425. /// </summary>
  426. [MenuItem("File/Open Scene", ButtonModifier.Ctrl, ButtonCode.L, 10050)]
  427. private static void LoadScene()
  428. {
  429. string[] scenePaths;
  430. if (BrowseDialog.OpenFile(ProjectLibrary.ResourceFolder, "", false, out scenePaths))
  431. {
  432. if (scenePaths.Length > 0)
  433. LoadScene(scenePaths[0]);
  434. }
  435. }
  436. /// <summary>
  437. /// Opens a dialog to allows the user to select a location where to save the current scene. If scene was previously
  438. /// saved it is instead automatically saved at the last location.
  439. /// </summary>
  440. public static void SaveScene(Action onSuccess = null, Action onFailure = null)
  441. {
  442. if (!Scene.ActiveSceneUUID.IsEmpty())
  443. {
  444. string scenePath = ProjectLibrary.GetPath(Scene.ActiveSceneUUID);
  445. if (!string.IsNullOrEmpty(scenePath))
  446. {
  447. if (Scene.IsGenericPrefab)
  448. {
  449. SaveGenericPrefab(onSuccess, onFailure);
  450. }
  451. else
  452. {
  453. SaveScene(scenePath);
  454. if (onSuccess != null)
  455. onSuccess();
  456. }
  457. }
  458. else
  459. SaveSceneAs(onSuccess, onFailure);
  460. }
  461. else
  462. SaveSceneAs(onSuccess, onFailure);
  463. }
  464. /// <summary>
  465. /// Opens a dialog to allows the user to select a location where to save the current scene.
  466. /// </summary>
  467. public static void SaveSceneAs(Action onSuccess = null, Action onFailure = null)
  468. {
  469. string scenePath = "";
  470. if (BrowseDialog.SaveFile(ProjectLibrary.ResourceFolder, "*.prefab", out scenePath))
  471. {
  472. if (!PathEx.IsPartOf(scenePath, ProjectLibrary.ResourceFolder))
  473. {
  474. DialogBox.Open("Error", "The location must be inside the Resources folder of the project.",
  475. DialogBox.Type.OK,
  476. x =>
  477. {
  478. if (onFailure != null)
  479. onFailure();
  480. });
  481. }
  482. else
  483. {
  484. // TODO - If path points to an existing non-scene asset or folder I should delete it otherwise
  485. // Internal_SaveScene will silently fail.
  486. scenePath = Path.ChangeExtension(scenePath, ".prefab");
  487. SaveScene(scenePath);
  488. }
  489. }
  490. else
  491. {
  492. // User canceled, so technically a success
  493. if (onSuccess != null)
  494. onSuccess();
  495. }
  496. }
  497. /// <summary>
  498. /// Loads a prefab as the current scene at the specified path. If current scene is modified the user is offered a
  499. /// chance to save it.
  500. /// </summary>
  501. /// <param name="path">Path to a valid prefab relative to the resource folder. If path is empty a brand new
  502. /// scene will be loaded.</param>
  503. public static void LoadScene(string path)
  504. {
  505. Action<string> continueLoad =
  506. (scenePath) =>
  507. {
  508. if (string.IsNullOrEmpty(path))
  509. {
  510. Scene.Clear();
  511. lastLoadedScene = null;
  512. }
  513. else
  514. lastLoadedScene = Scene.LoadAsync(path);
  515. SetSceneDirty(false);
  516. ProjectSettings.LastOpenScene = scenePath;
  517. ProjectSettings.Save();
  518. };
  519. Action<DialogBox.ResultType> dialogCallback =
  520. (result) =>
  521. {
  522. if (result == DialogBox.ResultType.Yes)
  523. {
  524. SaveScene();
  525. continueLoad(path);
  526. }
  527. else if (result == DialogBox.ResultType.No)
  528. continueLoad(path);
  529. };
  530. if (IsSceneModified())
  531. {
  532. DialogBox.Open("Warning", "You current scene has modifications. Do you wish to save them first?",
  533. DialogBox.Type.YesNoCancel, dialogCallback);
  534. }
  535. else
  536. continueLoad(path);
  537. }
  538. /// <summary>
  539. /// Saves the currently loaded scene to the specified path.
  540. /// </summary>
  541. /// <param name="path">Path relative to the resource folder. This can be the path to the existing scene
  542. /// prefab if it just needs updating. </param>
  543. internal static void SaveScene(string path)
  544. {
  545. Prefab scene = Internal_SaveScene(path);
  546. Scene.SetActive(scene);
  547. ProjectLibrary.Refresh(true);
  548. SetSceneDirty(false);
  549. }
  550. /// <summary>
  551. /// Attempts to save the current scene by applying the changes to a prefab, instead of saving it as a brand new
  552. /// scene. This is necessary for generic prefabs that have don't have a scene root included in the prefab. If the
  553. /// object added any other objects to the root, or has moved or deleted the original generic prefab the user
  554. /// will be asked to save the scene normally, creating a brand new prefab.
  555. /// </summary>
  556. private static void SaveGenericPrefab(Action onSuccess = null, Action onFailure = null)
  557. {
  558. // Find prefab root
  559. SceneObject root = null;
  560. int numChildren = Scene.Root.GetNumChildren();
  561. int numNormalChildren = 0;
  562. for (int i = 0; i < numChildren; i++)
  563. {
  564. SceneObject child = Scene.Root.GetChild(i);
  565. if (EditorUtility.IsInternal(child))
  566. continue;
  567. UUID prefabUUID = PrefabUtility.GetPrefabUUID(child);
  568. if (prefabUUID == Scene.ActiveSceneUUID)
  569. root = child;
  570. // If user added any other prefabs other than the initial one, the scene no longer represents a generic
  571. // prefab (as we can now longer save it by applying changes only to that prefab)
  572. numNormalChildren++;
  573. if (numNormalChildren > 1)
  574. {
  575. root = null;
  576. break;
  577. }
  578. }
  579. if (root != null)
  580. {
  581. PrefabUtility.ApplyPrefab(root, false);
  582. ProjectLibrary.Refresh(true);
  583. SetSceneDirty(false);
  584. if (onSuccess != null)
  585. onSuccess();
  586. }
  587. else
  588. {
  589. SaveSceneAs(onSuccess, onFailure);
  590. }
  591. }
  592. /// <summary>
  593. /// Checks does the folder at the provieded path contain a valid project.
  594. /// </summary>
  595. /// <param name="path">Absolute path to the root project folder.</param>
  596. /// <returns>True if the folder contains a valid project.</returns>
  597. public static bool IsValidProject(string path)
  598. {
  599. return Internal_IsValidProject(path);
  600. }
  601. /// <summary>
  602. /// Contains a new project in the provided folder.
  603. /// </summary>
  604. /// <param name="path">Absolute path to the folder to create the project in. Name of this folder will be used as the
  605. /// project's name.</param>
  606. public static void CreateProject(string path)
  607. {
  608. Internal_CreateProject(path);
  609. }
  610. /// <summary>
  611. /// Wrapper for menu items for <see cref="SaveScene(Action, Action)"/> method
  612. /// </summary>
  613. [MenuItem("File/Save Scene", ButtonModifier.Ctrl, ButtonCode.S, 10049)]
  614. [ToolbarItem("Save Scene", ToolbarIcon.SaveScene, "Save scene (Ctrl + S)", 1998)]
  615. private static void SaveSceneMenu()
  616. {
  617. SaveScene();
  618. }
  619. /// <summary>
  620. /// Wrapper for menu items for <see cref="SaveSceneAs(Action, Action)"/> method
  621. /// </summary>
  622. [MenuItem("File/Save Scene As", 10048)]
  623. private static void SaveSceneAsMenu()
  624. {
  625. SaveSceneAs();
  626. }
  627. /// <summary>
  628. /// Opens a Project Window allowing you to browse for or create a project.
  629. /// </summary>
  630. [MenuItem("File/Open Project", 10100)]
  631. [ToolbarItem("Open Project", ToolbarIcon.OpenProject, "Project manager", 2000)]
  632. public static void BrowseForProject()
  633. {
  634. ProjectWindow.Open();
  635. }
  636. /// <summary>
  637. /// Saves all data in the currently open project.
  638. /// </summary>
  639. [MenuItem("File/Save Project", 10099)]
  640. [ToolbarItem("Save Project", ToolbarIcon.SaveProject, "Save project", 1999)]
  641. public static void SaveProject()
  642. {
  643. OnProjectSave?.Invoke();
  644. // Apply changes to any animation clips edited using the animation editor
  645. foreach (var KVP in persistentData.dirtyAnimClips)
  646. KVP.Value.SaveToClip();
  647. // Save all dirty resources to disk
  648. foreach (var KVP in persistentData.dirtyResources)
  649. {
  650. UUID resourceUUID = KVP.Key;
  651. string path = ProjectLibrary.GetPath(resourceUUID);
  652. if (!IsNative(path))
  653. continue; // Imported resources can't be changed
  654. Resource resource = ProjectLibrary.Load<Resource>(path);
  655. if(resource != null)
  656. ProjectLibrary.Save(resource);
  657. }
  658. persistentData.dirtyAnimClips.Clear();
  659. persistentData.dirtyResources.Clear();
  660. SetStatusProject(false);
  661. Internal_SaveProject();
  662. }
  663. /// <summary>
  664. /// Loads the project at the specified path. This method executes asynchronously.
  665. /// </summary>
  666. /// <param name="path">Absolute path to the project's root folder.</param>
  667. public static void LoadProject(string path)
  668. {
  669. if (IsProjectLoaded && path == ProjectPath)
  670. return;
  671. if (!Internal_IsValidProject(path))
  672. {
  673. Debug.LogWarning("Provided path: \"" + path + "\" is not a valid project.");
  674. return;
  675. }
  676. if (IsProjectLoaded)
  677. TryUnloadProject(() => Internal_LoadProject(path));
  678. else
  679. Internal_LoadProject(path); // Triggers Internal_OnProjectLoaded when done
  680. }
  681. /// <summary>
  682. /// Closes the editor.
  683. /// </summary>
  684. public static void Quit()
  685. {
  686. Internal_Quit();
  687. }
  688. /// <summary>
  689. /// Toggles an existing toolbar button into an on or off state which changes the visuals of the button.
  690. /// </summary>
  691. /// <param name="name">Name of the existing button to toggle</param>
  692. /// <param name="on">True to toggle on, false to toggle off (default)</param>
  693. public static void ToggleToolbarItem(string name, bool on)
  694. {
  695. Internal_ToggleToolbarItem(name, on);
  696. }
  697. /// <summary>
  698. /// Opens a folder in the default external application.
  699. /// </summary>
  700. /// <param name="path">Absolute path to the folder to open.</param>
  701. public static void OpenFolder(string path)
  702. {
  703. Internal_OpenFolder(path);
  704. }
  705. /// <summary>
  706. /// Marks a resource as dirty so that it may be saved the next time the project is saved. Optionally you may also
  707. /// call <see cref="ProjectLibrary.Save"/> to save it immediately.
  708. /// </summary>
  709. /// <param name="resource">Resource to mark as dirty</param>
  710. public static void SetDirty(Resource resource)
  711. {
  712. if (resource == null)
  713. return;
  714. SetStatusProject(true);
  715. persistentData.dirtyResources[resource.UUID] = resource;
  716. }
  717. /// <summary>
  718. /// Marks the current project dirty (requires saving in order for changes not to be lost).
  719. /// </summary>
  720. public static void SetProjectDirty()
  721. {
  722. SetStatusProject(true);
  723. }
  724. /// <summary>
  725. /// Marks the current scene as dirty.
  726. /// </summary>
  727. public static void SetSceneDirty()
  728. {
  729. SetSceneDirty(true);
  730. NotifyNeedsRedraw();
  731. }
  732. /// <summary>
  733. /// Marks the current scene as clean or dirty.
  734. /// </summary>
  735. /// <param name="dirty">Should the scene be marked as clean or dirty.</param>
  736. internal static void SetSceneDirty(bool dirty)
  737. {
  738. sceneDirty = dirty;
  739. SetStatusScene(Scene.ActiveSceneName, dirty);
  740. if (!dirty && !Scene.ActiveSceneUUID.IsEmpty())
  741. persistentData.dirtyResources.Remove(Scene.ActiveSceneUUID);
  742. }
  743. /// <summary>
  744. /// Checks is the specific resource dirty and needs saving.
  745. /// </summary>
  746. /// <param name="resource">Resource to check.</param>
  747. /// <returns>True if the resource requires saving, false otherwise.</returns>
  748. public static bool IsDirty(Resource resource)
  749. {
  750. return persistentData.dirtyResources.ContainsKey(resource.UUID);
  751. }
  752. /// <summary>
  753. /// Notifies the system that the 3D viewports should be redrawn.
  754. /// </summary>
  755. public static void NotifyNeedsRedraw()
  756. {
  757. SceneWindow sceneWindow = EditorWindow.GetWindow<SceneWindow>();
  758. sceneWindow?.NotifyNeedsRedraw();
  759. GameWindow gameWindow = EditorWindow.GetWindow<GameWindow>();
  760. gameWindow?.NotifyNeedsRedraw();
  761. }
  762. /// <summary>
  763. /// Enables or disables on-demand drawing for 3D viewports. When enabled the viewports will only be
  764. /// redrawn when <see cref="NotifyNeedsRedraw"/> is called. If disabled the viewport will be redrawn
  765. /// every frame.
  766. /// </summary>
  767. /// <param name="enabled">True to enable on-demand drawing, false otherwise.</param>
  768. public static void ToggleOnDemandDrawing(bool enabled)
  769. {
  770. SceneWindow sceneWindow = EditorWindow.GetWindow<SceneWindow>();
  771. sceneWindow?.ToggleOnDemandDrawing(enabled);
  772. GameWindow gameWindow = EditorWindow.GetWindow<GameWindow>();
  773. gameWindow?.ToggleOnDemandDrawing(enabled);
  774. }
  775. /// <summary>
  776. /// Checks does the path represent a native resource.
  777. /// </summary>
  778. /// <param name="path">Filename or path to check.</param>
  779. /// <returns>True if the path represents a native resource.</returns>
  780. public static bool IsNative(string path)
  781. {
  782. string extension = Path.GetExtension(path);
  783. return extension == ".asset" || extension == ".prefab";
  784. }
  785. /// <summary>
  786. /// Attempts to unload the currently loaded project. Offers the user a chance to save the current scene if it is
  787. /// modified. Automatically saves all project data before unloading.
  788. /// </summary>
  789. /// <param name="onDone">Callback to trigger when project project unload is done.</param>
  790. private static void TryUnloadProject(Action onDone)
  791. {
  792. if (delayUnloadProject)
  793. return;
  794. AskToSaveSceneAndContinue(
  795. () =>
  796. {
  797. if (ProjectLibrary.ImportInProgress)
  798. {
  799. ConfirmImportInProgressWindow.Show();
  800. delayUnloadCallback = onDone;
  801. delayUnloadProject = true;
  802. }
  803. else
  804. {
  805. UnloadProject();
  806. onDone?.Invoke();
  807. }
  808. });
  809. }
  810. /// <summary>
  811. /// Unloads the currently loaded project, without making any checks or requiring confirmation.
  812. /// </summary>
  813. private static void UnloadProject()
  814. {
  815. Scene.Clear();
  816. if (monitor != null)
  817. {
  818. monitor.Destroy();
  819. monitor = null;
  820. }
  821. LibraryWindow window = EditorWindow.GetWindow<LibraryWindow>();
  822. if (window != null)
  823. window.Reset();
  824. SetSceneDirty(false);
  825. Internal_UnloadProject();
  826. SetStatusProject(false);
  827. }
  828. /// <summary>
  829. /// Checks if the current scene is modified and asks the user to save the scene if it is. Triggers the
  830. /// <see cref="next"/> callback when done, unless user cancels the operation.
  831. /// </summary>
  832. /// <param name="next">Callback to trigger after this method finishes.</param>
  833. internal static void AskToSaveSceneAndContinue(Action next)
  834. {
  835. Action trySaveScene = null;
  836. trySaveScene = () =>
  837. {
  838. SaveScene(next, trySaveScene);
  839. };
  840. Action<DialogBox.ResultType> dialogCallback =
  841. (result) =>
  842. {
  843. if (result == DialogBox.ResultType.Yes)
  844. trySaveScene();
  845. else if (result == DialogBox.ResultType.No)
  846. next?.Invoke();
  847. };
  848. if (IsSceneModified())
  849. {
  850. DialogBox.Open("Warning", "You current scene has modifications. Do you wish to save them first?",
  851. DialogBox.Type.YesNoCancel, dialogCallback);
  852. }
  853. else
  854. next?.Invoke();
  855. }
  856. /// <summary>
  857. /// Reloads all script assemblies in case they were modified. This action is delayed and will be executed
  858. /// at the beginning of the next frame.
  859. /// </summary>
  860. public static void ReloadAssemblies()
  861. {
  862. UpdateEditorSceneData();
  863. Internal_ReloadAssemblies();
  864. }
  865. /// <summary>
  866. /// Changes the scene displayed on the status bar.
  867. /// </summary>
  868. /// <param name="name">Name of the scene.</param>
  869. /// <param name="modified">Whether to display the scene as modified or not.</param>
  870. private static void SetStatusScene(string name, bool modified)
  871. {
  872. Internal_SetStatusScene(name, modified);
  873. }
  874. /// <summary>
  875. /// Changes the project state displayed on the status bar.
  876. /// </summary>
  877. /// <param name="modified">Whether to display the project as modified or not.</param>
  878. private static void SetStatusProject(bool modified)
  879. {
  880. Internal_SetStatusProject(modified);
  881. }
  882. /// <summary>
  883. /// Displays or hides the "compilation in progress" visual on the status bar.
  884. /// </summary>
  885. /// <param name="compiling">True to display the visual, false otherwise.</param>
  886. internal static void SetStatusCompiling(bool compiling)
  887. {
  888. Internal_SetStatusCompiling(compiling);
  889. }
  890. /// <summary>
  891. /// Displays or hides the "import in progress" visuals on the status bar and updates the related progress bar.
  892. /// </summary>
  893. /// <param name="importing">True to display the visual, false otherwise.</param>
  894. /// <param name="percent">Percent in range [0, 1] to display on the progress bar.</param>
  895. internal static void SetStatusImporting(bool importing, float percent)
  896. {
  897. Internal_SetStatusImporting(importing, percent);
  898. }
  899. /// <summary>
  900. /// Checks did we make any modifications to the scene since it was last saved.
  901. /// </summary>
  902. /// <returns>True if the scene was never saved, or was modified after last save.</returns>
  903. public static bool IsSceneModified()
  904. {
  905. return sceneDirty;
  906. }
  907. /// <summary>
  908. /// Executes any editor-specific unit tests. This should be called after a project is loaded if possible.
  909. /// </summary>
  910. private static void RunUnitTests()
  911. {
  912. #if DEBUG
  913. Internal_RunUnitTests();
  914. #endif
  915. }
  916. /// <summary>
  917. /// Triggered by the runtime when <see cref="LoadProject"/> method completes.
  918. /// </summary>
  919. private static void Internal_OnProjectLoaded()
  920. {
  921. SetStatusProject(false);
  922. if (!unitTestsExecuted)
  923. {
  924. RunUnitTests();
  925. unitTestsExecuted = true;
  926. }
  927. if (!IsProjectLoaded)
  928. {
  929. ProjectWindow.Open();
  930. return;
  931. }
  932. string projectPath = ProjectPath;
  933. RecentProject[] recentProjects = EditorSettings.RecentProjects;
  934. bool foundPath = false;
  935. for (int i = 0; i < recentProjects.Length; i++)
  936. {
  937. if (PathEx.Compare(recentProjects[i].path, projectPath))
  938. {
  939. recentProjects[i].accessTimestamp = (ulong)DateTime.Now.Ticks;
  940. EditorSettings.RecentProjects = recentProjects;
  941. foundPath = true;
  942. break;
  943. }
  944. }
  945. if (!foundPath)
  946. {
  947. List<RecentProject> extendedRecentProjects = new List<RecentProject>();
  948. extendedRecentProjects.AddRange(recentProjects);
  949. RecentProject newProject = new RecentProject();
  950. newProject.path = projectPath;
  951. newProject.accessTimestamp = (ulong)DateTime.Now.Ticks;
  952. extendedRecentProjects.Add(newProject);
  953. EditorSettings.RecentProjects = extendedRecentProjects.ToArray();
  954. }
  955. EditorSettings.LastOpenProject = projectPath;
  956. EditorSettings.Save();
  957. ProjectLibrary.Refresh();
  958. if(monitor != null)
  959. {
  960. monitor.Destroy();
  961. monitor = null;
  962. }
  963. monitor = new FolderMonitor(ProjectLibrary.ResourceFolder);
  964. monitor.OnAdded += OnAssetModified;
  965. monitor.OnRemoved += OnAssetModified;
  966. monitor.OnModified += OnAssetModified;
  967. if (!string.IsNullOrWhiteSpace(ProjectSettings.LastOpenScene))
  968. {
  969. lastLoadedScene = Scene.LoadAsync(ProjectSettings.LastOpenScene);
  970. SetSceneDirty(false);
  971. }
  972. }
  973. /// <summary>
  974. /// Triggered by the runtime when the user clicks on the status bar.
  975. /// </summary>
  976. private static void Internal_OnStatusBarClicked()
  977. {
  978. EditorWindow.OpenWindow<LogWindow>();
  979. }
  980. [MethodImpl(MethodImplOptions.InternalCall)]
  981. private static extern void Internal_SetStatusScene(string name, bool modified);
  982. [MethodImpl(MethodImplOptions.InternalCall)]
  983. private static extern void Internal_SetStatusProject(bool modified);
  984. [MethodImpl(MethodImplOptions.InternalCall)]
  985. private static extern void Internal_SetStatusCompiling(bool compiling);
  986. [MethodImpl(MethodImplOptions.InternalCall)]
  987. private static extern void Internal_SetStatusImporting(bool importing, float percent);
  988. [MethodImpl(MethodImplOptions.InternalCall)]
  989. private static extern string Internal_GetProjectPath();
  990. [MethodImpl(MethodImplOptions.InternalCall)]
  991. private static extern string Internal_GetProjectName();
  992. [MethodImpl(MethodImplOptions.InternalCall)]
  993. private static extern bool Internal_GetProjectLoaded();
  994. [MethodImpl(MethodImplOptions.InternalCall)]
  995. private static extern string Internal_GetCompilerPath();
  996. [MethodImpl(MethodImplOptions.InternalCall)]
  997. private static extern string Internal_GetMonoExecPath();
  998. [MethodImpl(MethodImplOptions.InternalCall)]
  999. private static extern string Internal_GetBuiltinReleaseAssemblyPath();
  1000. [MethodImpl(MethodImplOptions.InternalCall)]
  1001. private static extern string Internal_GetBuiltinDebugAssemblyPath();
  1002. [MethodImpl(MethodImplOptions.InternalCall)]
  1003. private static extern string Internal_GetScriptAssemblyPath();
  1004. [MethodImpl(MethodImplOptions.InternalCall)]
  1005. private static extern string Internal_GetFrameworkAssemblyPath();
  1006. [MethodImpl(MethodImplOptions.InternalCall)]
  1007. private static extern string Internal_GetEngineAssemblyName();
  1008. [MethodImpl(MethodImplOptions.InternalCall)]
  1009. private static extern string Internal_GetEditorAssemblyName();
  1010. [MethodImpl(MethodImplOptions.InternalCall)]
  1011. private static extern string Internal_GetScriptGameAssemblyName();
  1012. [MethodImpl(MethodImplOptions.InternalCall)]
  1013. private static extern string Internal_GetScriptEditorAssemblyName();
  1014. [MethodImpl(MethodImplOptions.InternalCall)]
  1015. private static extern Prefab Internal_SaveScene(string path);
  1016. [MethodImpl(MethodImplOptions.InternalCall)]
  1017. private static extern bool Internal_IsValidProject(string path);
  1018. [MethodImpl(MethodImplOptions.InternalCall)]
  1019. private static extern void Internal_SaveProject();
  1020. [MethodImpl(MethodImplOptions.InternalCall)]
  1021. private static extern void Internal_LoadProject(string path);
  1022. [MethodImpl(MethodImplOptions.InternalCall)]
  1023. private static extern void Internal_UnloadProject();
  1024. [MethodImpl(MethodImplOptions.InternalCall)]
  1025. private static extern void Internal_CreateProject(string path);
  1026. [MethodImpl(MethodImplOptions.InternalCall)]
  1027. private static extern void Internal_ReloadAssemblies();
  1028. [MethodImpl(MethodImplOptions.InternalCall)]
  1029. private static extern void Internal_OpenFolder(string path);
  1030. [MethodImpl(MethodImplOptions.InternalCall)]
  1031. private static extern void Internal_RunUnitTests();
  1032. [MethodImpl(MethodImplOptions.InternalCall)]
  1033. private static extern void Internal_Quit();
  1034. [MethodImpl(MethodImplOptions.InternalCall)]
  1035. private static extern void Internal_ToggleToolbarItem(string name, bool on);
  1036. [MethodImpl(MethodImplOptions.InternalCall)]
  1037. private static extern void Internal_SetMainRenderTarget(IntPtr rendertarget);
  1038. [MethodImpl(MethodImplOptions.InternalCall)]
  1039. private static extern bool Internal_HasFocus();
  1040. }
  1041. /** @} */
  1042. }