Environment Mapped Reflections
From XNAWiki
A Shader for applying environment mapped reflections on a reflective object.
//////////////////////////////////
// Environment Mapped Reflections
//
//////////////////////////////////
float4x4 World;
float4x4 WorldInvTrans;
float4x4 WorldViewProj;
float3 EyePos;
texture EnvMap;
sampler EnvTex = sampler_state
{
Texture = <EnvMap>;
MinFilter = Anisotropic;
MagFilter = LINEAR;
MipFilter = LINEAR;
MaxAnisotropy = 8;
AddressU = WRAP;
AddressV = WRAP;
};
struct VertexShaderInput
{
float4 Position : POSITION0;
float4 Normal : NORMAL0;
};
struct VertexShaderOutput
{
float4 PosH : POSITION0;
float3 PosW : TEXCOORD0;
float3 NormalW : TEXCOORD1;
};
VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
VertexShaderOutput output;
output.PosH = mul(input.Position, WorldViewProj);
output.PosW = mul(input.Position, World);
output.NormalW = mul(input.Normal, WorldInvTrans);
return output;
}
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
input.NormalW = normalize(input.NormalW);
//compute the vector from the camera eye position to the world space pixel position.
float3 fromEyeW = normalize(input.PosW - EyePos);
//find the relflected ray by reflecting the fromEyeW vector across the normal
float3 reflectedRay = reflect(fromEyeW, input.NormalW);
//finally, index the cube map with the 3d reflected ray vector.
return texCUBE(EnvTex, reflectedRay);
}
technique EnvironmentMap
{
pass Pass1
{
VertexShader = compile vs_2_0 VertexShaderFunction();
PixelShader = compile ps_2_0 PixelShaderFunction();
}
}