ScreenManager.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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.Input.Touch;
  14. using System.IO;
  15. using System.IO.IsolatedStorage;
  16. namespace GameStateManagement
  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. public class ScreenManager : DrawableGameComponent
  25. {
  26. List<GameScreen> screens = new List<GameScreen>();
  27. List<GameScreen> screensToUpdate = new List<GameScreen>();
  28. public InputState input = new InputState();
  29. SpriteBatch spriteBatch;
  30. SpriteFont font;
  31. Texture2D blankTexture;
  32. Texture2D buttonBackground;
  33. bool isInitialized;
  34. bool traceEnabled;
  35. internal const int BACK_BUFFER_WIDTH = 800;
  36. internal const int BACK_BUFFER_HEIGHT = 480;
  37. private int backbufferWidth;
  38. /// <summary>Gets or sets the current backbuffer width.</summary>
  39. public int BackbufferWidth { get => backbufferWidth; set => backbufferWidth = value; }
  40. private int backbufferHeight;
  41. /// <summary>Gets or sets the current backbuffer height.</summary>
  42. public int BackbufferHeight { get => backbufferHeight; set => backbufferHeight = value; }
  43. private Vector2 baseScreenSize = new Vector2(BACK_BUFFER_WIDTH, BACK_BUFFER_HEIGHT);
  44. /// <summary>Gets or sets the base screen size used for scaling calculations.</summary>
  45. public Vector2 BaseScreenSize { get => baseScreenSize; set => baseScreenSize = value; }
  46. private Matrix globalTransformation;
  47. /// <summary>Gets or sets the global transformation matrix for scaling and positioning.</summary>
  48. public Matrix GlobalTransformation { get => globalTransformation; set => globalTransformation = value; }
  49. /// <summary>
  50. /// A default SpriteBatch shared by all the screens. This saves
  51. /// each screen having to bother creating their own local instance.
  52. /// </summary>
  53. public SpriteBatch SpriteBatch
  54. {
  55. get { return spriteBatch; }
  56. }
  57. public Texture2D ButtonBackground
  58. {
  59. get { return buttonBackground; }
  60. }
  61. public Texture2D BlankTexture
  62. {
  63. get { return blankTexture; }
  64. }
  65. /// <summary>
  66. /// A default font shared by all the screens. This saves
  67. /// each screen having to bother loading their own local copy.
  68. /// </summary>
  69. public SpriteFont Font
  70. {
  71. get { return font; }
  72. }
  73. /// <summary>
  74. /// If true, the manager prints out a list of all the screens
  75. /// each time it is updated. This can be useful for making sure
  76. /// everything is being added and removed at the right times.
  77. /// </summary>
  78. public bool TraceEnabled
  79. {
  80. get { return traceEnabled; }
  81. set { traceEnabled = value; }
  82. }
  83. /// <summary>
  84. /// Returns the portion of the screen where drawing is safely allowed.
  85. /// </summary>
  86. public Rectangle SafeArea
  87. {
  88. get
  89. {
  90. return Game.GraphicsDevice.Viewport.TitleSafeArea;
  91. }
  92. }
  93. /// <summary>
  94. /// Constructs a new screen manager component.
  95. /// </summary>
  96. public ScreenManager(Game game)
  97. : base(game)
  98. {
  99. // we must set EnabledGestures before we can query for them, but
  100. // we don't assume the game wants to read them.
  101. TouchPanel.EnabledGestures = GestureType.None;
  102. }
  103. /// <summary>
  104. /// Initializes the screen manager component.
  105. /// </summary>
  106. public override void Initialize()
  107. {
  108. base.Initialize();
  109. isInitialized = true;
  110. }
  111. /// <summary>
  112. /// Load your graphics content.
  113. /// </summary>
  114. protected override void LoadContent()
  115. {
  116. // Load content belonging to the screen manager.
  117. ContentManager content = Game.Content;
  118. spriteBatch = new SpriteBatch(GraphicsDevice);
  119. font = content.Load<SpriteFont>("Fonts/MenuFont");
  120. blankTexture = content.Load<Texture2D>("Images/blank");
  121. buttonBackground = content.Load<Texture2D>("Images/ButtonRegular");
  122. // Tell each of the screens to load their content.
  123. foreach (GameScreen screen in screens)
  124. {
  125. screen.LoadContent();
  126. }
  127. }
  128. /// <summary>
  129. /// Unload your graphics content.
  130. /// </summary>
  131. protected override void UnloadContent()
  132. {
  133. // Tell each of the screens to unload their content.
  134. foreach (GameScreen screen in screens)
  135. {
  136. screen.UnloadContent();
  137. }
  138. }
  139. /// <summary>
  140. /// Allows each screen to run logic.
  141. /// </summary>
  142. public override void Update(GameTime gameTime)
  143. {
  144. // Read the keyboard and gamepad.
  145. input.Update();
  146. // Make a copy of the master screen list, to avoid confusion if
  147. // the process of updating one screen adds or removes others.
  148. screensToUpdate.Clear();
  149. foreach (GameScreen screen in screens)
  150. screensToUpdate.Add(screen);
  151. bool otherScreenHasFocus = !Game.IsActive;
  152. bool coveredByOtherScreen = false;
  153. // Loop as long as there are screens waiting to be updated.
  154. while (screensToUpdate.Count > 0)
  155. {
  156. // Pop the topmost screen off the waiting list.
  157. GameScreen screen = screensToUpdate[screensToUpdate.Count - 1];
  158. screensToUpdate.RemoveAt(screensToUpdate.Count - 1);
  159. // Update the screen.
  160. screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
  161. if (screen.ScreenState == ScreenState.TransitionOn ||
  162. screen.ScreenState == ScreenState.Active)
  163. {
  164. // If this is the first active screen we came across,
  165. // give it a chance to handle input.
  166. if (!otherScreenHasFocus)
  167. {
  168. screen.HandleInput(input);
  169. otherScreenHasFocus = true;
  170. }
  171. // If this is an active non-popup, inform any subsequent
  172. // screens that they are covered by it.
  173. if (!screen.IsPopup)
  174. coveredByOtherScreen = true;
  175. }
  176. }
  177. // Print debug trace?
  178. if (traceEnabled)
  179. TraceScreens();
  180. }
  181. /// <summary>
  182. /// Prints a list of all the screens, for debugging.
  183. /// </summary>
  184. void TraceScreens()
  185. {
  186. List<string> screenNames = new List<string>();
  187. foreach (GameScreen screen in screens)
  188. screenNames.Add(screen.GetType().Name);
  189. Debug.WriteLine(string.Join(", ", screenNames.ToArray()));
  190. }
  191. /// <summary>
  192. /// Tells each screen to draw itself.
  193. /// </summary>
  194. public override void Draw(GameTime gameTime)
  195. {
  196. foreach (GameScreen screen in screens)
  197. {
  198. if (screen.ScreenState == ScreenState.Hidden)
  199. continue;
  200. screen.Draw(gameTime);
  201. }
  202. }
  203. /// <summary>
  204. /// Adds a new screen to the screen manager.
  205. /// </summary>
  206. public void AddScreen(GameScreen screen, PlayerIndex? controllingPlayer)
  207. {
  208. screen.ControllingPlayer = controllingPlayer;
  209. screen.ScreenManager = this;
  210. screen.IsExiting = false;
  211. // If we have a graphics device, tell the screen to load content.
  212. if (isInitialized)
  213. {
  214. screen.LoadContent();
  215. }
  216. screens.Add(screen);
  217. // update the TouchPanel to respond to gestures this screen is interested in
  218. TouchPanel.EnabledGestures = screen.EnabledGestures;
  219. }
  220. /// <summary>
  221. /// Removes a screen from the screen manager. You should normally
  222. /// use GameScreen.ExitScreen instead of calling this directly, so
  223. /// the screen can gradually transition off rather than just being
  224. /// instantly removed.
  225. /// </summary>
  226. public void RemoveScreen(GameScreen screen)
  227. {
  228. // If we have a graphics device, tell the screen to unload content.
  229. if (isInitialized)
  230. {
  231. screen.UnloadContent();
  232. }
  233. screens.Remove(screen);
  234. screensToUpdate.Remove(screen);
  235. // if there is a screen still in the manager, update TouchPanel
  236. // to respond to gestures that screen is interested in.
  237. if (screens.Count > 0)
  238. {
  239. TouchPanel.EnabledGestures = screens[screens.Count - 1].EnabledGestures;
  240. }
  241. }
  242. /// <summary>
  243. /// Expose an array holding all the screens. We return a copy rather
  244. /// than the real master list, because screens should only ever be added
  245. /// or removed using the AddScreen and RemoveScreen methods.
  246. /// </summary>
  247. public GameScreen[] GetScreens()
  248. {
  249. return screens.ToArray();
  250. }
  251. /// <summary>
  252. /// Helper draws a translucent black fullscreen sprite, used for fading
  253. /// screens in and out, and for darkening the background behind popups.
  254. /// </summary>
  255. public void FadeBackBufferToBlack(float alpha)
  256. {
  257. Viewport viewport = GraphicsDevice.Viewport;
  258. spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, GlobalTransformation);
  259. spriteBatch.Draw(blankTexture,
  260. new Rectangle(0, 0, viewport.Width, viewport.Height),
  261. Color.Black * alpha);
  262. spriteBatch.End();
  263. }
  264. /// <summary>
  265. /// Scales the game presentation area to match the screen's aspect ratio.
  266. /// </summary>
  267. public void ScalePresentationArea()
  268. {
  269. // Validate parameters before calculation
  270. if (GraphicsDevice == null || baseScreenSize.X <= 0 || baseScreenSize.Y <= 0)
  271. {
  272. throw new InvalidOperationException("Invalid graphics configuration");
  273. }
  274. // Fetch screen dimensions
  275. backbufferWidth = GraphicsDevice.PresentationParameters.BackBufferWidth;
  276. backbufferHeight = GraphicsDevice.PresentationParameters.BackBufferHeight;
  277. // Prevent division by zero
  278. if (backbufferHeight == 0 || baseScreenSize.Y == 0)
  279. {
  280. return;
  281. }
  282. // Calculate aspect ratios
  283. float baseAspectRatio = baseScreenSize.X / baseScreenSize.Y;
  284. float screenAspectRatio = backbufferWidth / (float)backbufferHeight;
  285. // Determine uniform scaling factor
  286. float scalingFactor;
  287. float horizontalOffset = 0;
  288. float verticalOffset = 0;
  289. if (screenAspectRatio > baseAspectRatio)
  290. {
  291. // Wider screen: scale by height
  292. scalingFactor = backbufferHeight / baseScreenSize.Y;
  293. // Centre things horizontally.
  294. horizontalOffset = (backbufferWidth - baseScreenSize.X * scalingFactor) / 2;
  295. }
  296. else
  297. {
  298. // Taller screen: scale by width
  299. scalingFactor = backbufferWidth / baseScreenSize.X;
  300. // Centre things vertically.
  301. verticalOffset = (backbufferHeight - baseScreenSize.Y * scalingFactor) / 2;
  302. }
  303. // Update the transformation matrix
  304. globalTransformation = Matrix.CreateScale(scalingFactor) *
  305. Matrix.CreateTranslation(horizontalOffset, verticalOffset, 0);
  306. // Update the inputTransformation with the Inverted globalTransformation
  307. // TODO inputState.UpdateInputTransformation(Matrix.Invert(globalTransformation));
  308. // Debug info
  309. Debug.WriteLine($"Screen Size - Width[{backbufferWidth}] Height[{backbufferHeight}] ScalingFactor[{scalingFactor}]");
  310. }
  311. /// <summary>
  312. /// Informs the screen manager to serialize its state to disk.
  313. /// </summary>
  314. public void SerializeState()
  315. {
  316. // open up isolated storage
  317. using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
  318. {
  319. // if our screen manager directory already exists, delete the contents
  320. if (storage.DirectoryExists("ScreenManager"))
  321. {
  322. DeleteState(storage);
  323. }
  324. // otherwise just create the directory
  325. else
  326. {
  327. storage.CreateDirectory("ScreenManager");
  328. }
  329. // create a file we'll use to store the list of screens in the stack
  330. using (IsolatedStorageFileStream stream = storage.CreateFile("ScreenManager\\ScreenList.dat"))
  331. {
  332. using (BinaryWriter writer = new BinaryWriter(stream))
  333. {
  334. // write out the full name of all the types in our stack so we can
  335. // recreate them if needed.
  336. foreach (GameScreen screen in screens)
  337. {
  338. if (screen.IsSerializable)
  339. {
  340. writer.Write(screen.GetType().AssemblyQualifiedName);
  341. }
  342. }
  343. }
  344. }
  345. // now we create a new file stream for each screen so it can save its state
  346. // if it needs to. we name each file "ScreenX.dat" where X is the index of
  347. // the screen in the stack, to ensure the files are uniquely named
  348. int screenIndex = 0;
  349. foreach (GameScreen screen in screens)
  350. {
  351. if (screen.IsSerializable)
  352. {
  353. string fileName = string.Format("ScreenManager\\Screen{0}.dat", screenIndex);
  354. // open up the stream and let the screen serialize whatever state it wants
  355. using (IsolatedStorageFileStream stream = storage.CreateFile(fileName))
  356. {
  357. screen.Serialize(stream);
  358. }
  359. screenIndex++;
  360. }
  361. }
  362. }
  363. }
  364. public bool DeserializeState()
  365. {
  366. // open up isolated storage
  367. using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
  368. {
  369. // see if our saved state directory exists
  370. if (storage.DirectoryExists("ScreenManager"))
  371. {
  372. try
  373. {
  374. // see if we have a screen list
  375. if (storage.FileExists("ScreenManager\\ScreenList.dat"))
  376. {
  377. // load the list of screen types
  378. using (IsolatedStorageFileStream stream =
  379. storage.OpenFile("ScreenManager\\ScreenList.dat", FileMode.Open,
  380. FileAccess.Read))
  381. {
  382. using (BinaryReader reader = new BinaryReader(stream))
  383. {
  384. while (reader.BaseStream.Position < reader.BaseStream.Length)
  385. {
  386. // read a line from our file
  387. string line = reader.ReadString();
  388. // if it isn't blank, we can create a screen from it
  389. if (!string.IsNullOrEmpty(line))
  390. {
  391. Type screenType = Type.GetType(line);
  392. GameScreen screen = Activator.CreateInstance(screenType) as GameScreen;
  393. AddScreen(screen, PlayerIndex.One);
  394. }
  395. }
  396. }
  397. }
  398. }
  399. // next we give each screen a chance to deserialize from the disk
  400. for (int i = 0; i < screens.Count; i++)
  401. {
  402. string filename = string.Format("ScreenManager\\Screen{0}.dat", i);
  403. using (IsolatedStorageFileStream stream = storage.OpenFile(filename,
  404. FileMode.Open, FileAccess.Read))
  405. {
  406. screens[i].Deserialize(stream);
  407. }
  408. }
  409. return true;
  410. }
  411. catch (Exception)
  412. {
  413. // if an exception was thrown while reading, odds are we cannot recover
  414. // from the saved state, so we will delete it so the game can correctly
  415. // launch.
  416. DeleteState(storage);
  417. }
  418. }
  419. }
  420. return false;
  421. }
  422. /// <summary>
  423. /// Deletes the saved state files from isolated storage.
  424. /// </summary>
  425. private void DeleteState(IsolatedStorageFile storage)
  426. {
  427. // get all of the files in the directory and delete them
  428. string[] files = storage.GetFileNames("ScreenManager\\*");
  429. foreach (string file in files)
  430. {
  431. storage.DeleteFile(Path.Combine("ScreenManager", file));
  432. }
  433. }
  434. }
  435. }