SceneWindow.cs 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using bs;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. namespace bs.Editor
  8. {
  9. /** @addtogroup Scene-Editor
  10. * @{
  11. */
  12. /// <summary>
  13. /// Displays the scene view camera and various scene controls.
  14. /// </summary>
  15. internal sealed class SceneWindow : EditorWindow, IGlobalShortcuts
  16. {
  17. internal const string GizmoDrawSettingsKey = "SceneCamera0_GizmoDrawSettings";
  18. internal const string ToggleProfilerOverlayBinding = "ToggleProfilerOverlay";
  19. internal const string ViewToolBinding = "ViewTool";
  20. internal const string MoveToolBinding = "MoveTool";
  21. internal const string RotateToolBinding = "RotateTool";
  22. internal const string ScaleToolBinding = "ScaleTool";
  23. internal const string FrameBinding = "SceneFrame";
  24. private const string CameraPositionKey = "SceneCamera0_Position";
  25. private const string CameraRotationKey = "SceneCamera0_Rotation";
  26. private const int HeaderHeight = 20;
  27. private const float DefaultPlacementDepth = 5.0f;
  28. private static readonly Color ClearColor = new Color(0.0f, 0.3685f, 0.7969f);
  29. private const int HandleAxesGUISize = 50;
  30. private const int HandleAxesGUIPaddingX = 10;
  31. private const int HandleAxesGUIPaddingY = 5;
  32. private Camera camera;
  33. private SceneCamera sceneCamera;
  34. private RenderTexture renderTexture;
  35. private GUILayoutY mainLayout;
  36. private GUIPanel rtPanel;
  37. private GUIPanel sceneAxesPanel;
  38. private GUIButton focusCatcher;
  39. private GUIRenderTexture renderTextureGUI;
  40. private SceneGrid sceneGrid;
  41. private SceneSelection sceneSelection;
  42. private SceneGizmos sceneGizmos;
  43. private SceneHandles sceneHandles;
  44. private GUIToggle viewButton;
  45. private GUIToggle moveButton;
  46. private GUIToggle rotateButton;
  47. private GUIToggle scaleButton;
  48. private GUIToggle localCoordButton;
  49. private GUIToggle worldCoordButton;
  50. private GUIToggle pivotButton;
  51. private GUIToggle centerButton;
  52. private GUIToggle moveSnapButton;
  53. private GUIFloatField moveSnapInput;
  54. private GUIToggle rotateSnapButton;
  55. private GUIFloatField rotateSnapInput;
  56. private GUIButton cameraOptionsButton;
  57. private GUILayout progressLayout;
  58. private GUIProgressBar loadProgressBar;
  59. private GUILabel loadLabel;
  60. private SceneAxesGUI sceneAxesGUI;
  61. private ProjectionType sceneAxesLastProjectionType;
  62. private bool hasContentFocus = false;
  63. private bool HasContentFocus { get { return HasFocus && hasContentFocus; } }
  64. private bool loadingProgressShown = false;
  65. private bool AllowViewportInput { get { return !loadingProgressShown; } }
  66. private int editorSettingsHash = int.MaxValue;
  67. private GizmoDrawSettings gizmoDrawSettings = GizmoDrawSettings.Default();
  68. private VirtualButton frameKey;
  69. // Tool shortcuts
  70. private VirtualButton viewToolKey;
  71. private VirtualButton moveToolKey;
  72. private VirtualButton rotateToolKey;
  73. private VirtualButton scaleToolKey;
  74. // Drag & drop
  75. private bool dragActive;
  76. private SceneObject draggedSO;
  77. private Vector3 draggedSOOffset;
  78. private GUITexture dragSelection;
  79. private bool isDraggingSelection;
  80. private Vector2I dragSelectionStart;
  81. private Vector2I dragSelectionEnd;
  82. private Vector2I mouseDownPosition;
  83. private GUIPanel selectionPanel;
  84. // Camera previews
  85. private const int MaxCameraPreviews = 0; // Disabled until we resolve issues with adding temporary camera copies
  86. private List<CameraPreview> cameraPreviews = new List<CameraPreview>();
  87. private GUIPanel cameraPreviewsPanel;
  88. /// <summary>
  89. /// Returns the scene camera.
  90. /// </summary>
  91. public SceneCamera Camera => sceneCamera;
  92. /// <summary>
  93. /// Settings that control gizmo drawing.
  94. /// </summary>
  95. public GizmoDrawSettings GizmoDrawSettings
  96. {
  97. get => gizmoDrawSettings;
  98. set
  99. {
  100. gizmoDrawSettings = value;
  101. if(sceneGizmos != null)
  102. sceneGizmos.DrawSettings = gizmoDrawSettings;
  103. if(sceneSelection != null)
  104. sceneSelection.GizmoDrawSettings = gizmoDrawSettings;
  105. }
  106. }
  107. /// <summary>
  108. /// Constructs a new scene window.
  109. /// </summary>
  110. internal SceneWindow()
  111. { }
  112. /// <summary>
  113. /// Opens a scene window if its not open already.
  114. /// </summary>
  115. [MenuItem("Windows/Scene", ButtonModifier.CtrlAlt, ButtonCode.S, 6000)]
  116. private static void OpenSceneWindow()
  117. {
  118. OpenWindow<SceneWindow>();
  119. }
  120. /// <summary>
  121. /// Focuses on the currently selected object.
  122. /// </summary>
  123. [MenuItem("Tools/Frame Selected", ButtonModifier.None, ButtonCode.F, 9275, true)]
  124. private static void OpenSettingsWindow()
  125. {
  126. SceneWindow window = GetWindow<SceneWindow>();
  127. if (window != null)
  128. window.sceneCamera.FrameSelected();
  129. }
  130. /// <summary>
  131. /// Switches the active tool to the view tool.
  132. /// </summary>
  133. [MenuItem("Tools/View", ButtonModifier.Ctrl, ButtonCode.Q, 9274, true)]
  134. private static void SetViewTool()
  135. {
  136. SceneWindow window = GetWindow<SceneWindow>();
  137. if (window != null)
  138. window.OnSceneToolButtonClicked(SceneViewTool.View);
  139. }
  140. /// <summary>
  141. /// Switches the active tool to the move tool.
  142. /// </summary>
  143. [MenuItem("Tools/Move", ButtonModifier.Ctrl, ButtonCode.W, 9273)]
  144. private static void SetMoveTool()
  145. {
  146. SceneWindow window = GetWindow<SceneWindow>();
  147. if (window != null)
  148. window.OnSceneToolButtonClicked(SceneViewTool.Move);
  149. }
  150. /// <summary>
  151. /// Switches the active tool to the rotate tool.
  152. /// </summary>
  153. [MenuItem("Tools/Rotate", ButtonModifier.Ctrl, ButtonCode.E, 9272)]
  154. private static void SetRotateTool()
  155. {
  156. SceneWindow window = GetWindow<SceneWindow>();
  157. if (window != null)
  158. window.OnSceneToolButtonClicked(SceneViewTool.Rotate);
  159. }
  160. /// <summary>
  161. /// Switches the active tool to the scale tool.
  162. /// </summary>
  163. [MenuItem("Tools/Scale", ButtonModifier.Ctrl, ButtonCode.R, 9271)]
  164. private static void SetScaleTool()
  165. {
  166. SceneWindow window = GetWindow<SceneWindow>();
  167. if (window != null)
  168. window.OnSceneToolButtonClicked(SceneViewTool.Scale);
  169. }
  170. /// <inheritdoc/>
  171. protected override LocString GetDisplayName()
  172. {
  173. return new LocEdString("Scene");
  174. }
  175. private void OnInitialize()
  176. {
  177. if (ProjectSettings.HasKey(GizmoDrawSettingsKey))
  178. gizmoDrawSettings = ProjectSettings.GetObject<GizmoDrawSettings>(SceneWindow.GizmoDrawSettingsKey);
  179. else
  180. gizmoDrawSettings = GizmoDrawSettings.Default();
  181. mainLayout = GUI.AddLayoutY();
  182. GUIContent viewIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.View),
  183. new LocEdString("View"));
  184. GUIContent moveIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Move),
  185. new LocEdString("Move"));
  186. GUIContent rotateIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Rotate),
  187. new LocEdString("Rotate"));
  188. GUIContent scaleIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Scale),
  189. new LocEdString("Scale"));
  190. GUIContent localIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Local),
  191. new LocEdString("Local"));
  192. GUIContent worldIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.World),
  193. new LocEdString("World"));
  194. GUIContent pivotIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Pivot),
  195. new LocEdString("Pivot"));
  196. GUIContent centerIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Center),
  197. new LocEdString("Center"));
  198. GUIContent moveSnapIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.MoveSnap),
  199. new LocEdString("Move snap"));
  200. GUIContent rotateSnapIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.RotateSnap),
  201. new LocEdString("Rotate snap"));
  202. GUIToggleGroup handlesTG = new GUIToggleGroup();
  203. viewButton = new GUIToggle(viewIcon, handlesTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  204. moveButton = new GUIToggle(moveIcon, handlesTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  205. rotateButton = new GUIToggle(rotateIcon, handlesTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  206. scaleButton = new GUIToggle(scaleIcon, handlesTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  207. GUIToggleGroup coordModeTG = new GUIToggleGroup();
  208. localCoordButton = new GUIToggle(localIcon, coordModeTG, EditorStyles.Button, GUIOption.FlexibleWidth(75));
  209. worldCoordButton = new GUIToggle(worldIcon, coordModeTG, EditorStyles.Button, GUIOption.FlexibleWidth(75));
  210. GUIToggleGroup pivotModeTG = new GUIToggleGroup();
  211. pivotButton = new GUIToggle(pivotIcon, pivotModeTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  212. centerButton = new GUIToggle(centerIcon, pivotModeTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  213. moveSnapButton = new GUIToggle(moveSnapIcon, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  214. moveSnapInput = new GUIFloatField("", GUIOption.FlexibleWidth(35));
  215. rotateSnapButton = new GUIToggle(rotateSnapIcon, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  216. rotateSnapInput = new GUIFloatField("", GUIOption.FlexibleWidth(35));
  217. GUIContent cameraOptionsIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.SceneCameraOptions), new LocEdString("Camera options"));
  218. cameraOptionsButton = new GUIButton(cameraOptionsIcon);
  219. viewButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.View);
  220. moveButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.Move);
  221. rotateButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.Rotate);
  222. scaleButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.Scale);
  223. localCoordButton.OnClick += () => OnCoordinateModeButtonClicked(HandleCoordinateMode.Local);
  224. worldCoordButton.OnClick += () => OnCoordinateModeButtonClicked(HandleCoordinateMode.World);
  225. pivotButton.OnClick += () => OnPivotModeButtonClicked(HandlePivotMode.Pivot);
  226. centerButton.OnClick += () => OnPivotModeButtonClicked(HandlePivotMode.Center);
  227. moveSnapButton.OnToggled += (bool active) => OnMoveSnapToggled(active);
  228. moveSnapInput.OnChanged += (float value) => OnMoveSnapValueChanged(value);
  229. rotateSnapButton.OnToggled += (bool active) => OnRotateSnapToggled(active);
  230. rotateSnapInput.OnChanged += (float value) => OnRotateSnapValueChanged(value);
  231. cameraOptionsButton.OnClick += () => OnCameraOptionsClicked();
  232. GUILayout handlesLayout = mainLayout.AddLayoutX();
  233. handlesLayout.AddElement(viewButton);
  234. handlesLayout.AddElement(moveButton);
  235. handlesLayout.AddElement(rotateButton);
  236. handlesLayout.AddElement(scaleButton);
  237. handlesLayout.AddSpace(10);
  238. handlesLayout.AddElement(localCoordButton);
  239. handlesLayout.AddElement(worldCoordButton);
  240. handlesLayout.AddSpace(10);
  241. handlesLayout.AddElement(pivotButton);
  242. handlesLayout.AddElement(centerButton);
  243. handlesLayout.AddFlexibleSpace();
  244. handlesLayout.AddElement(moveSnapButton);
  245. handlesLayout.AddElement(moveSnapInput);
  246. handlesLayout.AddSpace(10);
  247. handlesLayout.AddElement(rotateSnapButton);
  248. handlesLayout.AddElement(rotateSnapInput);
  249. handlesLayout.AddSpace(10);
  250. handlesLayout.AddElement(cameraOptionsButton);
  251. handlesLayout.SetHeight(viewButton.Bounds.height);
  252. GUIPanel mainPanel = mainLayout.AddPanel();
  253. rtPanel = mainPanel.AddPanel();
  254. // Loading progress
  255. loadLabel = new GUILabel(new LocEdString("Loading scene..."));
  256. loadProgressBar = new GUIProgressBar("", GUIOption.FixedWidth(200));
  257. progressLayout = mainPanel.AddLayoutY();
  258. progressLayout.AddFlexibleSpace();
  259. GUILayout loadLabelLayout = progressLayout.AddLayoutX();
  260. loadLabelLayout.AddFlexibleSpace();
  261. loadLabelLayout.AddElement(loadLabel);
  262. loadLabelLayout.AddFlexibleSpace();
  263. GUILayout progressBarLayout = progressLayout.AddLayoutX();
  264. progressBarLayout.AddFlexibleSpace();
  265. progressBarLayout.AddElement(loadProgressBar);
  266. progressBarLayout.AddFlexibleSpace();
  267. progressLayout.AddFlexibleSpace();
  268. progressLayout.Active = false;
  269. selectionPanel = mainPanel.AddPanel(-1);
  270. sceneAxesPanel = mainPanel.AddPanel(-1);
  271. sceneAxesGUI = new SceneAxesGUI(this, sceneAxesPanel, HandleAxesGUISize, HandleAxesGUISize, ProjectionType.Perspective);
  272. sceneAxesLastProjectionType = ProjectionType.Perspective;
  273. focusCatcher = new GUIButton("", EditorStyles.Blank);
  274. focusCatcher.OnFocusGained += () => hasContentFocus = true;
  275. focusCatcher.OnFocusLost += () => hasContentFocus = false;
  276. GUIPanel focusPanel = GUI.AddPanel(-2);
  277. focusPanel.AddElement(focusCatcher);
  278. cameraPreviewsPanel = GUI.AddPanel(-3);
  279. viewToolKey = new VirtualButton(ViewToolBinding);
  280. moveToolKey = new VirtualButton(MoveToolBinding);
  281. rotateToolKey = new VirtualButton(RotateToolBinding);
  282. scaleToolKey = new VirtualButton(ScaleToolBinding);
  283. frameKey = new VirtualButton(FrameBinding);
  284. UpdateRenderTexture(Width, Height - HeaderHeight);
  285. UpdateLoadingProgress();
  286. UpdateCameraPreviews();
  287. Selection.OnSelectionChanged += OnSelectionChanged;
  288. }
  289. private void OnCameraOptionsClicked()
  290. {
  291. SceneCameraSettingsWindow.Open();
  292. }
  293. private void OnDestroy()
  294. {
  295. if (camera != null)
  296. {
  297. Vector3 pos = camera.SceneObject.Position;
  298. Quaternion rot = camera.SceneObject.Rotation;
  299. ProjectSettings.SetObject(CameraPositionKey, pos);
  300. ProjectSettings.SetObject(CameraRotationKey, rot);
  301. camera.SceneObject.Destroy(true);
  302. camera = null;
  303. }
  304. sceneAxesGUI.Destroy();
  305. sceneAxesGUI = null;
  306. Selection.OnSelectionChanged -= OnSelectionChanged;
  307. }
  308. /// <summary>
  309. /// Deletes all currently selected objects.
  310. /// </summary>
  311. private void DeleteSelection()
  312. {
  313. SceneObject[] selectedObjects = Selection.SceneObjects;
  314. CleanDuplicates(ref selectedObjects);
  315. if (selectedObjects.Length > 0)
  316. {
  317. foreach (var so in selectedObjects)
  318. {
  319. string message = "Deleted " + so.Name;
  320. UndoRedo.DeleteSO(so, message);
  321. }
  322. EditorApplication.SetSceneDirty();
  323. }
  324. }
  325. /// <summary>
  326. /// Duplicates all currently selected objects.
  327. /// </summary>
  328. private void DuplicateSelection()
  329. {
  330. SceneObject[] selectedObjects = Selection.SceneObjects;
  331. CleanDuplicates(ref selectedObjects);
  332. if (selectedObjects.Length > 0)
  333. {
  334. string message;
  335. if (selectedObjects.Length == 1)
  336. message = "Duplicated " + selectedObjects[0].Name;
  337. else
  338. message = "Duplicated " + selectedObjects.Length + " elements";
  339. Transform[] savedTransforms = new Transform[selectedObjects.Length];
  340. for (int i = 0; i < savedTransforms.Length; i++)
  341. savedTransforms[i] = new Transform(selectedObjects[i]);
  342. SceneObject[] clonedObjects = UndoRedo.CloneSO(selectedObjects, message);
  343. // Restore world positions
  344. for (int i = 0; i < savedTransforms.Length; i++)
  345. savedTransforms[i].Apply(clonedObjects[i]);
  346. EditorApplication.SetSceneDirty();
  347. }
  348. }
  349. /// <summary>
  350. /// Callback that triggers when a new set of scene objects or resources has been selected.
  351. /// </summary>
  352. /// <param name="objects">Selected scene objects.</param>
  353. /// <param name="resources">Selected resources.</param>
  354. private void OnSelectionChanged(SceneObject[] objects, string[] resources)
  355. {
  356. UpdateCameraPreviews();
  357. }
  358. /// <inheritdoc/>
  359. void IGlobalShortcuts.OnRenamePressed()
  360. {
  361. // Do nothing
  362. }
  363. /// <inheritdoc/>
  364. void IGlobalShortcuts.OnDuplicatePressed()
  365. {
  366. DuplicateSelection();
  367. }
  368. /// <inheritdoc/>
  369. void IGlobalShortcuts.OnDeletePressed()
  370. {
  371. DeleteSelection();
  372. }
  373. /// <inheritdoc/>
  374. void IGlobalShortcuts.OnCopyPressed()
  375. {
  376. // Do nothing
  377. }
  378. /// <inheritdoc/>
  379. void IGlobalShortcuts.OnCutPressed()
  380. {
  381. // Do nothing
  382. }
  383. /// <inheritdoc/>
  384. void IGlobalShortcuts.OnPastePressed()
  385. {
  386. // Do nothing
  387. }
  388. /// <summary>
  389. /// Orients the camera so it looks along the provided axis.
  390. /// </summary>
  391. /// <param name="axis">Axis to look along.</param>
  392. internal void LookAlong(Vector3 axis)
  393. {
  394. axis.Normalize();
  395. sceneCamera.LookAlong(axis);
  396. UpdateGridMode();
  397. }
  398. private void UpdateGridMode()
  399. {
  400. Vector3 forward = camera.SceneObject.Forward;
  401. if (camera.ProjectionType == ProjectionType.Perspective)
  402. sceneGrid.SetMode(GridMode.Perspective);
  403. else
  404. {
  405. float dotX = Vector3.Dot(forward, Vector3.XAxis);
  406. if (dotX >= 0.95f)
  407. sceneGrid.SetMode(GridMode.OrthoX);
  408. else if (dotX <= -0.95f)
  409. sceneGrid.SetMode(GridMode.OrthoNegX);
  410. else
  411. {
  412. float dotY = Vector3.Dot(forward, Vector3.YAxis);
  413. if (dotY >= 0.95f)
  414. sceneGrid.SetMode(GridMode.OrthoY);
  415. else if (dotY <= -0.95f)
  416. sceneGrid.SetMode(GridMode.OrthoNegY);
  417. else
  418. {
  419. float dotZ = Vector3.Dot(forward, Vector3.ZAxis);
  420. if (dotZ >= 0.95f)
  421. sceneGrid.SetMode(GridMode.OrthoZ);
  422. else if (dotZ <= -0.95f)
  423. sceneGrid.SetMode(GridMode.OrthoNegZ);
  424. else
  425. sceneGrid.SetMode(GridMode.Perspective);
  426. }
  427. }
  428. }
  429. }
  430. /// <summary>
  431. /// Converts screen coordinates into coordinates relative to the scene view render texture.
  432. /// </summary>
  433. /// <param name="screenPos">Coordinates relative to the screen.</param>
  434. /// <param name="scenePos">Output coordinates relative to the scene view texture.</param>
  435. /// <returns>True if the coordinates are within the scene view texture, false otherwise.</returns>
  436. private bool ScreenToScenePos(Vector2I screenPos, out Vector2I scenePos)
  437. {
  438. scenePos = screenPos;
  439. Vector2I windowPos = ScreenToWindowPos(screenPos);
  440. Rect2I bounds = GUIUtility.CalculateBounds(renderTextureGUI, GUI);
  441. if (bounds.Contains(windowPos))
  442. {
  443. scenePos.x = windowPos.x - bounds.x;
  444. scenePos.y = windowPos.y - bounds.y;
  445. return true;
  446. }
  447. return false;
  448. }
  449. private void OnEditorUpdate()
  450. {
  451. UpdateLoadingProgress();
  452. if (HasFocus)
  453. {
  454. if (!Input.IsPointerButtonHeld(PointerButton.Right))
  455. {
  456. if (VirtualInput.IsButtonDown(EditorApplication.DuplicateKey))
  457. DuplicateSelection();
  458. else if (VirtualInput.IsButtonDown(EditorApplication.DeleteKey))
  459. DeleteSelection();
  460. else if (VirtualInput.IsButtonDown(viewToolKey))
  461. EditorApplication.ActiveSceneTool = SceneViewTool.View;
  462. else if (VirtualInput.IsButtonDown(moveToolKey))
  463. EditorApplication.ActiveSceneTool = SceneViewTool.Move;
  464. else if (VirtualInput.IsButtonDown(rotateToolKey))
  465. EditorApplication.ActiveSceneTool = SceneViewTool.Rotate;
  466. else if (VirtualInput.IsButtonDown(scaleToolKey))
  467. EditorApplication.ActiveSceneTool = SceneViewTool.Scale;
  468. }
  469. }
  470. // Refresh GUI buttons if needed (in case someones changes the values from script)
  471. if (editorSettingsHash != EditorSettings.Hash)
  472. {
  473. UpdateButtonStates();
  474. editorSettingsHash = EditorSettings.Hash;
  475. }
  476. // Update scene view handles and selection
  477. sceneGrid.Draw();
  478. ProjectionType currentProjType = camera.ProjectionType;
  479. if (sceneAxesLastProjectionType != currentProjType)
  480. {
  481. sceneAxesGUI.ProjectionType = currentProjType;
  482. sceneAxesLastProjectionType = currentProjType;
  483. }
  484. bool handleActive = sceneHandles.IsActive() || sceneAxesGUI.IsActive();
  485. Vector2I scenePos;
  486. bool inBounds = ScreenToScenePos(Input.PointerPosition, out scenePos);
  487. bool clearSelection = false;
  488. if (AllowViewportInput)
  489. {
  490. if (Input.IsPointerButtonUp(PointerButton.Left))
  491. clearSelection = true;
  492. else if (Input.IsPointerButtonDown(PointerButton.Left))
  493. mouseDownPosition = scenePos;
  494. }
  495. else
  496. {
  497. clearSelection = true;
  498. inBounds = false;
  499. }
  500. bool dragResult = false;
  501. if (clearSelection)
  502. {
  503. dragResult = EndDragSelection();
  504. if (sceneHandles.IsActive())
  505. {
  506. sceneHandles.ClearSelection();
  507. NotifyNeedsRedraw();
  508. }
  509. if (sceneAxesGUI.IsActive())
  510. sceneAxesGUI.ClearSelection();
  511. }
  512. bool draggedOver = DragDrop.DragInProgress || DragDrop.DropInProgress;
  513. draggedOver &= IsPointerHovering && inBounds && DragDrop.Type == DragDropType.Resource;
  514. if (draggedOver)
  515. {
  516. if (DragDrop.DropInProgress)
  517. {
  518. dragActive = false;
  519. if (draggedSO != null)
  520. {
  521. Selection.SceneObject = draggedSO;
  522. EditorApplication.SetSceneDirty();
  523. }
  524. draggedSO = null;
  525. }
  526. else
  527. {
  528. if (!dragActive)
  529. {
  530. dragActive = true;
  531. ResourceDragDropData dragData = (ResourceDragDropData)DragDrop.Data;
  532. string[] draggedPaths = dragData.Paths;
  533. for (int i = 0; i < draggedPaths.Length; i++)
  534. {
  535. ResourceMeta meta = ProjectLibrary.GetMeta(draggedPaths[i]);
  536. if (meta != null)
  537. {
  538. if (meta.ResType == ResourceType.Mesh)
  539. {
  540. if (!string.IsNullOrEmpty(draggedPaths[i]))
  541. {
  542. Mesh mesh = ProjectLibrary.Load<Mesh>(draggedPaths[i]);
  543. string meshName = Path.GetFileNameWithoutExtension(draggedPaths[i]);
  544. draggedSO = new SceneObject(meshName);
  545. GameObjectUndo.RecordNewSceneObject(draggedSO);
  546. Renderable renderable = draggedSO.AddComponent<Renderable>();
  547. renderable.Mesh = mesh;
  548. GameObjectUndo.ResolveDiffs();
  549. if (mesh != null)
  550. draggedSOOffset = mesh.Bounds.Box.Center;
  551. else
  552. draggedSOOffset = Vector3.Zero;
  553. }
  554. break;
  555. }
  556. else if (meta.ResType == ResourceType.Prefab)
  557. {
  558. if (!string.IsNullOrEmpty(draggedPaths[i]))
  559. {
  560. Prefab prefab = ProjectLibrary.Load<Prefab>(draggedPaths[i]);
  561. draggedSO = UndoRedo.Instantiate(prefab, "Instantiating " + prefab.Name);
  562. if (draggedSO != null)
  563. {
  564. AABox draggedObjBounds = EditorUtility.CalculateBounds(draggedSO);
  565. draggedSOOffset = draggedObjBounds.Center;
  566. }
  567. else
  568. draggedSOOffset = Vector3.Zero;
  569. }
  570. break;
  571. }
  572. }
  573. }
  574. }
  575. if (draggedSO != null)
  576. {
  577. if (Input.IsButtonHeld(ButtonCode.Space))
  578. {
  579. SnapData snapData;
  580. sceneSelection.Snap(scenePos, out snapData, new SceneObject[] { draggedSO });
  581. Quaternion q = Quaternion.FromToRotation(Vector3.YAxis, snapData.normal);
  582. draggedSO.Position = snapData.position;
  583. draggedSO.Rotation = q;
  584. }
  585. else
  586. {
  587. Ray worldRay = camera.ScreenPointToRay(scenePos);
  588. draggedSO.Position = worldRay * DefaultPlacementDepth - draggedSOOffset;
  589. }
  590. }
  591. }
  592. return;
  593. }
  594. else
  595. {
  596. if (dragActive)
  597. {
  598. dragActive = false;
  599. if (draggedSO != null)
  600. {
  601. draggedSO.Destroy();
  602. draggedSO = null;
  603. }
  604. }
  605. }
  606. if ((HasContentFocus || IsPointerHovering) && AllowViewportInput)
  607. {
  608. sceneCamera.EnableInput(true);
  609. if (inBounds && HasContentFocus)
  610. {
  611. if (Input.IsPointerButtonDown(PointerButton.Left))
  612. {
  613. Rect2I sceneAxesGUIBounds = new Rect2I(Width - HandleAxesGUISize - HandleAxesGUIPaddingX,
  614. HandleAxesGUIPaddingY, HandleAxesGUISize, HandleAxesGUISize);
  615. if (sceneAxesGUIBounds.Contains(scenePos))
  616. sceneAxesGUI.TrySelect(scenePos);
  617. else
  618. {
  619. if(sceneHandles.TrySelect(scenePos))
  620. NotifyNeedsRedraw();
  621. }
  622. }
  623. else if (Input.IsPointerButtonHeld(PointerButton.Left) && !handleActive && !dragActive &&
  624. draggedSO == null && scenePos != mouseDownPosition)
  625. {
  626. if (isDraggingSelection)
  627. UpdateDragSelection(scenePos);
  628. else
  629. StartDragSelection(scenePos);
  630. }
  631. else if (Input.IsPointerButtonUp(PointerButton.Left))
  632. {
  633. if (!handleActive && !dragActive && !dragResult)
  634. {
  635. bool ctrlHeld = Input.IsButtonHeld(ButtonCode.LeftControl) ||
  636. Input.IsButtonHeld(ButtonCode.RightControl);
  637. sceneSelection.PickObject(scenePos, ctrlHeld, new SceneObject[] { draggedSO });
  638. }
  639. }
  640. }
  641. }
  642. else
  643. sceneCamera.EnableInput(false);
  644. if (AllowViewportInput)
  645. {
  646. SceneHandles.BeginInput();
  647. if(sceneHandles.UpdateInput(scenePos, Input.PointerDelta))
  648. NotifyNeedsRedraw();
  649. sceneAxesGUI.UpdateInput(scenePos);
  650. SceneHandles.EndInput();
  651. }
  652. if(sceneHandles.IsActive())
  653. NotifyNeedsRedraw();
  654. sceneHandles.Draw();
  655. sceneAxesGUI.Draw();
  656. // Must be done after handle input is processed, in order to reflect most recent transform
  657. sceneGizmos.Draw();
  658. sceneSelection.Draw();
  659. UpdateGridMode();
  660. if (VirtualInput.IsButtonDown(frameKey))
  661. sceneCamera.FrameSelected();
  662. }
  663. /// <inheritdoc/>
  664. protected override void WindowResized(int width, int height)
  665. {
  666. UpdateRenderTexture(width, height - HeaderHeight);
  667. base.WindowResized(width, height);
  668. }
  669. /// <inheritdoc/>
  670. protected override void FocusChanged(bool inFocus)
  671. {
  672. if (!inFocus)
  673. {
  674. sceneHandles.ClearSelection();
  675. NotifyNeedsRedraw();
  676. }
  677. }
  678. /// <summary>
  679. /// Triggered when one of the scene tool buttons is clicked, changing the active scene handle.
  680. /// </summary>
  681. /// <param name="tool">Clicked scene tool to activate.</param>
  682. private void OnSceneToolButtonClicked(SceneViewTool tool)
  683. {
  684. EditorApplication.ActiveSceneTool = tool;
  685. editorSettingsHash = EditorSettings.Hash;
  686. }
  687. /// <summary>
  688. /// Triggered when one of the coordinate mode buttons is clicked, changing the active coordinate mode.
  689. /// </summary>
  690. /// <param name="mode">Clicked coordinate mode to activate.</param>
  691. private void OnCoordinateModeButtonClicked(HandleCoordinateMode mode)
  692. {
  693. EditorApplication.ActiveCoordinateMode = mode;
  694. editorSettingsHash = EditorSettings.Hash;
  695. }
  696. /// <summary>
  697. /// Triggered when one of the pivot buttons is clicked, changing the active pivot mode.
  698. /// </summary>
  699. /// <param name="mode">Clicked pivot mode to activate.</param>
  700. private void OnPivotModeButtonClicked(HandlePivotMode mode)
  701. {
  702. EditorApplication.ActivePivotMode = mode;
  703. editorSettingsHash = EditorSettings.Hash;
  704. }
  705. /// <summary>
  706. /// Triggered when the move snap button is toggled.
  707. /// </summary>
  708. /// <param name="active">Determins should be move snap be activated or deactivated.</param>
  709. private void OnMoveSnapToggled(bool active)
  710. {
  711. Handles.MoveHandleSnapActive = active;
  712. editorSettingsHash = EditorSettings.Hash;
  713. }
  714. /// <summary>
  715. /// Triggered when the move snap increment value changes.
  716. /// </summary>
  717. /// <param name="value">Value that determines in what increments to perform move snapping.</param>
  718. private void OnMoveSnapValueChanged(float value)
  719. {
  720. Handles.MoveSnapAmount = MathEx.Clamp(value, 0.01f, 1000.0f);
  721. editorSettingsHash = EditorSettings.Hash;
  722. }
  723. /// <summary>
  724. /// Triggered when the rotate snap button is toggled.
  725. /// </summary>
  726. /// <param name="active">Determins should be rotate snap be activated or deactivated.</param>
  727. private void OnRotateSnapToggled(bool active)
  728. {
  729. Handles.RotateHandleSnapActive = active;
  730. editorSettingsHash = EditorSettings.Hash;
  731. }
  732. /// <summary>
  733. /// Triggered when the rotate snap increment value changes.
  734. /// </summary>
  735. /// <param name="value">Value that determines in what increments to perform rotate snapping.</param>
  736. private void OnRotateSnapValueChanged(float value)
  737. {
  738. Handles.RotateSnapAmount = (Degree)MathEx.Clamp(value, 0.01f, 360.0f);
  739. editorSettingsHash = EditorSettings.Hash;
  740. }
  741. /// <summary>
  742. /// Updates toggle button states according to current editor options. This is useful if tools, coordinate mode,
  743. /// pivot or other scene view options have been modified externally.
  744. /// </summary>
  745. private void UpdateButtonStates()
  746. {
  747. switch (EditorApplication.ActiveSceneTool)
  748. {
  749. case SceneViewTool.View:
  750. viewButton.Value = true;
  751. break;
  752. case SceneViewTool.Move:
  753. moveButton.Value = true;
  754. break;
  755. case SceneViewTool.Rotate:
  756. rotateButton.Value = true;
  757. break;
  758. case SceneViewTool.Scale:
  759. scaleButton.Value = true;
  760. break;
  761. }
  762. switch (EditorApplication.ActiveCoordinateMode)
  763. {
  764. case HandleCoordinateMode.Local:
  765. localCoordButton.Value = true;
  766. break;
  767. case HandleCoordinateMode.World:
  768. worldCoordButton.Value = true;
  769. break;
  770. }
  771. switch (EditorApplication.ActivePivotMode)
  772. {
  773. case HandlePivotMode.Center:
  774. centerButton.Value = true;
  775. break;
  776. case HandlePivotMode.Pivot:
  777. pivotButton.Value = true;
  778. break;
  779. }
  780. if (Handles.MoveHandleSnapActive)
  781. moveSnapButton.Value = true;
  782. else
  783. moveSnapButton.Value = false;
  784. moveSnapInput.Value = Handles.MoveSnapAmount;
  785. if (Handles.RotateHandleSnapActive)
  786. rotateSnapButton.Value = true;
  787. else
  788. rotateSnapButton.Value = false;
  789. moveSnapInput.Value = Handles.RotateSnapAmount.Degrees;
  790. }
  791. /// <summary>
  792. /// Creates the scene camera and updates the render texture. Should be called at least once before using the
  793. /// scene view. Should be called whenever the window is resized.
  794. /// </summary>
  795. /// <param name="width">Width of the scene render target, in pixels.</param>
  796. /// <param name="height">Height of the scene render target, in pixels.</param>
  797. private void UpdateRenderTexture(int width, int height)
  798. {
  799. width = MathEx.Max(20, width);
  800. height = MathEx.Max(20, height);
  801. // Note: Depth buffer and readable flags are required because ScenePicking uses it
  802. Texture colorTex = Texture.Create2D(width, height, PixelFormat.RGBA8, TextureUsage.Render | TextureUsage.CPUReadable);
  803. Texture depthTex = Texture.Create2D(width, height, PixelFormat.D32_S8X24, TextureUsage.DepthStencil | TextureUsage.CPUReadable);
  804. renderTexture = new RenderTexture(colorTex, depthTex);
  805. renderTexture.Priority = 1;
  806. if (camera == null)
  807. {
  808. SceneObject sceneCameraSO = new SceneObject("SceneCamera", true);
  809. camera = sceneCameraSO.AddComponent<Camera>();
  810. camera.Viewport.Target = renderTexture;
  811. camera.Viewport.Area = new Rect2(0.0f, 0.0f, 1.0f, 1.0f);
  812. Vector3 camPosition = new Vector3(0.0f, 1.7f, 5.0f);
  813. object camPosObj = ProjectSettings.GetObject<object>(CameraPositionKey);
  814. if (camPosObj is Vector3)
  815. camPosition = (Vector3)camPosObj;
  816. Quaternion camRotation = Quaternion.Identity;
  817. object camRotObj = ProjectSettings.GetObject<object>(CameraRotationKey);
  818. if (camRotObj is Quaternion)
  819. camRotation = (Quaternion)camRotObj;
  820. sceneCameraSO.Position = camPosition;
  821. sceneCameraSO.Rotation = camRotation;
  822. camera.Priority = 2;
  823. camera.Viewport.ClearColor = ClearColor;
  824. camera.Layers = UInt64.MaxValue & ~SceneAxesHandle.LAYER; // Don't draw scene axes in this camera
  825. camera.Flags = CameraFlag.OnDemand;
  826. sceneCamera = sceneCameraSO.AddComponent<SceneCamera>();
  827. renderTextureGUI = new GUIRenderTexture(renderTexture);
  828. rtPanel.AddElement(renderTextureGUI);
  829. sceneGrid = new SceneGrid(camera);
  830. sceneSelection = new SceneSelection(camera, gizmoDrawSettings);
  831. sceneGizmos = new SceneGizmos(camera, gizmoDrawSettings);
  832. sceneHandles = new SceneHandles(this, camera);
  833. }
  834. else
  835. {
  836. camera.Viewport.Target = renderTexture;
  837. renderTextureGUI.RenderTexture = renderTexture;
  838. }
  839. Rect2I rtBounds = new Rect2I(0, 0, width, height);
  840. renderTextureGUI.Bounds = rtBounds;
  841. focusCatcher.Bounds = GUIUtility.CalculateBounds(rtPanel, GUI);
  842. sceneAxesGUI.SetPosition(width - HandleAxesGUISize - HandleAxesGUIPaddingX, HandleAxesGUIPaddingY);
  843. // TODO - Consider only doing the resize once user stops resizing the widget in order to reduce constant
  844. // render target destroy/create cycle for every single pixel.
  845. camera.AspectRatio = width / (float)height;
  846. camera.NotifyNeedsRedraw();
  847. }
  848. /// <summary>
  849. /// Notifies the system that the 3D viewport should be redrawn.
  850. /// </summary>
  851. internal void NotifyNeedsRedraw()
  852. {
  853. sceneCamera?.NotifyNeedsRedraw();
  854. }
  855. /// <summary>
  856. /// Enables or disables on-demand drawing. When enabled the 3D viewport will only be redrawn when
  857. /// <see cref="NotifyNeedsRedraw"/> is called. If disabled the viewport will be redrawn every frame.
  858. /// </summary>
  859. /// <param name="enabled">True to enable on-demand drawing, false otherwise.</param>
  860. internal void ToggleOnDemandDrawing(bool enabled)
  861. {
  862. sceneCamera?.ToggleOnDemandDrawing(enabled);
  863. }
  864. /// <summary>
  865. /// Set up preview boxes for the currently selected cameras.
  866. /// </summary>
  867. private void UpdateCameraPreviews()
  868. {
  869. SceneObject[] selectedObjects = Selection.SceneObjects;
  870. // Hide unpinned camera previews which are not selected
  871. for (int i = 0; i < cameraPreviews.Count; i++)
  872. {
  873. var cameraPreview = cameraPreviews[i];
  874. // Remove preview for destroyed cameras
  875. if (cameraPreview.Camera == null || cameraPreview.Camera.SceneObject == null
  876. || /*Temporary hack until we can render preview non-main cameras properly*/ !cameraPreview.Camera.Main)
  877. {
  878. HideCameraPreview(cameraPreview.Camera);
  879. continue;
  880. }
  881. if (cameraPreview.IsPinned)
  882. continue;
  883. bool cameraExists = Array.Exists(selectedObjects, x => x == cameraPreview.Camera.SceneObject);
  884. if (!cameraExists)
  885. HideCameraPreview(cameraPreview.Camera);
  886. }
  887. // Create preview for selected cameras
  888. for (int i = 0; i < selectedObjects.Length; i++)
  889. {
  890. if (cameraPreviews.Count >= MaxCameraPreviews)
  891. break;
  892. var selectedCamera = selectedObjects[i].GetComponent<Camera>();
  893. if (selectedCamera != null && /*Temporary hack until we can render preview non-main cameras properly*/ selectedCamera.Main)
  894. {
  895. var cameraPreview = cameraPreviews.Find(x => x.Camera == selectedCamera);
  896. if (cameraPreview == null)
  897. cameraPreviews.Add(new CameraPreview(selectedCamera, cameraPreviewsPanel));
  898. }
  899. }
  900. // Update preview box placement
  901. int previewsCount = cameraPreviews.Count;
  902. if (previewsCount > 0)
  903. {
  904. const float PreviewBoxAspect = 16.0f / 9.0f;
  905. const float PreviewBoxMinHeight = 80;
  906. const float PreviewBoxMinWidth = PreviewBoxMinHeight * PreviewBoxAspect;
  907. const float PreviewBoxMaxHeight = 150;
  908. const float PreviewBoxMaxWidth = PreviewBoxMaxHeight * PreviewBoxAspect;
  909. const float PreviewBoxViewSpaceMaxPercentage = 0.9f;
  910. const float PreviewBoxMarigin = 10;
  911. Rect2I rtBounds = renderTextureGUI.VisibleBounds;
  912. Vector2 rtSize = new Vector2(rtBounds.width, rtBounds.height);
  913. Vector2 usableSize = rtSize * PreviewBoxViewSpaceMaxPercentage - PreviewBoxMarigin;
  914. Vector2 previewSize = usableSize / previewsCount - previewsCount * PreviewBoxMarigin;
  915. float previewWidth = MathEx.Clamp(previewSize.x, PreviewBoxMinWidth, PreviewBoxMaxWidth);
  916. float previewHeight = previewWidth / PreviewBoxAspect;
  917. previewSize = new Vector2(previewWidth, previewHeight);
  918. int countPerRow = MathEx.FloorToInt(usableSize.x / previewSize.x);
  919. int countPerColumn = MathEx.FloorToInt(usableSize.y / previewSize.y);
  920. int index = 0;
  921. for (int y = 1; y <= countPerColumn; y++)
  922. {
  923. for (int x = 1; x <= countPerRow; x++)
  924. {
  925. if (index == previewsCount)
  926. break;
  927. var pos = rtSize - (previewSize + PreviewBoxMarigin) * new Vector2(x, y);
  928. var cameraPreview = cameraPreviews[index++];
  929. cameraPreview.ShowPreview(cameraPreview.Camera,
  930. new Rect2I((int)pos.x, (int)pos.y, (int)previewSize.x, (int)previewSize.y));
  931. }
  932. if (index == previewsCount)
  933. break;
  934. }
  935. }
  936. }
  937. /// <summary>
  938. /// Hides the preview box for the provided camera, if one exists.
  939. /// </summary>
  940. /// <param name="camera">Camera whose preview box to hide.</param>
  941. private void HideCameraPreview(Camera camera)
  942. {
  943. var cameraPreview = cameraPreviews.Find(x => x.Camera == camera);
  944. if (cameraPreview != null)
  945. {
  946. cameraPreviews.Remove(cameraPreview);
  947. cameraPreview.Destroy();
  948. }
  949. }
  950. /// <summary>
  951. /// Hides all the camera preview boxes.
  952. /// </summary>
  953. private void HideAllCameraPreviews()
  954. {
  955. foreach(var entry in cameraPreviews)
  956. entry.Destroy();
  957. cameraPreviews.Clear();
  958. }
  959. /// <summary>
  960. /// Parses an array of scene objects and removes elements that are children of elements that are also in the array.
  961. /// </summary>
  962. /// <param name="objects">Array containing duplicate objects as input, and array without duplicate objects as
  963. /// output.</param>
  964. private void CleanDuplicates(ref SceneObject[] objects)
  965. {
  966. List<SceneObject> cleanList = new List<SceneObject>();
  967. for (int i = 0; i < objects.Length; i++)
  968. {
  969. bool foundParent = false;
  970. for (int j = 0; j < objects.Length; j++)
  971. {
  972. SceneObject elem = objects[i];
  973. while (elem != null && elem != objects[j])
  974. elem = elem.Parent;
  975. bool isChildOf = elem == objects[j];
  976. if (i != j && isChildOf)
  977. {
  978. foundParent = true;
  979. break;
  980. }
  981. }
  982. if (!foundParent)
  983. cleanList.Add(objects[i]);
  984. }
  985. objects = cleanList.ToArray();
  986. }
  987. /// <summary>
  988. /// Checks if the load progress bar needs to be shown, shows/hides it and updates the progress accordingly.
  989. /// </summary>
  990. private void UpdateLoadingProgress()
  991. {
  992. bool needsProgress = EditorApplication.IsSceneLoading;
  993. if (needsProgress && !loadingProgressShown)
  994. {
  995. progressLayout.Active = true;
  996. rtPanel.Active = false;
  997. sceneAxesPanel.Active = false;
  998. loadingProgressShown = true;
  999. }
  1000. else if (!needsProgress && loadingProgressShown)
  1001. {
  1002. progressLayout.Active = false;
  1003. rtPanel.Active = true;
  1004. sceneAxesPanel.Active = true;
  1005. loadingProgressShown = false;
  1006. }
  1007. if (needsProgress)
  1008. loadProgressBar.Percent = EditorApplication.SceneLoadProgress;
  1009. }
  1010. /// <summary>
  1011. /// Starts a drag operation that displays a selection outline allowing the user to select multiple entries at once.
  1012. /// </summary>
  1013. /// <param name="scenePos">Coordinates relative to the scene where the drag originated.</param>
  1014. private void StartDragSelection(Vector2I scenePos)
  1015. {
  1016. isDraggingSelection = true;
  1017. dragSelectionStart = scenePos;
  1018. dragSelectionEnd = dragSelectionStart;
  1019. }
  1020. /// <summary>
  1021. /// Updates a selection outline drag operation by expanding the outline to the new location. Elements in the outline
  1022. /// are selected.
  1023. /// </summary>
  1024. /// <param name="scenePos">Coordinates of the pointer relative to the scene.</param>
  1025. /// <returns>True if the selection outline drag is valid and was updated, false otherwise.</returns>
  1026. private bool UpdateDragSelection(Vector2I scenePos)
  1027. {
  1028. if (!isDraggingSelection)
  1029. return false;
  1030. if (dragSelection == null)
  1031. {
  1032. dragSelection = new GUITexture(null, true, EditorStylesInternal.SelectionArea);
  1033. selectionPanel.AddElement(dragSelection);
  1034. }
  1035. dragSelectionEnd = scenePos;
  1036. Rect2I selectionArea = new Rect2I();
  1037. Vector2I min = new Vector2I(Math.Min(dragSelectionStart.x, dragSelectionEnd.x), Math.Min(dragSelectionStart.y, dragSelectionEnd.y));
  1038. Vector2I max = new Vector2I(Math.Max(dragSelectionStart.x, dragSelectionEnd.x), Math.Max(dragSelectionStart.y, dragSelectionEnd.y));
  1039. selectionArea.x = min.x;
  1040. selectionArea.y = min.y;
  1041. selectionArea.width = Math.Max(max.x - min.x, 1);
  1042. selectionArea.height = Math.Max(max.y - min.y, 1);
  1043. dragSelection.Bounds = selectionArea;
  1044. return true;
  1045. }
  1046. /// <summary>
  1047. /// Ends the selection outline drag operation. Elements in the outline are selected.
  1048. /// </summary>
  1049. /// <returns>True if the selection outline drag is valid and was ended, false otherwise.</returns>
  1050. private bool EndDragSelection()
  1051. {
  1052. if (!isDraggingSelection)
  1053. return false;
  1054. if (dragSelection != null)
  1055. {
  1056. dragSelection.Destroy();
  1057. dragSelection = null;
  1058. }
  1059. if ((dragSelectionEnd - dragSelectionStart).Length < 1)
  1060. {
  1061. isDraggingSelection = false;
  1062. return false;
  1063. }
  1064. Vector2I min = new Vector2I(Math.Min(dragSelectionStart.x, dragSelectionEnd.x),
  1065. Math.Min(dragSelectionStart.y, dragSelectionEnd.y));
  1066. Vector2I max = new Vector2I(Math.Max(dragSelectionStart.x, dragSelectionEnd.x),
  1067. Math.Max(dragSelectionStart.y, dragSelectionEnd.y));
  1068. sceneSelection.PickObjects(min, max - min,
  1069. Input.IsButtonHeld(ButtonCode.LeftControl) || Input.IsButtonHeld(ButtonCode.RightControl));
  1070. isDraggingSelection = false;
  1071. return true;
  1072. }
  1073. /// <summary>
  1074. /// Contains information about world transform of a single scene object.
  1075. /// </summary>
  1076. struct Transform
  1077. {
  1078. public Transform(SceneObject so)
  1079. {
  1080. position = so.Position;
  1081. rotation = so.Rotation;
  1082. scale = so.Scale;
  1083. }
  1084. /// <summary>
  1085. /// Applies the saved transform to the specified scene object. The transform is assumed to be in world space.
  1086. /// </summary>
  1087. /// <param name="so">Scene object to apply the transform to.</param>
  1088. public void Apply(SceneObject so)
  1089. {
  1090. so.Position = position;
  1091. so.Rotation = rotation;
  1092. so.LocalScale = scale;
  1093. }
  1094. public Vector3 position;
  1095. public Quaternion rotation;
  1096. public Vector3 scale;
  1097. }
  1098. }
  1099. /** @} */
  1100. }