Search Unity

Custom basic lambert lighting model not working

Discussion in 'Shaders' started by Trindenberg, Jul 31, 2019.

  1. Trindenberg

    Trindenberg

    Joined:
    Dec 3, 2017
    Posts:
    20
    Hi,

    This is really bugging me, I'm sure I have the code correct but it is not shading correctly. Please help!



    Sphere on the left is with the code below, sphere on the right is simply using #pragma surface surf Lambert

    Shader "MyShaders/Lighting - Custom Lambert"
    {
    Properties
    {
    _Colour("Colour", Color) = (1,1,1,1)
    }
    SubShader
    {
    Tags { "Queue" = "Geometry" }

    CGPROGRAM
    #pragma surface surf BasicLambert

    half4 LightingBasicLambert(SurfaceOutput s, half3 lightDir, half atten) // 'Lighting' in front of custom name
    {
    half NdotL = dot(s.Normal, lightDir);
    half4 c;
    c.rgb = s.Albedo * _LightColor0.rgb * (NdotL * atten); // LightColor0 is the scene light
    c.a = s.Alpha;
    return c;
    }

    float4 _Colour;

    struct Input
    {
    float2 uv_MainTex;
    };

    void surf (Input IN, inout SurfaceOutput o)
    {
    o.Albedo = _Colour.rgb;
    }
    ENDCG
    }
    FallBack "Diffuse"
    }
     
  2. Trindenberg

    Trindenberg

    Joined:
    Dec 3, 2017
    Posts:
    20
    If I comment out Fallback "Diffuse" I get:



    But why is it falling back?
     
    Last edited: Jul 31, 2019
  3. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    7,161
    So, there are two things happening. The first one is you're not clamping the dot product, so you're getting negative lighting on the back side of the sphere. If you notice your example without the fallback goes completely black on the back side of the sphere, where as the built in lambert has some ambient lighting.

    This line:
    should be:
    Code (csharp):
    1. half NdotL = saturate(dot(s.Normal, lightDir));
    That will actually fix both issues, but there's an explanation for why you were getting the odd smudges with the fallback when you don't without. Shadows. Those weird smudges are from the sphere self-shadowing. Usually any face not pointed at the light isn't getting affected by the light that's being shadowed, but in this case because you had some negative lighting, the shadow was becoming visible. The fallback includes the shadow caster shader pass.
     
    Trindenberg likes this.
  4. Trindenberg

    Trindenberg

    Joined:
    Dec 3, 2017
    Posts:
    20
    Thank you, I really appreciate your help! I was learning about shading/lighting, and this is the code in the example but they had non-erroneous results in their version! Those kind of things get me stuck as I ask myself why I get different results. Thanks :)