EditorApplication.cs 41 KB

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