Using rendertarget to draw scene to backbuffer texture

Sep 26, 2014 at 5:48 PM

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.Draw(texture, DestinationRect, SourceRect, Microsoft.Xna.Framework.Color.White);


            //set Render Target To backbuffer texture

            // restore state of some graphics device's properties after 2D graphics,
             // so 3D rendering will work fine
            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
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 :)
Sep 28, 2014 at 6:31 PM

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)