SceneWindow.cs 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using BansheeEngine;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. namespace BansheeEditor
  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 ToggleProfilerOverlayBinding = "ToggleProfilerOverlay";
  18. internal const string ViewToolBinding = "ViewTool";
  19. internal const string MoveToolBinding = "MoveTool";
  20. internal const string RotateToolBinding = "RotateTool";
  21. internal const string ScaleToolBinding = "ScaleTool";
  22. internal const string FrameBinding = "SceneFrame";
  23. private const int HeaderHeight = 20;
  24. private const float DefaultPlacementDepth = 5.0f;
  25. private static readonly Color ClearColor = new Color(0.0f, 0.3685f, 0.7969f);
  26. private const int HandleAxesGUISize = 50;
  27. private const int HandleAxesGUIPaddingX = 10;
  28. private const int HandleAxesGUIPaddingY = 5;
  29. private Camera camera;
  30. private SceneCamera cameraController;
  31. private RenderTexture renderTexture;
  32. private GUILayoutY mainLayout;
  33. private GUIPanel rtPanel;
  34. private GUIButton focusCatcher;
  35. private GUIRenderTexture renderTextureGUI;
  36. private SceneGrid sceneGrid;
  37. private SceneSelection sceneSelection;
  38. private SceneGizmos sceneGizmos;
  39. private SceneHandles sceneHandles;
  40. private GUIToggle viewButton;
  41. private GUIToggle moveButton;
  42. private GUIToggle rotateButton;
  43. private GUIToggle scaleButton;
  44. private GUIToggle localCoordButton;
  45. private GUIToggle worldCoordButton;
  46. private GUIToggle pivotButton;
  47. private GUIToggle centerButton;
  48. private GUIToggle moveSnapButton;
  49. private GUIFloatField moveSnapInput;
  50. private GUIToggle rotateSnapButton;
  51. private GUIFloatField rotateSnapInput;
  52. private GUIButton cameraOptionsButton;
  53. private SceneAxesGUI sceneAxesGUI;
  54. private bool hasContentFocus = false;
  55. private bool HasContentFocus { get { return HasFocus && hasContentFocus; } }
  56. private int editorSettingsHash = int.MaxValue;
  57. private VirtualButton frameKey;
  58. // Tool shortcuts
  59. private VirtualButton viewToolKey;
  60. private VirtualButton moveToolKey;
  61. private VirtualButton rotateToolKey;
  62. private VirtualButton scaleToolKey;
  63. // Drag & drop
  64. private bool dragActive;
  65. private SceneObject draggedSO;
  66. private Vector3 draggedSOOffset;
  67. private GUITexture dragSelection;
  68. private bool isDraggingSelection;
  69. private Vector2I dragSelectionStart;
  70. private Vector2I dragSelectionEnd;
  71. private Vector2I mouseDownPosition;
  72. private GUIPanel selectionPanel;
  73. /// <summary>
  74. /// Returns the scene camera.
  75. /// </summary>
  76. public Camera Camera
  77. {
  78. get { return camera; }
  79. }
  80. /// <summary>
  81. /// Determines scene camera's projection type.
  82. /// </summary>
  83. internal ProjectionType ProjectionType
  84. {
  85. get { return cameraController.ProjectionType; }
  86. set { cameraController.ProjectionType = value; sceneAxesGUI.ProjectionType = value; }
  87. }
  88. /// <summary>
  89. /// Determines scene camera's orthographic size.
  90. /// </summary>
  91. internal float OrthographicSize
  92. {
  93. get { return cameraController.OrthographicSize; }
  94. set { cameraController.OrthographicSize = value; }
  95. }
  96. /// <summary>
  97. /// Determines scene camera's field of view.
  98. /// </summary>
  99. internal Degree FieldOfView
  100. {
  101. get { return cameraController.FieldOfView; }
  102. set { cameraController.FieldOfView = value; }
  103. }
  104. /// <summary>
  105. /// Determines scene camera's near clip plane.
  106. /// </summary>
  107. internal float NearClipPlane
  108. {
  109. get { return cameraController.NearClipPlane; }
  110. set { cameraController.NearClipPlane = value; }
  111. }
  112. /// <summary>
  113. /// Determines scene camera's far clip plane.
  114. /// </summary>
  115. internal float FarClipPlane
  116. {
  117. get { return cameraController.FarClipPlane; }
  118. set { cameraController.FarClipPlane = value; }
  119. }
  120. /// <summary>
  121. /// Determines scene camera's scroll speed.
  122. /// </summary>
  123. internal float ScrollSpeed
  124. {
  125. get { return cameraController.ScrollSpeed; }
  126. set { cameraController.ScrollSpeed = value; }
  127. }
  128. /// <summary>
  129. /// Constructs a new scene window.
  130. /// </summary>
  131. internal SceneWindow()
  132. { }
  133. /// <summary>
  134. /// Opens a scene window if its not open already.
  135. /// </summary>
  136. [MenuItem("Windows/Scene", ButtonModifier.CtrlAlt, ButtonCode.S, 6000)]
  137. private static void OpenSceneWindow()
  138. {
  139. OpenWindow<SceneWindow>();
  140. }
  141. /// <summary>
  142. /// Focuses on the currently selected object.
  143. /// </summary>
  144. [MenuItem("Tools/Frame Selected", ButtonModifier.None, ButtonCode.F, 9275, true)]
  145. private static void OpenSettingsWindow()
  146. {
  147. SceneWindow window = GetWindow<SceneWindow>();
  148. if (window != null)
  149. window.cameraController.FrameSelected();
  150. }
  151. /// <summary>
  152. /// Switches the active tool to the view tool.
  153. /// </summary>
  154. [MenuItem("Tools/View", ButtonModifier.Ctrl, ButtonCode.Q, 9274, true)]
  155. private static void SetViewTool()
  156. {
  157. SceneWindow window = GetWindow<SceneWindow>();
  158. if (window != null)
  159. window.OnSceneToolButtonClicked(SceneViewTool.View);
  160. }
  161. /// <summary>
  162. /// Switches the active tool to the move tool.
  163. /// </summary>
  164. [MenuItem("Tools/Move", ButtonModifier.Ctrl, ButtonCode.W, 9273)]
  165. private static void SetMoveTool()
  166. {
  167. SceneWindow window = GetWindow<SceneWindow>();
  168. if (window != null)
  169. window.OnSceneToolButtonClicked(SceneViewTool.Move);
  170. }
  171. /// <summary>
  172. /// Switches the active tool to the rotate tool.
  173. /// </summary>
  174. [MenuItem("Tools/Rotate", ButtonModifier.Ctrl, ButtonCode.E, 9272)]
  175. private static void SetRotateTool()
  176. {
  177. SceneWindow window = GetWindow<SceneWindow>();
  178. if (window != null)
  179. window.OnSceneToolButtonClicked(SceneViewTool.Rotate);
  180. }
  181. /// <summary>
  182. /// Switches the active tool to the scale tool.
  183. /// </summary>
  184. [MenuItem("Tools/Scale", ButtonModifier.Ctrl, ButtonCode.R, 9271)]
  185. private static void SetScaleTool()
  186. {
  187. SceneWindow window = GetWindow<SceneWindow>();
  188. if (window != null)
  189. window.OnSceneToolButtonClicked(SceneViewTool.Scale);
  190. }
  191. /// <inheritdoc/>
  192. protected override LocString GetDisplayName()
  193. {
  194. return new LocEdString("Scene");
  195. }
  196. private void OnInitialize()
  197. {
  198. mainLayout = GUI.AddLayoutY();
  199. GUIContent viewIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.View),
  200. new LocEdString("View"));
  201. GUIContent moveIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Move),
  202. new LocEdString("Move"));
  203. GUIContent rotateIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Rotate),
  204. new LocEdString("Rotate"));
  205. GUIContent scaleIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Scale),
  206. new LocEdString("Scale"));
  207. GUIContent localIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Local),
  208. new LocEdString("Local"));
  209. GUIContent worldIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.World),
  210. new LocEdString("World"));
  211. GUIContent pivotIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Pivot),
  212. new LocEdString("Pivot"));
  213. GUIContent centerIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Center),
  214. new LocEdString("Center"));
  215. GUIContent moveSnapIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.MoveSnap),
  216. new LocEdString("Move snap"));
  217. GUIContent rotateSnapIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.RotateSnap),
  218. new LocEdString("Rotate snap"));
  219. GUIToggleGroup handlesTG = new GUIToggleGroup();
  220. viewButton = new GUIToggle(viewIcon, handlesTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  221. moveButton = new GUIToggle(moveIcon, handlesTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  222. rotateButton = new GUIToggle(rotateIcon, handlesTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  223. scaleButton = new GUIToggle(scaleIcon, handlesTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  224. GUIToggleGroup coordModeTG = new GUIToggleGroup();
  225. localCoordButton = new GUIToggle(localIcon, coordModeTG, EditorStyles.Button, GUIOption.FlexibleWidth(75));
  226. worldCoordButton = new GUIToggle(worldIcon, coordModeTG, EditorStyles.Button, GUIOption.FlexibleWidth(75));
  227. GUIToggleGroup pivotModeTG = new GUIToggleGroup();
  228. pivotButton = new GUIToggle(pivotIcon, pivotModeTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  229. centerButton = new GUIToggle(centerIcon, pivotModeTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  230. moveSnapButton = new GUIToggle(moveSnapIcon, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  231. moveSnapInput = new GUIFloatField("", GUIOption.FlexibleWidth(35));
  232. rotateSnapButton = new GUIToggle(rotateSnapIcon, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  233. rotateSnapInput = new GUIFloatField("", GUIOption.FlexibleWidth(35));
  234. GUIContent cameraOptionsIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.SceneCameraOptions), new LocEdString("Camera options"));
  235. cameraOptionsButton = new GUIButton(cameraOptionsIcon);
  236. viewButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.View);
  237. moveButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.Move);
  238. rotateButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.Rotate);
  239. scaleButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.Scale);
  240. localCoordButton.OnClick += () => OnCoordinateModeButtonClicked(HandleCoordinateMode.Local);
  241. worldCoordButton.OnClick += () => OnCoordinateModeButtonClicked(HandleCoordinateMode.World);
  242. pivotButton.OnClick += () => OnPivotModeButtonClicked(HandlePivotMode.Pivot);
  243. centerButton.OnClick += () => OnPivotModeButtonClicked(HandlePivotMode.Center);
  244. moveSnapButton.OnToggled += (bool active) => OnMoveSnapToggled(active);
  245. moveSnapInput.OnChanged += (float value) => OnMoveSnapValueChanged(value);
  246. rotateSnapButton.OnToggled += (bool active) => OnRotateSnapToggled(active);
  247. rotateSnapInput.OnChanged += (float value) => OnRotateSnapValueChanged(value);
  248. cameraOptionsButton.OnClick += () => OnCameraOptionsClicked();
  249. GUILayout handlesLayout = mainLayout.AddLayoutX();
  250. handlesLayout.AddElement(viewButton);
  251. handlesLayout.AddElement(moveButton);
  252. handlesLayout.AddElement(rotateButton);
  253. handlesLayout.AddElement(scaleButton);
  254. handlesLayout.AddSpace(10);
  255. handlesLayout.AddElement(localCoordButton);
  256. handlesLayout.AddElement(worldCoordButton);
  257. handlesLayout.AddSpace(10);
  258. handlesLayout.AddElement(pivotButton);
  259. handlesLayout.AddElement(centerButton);
  260. handlesLayout.AddFlexibleSpace();
  261. handlesLayout.AddElement(moveSnapButton);
  262. handlesLayout.AddElement(moveSnapInput);
  263. handlesLayout.AddSpace(10);
  264. handlesLayout.AddElement(rotateSnapButton);
  265. handlesLayout.AddElement(rotateSnapInput);
  266. handlesLayout.AddSpace(10);
  267. handlesLayout.AddElement(cameraOptionsButton);
  268. GUIPanel mainPanel = mainLayout.AddPanel();
  269. rtPanel = mainPanel.AddPanel();
  270. selectionPanel = mainPanel.AddPanel(-1);
  271. GUIPanel sceneAxesPanel = mainPanel.AddPanel(-1);
  272. sceneAxesGUI = new SceneAxesGUI(this, sceneAxesPanel, HandleAxesGUISize, HandleAxesGUISize, 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. viewToolKey = new VirtualButton(ViewToolBinding);
  279. moveToolKey = new VirtualButton(MoveToolBinding);
  280. rotateToolKey = new VirtualButton(RotateToolBinding);
  281. scaleToolKey = new VirtualButton(ScaleToolBinding);
  282. frameKey = new VirtualButton(FrameBinding);
  283. UpdateRenderTexture(Width, Height - HeaderHeight);
  284. }
  285. private void OnCameraOptionsClicked()
  286. {
  287. Vector2I openPosition;
  288. Rect2I buttonBounds = GUIUtility.CalculateBounds(cameraOptionsButton, GUI);
  289. openPosition.x = buttonBounds.x + buttonBounds.width / 2;
  290. openPosition.y = buttonBounds.y + buttonBounds.height / 2;
  291. SceneCameraOptionsDropdown cameraOptionsDropdown = DropDownWindow.Open<SceneCameraOptionsDropdown>(GUI, openPosition);
  292. cameraOptionsDropdown.Initialize(this);
  293. }
  294. private void OnDestroy()
  295. {
  296. if (camera != null)
  297. {
  298. camera.SceneObject.Destroy(true);
  299. camera = null;
  300. }
  301. sceneAxesGUI.Destroy();
  302. sceneAxesGUI = null;
  303. }
  304. /// <summary>
  305. /// Deletes all currently selected objects.
  306. /// </summary>
  307. private void DeleteSelection()
  308. {
  309. SceneObject[] selectedObjects = Selection.SceneObjects;
  310. CleanDuplicates(ref selectedObjects);
  311. if (selectedObjects.Length > 0)
  312. {
  313. foreach (var so in selectedObjects)
  314. {
  315. string message = "Deleted " + so.Name;
  316. UndoRedo.DeleteSO(so, message);
  317. }
  318. EditorApplication.SetSceneDirty();
  319. }
  320. }
  321. /// <summary>
  322. /// Duplicates all currently selected objects.
  323. /// </summary>
  324. private void DuplicateSelection()
  325. {
  326. SceneObject[] selectedObjects = Selection.SceneObjects;
  327. CleanDuplicates(ref selectedObjects);
  328. if (selectedObjects.Length > 0)
  329. {
  330. string message;
  331. if (selectedObjects.Length == 1)
  332. message = "Duplicated " + selectedObjects[0].Name;
  333. else
  334. message = "Duplicated " + selectedObjects.Length + " elements";
  335. Transform[] savedTransforms = new Transform[selectedObjects.Length];
  336. for (int i = 0; i < savedTransforms.Length; i++)
  337. savedTransforms[i] = new Transform(selectedObjects[i]);
  338. SceneObject[] clonedObjects = UndoRedo.CloneSO(selectedObjects, message);
  339. // Restore world positions
  340. for (int i = 0; i < savedTransforms.Length; i++)
  341. savedTransforms[i].Apply(clonedObjects[i]);
  342. EditorApplication.SetSceneDirty();
  343. }
  344. }
  345. /// <inheritdoc/>
  346. void IGlobalShortcuts.OnRenamePressed()
  347. {
  348. // Do nothing
  349. }
  350. /// <inheritdoc/>
  351. void IGlobalShortcuts.OnDuplicatePressed()
  352. {
  353. DuplicateSelection();
  354. }
  355. /// <inheritdoc/>
  356. void IGlobalShortcuts.OnDeletePressed()
  357. {
  358. DeleteSelection();
  359. }
  360. /// <inheritdoc/>
  361. void IGlobalShortcuts.OnCopyPressed()
  362. {
  363. // Do nothing
  364. }
  365. /// <inheritdoc/>
  366. void IGlobalShortcuts.OnCutPressed()
  367. {
  368. // Do nothing
  369. }
  370. /// <inheritdoc/>
  371. void IGlobalShortcuts.OnPastePressed()
  372. {
  373. // Do nothing
  374. }
  375. /// <summary>
  376. /// Orients the camera so it looks along the provided axis.
  377. /// </summary>
  378. /// <param name="axis">Axis to look along.</param>
  379. internal void LookAlong(Vector3 axis)
  380. {
  381. axis.Normalize();
  382. cameraController.LookAlong(axis);
  383. UpdateGridMode();
  384. }
  385. private void UpdateGridMode()
  386. {
  387. Vector3 forward = camera.SceneObject.Forward;
  388. if (camera.ProjectionType == ProjectionType.Perspective)
  389. sceneGrid.SetMode(GridMode.Perspective);
  390. else
  391. {
  392. float dotX = Vector3.Dot(forward, Vector3.XAxis);
  393. if (dotX >= 0.95f)
  394. sceneGrid.SetMode(GridMode.OrthoX);
  395. else if (dotX <= -0.95f)
  396. sceneGrid.SetMode(GridMode.OrthoNegX);
  397. else
  398. {
  399. float dotY = Vector3.Dot(forward, Vector3.YAxis);
  400. if (dotY >= 0.95f)
  401. sceneGrid.SetMode(GridMode.OrthoY);
  402. else if (dotY <= -0.95f)
  403. sceneGrid.SetMode(GridMode.OrthoNegY);
  404. else
  405. {
  406. float dotZ = Vector3.Dot(forward, Vector3.ZAxis);
  407. if (dotZ >= 0.95f)
  408. sceneGrid.SetMode(GridMode.OrthoZ);
  409. else if (dotZ <= -0.95f)
  410. sceneGrid.SetMode(GridMode.OrthoNegZ);
  411. else
  412. sceneGrid.SetMode(GridMode.Perspective);
  413. }
  414. }
  415. }
  416. }
  417. /// <summary>
  418. /// Converts screen coordinates into coordinates relative to the scene view render texture.
  419. /// </summary>
  420. /// <param name="screenPos">Coordinates relative to the screen.</param>
  421. /// <param name="scenePos">Output coordinates relative to the scene view texture.</param>
  422. /// <returns>True if the coordinates are within the scene view texture, false otherwise.</returns>
  423. private bool ScreenToScenePos(Vector2I screenPos, out Vector2I scenePos)
  424. {
  425. scenePos = screenPos;
  426. Vector2I windowPos = ScreenToWindowPos(screenPos);
  427. Rect2I bounds = GUIUtility.CalculateBounds(renderTextureGUI, GUI);
  428. if (bounds.Contains(windowPos))
  429. {
  430. scenePos.x = windowPos.x - bounds.x;
  431. scenePos.y = windowPos.y - bounds.y;
  432. return true;
  433. }
  434. return false;
  435. }
  436. private void OnEditorUpdate()
  437. {
  438. if (HasFocus)
  439. {
  440. if (!Input.IsPointerButtonHeld(PointerButton.Right))
  441. {
  442. if (VirtualInput.IsButtonDown(EditorApplication.DuplicateKey))
  443. DuplicateSelection();
  444. else if (VirtualInput.IsButtonDown(EditorApplication.DeleteKey))
  445. DeleteSelection();
  446. else if (VirtualInput.IsButtonDown(viewToolKey))
  447. EditorApplication.ActiveSceneTool = SceneViewTool.View;
  448. else if (VirtualInput.IsButtonDown(moveToolKey))
  449. EditorApplication.ActiveSceneTool = SceneViewTool.Move;
  450. else if (VirtualInput.IsButtonDown(rotateToolKey))
  451. EditorApplication.ActiveSceneTool = SceneViewTool.Rotate;
  452. else if (VirtualInput.IsButtonDown(scaleToolKey))
  453. EditorApplication.ActiveSceneTool = SceneViewTool.Scale;
  454. }
  455. }
  456. // Refresh GUI buttons if needed (in case someones changes the values from script)
  457. if (editorSettingsHash != EditorSettings.Hash)
  458. {
  459. UpdateButtonStates();
  460. editorSettingsHash = EditorSettings.Hash;
  461. }
  462. // Update scene view handles and selection
  463. sceneGrid.Draw();
  464. bool handleActive = sceneHandles.IsActive() || sceneAxesGUI.IsActive();
  465. Vector2I scenePos;
  466. bool inBounds = ScreenToScenePos(Input.PointerPosition, out scenePos);
  467. bool dragResult = false;
  468. if (Input.IsPointerButtonUp(PointerButton.Left))
  469. {
  470. dragResult = EndDragSelection();
  471. if (sceneHandles.IsActive())
  472. sceneHandles.ClearSelection();
  473. if (sceneAxesGUI.IsActive())
  474. sceneAxesGUI.ClearSelection();
  475. }
  476. else if (Input.IsPointerButtonDown(PointerButton.Left))
  477. {
  478. mouseDownPosition = scenePos;
  479. }
  480. bool draggedOver = DragDrop.DragInProgress || DragDrop.DropInProgress;
  481. draggedOver &= IsPointerHovering && inBounds && DragDrop.Type == DragDropType.Resource;
  482. if (draggedOver)
  483. {
  484. if (DragDrop.DropInProgress)
  485. {
  486. dragActive = false;
  487. if (draggedSO != null)
  488. {
  489. Selection.SceneObject = draggedSO;
  490. EditorApplication.SetSceneDirty();
  491. }
  492. draggedSO = null;
  493. }
  494. else
  495. {
  496. if (!dragActive)
  497. {
  498. dragActive = true;
  499. ResourceDragDropData dragData = (ResourceDragDropData)DragDrop.Data;
  500. string[] draggedPaths = dragData.Paths;
  501. for (int i = 0; i < draggedPaths.Length; i++)
  502. {
  503. ResourceMeta meta = ProjectLibrary.GetMeta(draggedPaths[i]);
  504. if (meta != null)
  505. {
  506. if (meta.ResType == ResourceType.Mesh)
  507. {
  508. if (!string.IsNullOrEmpty(draggedPaths[i]))
  509. {
  510. string meshName = Path.GetFileNameWithoutExtension(draggedPaths[i]);
  511. draggedSO = UndoRedo.CreateSO(meshName, "Created a new Renderable \"" + meshName + "\"");
  512. Mesh mesh = ProjectLibrary.Load<Mesh>(draggedPaths[i]);
  513. Renderable renderable = draggedSO.AddComponent<Renderable>();
  514. renderable.Mesh = mesh;
  515. if (mesh != null)
  516. draggedSOOffset = mesh.Bounds.Box.Center;
  517. else
  518. draggedSOOffset = Vector3.Zero;
  519. }
  520. break;
  521. }
  522. else if (meta.ResType == ResourceType.Prefab)
  523. {
  524. if (!string.IsNullOrEmpty(draggedPaths[i]))
  525. {
  526. Prefab prefab = ProjectLibrary.Load<Prefab>(draggedPaths[i]);
  527. draggedSO = UndoRedo.Instantiate(prefab, "Instantiating " + prefab.Name);
  528. if (draggedSO != null)
  529. {
  530. AABox draggedObjBounds = EditorUtility.CalculateBounds(draggedSO);
  531. draggedSOOffset = draggedObjBounds.Center;
  532. }
  533. else
  534. draggedSOOffset = Vector3.Zero;
  535. }
  536. break;
  537. }
  538. }
  539. }
  540. }
  541. if (draggedSO != null)
  542. {
  543. if (Input.IsButtonHeld(ButtonCode.Space))
  544. {
  545. SnapData snapData;
  546. sceneSelection.Snap(scenePos, out snapData, new SceneObject[] { draggedSO });
  547. Quaternion q = Quaternion.FromToRotation(Vector3.YAxis, snapData.normal);
  548. draggedSO.Position = snapData.position;
  549. draggedSO.Rotation = q;
  550. }
  551. else
  552. {
  553. Ray worldRay = camera.ScreenPointToRay(scenePos);
  554. draggedSO.Position = worldRay * DefaultPlacementDepth - draggedSOOffset;
  555. }
  556. }
  557. }
  558. return;
  559. }
  560. else
  561. {
  562. if (dragActive)
  563. {
  564. dragActive = false;
  565. if (draggedSO != null)
  566. {
  567. draggedSO.Destroy();
  568. draggedSO = null;
  569. }
  570. }
  571. }
  572. if (HasContentFocus || IsPointerHovering)
  573. {
  574. cameraController.EnableInput(true);
  575. if (inBounds && HasContentFocus)
  576. {
  577. if (Input.IsPointerButtonDown(PointerButton.Left))
  578. {
  579. Rect2I sceneAxesGUIBounds = new Rect2I(Width - HandleAxesGUISize - HandleAxesGUIPaddingX,
  580. HandleAxesGUIPaddingY, HandleAxesGUISize, HandleAxesGUISize);
  581. if (sceneAxesGUIBounds.Contains(scenePos))
  582. sceneAxesGUI.TrySelect(scenePos);
  583. else
  584. sceneHandles.TrySelect(scenePos);
  585. }
  586. else if (Input.IsPointerButtonHeld(PointerButton.Left) && !handleActive && !dragActive &&
  587. draggedSO == null && scenePos != mouseDownPosition)
  588. {
  589. if (isDraggingSelection)
  590. UpdateDragSelection(scenePos);
  591. else
  592. StartDragSelection(scenePos);
  593. }
  594. else if (Input.IsPointerButtonUp(PointerButton.Left))
  595. {
  596. if (!handleActive && !dragActive && !dragResult)
  597. {
  598. bool ctrlHeld = Input.IsButtonHeld(ButtonCode.LeftControl) ||
  599. Input.IsButtonHeld(ButtonCode.RightControl);
  600. sceneSelection.PickObject(scenePos, ctrlHeld, new SceneObject[] { draggedSO });
  601. }
  602. }
  603. }
  604. }
  605. else
  606. cameraController.EnableInput(false);
  607. SceneHandles.BeginInput();
  608. sceneHandles.UpdateInput(scenePos, Input.PointerDelta);
  609. sceneAxesGUI.UpdateInput(scenePos);
  610. SceneHandles.EndInput();
  611. sceneHandles.Draw();
  612. sceneAxesGUI.Draw();
  613. // Must be done after handle input is processed, in order to reflect most recent transform
  614. sceneGizmos.Draw();
  615. sceneSelection.Draw();
  616. UpdateGridMode();
  617. if (VirtualInput.IsButtonDown(frameKey))
  618. cameraController.FrameSelected();
  619. }
  620. /// <inheritdoc/>
  621. protected override void WindowResized(int width, int height)
  622. {
  623. UpdateRenderTexture(width, height - HeaderHeight);
  624. base.WindowResized(width, height);
  625. }
  626. /// <inheritdoc/>
  627. protected override void FocusChanged(bool inFocus)
  628. {
  629. if (!inFocus)
  630. {
  631. sceneHandles.ClearSelection();
  632. }
  633. }
  634. /// <summary>
  635. /// Triggered when one of the scene tool buttons is clicked, changing the active scene handle.
  636. /// </summary>
  637. /// <param name="tool">Clicked scene tool to activate.</param>
  638. private void OnSceneToolButtonClicked(SceneViewTool tool)
  639. {
  640. EditorApplication.ActiveSceneTool = tool;
  641. editorSettingsHash = EditorSettings.Hash;
  642. }
  643. /// <summary>
  644. /// Triggered when one of the coordinate mode buttons is clicked, changing the active coordinate mode.
  645. /// </summary>
  646. /// <param name="mode">Clicked coordinate mode to activate.</param>
  647. private void OnCoordinateModeButtonClicked(HandleCoordinateMode mode)
  648. {
  649. EditorApplication.ActiveCoordinateMode = mode;
  650. editorSettingsHash = EditorSettings.Hash;
  651. }
  652. /// <summary>
  653. /// Triggered when one of the pivot buttons is clicked, changing the active pivot mode.
  654. /// </summary>
  655. /// <param name="mode">Clicked pivot mode to activate.</param>
  656. private void OnPivotModeButtonClicked(HandlePivotMode mode)
  657. {
  658. EditorApplication.ActivePivotMode = mode;
  659. editorSettingsHash = EditorSettings.Hash;
  660. }
  661. /// <summary>
  662. /// Triggered when the move snap button is toggled.
  663. /// </summary>
  664. /// <param name="active">Determins should be move snap be activated or deactivated.</param>
  665. private void OnMoveSnapToggled(bool active)
  666. {
  667. Handles.MoveHandleSnapActive = active;
  668. editorSettingsHash = EditorSettings.Hash;
  669. }
  670. /// <summary>
  671. /// Triggered when the move snap increment value changes.
  672. /// </summary>
  673. /// <param name="value">Value that determines in what increments to perform move snapping.</param>
  674. private void OnMoveSnapValueChanged(float value)
  675. {
  676. Handles.MoveSnapAmount = MathEx.Clamp(value, 0.01f, 1000.0f);
  677. editorSettingsHash = EditorSettings.Hash;
  678. }
  679. /// <summary>
  680. /// Triggered when the rotate snap button is toggled.
  681. /// </summary>
  682. /// <param name="active">Determins should be rotate snap be activated or deactivated.</param>
  683. private void OnRotateSnapToggled(bool active)
  684. {
  685. Handles.RotateHandleSnapActive = active;
  686. editorSettingsHash = EditorSettings.Hash;
  687. }
  688. /// <summary>
  689. /// Triggered when the rotate snap increment value changes.
  690. /// </summary>
  691. /// <param name="value">Value that determines in what increments to perform rotate snapping.</param>
  692. private void OnRotateSnapValueChanged(float value)
  693. {
  694. Handles.RotateSnapAmount = (Degree)MathEx.Clamp(value, 0.01f, 360.0f);
  695. editorSettingsHash = EditorSettings.Hash;
  696. }
  697. /// <summary>
  698. /// Updates toggle button states according to current editor options. This is useful if tools, coordinate mode,
  699. /// pivot or other scene view options have been modified externally.
  700. /// </summary>
  701. private void UpdateButtonStates()
  702. {
  703. switch (EditorApplication.ActiveSceneTool)
  704. {
  705. case SceneViewTool.View:
  706. viewButton.Value = true;
  707. break;
  708. case SceneViewTool.Move:
  709. moveButton.Value = true;
  710. break;
  711. case SceneViewTool.Rotate:
  712. rotateButton.Value = true;
  713. break;
  714. case SceneViewTool.Scale:
  715. scaleButton.Value = true;
  716. break;
  717. }
  718. switch (EditorApplication.ActiveCoordinateMode)
  719. {
  720. case HandleCoordinateMode.Local:
  721. localCoordButton.Value = true;
  722. break;
  723. case HandleCoordinateMode.World:
  724. worldCoordButton.Value = true;
  725. break;
  726. }
  727. switch (EditorApplication.ActivePivotMode)
  728. {
  729. case HandlePivotMode.Center:
  730. centerButton.Value = true;
  731. break;
  732. case HandlePivotMode.Pivot:
  733. pivotButton.Value = true;
  734. break;
  735. }
  736. if (Handles.MoveHandleSnapActive)
  737. moveSnapButton.Value = true;
  738. else
  739. moveSnapButton.Value = false;
  740. moveSnapInput.Value = Handles.MoveSnapAmount;
  741. if (Handles.RotateHandleSnapActive)
  742. rotateSnapButton.Value = true;
  743. else
  744. rotateSnapButton.Value = false;
  745. moveSnapInput.Value = Handles.RotateSnapAmount.Degrees;
  746. }
  747. /// <summary>
  748. /// Creates the scene camera and updates the render texture. Should be called at least once before using the
  749. /// scene view. Should be called whenever the window is resized.
  750. /// </summary>
  751. /// <param name="width">Width of the scene render target, in pixels.</param>
  752. /// <param name="height">Height of the scene render target, in pixels.</param>
  753. private void UpdateRenderTexture(int width, int height)
  754. {
  755. width = MathEx.Max(20, width);
  756. height = MathEx.Max(20, height);
  757. // Note: Depth buffer and readable flags are required because ScenePicking uses it
  758. Texture colorTex = Texture.Create2D((uint)width, (uint)height, PixelFormat.RGBA8, TextureUsage.Render | TextureUsage.CPUReadable);
  759. Texture depthTex = Texture.Create2D((uint)width, (uint)height, PixelFormat.D32_S8X24, TextureUsage.DepthStencil | TextureUsage.CPUReadable);
  760. renderTexture = new RenderTexture(colorTex, depthTex);
  761. renderTexture.Priority = 1;
  762. if (camera == null)
  763. {
  764. SceneObject sceneCameraSO = new SceneObject("SceneCamera", true);
  765. camera = sceneCameraSO.AddComponent<Camera>();
  766. camera.Viewport.Target = renderTexture;
  767. camera.Viewport.Area = new Rect2(0.0f, 0.0f, 1.0f, 1.0f);
  768. sceneCameraSO.Position = new Vector3(0, 0.5f, 1);
  769. sceneCameraSO.LookAt(new Vector3(0, 0.5f, 0));
  770. camera.Priority = 2;
  771. camera.Viewport.ClearColor = ClearColor;
  772. camera.Layers = UInt64.MaxValue & ~SceneAxesHandle.LAYER; // Don't draw scene axes in this camera
  773. cameraController = sceneCameraSO.AddComponent<SceneCamera>();
  774. cameraController.Initialize();
  775. renderTextureGUI = new GUIRenderTexture(renderTexture);
  776. rtPanel.AddElement(renderTextureGUI);
  777. sceneGrid = new SceneGrid(camera);
  778. sceneSelection = new SceneSelection(camera);
  779. sceneGizmos = new SceneGizmos(camera);
  780. sceneHandles = new SceneHandles(this, camera);
  781. }
  782. else
  783. {
  784. camera.Viewport.Target = renderTexture;
  785. renderTextureGUI.RenderTexture = renderTexture;
  786. }
  787. Rect2I rtBounds = new Rect2I(0, 0, width, height);
  788. renderTextureGUI.Bounds = rtBounds;
  789. focusCatcher.Bounds = GUIUtility.CalculateBounds(rtPanel, GUI);
  790. sceneAxesGUI.SetPosition(width - HandleAxesGUISize - HandleAxesGUIPaddingX, HandleAxesGUIPaddingY);
  791. // TODO - Consider only doing the resize once user stops resizing the widget in order to reduce constant
  792. // render target destroy/create cycle for every single pixel.
  793. camera.AspectRatio = width / (float)height;
  794. }
  795. /// <summary>
  796. /// Parses an array of scene objects and removes elements that are children of elements that are also in the array.
  797. /// </summary>
  798. /// <param name="objects">Array containing duplicate objects as input, and array without duplicate objects as
  799. /// output.</param>
  800. private void CleanDuplicates(ref SceneObject[] objects)
  801. {
  802. List<SceneObject> cleanList = new List<SceneObject>();
  803. for (int i = 0; i < objects.Length; i++)
  804. {
  805. bool foundParent = false;
  806. for (int j = 0; j < objects.Length; j++)
  807. {
  808. SceneObject elem = objects[i];
  809. while (elem != null && elem != objects[j])
  810. elem = elem.Parent;
  811. bool isChildOf = elem == objects[j];
  812. if (i != j && isChildOf)
  813. {
  814. foundParent = true;
  815. break;
  816. }
  817. }
  818. if (!foundParent)
  819. cleanList.Add(objects[i]);
  820. }
  821. objects = cleanList.ToArray();
  822. }
  823. /// <summary>
  824. /// Starts a drag operation that displays a selection outline allowing the user to select multiple entries at once.
  825. /// </summary>
  826. /// <param name="scenePos">Coordinates relative to the scene where the drag originated.</param>
  827. private void StartDragSelection(Vector2I scenePos)
  828. {
  829. isDraggingSelection = true;
  830. dragSelectionStart = scenePos;
  831. dragSelectionEnd = dragSelectionStart;
  832. }
  833. /// <summary>
  834. /// Updates a selection outline drag operation by expanding the outline to the new location. Elements in the outline
  835. /// are selected.
  836. /// </summary>
  837. /// <param name="scenePos">Coordinates of the pointer relative to the scene.</param>
  838. /// <returns>True if the selection outline drag is valid and was updated, false otherwise.</returns>
  839. private bool UpdateDragSelection(Vector2I scenePos)
  840. {
  841. if (!isDraggingSelection)
  842. return false;
  843. if (dragSelection == null)
  844. {
  845. dragSelection = new GUITexture(null, true, EditorStylesInternal.SelectionArea);
  846. selectionPanel.AddElement(dragSelection);
  847. }
  848. dragSelectionEnd = scenePos;
  849. Rect2I selectionArea = new Rect2I();
  850. Vector2I min = new Vector2I(Math.Min(dragSelectionStart.x, dragSelectionEnd.x), Math.Min(dragSelectionStart.y, dragSelectionEnd.y));
  851. Vector2I max = new Vector2I(Math.Max(dragSelectionStart.x, dragSelectionEnd.x), Math.Max(dragSelectionStart.y, dragSelectionEnd.y));
  852. selectionArea.x = min.x;
  853. selectionArea.y = min.y;
  854. selectionArea.width = Math.Max(max.x - min.x, 1);
  855. selectionArea.height = Math.Max(max.y - min.y, 1);
  856. dragSelection.Bounds = selectionArea;
  857. return true;
  858. }
  859. /// <summary>
  860. /// Ends the selection outline drag operation. Elements in the outline are selected.
  861. /// </summary>
  862. /// <returns>True if the selection outline drag is valid and was ended, false otherwise.</returns>
  863. private bool EndDragSelection()
  864. {
  865. if (!isDraggingSelection)
  866. return false;
  867. if (dragSelection != null)
  868. {
  869. dragSelection.Destroy();
  870. dragSelection = null;
  871. }
  872. if ((dragSelectionEnd - dragSelectionStart).Length < 1)
  873. {
  874. isDraggingSelection = false;
  875. return false;
  876. }
  877. Vector2I min = new Vector2I(Math.Min(dragSelectionStart.x, dragSelectionEnd.x),
  878. Math.Min(dragSelectionStart.y, dragSelectionEnd.y));
  879. Vector2I max = new Vector2I(Math.Max(dragSelectionStart.x, dragSelectionEnd.x),
  880. Math.Max(dragSelectionStart.y, dragSelectionEnd.y));
  881. sceneSelection.PickObjects(min, max - min,
  882. Input.IsButtonHeld(ButtonCode.LeftControl) || Input.IsButtonHeld(ButtonCode.RightControl));
  883. isDraggingSelection = false;
  884. return true;
  885. }
  886. /// <summary>
  887. /// Contains information about world transform of a single scene object.
  888. /// </summary>
  889. struct Transform
  890. {
  891. public Transform(SceneObject so)
  892. {
  893. position = so.Position;
  894. rotation = so.Rotation;
  895. scale = so.Scale;
  896. }
  897. /// <summary>
  898. /// Applies the saved transform to the specified scene object. The transform is assumed to be in world space.
  899. /// </summary>
  900. /// <param name="so">Scene object to apply the transform to.</param>
  901. public void Apply(SceneObject so)
  902. {
  903. so.Position = position;
  904. so.Rotation = rotation;
  905. so.LocalScale = scale;
  906. }
  907. public Vector3 position;
  908. public Quaternion rotation;
  909. public Vector3 scale;
  910. }
  911. }
  912. /** @} */
  913. }