Monday, July 25, 2016

XNA 4.0 - Why does using a RenderTarget2d cause transparency on models?


I have been working through Riemers ShadowMap tutorial and everything was going well until the section on drawing to a separate rendertarget. I am using a different model and quads but I assumed the process would still work.


If I draw the scene directly to the back buffer I get: Normal image


When I draw it first to a RenderTarget2D and THEN to the screen, I get this weird transparent effect only on the model, the textured primitives below are still rendered fine:


Weird transparency effect


The RenderTarget is defined:



PresentationParameters pp = device.PresentationParameters;
renderTarget = new RenderTarget2D(device, pp.BackBufferWidth,
pp.BackBufferHeight, true, device.DisplayMode.Format, DepthFormat.Depth24);

And it is used in this way:


protected override void Draw(GameTime gameTime)
{
device.SetRenderTarget(renderTarget);

device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);


DrawScene("Simplest");

device.SetRenderTarget(null);
shadowMap = (Texture2D)renderTarget;

device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0);
using (SpriteBatch sb = new SpriteBatch(device))
{
sb.Begin();

sb.Draw(shadowMap, new Vector2(0, 0), null, Color.White, 0, new Vector2(0, 0), 1.0f, SpriteEffects.None, 1);
sb.End();

}
base.Draw(gameTime);
}

What gives?


Edit 1: I resolved the transparency effect by resetting:


device.DepthStencilState = DepthStencilState.Default;

device.BlendState = BlendState.Opaque;

But now the model has a purple tint on the side away from the light. Something to do with my Shader code I presume.


Edit 2: Turns out the purple (blue) colour was a result of the window being cleared to .DarkSlateBlue and the RenderTarget having alpha transparency. Fixed with:


sb.Begin(SpriteSortMode.Immediate, BlendState.Opaque);

Answer



Worked it out:


device.DepthStencilState = DepthStencilState.Default;
device.BlendState = BlendState.Opaque;


But now the model has a purple tint on the side away from the light. Something to do with my Shader code I presume.


Turns out the purple (blue) colour was a result of the window being cleared to .DarkSlateBlue and the RenderTarget having alpha transparency. Fixed with:


sb.Begin(SpriteSortMode.Immediate, BlendState.Opaque);

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...