ScreenManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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 Microsoft.Xna.Framework.GamerServices;
  14. namespace NetRumble
  15. {
  16. /// <summary>
  17. /// The screen manager is a component which manages one or more GameScreen
  18. /// instances. It maintains a stack of screens, calls their Update and Draw
  19. /// methods at the appropriate times, and automatically routes input to the
  20. /// topmost active screen.
  21. /// </summary>
  22. /// <remarks>
  23. /// This public class is similar to one in the GameStateManagement sample.
  24. /// </remarks>
  25. public class ScreenManager : DrawableGameComponent
  26. {
  27. List<GameScreen> screens = new List<GameScreen>();
  28. List<GameScreen> screensToUpdate = new List<GameScreen>();
  29. List<GameScreen> screensToDraw = new List<GameScreen>();
  30. InputState inputState = new InputState(BASE_BUFFER_WIDTH, BASE_BUFFER_HEIGHT);
  31. public InputState InputState => inputState;
  32. IGraphicsDeviceService graphicsDeviceService;
  33. public SignedInGamer invited;
  34. ContentManager content;
  35. SpriteBatch spriteBatch;
  36. SpriteFont font;
  37. Texture2D blankTexture;
  38. Rectangle titleSafeArea;
  39. bool traceEnabled;
  40. internal const int BASE_BUFFER_WIDTH = 1280;
  41. internal const int BASE_BUFFER_HEIGHT = 720;
  42. private int backbufferWidth;
  43. /// <summary>Gets or sets the current backbuffer width.</summary>
  44. public int BackbufferWidth { get => backbufferWidth; set => backbufferWidth = value; }
  45. private int backbufferHeight;
  46. /// <summary>Gets or sets the current backbuffer height.</summary>
  47. public int BackbufferHeight { get => backbufferHeight; set => backbufferHeight = value; }
  48. private Vector2 baseScreenSize = new Vector2(BASE_BUFFER_WIDTH, BASE_BUFFER_HEIGHT);
  49. /// <summary>Gets or sets the base screen size used for scaling calculations.</summary>
  50. public Vector2 BaseScreenSize { get => baseScreenSize; set => baseScreenSize = value; }
  51. private static Matrix globalTransformation = Matrix.Identity;
  52. /// <summary>Gets or sets the global transformation matrix for scaling and positioning.</summary>
  53. public static Matrix GlobalTransformation { get => globalTransformation; set => globalTransformation = value; }
  54. /// <summary>
  55. /// Expose access to our Game instance (this is protected in the
  56. /// default GameComponent, but we want to make it public).
  57. /// </summary>
  58. new public Game Game
  59. {
  60. get { return base.Game; }
  61. }
  62. /// <summary>
  63. /// Expose access to our graphics device (this is protected in the
  64. /// default DrawableGameComponent, but we want to make it public).
  65. /// </summary>
  66. new public GraphicsDevice GraphicsDevice
  67. {
  68. get { return base.GraphicsDevice; }
  69. }
  70. /// <summary>
  71. /// A content manager used to load data that is shared between multiple
  72. /// screens. This is never unloaded, so if a screen requires a large amount
  73. /// of temporary data, it should create a local content manager instead.
  74. /// </summary>
  75. public ContentManager Content
  76. {
  77. get { return content; }
  78. }
  79. /// <summary>
  80. /// A default SpriteBatch shared by all the screens. This saves
  81. /// each screen having to bother creating their own local instance.
  82. /// </summary>
  83. public SpriteBatch SpriteBatch
  84. {
  85. get { return spriteBatch; }
  86. }
  87. /// <summary>
  88. /// A default font shared by all the screens. This saves
  89. /// each screen having to bother loading their own local copy.
  90. /// </summary>
  91. public SpriteFont Font
  92. {
  93. get { return font; }
  94. }
  95. /// <summary>
  96. /// If true, the manager prints out a list of all the screens
  97. /// each time it is updated. This can be useful for making sure
  98. /// everything is being added and removed at the right times.
  99. /// </summary>
  100. public bool TraceEnabled
  101. {
  102. get { return traceEnabled; }
  103. set { traceEnabled = value; }
  104. }
  105. /// <summary>
  106. /// The title-safe area for the menus.
  107. /// </summary>
  108. public Rectangle TitleSafeArea
  109. {
  110. get { return titleSafeArea; }
  111. }
  112. /// <summary>
  113. /// Constructs a new screen manager component.
  114. /// </summary>
  115. public ScreenManager(Game game)
  116. : base(game)
  117. {
  118. content = new ContentManager(game.Services, "Content");
  119. graphicsDeviceService = (IGraphicsDeviceService)game.Services.GetService(
  120. typeof(IGraphicsDeviceService));
  121. if (graphicsDeviceService == null)
  122. throw new InvalidOperationException("No graphics device service.");
  123. invited = null;
  124. }
  125. /// <summary>
  126. /// Load your graphics content.
  127. /// </summary>
  128. protected override void LoadContent()
  129. {
  130. // Load content belonging to the screen manager.
  131. spriteBatch = new SpriteBatch(GraphicsDevice);
  132. font = content.Load<SpriteFont>("Fonts/MenuFont");
  133. blankTexture = content.Load<Texture2D>("Textures/blank");
  134. // Tell each of the screens to load their content.
  135. foreach (GameScreen screen in screens)
  136. {
  137. screen.LoadContent();
  138. }
  139. // update the title-safe area
  140. titleSafeArea = new Rectangle(
  141. (int)Math.Floor(ScreenManager.BASE_BUFFER_WIDTH * 0.05f),
  142. (int)Math.Floor(ScreenManager.BASE_BUFFER_HEIGHT * 0.05f),
  143. (int)Math.Floor(ScreenManager.BASE_BUFFER_WIDTH * 0.9f),
  144. (int)Math.Floor(ScreenManager.BASE_BUFFER_HEIGHT * 0.9f));
  145. }
  146. /// <summary>
  147. /// Unload your graphics content.
  148. /// </summary>
  149. protected override void UnloadContent()
  150. {
  151. // Unload content belonging to the screen manager.
  152. content.Unload();
  153. // Tell each of the screens to unload their content.
  154. foreach (GameScreen screen in screens)
  155. {
  156. screen.UnloadContent();
  157. }
  158. }
  159. /// <summary>
  160. /// Allows each screen to run logic.
  161. /// </summary>
  162. public override void Update(GameTime gameTime)
  163. {
  164. // Read the keyboard and gamepad.
  165. inputState.Update();
  166. // Make a copy of the master screen list, to avoid confusion if
  167. // the process of updating one screen adds or removes others
  168. // (or it happens on another thread)
  169. screensToUpdate.Clear();
  170. foreach (GameScreen screen in screens)
  171. screensToUpdate.Add(screen);
  172. bool otherScreenHasFocus = !Game.IsActive;
  173. bool coveredByOtherScreen = false;
  174. // Loop as long as there are screens waiting to be updated.
  175. while (screensToUpdate.Count > 0)
  176. {
  177. // Pop the topmost screen off the waiting list.
  178. GameScreen screen = screensToUpdate[screensToUpdate.Count - 1];
  179. screensToUpdate.RemoveAt(screensToUpdate.Count - 1);
  180. // Update the screen.
  181. screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
  182. if (screen.ScreenState == ScreenState.TransitionOn ||
  183. screen.ScreenState == ScreenState.Active)
  184. {
  185. // If this is the first active screen we came across,
  186. // give it a chance to handle input and update presence.
  187. if (!otherScreenHasFocus)
  188. {
  189. screen.HandleInput(inputState);
  190. screen.UpdatePresence(); // presence support
  191. otherScreenHasFocus = true;
  192. }
  193. // If this is an active non-popup, inform any subsequent
  194. // screens that they are covered by it.
  195. if (!screen.IsPopup)
  196. coveredByOtherScreen = true;
  197. }
  198. }
  199. // Print debug trace?
  200. if (traceEnabled)
  201. TraceScreens();
  202. }
  203. /// <summary>
  204. /// Prints a list of all the screens, for debugging.
  205. /// </summary>
  206. void TraceScreens()
  207. {
  208. List<string> screenNames = new List<string>();
  209. foreach (GameScreen screen in screens)
  210. screenNames.Add(screen.GetType().Name);
  211. Debug.WriteLine(string.Join(", ", screenNames.ToArray()));
  212. }
  213. /// <summary>
  214. /// Tells each screen to draw itself.
  215. /// </summary>
  216. public override void Draw(GameTime gameTime)
  217. {
  218. // Make a copy of the master screen list, to avoid confusion if
  219. // the process of drawing one screen adds or removes others
  220. // (or it happens on another thread
  221. screensToDraw.Clear();
  222. foreach (GameScreen screen in screens)
  223. screensToDraw.Add(screen);
  224. foreach (GameScreen screen in screensToDraw)
  225. {
  226. if (screen.ScreenState == ScreenState.Hidden)
  227. continue;
  228. screen.Draw(gameTime);
  229. }
  230. }
  231. /// <summary>
  232. /// Draw an empty rectangle of the given size and color.
  233. /// </summary>
  234. /// <param name="rectangle">The destination rectangle.</param>
  235. /// <param name="color">The color of the rectangle.</param>
  236. public void DrawRectangle(Rectangle rectangle, Color color)
  237. {
  238. //SpriteBatch.Begin();
  239. // We changed this to be Opaque
  240. spriteBatch.Begin(0, BlendState.Opaque, null, null, null);
  241. SpriteBatch.Draw(blankTexture, rectangle, color);
  242. SpriteBatch.End();
  243. }
  244. /// <summary>
  245. /// Adds a new screen to the screen manager.
  246. /// </summary>
  247. public void AddScreen(GameScreen screen)
  248. {
  249. screen.ScreenManager = this;
  250. // If we have a graphics device, tell the screen to load content.
  251. if ((graphicsDeviceService != null) &&
  252. (graphicsDeviceService.GraphicsDevice != null))
  253. {
  254. screen.LoadContent();
  255. }
  256. screens.Add(screen);
  257. }
  258. /// <summary>
  259. /// Removes a screen from the screen manager. You should normally
  260. /// use GameScreen.ExitScreen instead of calling this directly, so
  261. /// the screen can gradually transition off rather than just being
  262. /// instantly removed.
  263. /// </summary>
  264. public void RemoveScreen(GameScreen screen)
  265. {
  266. // If we have a graphics device, tell the screen to unload content.
  267. if ((graphicsDeviceService != null) &&
  268. (graphicsDeviceService.GraphicsDevice != null))
  269. {
  270. screen.UnloadContent();
  271. }
  272. screens.Remove(screen);
  273. screensToUpdate.Remove(screen);
  274. }
  275. /// <summary>
  276. /// Expose an array holding all the screens. We return a copy rather
  277. /// than the real master list, because screens should only ever be added
  278. /// or removed using the AddScreen and RemoveScreen methods.
  279. /// </summary>
  280. public GameScreen[] GetScreens()
  281. {
  282. return screens.ToArray();
  283. }
  284. /// <summary>
  285. /// Helper draws a translucent black fullscreen sprite, used for fading
  286. /// screens in and out, and for darkening the background behind popups.
  287. /// </summary>
  288. public void FadeBackBufferToBlack(int alpha)
  289. {
  290. spriteBatch.Begin();
  291. spriteBatch.Draw(blankTexture,
  292. new Rectangle(0, 0, BASE_BUFFER_WIDTH, BASE_BUFFER_HEIGHT),
  293. new Color((byte)0, (byte)0, (byte)0, (byte)alpha));
  294. spriteBatch.End();
  295. }
  296. /// <summary>
  297. /// Scales the game presentation area to match the screen's aspect ratio.
  298. /// </summary>
  299. public void ScalePresentationArea()
  300. {
  301. // Validate parameters before calculation
  302. if (GraphicsDevice == null || baseScreenSize.X <= 0 || baseScreenSize.Y <= 0)
  303. {
  304. throw new InvalidOperationException("Invalid graphics configuration");
  305. }
  306. // Fetch screen dimensions
  307. backbufferWidth = GraphicsDevice.PresentationParameters.BackBufferWidth;
  308. backbufferHeight = GraphicsDevice.PresentationParameters.BackBufferHeight;
  309. // Prevent division by zero
  310. if (backbufferHeight == 0 || baseScreenSize.Y == 0)
  311. {
  312. return;
  313. }
  314. // Calculate aspect ratios
  315. float baseAspectRatio = baseScreenSize.X / baseScreenSize.Y;
  316. float screenAspectRatio = backbufferWidth / (float)backbufferHeight;
  317. // Determine uniform scaling factor
  318. float scalingFactor;
  319. float horizontalOffset = 0;
  320. float verticalOffset = 0;
  321. if (screenAspectRatio > baseAspectRatio)
  322. {
  323. // Wider screen: scale by height
  324. scalingFactor = backbufferHeight / baseScreenSize.Y;
  325. // Centre things horizontally.
  326. horizontalOffset = (backbufferWidth - baseScreenSize.X * scalingFactor) / 2;
  327. }
  328. else
  329. {
  330. // Taller screen: scale by width
  331. scalingFactor = backbufferWidth / baseScreenSize.X;
  332. // Centre things vertically.
  333. verticalOffset = (backbufferHeight - baseScreenSize.Y * scalingFactor) / 2;
  334. }
  335. // Update the transformation matrix
  336. globalTransformation = Matrix.CreateScale(scalingFactor) *
  337. Matrix.CreateTranslation(horizontalOffset, verticalOffset, 0);
  338. // Update the inputTransformation with the Inverted globalTransformation
  339. inputState.UpdateInputTransformation(Matrix.Invert(globalTransformation));
  340. // Debug info
  341. Debug.WriteLine($"Screen Size - Width[{backbufferWidth}] Height[{backbufferHeight}] ScalingFactor[{scalingFactor}]");
  342. }
  343. }
  344. }