Shadows and Lighting for custom materials

This tutorial explains how to apply deferred lighting on custom materials. This means objects with custom materials can receive shadows and lighting. To apply this feature to your custom material follow the instructions below.

Open your material.cs file and locate the custom material definition. Add the line in bold after "mapTo" :

singleton CustomMaterial( MyCustomMaterial )
mapTo = "MyTexture";
texture[0] = "#lightinfo";
shader = MyShader;
version = 2.0;


Open your vertex shader code and add the directive in bold:

#include "shadergen:/autogenConditioners.h"

Add the line in bold to your output VS semantics:

struct VSOutput 

float4 pos : POSITION; 
float4 screenspacePos : TEXCOORD0; 

After your vertex transformation add the line in bold:

OUT.pos = mul(modelview, float4(,1)); 

OUT.screenspacePos = OUT.pos


Open your pixel shader. Add the line in bold in the beginning of the file:

#include "shadergen:/autogenConditioners.h" 

Straight after this add the lines in bold:

uniform float4    rtParams0       : register(C0);
uniform sampler2D lightInfoBuffer : register(S0);

Locate your input structure of the pixel shader and add the line in bold:

struct PSInput 

float4 screenspacePos  : TEXCOORD0; 

At the end of your fragment shader paste the code in bold:

float2 uvScene = IN.screenspacePos.xy / IN.screenspacePos.w; 
uvScene = ( uvScene + 1.0 ) / 2.0; 
uvScene.y = 1.0 - uvScene.y; 
uvScene = ( uvScene * ) + rtParams0.xy; 
float3 d_lightcolor; 
float d_NL_Att; 
float d_specular;
lightinfoUncondition(tex2D(lightInfoBuffer, uvScene), d_lightcolor, d_NL_Att, d_specular); 
OUT.col *= float4(d_lightcolor, 1.0); 

return OUT; 

This code recalculates the texture coordinates to sample from a 2D buffer lightinfo. Then this color is applied to your lighting model.

*Additional notes: Pay attention to your sampler numeration and rtParams. The example above is setup for S0 register.