2
0

SceneCamera.cs 19 KB

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