I want to do a shadow mapping, i have the zdepth of light view rendered to a map and the zdepth of camera caculated.here is the initial shader code for render zdepth and the shader code for comparation:
v2f vert (appdata_base v) {
v2f o;
o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
o.depth.xy=o.pos.zw;
return o;
}
float4 frag(v2f i) : COLOR {
float d=i.depth.x/i.depth.y;
float4 c=EncodeFloatRGBA(d);
return c;
}
and the code to compare them
vertOut vert(appdata_base v)
{
vertOut o;
o.pos=mul(UNITY_MATRIX_MVP,v.vertex);
float4 wVertex=mul(_Object2World ,v.vertex);
o.litPos=mul(_litMVP,wVertex);
return o;
}
float4 frag(vertOut i):COLOR
{
float2 shadowTexc=0.5*i.litPos.xy/i.litPos.w+float2(0.5,0.5);
float litZ=i.litPos.z/i.litPos.w;
float4 c=tex2D(_myShadow,shadowTexc);
float t=DecodeFloatRGBA(c);
if(litZ>t)
return 0.3;
else
return 0.7;
}
it result something like this:
After i do some offset of both the z depth of light view and camera view like this
v2f vert (appdata_base v) {
v2f o;
o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
o.depth.xy=o.pos.zw;
return o;
}
float4 frag(v2f i) : COLOR {
float d=i.depth.x/i.depth.y-4/i.depth.y;//I modified the ZDepth here
float4 c=EncodeFloatRGBA(d);
return c;
}
ENDCG
the shader code to compares them in camera view:
vertOut vert(appdata_base v)
{
vertOut o;
o.pos=mul(UNITY_MATRIX_MVP,v.vertex);
float4 wVertex=mul(_Object2World ,v.vertex);
o.litPos=mul(_litMVP,wVertex);
return o;
}
float4 frag(vertOut i):COLOR
{
float2 shc=0.5*i.litPos.xy/i.litPos.w+float2(0.5,0.5);
float oZ=i.litPos.z/i.litPos.w-4/i.litPos.w;//I modified the ZDepth here
float4 c=tex2D(_myShadow,shc);
float sZ=DecodeFloatRGBA(c);
float r=0;
if(oZ<=sZ)
r=0.8;
else
r=0.5;
return r;
}
the result seems correct,like this:
it is what i want,
but could somebody tell me why i need to offset the zdepth by this way:
float d=i.depth.x/i.depth.y-4/i.depth.y;
float oZ=i.litPos.z/i.litPos.w-4/i.litPos.w;

