SceneWindow.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  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. public SceneSelection sceneSelection;
  24. private const int HeaderHeight = 20;
  25. private const float DefaultPlacementDepth = 5.0f;
  26. private static readonly Color ClearColor = new Color(83.0f/255.0f, 83.0f/255.0f, 83.0f/255.0f);
  27. private const string ProfilerOverlayActiveKey = "_Internal_ProfilerOverlayActive";
  28. private const int HandleAxesGUISize = 50;
  29. private const int HandleAxesGUIPaddingX = 10;
  30. private const int HandleAxesGUIPaddingY = 5;
  31. private Camera camera;
  32. private SceneCamera cameraController;
  33. private RenderTexture2D renderTexture;
  34. private GUILayoutY mainLayout;
  35. private GUIPanel rtPanel;
  36. private GUIButton focusCatcher;
  37. private GUIRenderTexture renderTextureGUI;
  38. private SceneGrid sceneGrid;
  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();
  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. UndoRedo.CloneSO(selectedObjects, message);
  288. EditorApplication.SetSceneDirty();
  289. }
  290. }
  291. /// <inheritdoc/>
  292. void IGlobalShortcuts.OnRenamePressed()
  293. {
  294. // Do nothing
  295. }
  296. /// <inheritdoc/>
  297. void IGlobalShortcuts.OnDuplicatePressed()
  298. {
  299. DuplicateSelection();
  300. }
  301. /// <inheritdoc/>
  302. void IGlobalShortcuts.OnDeletePressed()
  303. {
  304. DeleteSelection();
  305. }
  306. /// <inheritdoc/>
  307. void IGlobalShortcuts.OnCopyPressed()
  308. {
  309. // Do nothing
  310. }
  311. /// <inheritdoc/>
  312. void IGlobalShortcuts.OnCutPressed()
  313. {
  314. // Do nothing
  315. }
  316. /// <inheritdoc/>
  317. void IGlobalShortcuts.OnPastePressed()
  318. {
  319. // Do nothing
  320. }
  321. /// <summary>
  322. /// Orients the camera so it looks along the provided axis.
  323. /// </summary>
  324. /// <param name="axis">Axis to look along.</param>
  325. internal void LookAlong(Vector3 axis)
  326. {
  327. axis.Normalize();
  328. cameraController.LookAlong(axis);
  329. UpdateGridMode();
  330. }
  331. private void UpdateGridMode()
  332. {
  333. Vector3 forward = camera.SceneObject.Forward;
  334. if (camera.ProjectionType == ProjectionType.Perspective)
  335. sceneGrid.SetMode(GridMode.Perspective);
  336. else
  337. {
  338. float dotX = Vector3.Dot(forward, Vector3.XAxis);
  339. if (dotX >= 0.95f)
  340. sceneGrid.SetMode(GridMode.OrthoX);
  341. else if (dotX <= -0.95f)
  342. sceneGrid.SetMode(GridMode.OrthoNegX);
  343. else
  344. {
  345. float dotY = Vector3.Dot(forward, Vector3.YAxis);
  346. if (dotY >= 0.95f)
  347. sceneGrid.SetMode(GridMode.OrthoY);
  348. else if (dotY <= -0.95f)
  349. sceneGrid.SetMode(GridMode.OrthoNegY);
  350. else
  351. {
  352. float dotZ = Vector3.Dot(forward, Vector3.ZAxis);
  353. if (dotZ >= 0.95f)
  354. sceneGrid.SetMode(GridMode.OrthoZ);
  355. else if (dotZ <= -0.95f)
  356. sceneGrid.SetMode(GridMode.OrthoNegZ);
  357. else
  358. sceneGrid.SetMode(GridMode.Perspective);
  359. }
  360. }
  361. }
  362. }
  363. /// <summary>
  364. /// Converts screen coordinates into coordinates relative to the scene view render texture.
  365. /// </summary>
  366. /// <param name="screenPos">Coordinates relative to the screen.</param>
  367. /// <param name="scenePos">Output coordinates relative to the scene view texture.</param>
  368. /// <returns>True if the coordinates are within the scene view texture, false otherwise.</returns>
  369. public bool ScreenToScenePos(Vector2I screenPos, out Vector2I scenePos)
  370. {
  371. scenePos = screenPos;
  372. Vector2I windowPos = ScreenToWindowPos(screenPos);
  373. Rect2I bounds = GUIUtility.CalculateBounds(renderTextureGUI, GUI);
  374. if (bounds.Contains(windowPos))
  375. {
  376. scenePos.x = windowPos.x - bounds.x;
  377. scenePos.y = windowPos.y - bounds.y;
  378. return true;
  379. }
  380. return false;
  381. }
  382. private void OnEditorUpdate()
  383. {
  384. if (HasFocus)
  385. {
  386. if (!Input.IsPointerButtonHeld(PointerButton.Right))
  387. {
  388. if (VirtualInput.IsButtonDown(EditorApplication.DuplicateKey))
  389. DuplicateSelection();
  390. else if (VirtualInput.IsButtonDown(EditorApplication.DeleteKey))
  391. DeleteSelection();
  392. else if (VirtualInput.IsButtonDown(toggleProfilerOverlayKey))
  393. EditorSettings.SetBool(ProfilerOverlayActiveKey, !EditorSettings.GetBool(ProfilerOverlayActiveKey));
  394. else if(VirtualInput.IsButtonDown(viewToolKey))
  395. EditorApplication.ActiveSceneTool = SceneViewTool.View;
  396. else if(VirtualInput.IsButtonDown(moveToolKey))
  397. EditorApplication.ActiveSceneTool = SceneViewTool.Move;
  398. else if(VirtualInput.IsButtonDown(rotateToolKey))
  399. EditorApplication.ActiveSceneTool = SceneViewTool.Rotate;
  400. else if(VirtualInput.IsButtonDown(scaleToolKey))
  401. EditorApplication.ActiveSceneTool = SceneViewTool.Scale;
  402. }
  403. }
  404. // Refresh GUI buttons if needed (in case someones changes the values from script)
  405. if (editorSettingsHash != EditorSettings.Hash)
  406. {
  407. UpdateButtonStates();
  408. UpdateProfilerOverlay();
  409. editorSettingsHash = EditorSettings.Hash;
  410. }
  411. // Update scene view handles and selection
  412. sceneGizmos.Draw();
  413. sceneGrid.Draw();
  414. bool dragResult = false;
  415. bool handleActive = false;
  416. Vector2I scenePos;
  417. bool inBounds = ScreenToScenePos(Input.PointerPosition, out scenePos);
  418. if (Input.IsPointerButtonUp(PointerButton.Left))
  419. {
  420. dragResult = EndDragSelection();
  421. if (sceneHandles.IsActive())
  422. {
  423. sceneHandles.ClearSelection();
  424. handleActive = true;
  425. }
  426. if (sceneAxesGUI.IsActive())
  427. {
  428. sceneAxesGUI.ClearSelection();
  429. handleActive = true;
  430. }
  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. var snappedTo = sceneSelection.Snap(scenePos, out snapData, new SceneObject[] {draggedSO});
  503. if (snappedTo != null)
  504. {
  505. Quaternion q = Quaternion.FromToRotation(Vector3.YAxis, snapData.normal);
  506. draggedSO.Position = snapData.position;
  507. draggedSO.Rotation = q;
  508. }
  509. else
  510. {
  511. Ray worldRay = camera.ViewportToWorldRay(scenePos);
  512. Vector3 pos = worldRay*DefaultPlacementDepth - draggedSOOffset;
  513. float interval = EditorSettings.MoveHandleSnapAmount;
  514. if (EditorSettings.MoveHandleSnapActive)
  515. draggedSO.Position = new Vector3(pos.x - (pos.x % interval), pos.y - (pos.y % interval),
  516. pos.z - (pos.z % interval));
  517. else
  518. draggedSO.Position = new Vector3(pos.x, pos.y - (pos.y % interval), pos.z);
  519. draggedSO.Rotation = Quaternion.LookRotation(Vector3.YAxis);
  520. }
  521. }
  522. else
  523. {
  524. Ray worldRay = camera.ViewportToWorldRay(scenePos);
  525. draggedSO.Position = worldRay * DefaultPlacementDepth - draggedSOOffset;
  526. }
  527. }
  528. }
  529. return;
  530. }
  531. else
  532. {
  533. if (dragActive)
  534. {
  535. dragActive = false;
  536. if (draggedSO != null)
  537. {
  538. draggedSO.Destroy();
  539. draggedSO = null;
  540. }
  541. }
  542. }
  543. if (HasContentFocus || IsPointerHovering)
  544. {
  545. cameraController.EnableInput(true);
  546. if (inBounds && HasContentFocus)
  547. {
  548. if (Input.IsPointerButtonDown(PointerButton.Left))
  549. {
  550. Rect2I sceneAxesGUIBounds = new Rect2I(Width - HandleAxesGUISize - HandleAxesGUIPaddingX,
  551. HandleAxesGUIPaddingY, HandleAxesGUISize, HandleAxesGUISize);
  552. if (sceneAxesGUIBounds.Contains(scenePos))
  553. sceneAxesGUI.TrySelect(scenePos);
  554. else
  555. sceneHandles.TrySelect(scenePos);
  556. }
  557. else if (Input.IsPointerButtonHeld(PointerButton.Left) && !handleActive && !dragActive &&
  558. draggedSO == null && scenePos != mouseDownPosition)
  559. {
  560. if (isDraggingSelection)
  561. UpdateDragSelection(scenePos);
  562. else
  563. StartDragSelection(scenePos);
  564. }
  565. else if (Input.IsPointerButtonUp(PointerButton.Left))
  566. {
  567. if (!handleActive && !dragActive && !dragResult)
  568. {
  569. bool ctrlHeld = Input.IsButtonHeld(ButtonCode.LeftControl) ||
  570. Input.IsButtonHeld(ButtonCode.RightControl);
  571. sceneSelection.PickObject(scenePos, ctrlHeld, new SceneObject[] {draggedSO});
  572. }
  573. }
  574. }
  575. }
  576. else
  577. cameraController.EnableInput(false);
  578. SceneHandles.BeginInput();
  579. sceneHandles.UpdateInput(scenePos, Input.PointerDelta);
  580. sceneHandles.Draw();
  581. sceneAxesGUI.UpdateInput(scenePos);
  582. sceneAxesGUI.Draw();
  583. SceneHandles.EndInput();
  584. sceneSelection.Draw();
  585. UpdateGridMode();
  586. if (VirtualInput.IsButtonDown(frameKey))
  587. cameraController.FrameSelected();
  588. }
  589. /// <inheritdoc/>
  590. protected override void WindowResized(int width, int height)
  591. {
  592. UpdateRenderTexture(width, height - HeaderHeight);
  593. base.WindowResized(width, height);
  594. }
  595. /// <inheritdoc/>
  596. protected override void FocusChanged(bool inFocus)
  597. {
  598. if (!inFocus)
  599. {
  600. sceneHandles.ClearSelection();
  601. }
  602. }
  603. /// <summary>
  604. /// Triggered when one of the scene tool buttons is clicked, changing the active scene handle.
  605. /// </summary>
  606. /// <param name="tool">Clicked scene tool to activate.</param>
  607. private void OnSceneToolButtonClicked(SceneViewTool tool)
  608. {
  609. EditorApplication.ActiveSceneTool = tool;
  610. editorSettingsHash = EditorSettings.Hash;
  611. }
  612. /// <summary>
  613. /// Triggered when one of the coordinate mode buttons is clicked, changing the active coordinate mode.
  614. /// </summary>
  615. /// <param name="mode">Clicked coordinate mode to activate.</param>
  616. private void OnCoordinateModeButtonClicked(HandleCoordinateMode mode)
  617. {
  618. EditorApplication.ActiveCoordinateMode = mode;
  619. editorSettingsHash = EditorSettings.Hash;
  620. }
  621. /// <summary>
  622. /// Triggered when one of the pivot buttons is clicked, changing the active pivot mode.
  623. /// </summary>
  624. /// <param name="mode">Clicked pivot mode to activate.</param>
  625. private void OnPivotModeButtonClicked(HandlePivotMode mode)
  626. {
  627. EditorApplication.ActivePivotMode = mode;
  628. editorSettingsHash = EditorSettings.Hash;
  629. }
  630. /// <summary>
  631. /// Triggered when the move snap button is toggled.
  632. /// </summary>
  633. /// <param name="active">Determins should be move snap be activated or deactivated.</param>
  634. private void OnMoveSnapToggled(bool active)
  635. {
  636. Handles.MoveHandleSnapActive = active;
  637. editorSettingsHash = EditorSettings.Hash;
  638. }
  639. /// <summary>
  640. /// Triggered when the move snap increment value changes.
  641. /// </summary>
  642. /// <param name="value">Value that determines in what increments to perform move snapping.</param>
  643. private void OnMoveSnapValueChanged(float value)
  644. {
  645. Handles.MoveSnapAmount = MathEx.Clamp(value, 0.01f, 1000.0f);
  646. editorSettingsHash = EditorSettings.Hash;
  647. }
  648. /// <summary>
  649. /// Triggered when the rotate snap button is toggled.
  650. /// </summary>
  651. /// <param name="active">Determins should be rotate snap be activated or deactivated.</param>
  652. private void OnRotateSnapToggled(bool active)
  653. {
  654. Handles.RotateHandleSnapActive = active;
  655. editorSettingsHash = EditorSettings.Hash;
  656. }
  657. /// <summary>
  658. /// Triggered when the rotate snap increment value changes.
  659. /// </summary>
  660. /// <param name="value">Value that determines in what increments to perform rotate snapping.</param>
  661. private void OnRotateSnapValueChanged(float value)
  662. {
  663. Handles.RotateSnapAmount = (Degree)MathEx.Clamp(value, 0.01f, 360.0f);
  664. editorSettingsHash = EditorSettings.Hash;
  665. }
  666. /// <summary>
  667. /// Updates toggle button states according to current editor options. This is useful if tools, coordinate mode,
  668. /// pivot or other scene view options have been modified externally.
  669. /// </summary>
  670. private void UpdateButtonStates()
  671. {
  672. switch (EditorApplication.ActiveSceneTool)
  673. {
  674. case SceneViewTool.View:
  675. viewButton.Value = true;
  676. break;
  677. case SceneViewTool.Move:
  678. moveButton.Value = true;
  679. break;
  680. case SceneViewTool.Rotate:
  681. rotateButton.Value = true;
  682. break;
  683. case SceneViewTool.Scale:
  684. scaleButton.Value = true;
  685. break;
  686. }
  687. switch (EditorApplication.ActiveCoordinateMode)
  688. {
  689. case HandleCoordinateMode.Local:
  690. localCoordButton.Value = true;
  691. break;
  692. case HandleCoordinateMode.World:
  693. worldCoordButton.Value = true;
  694. break;
  695. }
  696. switch (EditorApplication.ActivePivotMode)
  697. {
  698. case HandlePivotMode.Center:
  699. centerButton.Value = true;
  700. break;
  701. case HandlePivotMode.Pivot:
  702. pivotButton.Value = true;
  703. break;
  704. }
  705. if (Handles.MoveHandleSnapActive)
  706. moveSnapButton.Value = true;
  707. else
  708. moveSnapButton.Value = false;
  709. moveSnapInput.Value = Handles.MoveSnapAmount;
  710. if (Handles.RotateHandleSnapActive)
  711. rotateSnapButton.Value = true;
  712. else
  713. rotateSnapButton.Value = false;
  714. moveSnapInput.Value = Handles.RotateSnapAmount.Degrees;
  715. }
  716. /// <summary>
  717. /// Activates or deactivates the profiler overlay according to current editor settings.
  718. /// </summary>
  719. private void UpdateProfilerOverlay()
  720. {
  721. if (EditorSettings.GetBool(ProfilerOverlayActiveKey))
  722. {
  723. if (activeProfilerOverlay == null)
  724. {
  725. SceneObject profilerSO = new SceneObject("EditorProfilerOverlay");
  726. profilerCamera = profilerSO.AddComponent<Camera>();
  727. profilerCamera.Target = renderTexture;
  728. profilerCamera.ClearFlags = ClearFlags.None;
  729. profilerCamera.Priority = 1;
  730. profilerCamera.Layers = 0;
  731. profilerCamera.HDR = false;
  732. activeProfilerOverlay = profilerSO.AddComponent<ProfilerOverlay>();
  733. }
  734. }
  735. else
  736. {
  737. if (activeProfilerOverlay != null)
  738. {
  739. activeProfilerOverlay.SceneObject.Destroy();
  740. activeProfilerOverlay = null;
  741. profilerCamera = null;
  742. }
  743. }
  744. }
  745. /// <summary>
  746. /// Creates the scene camera and updates the render texture. Should be called at least once before using the
  747. /// scene view. Should be called whenever the window is resized.
  748. /// </summary>
  749. /// <param name="width">Width of the scene render target, in pixels.</param>
  750. /// <param name="height">Height of the scene render target, in pixels.</param>
  751. private void UpdateRenderTexture(int width, int height)
  752. {
  753. width = MathEx.Max(20, width);
  754. height = MathEx.Max(20, height);
  755. // Note: Depth buffer is required because ScenePicking uses it
  756. renderTexture = new RenderTexture2D(PixelFormat.R8G8B8A8, width, height, 1, false, true);
  757. renderTexture.Priority = 1;
  758. if (camera == null)
  759. {
  760. SceneObject sceneCameraSO = new SceneObject("SceneCamera", true);
  761. camera = sceneCameraSO.AddComponent<Camera>();
  762. camera.Target = renderTexture;
  763. camera.ViewportRect = new Rect2(0.0f, 0.0f, 1.0f, 1.0f);
  764. sceneCameraSO.Position = new Vector3(0, 0.5f, 1);
  765. sceneCameraSO.LookAt(new Vector3(0, 0.5f, 0));
  766. camera.Priority = 2;
  767. camera.NearClipPlane = 0.05f;
  768. camera.FarClipPlane = 2500.0f;
  769. camera.ClearColor = ClearColor;
  770. camera.Layers = UInt64.MaxValue & ~SceneAxesHandle.LAYER; // Don't draw scene axes in this camera
  771. cameraController = sceneCameraSO.AddComponent<SceneCamera>();
  772. renderTextureGUI = new GUIRenderTexture(renderTexture);
  773. rtPanel.AddElement(renderTextureGUI);
  774. sceneGrid = new SceneGrid(camera);
  775. sceneSelection = new SceneSelection(camera);
  776. sceneGizmos = new SceneGizmos(camera);
  777. sceneHandles = new SceneHandles(this, camera);
  778. }
  779. else
  780. {
  781. camera.Target = renderTexture;
  782. renderTextureGUI.RenderTexture = renderTexture;
  783. }
  784. Rect2I rtBounds = new Rect2I(0, 0, width, height);
  785. renderTextureGUI.Bounds = rtBounds;
  786. focusCatcher.Bounds = GUIUtility.CalculateBounds(rtPanel, GUI);
  787. sceneAxesGUI.SetPosition(width - HandleAxesGUISize - HandleAxesGUIPaddingX, HandleAxesGUIPaddingY);
  788. // TODO - Consider only doing the resize once user stops resizing the widget in order to reduce constant
  789. // render target destroy/create cycle for every single pixel.
  790. camera.AspectRatio = width / (float)height;
  791. if (profilerCamera != null)
  792. profilerCamera.Target = renderTexture;
  793. }
  794. /// <summary>
  795. /// Parses an array of scene objects and removes elements that are children of elements that are also in the array.
  796. /// </summary>
  797. /// <param name="objects">Array containing duplicate objects as input, and array without duplicate objects as
  798. /// output.</param>
  799. private void CleanDuplicates(ref SceneObject[] objects)
  800. {
  801. List<SceneObject> cleanList = new List<SceneObject>();
  802. for (int i = 0; i < objects.Length; i++)
  803. {
  804. bool foundParent = false;
  805. for (int j = 0; j < objects.Length; j++)
  806. {
  807. SceneObject elem = objects[i];
  808. while (elem != null && elem != objects[j])
  809. elem = elem.Parent;
  810. bool isChildOf = elem == objects[j];
  811. if (i != j && isChildOf)
  812. {
  813. foundParent = true;
  814. break;
  815. }
  816. }
  817. if (!foundParent)
  818. cleanList.Add(objects[i]);
  819. }
  820. objects = cleanList.ToArray();
  821. }
  822. /// <summary>
  823. /// Starts a drag operation that displays a selection outline allowing the user to select multiple entries at once.
  824. /// </summary>
  825. /// <param name="scenePos">Coordinates relative to the scene where the drag originated.</param>
  826. private void StartDragSelection(Vector2I scenePos)
  827. {
  828. isDraggingSelection = true;
  829. dragSelectionStart = scenePos;
  830. dragSelectionEnd = dragSelectionStart;
  831. }
  832. /// <summary>
  833. /// Updates a selection outline drag operation by expanding the outline to the new location. Elements in the outline
  834. /// are selected.
  835. /// </summary>
  836. /// <param name="scenePos">Coordinates of the pointer relative to the scene.</param>
  837. /// <returns>True if the selection outline drag is valid and was updated, false otherwise.</returns>
  838. private bool UpdateDragSelection(Vector2I scenePos)
  839. {
  840. if (!isDraggingSelection)
  841. return false;
  842. if (dragSelection == null)
  843. {
  844. dragSelection = new GUITexture(null, true, EditorStylesInternal.SelectionArea);
  845. selectionPanel.AddElement(dragSelection);
  846. }
  847. dragSelectionEnd = scenePos;
  848. Rect2I selectionArea = new Rect2I();
  849. Vector2I min = new Vector2I(Math.Min(dragSelectionStart.x, dragSelectionEnd.x), Math.Min(dragSelectionStart.y, dragSelectionEnd.y));
  850. Vector2I max = new Vector2I(Math.Max(dragSelectionStart.x, dragSelectionEnd.x), Math.Max(dragSelectionStart.y, dragSelectionEnd.y));
  851. selectionArea.x = min.x;
  852. selectionArea.y = min.y;
  853. selectionArea.width = Math.Max(max.x - min.x, 1);
  854. selectionArea.height = Math.Max(max.y - min.y, 1);
  855. dragSelection.Bounds = selectionArea;
  856. return true;
  857. }
  858. /// <summary>
  859. /// Ends the selection outline drag operation. Elements in the outline are selected.
  860. /// </summary>
  861. /// <returns>True if the selection outline drag is valid and was ended, false otherwise.</returns>
  862. private bool EndDragSelection()
  863. {
  864. if (!isDraggingSelection)
  865. return false;
  866. if (dragSelection != null)
  867. {
  868. dragSelection.Destroy();
  869. dragSelection = null;
  870. }
  871. if ((dragSelectionEnd - dragSelectionStart).Length < 1)
  872. {
  873. isDraggingSelection = false;
  874. return false;
  875. }
  876. Vector2I min = new Vector2I(Math.Min(dragSelectionStart.x, dragSelectionEnd.x),
  877. Math.Min(dragSelectionStart.y, dragSelectionEnd.y));
  878. Vector2I max = new Vector2I(Math.Max(dragSelectionStart.x, dragSelectionEnd.x),
  879. Math.Max(dragSelectionStart.y, dragSelectionEnd.y));
  880. sceneSelection.PickObjects(min, max - min,
  881. Input.IsButtonHeld(ButtonCode.LeftControl) || Input.IsButtonHeld(ButtonCode.RightControl));
  882. isDraggingSelection = false;
  883. return true;
  884. }
  885. }
  886. /** @} */
  887. }