Game1.cs 9.6 KB

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