SceneWindow.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using BansheeEngine;
  8. namespace BansheeEditor
  9. {
  10. /// <summary>
  11. /// Displays the scene view camera and various scene controls.
  12. /// </summary>
  13. internal sealed class SceneWindow : EditorWindow
  14. {
  15. internal const string ToggleProfilerOverlayBinding = "ToggleProfilerOverlay";
  16. internal const string ViewToolBinding = "EdViewTool";
  17. internal const string MoveToolBinding = "EdMoveTool";
  18. internal const string RotateToolBinding = "EdRotateTool";
  19. internal const string ScaleToolBinding = "EdScaleTool";
  20. internal const string DuplicateBinding = "EdDuplicate";
  21. private const int HeaderHeight = 20;
  22. private const float DefaultPlacementDepth = 5.0f;
  23. private static readonly Color ClearColor = new Color(83.0f/255.0f, 83.0f/255.0f, 83.0f/255.0f);
  24. private const string ProfilerOverlayActiveKey = "_Internal_ProfilerOverlayActive";
  25. private Camera camera;
  26. private SceneCamera cameraController;
  27. private RenderTexture2D renderTexture;
  28. private GUILayoutY mainLayout;
  29. private GUIRenderTexture renderTextureGUI;
  30. private SceneViewHandler sceneViewHandler;
  31. private GUIToggle viewButton;
  32. private GUIToggle moveButton;
  33. private GUIToggle rotateButton;
  34. private GUIToggle scaleButton;
  35. private GUIToggle localCoordButton;
  36. private GUIToggle worldCoordButton;
  37. private GUIToggle pivotButton;
  38. private GUIToggle centerButton;
  39. private GUIToggle moveSnapButton;
  40. private GUIFloatField moveSnapInput;
  41. private GUIToggle rotateSnapButton;
  42. private GUIFloatField rotateSnapInput;
  43. private int editorSettingsHash = int.MaxValue;
  44. private VirtualButton duplicateKey;
  45. // Tool shortcuts
  46. private VirtualButton viewToolKey;
  47. private VirtualButton moveToolKey;
  48. private VirtualButton rotateToolKey;
  49. private VirtualButton scaleToolKey;
  50. // Profiler overlay
  51. private ProfilerOverlay activeProfilerOverlay;
  52. private Camera profilerCamera;
  53. private VirtualButton toggleProfilerOverlayKey;
  54. // Drag & drop
  55. private bool dragActive;
  56. private SceneObject draggedSO;
  57. /// <summary>
  58. /// Returns the scene camera.
  59. /// </summary>
  60. public Camera Camera
  61. {
  62. get { return camera; }
  63. }
  64. /// <summary>
  65. /// Constructs a new scene window.
  66. /// </summary>
  67. internal SceneWindow()
  68. { }
  69. /// <summary>
  70. /// Opens a scene window if its not open already.
  71. /// </summary>
  72. [MenuItem("Windows/Scene", ButtonModifier.CtrlAlt, ButtonCode.S, 6000)]
  73. private static void OpenSceneWindow()
  74. {
  75. OpenWindow<SceneWindow>();
  76. }
  77. /// <inheritdoc/>
  78. protected override LocString GetDisplayName()
  79. {
  80. return new LocEdString("Scene");
  81. }
  82. private void OnInitialize()
  83. {
  84. mainLayout = GUI.AddLayoutY();
  85. GUIToggleGroup handlesTG = new GUIToggleGroup();
  86. viewButton = new GUIToggle("V", handlesTG, EditorStyles.Button);
  87. moveButton = new GUIToggle("M", handlesTG, EditorStyles.Button);
  88. rotateButton = new GUIToggle("R", handlesTG, EditorStyles.Button);
  89. scaleButton = new GUIToggle("S", handlesTG, EditorStyles.Button);
  90. GUIToggleGroup coordModeTG = new GUIToggleGroup();
  91. localCoordButton = new GUIToggle("L", coordModeTG, EditorStyles.Button);
  92. worldCoordButton = new GUIToggle("W", coordModeTG, EditorStyles.Button);
  93. GUIToggleGroup pivotModeTG = new GUIToggleGroup();
  94. pivotButton = new GUIToggle("P", pivotModeTG, EditorStyles.Button);
  95. centerButton = new GUIToggle("C", pivotModeTG, EditorStyles.Button);
  96. moveSnapButton = new GUIToggle("MS", EditorStyles.Button);
  97. moveSnapInput = new GUIFloatField();
  98. rotateSnapButton = new GUIToggle("RS", EditorStyles.Button);
  99. rotateSnapInput = new GUIFloatField();
  100. viewButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.View);
  101. moveButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.Move);
  102. rotateButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.Rotate);
  103. scaleButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.Scale);
  104. localCoordButton.OnClick += () => OnCoordinateModeButtonClicked(HandleCoordinateMode.Local);
  105. worldCoordButton.OnClick += () => OnCoordinateModeButtonClicked(HandleCoordinateMode.World);
  106. pivotButton.OnClick += () => OnPivotModeButtonClicked(HandlePivotMode.Pivot);
  107. centerButton.OnClick += () => OnPivotModeButtonClicked(HandlePivotMode.Center);
  108. moveSnapButton.OnToggled += (bool active) => OnMoveSnapToggled(active);
  109. moveSnapInput.OnChanged += (float value) => OnMoveSnapValueChanged(value);
  110. rotateSnapButton.OnToggled += (bool active) => OnRotateSnapToggled(active);
  111. rotateSnapInput.OnChanged += (float value) => OnRotateSnapValueChanged(value);
  112. GUILayout handlesLayout = mainLayout.AddLayoutX();
  113. handlesLayout.AddElement(viewButton);
  114. handlesLayout.AddElement(moveButton);
  115. handlesLayout.AddElement(rotateButton);
  116. handlesLayout.AddElement(scaleButton);
  117. handlesLayout.AddSpace(10);
  118. handlesLayout.AddElement(localCoordButton);
  119. handlesLayout.AddElement(worldCoordButton);
  120. handlesLayout.AddSpace(10);
  121. handlesLayout.AddElement(pivotButton);
  122. handlesLayout.AddElement(centerButton);
  123. handlesLayout.AddFlexibleSpace();
  124. handlesLayout.AddElement(moveSnapButton);
  125. handlesLayout.AddElement(moveSnapInput);
  126. handlesLayout.AddSpace(10);
  127. handlesLayout.AddElement(rotateSnapButton);
  128. handlesLayout.AddElement(rotateSnapInput);
  129. toggleProfilerOverlayKey = new VirtualButton(ToggleProfilerOverlayBinding);
  130. viewToolKey = new VirtualButton(ViewToolBinding);
  131. moveToolKey = new VirtualButton(MoveToolBinding);
  132. rotateToolKey = new VirtualButton(RotateToolBinding);
  133. scaleToolKey = new VirtualButton(ScaleToolBinding);
  134. duplicateKey = new VirtualButton(DuplicateBinding);
  135. UpdateRenderTexture(Width, Height - HeaderHeight);
  136. UpdateProfilerOverlay();
  137. }
  138. private void OnDestroy()
  139. {
  140. if (camera != null)
  141. {
  142. camera.SceneObject.Destroy();
  143. camera = null;
  144. }
  145. }
  146. /// <summary>
  147. /// Converts screen coordinates into coordinates relative to the scene view render texture.
  148. /// </summary>
  149. /// <param name="screenPos">Coordinates relative to the screen.</param>
  150. /// <param name="scenePos">Output coordinates relative to the scene view texture.</param>
  151. /// <returns>True if the coordinates are within the scene view texture, false otherwise.</returns>
  152. private bool ScreenToScenePos(Vector2I screenPos, out Vector2I scenePos)
  153. {
  154. scenePos = screenPos;
  155. Vector2I windowPos = ScreenToWindowPos(screenPos);
  156. Rect2I bounds = GUILayoutUtility.CalculateBounds(renderTextureGUI);
  157. if (bounds.Contains(windowPos))
  158. {
  159. scenePos.x = windowPos.x - bounds.x;
  160. scenePos.y = windowPos.y - bounds.y;
  161. return true;
  162. }
  163. return false;
  164. }
  165. private void OnEditorUpdate()
  166. {
  167. if (HasFocus)
  168. {
  169. if (!Input.IsPointerButtonHeld(PointerButton.Right))
  170. {
  171. if (VirtualInput.IsButtonUp(toggleProfilerOverlayKey))
  172. EditorSettings.SetBool(ProfilerOverlayActiveKey, !EditorSettings.GetBool(ProfilerOverlayActiveKey));
  173. if (VirtualInput.IsButtonUp(viewToolKey))
  174. EditorApplication.ActiveSceneTool = SceneViewTool.View;
  175. if (VirtualInput.IsButtonUp(moveToolKey))
  176. EditorApplication.ActiveSceneTool = SceneViewTool.Move;
  177. if (VirtualInput.IsButtonUp(rotateToolKey))
  178. EditorApplication.ActiveSceneTool = SceneViewTool.Rotate;
  179. if (VirtualInput.IsButtonUp(scaleToolKey))
  180. EditorApplication.ActiveSceneTool = SceneViewTool.Scale;
  181. if (VirtualInput.IsButtonUp(duplicateKey))
  182. {
  183. SceneObject[] selectedObjects = Selection.sceneObjects;
  184. CleanDuplicates(ref selectedObjects);
  185. if (selectedObjects.Length > 0)
  186. {
  187. String message;
  188. if (selectedObjects.Length == 1)
  189. message = "Duplicated " + selectedObjects[0].Name;
  190. else
  191. message = "Duplicated " + selectedObjects.Length + " elements";
  192. UndoRedo.CloneSO(selectedObjects, message);
  193. }
  194. }
  195. }
  196. }
  197. // Refresh GUI buttons if needed (in case someones changes the values from script)
  198. if (editorSettingsHash != EditorSettings.Hash)
  199. {
  200. UpdateButtonStates();
  201. UpdateProfilerOverlay();
  202. editorSettingsHash = EditorSettings.Hash;
  203. }
  204. // Update scene view handles and selection
  205. sceneViewHandler.Update();
  206. bool handleActive = false;
  207. if (Input.IsPointerButtonUp(PointerButton.Left))
  208. {
  209. if (sceneViewHandler.IsHandleActive())
  210. {
  211. sceneViewHandler.ClearHandleSelection();
  212. handleActive = true;
  213. }
  214. }
  215. Vector2I scenePos;
  216. bool inBounds = ScreenToScenePos(Input.PointerPosition, out scenePos);
  217. bool draggedOver = DragDrop.DragInProgress || DragDrop.DropInProgress;
  218. draggedOver &= inBounds && DragDrop.Type == DragDropType.Resource;
  219. if (draggedOver)
  220. {
  221. if (DragDrop.DropInProgress)
  222. {
  223. dragActive = false;
  224. draggedSO = null;
  225. }
  226. else
  227. {
  228. if (!dragActive)
  229. {
  230. dragActive = true;
  231. ResourceDragDropData dragData = (ResourceDragDropData)DragDrop.Data;
  232. string draggedMeshPath = "";
  233. string[] draggedPaths = dragData.Paths;
  234. for (int i = 0; i < draggedPaths.Length; i++)
  235. {
  236. LibraryEntry entry = ProjectLibrary.GetEntry(draggedPaths[i]);
  237. if (entry != null && entry.Type == LibraryEntryType.File)
  238. {
  239. FileEntry fileEntry = (FileEntry) entry;
  240. if (fileEntry.ResType == ResourceType.Mesh)
  241. {
  242. draggedMeshPath = draggedPaths[i];
  243. break;
  244. }
  245. }
  246. }
  247. if (!string.IsNullOrEmpty(draggedMeshPath))
  248. {
  249. string meshName = Path.GetFileName(draggedMeshPath);
  250. draggedSO = new SceneObject(meshName);
  251. Mesh mesh = ProjectLibrary.Load<Mesh>(draggedMeshPath);
  252. Material material = new Material(Builtin.DiffuseShader);
  253. Renderable renderable = draggedSO.AddComponent<Renderable>();
  254. renderable.Mesh = mesh;
  255. renderable.SetMaterial(material);
  256. }
  257. }
  258. if (draggedSO != null)
  259. {
  260. Ray worldRay = camera.ScreenToWorldRay(scenePos);
  261. draggedSO.Position = worldRay*DefaultPlacementDepth;
  262. }
  263. }
  264. return;
  265. }
  266. else
  267. {
  268. if (dragActive)
  269. {
  270. dragActive = false;
  271. if (draggedSO != null)
  272. {
  273. draggedSO.Destroy();
  274. draggedSO = null;
  275. }
  276. }
  277. }
  278. if (HasFocus)
  279. {
  280. cameraController.SceneObject.Active = true;
  281. if (inBounds)
  282. {
  283. if (Input.IsPointerButtonDown(PointerButton.Left))
  284. {
  285. sceneViewHandler.TrySelectHandle(scenePos);
  286. }
  287. else if (Input.IsPointerButtonUp(PointerButton.Left))
  288. {
  289. if (!handleActive)
  290. {
  291. bool ctrlHeld = Input.IsButtonHeld(ButtonCode.LeftControl) ||
  292. Input.IsButtonHeld(ButtonCode.RightControl);
  293. sceneViewHandler.PickObject(scenePos, ctrlHeld);
  294. }
  295. }
  296. }
  297. }
  298. else
  299. cameraController.SceneObject.Active = false;
  300. sceneViewHandler.UpdateHandle(scenePos, Input.PointerDelta);
  301. sceneViewHandler.UpdateSelection();
  302. }
  303. /// <inheritdoc/>
  304. protected override void WindowResized(int width, int height)
  305. {
  306. UpdateRenderTexture(width, height - HeaderHeight);
  307. base.WindowResized(width, height);
  308. }
  309. /// <inheritdoc/>
  310. protected override void FocusChanged(bool inFocus)
  311. {
  312. if (!inFocus)
  313. {
  314. sceneViewHandler.ClearHandleSelection();
  315. }
  316. }
  317. /// <summary>
  318. /// Triggered when one of the scene tool buttons is clicked, changing the active scene handle.
  319. /// </summary>
  320. /// <param name="tool">Clicked scene tool to activate.</param>
  321. private void OnSceneToolButtonClicked(SceneViewTool tool)
  322. {
  323. EditorApplication.ActiveSceneTool = tool;
  324. editorSettingsHash = EditorSettings.Hash;
  325. }
  326. /// <summary>
  327. /// Triggered when one of the coordinate mode buttons is clicked, changing the active coordinate mode.
  328. /// </summary>
  329. /// <param name="mode">Clicked coordinate mode to activate.</param>
  330. private void OnCoordinateModeButtonClicked(HandleCoordinateMode mode)
  331. {
  332. EditorApplication.ActiveCoordinateMode = mode;
  333. editorSettingsHash = EditorSettings.Hash;
  334. }
  335. /// <summary>
  336. /// Triggered when one of the pivot buttons is clicked, changing the active pivot mode.
  337. /// </summary>
  338. /// <param name="mode">Clicked pivot mode to activate.</param>
  339. private void OnPivotModeButtonClicked(HandlePivotMode mode)
  340. {
  341. EditorApplication.ActivePivotMode = mode;
  342. editorSettingsHash = EditorSettings.Hash;
  343. }
  344. /// <summary>
  345. /// Triggered when the move snap button is toggled.
  346. /// </summary>
  347. /// <param name="active">Determins should be move snap be activated or deactivated.</param>
  348. private void OnMoveSnapToggled(bool active)
  349. {
  350. Handles.MoveHandleSnapActive = active;
  351. editorSettingsHash = EditorSettings.Hash;
  352. }
  353. /// <summary>
  354. /// Triggered when the move snap increment value changes.
  355. /// </summary>
  356. /// <param name="value">Value that determines in what increments to perform move snapping.</param>
  357. private void OnMoveSnapValueChanged(float value)
  358. {
  359. Handles.MoveSnapAmount = MathEx.Clamp(value, 0.01f, 1000.0f);
  360. editorSettingsHash = EditorSettings.Hash;
  361. }
  362. /// <summary>
  363. /// Triggered when the rotate snap button is toggled.
  364. /// </summary>
  365. /// <param name="active">Determins should be rotate snap be activated or deactivated.</param>
  366. private void OnRotateSnapToggled(bool active)
  367. {
  368. Handles.RotateHandleSnapActive = active;
  369. editorSettingsHash = EditorSettings.Hash;
  370. }
  371. /// <summary>
  372. /// Triggered when the rotate snap increment value changes.
  373. /// </summary>
  374. /// <param name="value">Value that determines in what increments to perform rotate snapping.</param>
  375. private void OnRotateSnapValueChanged(float value)
  376. {
  377. Handles.RotateSnapAmount = MathEx.Clamp(value, 0.01f, 360.0f);
  378. editorSettingsHash = EditorSettings.Hash;
  379. }
  380. /// <summary>
  381. /// Updates toggle button states according to current editor options. This is useful if tools, coordinate mode,
  382. /// pivot or other scene view options have been modified externally.
  383. /// </summary>
  384. private void UpdateButtonStates()
  385. {
  386. switch (EditorApplication.ActiveSceneTool)
  387. {
  388. case SceneViewTool.View:
  389. viewButton.Value = true;
  390. break;
  391. case SceneViewTool.Move:
  392. moveButton.Value = true;
  393. break;
  394. case SceneViewTool.Rotate:
  395. rotateButton.Value = true;
  396. break;
  397. case SceneViewTool.Scale:
  398. scaleButton.Value = true;
  399. break;
  400. }
  401. switch (EditorApplication.ActiveCoordinateMode)
  402. {
  403. case HandleCoordinateMode.Local:
  404. localCoordButton.Value = true;
  405. break;
  406. case HandleCoordinateMode.World:
  407. worldCoordButton.Value = true;
  408. break;
  409. }
  410. switch (EditorApplication.ActivePivotMode)
  411. {
  412. case HandlePivotMode.Center:
  413. centerButton.Value = true;
  414. break;
  415. case HandlePivotMode.Pivot:
  416. pivotButton.Value = true;
  417. break;
  418. }
  419. if (Handles.MoveHandleSnapActive)
  420. moveSnapButton.Value = true;
  421. else
  422. moveSnapButton.Value = false;
  423. moveSnapInput.Value = Handles.MoveSnapAmount;
  424. if (Handles.RotateHandleSnapActive)
  425. rotateSnapButton.Value = true;
  426. else
  427. rotateSnapButton.Value = false;
  428. moveSnapInput.Value = Handles.RotateSnapAmount.Degrees;
  429. }
  430. /// <summary>
  431. /// Activates or deactivates the profiler overlay according to current editor settings.
  432. /// </summary>
  433. private void UpdateProfilerOverlay()
  434. {
  435. if (EditorSettings.GetBool(ProfilerOverlayActiveKey))
  436. {
  437. if (activeProfilerOverlay == null)
  438. {
  439. SceneObject profilerSO = new SceneObject("EditorProfilerOverlay");
  440. profilerCamera = profilerSO.AddComponent<Camera>();
  441. profilerCamera.Target = renderTexture;
  442. profilerCamera.ClearFlags = ClearFlags.None;
  443. profilerCamera.Priority = 1;
  444. profilerCamera.Layers = 0;
  445. activeProfilerOverlay = profilerSO.AddComponent<ProfilerOverlay>();
  446. }
  447. }
  448. else
  449. {
  450. if (activeProfilerOverlay != null)
  451. {
  452. activeProfilerOverlay.SceneObject.Destroy();
  453. activeProfilerOverlay = null;
  454. profilerCamera = null;
  455. }
  456. }
  457. }
  458. /// <summary>
  459. /// Creates the scene camera and updates the render texture. Should be called at least once before using the
  460. /// scene view. Should be called whenver the window is resized.
  461. /// </summary>
  462. /// <param name="width">Width of the scene render target, in pixels.</param>
  463. /// <param name="height">Height of the scene render target, in pixels.</param>
  464. private void UpdateRenderTexture(int width, int height)
  465. {
  466. width = MathEx.Max(20, width);
  467. height = MathEx.Max(20, height);
  468. renderTexture = new RenderTexture2D(PixelFormat.R8G8B8A8, width, height);
  469. renderTexture.Priority = 1;
  470. if (camera == null)
  471. {
  472. SceneObject sceneCameraSO = new SceneObject("SceneCamera", true);
  473. camera = sceneCameraSO.AddComponent<Camera>();
  474. camera.Target = renderTexture;
  475. camera.ViewportRect = new Rect2(0.0f, 0.0f, 1.0f, 1.0f);
  476. sceneCameraSO.Position = new Vector3(0, 0.5f, 1);
  477. sceneCameraSO.LookAt(new Vector3(0, 0, 0));
  478. camera.Priority = 2;
  479. camera.NearClipPlane = 0.005f;
  480. camera.FarClipPlane = 1000.0f;
  481. camera.ClearColor = ClearColor;
  482. cameraController = sceneCameraSO.AddComponent<SceneCamera>();
  483. renderTextureGUI = new GUIRenderTexture(renderTexture);
  484. mainLayout.AddElement(renderTextureGUI);
  485. sceneViewHandler = new SceneViewHandler(this, camera);
  486. }
  487. else
  488. {
  489. camera.Target = renderTexture;
  490. renderTextureGUI.RenderTexture = renderTexture;
  491. }
  492. // TODO - Consider only doing the resize once user stops resizing the widget in order to reduce constant
  493. // render target destroy/create cycle for every single pixel.
  494. camera.AspectRatio = width / (float)height;
  495. if (profilerCamera != null)
  496. profilerCamera.Target = renderTexture;
  497. }
  498. /// <summary>
  499. /// Parses an array of scene objects and removes elements that are children of elements that are also in the array.
  500. /// </summary>
  501. /// <param name="objects">Array containing duplicate objects as input, and array without duplicate objects as
  502. /// output.</param>
  503. private void CleanDuplicates(ref SceneObject[] objects)
  504. {
  505. List<SceneObject> cleanList = new List<SceneObject>();
  506. for (int i = 0; i < objects.Length; i++)
  507. {
  508. bool foundParent = false;
  509. for (int j = 0; j < objects.Length; j++)
  510. {
  511. SceneObject elem = objects[i];
  512. while (elem != null && elem != objects[j])
  513. elem = objects[i].Parent;
  514. bool isChildOf = elem == objects[j];
  515. if (i != j && isChildOf)
  516. {
  517. foundParent = true;
  518. break;
  519. }
  520. }
  521. if (!foundParent)
  522. cleanList.Add(objects[i]);
  523. }
  524. objects = cleanList.ToArray();
  525. }
  526. }
  527. }