SceneCamera.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. using BansheeEngine;
  2. namespace BansheeEditor
  3. {
  4. /// <summary>
  5. /// Handles camera movement in the scene view.
  6. /// </summary>
  7. [RunInEditor]
  8. internal sealed class SceneCamera : Component
  9. {
  10. public const string MoveForwardBinding = "SceneForward";
  11. public const string MoveLeftBinding = "SceneLeft";
  12. public const string MoveRightBinding = "SceneRight";
  13. public const string MoveBackBinding = "SceneBackward";
  14. public const string FastMoveBinding = "SceneFastMove";
  15. public const string RotateBinding = "SceneRotate";
  16. public const string HorizontalAxisBinding = "SceneHorizontal";
  17. public const string VerticalAxisBinding = "SceneVertical";
  18. private const float StartSpeed = 4.0f;
  19. private const float TopSpeed = 12.0f;
  20. private const float Acceleration = 1.0f;
  21. private const float FastModeMultiplier = 2.0f;
  22. private const float RotationalSpeed = 360.0f; // Degrees/second
  23. private readonly Degree FieldOfView = 90.0f;
  24. private VirtualButton moveForwardBtn;
  25. private VirtualButton moveLeftBtn;
  26. private VirtualButton moveRightBtn;
  27. private VirtualButton moveBackwardBtn;
  28. private VirtualButton fastMoveBtn;
  29. private VirtualButton activeBtn;
  30. private VirtualAxis horizontalAxis;
  31. private VirtualAxis verticalAxis;
  32. private float currentSpeed;
  33. private Degree yaw;
  34. private Degree pitch;
  35. private bool lastButtonState;
  36. private Camera camera;
  37. private bool inputEnabled = true;
  38. // Animating camera transitions
  39. private CameraAnimation animation = new CameraAnimation();
  40. private float frustumWidth = 50.0f;
  41. private float lerp;
  42. private bool isAnimating;
  43. private void OnReset()
  44. {
  45. camera = SceneObject.GetComponent<Camera>();
  46. moveForwardBtn = new VirtualButton(MoveForwardBinding);
  47. moveLeftBtn = new VirtualButton(MoveLeftBinding);
  48. moveRightBtn = new VirtualButton(MoveRightBinding);
  49. moveBackwardBtn = new VirtualButton(MoveBackBinding);
  50. fastMoveBtn = new VirtualButton(FastMoveBinding);
  51. activeBtn = new VirtualButton(RotateBinding);
  52. horizontalAxis = new VirtualAxis(HorizontalAxisBinding);
  53. verticalAxis = new VirtualAxis(VerticalAxisBinding);
  54. }
  55. private void OnUpdate()
  56. {
  57. bool goingForward = VirtualInput.IsButtonHeld(moveForwardBtn);
  58. bool goingBack = VirtualInput.IsButtonHeld(moveBackwardBtn);
  59. bool goingLeft = VirtualInput.IsButtonHeld(moveLeftBtn);
  60. bool goingRight = VirtualInput.IsButtonHeld(moveRightBtn);
  61. bool fastMove = VirtualInput.IsButtonHeld(fastMoveBtn);
  62. bool camActive = VirtualInput.IsButtonHeld(activeBtn);
  63. if (camActive != lastButtonState)
  64. {
  65. if (camActive)
  66. Cursor.Hide();
  67. else
  68. Cursor.Show();
  69. lastButtonState = camActive;
  70. }
  71. float frameDelta = Time.FrameDelta;
  72. if (camActive)
  73. {
  74. float horzValue = VirtualInput.GetAxisValue(horizontalAxis);
  75. float vertValue = VirtualInput.GetAxisValue(verticalAxis);
  76. yaw += new Degree(horzValue * RotationalSpeed * frameDelta);
  77. pitch += new Degree(vertValue * RotationalSpeed * frameDelta);
  78. yaw = MathEx.WrapAngle(yaw);
  79. pitch = MathEx.WrapAngle(pitch);
  80. Quaternion yRot = Quaternion.FromAxisAngle(Vector3.YAxis, yaw);
  81. Quaternion xRot = Quaternion.FromAxisAngle(Vector3.XAxis, pitch);
  82. Quaternion camRot = yRot * xRot;
  83. camRot.Normalize();
  84. SceneObject.Rotation = camRot;
  85. Vector3 direction = Vector3.Zero;
  86. if (goingForward) direction += SceneObject.Forward;
  87. if (goingBack) direction -= SceneObject.Forward;
  88. if (goingRight) direction += SceneObject.Right;
  89. if (goingLeft) direction -= SceneObject.Right;
  90. if (direction.SqrdLength != 0)
  91. {
  92. direction.Normalize();
  93. float multiplier = 1.0f;
  94. if (fastMove)
  95. multiplier = FastModeMultiplier;
  96. currentSpeed = MathEx.Clamp(currentSpeed + Acceleration * frameDelta, StartSpeed, TopSpeed);
  97. currentSpeed *= multiplier;
  98. }
  99. else
  100. {
  101. currentSpeed = 0.0f;
  102. }
  103. const float tooSmall = 0.0001f;
  104. if (currentSpeed > tooSmall)
  105. {
  106. Vector3 velocity = direction * currentSpeed;
  107. SceneObject.Move(velocity * frameDelta);
  108. }
  109. }
  110. UpdateAnim();
  111. }
  112. /// <summary>
  113. /// Enables or disables camera controls.
  114. /// </summary>
  115. /// <param name="enable">True to enable controls, false to disable.</param>
  116. public void EnableInput(bool enable)
  117. {
  118. if (inputEnabled == enable)
  119. return;
  120. inputEnabled = enable;
  121. if (!inputEnabled)
  122. {
  123. if (VirtualInput.IsButtonHeld(activeBtn))
  124. Cursor.Show();
  125. }
  126. }
  127. /// <summary>
  128. /// Focuses the camera on the currently selected object(s).
  129. /// </summary>
  130. public void FrameSelected()
  131. {
  132. SceneObject[] selectedObjects = Selection.SceneObjects;
  133. if (selectedObjects.Length > 0)
  134. {
  135. AABox box = EditorUtility.CalculateBounds(Selection.SceneObjects);
  136. FrameBounds(box);
  137. }
  138. }
  139. /// <summary>
  140. /// Moves and orients a camera so that the provided bounds end covering the camera's viewport.
  141. /// </summary>
  142. /// <param name="bounds">Bounds to frame in camera's view.</param>
  143. /// <param name="padding">Amount of padding to leave on the borders of the viewport, in percent [0, 1].</param>
  144. private void FrameBounds(AABox bounds, float padding = 0.0f)
  145. {
  146. // TODO - Use AABox bounds directly instead of a sphere to be more accurate
  147. float worldWidth = bounds.Size.Length;
  148. float worldHeight = worldWidth;
  149. if (worldWidth == 0.0f)
  150. worldWidth = 1.0f;
  151. if (worldHeight == 0.0f)
  152. worldHeight = 1.0f;
  153. float boundsAspect = worldWidth / worldHeight;
  154. float paddingScale = MathEx.Clamp01(padding) + 1.0f;
  155. float frustumWidth;
  156. // If camera has wider aspect than bounds then height will be the limiting dimension
  157. if (camera.AspectRatio > boundsAspect)
  158. frustumWidth = worldHeight * camera.AspectRatio * paddingScale;
  159. else // Otherwise width
  160. frustumWidth = worldWidth * paddingScale;
  161. float distance = CalcDistanceForFrustumWidth(frustumWidth);
  162. Vector3 forward = bounds.Center - SceneObject.Position;
  163. forward.Normalize();
  164. CameraState state = new CameraState();
  165. state.Position = bounds.Center - forward * distance;
  166. state.Rotation = Quaternion.LookRotation(forward, Vector3.YAxis);
  167. state.Ortographic = camera.ProjectionType == ProjectionType.Orthographic;
  168. state.FrustumWidth = frustumWidth;
  169. SetState(state);
  170. }
  171. /// <summary>
  172. /// Changes the state of the camera, either instantly or animated over several frames. The state includes
  173. /// camera position, rotation, type and possibly other parameters.
  174. /// </summary>
  175. /// <param name="state">New state of the camera.</param>
  176. /// <param name="animated">Should the state be linearly interpolated over a course of several frames.</param>
  177. private void SetState(CameraState state, bool animated = true)
  178. {
  179. CameraState startState = new CameraState();
  180. startState.Position = SceneObject.Position;
  181. startState.Rotation = SceneObject.Rotation;
  182. startState.Ortographic = camera.ProjectionType == ProjectionType.Orthographic;
  183. startState.FrustumWidth = frustumWidth;
  184. animation.Start(startState, state);
  185. if (!animated)
  186. {
  187. ApplyState(1.0f);
  188. isAnimating = false;
  189. }
  190. else
  191. {
  192. isAnimating = true;
  193. lerp = 0.0f;
  194. }
  195. }
  196. /// <summary>
  197. /// Applies the animation target state depending on the interpolation parameter. <see cref="SetState"/>.
  198. /// </summary>
  199. /// <param name="t">Interpolation parameter ranging [0, 1] that interpolated between the start state and the
  200. /// target state.</param>
  201. private void ApplyState(float t)
  202. {
  203. animation.Update(t);
  204. SceneObject.Position = animation.State.Position;
  205. SceneObject.Rotation = animation.State.Rotation;
  206. frustumWidth = animation.State.FrustumWidth;
  207. Vector3 eulerAngles = SceneObject.Rotation.ToEuler();
  208. pitch = eulerAngles.x;
  209. yaw = eulerAngles.y;
  210. Degree FOV = (1.0f - animation.State.OrtographicPct)*FieldOfView;
  211. if (FOV < 5.0f)
  212. {
  213. camera.ProjectionType = ProjectionType.Orthographic;
  214. camera.OrthoHeight = frustumWidth * 0.5f / camera.AspectRatio;
  215. }
  216. else
  217. {
  218. camera.ProjectionType = ProjectionType.Perspective;
  219. camera.FieldOfView = FOV;
  220. }
  221. // Note: Consider having a global setting for near/far planes as changing it here might confuse the user
  222. float distance = CalcDistanceForFrustumWidth(frustumWidth);
  223. if (distance < 1)
  224. {
  225. camera.NearClipPlane = 0.005f;
  226. camera.FarClipPlane = 1000f;
  227. }
  228. if (distance < 100)
  229. {
  230. camera.NearClipPlane = 0.05f;
  231. camera.FarClipPlane = 2500f;
  232. }
  233. else if (distance < 1000)
  234. {
  235. camera.NearClipPlane = 0.5f;
  236. camera.FarClipPlane = 10000f;
  237. }
  238. else
  239. {
  240. camera.NearClipPlane = 5.0f;
  241. camera.FarClipPlane = 1000000f;
  242. }
  243. }
  244. /// <summary>
  245. /// Calculates distance at which the camera's frustum width is equal to the provided width.
  246. /// </summary>
  247. /// <param name="frustumWidth">Frustum width to find the distance for, in world units.</param>
  248. /// <returns>Distance at which the camera's frustum is the specified width, in world units.</returns>
  249. private float CalcDistanceForFrustumWidth(float frustumWidth)
  250. {
  251. if (camera.ProjectionType == ProjectionType.Perspective)
  252. return (frustumWidth*0.5f)/MathEx.Tan(camera.FieldOfView*0.5f);
  253. else
  254. return frustumWidth * 2.0f;
  255. }
  256. /// <summary>
  257. /// Updates camera state transition animation. Should be called every frame.
  258. /// </summary>
  259. private void UpdateAnim()
  260. {
  261. if (!isAnimating)
  262. return;
  263. const float ANIM_TIME = 0.5f; // 0.5f seconds
  264. lerp += Time.FrameDelta * (1.0f / ANIM_TIME);
  265. if (lerp >= 1.0f)
  266. {
  267. lerp = 1.0f;
  268. isAnimating = false;
  269. }
  270. ApplyState(lerp);
  271. }
  272. /// <summary>
  273. /// Contains data for a possible camera state. Camera states can be interpolated between each other as needed.
  274. /// </summary>
  275. private struct CameraState
  276. {
  277. private float _ortographic;
  278. public Vector3 Position { get; set; }
  279. public Quaternion Rotation { get; set; }
  280. public float FrustumWidth { get; set; }
  281. public bool Ortographic
  282. {
  283. get { return _ortographic > 0.5; }
  284. set { _ortographic = value ? 1.0f : 0.0f; }
  285. }
  286. public float OrtographicPct
  287. {
  288. get { return _ortographic; }
  289. set { _ortographic = value; }
  290. }
  291. }
  292. /// <summary>
  293. /// Helper class that performs linear interpolation between two camera states.
  294. /// </summary>
  295. private struct CameraAnimation
  296. {
  297. private CameraState start;
  298. private CameraState target;
  299. private CameraState interpolated;
  300. /// <summary>
  301. /// Returns currently interpolated animation state.
  302. /// </summary>
  303. public CameraState State
  304. {
  305. get { return interpolated; }
  306. }
  307. /// <summary>
  308. /// Initializes the animation with initial and target states.
  309. /// </summary>
  310. /// <param name="start">Initial state to animate from.</param>
  311. /// <param name="target">Target state to animate towards.</param>
  312. public void Start(CameraState start, CameraState target)
  313. {
  314. this.start = start;
  315. this.target = target;
  316. }
  317. /// <summary>
  318. /// Updates the animation by interpolating between the start and target states.
  319. /// </summary>
  320. /// <param name="t">Interpolation parameter in range [0, 1] that determines how much to interpolate between
  321. /// start and target states.</param>
  322. public void Update(float t)
  323. {
  324. interpolated.Position = start.Position * (1.0f - t) + target.Position * t;
  325. interpolated.Rotation = Quaternion.Slerp(start.Rotation, target.Rotation, t);
  326. interpolated.OrtographicPct = start.OrtographicPct * (1.0f - t) + target.OrtographicPct * t;
  327. interpolated.FrustumWidth = start.FrustumWidth * (1.0f - t) + target.FrustumWidth * t;
  328. }
  329. };
  330. }
  331. }