SceneWindow.cs 40 KB

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