Shawn posted a great writeup today talking about the changes to RenderTargets in GS4. I recently helped a dev figure out how to use a RenderTarget in his game. He was using RTs for a common purpose; rendering a 3d model into a RT, and then using that as a sprite in the game, using SpriteBatch.

There is some potential for a gotcha, based on the interaction of a couple of new defaults in GS4. I spent more time than I'd like to admit trying to figure out why I was seeing the effect I was. Hopefully I can help you avoid making the same mistake.

If you've read Shawn's blog, you know how he feels about premultiplied alpha.  In GS4, support for premultiplied alpha has been integrated at a much lower level. So much so, SpriteBatch's default behavior has been to do alpha blending, expecting premultiplied alpha.

That's pretty cool, and seems like a great approach.  It can catch you, however, if you render without premultiplied alpha, and then use SpriteBatch to draw the results of that rendering as a texture. If you find your model bleeding a strange color through in places, and having a glow-like effect on it, then you might double check the alpha blending settings. 

In order to make the effect more apparent, I've set the code to clear the back buffer to an unusual color, Color.Tomato.  I'm drawing the model p1_wedge from the SpaceWar starter kit, and using code directly from the help documentation to draw the model.  Here's the code that draws the RenderTarget to the back buffer:

GraphicsDevice.SetRenderTarget(null); 
GraphicsDevice.Clear(Color.Tomato); 
spriteBatch.Begin(); 
spriteBatch.Draw(renderTarget, Vector2.Zero, Color.White); 
spriteBatch.End();

Here's the result of this code, running in the WP7 emulator:

glow

Notice the strong glow around several of the lines.  That glow shouldn't be there. Where is it coming from? This artifact is caused by SpriteBatch interpreting black shades as partially transparent, as if the alpha had been premultiplied, and blending in the tomato color from the backbuffer.

How do we get rid of the glowing artifact? My first thought was to modify the SpriteBatch.Draw() call, and change the options for blending. This has changed in GS4, though. The options for changing alpha blending are on the SpriteBatch.Begin() call instead. I changed the code to the following:

GraphicsDevice.SetRenderTarget(null);
GraphicsDevice.Clear(Color.Tomato);
spriteBatch.Begin(SpriteSortMode.Texture, BlendState.Opaque);
spriteBatch.Draw(renderTarget, Vector2.Zero, Color.White);
spriteBatch.End();

Which fixed the model rendering, removing the reddish glow:

noglow

Hopefully this helps someone else skip the time I spent trying to figure this out.