SceneCamera.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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 : Component
  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 = 360.0f; // Degrees/second
  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 lastButtonState;
  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 != lastButtonState)
  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. lastButtonState = 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 * frameDelta;
  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. Cursor.Show();
  227. Cursor.ClipDisable();
  228. }
  229. SceneWindow sceneWindow = EditorWindow.GetWindow<SceneWindow>();
  230. if (sceneWindow.Active && sceneWindow.HasFocus)
  231. {
  232. Rect2I bounds = sceneWindow.Bounds;
  233. // Move using scroll wheel
  234. if (bounds.Contains(Input.PointerPosition))
  235. {
  236. float scrollAmount = VirtualInput.GetAxisValue(scrollAxis);
  237. if (!isOrtographic)
  238. {
  239. SceneObject.Move(SceneObject.Forward*scrollAmount*ScrollSpeed);
  240. }
  241. else
  242. {
  243. float orthoHeight = MathEx.Max(1.0f, camera.OrthoHeight - scrollAmount);
  244. camera.OrthoHeight = orthoHeight;
  245. }
  246. }
  247. }
  248. UpdateAnim();
  249. }
  250. /// <summary>
  251. /// Moves and orients a camera so that the provided bounds end covering the camera's viewport.
  252. /// </summary>
  253. /// <param name="bounds">Bounds to frame in camera's view.</param>
  254. /// <param name="padding">Amount of padding to leave on the borders of the viewport, in percent [0, 1].</param>
  255. private void FrameBounds(AABox bounds, float padding = 0.0f)
  256. {
  257. // TODO - Use AABox bounds directly instead of a sphere to be more accurate
  258. float worldWidth = bounds.Size.Length;
  259. float worldHeight = worldWidth;
  260. if (worldWidth == 0.0f)
  261. worldWidth = 1.0f;
  262. if (worldHeight == 0.0f)
  263. worldHeight = 1.0f;
  264. float boundsAspect = worldWidth / worldHeight;
  265. float paddingScale = MathEx.Clamp01(padding) + 1.0f;
  266. float frustumWidth;
  267. // If camera has wider aspect than bounds then height will be the limiting dimension
  268. if (camera.AspectRatio > boundsAspect)
  269. frustumWidth = worldHeight * camera.AspectRatio * paddingScale;
  270. else // Otherwise width
  271. frustumWidth = worldWidth * paddingScale;
  272. float distance = CalcDistanceForFrustumWidth(frustumWidth);
  273. Vector3 forward = bounds.Center - SceneObject.Position;
  274. forward.Normalize();
  275. CameraState state = new CameraState();
  276. state.Position = bounds.Center - forward * distance;
  277. state.Rotation = Quaternion.LookRotation(forward, Vector3.YAxis);
  278. state.Ortographic = camera.ProjectionType == ProjectionType.Orthographic;
  279. state.FrustumWidth = frustumWidth;
  280. SetState(state);
  281. }
  282. /// <summary>
  283. /// Changes the state of the camera, either instantly or animated over several frames. The state includes
  284. /// camera position, rotation, type and possibly other parameters.
  285. /// </summary>
  286. /// <param name="state">New state of the camera.</param>
  287. /// <param name="animated">Should the state be linearly interpolated over a course of several frames.</param>
  288. private void SetState(CameraState state, bool animated = true)
  289. {
  290. CameraState startState = new CameraState();
  291. startState.Position = SceneObject.Position;
  292. startState.Rotation = SceneObject.Rotation;
  293. startState.Ortographic = camera.ProjectionType == ProjectionType.Orthographic;
  294. startState.FrustumWidth = frustumWidth;
  295. animation.Start(startState, state);
  296. if (!animated)
  297. {
  298. ApplyState(1.0f);
  299. isAnimating = false;
  300. }
  301. else
  302. {
  303. isAnimating = true;
  304. lerp = 0.0f;
  305. }
  306. }
  307. /// <summary>
  308. /// Applies the animation target state depending on the interpolation parameter. <see cref="SetState"/>.
  309. /// </summary>
  310. /// <param name="t">Interpolation parameter ranging [0, 1] that interpolated between the start state and the
  311. /// target state.</param>
  312. private void ApplyState(float t)
  313. {
  314. animation.Update(t);
  315. SceneObject.Position = animation.State.Position;
  316. SceneObject.Rotation = animation.State.Rotation;
  317. frustumWidth = animation.State.FrustumWidth;
  318. Vector3 eulerAngles = SceneObject.Rotation.ToEuler();
  319. pitch = (Degree)eulerAngles.x;
  320. yaw = (Degree)eulerAngles.y;
  321. Degree FOV = (Degree)(1.0f - animation.State.OrtographicPct)*FieldOfView;
  322. if (FOV < (Degree)5.0f)
  323. {
  324. camera.ProjectionType = ProjectionType.Orthographic;
  325. camera.OrthoHeight = frustumWidth * 0.5f / camera.AspectRatio;
  326. }
  327. else
  328. {
  329. camera.ProjectionType = ProjectionType.Perspective;
  330. camera.FieldOfView = FOV;
  331. }
  332. // Note: Consider having a global setting for near/far planes as changing it here might confuse the user
  333. float distance = CalcDistanceForFrustumWidth(frustumWidth);
  334. if (distance < 1)
  335. {
  336. camera.NearClipPlane = 0.005f;
  337. camera.FarClipPlane = 1000f;
  338. }
  339. if (distance < 100)
  340. {
  341. camera.NearClipPlane = 0.05f;
  342. camera.FarClipPlane = 2500f;
  343. }
  344. else if (distance < 1000)
  345. {
  346. camera.NearClipPlane = 0.5f;
  347. camera.FarClipPlane = 10000f;
  348. }
  349. else
  350. {
  351. camera.NearClipPlane = 5.0f;
  352. camera.FarClipPlane = 1000000f;
  353. }
  354. }
  355. /// <summary>
  356. /// Calculates distance at which the camera's frustum width is equal to the provided width.
  357. /// </summary>
  358. /// <param name="frustumWidth">Frustum width to find the distance for, in world units.</param>
  359. /// <returns>Distance at which the camera's frustum is the specified width, in world units.</returns>
  360. private float CalcDistanceForFrustumWidth(float frustumWidth)
  361. {
  362. if (camera.ProjectionType == ProjectionType.Perspective)
  363. return (frustumWidth*0.5f)/MathEx.Tan(camera.FieldOfView*0.5f);
  364. else
  365. return frustumWidth * 2.0f;
  366. }
  367. /// <summary>
  368. /// Updates camera state transition animation. Should be called every frame.
  369. /// </summary>
  370. private void UpdateAnim()
  371. {
  372. if (!isAnimating)
  373. return;
  374. const float ANIM_TIME = 0.5f; // 0.5f seconds
  375. lerp += Time.FrameDelta * (1.0f / ANIM_TIME);
  376. if (lerp >= 1.0f)
  377. {
  378. lerp = 1.0f;
  379. isAnimating = false;
  380. }
  381. ApplyState(lerp);
  382. }
  383. /// <summary>
  384. /// Contains data for a possible camera state. Camera states can be interpolated between each other as needed.
  385. /// </summary>
  386. private struct CameraState
  387. {
  388. private float _ortographic;
  389. public Vector3 Position { get; set; }
  390. public Quaternion Rotation { get; set; }
  391. public float FrustumWidth { get; set; }
  392. public bool Ortographic
  393. {
  394. get { return _ortographic > 0.5; }
  395. set { _ortographic = value ? 1.0f : 0.0f; }
  396. }
  397. public float OrtographicPct
  398. {
  399. get { return _ortographic; }
  400. set { _ortographic = value; }
  401. }
  402. }
  403. /// <summary>
  404. /// Helper class that performs linear interpolation between two camera states.
  405. /// </summary>
  406. private struct CameraAnimation
  407. {
  408. private CameraState start;
  409. private CameraState target;
  410. private CameraState interpolated;
  411. /// <summary>
  412. /// Returns currently interpolated animation state.
  413. /// </summary>
  414. public CameraState State
  415. {
  416. get { return interpolated; }
  417. }
  418. /// <summary>
  419. /// Initializes the animation with initial and target states.
  420. /// </summary>
  421. /// <param name="start">Initial state to animate from.</param>
  422. /// <param name="target">Target state to animate towards.</param>
  423. public void Start(CameraState start, CameraState target)
  424. {
  425. this.start = start;
  426. this.target = target;
  427. }
  428. /// <summary>
  429. /// Updates the animation by interpolating between the start and target states.
  430. /// </summary>
  431. /// <param name="t">Interpolation parameter in range [0, 1] that determines how much to interpolate between
  432. /// start and target states.</param>
  433. public void Update(float t)
  434. {
  435. interpolated.Position = start.Position * (1.0f - t) + target.Position * t;
  436. interpolated.Rotation = Quaternion.Slerp(start.Rotation, target.Rotation, t);
  437. interpolated.OrtographicPct = start.OrtographicPct * (1.0f - t) + target.OrtographicPct * t;
  438. interpolated.FrustumWidth = start.FrustumWidth * (1.0f - t) + target.FrustumWidth * t;
  439. }
  440. };
  441. #endregion
  442. }
  443. /** @} */
  444. }