Search code examples
c#xnaspritebatchrendertarget

RenderTarget2D tints all alpha purple


So, I'm trying to render my gameplay to a RenderTarget2D in XNA so I can apply shaders to the scene. It's working, to some extent, but anything that has was drawn with an alpha level other than 255 seems to be tinted purple. The alpha effect is working, but there is also a purple tint to it. I've tried looking around for a solution, and the only ones I can seem to find are either the full screen being rendered purple, or the alpha being replaced with purple.

My issue is not quite either of those...

Tinting purple!

This is a scene I threw up to show you what's going on. As you can see, the alpha effect is working, but the object is tinted purple.

Here's the part where I post my render code:

gameTarget = new RenderTarget2D(GraphicsDevice, (int)screenSize.X, (int)screenSize.Y, 1, SurfaceFormat.Color, RenderTargetUsage.PreserveContents);

gameDepthBuffer = new DepthStencilBuffer(GraphicsDevice, (int)screenSize.X, (int)screenSize.Y, GraphicsDevice.DepthStencilBuffer.Format);

This is the initialisation I'm using.

GraphicsDevice g = GraphicsDevice;
DepthStencilBuffer d = g.DepthStencilBuffer;
g.SetRenderTarget(0, gameTarget);
g.DepthStencilBuffer = gameDepthBuffer;
g.Clear(Color.Black);
GameBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.SaveState);
        level.Draw(GameBatch);

GameBatch.End();
g.SetRenderTarget(0, null);
g.DepthStencilBuffer = d;
GameBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.SaveState);
        if (renderEffect != null)
        {
            renderEffect.Begin();
            renderEffect.CurrentTechnique.Passes[0].Begin();
        }
        Sprite.Draw(GameBatch, gameTarget.GetTexture(), new Rectangle(0, 0, (int)assumedSize.X, (int)assumedSize.Y), Color.White);
        if (renderEffect != null)
        {
            renderEffect.CurrentTechnique.Passes[0].End();
            renderEffect.End();
        }
        GameBatch.End();

renderEffect is the effect file, Sprite is class that deal with drawing relative to an assumed screen size (to cope with varying resolutions).

I'm working in XNA 3.1. I know I should be using 4.0 by now, but I'm not because I have book on 3.1, which is helpful in certain circumstances.

Anyway, some help here would be greatly appreciated...


Solution

  • Fixed! I needed to set some alpha parameters:

    GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = true;
    GraphicsDevice.RenderState.AlphaDestinationBlend = Blend.One;
    GraphicsDevice.RenderState.AlphaSourceBlend = Blend.SourceAlpha;
    GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
    GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;