Game1.cs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Microsoft.Xna.Framework;
  5. using Microsoft.Xna.Framework.Audio;
  6. using Microsoft.Xna.Framework.Content;
  7. using Microsoft.Xna.Framework.GamerServices;
  8. using Microsoft.Xna.Framework.Graphics;
  9. using Microsoft.Xna.Framework.Input;
  10. using Microsoft.Xna.Framework.Media;
  11. namespace RenderTarget2DSample
  12. {
  13. /// <summary>
  14. /// This is the main type for your game
  15. /// </summary>
  16. public class Game1 : Microsoft.Xna.Framework.Game
  17. {
  18. /// <summary>
  19. /// The GraphicsDeviceManager is what creates and automagically manages the game's GraphicsDevice.
  20. /// </summary>
  21. GraphicsDeviceManager graphics;
  22. /// <summary>
  23. /// We use SpriteBatch to draw all of our 2D graphics.
  24. /// </summary>
  25. SpriteBatch spriteBatch;
  26. /// <summary>
  27. /// This is the rendertarget we'll be drawing to.
  28. /// </summary>
  29. RenderTarget2D renderTarget;
  30. /// <summary>
  31. /// This is a texture we'll be using to load a picture of Seamus the dog.
  32. /// </summary>
  33. Texture2D mooTheMerciless;
  34. /// <summary>
  35. /// This is a texture we'll be using to load a picture of a tileable wood surface.
  36. /// </summary>
  37. Texture2D wood;
  38. bool oneTimeOnly = true;
  39. /// <summary>
  40. /// The constructor for our Game1 class.
  41. /// </summary>
  42. #if ANDROID
  43. public Game1(AndroidGameActivity activity)
  44. : base(activity)
  45. #else
  46. public Game1 ()
  47. #endif
  48. {
  49. // Create the GraphicsDeviceManager for our game.
  50. graphics = new GraphicsDeviceManager (this);
  51. #if ANDROID || IOS
  52. graphics.IsFullScreen = true;
  53. #else
  54. graphics.PreferredBackBufferWidth = screenWidth;
  55. graphics.PreferredBackBufferHeight = screenHeight;
  56. graphics.IsFullScreen = false;
  57. #endif
  58. // Set the root directory of the game's ContentManager to the "Content" folder.
  59. Content.RootDirectory = "Content";
  60. }
  61. /// <summary>
  62. /// Allows the game to perform any initialization it needs to before starting to run.
  63. /// This is where it can query for any required services and load any non-graphic
  64. /// related content. Calling base.Initialize will enumerate through any components
  65. /// and initialize them as well.
  66. /// </summary>
  67. protected override void Initialize ()
  68. {
  69. // We don't have anything to initialize.
  70. base.Initialize ();
  71. }
  72. /// <summary>
  73. /// LoadContent will be called once per game and is the place to load
  74. /// all of your content.
  75. /// </summary>
  76. protected override void LoadContent ()
  77. {
  78. // Create a new SpriteBatch, which can be used to draw textures.
  79. spriteBatch = new SpriteBatch (GraphicsDevice);
  80. // Create a rendertarget that matches the back buffer's dimensions, does not generate mipmaps automatically
  81. // (the Reach profile requires power of 2 sizing in order to do that), uses an RGBA color format, and
  82. // has no depth buffer or stencil buffer.
  83. renderTarget = new RenderTarget2D (GraphicsDevice, GraphicsDevice.PresentationParameters.BackBufferWidth,
  84. GraphicsDevice.PresentationParameters.BackBufferHeight, false, SurfaceFormat.Color, DepthFormat.None);
  85. // Load in the picture of Seamus.
  86. mooTheMerciless = Content.Load<Texture2D> ("MooTheMerciless");
  87. // Load in our wood tile.
  88. wood = Content.Load<Texture2D> ("wood");
  89. }
  90. /// <summary>
  91. /// UnloadContent will be called once per game and is the place to unload
  92. /// all content.
  93. /// </summary>
  94. protected override void UnloadContent ()
  95. {
  96. // While not strictly necessary, you should always dispose of assets you create
  97. // (excluding those you load the the ContentManager) when those assets implement
  98. // IDisposable. RenderTarget2D is one such asset type, so we dispose of it properly.
  99. if (renderTarget != null) {
  100. // We put this in a try-catch block. The reason is that if for some odd reason this failed
  101. // (e.g. we were using threading and nulled out renderTarget on some other thread),
  102. // then none of the rest of the UnloadContent method would run. Here it doesn't make a
  103. // difference, but it's good practice nonethless.
  104. try {
  105. renderTarget.Dispose ();
  106. renderTarget = null;
  107. } catch {
  108. }
  109. }
  110. }
  111. /// <summary>
  112. /// Allows the game to run logic such as updating the world,
  113. /// checking for collisions, gathering input, and playing audio.
  114. /// </summary>
  115. /// <param name="gameTime">Provides a snapshot of timing values.</param>
  116. protected override void Update (GameTime gameTime)
  117. {
  118. // Allows the game to exit. If this is a Windows version, I also like to check for an Esc key press. I put
  119. // it within an #if WINDOWS .. #endif block since that way it won't run on other platforms.
  120. if (GamePad.GetState (PlayerIndex.One).Buttons.Back == ButtonState.Pressed
  121. //#if WINDOWS
  122. || Keyboard.GetState ().IsKeyDown (Keys.Escape)
  123. //#endif
  124. ) {
  125. this.Exit ();
  126. }
  127. // We don't have any update logic since this is just an example usage of RenderTarget2D
  128. base.Update (gameTime);
  129. }
  130. /// <summary>
  131. /// This is called when the game should draw itself.
  132. /// </summary>
  133. /// <param name="gameTime">Provides a snapshot of timing values.</param>
  134. protected override void Draw (GameTime gameTime)
  135. {
  136. // A one time only flag to help test for memory leaks
  137. if (oneTimeOnly) {
  138. oneTimeOnly = false;
  139. // Set renderTarget as the surface to draw to instead of the back buffer
  140. GraphicsDevice.SetRenderTarget (renderTarget);
  141. // Clear the renderTarget. By default it's all a bright purple color. I like to use Color.Transparent to
  142. // enable easy alpha blending.
  143. GraphicsDevice.Clear (Color.Transparent);
  144. Vector2 woodPosition = Vector2.Zero;
  145. // Begin drawing
  146. spriteBatch.Begin ();
  147. int xBlank = 0;
  148. int yBlank = 0;
  149. // Use nested do-whiles to fill the rendertarget with tiles. We use some trickery to draw every other tile
  150. do {
  151. do {
  152. // We use the modulus operator to get the remainder of dividing xBlank by 2. If xBlank is odd, it'll
  153. // return 1 and the spriteBatch.Draw call gets skipped. If it's even, it'll return 0 so
  154. // spriteBatch.Draw will get called and it'll draw a tile there.
  155. if (xBlank % 2 == 0) {
  156. spriteBatch.Draw (wood, woodPosition, Color.White);
  157. }
  158. // Increment xBlank by one so that every other tile will get drawn.
  159. xBlank++;
  160. // Increase the X coordinate of where we'll draw the wood tile in order to progressively draw
  161. // each column of tiles.
  162. woodPosition.X += wood.Width;
  163. // We draw so long as woodPosition.X is less than our renderTarget's width
  164. } while (woodPosition.X < renderTarget.Width);
  165. // We increment yBlank by one. Why is explained below.
  166. yBlank++;
  167. // We use the modulus operater to get the remainder of dividing yBlank by 2. If yBlank is odd, we reset
  168. // xBlank to 1. If it's even, we reset xBlank to 0. This way each row shifts by one so that the tiles
  169. // are drawn in a checkered pattern rather than in columns.
  170. if (yBlank % 2 == 0) {
  171. xBlank = 0;
  172. } else {
  173. xBlank = 1;
  174. }
  175. // Reset woodPosition.X to zero so that we start drawing from the beginning of the next row.
  176. woodPosition.X = 0;
  177. // Increase the Y coord of where we'll draw the wood tile in order to progressively draw each
  178. // row of tiles.
  179. woodPosition.Y += wood.Height;
  180. // We draw so long as woodPosition.Y is less than our renderTarget's width
  181. } while (woodPosition.Y < renderTarget.Height);
  182. // Now that we've drawn the wood tiles, we draw Moo the Merciless. We draw him centered in the rendertarget.
  183. spriteBatch.Draw (mooTheMerciless,
  184. new Vector2 ((renderTarget.Width / 2f) - (mooTheMerciless.Width / 2f), (renderTarget.Height / 2f) - (mooTheMerciless.Height / 2f)),
  185. Color.White);
  186. // End the spriteBatch draw.
  187. spriteBatch.End ();
  188. // Switch back to drawing onto the back buffer
  189. GraphicsDevice.SetRenderTarget (null);
  190. }
  191. // Now that we're back to drawing onto the back buffer, we want to clear it. If we had done so earlier
  192. // then when we switched to drawing to the render target, the old back buffer would've just be filled with
  193. // that bright purple color when we came back to it.
  194. GraphicsDevice.Clear (Color.CornflowerBlue);
  195. // Ok. At this point we have everything we drew in renderTarget, which we can use just like a regular Texture2D.
  196. // To make it look more interesting, we're going to scale up and down based on total elapsed time.
  197. float scale = 1.0f;
  198. if (gameTime.TotalGameTime.TotalSeconds % 10 < 5.0) {
  199. // We're running on a ten second scale timer. For the first five second we scale down from 1f to
  200. // no less than 0.01f.
  201. scale = MathHelper.Clamp (1f - (((float)gameTime.TotalGameTime.TotalSeconds % 5) / 5f), 0.01f, 1f);
  202. } else {
  203. // For the second five seconds, we scale up from no less than 0.01f up to 1f.
  204. scale = MathHelper.Clamp (((float)gameTime.TotalGameTime.TotalSeconds % 5) / 5f, 0.01f, 1f);
  205. }
  206. // Start spriteBatch again (this time drawing to the back buffer)
  207. spriteBatch.Begin ();
  208. // Now we draw our render target to the back buffer so that it will get displayed on the screen. We
  209. // position it in the center of the screen, but we make the origin be the center of the render target
  210. // such that it actually gets drawn centered (as opposed to shrinking and exanding with the left corner
  211. // in the center). We use our scale computation, and specify no SpriteEffects and an unused 0f for layer
  212. // depth
  213. spriteBatch.Draw (renderTarget,
  214. new Vector2 (GraphicsDevice.PresentationParameters.BackBufferWidth / 2, GraphicsDevice.PresentationParameters.BackBufferHeight / 2),
  215. null, Color.White, 0f, new Vector2 (renderTarget.Width / 2, renderTarget.Height / 2), scale,
  216. SpriteEffects.None, 0f);
  217. // End our spriteBatch call.
  218. spriteBatch.End ();
  219. base.Draw (gameTime);
  220. }
  221. }
  222. }