0
$\begingroup$

due to some features in materials I need to create my own directional shadow map.

Everything seems to work ok, until the moment where I compare depths.

First I add camera component to directional light with RenderTexture:

enter image description here enter image description here

then in code, I set this texture and camera projection matrix as global variables for shaders:

Camera shadowCaptureCamera = GetComponent<Camera>();
Shader.SetGlobalTexture("_CustomShadowsTex", shadowCaptureCamera.targetTexture, UnityEngine.Rendering.RenderTextureSubElement.Depth);
           
Matrix4x4 worldToClipMatrix = shadowCaptureCamera.projectionMatrix * shadowCaptureCamera.worldToCameraMatrix;
Shader.SetGlobalMatrix("_CustomShadowsMatrix", worldToClipMatrix);

Then in shaders I do this:

v2f vert(appdata v)
{
    v2f o;
    o.pos = UnityObjectToClipPos(v.vertex);
    o.uv = TRANSFORM_TEX(v.uv, _MainTex);

    float4 worldPos = mul( unity_ObjectToWorld, float4( v.vertex.xyz, 1.0f) );
    float4 shadowPosition = mul( _CustomShadowsMatrix, worldPos );
    shadowPosition.xyz /= shadowPosition.w;
    shadowPosition.xy = shadowPosition.xy * 0.5f + 0.5f;
    o.shadowMapUV = shadowPosition;
    return o;
}

fixed4 frag(v2f i) : SV_Target
{

    ......

    float shadowDepth = tex2D( _CustomShadowsTex, i.shadowMapUV.xy ).r;             
    float atten = shadowDepth > abs(i.shadowMapUV.z) ? 1.0f : 0.0f;
    return atten;
}

Everything has value 1.0f.

Any idea what's wrong? It samples shadow at correct place, but something is wrong with values. I'm also not sure why i.shadowMapUV.z is <0.f. Looking at matrix's values it shouldn't be.

$\endgroup$

1 Answer 1

0
$\begingroup$

Ok, I got it. i.shadowMapUV.z is < 0.f because it's mapped to -1;1 between near;far. Forward is also at -Z, so correct way to calculate shadowPosition is:

float4 shadowPosition= mul( _CustomShadowsMatrix, float4(worldPos, 1.f) );
shadowPosition.xyz /= shadowPosition.w;
shadowPosition.xy = shadowPosition.xy * 0.5f + 0.5f;
shadowPosition.z = -shadowPosition.z * 0.5f + 0.5f;
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.