EditorApplication.cs 42 KB

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