ScreenManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // ScreenManager.cs
  4. //
  5. // Microsoft XNA Community Game Platform
  6. // Copyright (C) Microsoft Corporation. All rights reserved.
  7. //-----------------------------------------------------------------------------
  8. #endregion
  9. #region Using Statements
  10. using System;
  11. using System.Diagnostics;
  12. using System.Collections.Generic;
  13. using Microsoft.Xna.Framework;
  14. using Microsoft.Xna.Framework.Content;
  15. using Microsoft.Xna.Framework.Graphics;
  16. using Microsoft.Xna.Framework.Input.Touch;
  17. using System.IO;
  18. using System.IO.IsolatedStorage;
  19. #endregion
  20. namespace GameStateManagement
  21. {
  22. /// <summary>
  23. /// The screen manager is a component which manages one or more GameScreen
  24. /// instances. It maintains a stack of screens, calls their Update and Draw
  25. /// methods at the appropriate times, and automatically routes input to the
  26. /// topmost active screen.
  27. /// </summary>
  28. public class ScreenManager : DrawableGameComponent
  29. {
  30. #region Fields
  31. List<GameScreen> screens = new List<GameScreen>();
  32. List<GameScreen> screensToUpdate = new List<GameScreen>();
  33. InputState input = new InputState();
  34. SpriteBatch spriteBatch;
  35. SpriteFont font;
  36. Texture2D blankTexture;
  37. bool isInitialized;
  38. bool traceEnabled;
  39. #endregion
  40. #region Properties
  41. /// <summary>
  42. /// A default SpriteBatch shared by all the screens. This saves
  43. /// each screen having to bother creating their own local instance.
  44. /// </summary>
  45. public SpriteBatch SpriteBatch
  46. {
  47. get { return spriteBatch; }
  48. }
  49. /// <summary>
  50. /// A default font shared by all the screens. This saves
  51. /// each screen having to bother loading their own local copy.
  52. /// </summary>
  53. public SpriteFont Font
  54. {
  55. get { return font; }
  56. }
  57. /// <summary>
  58. /// If true, the manager prints out a list of all the screens
  59. /// each time it is updated. This can be useful for making sure
  60. /// everything is being added and removed at the right times.
  61. /// </summary>
  62. public bool TraceEnabled
  63. {
  64. get { return traceEnabled; }
  65. set { traceEnabled = value; }
  66. }
  67. #endregion
  68. #region Initialization
  69. /// <summary>
  70. /// Constructs a new screen manager component.
  71. /// </summary>
  72. public ScreenManager(Game game)
  73. : base(game)
  74. {
  75. // we must set EnabledGestures before we can query for them, but
  76. // we don't assume the game wants to read them.
  77. TouchPanel.EnabledGestures = GestureType.None;
  78. }
  79. /// <summary>
  80. /// Initializes the screen manager component.
  81. /// </summary>
  82. public override void Initialize()
  83. {
  84. base.Initialize();
  85. isInitialized = true;
  86. }
  87. /// <summary>
  88. /// Load your graphics content.
  89. /// </summary>
  90. protected override void LoadContent()
  91. {
  92. // Load content belonging to the screen manager.
  93. ContentManager content = Game.Content;
  94. spriteBatch = new SpriteBatch(GraphicsDevice);
  95. font = content.Load<SpriteFont>("Fonts/MenuFont");
  96. blankTexture = content.Load<Texture2D>("Textures/Backgrounds/blank");
  97. // Tell each of the screens to load their content.
  98. foreach (GameScreen screen in screens)
  99. {
  100. screen.LoadContent();
  101. }
  102. }
  103. /// <summary>
  104. /// Unload your graphics content.
  105. /// </summary>
  106. protected override void UnloadContent()
  107. {
  108. // Tell each of the screens to unload their content.
  109. foreach (GameScreen screen in screens)
  110. {
  111. screen.UnloadContent();
  112. }
  113. }
  114. #endregion
  115. #region Update and Draw
  116. /// <summary>
  117. /// Allows each screen to run logic.
  118. /// </summary>
  119. public override void Update(GameTime gameTime)
  120. {
  121. // Read the keyboard and gamepad.
  122. input.Update();
  123. // Make a copy of the master screen list, to avoid confusion if
  124. // the process of updating one screen adds or removes others.
  125. screensToUpdate.Clear();
  126. foreach (GameScreen screen in screens)
  127. screensToUpdate.Add(screen);
  128. bool otherScreenHasFocus = !Game.IsActive;
  129. bool coveredByOtherScreen = false;
  130. // Loop as long as there are screens waiting to be updated.
  131. while (screensToUpdate.Count > 0)
  132. {
  133. // Pop the topmost screen off the waiting list.
  134. GameScreen screen = screensToUpdate[screensToUpdate.Count - 1];
  135. screensToUpdate.RemoveAt(screensToUpdate.Count - 1);
  136. // Update the screen.
  137. screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
  138. if (screen.ScreenState == ScreenState.TransitionOn ||
  139. screen.ScreenState == ScreenState.Active)
  140. {
  141. // If this is the first active screen we came across,
  142. // give it a chance to handle input.
  143. if (!otherScreenHasFocus)
  144. {
  145. screen.HandleInput(input);
  146. otherScreenHasFocus = true;
  147. }
  148. // If this is an active non-popup, inform any subsequent
  149. // screens that they are covered by it.
  150. if (!screen.IsPopup)
  151. coveredByOtherScreen = true;
  152. }
  153. }
  154. // Print debug trace?
  155. if (traceEnabled)
  156. TraceScreens();
  157. }
  158. /// <summary>
  159. /// Prints a list of all the screens, for debugging.
  160. /// </summary>
  161. void TraceScreens()
  162. {
  163. List<string> screenNames = new List<string>();
  164. foreach (GameScreen screen in screens)
  165. screenNames.Add(screen.GetType().Name);
  166. Debug.WriteLine(string.Join(", ", screenNames.ToArray()));
  167. }
  168. /// <summary>
  169. /// Tells each screen to draw itself.
  170. /// </summary>
  171. public override void Draw(GameTime gameTime)
  172. {
  173. foreach (GameScreen screen in screens)
  174. {
  175. if (screen.ScreenState == ScreenState.Hidden)
  176. continue;
  177. screen.Draw(gameTime);
  178. }
  179. }
  180. #endregion
  181. #region Public Methods
  182. /// <summary>
  183. /// Adds a new screen to the screen manager.
  184. /// </summary>
  185. public void AddScreen(GameScreen screen, PlayerIndex? controllingPlayer)
  186. {
  187. screen.ControllingPlayer = controllingPlayer;
  188. screen.ScreenManager = this;
  189. screen.IsExiting = false;
  190. // If we have a graphics device, tell the screen to load content.
  191. if (isInitialized)
  192. {
  193. screen.LoadContent();
  194. }
  195. screens.Add(screen);
  196. // update the TouchPanel to respond to gestures this screen is interested in
  197. TouchPanel.EnabledGestures = screen.EnabledGestures;
  198. }
  199. /// <summary>
  200. /// Removes a screen from the screen manager. You should normally
  201. /// use GameScreen.ExitScreen instead of calling this directly, so
  202. /// the screen can gradually transition off rather than just being
  203. /// instantly removed.
  204. /// </summary>
  205. public void RemoveScreen(GameScreen screen)
  206. {
  207. // If we have a graphics device, tell the screen to unload content.
  208. if (isInitialized)
  209. {
  210. screen.UnloadContent();
  211. }
  212. screens.Remove(screen);
  213. screensToUpdate.Remove(screen);
  214. // if there is a screen still in the manager, update TouchPanel
  215. // to respond to gestures that screen is interested in.
  216. if (screens.Count > 0)
  217. {
  218. TouchPanel.EnabledGestures = screens[screens.Count - 1].EnabledGestures;
  219. }
  220. }
  221. /// <summary>
  222. /// Expose an array holding all the screens. We return a copy rather
  223. /// than the real master list, because screens should only ever be added
  224. /// or removed using the AddScreen and RemoveScreen methods.
  225. /// </summary>
  226. public GameScreen[] GetScreens()
  227. {
  228. return screens.ToArray();
  229. }
  230. /// <summary>
  231. /// Helper draws a translucent black fullscreen sprite, used for fading
  232. /// screens in and out, and for darkening the background behind popups.
  233. /// </summary>
  234. public void FadeBackBufferToBlack(float alpha)
  235. {
  236. Viewport viewport = GraphicsDevice.Viewport;
  237. spriteBatch.Begin();
  238. spriteBatch.Draw(blankTexture,
  239. new Rectangle(0, 0, viewport.Width, viewport.Height),
  240. Color.Black * alpha);
  241. spriteBatch.End();
  242. }
  243. /// <summary>
  244. /// Informs the screen manager to serialize its state to disk.
  245. /// </summary>
  246. public void SerializeState()
  247. {
  248. // open up isolated storage
  249. using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
  250. {
  251. // if our screen manager directory already exists, delete the contents
  252. if (storage.DirectoryExists("ScreenManager"))
  253. {
  254. DeleteState(storage);
  255. }
  256. // otherwise just create the directory
  257. else
  258. {
  259. storage.CreateDirectory("ScreenManager");
  260. }
  261. // create a file we'll use to store the list of screens in the stack
  262. using (IsolatedStorageFileStream stream = storage.CreateFile("ScreenManager\\ScreenList.dat"))
  263. {
  264. using (BinaryWriter writer = new BinaryWriter(stream))
  265. {
  266. // write out the full name of all the types in our stack so we can
  267. // recreate them if needed.
  268. foreach (GameScreen screen in screens)
  269. {
  270. if (screen.IsSerializable)
  271. {
  272. writer.Write(screen.GetType().AssemblyQualifiedName);
  273. }
  274. }
  275. }
  276. }
  277. // now we create a new file stream for each screen so it can save its state
  278. // if it needs to. we name each file "ScreenX.dat" where X is the index of
  279. // the screen in the stack, to ensure the files are uniquely named
  280. int screenIndex = 0;
  281. foreach (GameScreen screen in screens)
  282. {
  283. if (screen.IsSerializable)
  284. {
  285. string fileName = string.Format("ScreenManager\\Screen{0}.dat", screenIndex);
  286. // open up the stream and let the screen serialize whatever state it wants
  287. using (IsolatedStorageFileStream stream = storage.CreateFile(fileName))
  288. {
  289. screen.Serialize(stream);
  290. }
  291. screenIndex++;
  292. }
  293. }
  294. }
  295. }
  296. public bool DeserializeState()
  297. {
  298. // open up isolated storage
  299. using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
  300. {
  301. // see if our saved state directory exists
  302. if (storage.DirectoryExists("ScreenManager"))
  303. {
  304. try
  305. {
  306. // see if we have a screen list
  307. if (storage.FileExists("ScreenManager\\ScreenList.dat"))
  308. {
  309. // load the list of screen types
  310. using (IsolatedStorageFileStream stream =
  311. storage.OpenFile("ScreenManager\\ScreenList.dat", FileMode.Open, FileAccess.Read))
  312. {
  313. using (BinaryReader reader = new BinaryReader(stream))
  314. {
  315. while (reader.BaseStream.Position < reader.BaseStream.Length)
  316. {
  317. // read a line from our file
  318. string line = reader.ReadString();
  319. // if it isn't blank, we can create a screen from it
  320. if (!string.IsNullOrEmpty(line))
  321. {
  322. Type screenType = Type.GetType(line);
  323. GameScreen screen = Activator.CreateInstance(screenType) as GameScreen;
  324. AddScreen(screen, PlayerIndex.One);
  325. }
  326. }
  327. }
  328. }
  329. }
  330. // next we give each screen a chance to deserialize from the disk
  331. for (int i = 0; i < screens.Count; i++)
  332. {
  333. string filename = string.Format("ScreenManager\\Screen{0}.dat", i);
  334. using (IsolatedStorageFileStream stream =
  335. storage.OpenFile(filename, FileMode.Open, FileAccess.Read))
  336. {
  337. screens[i].Deserialize(stream);
  338. }
  339. }
  340. return true;
  341. }
  342. catch (Exception)
  343. {
  344. // if an exception was thrown while reading, odds are we cannot recover
  345. // from the saved state, so we will delete it so the game can correctly
  346. // launch.
  347. DeleteState(storage);
  348. }
  349. }
  350. }
  351. return false;
  352. }
  353. /// <summary>
  354. /// Deletes the saved state files from isolated storage.
  355. /// </summary>
  356. private void DeleteState(IsolatedStorageFile storage)
  357. {
  358. // get all of the files in the directory and delete them
  359. string[] files = storage.GetFileNames("ScreenManager\\*");
  360. foreach (string file in files)
  361. {
  362. storage.DeleteFile(Path.Combine("ScreenManager", file));
  363. }
  364. }
  365. #endregion
  366. }
  367. }