XNA Shader Programming – Tutorial 10, Post process Negative

XNA Shader Programming
Tutorial 10 – Post process, negative
This tutorial builds on Tutorial 9, post process wiggling. If you haven’t read that yet, you should in order to fully understand what’s going on here.
The source-code and binaries can be found in the end of the chapter.
Negative Image
This shader is also very simple, but, I got a lot of questions about this so I decided I wanted to write a short tutorial on it.. and it’s really short 😉
To get the color from a texture sampler, you usually do this: float4 Color = tex2D(ColorMapSampler, Tex);
To get the negative color, you simply subracts each channel on Color with one, or, simply:
float4 ColorInverse = 1.0f – tex2D(ColorMapSampler, Tex);
And, thats it!
Implementing the shader
Let’s start by implementing the shader. Its pretty short so I’ll just add the code:
sampler ColorMapSampler : register(s0);
// Negative image
float4 PixelShader(float2 Tex: TEXCOORD0) : COLOR
 float4 Color = 1.0f – tex2D(ColorMapSampler, Tex); 
 // Keep our alphachannel at 1.
 Color.a = 1.0f;
    return Color;
technique PostProcess
 pass P0
  // A post process shader only needs a pixel shader.
  PixelShader = compile ps_2_0 PixelShader();
First, we subtract the color from our sampler, from 1.0f to get the inverse.
But, when doing this, we are inverting the Alpha channel as well. If this is what you want, go ahead, but if you want to keep the alpha-values from the original image, you must set it back to what it was, or set it to something manually.
In this case, we want the image to have the alpha of 1.0, so we set the a component of Color to 1.0, making our image fully opque if we have shading enabled.
Thats it for this tutorial. I’ll keep adding some post process effects during the next days so keep comming back 🙂
You might have noticed that I have not used effect.commitChanges(); in this code. If you are rendering many objects using this shader, you should add this code in the pass.Begin() part so the changed will get affected in the current pass, and not in the next pass. This should be done if you set any shader paramteres inside the pass.
This entry was posted in XNA Shader Tutorial. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.