Including Fx Files

You’ll find that you’ll have repeated code in your effects at times. To reduce this redundancy you can just put your common functions and variables in another file and include it from your other effects. Here’s how to do it:

For this tutorial i use the default code given when you create an effect with xna:

float4x4 World;
float4x4 View;
float4x4 Projection;

// TODO: add effect parameters here.

struct VertexShaderInput
{
 float4 Position : POSITION0;

// TODO: add input channels such as texture
 // coordinates and vertex colors here.
};

struct VertexShaderOutput
{
 float4 Position : POSITION0;

// TODO: add vertex shader outputs such as colors and texture
 // coordinates here. These values will automatically be interpolated
 // over the triangle, and provided as input to your pixel shader.
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
 VertexShaderOutput output;

float4 worldPosition = mul(input.Position, World);
 float4 viewPosition = mul(worldPosition, View);
 output.Position = mul(viewPosition, Projection);

// TODO: add your vertex shader code here.

return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
 // TODO: add your pixel shader code here.

return float4(1, 0, 0, 1);
}

technique Technique1
{
 pass Pass1
 {
 // TODO: set renderstates here.

VertexShader = compile vs_2_0 VertexShaderFunction();
 PixelShader = compile ps_2_0 PixelShaderFunction();
 }
}

I call is myeffect.fx
lets say the World, View and Projection variable common among your other effects and you’d like to put them in another file. You can include other shaders into your similar to how you’d do it in c++. So create another effect, then copy and paste the following code code from the first shader into it.


float4x4 World;
float4x4 View;
float4x4 Projection;

i call mine included.fxh

at the top of myeffect.fx i add:


#include "included.fxh"

if you get an error saying the compilation of the effect failed its because the effect we’re including is being process by XNA’s EffectProcessor, we dont want that. This error would only happen if the extension of the file you’re including is “.fx” . To fix this, click on the file in the Solution Explorer then go down to the Properties pane. change the Build Action of the effect file from Compile to None:

If you followed my instructions correctly your project should compile.

This is a screenshot from my project

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s