How to modify shadow maps?

Does anybody know how I can take Unity’s shadow maps before they’re rendered on the screen, apply some custom processing to them on a per light basis and then send them back on their way?

Hello,
I’m not a professional, but I have some ideas which might interest you.

If you want to replace the shadows for every objects:
You can replace a Built in shader by your own in Edit → Project settings → graphics. Just copy their original shadow caster add a pass and then replace.

For only one shader you can add the subshader with “LightMode” = “ShadowCaster”.

Thanks for the info :smile:

For the built-in shader, isn’t that only for the directional light?

The shadowcaster pass is used for shadows from all lights, as well as the camera depth texture in forward rendering. Depending on what you want to do you could use a custom one for your shaders. Alternatively you could use command buffers to render stuff into / copy the shadow maps, but I don’t know of any good way to modify the shadow maps like via a shader and have the game still use them.

1 Like

Unity seems to use the RHalf format for the shadow caster pass, do you know if there is a way of getting the current format as I think this might vary with platforms?

  shadow.GetTemporaryRT(idd, 4096, 4096, 32, FilterMode.Point, RenderTextureFormat.RHalf);
            shadow.CopyTexture(BuiltinRenderTextureType.CurrentActive, idd);
            shadow.Blit(idd, BuiltinRenderTextureType.CurrentActive, shadowMat);
            shadow.SetGlobalTexture(idd, BuiltinRenderTextureType.CurrentActive);
            shadow.ReleaseTemporaryRT(idd);

There is RenderTextureFormat.ShadowMap but not sure if that works. I think what you are actually creating in your sample is a RHalf color buffer with a 32 bit depth buffer. AFAIK, you have to pass RenderTextureFormat.Depth or .ShadowMap to avoid creating an unnecessary color buffer.

The difference between .Depth and .ShadowMap is the sampler. .ShadowMap creates a comparison sampler which can be used for percentage closer filtering (PCF).