EditorApplication.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  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 BansheeEngine;
  8. namespace BansheeEditor
  9. {
  10. /// <summary>
  11. /// Available tools in the scene view.
  12. /// </summary>
  13. public enum SceneViewTool
  14. {
  15. View,
  16. Move,
  17. Rotate,
  18. Scale
  19. }
  20. /// <summary>
  21. /// Pivot mode used by the scene view tools.
  22. /// </summary>
  23. public enum HandlePivotMode
  24. {
  25. Center,
  26. Pivot
  27. }
  28. /// <summary>
  29. /// Coordinate mode used by the scene view tools.
  30. /// </summary>
  31. public enum HandleCoordinateMode
  32. {
  33. Local,
  34. World
  35. }
  36. /// <summary>
  37. /// Manages various generic and global settings relating to the editor.
  38. /// </summary>
  39. public class EditorApplication
  40. {
  41. internal const string CutBinding = "Cut";
  42. internal const string CopyBinding = "Copy";
  43. internal const string RenameBinding = "Rename";
  44. internal const string DuplicateBinding = "Duplicate";
  45. internal const string DeleteBinding = "Delete";
  46. internal const string PasteBinding = "Paste";
  47. /// <summary>
  48. /// Determines the active tool shown in the scene view.
  49. /// </summary>
  50. public static SceneViewTool ActiveSceneTool
  51. {
  52. get { return EditorSettings.ActiveSceneTool; }
  53. set { EditorSettings.ActiveSceneTool = value; }
  54. }
  55. /// <summary>
  56. /// Determines the coordinate mode used by the tools in the scene view.
  57. /// </summary>
  58. public static HandleCoordinateMode ActiveCoordinateMode
  59. {
  60. get { return EditorSettings.ActiveCoordinateMode; }
  61. set { EditorSettings.ActiveCoordinateMode = value; }
  62. }
  63. /// <summary>
  64. /// Determines the pivot mode used by the tools in the scene view.
  65. /// </summary>
  66. public static HandlePivotMode ActivePivotMode
  67. {
  68. get { return EditorSettings.ActivePivotMode; }
  69. set { EditorSettings.ActivePivotMode = value; }
  70. }
  71. /// <summary>
  72. /// Camera used for rendering the scene view.
  73. /// </summary>
  74. public static Camera SceneViewCamera
  75. {
  76. get { return EditorWindow.GetWindow<SceneWindow>().Camera; }
  77. }
  78. /// <summary>
  79. /// Absolute path to the folder containing the currently open project.
  80. /// </summary>
  81. public static string ProjectPath { get { return Internal_GetProjectPath(); } }
  82. /// <summary>
  83. /// Name of the currently open project.
  84. /// </summary>
  85. public static string ProjectName { get { return Internal_GetProjectName(); } }
  86. /// <summary>
  87. /// Checks is any project currently loaded.
  88. /// </summary>
  89. public static bool IsProjectLoaded { get { return Internal_GetProjectLoaded(); } }
  90. /// <summary>
  91. /// Determines is the game currently running in the editor, or is it stopped or paused. Setting this value to false
  92. /// will stop the game, but if you just want to pause it use <see cref="IsPaused"/> property.
  93. /// </summary>
  94. public static bool IsPlaying
  95. {
  96. get { return Internal_GetIsPlaying(); }
  97. set
  98. {
  99. ToggleToolbarItem("Play", value);
  100. ToggleToolbarItem("Pause", false);
  101. if (!value)
  102. Selection.SceneObject = null;
  103. else
  104. {
  105. if (EditorSettings.GetBool(LogWindow.CLEAR_ON_PLAY_KEY, true))
  106. {
  107. Debug.Clear();
  108. LogWindow log = EditorWindow.GetWindow<LogWindow>();
  109. if (log != null)
  110. log.Refresh();
  111. }
  112. }
  113. Internal_SetIsPlaying(value);
  114. }
  115. }
  116. /// <summary>
  117. /// Determines if the game is currently running in the editor, but paused. If the game is stopped and not running
  118. /// this will return false. If the game is not running and this is enabled, the game will start running but be
  119. /// immediately paused.
  120. /// </summary>
  121. public static bool IsPaused
  122. {
  123. get { return Internal_GetIsPaused(); }
  124. set
  125. {
  126. ToggleToolbarItem("Play", !value);
  127. ToggleToolbarItem("Pause", value);
  128. Internal_SetIsPaused(value);
  129. }
  130. }
  131. /// <summary>
  132. /// Returns true if the game is currently neither running nor paused. Use <see cref="IsPlaying"/> or
  133. /// <see cref="IsPaused"/> to actually change these states.
  134. /// </summary>
  135. public static bool IsStopped
  136. {
  137. get { return !IsPlaying && !IsPaused; }
  138. }
  139. /// <summary>
  140. /// Checks whether the editor currently has focus.
  141. /// </summary>
  142. public static bool HasFocus
  143. {
  144. get { return Internal_HasFocus(); }
  145. }
  146. /// <summary>
  147. /// Render target that the main camera in the scene (if any) will render its view to. This generally means the main
  148. /// game window when running standalone, or the Game viewport when running in editor.
  149. /// </summary>
  150. internal static RenderTarget MainRenderTarget
  151. {
  152. set
  153. {
  154. IntPtr rtPtr = IntPtr.Zero;
  155. if (value != null)
  156. rtPtr = value.GetCachedPtr();
  157. Internal_SetMainRenderTarget(rtPtr);
  158. }
  159. }
  160. /// <summary>
  161. /// Returns the path where the script compiler is located at.
  162. /// </summary>
  163. internal static string CompilerPath { get { return Internal_GetCompilerPath(); } }
  164. /// <summary>
  165. /// Returns the path to the folder where the custom script assemblies are located at.
  166. /// </summary>
  167. internal static string ScriptAssemblyPath { get { return Internal_GetScriptAssemblyPath(); } }
  168. /// <summary>
  169. /// Returns the path to the folder where the .NET framework assemblies are located at.
  170. /// </summary>
  171. internal static string FrameworkAssemblyPath { get { return Internal_GetFrameworkAssemblyPath(); } }
  172. /// <summary>
  173. /// Name of the builtin assembly containing engine specific types.
  174. /// </summary>
  175. internal static string EngineAssemblyName { get { return Internal_GetEngineAssemblyName(); } }
  176. /// <summary>
  177. /// Name of the builtin assembly containing editor specific types.
  178. /// </summary>
  179. internal static string EditorAssemblyName { get { return Internal_GetEditorAssemblyName(); } }
  180. /// <summary>
  181. /// Name of the custom assembly compiled from non-editor scripts within the project.
  182. /// </summary>
  183. internal static string ScriptGameAssemblyName { get { return Internal_GetScriptGameAssemblyName(); } }
  184. /// <summary>
  185. /// Name of the custom assembly compiled from editor scripts within the project.
  186. /// </summary>
  187. internal static string ScriptEditorAssemblyName { get { return Internal_GetScriptEditorAssemblyName(); } }
  188. /// <summary>
  189. /// Returns the path to the folder where the builtin release script assemblies are located at.
  190. /// </summary>
  191. internal static string BuiltinReleaseAssemblyPath { get { return Internal_GetBuiltinReleaseAssemblyPath(); } }
  192. /// <summary>
  193. /// Returns the path to the folder where the builtin debug script assemblies are located at.
  194. /// </summary>
  195. internal static string BuiltinDebugAssemblyPath { get { return Internal_GetBuiltinDebugAssemblyPath(); } }
  196. internal static VirtualButton CutKey = new VirtualButton(CutBinding);
  197. internal static VirtualButton CopyKey = new VirtualButton(CopyBinding);
  198. internal static VirtualButton PasteKey = new VirtualButton(PasteBinding);
  199. internal static VirtualButton RenameKey = new VirtualButton(RenameBinding);
  200. internal static VirtualButton DuplicateKey = new VirtualButton(DuplicateBinding);
  201. internal static VirtualButton DeleteKey = new VirtualButton(DeleteBinding);
  202. private static EditorApplication instance;
  203. private static FolderMonitor monitor;
  204. private static ScriptCodeManager codeManager;
  205. private static bool sceneDirty;
  206. private static bool unitTestsExecuted;
  207. private static EditorPersistentData persistentData;
  208. /// <summary>
  209. /// Constructs a new editor application. Called at editor start-up by the runtime, and any time assembly refresh
  210. /// occurrs.
  211. /// </summary>
  212. internal EditorApplication()
  213. {
  214. instance = this;
  215. codeManager = new ScriptCodeManager();
  216. const string soName = "EditorPersistentData";
  217. SceneObject so = Scene.Root.FindChild(soName);
  218. if (so == null)
  219. so = new SceneObject(soName, true);
  220. persistentData = so.GetComponent<EditorPersistentData>();
  221. if (persistentData == null)
  222. persistentData = so.AddComponent<EditorPersistentData>();
  223. // Register controls
  224. InputConfiguration inputConfig = VirtualInput.KeyConfig;
  225. inputConfig.RegisterButton(SceneCamera.MoveForwardBinding, ButtonCode.W);
  226. inputConfig.RegisterButton(SceneCamera.MoveBackBinding, ButtonCode.S);
  227. inputConfig.RegisterButton(SceneCamera.MoveLeftBinding, ButtonCode.A);
  228. inputConfig.RegisterButton(SceneCamera.MoveRightBinding, ButtonCode.D);
  229. inputConfig.RegisterButton(SceneCamera.MoveUpBinding, ButtonCode.E);
  230. inputConfig.RegisterButton(SceneCamera.MoveDownBinding, ButtonCode.Q);
  231. inputConfig.RegisterButton(SceneCamera.MoveForwardBinding, ButtonCode.Up);
  232. inputConfig.RegisterButton(SceneCamera.MoveBackBinding, ButtonCode.Down);
  233. inputConfig.RegisterButton(SceneCamera.MoveLeftBinding, ButtonCode.Left);
  234. inputConfig.RegisterButton(SceneCamera.MoveRightBinding, ButtonCode.Right);
  235. inputConfig.RegisterButton(SceneCamera.FastMoveBinding, ButtonCode.LeftShift);
  236. inputConfig.RegisterButton(SceneCamera.RotateBinding, ButtonCode.MouseRight);
  237. inputConfig.RegisterButton(SceneCamera.PanBinding, ButtonCode.MouseMiddle);
  238. inputConfig.RegisterAxis(SceneCamera.HorizontalAxisBinding, InputAxis.MouseX);
  239. inputConfig.RegisterAxis(SceneCamera.VerticalAxisBinding, InputAxis.MouseY);
  240. inputConfig.RegisterAxis(SceneCamera.ScrollAxisBinding, InputAxis.MouseZ);
  241. inputConfig.RegisterButton(SceneWindow.ToggleProfilerOverlayBinding, ButtonCode.P, ButtonModifier.CtrlAlt);
  242. inputConfig.RegisterButton(SceneWindow.ViewToolBinding, ButtonCode.Q);
  243. inputConfig.RegisterButton(SceneWindow.FrameBinding, ButtonCode.F);
  244. inputConfig.RegisterButton(SceneWindow.MoveToolBinding, ButtonCode.W);
  245. inputConfig.RegisterButton(SceneWindow.RotateToolBinding, ButtonCode.E);
  246. inputConfig.RegisterButton(SceneWindow.ScaleToolBinding, ButtonCode.R);
  247. inputConfig.RegisterButton(CutBinding, ButtonCode.X, ButtonModifier.Ctrl);
  248. inputConfig.RegisterButton(CopyBinding, ButtonCode.C, ButtonModifier.Ctrl);
  249. inputConfig.RegisterButton(PasteBinding, ButtonCode.V, ButtonModifier.Ctrl);
  250. inputConfig.RegisterButton(DuplicateBinding, ButtonCode.D, ButtonModifier.Ctrl);
  251. inputConfig.RegisterButton(DeleteBinding, ButtonCode.Delete);
  252. inputConfig.RegisterButton(RenameBinding, ButtonCode.F2);
  253. if (IsProjectLoaded)
  254. {
  255. monitor = new FolderMonitor(ProjectLibrary.ResourceFolder);
  256. monitor.OnAdded += OnAssetModified;
  257. monitor.OnRemoved += OnAssetModified;
  258. monitor.OnModified += OnAssetModified;
  259. }
  260. EditorVirtualInput.OnButtonUp += OnButtonUp;
  261. }
  262. /// <summary>
  263. /// Triggered when the folder monitor detects an asset in the monitored folder was modified.
  264. /// </summary>
  265. /// <param name="path">Path to the modified file or folder.</param>
  266. private static void OnAssetModified(string path)
  267. {
  268. ProjectLibrary.Refresh(path);
  269. }
  270. /// <summary>
  271. /// Triggered when the user presses a virtual button.
  272. /// </summary>
  273. /// <param name="btn">Button that was pressed.</param>
  274. /// <param name="deviceIdx">Index of the device it was pressed on. </param>
  275. private static void OnButtonUp(VirtualButton btn, int deviceIdx)
  276. {
  277. TriggerGlobalShortcut(btn);
  278. }
  279. /// <summary>
  280. /// Called every frame by the runtime.
  281. /// </summary>
  282. internal void OnEditorUpdate()
  283. {
  284. // Update managers
  285. ProjectLibrary.Update();
  286. codeManager.Update();
  287. }
  288. /// <summary>
  289. /// Manually triggers a global shortcut.
  290. /// </summary>
  291. /// <param name="btn">Button for the shortcut. If this doesn't correspond to any shortcut, it is ignored.</param>
  292. internal static void TriggerGlobalShortcut(VirtualButton btn)
  293. {
  294. IGlobalShortcuts window = null;
  295. if (btn != PasteKey)
  296. {
  297. // The system ensures elsewhere that only either a resource or a scene object is selected, but not both
  298. if (Selection.ResourcePaths.Length > 0)
  299. {
  300. window = EditorWindow.GetWindow<LibraryWindow>();
  301. }
  302. else if (Selection.SceneObjects.Length > 0)
  303. {
  304. window = EditorWindow.GetWindow<HierarchyWindow>();
  305. if (window == null)
  306. window = EditorWindow.GetWindow<SceneWindow>();
  307. }
  308. if (window != null)
  309. {
  310. if (btn == CopyKey)
  311. window.OnCopyPressed();
  312. else if (btn == CutKey)
  313. window.OnCutPressed();
  314. else if (btn == PasteKey)
  315. window.OnPastePressed();
  316. else if (btn == DuplicateKey)
  317. window.OnDuplicatePressed();
  318. else if (btn == RenameKey)
  319. window.OnRenamePressed();
  320. else if (btn == DeleteKey)
  321. window.OnDeletePressed();
  322. }
  323. }
  324. else
  325. {
  326. HierarchyWindow hierarchy = EditorWindow.GetWindow<HierarchyWindow>();
  327. if (hierarchy != null && hierarchy.HasFocus)
  328. window = hierarchy;
  329. else
  330. {
  331. LibraryWindow library = EditorWindow.GetWindow<LibraryWindow>();
  332. if (library != null && library.HasFocus)
  333. window = library;
  334. }
  335. if (window != null)
  336. window.OnPastePressed();
  337. }
  338. }
  339. /// <summary>
  340. /// Creates a new empty scene.
  341. /// </summary>
  342. [MenuItem("File/New Scene", 10051, true)]
  343. private static void NewScene()
  344. {
  345. LoadScene(null);
  346. }
  347. /// <summary>
  348. /// Opens a dialog that allows the user to select a new prefab to load as the current scene. If current scene
  349. /// is modified the user is offered a chance to save it.
  350. /// </summary>
  351. [MenuItem("File/Open Scene", ButtonModifier.Ctrl, ButtonCode.L, 10050)]
  352. private static void LoadScene()
  353. {
  354. string[] scenePaths;
  355. if (BrowseDialog.OpenFile(ProjectLibrary.ResourceFolder, "", false, out scenePaths))
  356. {
  357. if (scenePaths.Length > 0)
  358. LoadScene(scenePaths[0]);
  359. }
  360. }
  361. /// <summary>
  362. /// Opens a dialog to allows the user to select a location where to save the current scene. If scene was previously
  363. /// saved it is instead automatically saved at the last location.
  364. /// </summary>
  365. public static void SaveScene(Action onSuccess = null, Action onFailure = null)
  366. {
  367. if (!string.IsNullOrEmpty(Scene.ActiveSceneUUID))
  368. {
  369. string scenePath = ProjectLibrary.GetPath(Scene.ActiveSceneUUID);
  370. if (!string.IsNullOrEmpty(scenePath))
  371. {
  372. SaveScene(scenePath);
  373. if (onSuccess != null)
  374. onSuccess();
  375. }
  376. else
  377. SaveSceneAs(onSuccess, onFailure);
  378. }
  379. else
  380. SaveSceneAs(onSuccess, onFailure);
  381. }
  382. /// <summary>
  383. /// Opens a dialog to allows the user to select a location where to save the current scene.
  384. /// </summary>
  385. public static void SaveSceneAs(Action onSuccess = null, Action onFailure = null)
  386. {
  387. string scenePath = "";
  388. if (BrowseDialog.SaveFile(ProjectLibrary.ResourceFolder, "*.prefab", out scenePath))
  389. {
  390. if (!PathEx.IsPartOf(scenePath, ProjectLibrary.ResourceFolder))
  391. {
  392. DialogBox.Open("Error", "The location must be inside the Resources folder of the project.",
  393. DialogBox.Type.OK,
  394. x =>
  395. {
  396. if (onFailure != null)
  397. onFailure();
  398. });
  399. }
  400. else
  401. {
  402. // TODO - If path points to an existing non-scene asset or folder I should delete it otherwise
  403. // Internal_SaveScene will silently fail.
  404. scenePath = Path.ChangeExtension(scenePath, ".prefab");
  405. SaveScene(scenePath);
  406. }
  407. }
  408. else
  409. {
  410. // User canceled, so technically a success
  411. if (onSuccess != null)
  412. onSuccess();
  413. }
  414. }
  415. /// <summary>
  416. /// Loads a prefab as the current scene at the specified path. If current scene is modified the user is offered a
  417. /// chance to save it.
  418. /// </summary>
  419. /// <param name="path">Path to a valid prefab relative to the resource folder. If path is empty a brand new
  420. /// scene will be loaded.</param>
  421. public static void LoadScene(string path)
  422. {
  423. Action<string> continueLoad =
  424. (scenePath) =>
  425. {
  426. if (string.IsNullOrEmpty(path))
  427. Scene.Clear();
  428. else
  429. Scene.Load(path);
  430. SetSceneDirty(false);
  431. ProjectSettings.LastOpenScene = scenePath;
  432. ProjectSettings.Save();
  433. };
  434. Action<DialogBox.ResultType> dialogCallback =
  435. (result) =>
  436. {
  437. if (result == DialogBox.ResultType.Yes)
  438. {
  439. SaveScene();
  440. continueLoad(path);
  441. }
  442. else if (result == DialogBox.ResultType.No)
  443. continueLoad(path);
  444. };
  445. if (IsSceneModified())
  446. {
  447. DialogBox.Open("Warning", "You current scene has modifications. Do you wish to save them first?",
  448. DialogBox.Type.YesNoCancel, dialogCallback);
  449. }
  450. else
  451. continueLoad(path);
  452. }
  453. /// <summary>
  454. /// Saves the currently loaded scene to the specified path.
  455. /// </summary>
  456. /// <param name="path">Path relative to the resource folder. This can be the path to the existing scene
  457. /// prefab if it just needs updating. </param>
  458. public static void SaveScene(string path)
  459. {
  460. Prefab scene = Internal_SaveScene(path);
  461. Scene.SetActive(scene);
  462. ProjectLibrary.Refresh(true);
  463. SetSceneDirty(false);
  464. }
  465. /// <summary>
  466. /// Checks does the folder at the provieded path contain a valid project.
  467. /// </summary>
  468. /// <param name="path">Absolute path to the root project folder.</param>
  469. /// <returns>True if the folder contains a valid project.</returns>
  470. public static bool IsValidProject(string path)
  471. {
  472. return Internal_IsValidProject(path);
  473. }
  474. /// <summary>
  475. /// Contains a new project in the provided folder.
  476. /// </summary>
  477. /// <param name="path">Absolute path to the folder to create the project in. Name of this folder will be used as the
  478. /// project's name.</param>
  479. public static void CreateProject(string path)
  480. {
  481. Internal_CreateProject(path);
  482. }
  483. /// <summary>
  484. /// Wrapper for menu items for <see cref="SaveScene(Action, Action)"/> method
  485. /// </summary>
  486. [MenuItem("File/Save Scene", ButtonModifier.Ctrl, ButtonCode.S, 10049)]
  487. [ToolbarItem("Save Scene", ToolbarIcon.SaveScene, "Save scene (Ctrl + S)", 1998)]
  488. private static void SaveSceneMenu()
  489. {
  490. SaveScene();
  491. }
  492. /// <summary>
  493. /// Wrapper for menu items for <see cref="SaveSceneAs(Action, Action)"/> method
  494. /// </summary>
  495. [MenuItem("File/Save Scene As", 10048)]
  496. private static void SaveSceneAsMenu()
  497. {
  498. SaveSceneAs();
  499. }
  500. /// <summary>
  501. /// Opens a Project Window allowing you to browse for or create a project.
  502. /// </summary>
  503. [MenuItem("File/Open Project", 10100)]
  504. [ToolbarItem("Open Project", ToolbarIcon.OpenProject, "Project manager", 2000)]
  505. public static void BrowseForProject()
  506. {
  507. ProjectWindow.Open();
  508. }
  509. /// <summary>
  510. /// Saves all data in the currently open project.
  511. /// </summary>
  512. [MenuItem("File/Save Project", 10099)]
  513. [ToolbarItem("Save Project", ToolbarIcon.SaveProject, "Save project", 1999)]
  514. public static void SaveProject()
  515. {
  516. foreach (var KVP in persistentData.dirtyResources)
  517. {
  518. string resourceUUID = KVP.Key;
  519. string path = ProjectLibrary.GetPath(resourceUUID);
  520. if (!IsNative(path))
  521. continue; // Native resources can't be changed
  522. Resource resource = ProjectLibrary.Load<Resource>(path);
  523. if(resource != null)
  524. ProjectLibrary.Save(resource);
  525. }
  526. persistentData.dirtyResources.Clear();
  527. SetStatusProject(false);
  528. Internal_SaveProject();
  529. }
  530. /// <summary>
  531. /// Loads the project at the specified path. This method executes asynchronously.
  532. /// </summary>
  533. /// <param name="path">Absolute path to the project's root folder.</param>
  534. public static void LoadProject(string path)
  535. {
  536. if (IsProjectLoaded && path == ProjectPath)
  537. return;
  538. if (!Internal_IsValidProject(path))
  539. {
  540. Debug.LogWarning("Provided path: \"" + path + "\" is not a valid project.");
  541. return;
  542. }
  543. if (IsProjectLoaded)
  544. UnloadProject();
  545. Internal_LoadProject(path); // Triggers Internal_OnProjectLoaded when done
  546. }
  547. /// <summary>
  548. /// Closes the editor.
  549. /// </summary>
  550. public static void Quit()
  551. {
  552. Internal_Quit();
  553. }
  554. /// <summary>
  555. /// Toggles an existing toolbar button into an on or off state which changes the visuals of the button.
  556. /// </summary>
  557. /// <param name="name">Name of the existing button to toggle</param>
  558. /// <param name="on">True to toggle on, false to toggle off (default)</param>
  559. public static void ToggleToolbarItem(string name, bool on)
  560. {
  561. Internal_ToggleToolbarItem(name, on);
  562. }
  563. /// <summary>
  564. /// Opens a file or a folder in the default external application.
  565. /// </summary>
  566. /// <param name="path">Absolute path to the file or folder to open.</param>
  567. public static void OpenExternally(string path)
  568. {
  569. Internal_OpenExternally(path);
  570. }
  571. /// <summary>
  572. /// Marks a resource as dirty so that it may be saved the next time the project is saved. Optionally you may also
  573. /// call <see cref="ProjectLibrary.Save"/> to save it immediately.
  574. /// </summary>
  575. /// <param name="resource">Resource to mark as dirty</param>
  576. public static void SetDirty(Resource resource)
  577. {
  578. if (resource == null)
  579. return;
  580. SetStatusProject(true);
  581. persistentData.dirtyResources[resource.UUID] = true;
  582. }
  583. /// <summary>
  584. /// Marks the current scene as dirty.
  585. /// </summary>
  586. public static void SetSceneDirty()
  587. {
  588. SetSceneDirty(true);
  589. }
  590. /// <summary>
  591. /// Marks the current scene as clean or dirty.
  592. /// </summary>
  593. /// <param name="dirty">Should the scene be marked as clean or dirty.</param>
  594. internal static void SetSceneDirty(bool dirty)
  595. {
  596. sceneDirty = dirty;
  597. SetStatusScene(Scene.ActiveSceneName, dirty);
  598. if (!dirty && Scene.ActiveSceneUUID != null)
  599. persistentData.dirtyResources.Remove(Scene.ActiveSceneUUID);
  600. }
  601. /// <summary>
  602. /// Checks is the specific resource dirty and needs saving.
  603. /// </summary>
  604. /// <param name="resource">Resource to check.</param>
  605. /// <returns>True if the resource requires saving, false otherwise.</returns>
  606. public static bool IsDirty(Resource resource)
  607. {
  608. return persistentData.dirtyResources.ContainsKey(resource.UUID);
  609. }
  610. /// <summary>
  611. /// Checks does the path represent a native resource.
  612. /// </summary>
  613. /// <param name="path">Filename or path to check.</param>
  614. /// <returns>True if the path represents a native resource.</returns>
  615. public static bool IsNative(string path)
  616. {
  617. string extension = Path.GetExtension(path);
  618. return extension == ".asset" || extension == ".prefab";
  619. }
  620. /// <summary>
  621. /// Unloads the currently loaded project. Offers the user a chance to save the current scene if it is modified.
  622. /// Automatically saves all project data before unloading.
  623. /// </summary>
  624. private static void UnloadProject()
  625. {
  626. Action continueUnload =
  627. () =>
  628. {
  629. Scene.Clear();
  630. if (monitor != null)
  631. {
  632. monitor.Destroy();
  633. monitor = null;
  634. }
  635. LibraryWindow window = EditorWindow.GetWindow<LibraryWindow>();
  636. if(window != null)
  637. window.Reset();
  638. SetSceneDirty(false);
  639. Internal_UnloadProject();
  640. SetStatusProject(false);
  641. };
  642. Action<DialogBox.ResultType> dialogCallback =
  643. (result) =>
  644. {
  645. if (result == DialogBox.ResultType.Yes)
  646. SaveScene();
  647. continueUnload();
  648. };
  649. if (IsSceneModified())
  650. {
  651. DialogBox.Open("Warning", "You current scene has modifications. Do you wish to save them first?",
  652. DialogBox.Type.YesNoCancel, dialogCallback);
  653. }
  654. else
  655. continueUnload();
  656. }
  657. /// <summary>
  658. /// Reloads all script assemblies in case they were modified. This action is delayed and will be executed
  659. /// at the beginning of the next frame.
  660. /// </summary>
  661. public static void ReloadAssemblies()
  662. {
  663. Internal_ReloadAssemblies();
  664. }
  665. /// <summary>
  666. /// Changes the scene displayed on the status bar.
  667. /// </summary>
  668. /// <param name="name">Name of the scene.</param>
  669. /// <param name="modified">Whether to display the scene as modified or not.</param>
  670. private static void SetStatusScene(string name, bool modified)
  671. {
  672. Internal_SetStatusScene(name, modified);
  673. }
  674. /// <summary>
  675. /// Changes the project state displayed on the status bar.
  676. /// </summary>
  677. /// <param name="modified">Whether to display the project as modified or not.</param>
  678. private static void SetStatusProject(bool modified)
  679. {
  680. Internal_SetStatusProject(modified);
  681. }
  682. /// <summary>
  683. /// Displays or hides the "compilation in progress" visual on the status bar.
  684. /// </summary>
  685. /// <param name="compiling">True to display the visual, false otherwise.</param>
  686. internal static void SetStatusCompiling(bool compiling)
  687. {
  688. Internal_SetStatusCompiling(compiling);
  689. }
  690. /// <summary>
  691. /// Checks did we make any modifications to the scene since it was last saved.
  692. /// </summary>
  693. /// <returns>True if the scene was never saved, or was modified after last save.</returns>
  694. public static bool IsSceneModified()
  695. {
  696. return sceneDirty;
  697. }
  698. /// <summary>
  699. /// Runs a single frame of the game and pauses it. If the game is not currently running it will be started.
  700. /// </summary>
  701. public static void FrameStep()
  702. {
  703. if (IsStopped)
  704. {
  705. if (EditorSettings.GetBool(LogWindow.CLEAR_ON_PLAY_KEY, true))
  706. {
  707. Debug.Clear();
  708. LogWindow log = EditorWindow.GetWindow<LogWindow>();
  709. if (log != null)
  710. log.Refresh();
  711. }
  712. }
  713. ToggleToolbarItem("Play", false);
  714. ToggleToolbarItem("Pause", true);
  715. Internal_FrameStep();
  716. }
  717. /// <summary>
  718. /// Executes any editor-specific unit tests. This should be called after a project is loaded if possible.
  719. /// </summary>
  720. private static void RunUnitTests()
  721. {
  722. #if DEBUG
  723. Internal_RunUnitTests();
  724. #endif
  725. }
  726. /// <summary>
  727. /// Triggered by the runtime when <see cref="LoadProject"/> method completes.
  728. /// </summary>
  729. private static void Internal_OnProjectLoaded()
  730. {
  731. SetStatusProject(false);
  732. if (!unitTestsExecuted)
  733. {
  734. RunUnitTests();
  735. unitTestsExecuted = true;
  736. }
  737. if (!IsProjectLoaded)
  738. {
  739. ProjectWindow.Open();
  740. return;
  741. }
  742. string projectPath = ProjectPath;
  743. RecentProject[] recentProjects = EditorSettings.RecentProjects;
  744. bool foundPath = false;
  745. for (int i = 0; i < recentProjects.Length; i++)
  746. {
  747. if (PathEx.Compare(recentProjects[i].path, projectPath))
  748. {
  749. recentProjects[i].accessTimestamp = (ulong)DateTime.Now.Ticks;
  750. EditorSettings.RecentProjects = recentProjects;
  751. foundPath = true;
  752. break;
  753. }
  754. }
  755. if (!foundPath)
  756. {
  757. List<RecentProject> extendedRecentProjects = new List<RecentProject>();
  758. extendedRecentProjects.AddRange(recentProjects);
  759. RecentProject newProject = new RecentProject();
  760. newProject.path = projectPath;
  761. newProject.accessTimestamp = (ulong)DateTime.Now.Ticks;
  762. extendedRecentProjects.Add(newProject);
  763. EditorSettings.RecentProjects = extendedRecentProjects.ToArray();
  764. }
  765. EditorSettings.LastOpenProject = projectPath;
  766. EditorSettings.Save();
  767. ProjectLibrary.Refresh();
  768. monitor = new FolderMonitor(ProjectLibrary.ResourceFolder);
  769. monitor.OnAdded += OnAssetModified;
  770. monitor.OnRemoved += OnAssetModified;
  771. monitor.OnModified += OnAssetModified;
  772. if (!string.IsNullOrWhiteSpace(ProjectSettings.LastOpenScene))
  773. {
  774. Scene.Load(ProjectSettings.LastOpenScene);
  775. SetSceneDirty(false);
  776. }
  777. }
  778. /// <summary>
  779. /// Triggered by the runtime when the user clicks on the status bar.
  780. /// </summary>
  781. private static void Internal_OnStatusBarClicked()
  782. {
  783. EditorWindow.OpenWindow<LogWindow>();
  784. }
  785. [MethodImpl(MethodImplOptions.InternalCall)]
  786. private static extern void Internal_SetStatusScene(string name, bool modified);
  787. [MethodImpl(MethodImplOptions.InternalCall)]
  788. private static extern void Internal_SetStatusProject(bool modified);
  789. [MethodImpl(MethodImplOptions.InternalCall)]
  790. private static extern void Internal_SetStatusCompiling(bool compiling);
  791. [MethodImpl(MethodImplOptions.InternalCall)]
  792. private static extern string Internal_GetProjectPath();
  793. [MethodImpl(MethodImplOptions.InternalCall)]
  794. private static extern string Internal_GetProjectName();
  795. [MethodImpl(MethodImplOptions.InternalCall)]
  796. private static extern bool Internal_GetProjectLoaded();
  797. [MethodImpl(MethodImplOptions.InternalCall)]
  798. private static extern string Internal_GetCompilerPath();
  799. [MethodImpl(MethodImplOptions.InternalCall)]
  800. private static extern string Internal_GetBuiltinReleaseAssemblyPath();
  801. [MethodImpl(MethodImplOptions.InternalCall)]
  802. private static extern string Internal_GetBuiltinDebugAssemblyPath();
  803. [MethodImpl(MethodImplOptions.InternalCall)]
  804. private static extern string Internal_GetScriptAssemblyPath();
  805. [MethodImpl(MethodImplOptions.InternalCall)]
  806. private static extern string Internal_GetFrameworkAssemblyPath();
  807. [MethodImpl(MethodImplOptions.InternalCall)]
  808. private static extern string Internal_GetEngineAssemblyName();
  809. [MethodImpl(MethodImplOptions.InternalCall)]
  810. private static extern string Internal_GetEditorAssemblyName();
  811. [MethodImpl(MethodImplOptions.InternalCall)]
  812. private static extern string Internal_GetScriptGameAssemblyName();
  813. [MethodImpl(MethodImplOptions.InternalCall)]
  814. private static extern string Internal_GetScriptEditorAssemblyName();
  815. [MethodImpl(MethodImplOptions.InternalCall)]
  816. private static extern Prefab Internal_SaveScene(string path);
  817. [MethodImpl(MethodImplOptions.InternalCall)]
  818. private static extern bool Internal_IsValidProject(string path);
  819. [MethodImpl(MethodImplOptions.InternalCall)]
  820. private static extern void Internal_SaveProject();
  821. [MethodImpl(MethodImplOptions.InternalCall)]
  822. private static extern void Internal_LoadProject(string path);
  823. [MethodImpl(MethodImplOptions.InternalCall)]
  824. private static extern void Internal_UnloadProject();
  825. [MethodImpl(MethodImplOptions.InternalCall)]
  826. private static extern void Internal_CreateProject(string path);
  827. [MethodImpl(MethodImplOptions.InternalCall)]
  828. private static extern void Internal_ReloadAssemblies();
  829. [MethodImpl(MethodImplOptions.InternalCall)]
  830. private static extern void Internal_OpenExternally(string path);
  831. [MethodImpl(MethodImplOptions.InternalCall)]
  832. private static extern void Internal_RunUnitTests();
  833. [MethodImpl(MethodImplOptions.InternalCall)]
  834. private static extern void Internal_Quit();
  835. [MethodImpl(MethodImplOptions.InternalCall)]
  836. private static extern void Internal_ToggleToolbarItem(string name, bool on);
  837. [MethodImpl(MethodImplOptions.InternalCall)]
  838. private static extern bool Internal_GetIsPlaying();
  839. [MethodImpl(MethodImplOptions.InternalCall)]
  840. private static extern void Internal_SetIsPlaying(bool value);
  841. [MethodImpl(MethodImplOptions.InternalCall)]
  842. private static extern bool Internal_GetIsPaused();
  843. [MethodImpl(MethodImplOptions.InternalCall)]
  844. private static extern void Internal_SetIsPaused(bool value);
  845. [MethodImpl(MethodImplOptions.InternalCall)]
  846. private static extern void Internal_FrameStep();
  847. [MethodImpl(MethodImplOptions.InternalCall)]
  848. private static extern void Internal_SetMainRenderTarget(IntPtr rendertarget);
  849. [MethodImpl(MethodImplOptions.InternalCall)]
  850. private static extern bool Internal_HasFocus();
  851. }
  852. }