any way to cast shadows on self-lit materials?

We have sprite images that are pre-rendered with proper lighting for normal, fully lit conditions. And we have a minor variant of the sprite shader that allows them to accept (and cast) shadows… but in doing so, they now are using the diffuse lighting model, which we don’t want (because it causes our carefully rendered sprites to look too dark or bright, depending on the light intensity).

We want them to use their standard lighting when not in shadow, but darken where shadows are received.

Apparently 3ds Max and Maya both have materials like this… self-illuminated, but still able to receive shadows.

Any idea how we could do this in Unity?

A quick search brought up this and this.

Do either of those fit the bill?

Not directly, it seems… but they may contain the clues I need to write a perfect shader for our needs. Thanks!

OK, this is oh so close.

// Unlit shader that nonetheless receives shadows.
// Adapted from: http://answers.unity3d.com/questions/1187379
Shader "Unlit/Custom/Unlit Transparent Shadow Receiver" {
     Properties {
         _Color ("Main Color", Color) = (1,1,1,1)
         _MainTex ("Base (RGB)", 2D) = "white" {}
     }
     SubShader {
         Tags {"Queue" = "Geometry" "IgnoreProjector"="True" "RenderType" = "Transparent"}
         Cull Off
         ZWrite On
         Blend SrcAlpha OneMinusSrcAlpha

         Pass {
             Tags { "LightMode" = "ForwardBase" }    // handles main directional light, vertex/SH lights, and lightmaps
             CGPROGRAM
                 #pragma vertex vert
                 #pragma fragment frag
                 #pragma multi_compile_fwdbase
                 #pragma fragmentoption ARB_fog_exp2
                 #pragma fragmentoption ARB_precision_hint_fastest
                 
                 #include "UnityCG.cginc"
                 #include "AutoLight.cginc"
                 
                 struct v2f
                 {
                     float4    pos            : SV_POSITION;
                     float2    uv            : TEXCOORD0;
                     LIGHTING_COORDS(1,2)
                 };

                 float4 _MainTex_ST;

                 v2f vert (appdata_tan v)
                 {
                     v2f o;
                     
                     o.pos = mul( UNITY_MATRIX_MVP, v.vertex);
                     o.uv = TRANSFORM_TEX (v.texcoord, _MainTex).xy;
                     TRANSFER_VERTEX_TO_FRAGMENT(o);
                     return o;
                 }

                 sampler2D _MainTex;

                 fixed4 frag(v2f i) : COLOR
                 {
                     //fixed atten = LIGHT_ATTENUATION(i);    // Light attenuation + shadows.
                     fixed atten = SHADOW_ATTENUATION(i); // Shadows ONLY.
                     fixed4 tex = tex2D(_MainTex, i.uv);
                     fixed4 c = tex * atten;    // attenuate color
                     c.a = tex.a;                // don't attenuate alpha
                     return c;
                 }
             ENDCG
         }
          Pass {
             Tags {"LightMode" = "ForwardAdd"}    // handles per-pixel additive lights (called once per such light)
             Blend One One
             CGPROGRAM
                 #pragma vertex vert
                 #pragma fragment frag
                 #pragma multi_compile_fwdadd_fullshadows
                 #pragma fragmentoption ARB_fog_exp2
                 #pragma fragmentoption ARB_precision_hint_fastest
                 
                 #include "UnityCG.cginc"
                 #include "AutoLight.cginc"
                 
                 struct v2f
                 {
                     float4    pos            : SV_POSITION;
                     float2    uv            : TEXCOORD0;
                     LIGHTING_COORDS(1,2)
                 };

                 float4 _MainTex_ST;

                 v2f vert (appdata_tan v)
                 {
                     v2f o;
                     
                     o.pos = mul( UNITY_MATRIX_MVP, v.vertex);
                     o.uv = TRANSFORM_TEX (v.texcoord, _MainTex).xy;
                     TRANSFER_VERTEX_TO_FRAGMENT(o);
                     return o;
                 }

                 sampler2D _MainTex;

                 fixed4 frag(v2f i) : COLOR
                 {
                    // fixed atten = LIGHT_ATTENUATION(i);    // Light attenuation + shadows.
                     fixed atten = SHADOW_ATTENUATION(i); // Shadows ONLY.
                     fixed4 tex = tex2D(_MainTex, i.uv);
                     fixed4 c = tex * atten;    // attenuate color
                     c.a = tex.a;                // don't attenuate alpha
                     return c;
                 }
             ENDCG
         }
     }
     FallBack "VertexLit"
}

As long as my sprite isn’t flipped (facing away from the camera or flipX=true or localScale.x=-1), it works great. Shadows fall on my sprite, which otherwise is unlit and supports full alpha blending.

But as soon as I flip my sprite by any means, it no longer works properly. Shadows still show up, but only if there is some geometry behind the sprite that would catch them… and then they show up, on my sprite, in the position & shape that the would appear on that other geometry.

This suggests to me that somehow the flipped sprite is not properly writing to the depth buffer, or some such… but I’m in way over my head here. Anybody have a clue?

1 Like

Hmm, maybe I should be posting this in the shader forum?

Something is definitely different when the sprite is flipped (or rotated or negative-scaled). My shader’s working so great for a non-flipped sprite… what would be different, in the rendering pipeline, for a flipped one?

Joe I have no answer but hope you find a solution - I do know in 3D Max with a standard 100% self illuminated material shadows will not cast on those objects, so some fine layered shadow rendering and compositing is required to get cast shadows to fall on 100% self illuminated objects.

I know that’s probably not helpful, but thought you might like the funny that hit me while reading your previous post.

Does applying this code to the flipped sprites have better results?

:slight_smile:

5 Likes

I’m still convinced it has something to do with the depth buffer. Is there a way to visualize the contents of the depth buffer, for debugging purposes?

And it occurs to me that if I’m right, I could probably make a special shader that only writes to the depth buffer, and apply this to a big plane (quad) at same level as the character. I suppose that would mimic the effect of putting something just behind the character to catch the shadows.

But that feels like a hackish work-around, since no such shenanigans are required when the sprite isn’t flipped.

Frame Debugger shows that,
maybe its something to do with normals/tangents… (that back face doesnt work properly)

1 Like

Hey, thank you! I’d never noticed Frame Debugger before. I have a feeling it and I are going to become close friends.

OK, so this shows an important difference right away in the DepthPass job. With sprite facing forward, we get this:

3064163--230298--upload_2017-5-9_21-54-22.png

That gray blob on the right is the shape of my sprite (or rather, the mesh around my sprite). Now flip the sprite, and we instead get this:

3064163--230299--upload_2017-5-9_21-55-12.png

So, yeah, it’s not drawing to the buffer at all in this case. The info on the right says “Cull Back” which is probably the cause, but I don’t quite understand why that is — my shader has “Cull Off” in both passes.

However, the text above that got cut off (next to the name of the shader) says “pass #3 SHADOWS_DEPTH”. Could it be my shader doesn’t have a pass for this, so it’s falling back on some default behavior, or perhaps the VertexLit shader specified as the FallBack at the bottom?

Jeez, I wish I could move this thread over to the Shaders sub-forum… but I can’t, and I hate to split it into two threads, so I’ll forge ahead. Looking at the docs for the LightMode tag, maybe I need to create another pass with LightMode = “ShadowCaster”? Or is there some easier way to turn backface culling off for the SHADOWS_DEPTH pass?

All right! Adding this extra pass to my shader appears to do the trick:

// ------------------------------------------------------------------
//  Shadow rendering pass
Pass {
    Name "ShadowCaster"
    Tags { "LightMode" = "ShadowCaster" }

    ZWrite On ZTest LEqual Cull Off

    CGPROGRAM
    #pragma target 2.0

    #pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
    #pragma skip_variants SHADOWS_SOFT
    #pragma multi_compile_shadowcaster

    #pragma vertex vertShadowCaster
    #pragma fragment fragShadowCaster

    #include "UnityStandardShadow.cginc"

    ENDCG
}

That code was snatched from here. It still feels like meddling with arcade magics I do not fully comprehend, but it works!