SceneCamera.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using BansheeEngine;
  4. namespace BansheeEditor
  5. {
  6. /** @addtogroup Scene-Editor
  7. * @{
  8. */
  9. /// <summary>
  10. /// Handles camera movement in the scene view.
  11. /// </summary>
  12. [RunInEditor]
  13. internal sealed class SceneCamera : ManagedComponent
  14. {
  15. #region Constants
  16. public const string MoveForwardBinding = "SceneForward";
  17. public const string MoveLeftBinding = "SceneLeft";
  18. public const string MoveRightBinding = "SceneRight";
  19. public const string MoveBackBinding = "SceneBackward";
  20. public const string MoveUpBinding = "SceneUp";
  21. public const string MoveDownBinding = "SceneDown";
  22. public const string FastMoveBinding = "SceneFastMove";
  23. public const string PanBinding = "ScenePan";
  24. public const string RotateBinding = "SceneRotate";
  25. public const string HorizontalAxisBinding = "SceneHorizontal";
  26. public const string VerticalAxisBinding = "SceneVertical";
  27. public const string ScrollAxisBinding = "SceneScroll";
  28. private const float StartSpeed = 4.0f;
  29. private const float TopSpeed = 12.0f;
  30. private const float Acceleration = 1.0f;
  31. private const float FastModeMultiplier = 2.0f;
  32. private const float PanSpeed = 3.0f;
  33. private const float ScrollSpeed = 3.0f;
  34. private const float RotationalSpeed = 3.0f;
  35. private readonly Degree FieldOfView = (Degree)90.0f;
  36. #endregion
  37. #region Fields
  38. private VirtualButton moveForwardBtn;
  39. private VirtualButton moveLeftBtn;
  40. private VirtualButton moveRightBtn;
  41. private VirtualButton moveBackwardBtn;
  42. private VirtualButton moveUpBtn;
  43. private VirtualButton moveDownBtn;
  44. private VirtualButton fastMoveBtn;
  45. private VirtualButton activeBtn;
  46. private VirtualButton panBtn;
  47. private VirtualAxis horizontalAxis;
  48. private VirtualAxis verticalAxis;
  49. private VirtualAxis scrollAxis;
  50. private float currentSpeed;
  51. private Degree yaw;
  52. private Degree pitch;
  53. private bool lastHideCursorState;
  54. private Camera camera;
  55. private bool inputEnabled = true;
  56. // Animating camera transitions
  57. private CameraAnimation animation = new CameraAnimation();
  58. private float frustumWidth = 50.0f;
  59. private float lerp;
  60. private bool isAnimating;
  61. #endregion
  62. #region Public properties
  63. /// <summary>
  64. /// Type of projection used by camera for rendering the scene.
  65. /// </summary>
  66. public ProjectionType ProjectionType
  67. {
  68. get { return camera.ProjectionType; }
  69. set
  70. {
  71. if (camera.ProjectionType != value)
  72. {
  73. CameraState state = new CameraState();
  74. state.Position = camera.SceneObject.Position;
  75. state.Rotation = camera.SceneObject.Rotation;
  76. state.Ortographic = value == ProjectionType.Orthographic;
  77. state.FrustumWidth = frustumWidth;
  78. SetState(state);
  79. }
  80. }
  81. }
  82. #endregion
  83. #region Public methods
  84. /// <summary>
  85. /// Enables or disables camera controls.
  86. /// </summary>
  87. /// <param name="enable">True to enable controls, false to disable.</param>
  88. public void EnableInput(bool enable)
  89. {
  90. inputEnabled = enable;
  91. }
  92. /// <summary>
  93. /// Focuses the camera on the currently selected object(s).
  94. /// </summary>
  95. public void FrameSelected()
  96. {
  97. SceneObject[] selectedObjects = Selection.SceneObjects;
  98. if (selectedObjects.Length > 0)
  99. {
  100. AABox box = EditorUtility.CalculateBounds(Selection.SceneObjects);
  101. FrameBounds(box);
  102. }
  103. }
  104. /// <summary>
  105. /// Orients the camera so it looks along the provided axis.
  106. /// </summary>
  107. public void LookAlong(Vector3 axis)
  108. {
  109. Vector3 up = Vector3.YAxis;
  110. if (MathEx.Abs(Vector3.Dot(axis, up)) > 0.9f)
  111. up = Vector3.ZAxis;
  112. CameraState state = new CameraState();
  113. state.Position = camera.SceneObject.Position;
  114. state.Rotation = Quaternion.LookRotation(axis, up);
  115. state.Ortographic = camera.ProjectionType == ProjectionType.Orthographic;
  116. state.FrustumWidth = frustumWidth;
  117. SetState(state);
  118. }
  119. #endregion
  120. #region Private methods
  121. private void OnReset()
  122. {
  123. camera = SceneObject.GetComponent<Camera>();
  124. moveForwardBtn = new VirtualButton(MoveForwardBinding);
  125. moveLeftBtn = new VirtualButton(MoveLeftBinding);
  126. moveRightBtn = new VirtualButton(MoveRightBinding);
  127. moveBackwardBtn = new VirtualButton(MoveBackBinding);
  128. moveUpBtn = new VirtualButton(MoveUpBinding);
  129. moveDownBtn = new VirtualButton(MoveDownBinding);
  130. fastMoveBtn = new VirtualButton(FastMoveBinding);
  131. activeBtn = new VirtualButton(RotateBinding);
  132. panBtn = new VirtualButton(PanBinding);
  133. horizontalAxis = new VirtualAxis(HorizontalAxisBinding);
  134. verticalAxis = new VirtualAxis(VerticalAxisBinding);
  135. scrollAxis = new VirtualAxis(ScrollAxisBinding);
  136. }
  137. private void OnUpdate()
  138. {
  139. bool isOrtographic = camera.ProjectionType == ProjectionType.Orthographic;
  140. if (inputEnabled)
  141. {
  142. bool goingForward = VirtualInput.IsButtonHeld(moveForwardBtn);
  143. bool goingBack = VirtualInput.IsButtonHeld(moveBackwardBtn);
  144. bool goingLeft = VirtualInput.IsButtonHeld(moveLeftBtn);
  145. bool goingRight = VirtualInput.IsButtonHeld(moveRightBtn);
  146. bool goingUp = VirtualInput.IsButtonHeld(moveUpBtn);
  147. bool goingDown = VirtualInput.IsButtonHeld(moveDownBtn);
  148. bool fastMove = VirtualInput.IsButtonHeld(fastMoveBtn);
  149. bool camActive = VirtualInput.IsButtonHeld(activeBtn);
  150. bool isPanning = VirtualInput.IsButtonHeld(panBtn);
  151. bool hideCursor = camActive || isPanning;
  152. if (hideCursor != lastHideCursorState)
  153. {
  154. if (hideCursor)
  155. {
  156. Cursor.Hide();
  157. Rect2I clipRect;
  158. clipRect.x = Input.PointerPosition.x - 2;
  159. clipRect.y = Input.PointerPosition.y - 2;
  160. clipRect.width = 4;
  161. clipRect.height = 4;
  162. Cursor.ClipToRect(clipRect);
  163. }
  164. else
  165. {
  166. Cursor.Show();
  167. Cursor.ClipDisable();
  168. }
  169. lastHideCursorState = hideCursor;
  170. }
  171. float frameDelta = Time.FrameDelta;
  172. if (camActive)
  173. {
  174. float horzValue = VirtualInput.GetAxisValue(horizontalAxis);
  175. float vertValue = VirtualInput.GetAxisValue(verticalAxis);
  176. float rotationAmount = RotationalSpeed * EditorSettings.MouseSensitivity;
  177. yaw += new Degree(horzValue * rotationAmount);
  178. pitch += new Degree(vertValue * rotationAmount);
  179. yaw = MathEx.WrapAngle(yaw);
  180. pitch = MathEx.WrapAngle(pitch);
  181. Quaternion yRot = Quaternion.FromAxisAngle(Vector3.YAxis, yaw);
  182. Quaternion xRot = Quaternion.FromAxisAngle(Vector3.XAxis, pitch);
  183. Quaternion camRot = yRot*xRot;
  184. camRot.Normalize();
  185. SceneObject.Rotation = camRot;
  186. // Handle movement using movement keys
  187. Vector3 direction = Vector3.Zero;
  188. if (goingForward) direction += SceneObject.Forward;
  189. if (goingBack) direction -= SceneObject.Forward;
  190. if (goingRight) direction += SceneObject.Right;
  191. if (goingLeft) direction -= SceneObject.Right;
  192. if (goingUp) direction += SceneObject.Up;
  193. if (goingDown) direction -= SceneObject.Up;
  194. if (direction.SqrdLength != 0)
  195. {
  196. direction.Normalize();
  197. float multiplier = 1.0f;
  198. if (fastMove)
  199. multiplier = FastModeMultiplier;
  200. currentSpeed = MathEx.Clamp(currentSpeed + Acceleration*frameDelta, StartSpeed, TopSpeed);
  201. currentSpeed *= multiplier;
  202. }
  203. else
  204. {
  205. currentSpeed = 0.0f;
  206. }
  207. const float tooSmall = 0.0001f;
  208. if (currentSpeed > tooSmall)
  209. {
  210. Vector3 velocity = direction*currentSpeed;
  211. SceneObject.Move(velocity*frameDelta);
  212. }
  213. }
  214. // Pan
  215. if (isPanning)
  216. {
  217. float horzValue = VirtualInput.GetAxisValue(horizontalAxis);
  218. float vertValue = VirtualInput.GetAxisValue(verticalAxis);
  219. Vector3 direction = new Vector3(horzValue, -vertValue, 0.0f);
  220. direction = camera.SceneObject.Rotation.Rotate(direction);
  221. SceneObject.Move(direction*PanSpeed*frameDelta);
  222. }
  223. }
  224. else
  225. {
  226. if (lastHideCursorState)
  227. {
  228. Cursor.Show();
  229. Cursor.ClipDisable();
  230. lastHideCursorState = false;
  231. }
  232. }
  233. SceneWindow sceneWindow = EditorWindow.GetWindow<SceneWindow>();
  234. if ((sceneWindow.Active && sceneWindow.HasFocus) || sceneWindow.IsPointerHovering)
  235. {
  236. Rect2I bounds = sceneWindow.Bounds;
  237. // Move using scroll wheel
  238. if (bounds.Contains(Input.PointerPosition))
  239. {
  240. float scrollAmount = VirtualInput.GetAxisValue(scrollAxis);
  241. if (!isOrtographic)
  242. {
  243. SceneObject.Move(SceneObject.Forward*scrollAmount*ScrollSpeed);
  244. }
  245. else
  246. {
  247. float orthoHeight = MathEx.Max(1.0f, camera.OrthoHeight - scrollAmount);
  248. camera.OrthoHeight = orthoHeight;
  249. }
  250. }
  251. }
  252. UpdateAnim();
  253. }
  254. /// <summary>
  255. /// Moves and orients a camera so that the provided bounds end covering the camera's viewport.
  256. /// </summary>
  257. /// <param name="bounds">Bounds to frame in camera's view.</param>
  258. /// <param name="padding">Amount of padding to leave on the borders of the viewport, in percent [0, 1].</param>
  259. private void FrameBounds(AABox bounds, float padding = 0.0f)
  260. {
  261. // TODO - Use AABox bounds directly instead of a sphere to be more accurate
  262. float worldWidth = bounds.Size.Length;
  263. float worldHeight = worldWidth;
  264. if (worldWidth == 0.0f)
  265. worldWidth = 1.0f;
  266. if (worldHeight == 0.0f)
  267. worldHeight = 1.0f;
  268. float boundsAspect = worldWidth / worldHeight;
  269. float paddingScale = MathEx.Clamp01(padding) + 1.0f;
  270. float frustumWidth;
  271. // If camera has wider aspect than bounds then height will be the limiting dimension
  272. if (camera.AspectRatio > boundsAspect)
  273. frustumWidth = worldHeight * camera.AspectRatio * paddingScale;
  274. else // Otherwise width
  275. frustumWidth = worldWidth * paddingScale;
  276. float distance = CalcDistanceForFrustumWidth(frustumWidth);
  277. Vector3 forward = bounds.Center - SceneObject.Position;
  278. forward.Normalize();
  279. CameraState state = new CameraState();
  280. state.Position = bounds.Center - forward * distance;
  281. state.Rotation = Quaternion.LookRotation(forward, Vector3.YAxis);
  282. state.Ortographic = camera.ProjectionType == ProjectionType.Orthographic;
  283. state.FrustumWidth = frustumWidth;
  284. SetState(state);
  285. }
  286. /// <summary>
  287. /// Changes the state of the camera, either instantly or animated over several frames. The state includes
  288. /// camera position, rotation, type and possibly other parameters.
  289. /// </summary>
  290. /// <param name="state">New state of the camera.</param>
  291. /// <param name="animated">Should the state be linearly interpolated over a course of several frames.</param>
  292. private void SetState(CameraState state, bool animated = true)
  293. {
  294. CameraState startState = new CameraState();
  295. startState.Position = SceneObject.Position;
  296. startState.Rotation = SceneObject.Rotation;
  297. startState.Ortographic = camera.ProjectionType == ProjectionType.Orthographic;
  298. startState.FrustumWidth = frustumWidth;
  299. animation.Start(startState, state);
  300. if (!animated)
  301. {
  302. ApplyState(1.0f);
  303. isAnimating = false;
  304. }
  305. else
  306. {
  307. isAnimating = true;
  308. lerp = 0.0f;
  309. }
  310. }
  311. /// <summary>
  312. /// Applies the animation target state depending on the interpolation parameter. <see cref="SetState"/>.
  313. /// </summary>
  314. /// <param name="t">Interpolation parameter ranging [0, 1] that interpolated between the start state and the
  315. /// target state.</param>
  316. private void ApplyState(float t)
  317. {
  318. animation.Update(t);
  319. SceneObject.Position = animation.State.Position;
  320. SceneObject.Rotation = animation.State.Rotation;
  321. frustumWidth = animation.State.FrustumWidth;
  322. Vector3 eulerAngles = SceneObject.Rotation.ToEuler();
  323. pitch = (Degree)eulerAngles.x;
  324. yaw = (Degree)eulerAngles.y;
  325. Degree FOV = (Degree)(1.0f - animation.State.OrtographicPct)*FieldOfView;
  326. if (FOV < (Degree)5.0f)
  327. {
  328. camera.ProjectionType = ProjectionType.Orthographic;
  329. camera.OrthoHeight = frustumWidth * 0.5f / camera.AspectRatio;
  330. }
  331. else
  332. {
  333. camera.ProjectionType = ProjectionType.Perspective;
  334. camera.FieldOfView = FOV;
  335. }
  336. // Note: Consider having a global setting for near/far planes as changing it here might confuse the user
  337. float distance = CalcDistanceForFrustumWidth(frustumWidth);
  338. if (distance < 1)
  339. {
  340. camera.NearClipPlane = 0.005f;
  341. camera.FarClipPlane = 1000f;
  342. }
  343. if (distance < 100)
  344. {
  345. camera.NearClipPlane = 0.05f;
  346. camera.FarClipPlane = 2500f;
  347. }
  348. else if (distance < 1000)
  349. {
  350. camera.NearClipPlane = 0.5f;
  351. camera.FarClipPlane = 10000f;
  352. }
  353. else
  354. {
  355. camera.NearClipPlane = 5.0f;
  356. camera.FarClipPlane = 1000000f;
  357. }
  358. }
  359. /// <summary>
  360. /// Calculates distance at which the camera's frustum width is equal to the provided width.
  361. /// </summary>
  362. /// <param name="frustumWidth">Frustum width to find the distance for, in world units.</param>
  363. /// <returns>Distance at which the camera's frustum is the specified width, in world units.</returns>
  364. private float CalcDistanceForFrustumWidth(float frustumWidth)
  365. {
  366. if (camera.ProjectionType == ProjectionType.Perspective)
  367. return (frustumWidth*0.5f)/MathEx.Tan(camera.FieldOfView*0.5f);
  368. else
  369. return frustumWidth * 2.0f;
  370. }
  371. /// <summary>
  372. /// Updates camera state transition animation. Should be called every frame.
  373. /// </summary>
  374. private void UpdateAnim()
  375. {
  376. if (!isAnimating)
  377. return;
  378. const float ANIM_TIME = 0.5f; // 0.5f seconds
  379. lerp += Time.FrameDelta * (1.0f / ANIM_TIME);
  380. if (lerp >= 1.0f)
  381. {
  382. lerp = 1.0f;
  383. isAnimating = false;
  384. }
  385. ApplyState(lerp);
  386. }
  387. /// <summary>
  388. /// Contains data for a possible camera state. Camera states can be interpolated between each other as needed.
  389. /// </summary>
  390. private struct CameraState
  391. {
  392. private float _ortographic;
  393. public Vector3 Position { get; set; }
  394. public Quaternion Rotation { get; set; }
  395. public float FrustumWidth { get; set; }
  396. public bool Ortographic
  397. {
  398. get { return _ortographic > 0.5; }
  399. set { _ortographic = value ? 1.0f : 0.0f; }
  400. }
  401. public float OrtographicPct
  402. {
  403. get { return _ortographic; }
  404. set { _ortographic = value; }
  405. }
  406. }
  407. /// <summary>
  408. /// Helper class that performs linear interpolation between two camera states.
  409. /// </summary>
  410. private struct CameraAnimation
  411. {
  412. private CameraState start;
  413. private CameraState target;
  414. private CameraState interpolated;
  415. /// <summary>
  416. /// Returns currently interpolated animation state.
  417. /// </summary>
  418. public CameraState State
  419. {
  420. get { return interpolated; }
  421. }
  422. /// <summary>
  423. /// Initializes the animation with initial and target states.
  424. /// </summary>
  425. /// <param name="start">Initial state to animate from.</param>
  426. /// <param name="target">Target state to animate towards.</param>
  427. public void Start(CameraState start, CameraState target)
  428. {
  429. this.start = start;
  430. this.target = target;
  431. }
  432. /// <summary>
  433. /// Updates the animation by interpolating between the start and target states.
  434. /// </summary>
  435. /// <param name="t">Interpolation parameter in range [0, 1] that determines how much to interpolate between
  436. /// start and target states.</param>
  437. public void Update(float t)
  438. {
  439. interpolated = new CameraState();
  440. interpolated.Position = start.Position * (1.0f - t) + target.Position * t;
  441. interpolated.Rotation = Quaternion.Slerp(start.Rotation, target.Rotation, t);
  442. interpolated.OrtographicPct = start.OrtographicPct * (1.0f - t) + target.OrtographicPct * t;
  443. interpolated.FrustumWidth = start.FrustumWidth * (1.0f - t) + target.FrustumWidth * t;
  444. }
  445. };
  446. #endregion
  447. }
  448. /** @} */
  449. }