ScreenManager.cs 11 KB

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