Anaglyphs are images designed to give a 3D effect when viewed with special glasses, usually with red and blue (sometimes red and cyan) filters over the left and right eyes, respectively.
Using anaglyphs we can make our game look real 3D through those cheap red/cyan 3D-glasses. Adding an anaglyph effect to your XNA game is fairly easy.
Basically we need to undertake the following steps: -Draw our scene twice to separate render targets, with a slightly offset camera -Use a shader and draw a full screen quad to blend the images and color coding the images for each eye
Lets start by assuming you have the following draw code:
We need to extract all your drawing code (except base.Draw(..)) to a new method that as argument accepts a view matrix. Update your code so that the passed viewMatrix is used instead of your normal camera’s viewMatrix. Doing this will allow us to easily draw the scene twice with a slightly offset camera. You should now have something like this:
Now let’s first write the shader that is going to blend the images, create a new effect in your content project and paste in the following code:
This is a pretty standard HLSL shader, but I will quickly go over it.
The texture’s left and right will be the textures resulting from drawing the scene twice, slightly offset from each other. We use a sampler with POINT filters because the left and right textures are going to be exactly the same size as our final rendering.
The vertex shader is passed as input nothing more than the position and texture coordinate of the vertex, it doesn’t transform anything but it just directly passes to the pixel shader.
The pixel shader samples the textures for the left and right eye. The red channel is used to ‘encode’ the image for the right eye (the red is unfiltered by the cyan colored lens). The green and blue channel are taken from the image for the left eye (they are unfiltered by the red colored lens). You can look at this wikipedia entry for other color combinations in case you have different 3D-glasses.
Now that we have our effect we need to add 2 render targets, the effect and a quad renderer to our game class. (The Quad class is posted as a code snippet here and used as to render the final image).
Added these lines to the top of your game class.
And add these lines in your LoadContent method:
Now we need to calculate two slightly offset view-matrices, draw the scene two times using these view-matrices and then combine them using our effect. To accomplish this write the following Draw method:
And hooray! We now have anaglyphs in our game! This will result in some pretty picture (the following picture of course only make sense when you use red/cyan 3D-glasses)
When you have created some cool anaglyph images in XNA, be sure to send them in, I’ll make a small gallery here!