BloomComponent.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. //-----------------------------------------------------------------------------
  2. // BloomComponent.cs
  3. //
  4. // Microsoft XNA Community Game Platform
  5. // Copyright (C) Microsoft Corporation. All rights reserved.
  6. //-----------------------------------------------------------------------------
  7. using System;
  8. using Microsoft.Xna.Framework;
  9. using Microsoft.Xna.Framework.Content;
  10. using Microsoft.Xna.Framework.Graphics;
  11. namespace BloomSample.Core
  12. {
  13. public class BloomComponent : DrawableGameComponent
  14. {
  15. SpriteBatch spriteBatch;
  16. Effect bloomExtractEffect;
  17. Effect bloomCombineEffect;
  18. Effect gaussianBlurEffect;
  19. RenderTarget2D sceneRenderTarget;
  20. RenderTarget2D renderTarget1;
  21. RenderTarget2D renderTarget2;
  22. // Choose what display settings the bloom should use.
  23. public BloomSettings Settings
  24. {
  25. get { return settings; }
  26. set { settings = value; }
  27. }
  28. BloomSettings settings = BloomSettings.PresetSettings[0];
  29. // Optionally displays one of the intermediate buffers used
  30. // by the bloom postprocess, so you can see exactly what is
  31. // being drawn into each rendertarget.
  32. public enum IntermediateBuffer
  33. {
  34. PreBloom,
  35. BlurredHorizontally,
  36. BlurredBothWays,
  37. FinalResult,
  38. }
  39. public IntermediateBuffer ShowBuffer
  40. {
  41. get { return showBuffer; }
  42. set { showBuffer = value; }
  43. }
  44. IntermediateBuffer showBuffer = IntermediateBuffer.FinalResult;
  45. public BloomComponent(Game game)
  46. : base(game)
  47. {
  48. if (game == null)
  49. throw new ArgumentNullException("game");
  50. }
  51. /// <summary>
  52. /// Load your graphics content.
  53. /// </summary>
  54. protected override void LoadContent()
  55. {
  56. spriteBatch = new SpriteBatch(GraphicsDevice);
  57. bloomExtractEffect = Game.Content.Load<Effect>("BloomExtract");
  58. bloomCombineEffect = Game.Content.Load<Effect>("BloomCombine");
  59. gaussianBlurEffect = Game.Content.Load<Effect>("GaussianBlur");
  60. // Look up the resolution and format of our main backbuffer.
  61. PresentationParameters pp = GraphicsDevice.PresentationParameters;
  62. int width = pp.BackBufferWidth;
  63. int height = pp.BackBufferHeight;
  64. SurfaceFormat format = pp.BackBufferFormat;
  65. // Create a texture for rendering the main scene, prior to applying bloom.
  66. sceneRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, false,
  67. format, pp.DepthStencilFormat, pp.MultiSampleCount,
  68. RenderTargetUsage.DiscardContents);
  69. // Create two rendertargets for the bloom processing. These are half the
  70. // size of the backbuffer, in order to minimize fillrate costs. Reducing
  71. // the resolution in this way doesn't hurt quality, because we are going
  72. // to be blurring the bloom images in any case.
  73. width /= 2;
  74. height /= 2;
  75. renderTarget1 = new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None);
  76. renderTarget2 = new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None);
  77. }
  78. /// <summary>
  79. /// Unload your graphics content.
  80. /// </summary>
  81. protected override void UnloadContent()
  82. {
  83. sceneRenderTarget.Dispose();
  84. renderTarget1.Dispose();
  85. renderTarget2.Dispose();
  86. }
  87. /// <summary>
  88. /// This should be called at the very start of the scene rendering. The bloom
  89. /// component uses it to redirect drawing into its custom rendertarget, so it
  90. /// can capture the scene image in preparation for applying the bloom filter.
  91. /// </summary>
  92. public void BeginDraw()
  93. {
  94. if (Visible)
  95. {
  96. GraphicsDevice.SetRenderTarget(sceneRenderTarget);
  97. }
  98. }
  99. /// <summary>
  100. /// This is where it all happens. Grabs a scene that has already been rendered,
  101. /// and uses postprocess magic to add a glowing bloom effect over the top of it.
  102. /// </summary>
  103. public override void Draw(GameTime gameTime)
  104. {
  105. GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp;
  106. // Pass 1: draw the scene into rendertarget 1, using a
  107. // shader that extracts only the brightest parts of the image.
  108. bloomExtractEffect.Parameters["BloomThreshold"].SetValue(
  109. Settings.BloomThreshold);
  110. DrawFullscreenQuad(sceneRenderTarget, renderTarget1,
  111. bloomExtractEffect,
  112. IntermediateBuffer.PreBloom);
  113. // Pass 2: draw from rendertarget 1 into rendertarget 2,
  114. // using a shader to apply a horizontal gaussian blur filter.
  115. SetBlurEffectParameters(1.0f / (float)renderTarget1.Width, 0);
  116. DrawFullscreenQuad(renderTarget1, renderTarget2,
  117. gaussianBlurEffect,
  118. IntermediateBuffer.BlurredHorizontally);
  119. // Pass 3: draw from rendertarget 2 back into rendertarget 1,
  120. // using a shader to apply a vertical gaussian blur filter.
  121. SetBlurEffectParameters(0, 1.0f / (float)renderTarget1.Height);
  122. DrawFullscreenQuad(renderTarget2, renderTarget1,
  123. gaussianBlurEffect,
  124. IntermediateBuffer.BlurredBothWays);
  125. // Pass 4: draw both rendertarget 1 and the original scene
  126. // image back into the main backbuffer, using a shader that
  127. // combines them to produce the final bloomed result.
  128. GraphicsDevice.SetRenderTarget(null);
  129. EffectParameterCollection parameters = bloomCombineEffect.Parameters;
  130. parameters["BloomIntensity"].SetValue(Settings.BloomIntensity);
  131. parameters["BaseIntensity"].SetValue(Settings.BaseIntensity);
  132. parameters["BloomSaturation"].SetValue(Settings.BloomSaturation);
  133. parameters["BaseSaturation"].SetValue(Settings.BaseSaturation);
  134. GraphicsDevice.Textures[1] = sceneRenderTarget;
  135. Viewport viewport = GraphicsDevice.Viewport;
  136. DrawFullscreenQuad(renderTarget1,
  137. viewport.Width, viewport.Height,
  138. bloomCombineEffect,
  139. IntermediateBuffer.FinalResult);
  140. }
  141. /// <summary>
  142. /// Helper for drawing a texture into a rendertarget, using
  143. /// a custom shader to apply postprocessing effects.
  144. /// </summary>
  145. void DrawFullscreenQuad(Texture2D texture, RenderTarget2D renderTarget,
  146. Effect effect, IntermediateBuffer currentBuffer)
  147. {
  148. GraphicsDevice.SetRenderTarget(renderTarget);
  149. DrawFullscreenQuad(texture,
  150. renderTarget.Width, renderTarget.Height,
  151. effect, currentBuffer);
  152. }
  153. /// <summary>
  154. /// Helper for drawing a texture into the current rendertarget,
  155. /// using a custom shader to apply postprocessing effects.
  156. /// </summary>
  157. void DrawFullscreenQuad(Texture2D texture, int width, int height,
  158. Effect effect, IntermediateBuffer currentBuffer)
  159. {
  160. // If the user has selected one of the show intermediate buffer options,
  161. // we still draw the quad to make sure the image will end up on the screen,
  162. // but might need to skip applying the custom pixel shader.
  163. if (showBuffer < currentBuffer)
  164. {
  165. effect = null;
  166. }
  167. spriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect);
  168. spriteBatch.Draw(texture, new Rectangle(0, 0, width, height), Color.White);
  169. spriteBatch.End();
  170. }
  171. /// <summary>
  172. /// Computes sample weightings and texture coordinate offsets
  173. /// for one pass of a separable gaussian blur filter.
  174. /// </summary>
  175. void SetBlurEffectParameters(float dx, float dy)
  176. {
  177. // Look up the sample weight and offset effect parameters.
  178. EffectParameter weightsParameter, offsetsParameter;
  179. weightsParameter = gaussianBlurEffect.Parameters["SampleWeights"];
  180. offsetsParameter = gaussianBlurEffect.Parameters["SampleOffsets"];
  181. // Look up how many samples our gaussian blur effect supports.
  182. int sampleCount = weightsParameter.Elements.Count;
  183. // Create temporary arrays for computing our filter settings.
  184. float[] sampleWeights = new float[sampleCount];
  185. Vector2[] sampleOffsets = new Vector2[sampleCount];
  186. // The first sample always has a zero offset.
  187. sampleWeights[0] = ComputeGaussian(0);
  188. sampleOffsets[0] = new Vector2(0);
  189. // Maintain a sum of all the weighting values.
  190. float totalWeights = sampleWeights[0];
  191. // Add pairs of additional sample taps, positioned
  192. // along a line in both directions from the center.
  193. for (int i = 0; i < sampleCount / 2; i++)
  194. {
  195. // Store weights for the positive and negative taps.
  196. float weight = ComputeGaussian(i + 1);
  197. sampleWeights[i * 2 + 1] = weight;
  198. sampleWeights[i * 2 + 2] = weight;
  199. totalWeights += weight * 2;
  200. // To get the maximum amount of blurring from a limited number of
  201. // pixel shader samples, we take advantage of the bilinear filtering
  202. // hardware inside the texture fetch unit. If we position our texture
  203. // coordinates exactly halfway between two texels, the filtering unit
  204. // will average them for us, giving two samples for the price of one.
  205. // This allows us to step in units of two texels per sample, rather
  206. // than just one at a time. The 1.5 offset kicks things off by
  207. // positioning us nicely in between two texels.
  208. float sampleOffset = i * 2 + 1.5f;
  209. Vector2 delta = new Vector2(dx, dy) * sampleOffset;
  210. // Store texture coordinate offsets for the positive and negative taps.
  211. sampleOffsets[i * 2 + 1] = delta;
  212. sampleOffsets[i * 2 + 2] = -delta;
  213. }
  214. // Normalize the list of sample weightings, so they will always sum to one.
  215. for (int i = 0; i < sampleWeights.Length; i++)
  216. {
  217. sampleWeights[i] /= totalWeights;
  218. }
  219. // Tell the effect about our new filter settings.
  220. weightsParameter.SetValue(sampleWeights);
  221. offsetsParameter.SetValue(sampleOffsets);
  222. }
  223. /// <summary>
  224. /// Evaluates a single point on the gaussian falloff curve.
  225. /// Used for setting up the blur filter weightings.
  226. /// </summary>
  227. float ComputeGaussian(float n)
  228. {
  229. float theta = Settings.BlurAmount;
  230. return (float)((1.0 / Math.Sqrt(2 * Math.PI * theta)) *
  231. Math.Exp(-(n * n) / (2 * theta * theta)));
  232. }
  233. }
  234. }