@Ravendarke by setting bloom.ShowBuffer = BloomComponent.IntermediateBuffer here is what being drawn:
PRE-BLOOM:
BLURRED BOTH WAYS:
FINAL RESULT:
Bloom Combine:
// Pixel shader combines the bloom image with the original
// scene, using tweakable intensity levels and saturation.
// This is the final step in applying a bloom postprocess.
sampler BloomSampler : register(s0);
sampler BaseSampler : register(s1)
{
Texture = (BaseTexture);
Filter = Linear;
AddressU = clamp;
AddressV = clamp;
};
float BloomIntensity;
float BaseIntensity;
float BloomSaturation;
float BaseSaturation;
// Helper for modifying the saturation of a color.
float4 AdjustSaturation(float4 color, float saturation)
{
// The constants 0.3, 0.59, and 0.11 are chosen because the
// human eye is more sensitive to green light, and less to blue.
float grey = dot(color, float3(0.3, 0.59, 0.11));
return lerp(grey, color, saturation);
}
float4 PixelShaderFunction(float2 texCoord : TEXCOORD0) : COLOR0
{
// Look up the bloom and original base image colors.
float4 bloom = tex2D(BloomSampler, texCoord);
float4 base = tex2D(BaseSampler, texCoord);
// Adjust color saturation and intensity.
bloom = AdjustSaturation(bloom, BloomSaturation) * BloomIntensity;
base = AdjustSaturation(base, BaseSaturation) * BaseIntensity;
// Darken down the base image in areas where there is a lot of bloom,
// to prevent things looking excessively burned-out.
base *= (1 - saturate(bloom));
// Combine the two images.
return base + bloom;
}
technique BloomCombine
{
pass Pass1
{
#if SM4
PixelShader = compile ps_4_0_level_9_1 PixelShaderFunction();
#elif SM3
PixelShader = compile ps_3_0 PixelShaderFunction();
#else
PixelShader = compile ps_2_0 PixelShaderFunction();
#endif
}
}
Bloom Compontent with set texture in parameter:
#region File Description
//-----------------------------------------------------------------------------
// BloomComponent.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System.IO;
#endregion
namespace BloomPostprocess
{
public class BloomComponent : DrawableGameComponent
{
#region Fields
SpriteBatch spriteBatch;
Effect bloomExtractEffect;
Effect bloomCombineEffect;
Effect gaussianBlurEffect;
RenderTarget2D renderTarget1;
RenderTarget2D renderTarget2;
// Choose what display settings the bloom should use.
public BloomSettings Settings
{
get { return settings; }
set { settings = value; }
}
BloomSettings settings = BloomSettings.PresetSettings[0];
// Optionally displays one of the intermediate buffers used
// by the bloom postprocess, so you can see exactly what is
// being drawn into each rendertarget.
public enum IntermediateBuffer
{
PreBloom,
BlurredHorizontally,
BlurredBothWays,
FinalResult,
}
public IntermediateBuffer ShowBuffer
{
get { return showBuffer; }
set { showBuffer = value; }
}
IntermediateBuffer showBuffer = IntermediateBuffer.FinalResult;
#endregion
#region Initialization
public BloomComponent(Game game)
: base(game)
{
if (game == null)
throw new ArgumentNullException("game");
}
/// <summary>
/// Load your graphics content.
/// </summary>
public void LoadContent(GraphicsDevice g, ContentManager theContentManager)
{
spriteBatch = new SpriteBatch(g);
bloomExtractEffect = theContentManager.Load<Effect>("BloomExtract");
bloomCombineEffect = theContentManager.Load<Effect>("BloomCombine");
gaussianBlurEffect = theContentManager.Load<Effect>("GaussianBlur");
// Look up the resolution and format of our main backbuffer.
PresentationParameters pp = g.PresentationParameters;
int width = pp.BackBufferWidth;
int height = pp.BackBufferHeight;
SurfaceFormat format = pp.BackBufferFormat;
// Create a texture for rendering the main scene, prior to applying bloom.
// Create two rendertargets for the bloom processing. These are half the
// size of the backbuffer, in order to minimize fillrate costs. Reducing
// the resolution in this way doesn't hurt quality, because we are going
// to be blurring the bloom images in any case.
width /= 2;
height /= 2;
renderTarget1 = new RenderTarget2D(g, width, height, false, format, DepthFormat.Depth24);
renderTarget2 = new RenderTarget2D(g, width, height, false, format, DepthFormat.Depth24);
}
/// <summary>
/// Unload your graphics content.
/// </summary>
public void UnloadContent(ContentManager theContentManager)
{
renderTarget1.Dispose();
renderTarget2.Dispose();
}
#endregion
#region Draw
/// <summary>
/// This should be called at the very start of the scene rendering. The bloom
/// component uses it to redirect drawing into its custom rendertarget, so it
/// can capture the scene image in preparation for applying the bloom filter.
/// </summary>
public void BeginDraw(RenderTarget2D renderTarget)
{
if (Visible)
{
GraphicsDevice.SetRenderTarget(renderTarget);
}
}
/// <summary>
/// This is where it all happens. Grabs a scene that has already been rendered,
/// and uses postprocess magic to add a glowing bloom effect over the top of it.
/// </summary>
public void Draw(GameTime gameTime, RenderTarget2D renderTarget)
{
// Pass 1: draw the scene into rendertarget 1, using a
// shader that extracts only the brightest parts of the image.
bloomExtractEffect.Parameters["BloomThreshold"].SetValue(
Settings.BloomThreshold);
DrawFullscreenQuad(renderTarget, renderTarget1,
bloomExtractEffect,
IntermediateBuffer.PreBloom);
// Pass 2: draw from rendertarget 1 into rendertarget 2,
// using a shader to apply a horizontal gaussian blur filter.
SetBlurEffectParameters(1.0f / (float)renderTarget1.Width, 0);
DrawFullscreenQuad(renderTarget1, renderTarget2,
gaussianBlurEffect,
IntermediateBuffer.BlurredHorizontally);
// Pass 3: draw from rendertarget 2 back into rendertarget 1,
// using a shader to apply a vertical gaussian blur filter.
SetBlurEffectParameters(0, 1.0f / (float)renderTarget1.Height);
DrawFullscreenQuad(renderTarget2, renderTarget1,
gaussianBlurEffect,
IntermediateBuffer.BlurredBothWays);
// Pass 4: draw both rendertarget 1 and the original scene
// image back into the main backbuffer, using a shader that
// combines them to produce the final bloomed result.
GraphicsDevice.SetRenderTarget(null);
EffectParameterCollection parameters = bloomCombineEffect.Parameters;
parameters["BaseTexture"].SetValue(renderTarget);
parameters["BloomIntensity"].SetValue(Settings.BloomIntensity);
parameters["BaseIntensity"].SetValue(Settings.BaseIntensity);
parameters["BloomSaturation"].SetValue(Settings.BloomSaturation);
parameters["BaseSaturation"].SetValue(Settings.BaseSaturation);
GraphicsDevice.Textures[1] = renderTarget1;
Viewport viewport = GraphicsDevice.Viewport;
DrawFullscreenQuad(renderTarget,
viewport.Width, viewport.Height,
bloomCombineEffect,
IntermediateBuffer.FinalResult);
}
/// <summary>
/// Helper for drawing a texture into a rendertarget, using
/// a custom shader to apply postprocessing effects.
/// </summary>
void DrawFullscreenQuad(Texture2D texture, RenderTarget2D renderTarget,
Effect effect, IntermediateBuffer currentBuffer)
{
GraphicsDevice.SetRenderTarget(renderTarget);
DrawFullscreenQuad(texture,
renderTarget.Width, renderTarget.Height,
effect, currentBuffer);
}
/// <summary>
/// Helper for drawing a texture into the current rendertarget,
/// using a custom shader to apply postprocessing effects.
/// </summary>
void DrawFullscreenQuad(Texture2D texture, int width, int height,
Effect effect, IntermediateBuffer currentBuffer)
{
// If the user has selected one of the show intermediate buffer options,
// we still draw the quad to make sure the image will end up on the screen,
// but might need to skip applying the custom pixel shader.
if (showBuffer < currentBuffer)
{
effect = null;
}
spriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect);
spriteBatch.Draw(texture, new Rectangle(0, 0, width, height), Color.White);
spriteBatch.End();
}
/// <summary>
/// Computes sample weightings and texture coordinate offsets
/// for one pass of a separable gaussian blur filter.
/// </summary>
void SetBlurEffectParameters(float dx, float dy)
{
// Look up the sample weight and offset effect parameters.
EffectParameter weightsParameter, offsetsParameter;
weightsParameter = gaussianBlurEffect.Parameters["SampleWeights"];
offsetsParameter = gaussianBlurEffect.Parameters["SampleOffsets"];
// Look up how many samples our gaussian blur effect supports.
int sampleCount = weightsParameter.Elements.Count;
// Create temporary arrays for computing our filter settings.
float[] sampleWeights = new float[sampleCount];
Vector2[] sampleOffsets = new Vector2[sampleCount];
// The first sample always has a zero offset.
sampleWeights[0] = ComputeGaussian(0);
sampleOffsets[0] = new Vector2(0);
// Maintain a sum of all the weighting values.
float totalWeights = sampleWeights[0];
// Add pairs of additional sample taps, positioned
// along a line in both directions from the center.
for (int i = 0; i < sampleCount / 2; i++)
{
// Store weights for the positive and negative taps.
float weight = ComputeGaussian(i + 1);
sampleWeights[i * 2 + 1] = weight;
sampleWeights[i * 2 + 2] = weight;
totalWeights += weight * 2;
// To get the maximum amount of blurring from a limited number of
// pixel shader samples, we take advantage of the bilinear filtering
// hardware inside the texture fetch unit. If we position our texture
// coordinates exactly halfway between two texels, the filtering unit
// will average them for us, giving two samples for the price of one.
// This allows us to step in units of two texels per sample, rather
// than just one at a time. The 1.5 offset kicks things off by
// positioning us nicely in between two texels.
float sampleOffset = i * 2 + 1.5f;
Vector2 delta = new Vector2(dx, dy) * sampleOffset;
// Store texture coordinate offsets for the positive and negative taps.
sampleOffsets[i * 2 + 1] = delta;
sampleOffsets[i * 2 + 2] = -delta;
}
// Normalize the list of sample weightings, so they will always sum to one.
for (int i = 0; i < sampleWeights.Length; i++)
{
sampleWeights[i] /= totalWeights;
}
// Tell the effect about our new filter settings.
weightsParameter.SetValue(sampleWeights);
offsetsParameter.SetValue(sampleOffsets);
}
/// <summary>
/// Evaluates a single point on the gaussian falloff curve.
/// Used for setting up the blur filter weightings.
/// </summary>
float ComputeGaussian(float n)
{
float theta = Settings.BlurAmount;
return (float)((1.0 / Math.Sqrt(2 * Math.PI * theta)) *
Math.Exp(-(n * n) / (2 * theta * theta)));
}
#endregion
}
}
Game class:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using BloomPostprocess;
namespace Morior
{
/// <summary>
/// This is the main type for your game.
/// </summary>
///
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Vector2 mPosition = new Vector2(250, 100);
Laevus mLeavusSprite;
DirtBlock b;
Rectangle cursorSource;
private Texture2D cursorTex;
private Vector2 cursorPos;
BloomComponent bloom;
RenderTarget2D renderTarget;
Rectangle rec;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
mLeavusSprite = new Laevus();
b = new DirtBlock();
renderTarget = new RenderTarget2D(
GraphicsDevice,
GraphicsDevice.PresentationParameters.BackBufferWidth,
GraphicsDevice.PresentationParameters.BackBufferHeight,
false,
GraphicsDevice.PresentationParameters.BackBufferFormat,
DepthFormat.Depth24);
rec = new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
bloom = new BloomComponent(this);
Components.Add(bloom);
bloom.Settings = new BloomSettings(null, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f);
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
mLeavusSprite.LoadContent(this.Content);
mLeavusSprite.Position.Y = GraphicsDevice.Viewport.Height - mLeavusSprite.mSpriteTexture.Height - (mLeavusSprite.mSpriteTexture.Height / 6);
mLeavusSprite.Position.X = GraphicsDevice.Viewport.Width / 2;
b.LoadContent(this.Content);
cursorTex = Content.Load<Texture2D>("sunset");
cursorSource = new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
bloom.LoadContent(GraphicsDevice, this.Content);
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// game-specific content.
/// </summary>
protected override void UnloadContent()
{
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
// TODO: Add your update logic here
mLeavusSprite.Update(gameTime);
var mouseState = Microsoft.Xna.Framework.Input.Mouse.GetState();
cursorPos = new Vector2(mouseState.X, mouseState.Y);
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
bloom.ShowBuffer = BloomComponent.IntermediateBuffer.PreBloom;
//bloom.BeginDraw(renderTarget);
DrawSceneToTexture(renderTarget,gameTime);
bloom.Draw(gameTime, renderTarget);
//base.Draw(gameTime);
}
protected void DrawSceneToTexture(RenderTarget2D renderTarget, GameTime gametime)
{
GraphicsDevice.SetRenderTarget(renderTarget);
GraphicsDevice.DepthStencilState = new DepthStencilState() { DepthBufferEnable = true };
// Draw the scene
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin(SpriteSortMode.Immediate,
BlendState.AlphaBlend,
SamplerState.PointClamp,
null, null, null, null);
mLeavusSprite.Draw(this.spriteBatch);
b.Draw(this.spriteBatch);
spriteBatch.Draw(cursorTex, cursorSource,
Color.White);
spriteBatch.End();
// Drop the render target
GraphicsDevice.SetRenderTarget(null);
}
}
}
I wish I could make my own shader, but as I said, I’m new to shaders, you really expect me to create whole new one when I cant even get premade one working?