SceneWindow.cs 41 KB

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