Using rendertarget to draw scene to backbuffer texture

Sep 26, 2014 at 6:48 PM
Hello,

I'm trying to mix a 2d image and a 3d animated model.
I need to have the 2d image in the back, so First I tried using a sprite defined in an xaml scene file. I set the Zorder to -1 but it still draws the sprite on top of the model.

So now I'm trying to draw the model to a backbuffer texture, then drawing the backbuffer to the main screen using an alpha key.

I'm using this code:

declaration of backbuffer texture (during loadcontent):


RenderTarget2D rendertarget = new RenderTarget2D(GraphicsDevice, 1600, 900);


draw method:
            //Draw 2d image first
            sb.Begin();

            sb.Draw(texture, DestinationRect, SourceRect, Microsoft.Xna.Framework.Color.White);

            sb.End();

            //set Render Target To backbuffer texture
            graphicsDevice.SetRenderTarget(rendertarget)


            // restore state of some graphics device's properties after 2D graphics,
             // so 3D rendering will work fine
            graphicsDevice.Clear(Microsoft.Xna.Framework.Color.Black);
            graphicsDevice.BlendState = BlendState.AlphaBlend;
            graphicsDevice.DepthStencilState = DepthStencilState.Default;
            graphicsDevice.SamplerStates[0] = new SamplerState
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap
            };
            graphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;

            //Draw scene containing 3d animated model
            scene.Draw(graphicsDevice, gameTime.ElapsedGameTime);

            //reset the render target to the default device
            graphicsDevice.SetRenderTarget(null);
The code runs without errors, but the first 2d texture is not drawn, instead I get a purple like clear color it seems.

I'm really stuck on this, any help is appreciated :)
Developer
Sep 28, 2014 at 7:31 PM
Hello,

The scene uses multiple drawing passes, so it clears the screen. Therefore everything drawing before is never sent to the screen.

Currently there are a few ways to work around this, for example:
  1. Creating a post effect that draws a texture, that depends on the depth buffer.
  2. Simplest way would be to just have a plane behind the model, the drawback would be the perspective.
  3. Rewrite the scene's drawing pass. (DrawingContext)