Game1.cs 9.9 KB

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