SceneWindow.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  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. var snappedTo = sceneSelection.Snap(scenePos, out snapData, new SceneObject[] {draggedSO});
  504. if (snappedTo != null)
  505. {
  506. Quaternion q = Quaternion.FromToRotation(Vector3.YAxis, snapData.normal);
  507. draggedSO.Position = snapData.position;
  508. draggedSO.Rotation = q;
  509. }
  510. else
  511. {
  512. Ray worldRay = camera.ViewportToWorldRay(scenePos);
  513. draggedSO.Position = worldRay * DefaultPlacementDepth - draggedSOOffset;
  514. draggedSO.Rotation = Quaternion.LookRotation(Vector3.YAxis);
  515. }
  516. }
  517. else
  518. {
  519. Ray worldRay = camera.ViewportToWorldRay(scenePos);
  520. draggedSO.Position = worldRay * DefaultPlacementDepth - draggedSOOffset;
  521. }
  522. }
  523. }
  524. return;
  525. }
  526. else
  527. {
  528. if (dragActive)
  529. {
  530. dragActive = false;
  531. if (draggedSO != null)
  532. {
  533. draggedSO.Destroy();
  534. draggedSO = null;
  535. }
  536. }
  537. }
  538. if (HasContentFocus || IsPointerHovering)
  539. {
  540. cameraController.EnableInput(true);
  541. if (inBounds && HasContentFocus)
  542. {
  543. bool newHandle = false;
  544. SceneHandles.BeginInput();
  545. newHandle = sceneHandles.IsActive();
  546. SceneHandles.EndInput();
  547. if (Input.IsPointerButtonDown(PointerButton.Left))
  548. {
  549. Rect2I sceneAxesGUIBounds = new Rect2I(Width - HandleAxesGUISize - HandleAxesGUIPaddingX,
  550. HandleAxesGUIPaddingY, HandleAxesGUISize, HandleAxesGUISize);
  551. if (sceneAxesGUIBounds.Contains(scenePos))
  552. sceneAxesGUI.TrySelect(scenePos);
  553. else
  554. sceneHandles.TrySelect(scenePos);
  555. }
  556. else if (Input.IsPointerButtonHeld(PointerButton.Left) && !newHandle && !dragActive &&
  557. draggedSO == null && scenePos != mouseDownPosition)
  558. {
  559. if (isDraggingSelection)
  560. UpdateDragSelection(scenePos);
  561. else
  562. StartDragSelection(scenePos);
  563. }
  564. else if (Input.IsPointerButtonUp(PointerButton.Left))
  565. {
  566. if (!handleActive && !dragActive && !dragResult)
  567. {
  568. bool ctrlHeld = Input.IsButtonHeld(ButtonCode.LeftControl) ||
  569. Input.IsButtonHeld(ButtonCode.RightControl);
  570. sceneSelection.PickObject(scenePos, ctrlHeld, new SceneObject[] {draggedSO});
  571. }
  572. }
  573. }
  574. }
  575. else
  576. cameraController.EnableInput(false);
  577. SceneHandles.BeginInput();
  578. sceneHandles.UpdateInput(scenePos, Input.PointerDelta);
  579. sceneHandles.Draw();
  580. sceneAxesGUI.UpdateInput(scenePos);
  581. sceneAxesGUI.Draw();
  582. SceneHandles.EndInput();
  583. sceneSelection.Draw();
  584. UpdateGridMode();
  585. if (VirtualInput.IsButtonDown(frameKey))
  586. cameraController.FrameSelected();
  587. }
  588. /// <inheritdoc/>
  589. protected override void WindowResized(int width, int height)
  590. {
  591. UpdateRenderTexture(width, height - HeaderHeight);
  592. base.WindowResized(width, height);
  593. }
  594. /// <inheritdoc/>
  595. protected override void FocusChanged(bool inFocus)
  596. {
  597. if (!inFocus)
  598. {
  599. sceneHandles.ClearSelection();
  600. }
  601. }
  602. /// <summary>
  603. /// Triggered when one of the scene tool buttons is clicked, changing the active scene handle.
  604. /// </summary>
  605. /// <param name="tool">Clicked scene tool to activate.</param>
  606. private void OnSceneToolButtonClicked(SceneViewTool tool)
  607. {
  608. EditorApplication.ActiveSceneTool = tool;
  609. editorSettingsHash = EditorSettings.Hash;
  610. }
  611. /// <summary>
  612. /// Triggered when one of the coordinate mode buttons is clicked, changing the active coordinate mode.
  613. /// </summary>
  614. /// <param name="mode">Clicked coordinate mode to activate.</param>
  615. private void OnCoordinateModeButtonClicked(HandleCoordinateMode mode)
  616. {
  617. EditorApplication.ActiveCoordinateMode = mode;
  618. editorSettingsHash = EditorSettings.Hash;
  619. }
  620. /// <summary>
  621. /// Triggered when one of the pivot buttons is clicked, changing the active pivot mode.
  622. /// </summary>
  623. /// <param name="mode">Clicked pivot mode to activate.</param>
  624. private void OnPivotModeButtonClicked(HandlePivotMode mode)
  625. {
  626. EditorApplication.ActivePivotMode = mode;
  627. editorSettingsHash = EditorSettings.Hash;
  628. }
  629. /// <summary>
  630. /// Triggered when the move snap button is toggled.
  631. /// </summary>
  632. /// <param name="active">Determins should be move snap be activated or deactivated.</param>
  633. private void OnMoveSnapToggled(bool active)
  634. {
  635. Handles.MoveHandleSnapActive = active;
  636. editorSettingsHash = EditorSettings.Hash;
  637. }
  638. /// <summary>
  639. /// Triggered when the move snap increment value changes.
  640. /// </summary>
  641. /// <param name="value">Value that determines in what increments to perform move snapping.</param>
  642. private void OnMoveSnapValueChanged(float value)
  643. {
  644. Handles.MoveSnapAmount = MathEx.Clamp(value, 0.01f, 1000.0f);
  645. editorSettingsHash = EditorSettings.Hash;
  646. }
  647. /// <summary>
  648. /// Triggered when the rotate snap button is toggled.
  649. /// </summary>
  650. /// <param name="active">Determins should be rotate snap be activated or deactivated.</param>
  651. private void OnRotateSnapToggled(bool active)
  652. {
  653. Handles.RotateHandleSnapActive = active;
  654. editorSettingsHash = EditorSettings.Hash;
  655. }
  656. /// <summary>
  657. /// Triggered when the rotate snap increment value changes.
  658. /// </summary>
  659. /// <param name="value">Value that determines in what increments to perform rotate snapping.</param>
  660. private void OnRotateSnapValueChanged(float value)
  661. {
  662. Handles.RotateSnapAmount = (Degree)MathEx.Clamp(value, 0.01f, 360.0f);
  663. editorSettingsHash = EditorSettings.Hash;
  664. }
  665. /// <summary>
  666. /// Updates toggle button states according to current editor options. This is useful if tools, coordinate mode,
  667. /// pivot or other scene view options have been modified externally.
  668. /// </summary>
  669. private void UpdateButtonStates()
  670. {
  671. switch (EditorApplication.ActiveSceneTool)
  672. {
  673. case SceneViewTool.View:
  674. viewButton.Value = true;
  675. break;
  676. case SceneViewTool.Move:
  677. moveButton.Value = true;
  678. break;
  679. case SceneViewTool.Rotate:
  680. rotateButton.Value = true;
  681. break;
  682. case SceneViewTool.Scale:
  683. scaleButton.Value = true;
  684. break;
  685. }
  686. switch (EditorApplication.ActiveCoordinateMode)
  687. {
  688. case HandleCoordinateMode.Local:
  689. localCoordButton.Value = true;
  690. break;
  691. case HandleCoordinateMode.World:
  692. worldCoordButton.Value = true;
  693. break;
  694. }
  695. switch (EditorApplication.ActivePivotMode)
  696. {
  697. case HandlePivotMode.Center:
  698. centerButton.Value = true;
  699. break;
  700. case HandlePivotMode.Pivot:
  701. pivotButton.Value = true;
  702. break;
  703. }
  704. if (Handles.MoveHandleSnapActive)
  705. moveSnapButton.Value = true;
  706. else
  707. moveSnapButton.Value = false;
  708. moveSnapInput.Value = Handles.MoveSnapAmount;
  709. if (Handles.RotateHandleSnapActive)
  710. rotateSnapButton.Value = true;
  711. else
  712. rotateSnapButton.Value = false;
  713. moveSnapInput.Value = Handles.RotateSnapAmount.Degrees;
  714. }
  715. /// <summary>
  716. /// Activates or deactivates the profiler overlay according to current editor settings.
  717. /// </summary>
  718. private void UpdateProfilerOverlay()
  719. {
  720. if (EditorSettings.GetBool(ProfilerOverlayActiveKey))
  721. {
  722. if (activeProfilerOverlay == null)
  723. {
  724. SceneObject profilerSO = new SceneObject("EditorProfilerOverlay");
  725. profilerCamera = profilerSO.AddComponent<Camera>();
  726. profilerCamera.Target = renderTexture;
  727. profilerCamera.ClearFlags = ClearFlags.None;
  728. profilerCamera.Priority = 1;
  729. profilerCamera.Layers = 0;
  730. profilerCamera.HDR = false;
  731. activeProfilerOverlay = profilerSO.AddComponent<ProfilerOverlay>();
  732. }
  733. }
  734. else
  735. {
  736. if (activeProfilerOverlay != null)
  737. {
  738. activeProfilerOverlay.SceneObject.Destroy();
  739. activeProfilerOverlay = null;
  740. profilerCamera = null;
  741. }
  742. }
  743. }
  744. /// <summary>
  745. /// Creates the scene camera and updates the render texture. Should be called at least once before using the
  746. /// scene view. Should be called whenever the window is resized.
  747. /// </summary>
  748. /// <param name="width">Width of the scene render target, in pixels.</param>
  749. /// <param name="height">Height of the scene render target, in pixels.</param>
  750. private void UpdateRenderTexture(int width, int height)
  751. {
  752. width = MathEx.Max(20, width);
  753. height = MathEx.Max(20, height);
  754. // Note: Depth buffer is required because ScenePicking uses it
  755. renderTexture = new RenderTexture2D(PixelFormat.R8G8B8A8, width, height, 1, false, true);
  756. renderTexture.Priority = 1;
  757. if (camera == null)
  758. {
  759. SceneObject sceneCameraSO = new SceneObject("SceneCamera", true);
  760. camera = sceneCameraSO.AddComponent<Camera>();
  761. camera.Target = renderTexture;
  762. camera.ViewportRect = new Rect2(0.0f, 0.0f, 1.0f, 1.0f);
  763. sceneCameraSO.Position = new Vector3(0, 0.5f, 1);
  764. sceneCameraSO.LookAt(new Vector3(0, 0.5f, 0));
  765. camera.Priority = 2;
  766. camera.NearClipPlane = 0.05f;
  767. camera.FarClipPlane = 2500.0f;
  768. camera.ClearColor = ClearColor;
  769. camera.Layers = UInt64.MaxValue & ~SceneAxesHandle.LAYER; // Don't draw scene axes in this camera
  770. cameraController = sceneCameraSO.AddComponent<SceneCamera>();
  771. renderTextureGUI = new GUIRenderTexture(renderTexture);
  772. rtPanel.AddElement(renderTextureGUI);
  773. sceneGrid = new SceneGrid(camera);
  774. sceneSelection = new SceneSelection(camera);
  775. sceneGizmos = new SceneGizmos(camera);
  776. sceneHandles = new SceneHandles(this, camera);
  777. }
  778. else
  779. {
  780. camera.Target = renderTexture;
  781. renderTextureGUI.RenderTexture = renderTexture;
  782. }
  783. Rect2I rtBounds = new Rect2I(0, 0, width, height);
  784. renderTextureGUI.Bounds = rtBounds;
  785. focusCatcher.Bounds = GUIUtility.CalculateBounds(rtPanel, GUI);
  786. sceneAxesGUI.SetPosition(width - HandleAxesGUISize - HandleAxesGUIPaddingX, HandleAxesGUIPaddingY);
  787. // TODO - Consider only doing the resize once user stops resizing the widget in order to reduce constant
  788. // render target destroy/create cycle for every single pixel.
  789. camera.AspectRatio = width / (float)height;
  790. if (profilerCamera != null)
  791. profilerCamera.Target = renderTexture;
  792. }
  793. /// <summary>
  794. /// Parses an array of scene objects and removes elements that are children of elements that are also in the array.
  795. /// </summary>
  796. /// <param name="objects">Array containing duplicate objects as input, and array without duplicate objects as
  797. /// output.</param>
  798. private void CleanDuplicates(ref SceneObject[] objects)
  799. {
  800. List<SceneObject> cleanList = new List<SceneObject>();
  801. for (int i = 0; i < objects.Length; i++)
  802. {
  803. bool foundParent = false;
  804. for (int j = 0; j < objects.Length; j++)
  805. {
  806. SceneObject elem = objects[i];
  807. while (elem != null && elem != objects[j])
  808. elem = elem.Parent;
  809. bool isChildOf = elem == objects[j];
  810. if (i != j && isChildOf)
  811. {
  812. foundParent = true;
  813. break;
  814. }
  815. }
  816. if (!foundParent)
  817. cleanList.Add(objects[i]);
  818. }
  819. objects = cleanList.ToArray();
  820. }
  821. /// <summary>
  822. /// Starts a drag operation that displays a selection outline allowing the user to select multiple entries at once.
  823. /// </summary>
  824. /// <param name="scenePos">Coordinates relative to the scene where the drag originated.</param>
  825. private void StartDragSelection(Vector2I scenePos)
  826. {
  827. isDraggingSelection = true;
  828. dragSelectionStart = scenePos;
  829. dragSelectionEnd = dragSelectionStart;
  830. }
  831. /// <summary>
  832. /// Updates a selection outline drag operation by expanding the outline to the new location. Elements in the outline
  833. /// are selected.
  834. /// </summary>
  835. /// <param name="scenePos">Coordinates of the pointer relative to the scene.</param>
  836. /// <returns>True if the selection outline drag is valid and was updated, false otherwise.</returns>
  837. private bool UpdateDragSelection(Vector2I scenePos)
  838. {
  839. if (!isDraggingSelection)
  840. return false;
  841. if (dragSelection == null)
  842. {
  843. dragSelection = new GUITexture(null, true, EditorStylesInternal.SelectionArea);
  844. selectionPanel.AddElement(dragSelection);
  845. }
  846. dragSelectionEnd = scenePos;
  847. Rect2I selectionArea = new Rect2I();
  848. Vector2I min = new Vector2I(Math.Min(dragSelectionStart.x, dragSelectionEnd.x), Math.Min(dragSelectionStart.y, dragSelectionEnd.y));
  849. Vector2I max = new Vector2I(Math.Max(dragSelectionStart.x, dragSelectionEnd.x), Math.Max(dragSelectionStart.y, dragSelectionEnd.y));
  850. selectionArea.x = min.x;
  851. selectionArea.y = min.y;
  852. selectionArea.width = Math.Max(max.x - min.x, 1);
  853. selectionArea.height = Math.Max(max.y - min.y, 1);
  854. dragSelection.Bounds = selectionArea;
  855. return true;
  856. }
  857. /// <summary>
  858. /// Ends the selection outline drag operation. Elements in the outline are selected.
  859. /// </summary>
  860. /// <returns>True if the selection outline drag is valid and was ended, false otherwise.</returns>
  861. private bool EndDragSelection()
  862. {
  863. if (!isDraggingSelection)
  864. return false;
  865. if (dragSelection != null)
  866. {
  867. dragSelection.Destroy();
  868. dragSelection = null;
  869. }
  870. if ((dragSelectionEnd - dragSelectionStart).Length < 1)
  871. {
  872. isDraggingSelection = false;
  873. return false;
  874. }
  875. Vector2I min = new Vector2I(Math.Min(dragSelectionStart.x, dragSelectionEnd.x),
  876. Math.Min(dragSelectionStart.y, dragSelectionEnd.y));
  877. Vector2I max = new Vector2I(Math.Max(dragSelectionStart.x, dragSelectionEnd.x),
  878. Math.Max(dragSelectionStart.y, dragSelectionEnd.y));
  879. sceneSelection.PickObjects(min, max - min,
  880. Input.IsButtonHeld(ButtonCode.LeftControl) || Input.IsButtonHeld(ButtonCode.RightControl));
  881. isDraggingSelection = false;
  882. return true;
  883. }
  884. }
  885. /** @} */
  886. }