ScreenManager.cs 18 KB

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