2
0

EditorApplication.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  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. /** @addtogroup 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. /// <summary>
  51. /// Determines the active tool shown in the scene view.
  52. /// </summary>
  53. public static SceneViewTool ActiveSceneTool
  54. {
  55. get { return EditorSettings.ActiveSceneTool; }
  56. set { EditorSettings.ActiveSceneTool = value; }
  57. }
  58. /// <summary>
  59. /// Determines the coordinate mode used by the tools in the scene view.
  60. /// </summary>
  61. public static HandleCoordinateMode ActiveCoordinateMode
  62. {
  63. get { return EditorSettings.ActiveCoordinateMode; }
  64. set { EditorSettings.ActiveCoordinateMode = value; }
  65. }
  66. /// <summary>
  67. /// Determines the pivot mode used by the tools in the scene view.
  68. /// </summary>
  69. public static HandlePivotMode ActivePivotMode
  70. {
  71. get { return EditorSettings.ActivePivotMode; }
  72. set { EditorSettings.ActivePivotMode = value; }
  73. }
  74. /// <summary>
  75. /// Camera used for rendering the scene view.
  76. /// </summary>
  77. public static Camera SceneViewCamera
  78. {
  79. get { return EditorWindow.GetWindow<SceneWindow>().Camera; }
  80. }
  81. /// <summary>
  82. /// Absolute path to the folder containing the currently open project.
  83. /// </summary>
  84. public static string ProjectPath { get { return Internal_GetProjectPath(); } }
  85. /// <summary>
  86. /// Name of the currently open project.
  87. /// </summary>
  88. public static string ProjectName { get { return Internal_GetProjectName(); } }
  89. /// <summary>
  90. /// Checks is any project currently loaded.
  91. /// </summary>
  92. public static bool IsProjectLoaded { get { return Internal_GetProjectLoaded(); } }
  93. /// <summary>
  94. /// Determines is the game currently running in the editor, or is it stopped or paused. Setting this value to false
  95. /// will stop the game, but if you just want to pause it use <see cref="IsPaused"/> property.
  96. /// </summary>
  97. public static bool IsPlaying
  98. {
  99. get { return Internal_GetIsPlaying(); }
  100. set
  101. {
  102. ToggleToolbarItem("Play", value);
  103. ToggleToolbarItem("Pause", false);
  104. if (!value)
  105. Selection.SceneObject = null;
  106. else
  107. {
  108. if (EditorSettings.GetBool(LogWindow.CLEAR_ON_PLAY_KEY, true))
  109. {
  110. Debug.Clear();
  111. LogWindow log = EditorWindow.GetWindow<LogWindow>();
  112. if (log != null)
  113. log.Refresh();
  114. }
  115. }
  116. Internal_SetIsPlaying(value);
  117. }
  118. }
  119. /// <summary>
  120. /// Determines if the game is currently running in the editor, but paused. If the game is stopped and not running
  121. /// this will return false. If the game is not running and this is enabled, the game will start running but be
  122. /// immediately paused.
  123. /// </summary>
  124. public static bool IsPaused
  125. {
  126. get { return Internal_GetIsPaused(); }
  127. set
  128. {
  129. ToggleToolbarItem("Play", !value);
  130. ToggleToolbarItem("Pause", value);
  131. Internal_SetIsPaused(value);
  132. }
  133. }
  134. /// <summary>
  135. /// Returns true if the game is currently neither running nor paused. Use <see cref="IsPlaying"/> or
  136. /// <see cref="IsPaused"/> to actually change these states.
  137. /// </summary>
  138. public static bool IsStopped
  139. {
  140. get { return !IsPlaying && !IsPaused; }
  141. }
  142. /// <summary>
  143. /// Checks whether the editor currently has focus.
  144. /// </summary>
  145. public static bool HasFocus
  146. {
  147. get { return Internal_HasFocus(); }
  148. }
  149. /// <summary>
  150. /// Render target that the main camera in the scene (if any) will render its view to. This generally means the main
  151. /// game window when running standalone, or the Game viewport when running in editor.
  152. /// </summary>
  153. internal static RenderTarget MainRenderTarget
  154. {
  155. set
  156. {
  157. IntPtr rtPtr = IntPtr.Zero;
  158. if (value != null)
  159. rtPtr = value.GetCachedPtr();
  160. Internal_SetMainRenderTarget(rtPtr);
  161. }
  162. }
  163. /// <summary>
  164. /// Returns an object that can be used for storing data that persists throughout the entire editor session.
  165. /// </summary>
  166. internal static EditorPersistentData PersistentData
  167. {
  168. get { return persistentData; }
  169. }
  170. /// <summary>
  171. /// Returns the path where the script compiler is located at.
  172. /// </summary>
  173. internal static string CompilerPath { get { return Internal_GetCompilerPath(); } }
  174. /// <summary>
  175. /// Returns the path to the folder where the custom script assemblies are located at.
  176. /// </summary>
  177. internal static string ScriptAssemblyPath { get { return Internal_GetScriptAssemblyPath(); } }
  178. /// <summary>
  179. /// Returns the path to the folder where the .NET framework assemblies are located at.
  180. /// </summary>
  181. internal static string FrameworkAssemblyPath { get { return Internal_GetFrameworkAssemblyPath(); } }
  182. /// <summary>
  183. /// Name of the builtin assembly containing engine specific types.
  184. /// </summary>
  185. internal static string EngineAssemblyName { get { return Internal_GetEngineAssemblyName(); } }
  186. /// <summary>
  187. /// Name of the builtin assembly containing editor specific types.
  188. /// </summary>
  189. internal static string EditorAssemblyName { get { return Internal_GetEditorAssemblyName(); } }
  190. /// <summary>
  191. /// Name of the custom assembly compiled from non-editor scripts within the project.
  192. /// </summary>
  193. internal static string ScriptGameAssemblyName { get { return Internal_GetScriptGameAssemblyName(); } }
  194. /// <summary>
  195. /// Name of the custom assembly compiled from editor scripts within the project.
  196. /// </summary>
  197. internal static string ScriptEditorAssemblyName { get { return Internal_GetScriptEditorAssemblyName(); } }
  198. /// <summary>
  199. /// Returns the path to the folder where the builtin release script assemblies are located at.
  200. /// </summary>
  201. internal static string BuiltinReleaseAssemblyPath { get { return Internal_GetBuiltinReleaseAssemblyPath(); } }
  202. /// <summary>
  203. /// Returns the path to the folder where the builtin debug script assemblies are located at.
  204. /// </summary>
  205. internal static string BuiltinDebugAssemblyPath { get { return Internal_GetBuiltinDebugAssemblyPath(); } }
  206. internal static VirtualButton CutKey = new VirtualButton(CutBinding);
  207. internal static VirtualButton CopyKey = new VirtualButton(CopyBinding);
  208. internal static VirtualButton PasteKey = new VirtualButton(PasteBinding);
  209. internal static VirtualButton RenameKey = new VirtualButton(RenameBinding);
  210. internal static VirtualButton DuplicateKey = new VirtualButton(DuplicateBinding);
  211. internal static VirtualButton DeleteKey = new VirtualButton(DeleteBinding);
  212. private static EditorApplication instance;
  213. private static FolderMonitor monitor;
  214. private static ScriptCodeManager codeManager;
  215. private static bool sceneDirty;
  216. private static bool unitTestsExecuted;
  217. private static EditorPersistentData persistentData;
  218. /// <summary>
  219. /// Constructs a new editor application. Called at editor start-up by the runtime, and any time assembly refresh
  220. /// occurrs.
  221. /// </summary>
  222. internal EditorApplication()
  223. {
  224. instance = this;
  225. codeManager = new ScriptCodeManager();
  226. const string soName = "EditorPersistentData";
  227. SceneObject so = Scene.Root.FindChild(soName);
  228. if (so == null)
  229. so = new SceneObject(soName, true);
  230. persistentData = so.GetComponent<EditorPersistentData>();
  231. if (persistentData == null)
  232. persistentData = so.AddComponent<EditorPersistentData>();
  233. // Register controls
  234. InputConfiguration inputConfig = VirtualInput.KeyConfig;
  235. inputConfig.RegisterButton(SceneCamera.MoveForwardBinding, ButtonCode.W);
  236. inputConfig.RegisterButton(SceneCamera.MoveBackBinding, ButtonCode.S);
  237. inputConfig.RegisterButton(SceneCamera.MoveLeftBinding, ButtonCode.A);
  238. inputConfig.RegisterButton(SceneCamera.MoveRightBinding, ButtonCode.D);
  239. inputConfig.RegisterButton(SceneCamera.MoveUpBinding, ButtonCode.E);
  240. inputConfig.RegisterButton(SceneCamera.MoveDownBinding, ButtonCode.Q);
  241. inputConfig.RegisterButton(SceneCamera.MoveForwardBinding, ButtonCode.Up);
  242. inputConfig.RegisterButton(SceneCamera.MoveBackBinding, ButtonCode.Down);
  243. inputConfig.RegisterButton(SceneCamera.MoveLeftBinding, ButtonCode.Left);
  244. inputConfig.RegisterButton(SceneCamera.MoveRightBinding, ButtonCode.Right);
  245. inputConfig.RegisterButton(SceneCamera.FastMoveBinding, ButtonCode.LeftShift);
  246. inputConfig.RegisterButton(SceneCamera.RotateBinding, ButtonCode.MouseRight);
  247. inputConfig.RegisterButton(SceneCamera.PanBinding, ButtonCode.MouseMiddle);
  248. inputConfig.RegisterAxis(SceneCamera.HorizontalAxisBinding, InputAxis.MouseX);
  249. inputConfig.RegisterAxis(SceneCamera.VerticalAxisBinding, InputAxis.MouseY);
  250. inputConfig.RegisterAxis(SceneCamera.ScrollAxisBinding, InputAxis.MouseZ);
  251. inputConfig.RegisterButton(SceneWindow.ToggleProfilerOverlayBinding, ButtonCode.P, ButtonModifier.CtrlAlt);
  252. inputConfig.RegisterButton(SceneWindow.ViewToolBinding, ButtonCode.Q);
  253. inputConfig.RegisterButton(SceneWindow.FrameBinding, ButtonCode.F);
  254. inputConfig.RegisterButton(SceneWindow.MoveToolBinding, ButtonCode.W);
  255. inputConfig.RegisterButton(SceneWindow.RotateToolBinding, ButtonCode.E);
  256. inputConfig.RegisterButton(SceneWindow.ScaleToolBinding, ButtonCode.R);
  257. inputConfig.RegisterButton(CutBinding, ButtonCode.X, ButtonModifier.Ctrl);
  258. inputConfig.RegisterButton(CopyBinding, ButtonCode.C, ButtonModifier.Ctrl);
  259. inputConfig.RegisterButton(PasteBinding, ButtonCode.V, ButtonModifier.Ctrl);
  260. inputConfig.RegisterButton(DuplicateBinding, ButtonCode.D, ButtonModifier.Ctrl);
  261. inputConfig.RegisterButton(DeleteBinding, ButtonCode.Delete);
  262. inputConfig.RegisterButton(RenameBinding, ButtonCode.F2);
  263. if (IsProjectLoaded)
  264. {
  265. monitor = new FolderMonitor(ProjectLibrary.ResourceFolder);
  266. monitor.OnAdded += OnAssetModified;
  267. monitor.OnRemoved += OnAssetModified;
  268. monitor.OnModified += OnAssetModified;
  269. }
  270. }
  271. /// <summary>
  272. /// Triggered when the folder monitor detects an asset in the monitored folder was modified.
  273. /// </summary>
  274. /// <param name="path">Path to the modified file or folder.</param>
  275. private static void OnAssetModified(string path)
  276. {
  277. ProjectLibrary.Refresh(path);
  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. if (Scene.IsGenericPrefab)
  373. {
  374. SaveGenericPrefab(onSuccess, onFailure);
  375. }
  376. else
  377. {
  378. SaveScene(scenePath);
  379. if (onSuccess != null)
  380. onSuccess();
  381. }
  382. }
  383. else
  384. SaveSceneAs(onSuccess, onFailure);
  385. }
  386. else
  387. SaveSceneAs(onSuccess, onFailure);
  388. }
  389. /// <summary>
  390. /// Opens a dialog to allows the user to select a location where to save the current scene.
  391. /// </summary>
  392. public static void SaveSceneAs(Action onSuccess = null, Action onFailure = null)
  393. {
  394. string scenePath = "";
  395. if (BrowseDialog.SaveFile(ProjectLibrary.ResourceFolder, "*.prefab", out scenePath))
  396. {
  397. if (!PathEx.IsPartOf(scenePath, ProjectLibrary.ResourceFolder))
  398. {
  399. DialogBox.Open("Error", "The location must be inside the Resources folder of the project.",
  400. DialogBox.Type.OK,
  401. x =>
  402. {
  403. if (onFailure != null)
  404. onFailure();
  405. });
  406. }
  407. else
  408. {
  409. // TODO - If path points to an existing non-scene asset or folder I should delete it otherwise
  410. // Internal_SaveScene will silently fail.
  411. scenePath = Path.ChangeExtension(scenePath, ".prefab");
  412. SaveScene(scenePath);
  413. }
  414. }
  415. else
  416. {
  417. // User canceled, so technically a success
  418. if (onSuccess != null)
  419. onSuccess();
  420. }
  421. }
  422. /// <summary>
  423. /// Loads a prefab as the current scene at the specified path. If current scene is modified the user is offered a
  424. /// chance to save it.
  425. /// </summary>
  426. /// <param name="path">Path to a valid prefab relative to the resource folder. If path is empty a brand new
  427. /// scene will be loaded.</param>
  428. public static void LoadScene(string path)
  429. {
  430. Action<string> continueLoad =
  431. (scenePath) =>
  432. {
  433. if (string.IsNullOrEmpty(path))
  434. Scene.Clear();
  435. else
  436. Scene.Load(path);
  437. SetSceneDirty(false);
  438. ProjectSettings.LastOpenScene = scenePath;
  439. ProjectSettings.Save();
  440. };
  441. Action<DialogBox.ResultType> dialogCallback =
  442. (result) =>
  443. {
  444. if (result == DialogBox.ResultType.Yes)
  445. {
  446. SaveScene();
  447. continueLoad(path);
  448. }
  449. else if (result == DialogBox.ResultType.No)
  450. continueLoad(path);
  451. };
  452. if (IsSceneModified())
  453. {
  454. DialogBox.Open("Warning", "You current scene has modifications. Do you wish to save them first?",
  455. DialogBox.Type.YesNoCancel, dialogCallback);
  456. }
  457. else
  458. continueLoad(path);
  459. }
  460. /// <summary>
  461. /// Saves the currently loaded scene to the specified path.
  462. /// </summary>
  463. /// <param name="path">Path relative to the resource folder. This can be the path to the existing scene
  464. /// prefab if it just needs updating. </param>
  465. internal static void SaveScene(string path)
  466. {
  467. Prefab scene = Internal_SaveScene(path);
  468. Scene.SetActive(scene);
  469. ProjectLibrary.Refresh(true);
  470. SetSceneDirty(false);
  471. }
  472. /// <summary>
  473. /// Attempts to save the current scene by applying the changes to a prefab, instead of saving it as a brand new
  474. /// scene. This is necessary for generic prefabs that have don't have a scene root included in the prefab. If the
  475. /// object added any other objects to the root, or has moved or deleted the original generic prefab the user
  476. /// will be asked to save the scene normally, creating a brand new prefab.
  477. /// </summary>
  478. private static void SaveGenericPrefab(Action onSuccess = null, Action onFailure = null)
  479. {
  480. // Find prefab root
  481. SceneObject root = null;
  482. int numChildren = Scene.Root.GetNumChildren();
  483. int numNormalChildren = 0;
  484. for (int i = 0; i < numChildren; i++)
  485. {
  486. SceneObject child = Scene.Root.GetChild(i);
  487. if (EditorUtility.IsInternal(child))
  488. continue;
  489. string prefabUUID = PrefabUtility.GetPrefabUUID(child);
  490. if (prefabUUID == Scene.ActiveSceneUUID)
  491. root = child;
  492. // If user added any other prefabs other than the initial one, the scene no longer represents a generic
  493. // prefab (as we can now longer save it by applying changes only to that prefab)
  494. numNormalChildren++;
  495. if (numNormalChildren > 1)
  496. {
  497. root = null;
  498. break;
  499. }
  500. }
  501. if (root != null)
  502. {
  503. PrefabUtility.ApplyPrefab(root, false);
  504. ProjectLibrary.Refresh(true);
  505. SetSceneDirty(false);
  506. if (onSuccess != null)
  507. onSuccess();
  508. }
  509. else
  510. {
  511. SaveSceneAs(onSuccess, onFailure);
  512. }
  513. }
  514. /// <summary>
  515. /// Checks does the folder at the provieded path contain a valid project.
  516. /// </summary>
  517. /// <param name="path">Absolute path to the root project folder.</param>
  518. /// <returns>True if the folder contains a valid project.</returns>
  519. public static bool IsValidProject(string path)
  520. {
  521. return Internal_IsValidProject(path);
  522. }
  523. /// <summary>
  524. /// Contains a new project in the provided folder.
  525. /// </summary>
  526. /// <param name="path">Absolute path to the folder to create the project in. Name of this folder will be used as the
  527. /// project's name.</param>
  528. public static void CreateProject(string path)
  529. {
  530. Internal_CreateProject(path);
  531. }
  532. /// <summary>
  533. /// Wrapper for menu items for <see cref="SaveScene(Action, Action)"/> method
  534. /// </summary>
  535. [MenuItem("File/Save Scene", ButtonModifier.Ctrl, ButtonCode.S, 10049)]
  536. [ToolbarItem("Save Scene", ToolbarIcon.SaveScene, "Save scene (Ctrl + S)", 1998)]
  537. private static void SaveSceneMenu()
  538. {
  539. SaveScene();
  540. }
  541. /// <summary>
  542. /// Wrapper for menu items for <see cref="SaveSceneAs(Action, Action)"/> method
  543. /// </summary>
  544. [MenuItem("File/Save Scene As", 10048)]
  545. private static void SaveSceneAsMenu()
  546. {
  547. SaveSceneAs();
  548. }
  549. /// <summary>
  550. /// Opens a Project Window allowing you to browse for or create a project.
  551. /// </summary>
  552. [MenuItem("File/Open Project", 10100)]
  553. [ToolbarItem("Open Project", ToolbarIcon.OpenProject, "Project manager", 2000)]
  554. public static void BrowseForProject()
  555. {
  556. ProjectWindow.Open();
  557. }
  558. /// <summary>
  559. /// Saves all data in the currently open project.
  560. /// </summary>
  561. [MenuItem("File/Save Project", 10099)]
  562. [ToolbarItem("Save Project", ToolbarIcon.SaveProject, "Save project", 1999)]
  563. public static void SaveProject()
  564. {
  565. // Apply changes to any animation clips edited using the animation editor
  566. foreach (var KVP in persistentData.dirtyAnimClips)
  567. KVP.Value.SaveToClip();
  568. // Save all dirty resources to disk
  569. foreach (var KVP in persistentData.dirtyResources)
  570. {
  571. string resourceUUID = KVP.Key;
  572. string path = ProjectLibrary.GetPath(resourceUUID);
  573. if (!IsNative(path))
  574. continue; // Imported resources can't be changed
  575. Resource resource = ProjectLibrary.Load<Resource>(path);
  576. if(resource != null)
  577. ProjectLibrary.Save(resource);
  578. }
  579. persistentData.dirtyAnimClips.Clear();
  580. persistentData.dirtyResources.Clear();
  581. SetStatusProject(false);
  582. Internal_SaveProject();
  583. }
  584. /// <summary>
  585. /// Loads the project at the specified path. This method executes asynchronously.
  586. /// </summary>
  587. /// <param name="path">Absolute path to the project's root folder.</param>
  588. public static void LoadProject(string path)
  589. {
  590. if (IsProjectLoaded && path == ProjectPath)
  591. return;
  592. if (!Internal_IsValidProject(path))
  593. {
  594. Debug.LogWarning("Provided path: \"" + path + "\" is not a valid project.");
  595. return;
  596. }
  597. if (IsProjectLoaded)
  598. UnloadProject();
  599. Internal_LoadProject(path); // Triggers Internal_OnProjectLoaded when done
  600. }
  601. /// <summary>
  602. /// Closes the editor.
  603. /// </summary>
  604. public static void Quit()
  605. {
  606. Internal_Quit();
  607. }
  608. /// <summary>
  609. /// Toggles an existing toolbar button into an on or off state which changes the visuals of the button.
  610. /// </summary>
  611. /// <param name="name">Name of the existing button to toggle</param>
  612. /// <param name="on">True to toggle on, false to toggle off (default)</param>
  613. public static void ToggleToolbarItem(string name, bool on)
  614. {
  615. Internal_ToggleToolbarItem(name, on);
  616. }
  617. /// <summary>
  618. /// Opens a file or a folder in the default external application.
  619. /// </summary>
  620. /// <param name="path">Absolute path to the file or folder to open.</param>
  621. public static void OpenExternally(string path)
  622. {
  623. Internal_OpenExternally(path);
  624. }
  625. /// <summary>
  626. /// Marks a resource as dirty so that it may be saved the next time the project is saved. Optionally you may also
  627. /// call <see cref="ProjectLibrary.Save"/> to save it immediately.
  628. /// </summary>
  629. /// <param name="resource">Resource to mark as dirty</param>
  630. public static void SetDirty(Resource resource)
  631. {
  632. if (resource == null)
  633. return;
  634. SetStatusProject(true);
  635. persistentData.dirtyResources[resource.UUID] = true;
  636. }
  637. /// <summary>
  638. /// Marks the current project dirty (requires saving in order for changes not to be lost).
  639. /// </summary>
  640. public static void SetProjectDirty()
  641. {
  642. SetStatusProject(true);
  643. }
  644. /// <summary>
  645. /// Marks the current scene as dirty.
  646. /// </summary>
  647. public static void SetSceneDirty()
  648. {
  649. SetSceneDirty(true);
  650. }
  651. /// <summary>
  652. /// Marks the current scene as clean or dirty.
  653. /// </summary>
  654. /// <param name="dirty">Should the scene be marked as clean or dirty.</param>
  655. internal static void SetSceneDirty(bool dirty)
  656. {
  657. sceneDirty = dirty;
  658. SetStatusScene(Scene.ActiveSceneName, dirty);
  659. if (!dirty && Scene.ActiveSceneUUID != null)
  660. persistentData.dirtyResources.Remove(Scene.ActiveSceneUUID);
  661. }
  662. /// <summary>
  663. /// Checks is the specific resource dirty and needs saving.
  664. /// </summary>
  665. /// <param name="resource">Resource to check.</param>
  666. /// <returns>True if the resource requires saving, false otherwise.</returns>
  667. public static bool IsDirty(Resource resource)
  668. {
  669. return persistentData.dirtyResources.ContainsKey(resource.UUID);
  670. }
  671. /// <summary>
  672. /// Checks does the path represent a native resource.
  673. /// </summary>
  674. /// <param name="path">Filename or path to check.</param>
  675. /// <returns>True if the path represents a native resource.</returns>
  676. public static bool IsNative(string path)
  677. {
  678. string extension = Path.GetExtension(path);
  679. return extension == ".asset" || extension == ".prefab";
  680. }
  681. /// <summary>
  682. /// Unloads the currently loaded project. Offers the user a chance to save the current scene if it is modified.
  683. /// Automatically saves all project data before unloading.
  684. /// </summary>
  685. private static void UnloadProject()
  686. {
  687. Action continueUnload =
  688. () =>
  689. {
  690. Scene.Clear();
  691. if (monitor != null)
  692. {
  693. monitor.Destroy();
  694. monitor = null;
  695. }
  696. LibraryWindow window = EditorWindow.GetWindow<LibraryWindow>();
  697. if(window != null)
  698. window.Reset();
  699. SetSceneDirty(false);
  700. Internal_UnloadProject();
  701. SetStatusProject(false);
  702. };
  703. Action<DialogBox.ResultType> dialogCallback =
  704. (result) =>
  705. {
  706. if (result == DialogBox.ResultType.Yes)
  707. SaveScene();
  708. continueUnload();
  709. };
  710. if (IsSceneModified())
  711. {
  712. DialogBox.Open("Warning", "You current scene has modifications. Do you wish to save them first?",
  713. DialogBox.Type.YesNoCancel, dialogCallback);
  714. }
  715. else
  716. continueUnload();
  717. }
  718. /// <summary>
  719. /// Reloads all script assemblies in case they were modified. This action is delayed and will be executed
  720. /// at the beginning of the next frame.
  721. /// </summary>
  722. public static void ReloadAssemblies()
  723. {
  724. Internal_ReloadAssemblies();
  725. }
  726. /// <summary>
  727. /// Changes the scene displayed on the status bar.
  728. /// </summary>
  729. /// <param name="name">Name of the scene.</param>
  730. /// <param name="modified">Whether to display the scene as modified or not.</param>
  731. private static void SetStatusScene(string name, bool modified)
  732. {
  733. Internal_SetStatusScene(name, modified);
  734. }
  735. /// <summary>
  736. /// Changes the project state displayed on the status bar.
  737. /// </summary>
  738. /// <param name="modified">Whether to display the project as modified or not.</param>
  739. private static void SetStatusProject(bool modified)
  740. {
  741. Internal_SetStatusProject(modified);
  742. }
  743. /// <summary>
  744. /// Displays or hides the "compilation in progress" visual on the status bar.
  745. /// </summary>
  746. /// <param name="compiling">True to display the visual, false otherwise.</param>
  747. internal static void SetStatusCompiling(bool compiling)
  748. {
  749. Internal_SetStatusCompiling(compiling);
  750. }
  751. /// <summary>
  752. /// Checks did we make any modifications to the scene since it was last saved.
  753. /// </summary>
  754. /// <returns>True if the scene was never saved, or was modified after last save.</returns>
  755. public static bool IsSceneModified()
  756. {
  757. return sceneDirty;
  758. }
  759. /// <summary>
  760. /// Runs a single frame of the game and pauses it. If the game is not currently running it will be started.
  761. /// </summary>
  762. public static void FrameStep()
  763. {
  764. if (IsStopped)
  765. {
  766. if (EditorSettings.GetBool(LogWindow.CLEAR_ON_PLAY_KEY, true))
  767. {
  768. Debug.Clear();
  769. LogWindow log = EditorWindow.GetWindow<LogWindow>();
  770. if (log != null)
  771. log.Refresh();
  772. }
  773. }
  774. ToggleToolbarItem("Play", false);
  775. ToggleToolbarItem("Pause", true);
  776. Internal_FrameStep();
  777. }
  778. /// <summary>
  779. /// Executes any editor-specific unit tests. This should be called after a project is loaded if possible.
  780. /// </summary>
  781. private static void RunUnitTests()
  782. {
  783. #if DEBUG
  784. Internal_RunUnitTests();
  785. #endif
  786. }
  787. /// <summary>
  788. /// Triggered by the runtime when <see cref="LoadProject"/> method completes.
  789. /// </summary>
  790. private static void Internal_OnProjectLoaded()
  791. {
  792. SetStatusProject(false);
  793. if (!unitTestsExecuted)
  794. {
  795. RunUnitTests();
  796. unitTestsExecuted = true;
  797. }
  798. if (!IsProjectLoaded)
  799. {
  800. ProjectWindow.Open();
  801. return;
  802. }
  803. string projectPath = ProjectPath;
  804. RecentProject[] recentProjects = EditorSettings.RecentProjects;
  805. bool foundPath = false;
  806. for (int i = 0; i < recentProjects.Length; i++)
  807. {
  808. if (PathEx.Compare(recentProjects[i].path, projectPath))
  809. {
  810. recentProjects[i].accessTimestamp = (ulong)DateTime.Now.Ticks;
  811. EditorSettings.RecentProjects = recentProjects;
  812. foundPath = true;
  813. break;
  814. }
  815. }
  816. if (!foundPath)
  817. {
  818. List<RecentProject> extendedRecentProjects = new List<RecentProject>();
  819. extendedRecentProjects.AddRange(recentProjects);
  820. RecentProject newProject = new RecentProject();
  821. newProject.path = projectPath;
  822. newProject.accessTimestamp = (ulong)DateTime.Now.Ticks;
  823. extendedRecentProjects.Add(newProject);
  824. EditorSettings.RecentProjects = extendedRecentProjects.ToArray();
  825. }
  826. EditorSettings.LastOpenProject = projectPath;
  827. EditorSettings.Save();
  828. ProjectLibrary.Refresh();
  829. monitor = new FolderMonitor(ProjectLibrary.ResourceFolder);
  830. monitor.OnAdded += OnAssetModified;
  831. monitor.OnRemoved += OnAssetModified;
  832. monitor.OnModified += OnAssetModified;
  833. if (!string.IsNullOrWhiteSpace(ProjectSettings.LastOpenScene))
  834. {
  835. Scene.Load(ProjectSettings.LastOpenScene);
  836. SetSceneDirty(false);
  837. }
  838. }
  839. /// <summary>
  840. /// Triggered by the runtime when the user clicks on the status bar.
  841. /// </summary>
  842. private static void Internal_OnStatusBarClicked()
  843. {
  844. EditorWindow.OpenWindow<LogWindow>();
  845. }
  846. [MethodImpl(MethodImplOptions.InternalCall)]
  847. private static extern void Internal_SetStatusScene(string name, bool modified);
  848. [MethodImpl(MethodImplOptions.InternalCall)]
  849. private static extern void Internal_SetStatusProject(bool modified);
  850. [MethodImpl(MethodImplOptions.InternalCall)]
  851. private static extern void Internal_SetStatusCompiling(bool compiling);
  852. [MethodImpl(MethodImplOptions.InternalCall)]
  853. private static extern string Internal_GetProjectPath();
  854. [MethodImpl(MethodImplOptions.InternalCall)]
  855. private static extern string Internal_GetProjectName();
  856. [MethodImpl(MethodImplOptions.InternalCall)]
  857. private static extern bool Internal_GetProjectLoaded();
  858. [MethodImpl(MethodImplOptions.InternalCall)]
  859. private static extern string Internal_GetCompilerPath();
  860. [MethodImpl(MethodImplOptions.InternalCall)]
  861. private static extern string Internal_GetBuiltinReleaseAssemblyPath();
  862. [MethodImpl(MethodImplOptions.InternalCall)]
  863. private static extern string Internal_GetBuiltinDebugAssemblyPath();
  864. [MethodImpl(MethodImplOptions.InternalCall)]
  865. private static extern string Internal_GetScriptAssemblyPath();
  866. [MethodImpl(MethodImplOptions.InternalCall)]
  867. private static extern string Internal_GetFrameworkAssemblyPath();
  868. [MethodImpl(MethodImplOptions.InternalCall)]
  869. private static extern string Internal_GetEngineAssemblyName();
  870. [MethodImpl(MethodImplOptions.InternalCall)]
  871. private static extern string Internal_GetEditorAssemblyName();
  872. [MethodImpl(MethodImplOptions.InternalCall)]
  873. private static extern string Internal_GetScriptGameAssemblyName();
  874. [MethodImpl(MethodImplOptions.InternalCall)]
  875. private static extern string Internal_GetScriptEditorAssemblyName();
  876. [MethodImpl(MethodImplOptions.InternalCall)]
  877. private static extern Prefab Internal_SaveScene(string path);
  878. [MethodImpl(MethodImplOptions.InternalCall)]
  879. private static extern bool Internal_IsValidProject(string path);
  880. [MethodImpl(MethodImplOptions.InternalCall)]
  881. private static extern void Internal_SaveProject();
  882. [MethodImpl(MethodImplOptions.InternalCall)]
  883. private static extern void Internal_LoadProject(string path);
  884. [MethodImpl(MethodImplOptions.InternalCall)]
  885. private static extern void Internal_UnloadProject();
  886. [MethodImpl(MethodImplOptions.InternalCall)]
  887. private static extern void Internal_CreateProject(string path);
  888. [MethodImpl(MethodImplOptions.InternalCall)]
  889. private static extern void Internal_ReloadAssemblies();
  890. [MethodImpl(MethodImplOptions.InternalCall)]
  891. private static extern void Internal_OpenExternally(string path);
  892. [MethodImpl(MethodImplOptions.InternalCall)]
  893. private static extern void Internal_RunUnitTests();
  894. [MethodImpl(MethodImplOptions.InternalCall)]
  895. private static extern void Internal_Quit();
  896. [MethodImpl(MethodImplOptions.InternalCall)]
  897. private static extern void Internal_ToggleToolbarItem(string name, bool on);
  898. [MethodImpl(MethodImplOptions.InternalCall)]
  899. private static extern bool Internal_GetIsPlaying();
  900. [MethodImpl(MethodImplOptions.InternalCall)]
  901. private static extern void Internal_SetIsPlaying(bool value);
  902. [MethodImpl(MethodImplOptions.InternalCall)]
  903. private static extern bool Internal_GetIsPaused();
  904. [MethodImpl(MethodImplOptions.InternalCall)]
  905. private static extern void Internal_SetIsPaused(bool value);
  906. [MethodImpl(MethodImplOptions.InternalCall)]
  907. private static extern void Internal_FrameStep();
  908. [MethodImpl(MethodImplOptions.InternalCall)]
  909. private static extern void Internal_SetMainRenderTarget(IntPtr rendertarget);
  910. [MethodImpl(MethodImplOptions.InternalCall)]
  911. private static extern bool Internal_HasFocus();
  912. }
  913. /** @} */
  914. }