EditorApplication.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  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. }
  261. /// <summary>
  262. /// Triggered when the folder monitor detects an asset in the monitored folder was modified.
  263. /// </summary>
  264. /// <param name="path">Path to the modified file or folder.</param>
  265. private static void OnAssetModified(string path)
  266. {
  267. ProjectLibrary.Refresh(path);
  268. }
  269. /// <summary>
  270. /// Called every frame by the runtime.
  271. /// </summary>
  272. internal void OnEditorUpdate()
  273. {
  274. // Update managers
  275. ProjectLibrary.Update();
  276. codeManager.Update();
  277. }
  278. /// <summary>
  279. /// Manually triggers a global shortcut.
  280. /// </summary>
  281. /// <param name="btn">Button for the shortcut. If this doesn't correspond to any shortcut, it is ignored.</param>
  282. internal static void TriggerGlobalShortcut(VirtualButton btn)
  283. {
  284. IGlobalShortcuts window = null;
  285. if (btn != PasteKey)
  286. {
  287. // The system ensures elsewhere that only either a resource or a scene object is selected, but not both
  288. if (Selection.ResourcePaths.Length > 0)
  289. {
  290. window = EditorWindow.GetWindow<LibraryWindow>();
  291. }
  292. else if (Selection.SceneObjects.Length > 0)
  293. {
  294. window = EditorWindow.GetWindow<HierarchyWindow>();
  295. if (window == null)
  296. window = EditorWindow.GetWindow<SceneWindow>();
  297. }
  298. if (window != null)
  299. {
  300. if (btn == CopyKey)
  301. window.OnCopyPressed();
  302. else if (btn == CutKey)
  303. window.OnCutPressed();
  304. else if (btn == PasteKey)
  305. window.OnPastePressed();
  306. else if (btn == DuplicateKey)
  307. window.OnDuplicatePressed();
  308. else if (btn == RenameKey)
  309. window.OnRenamePressed();
  310. else if (btn == DeleteKey)
  311. window.OnDeletePressed();
  312. }
  313. }
  314. else
  315. {
  316. HierarchyWindow hierarchy = EditorWindow.GetWindow<HierarchyWindow>();
  317. if (hierarchy != null && hierarchy.HasFocus)
  318. window = hierarchy;
  319. else
  320. {
  321. LibraryWindow library = EditorWindow.GetWindow<LibraryWindow>();
  322. if (library != null && library.HasFocus)
  323. window = library;
  324. }
  325. if (window != null)
  326. window.OnPastePressed();
  327. }
  328. }
  329. /// <summary>
  330. /// Creates a new empty scene.
  331. /// </summary>
  332. [MenuItem("File/New Scene", 10051, true)]
  333. private static void NewScene()
  334. {
  335. LoadScene(null);
  336. }
  337. /// <summary>
  338. /// Opens a dialog that allows the user to select a new prefab to load as the current scene. If current scene
  339. /// is modified the user is offered a chance to save it.
  340. /// </summary>
  341. [MenuItem("File/Open Scene", ButtonModifier.Ctrl, ButtonCode.L, 10050)]
  342. private static void LoadScene()
  343. {
  344. string[] scenePaths;
  345. if (BrowseDialog.OpenFile(ProjectLibrary.ResourceFolder, "", false, out scenePaths))
  346. {
  347. if (scenePaths.Length > 0)
  348. LoadScene(scenePaths[0]);
  349. }
  350. }
  351. /// <summary>
  352. /// Opens a dialog to allows the user to select a location where to save the current scene. If scene was previously
  353. /// saved it is instead automatically saved at the last location.
  354. /// </summary>
  355. public static void SaveScene(Action onSuccess = null, Action onFailure = null)
  356. {
  357. if (!string.IsNullOrEmpty(Scene.ActiveSceneUUID))
  358. {
  359. string scenePath = ProjectLibrary.GetPath(Scene.ActiveSceneUUID);
  360. if (!string.IsNullOrEmpty(scenePath))
  361. {
  362. SaveScene(scenePath);
  363. if (onSuccess != null)
  364. onSuccess();
  365. }
  366. else
  367. SaveSceneAs(onSuccess, onFailure);
  368. }
  369. else
  370. SaveSceneAs(onSuccess, onFailure);
  371. }
  372. /// <summary>
  373. /// Opens a dialog to allows the user to select a location where to save the current scene.
  374. /// </summary>
  375. public static void SaveSceneAs(Action onSuccess = null, Action onFailure = null)
  376. {
  377. string scenePath = "";
  378. if (BrowseDialog.SaveFile(ProjectLibrary.ResourceFolder, "*.prefab", out scenePath))
  379. {
  380. if (!PathEx.IsPartOf(scenePath, ProjectLibrary.ResourceFolder))
  381. {
  382. DialogBox.Open("Error", "The location must be inside the Resources folder of the project.",
  383. DialogBox.Type.OK,
  384. x =>
  385. {
  386. if (onFailure != null)
  387. onFailure();
  388. });
  389. }
  390. else
  391. {
  392. // TODO - If path points to an existing non-scene asset or folder I should delete it otherwise
  393. // Internal_SaveScene will silently fail.
  394. scenePath = Path.ChangeExtension(scenePath, ".prefab");
  395. SaveScene(scenePath);
  396. }
  397. }
  398. else
  399. {
  400. // User canceled, so technically a success
  401. if (onSuccess != null)
  402. onSuccess();
  403. }
  404. }
  405. /// <summary>
  406. /// Loads a prefab as the current scene at the specified path. If current scene is modified the user is offered a
  407. /// chance to save it.
  408. /// </summary>
  409. /// <param name="path">Path to a valid prefab relative to the resource folder. If path is empty a brand new
  410. /// scene will be loaded.</param>
  411. public static void LoadScene(string path)
  412. {
  413. Action<string> continueLoad =
  414. (scenePath) =>
  415. {
  416. if (string.IsNullOrEmpty(path))
  417. Scene.Clear();
  418. else
  419. Scene.Load(path);
  420. SetSceneDirty(false);
  421. ProjectSettings.LastOpenScene = scenePath;
  422. ProjectSettings.Save();
  423. };
  424. Action<DialogBox.ResultType> dialogCallback =
  425. (result) =>
  426. {
  427. if (result == DialogBox.ResultType.Yes)
  428. {
  429. SaveScene();
  430. continueLoad(path);
  431. }
  432. else if (result == DialogBox.ResultType.No)
  433. continueLoad(path);
  434. };
  435. if (IsSceneModified())
  436. {
  437. DialogBox.Open("Warning", "You current scene has modifications. Do you wish to save them first?",
  438. DialogBox.Type.YesNoCancel, dialogCallback);
  439. }
  440. else
  441. continueLoad(path);
  442. }
  443. /// <summary>
  444. /// Saves the currently loaded scene to the specified path.
  445. /// </summary>
  446. /// <param name="path">Path relative to the resource folder. This can be the path to the existing scene
  447. /// prefab if it just needs updating. </param>
  448. public static void SaveScene(string path)
  449. {
  450. Prefab scene = Internal_SaveScene(path);
  451. Scene.SetActive(scene);
  452. ProjectLibrary.Refresh(true);
  453. SetSceneDirty(false);
  454. }
  455. /// <summary>
  456. /// Checks does the folder at the provieded path contain a valid project.
  457. /// </summary>
  458. /// <param name="path">Absolute path to the root project folder.</param>
  459. /// <returns>True if the folder contains a valid project.</returns>
  460. public static bool IsValidProject(string path)
  461. {
  462. return Internal_IsValidProject(path);
  463. }
  464. /// <summary>
  465. /// Contains a new project in the provided folder.
  466. /// </summary>
  467. /// <param name="path">Absolute path to the folder to create the project in. Name of this folder will be used as the
  468. /// project's name.</param>
  469. public static void CreateProject(string path)
  470. {
  471. Internal_CreateProject(path);
  472. }
  473. /// <summary>
  474. /// Wrapper for menu items for <see cref="SaveScene(Action, Action)"/> method
  475. /// </summary>
  476. [MenuItem("File/Save Scene", ButtonModifier.Ctrl, ButtonCode.S, 10049)]
  477. [ToolbarItem("Save Scene", ToolbarIcon.SaveScene, "Save scene (Ctrl + S)", 1998)]
  478. private static void SaveSceneMenu()
  479. {
  480. SaveScene();
  481. }
  482. /// <summary>
  483. /// Wrapper for menu items for <see cref="SaveSceneAs(Action, Action)"/> method
  484. /// </summary>
  485. [MenuItem("File/Save Scene As", 10048)]
  486. private static void SaveSceneAsMenu()
  487. {
  488. SaveSceneAs();
  489. }
  490. /// <summary>
  491. /// Opens a Project Window allowing you to browse for or create a project.
  492. /// </summary>
  493. [MenuItem("File/Open Project", 10100)]
  494. [ToolbarItem("Open Project", ToolbarIcon.OpenProject, "Project manager", 2000)]
  495. public static void BrowseForProject()
  496. {
  497. ProjectWindow.Open();
  498. }
  499. /// <summary>
  500. /// Saves all data in the currently open project.
  501. /// </summary>
  502. [MenuItem("File/Save Project", 10099)]
  503. [ToolbarItem("Save Project", ToolbarIcon.SaveProject, "Save project", 1999)]
  504. public static void SaveProject()
  505. {
  506. foreach (var KVP in persistentData.dirtyResources)
  507. {
  508. string resourceUUID = KVP.Key;
  509. string path = ProjectLibrary.GetPath(resourceUUID);
  510. if (!IsNative(path))
  511. continue; // Native resources can't be changed
  512. Resource resource = ProjectLibrary.Load<Resource>(path);
  513. if(resource != null)
  514. ProjectLibrary.Save(resource);
  515. }
  516. persistentData.dirtyResources.Clear();
  517. SetStatusProject(false);
  518. Internal_SaveProject();
  519. }
  520. /// <summary>
  521. /// Loads the project at the specified path. This method executes asynchronously.
  522. /// </summary>
  523. /// <param name="path">Absolute path to the project's root folder.</param>
  524. public static void LoadProject(string path)
  525. {
  526. if (IsProjectLoaded && path == ProjectPath)
  527. return;
  528. if (!Internal_IsValidProject(path))
  529. {
  530. Debug.LogWarning("Provided path: \"" + path + "\" is not a valid project.");
  531. return;
  532. }
  533. if (IsProjectLoaded)
  534. UnloadProject();
  535. Internal_LoadProject(path); // Triggers Internal_OnProjectLoaded when done
  536. }
  537. /// <summary>
  538. /// Closes the editor.
  539. /// </summary>
  540. public static void Quit()
  541. {
  542. Internal_Quit();
  543. }
  544. /// <summary>
  545. /// Toggles an existing toolbar button into an on or off state which changes the visuals of the button.
  546. /// </summary>
  547. /// <param name="name">Name of the existing button to toggle</param>
  548. /// <param name="on">True to toggle on, false to toggle off (default)</param>
  549. public static void ToggleToolbarItem(string name, bool on)
  550. {
  551. Internal_ToggleToolbarItem(name, on);
  552. }
  553. /// <summary>
  554. /// Opens a file or a folder in the default external application.
  555. /// </summary>
  556. /// <param name="path">Absolute path to the file or folder to open.</param>
  557. public static void OpenExternally(string path)
  558. {
  559. Internal_OpenExternally(path);
  560. }
  561. /// <summary>
  562. /// Marks a resource as dirty so that it may be saved the next time the project is saved. Optionally you may also
  563. /// call <see cref="ProjectLibrary.Save"/> to save it immediately.
  564. /// </summary>
  565. /// <param name="resource">Resource to mark as dirty</param>
  566. public static void SetDirty(Resource resource)
  567. {
  568. if (resource == null)
  569. return;
  570. SetStatusProject(true);
  571. persistentData.dirtyResources[resource.UUID] = true;
  572. }
  573. /// <summary>
  574. /// Marks the current scene as dirty.
  575. /// </summary>
  576. public static void SetSceneDirty()
  577. {
  578. SetSceneDirty(true);
  579. }
  580. /// <summary>
  581. /// Marks the current scene as clean or dirty.
  582. /// </summary>
  583. /// <param name="dirty">Should the scene be marked as clean or dirty.</param>
  584. internal static void SetSceneDirty(bool dirty)
  585. {
  586. sceneDirty = dirty;
  587. SetStatusScene(Scene.ActiveSceneName, dirty);
  588. if (!dirty && Scene.ActiveSceneUUID != null)
  589. persistentData.dirtyResources.Remove(Scene.ActiveSceneUUID);
  590. }
  591. /// <summary>
  592. /// Checks is the specific resource dirty and needs saving.
  593. /// </summary>
  594. /// <param name="resource">Resource to check.</param>
  595. /// <returns>True if the resource requires saving, false otherwise.</returns>
  596. public static bool IsDirty(Resource resource)
  597. {
  598. return persistentData.dirtyResources.ContainsKey(resource.UUID);
  599. }
  600. /// <summary>
  601. /// Checks does the path represent a native resource.
  602. /// </summary>
  603. /// <param name="path">Filename or path to check.</param>
  604. /// <returns>True if the path represents a native resource.</returns>
  605. public static bool IsNative(string path)
  606. {
  607. string extension = Path.GetExtension(path);
  608. return extension == ".asset" || extension == ".prefab";
  609. }
  610. /// <summary>
  611. /// Unloads the currently loaded project. Offers the user a chance to save the current scene if it is modified.
  612. /// Automatically saves all project data before unloading.
  613. /// </summary>
  614. private static void UnloadProject()
  615. {
  616. Action continueUnload =
  617. () =>
  618. {
  619. Scene.Clear();
  620. if (monitor != null)
  621. {
  622. monitor.Destroy();
  623. monitor = null;
  624. }
  625. LibraryWindow window = EditorWindow.GetWindow<LibraryWindow>();
  626. if(window != null)
  627. window.Reset();
  628. SetSceneDirty(false);
  629. Internal_UnloadProject();
  630. SetStatusProject(false);
  631. };
  632. Action<DialogBox.ResultType> dialogCallback =
  633. (result) =>
  634. {
  635. if (result == DialogBox.ResultType.Yes)
  636. SaveScene();
  637. continueUnload();
  638. };
  639. if (IsSceneModified())
  640. {
  641. DialogBox.Open("Warning", "You current scene has modifications. Do you wish to save them first?",
  642. DialogBox.Type.YesNoCancel, dialogCallback);
  643. }
  644. else
  645. continueUnload();
  646. }
  647. /// <summary>
  648. /// Reloads all script assemblies in case they were modified. This action is delayed and will be executed
  649. /// at the beginning of the next frame.
  650. /// </summary>
  651. public static void ReloadAssemblies()
  652. {
  653. Internal_ReloadAssemblies();
  654. }
  655. /// <summary>
  656. /// Changes the scene displayed on the status bar.
  657. /// </summary>
  658. /// <param name="name">Name of the scene.</param>
  659. /// <param name="modified">Whether to display the scene as modified or not.</param>
  660. private static void SetStatusScene(string name, bool modified)
  661. {
  662. Internal_SetStatusScene(name, modified);
  663. }
  664. /// <summary>
  665. /// Changes the project state displayed on the status bar.
  666. /// </summary>
  667. /// <param name="modified">Whether to display the project as modified or not.</param>
  668. private static void SetStatusProject(bool modified)
  669. {
  670. Internal_SetStatusProject(modified);
  671. }
  672. /// <summary>
  673. /// Displays or hides the "compilation in progress" visual on the status bar.
  674. /// </summary>
  675. /// <param name="compiling">True to display the visual, false otherwise.</param>
  676. internal static void SetStatusCompiling(bool compiling)
  677. {
  678. Internal_SetStatusCompiling(compiling);
  679. }
  680. /// <summary>
  681. /// Checks did we make any modifications to the scene since it was last saved.
  682. /// </summary>
  683. /// <returns>True if the scene was never saved, or was modified after last save.</returns>
  684. public static bool IsSceneModified()
  685. {
  686. return sceneDirty;
  687. }
  688. /// <summary>
  689. /// Runs a single frame of the game and pauses it. If the game is not currently running it will be started.
  690. /// </summary>
  691. public static void FrameStep()
  692. {
  693. if (IsStopped)
  694. {
  695. if (EditorSettings.GetBool(LogWindow.CLEAR_ON_PLAY_KEY, true))
  696. {
  697. Debug.Clear();
  698. LogWindow log = EditorWindow.GetWindow<LogWindow>();
  699. if (log != null)
  700. log.Refresh();
  701. }
  702. }
  703. ToggleToolbarItem("Play", false);
  704. ToggleToolbarItem("Pause", true);
  705. Internal_FrameStep();
  706. }
  707. /// <summary>
  708. /// Executes any editor-specific unit tests. This should be called after a project is loaded if possible.
  709. /// </summary>
  710. private static void RunUnitTests()
  711. {
  712. #if DEBUG
  713. Internal_RunUnitTests();
  714. #endif
  715. }
  716. /// <summary>
  717. /// Triggered by the runtime when <see cref="LoadProject"/> method completes.
  718. /// </summary>
  719. private static void Internal_OnProjectLoaded()
  720. {
  721. SetStatusProject(false);
  722. if (!unitTestsExecuted)
  723. {
  724. RunUnitTests();
  725. unitTestsExecuted = true;
  726. }
  727. if (!IsProjectLoaded)
  728. {
  729. ProjectWindow.Open();
  730. return;
  731. }
  732. string projectPath = ProjectPath;
  733. RecentProject[] recentProjects = EditorSettings.RecentProjects;
  734. bool foundPath = false;
  735. for (int i = 0; i < recentProjects.Length; i++)
  736. {
  737. if (PathEx.Compare(recentProjects[i].path, projectPath))
  738. {
  739. recentProjects[i].accessTimestamp = (ulong)DateTime.Now.Ticks;
  740. EditorSettings.RecentProjects = recentProjects;
  741. foundPath = true;
  742. break;
  743. }
  744. }
  745. if (!foundPath)
  746. {
  747. List<RecentProject> extendedRecentProjects = new List<RecentProject>();
  748. extendedRecentProjects.AddRange(recentProjects);
  749. RecentProject newProject = new RecentProject();
  750. newProject.path = projectPath;
  751. newProject.accessTimestamp = (ulong)DateTime.Now.Ticks;
  752. extendedRecentProjects.Add(newProject);
  753. EditorSettings.RecentProjects = extendedRecentProjects.ToArray();
  754. }
  755. EditorSettings.LastOpenProject = projectPath;
  756. EditorSettings.Save();
  757. ProjectLibrary.Refresh();
  758. monitor = new FolderMonitor(ProjectLibrary.ResourceFolder);
  759. monitor.OnAdded += OnAssetModified;
  760. monitor.OnRemoved += OnAssetModified;
  761. monitor.OnModified += OnAssetModified;
  762. if (!string.IsNullOrWhiteSpace(ProjectSettings.LastOpenScene))
  763. {
  764. Scene.Load(ProjectSettings.LastOpenScene);
  765. SetSceneDirty(false);
  766. }
  767. }
  768. /// <summary>
  769. /// Triggered by the runtime when the user clicks on the status bar.
  770. /// </summary>
  771. private static void Internal_OnStatusBarClicked()
  772. {
  773. EditorWindow.OpenWindow<LogWindow>();
  774. }
  775. [MethodImpl(MethodImplOptions.InternalCall)]
  776. private static extern void Internal_SetStatusScene(string name, bool modified);
  777. [MethodImpl(MethodImplOptions.InternalCall)]
  778. private static extern void Internal_SetStatusProject(bool modified);
  779. [MethodImpl(MethodImplOptions.InternalCall)]
  780. private static extern void Internal_SetStatusCompiling(bool compiling);
  781. [MethodImpl(MethodImplOptions.InternalCall)]
  782. private static extern string Internal_GetProjectPath();
  783. [MethodImpl(MethodImplOptions.InternalCall)]
  784. private static extern string Internal_GetProjectName();
  785. [MethodImpl(MethodImplOptions.InternalCall)]
  786. private static extern bool Internal_GetProjectLoaded();
  787. [MethodImpl(MethodImplOptions.InternalCall)]
  788. private static extern string Internal_GetCompilerPath();
  789. [MethodImpl(MethodImplOptions.InternalCall)]
  790. private static extern string Internal_GetBuiltinReleaseAssemblyPath();
  791. [MethodImpl(MethodImplOptions.InternalCall)]
  792. private static extern string Internal_GetBuiltinDebugAssemblyPath();
  793. [MethodImpl(MethodImplOptions.InternalCall)]
  794. private static extern string Internal_GetScriptAssemblyPath();
  795. [MethodImpl(MethodImplOptions.InternalCall)]
  796. private static extern string Internal_GetFrameworkAssemblyPath();
  797. [MethodImpl(MethodImplOptions.InternalCall)]
  798. private static extern string Internal_GetEngineAssemblyName();
  799. [MethodImpl(MethodImplOptions.InternalCall)]
  800. private static extern string Internal_GetEditorAssemblyName();
  801. [MethodImpl(MethodImplOptions.InternalCall)]
  802. private static extern string Internal_GetScriptGameAssemblyName();
  803. [MethodImpl(MethodImplOptions.InternalCall)]
  804. private static extern string Internal_GetScriptEditorAssemblyName();
  805. [MethodImpl(MethodImplOptions.InternalCall)]
  806. private static extern Prefab Internal_SaveScene(string path);
  807. [MethodImpl(MethodImplOptions.InternalCall)]
  808. private static extern bool Internal_IsValidProject(string path);
  809. [MethodImpl(MethodImplOptions.InternalCall)]
  810. private static extern void Internal_SaveProject();
  811. [MethodImpl(MethodImplOptions.InternalCall)]
  812. private static extern void Internal_LoadProject(string path);
  813. [MethodImpl(MethodImplOptions.InternalCall)]
  814. private static extern void Internal_UnloadProject();
  815. [MethodImpl(MethodImplOptions.InternalCall)]
  816. private static extern void Internal_CreateProject(string path);
  817. [MethodImpl(MethodImplOptions.InternalCall)]
  818. private static extern void Internal_ReloadAssemblies();
  819. [MethodImpl(MethodImplOptions.InternalCall)]
  820. private static extern void Internal_OpenExternally(string path);
  821. [MethodImpl(MethodImplOptions.InternalCall)]
  822. private static extern void Internal_RunUnitTests();
  823. [MethodImpl(MethodImplOptions.InternalCall)]
  824. private static extern void Internal_Quit();
  825. [MethodImpl(MethodImplOptions.InternalCall)]
  826. private static extern void Internal_ToggleToolbarItem(string name, bool on);
  827. [MethodImpl(MethodImplOptions.InternalCall)]
  828. private static extern bool Internal_GetIsPlaying();
  829. [MethodImpl(MethodImplOptions.InternalCall)]
  830. private static extern void Internal_SetIsPlaying(bool value);
  831. [MethodImpl(MethodImplOptions.InternalCall)]
  832. private static extern bool Internal_GetIsPaused();
  833. [MethodImpl(MethodImplOptions.InternalCall)]
  834. private static extern void Internal_SetIsPaused(bool value);
  835. [MethodImpl(MethodImplOptions.InternalCall)]
  836. private static extern void Internal_FrameStep();
  837. [MethodImpl(MethodImplOptions.InternalCall)]
  838. private static extern void Internal_SetMainRenderTarget(IntPtr rendertarget);
  839. [MethodImpl(MethodImplOptions.InternalCall)]
  840. private static extern bool Internal_HasFocus();
  841. }
  842. }