Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to properly implement shadows in vertex/fragment shaders?

Discussion in 'Shaders' started by 00christian00, Aug 13, 2020.

  1. 00christian00

    00christian00

    Joined:
    Jul 22, 2012
    Posts:
    1,035
    I am trying to implement shadows in my custom shaders but everything after the shadow distance is treated like if it is in shadow, making it quite ugly.
    I noticed this doesn't happen with surface shaders.
    How do I get the same result as the surface shaders?
    I saw many examples online, but I always get the same results. All I do is use the SHADOW_ATTENUATION macro.
    I am using forward rendering, and for my game the fps are more than enough so I would like to stick to it.
    Fragment shader output:
    shadow_error.png

    Legacy surface shader output:

    shadow_ok.png

    This is how i am testing the shadows:

    Code (CSharp):
    1.      fixed4 frag (v2f i) : SV_Target
    2.             {
    3.                 fixed4 col = tex2D(_MainTex, i.uv);
    4.                 // compute shadow attenuation (1.0 = fully lit, 0.0 = fully shadowed)
    5.                 fixed shadow = SHADOW_ATTENUATION(i);
    6.                 // darken light's illumination with shadow, keep ambient intact
    7.                 fixed3 lighting = i.diff * shadow + i.ambient;
    8.                 col.rgb *= lighting*i.color;
    9.                 return col;
    10.             }
     
    Last edited: Aug 13, 2020
  2. aleksandrk

    aleksandrk

    Unity Technologies

    Joined:
    Jul 3, 2017
    Posts:
    2,983
    The "SHADOW_ATTENUATION" macro is from, like, Unity 4...
    Try using "UNITY_SHADOW_ATTENUATION" instead.
     
    00christian00 likes this.
  3. 00christian00

    00christian00

    Joined:
    Jul 22, 2012
    Posts:
    1,035
    Thanks! That fixed it. I'm going to update all my custom shaders then.
    Perfomance of hard shadows overall is not bad, even on devices of 7-8 years ago it lose around 10fps in my project, from 40 to 30, to project a shadow on a road mesh.
    Should update the docs, they still point to the old macros.
     
    aleksandrk likes this.
  4. aleksandrk

    aleksandrk

    Unity Technologies

    Joined:
    Jul 3, 2017
    Posts:
    2,983
    Yes!
    It's in progress :)
     
    00christian00 likes this.
  5. Tortuap

    Tortuap

    Joined:
    Dec 4, 2013
    Posts:
    137
    Documentation still not updated.
     
  6. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,329
    Some of Unity's own shaders still use
    SHADOW_ATTENUATION
    ... and I think everyone's been moved onto the SRPs at this point, so I don't really expect either to get fixed. :(