EditorApplication.cs 40 KB

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