ScreenManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. //-----------------------------------------------------------------------------
  2. // ScreenManager.cs
  3. //
  4. // Microsoft XNA Community Game Platform
  5. // Copyright (C) Microsoft Corporation. All rights reserved.
  6. //-----------------------------------------------------------------------------
  7. using System;
  8. using System.Diagnostics;
  9. using System.Collections.Generic;
  10. using Microsoft.Xna.Framework;
  11. using Microsoft.Xna.Framework.Content;
  12. using Microsoft.Xna.Framework.Graphics;
  13. using System.Text;
  14. using Microsoft.Xna.Framework.Input.Touch;
  15. namespace RolePlaying
  16. {
  17. /// <summary>
  18. /// The screen manager is a component which manages one or more GameScreen
  19. /// instances. It maintains a stack of screens, calls their Update and Draw
  20. /// methods at the appropriate times, and automatically routes input to the
  21. /// topmost active screen.
  22. /// </summary>
  23. /// <remarks>
  24. /// Similar to a class found in the Game State Management sample on the
  25. /// XNA Creators Club Online website (http://creators.xna.com).
  26. /// </remarks>
  27. public class ScreenManager : DrawableGameComponent
  28. {
  29. List<GameScreen> screens = new List<GameScreen>();
  30. List<GameScreen> screensToUpdate = new List<GameScreen>();
  31. SpriteBatch spriteBatch;
  32. private Texture2D blankTexture;
  33. bool isInitialized;
  34. bool traceEnabled;
  35. private int backbufferWidth;
  36. /// <summary>Gets or sets the current backbuffer width.</summary>
  37. public int BackbufferWidth { get => backbufferWidth; set => backbufferWidth = value; }
  38. private int backbufferHeight;
  39. /// <summary>Gets or sets the current backbuffer height.</summary>
  40. public int BackbufferHeight { get => backbufferHeight; set => backbufferHeight = value; }
  41. private Vector2 baseScreenSize = new Vector2(Session.BACK_BUFFER_WIDTH, Session.BACK_BUFFER_HEIGHT);
  42. /// <summary>Gets or sets the base screen size used for scaling calculations.</summary>
  43. public Vector2 BaseScreenSize { get => baseScreenSize; set => baseScreenSize = value; }
  44. private Matrix globalTransformation;
  45. /// <summary>Gets or sets the global transformation matrix for scaling and positioning.</summary>
  46. public Matrix GlobalTransformation { get => globalTransformation; set => globalTransformation = value; }
  47. /// <summary>
  48. /// A default SpriteBatch shared by all the screens. This saves
  49. /// each screen having to bother creating their own local instance.
  50. /// </summary>
  51. public SpriteBatch SpriteBatch
  52. {
  53. get { return spriteBatch; }
  54. }
  55. /// <summary>
  56. /// If true, the manager prints out a list of all the screens
  57. /// each time it is updated. This can be useful for making sure
  58. /// everything is being added and removed at the right times.
  59. /// </summary>
  60. public bool TraceEnabled
  61. {
  62. get { return traceEnabled; }
  63. set { traceEnabled = value; }
  64. }
  65. /// <summary>
  66. /// Constructs a new screen manager component.
  67. /// </summary>
  68. public ScreenManager(Game game)
  69. : base(game)
  70. {
  71. TouchPanel.EnabledGestures = GestureType.None;
  72. }
  73. /// <summary>
  74. /// Initializes the screen manager component.
  75. /// </summary>
  76. public override void Initialize()
  77. {
  78. base.Initialize();
  79. isInitialized = true;
  80. }
  81. /// <summary>
  82. /// Load your graphics content.
  83. /// </summary>
  84. protected override void LoadContent()
  85. {
  86. // Load content belonging to the screen manager.
  87. ContentManager content = Game.Content;
  88. spriteBatch = new SpriteBatch(GraphicsDevice);
  89. blankTexture = content.Load<Texture2D>("Textures/GameScreens/blank");
  90. // Tell each of the screens to load their content.
  91. foreach (GameScreen screen in screens)
  92. {
  93. screen.LoadContent();
  94. }
  95. }
  96. /// <summary>
  97. /// Unload your graphics content.
  98. /// </summary>
  99. protected override void UnloadContent()
  100. {
  101. // Tell each of the screens to unload their content.
  102. foreach (GameScreen screen in screens)
  103. {
  104. screen.UnloadContent();
  105. }
  106. }
  107. /// <summary>
  108. /// Allows each screen to run logic.
  109. /// </summary>
  110. public override void Update(GameTime gameTime)
  111. {
  112. // Make a copy of the master screen list, to avoid confusion if
  113. // the process of updating one screen adds or removes others.
  114. screensToUpdate.Clear();
  115. foreach (GameScreen screen in screens)
  116. screensToUpdate.Add(screen);
  117. bool otherScreenHasFocus = !Game.IsActive;
  118. bool coveredByOtherScreen = false;
  119. // Loop as long as there are screens waiting to be updated.
  120. while (screensToUpdate.Count > 0)
  121. {
  122. // Pop the topmost screen off the waiting list.
  123. GameScreen screen = screensToUpdate[screensToUpdate.Count - 1];
  124. screensToUpdate.RemoveAt(screensToUpdate.Count - 1);
  125. // Update the screen.
  126. screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
  127. if (screen.ScreenState == ScreenState.TransitionOn ||
  128. screen.ScreenState == ScreenState.Active)
  129. {
  130. // If this is the first active screen we came across,
  131. // give it a chance to handle input.
  132. if (!otherScreenHasFocus)
  133. {
  134. screen.HandleInput();
  135. otherScreenHasFocus = true;
  136. }
  137. // If this is an active non-popup, inform any subsequent
  138. // screens that they are covered by it.
  139. if (!screen.IsPopup)
  140. coveredByOtherScreen = true;
  141. }
  142. }
  143. // Print debug trace?
  144. if (traceEnabled)
  145. TraceScreens();
  146. }
  147. /// <summary>
  148. /// Prints a list of all the screens, for debugging.
  149. /// </summary>
  150. void TraceScreens()
  151. {
  152. List<string> screenNames = new List<string>();
  153. foreach (GameScreen screen in screens)
  154. screenNames.Add(screen.GetType().Name);
  155. #if DEBUG
  156. Trace.WriteLine(string.Join(", ", screenNames.ToArray()));
  157. #endif
  158. }
  159. /// <summary>
  160. /// Tells each screen to draw itself.
  161. /// </summary>
  162. public override void Draw(GameTime gameTime)
  163. {
  164. foreach (GameScreen screen in screens)
  165. {
  166. if (screen.ScreenState == ScreenState.Hidden)
  167. continue;
  168. screen.Draw(gameTime);
  169. }
  170. }
  171. /// <summary>
  172. /// Adds a new screen to the screen manager.
  173. /// </summary>
  174. public void AddScreen(GameScreen screen)
  175. {
  176. screen.ScreenManager = this;
  177. screen.IsExiting = false;
  178. // If we have a graphics device, tell the screen to load content.
  179. if (isInitialized)
  180. {
  181. screen.LoadContent();
  182. }
  183. screens.Add(screen);
  184. TouchPanel.EnabledGestures = screen.EnabledGestures;
  185. }
  186. /// <summary>
  187. /// Removes a screen from the screen manager. You should normally
  188. /// use GameScreen.ExitScreen instead of calling this directly, so
  189. /// the screen can gradually transition off rather than just being
  190. /// instantly removed.
  191. /// </summary>
  192. public void RemoveScreen(GameScreen screen)
  193. {
  194. // If we have a graphics device, tell the screen to unload content.
  195. if (isInitialized)
  196. {
  197. screen.UnloadContent();
  198. }
  199. screens.Remove(screen);
  200. screensToUpdate.Remove(screen);
  201. }
  202. /// <summary>
  203. /// Expose an array holding all the screens. We return a copy rather
  204. /// than the real master list, because screens should only ever be added
  205. /// or removed using the AddScreen and RemoveScreen methods.
  206. /// </summary>
  207. public GameScreen[] GetScreens()
  208. {
  209. return screens.ToArray();
  210. }
  211. /// <summary>
  212. /// Draws a translucent black fullscreen sprite. This is used for fading
  213. /// screens in and out, or for darkening the background behind popups.
  214. /// </summary>
  215. /// <param name="alpha">The opacity level of the fade (0 = fully transparent, 1 = fully opaque).</param>
  216. public void FadeBackBufferToBlack(float alpha)
  217. {
  218. spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, GlobalTransformation);
  219. spriteBatch.Draw(blankTexture,
  220. new Rectangle(0, 0, Session.BACK_BUFFER_WIDTH, Session.BACK_BUFFER_HEIGHT),
  221. Color.Black * alpha);
  222. spriteBatch.End();
  223. }
  224. /// <summary>
  225. /// Scales the game presentation area to match the screen's aspect ratio.
  226. /// </summary>
  227. public void ScalePresentationArea()
  228. {
  229. // Validate parameters before calculation
  230. if (GraphicsDevice == null || baseScreenSize.X <= 0 || baseScreenSize.Y <= 0)
  231. {
  232. throw new InvalidOperationException("Invalid graphics configuration");
  233. }
  234. // Fetch screen dimensions
  235. backbufferWidth = GraphicsDevice.PresentationParameters.BackBufferWidth;
  236. backbufferHeight = GraphicsDevice.PresentationParameters.BackBufferHeight;
  237. // Prevent division by zero
  238. if (backbufferHeight == 0 || baseScreenSize.Y == 0)
  239. {
  240. return;
  241. }
  242. // Calculate aspect ratios
  243. float baseAspectRatio = baseScreenSize.X / baseScreenSize.Y;
  244. float screenAspectRatio = backbufferWidth / (float)backbufferHeight;
  245. // Determine uniform scaling factor
  246. float scalingFactor;
  247. float horizontalOffset = 0;
  248. float verticalOffset = 0;
  249. if (screenAspectRatio > baseAspectRatio)
  250. {
  251. // Wider screen: scale by height
  252. scalingFactor = backbufferHeight / baseScreenSize.Y;
  253. // Centre things horizontally.
  254. horizontalOffset = (backbufferWidth - baseScreenSize.X * scalingFactor) / 2;
  255. }
  256. else
  257. {
  258. // Taller screen: scale by width
  259. scalingFactor = backbufferWidth / baseScreenSize.X;
  260. // Centre things vertically.
  261. verticalOffset = (backbufferHeight - baseScreenSize.Y * scalingFactor) / 2;
  262. }
  263. // Update the transformation matrix
  264. globalTransformation = Matrix.CreateScale(scalingFactor) *
  265. Matrix.CreateTranslation(horizontalOffset, verticalOffset, 0);
  266. // Update the inputTransformation with the Inverted globalTransformation
  267. // TODO inputState.UpdateInputTransformation(Matrix.Invert(globalTransformation));
  268. // Debug info
  269. Debug.WriteLine($"Screen Size - Width[{backbufferWidth}] Height[{backbufferHeight}] ScalingFactor[{scalingFactor}]");
  270. }
  271. }
  272. }