Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Srites do not receive any shadows from 3D objects in the Universal Render Pipeline (URP)

Discussion in '2D' started by OG_oliver, Jan 4, 2020.

?

does anyone know how to make sprites receive shadows from 3D objects in Universal Render Pipeline

  1. A modified version of the shader shown in this https://youtu.be/e1j82BEnHhg may be a good idea

    1 vote(s)
    100.0%
  2. another method different than using a shader that works on mobile phones

    0 vote(s)
    0.0%
Multiple votes are allowed.
  1. OG_oliver

    OG_oliver

    Joined:
    Aug 11, 2019
    Posts:
    15
    Hello!
    I'm in Unity 2019.3 and I'm using the Universal Render Pipeline (URP). I'm making a 2.5D game and I have to use the 3D environment instead of the 2D environment. I started to work in 2D but when I tried to introduce low poly 3D objects I realized that the new 2D lighting (which is good and super handy if there are no 3D objects) doesn't work with 3D renderers. So I switched to a 3D space with the setup shown in the video of NotSlot:
    and everything was ok. The only problem is that I need the shadows of the sprites (to treat them as 3D planes) and I managed to modify a little bit his shader to make the sprites cast shadows but not to receive shadows. I've tried all the methods I've found in the community like enabling them by script using:
    GetComponent<Renderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On;
    GetComponent<Renderer>().receiveShadows = true;
    and in the inspector in debug mode but nothing happens. If anyone has tried and managed to do this in the new URP, a bit of explanation or an example is all I ask.
    Thank you in advance.
     
    Last edited: Jan 6, 2020
  2. OG_oliver

    OG_oliver

    Joined:
    Aug 11, 2019
    Posts:
    15
    I let my version of the UnlitSprite.shader shown on the video above that can make sprites (I'm using pixel art sprites by the way) cast shadows if it can help anyone:

    Code (CSharp):
    1. Shader "Universal Render Pipeline/Unlit Sprite"
    2. {
    3.     Properties
    4.     {
    5.         [PerRendererData]  _MainTex("Texture", 2D) = "white" {}
    6.         _Color("Tint", Color) = (1, 1, 1, 1)
    7.         [MaterialToggle] PixelSnap("Pixel snap", Float) = 0    // EXTRA
    8.         _Cutoff("AlphaCutout", Range(0.0, 1.0)) = 0.5
    9.         //_Cutoff("Alpha Cutoff", Range(0,1)) = 1        // EXTRA
    10.         _ReceiveShadows("Receive Shadows", Float) = 1.0
    11.         _ShadowIntensity("Shadow Intensity", Range(0, 1)) = 0.6
    12.         // BlendMode
    13.         [HideInInspector] _Surface("__surface", Float) = 0.0
    14.         [HideInInspector] _Blend("__blend", Float) = 0.0
    15.         [HideInInspector] _AlphaClip("__clip", Float) = 0.0
    16.         [HideInInspector] _SrcBlend("Src", Float) = 1.0
    17.         [HideInInspector] _DstBlend("Dst", Float) = 0.0
    18.         [HideInInspector] _ZWrite("ZWrite", Float) = 1.0
    19.         [HideInInspector] _Cull("__cull", Float) = 2.0
    20.         // Editmode props
    21.         [HideInInspector] _QueueOffset("Queue offset", Float) = 0.0
    22.         // ObsoleteProperties
    23. //        [HideInInspector] _MainTex("BaseMap", 2D) = "white" {}
    24. //        [HideInInspector] _Color("Base Color", Color) = (0.5, 0.5, 0.5, 1)
    25.         [HideInInspector] _SampleGI("SampleGI", float) = 0.0 // needed from bakedlit
    26.     }
    27.     SubShader
    28.     {
    29.         Tags
    30.         {
    31.             "RenderType" = "Opaque"
    32.             "IgnoreProjector" = "True"
    33.             "RenderPipeline" = "UniversalPipeline"
    34.             "Queue" = "Transparent"                //    EXTRA
    35.             //"RenderType" = "TransparentCutOut"    //
    36.             "PreviewType" = "Plane"                //
    37.             "CanUseSpriteAtlas" = "True"        //
    38.         }
    39.         LOD 300
    40.         Blend [_SrcBlend][_DstBlend]
    41.         ZWrite On
    42.         Cull Off
    43.         //Lighting On            //    EXTRA
    44.         //ZWrite Off            //
    45.         //Fog { Mode Off }    //
    46.        
    47.         Pass
    48.         {
    49.             Name "Unlit"
    50.             HLSLPROGRAM
    51.             // Required to compile gles 2.0 with standard srp library
    52.             #pragma prefer_hlslcc gles
    53.             #pragma exclude_renderers d3d11_9x
    54.             #pragma vertex vert
    55.             #pragma fragment frag
    56.             #pragma shader_feature _ALPHATEST_ON
    57.             #pragma shader_feature _ALPHAPREMULTIPLY_ON
    58.             // -------------------------------------
    59.             // Unity defined keywords
    60.             #pragma multi_compile_fog
    61.             #pragma multi_compile_instancing
    62.             #include "UnlitInput.hlsl"
    63.             struct Attributes
    64.             {
    65.                 float4 positionOS       : POSITION;
    66.                 float2 uv               : TEXCOORD0;
    67.                 UNITY_VERTEX_INPUT_INSTANCE_ID
    68.             };
    69.             struct Varyings
    70.             {
    71.                 float2 uv        : TEXCOORD0;
    72.                 float fogCoord  : TEXCOORD1;
    73.                 float4 vertex : SV_POSITION;
    74.                 UNITY_VERTEX_INPUT_INSTANCE_ID
    75.                 UNITY_VERTEX_OUTPUT_STEREO
    76.             };
    77.             Varyings vert(Attributes input)
    78.             {
    79.                 Varyings output = (Varyings)0;
    80.                 UNITY_SETUP_INSTANCE_ID(input);
    81.                 UNITY_TRANSFER_INSTANCE_ID(input, output);
    82.                 UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
    83.                 VertexPositionInputs vertexInput = GetVertexPositionInputs(input.positionOS.xyz);
    84.                 output.vertex = vertexInput.positionCS;
    85.                 output.uv = TRANSFORM_TEX(input.uv, _MainTex);
    86.                 output.fogCoord = ComputeFogFactor(vertexInput.positionCS.z);
    87.                 return output;
    88.             }
    89.             half4 frag(Varyings input) : SV_Target
    90.             {
    91.                 UNITY_SETUP_INSTANCE_ID(input);
    92.                 UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
    93.                 half2 uv = input.uv;
    94.                 half4 texColor = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, uv);
    95.                 half3 color = texColor.rgb * _Color.rgb;
    96.                 half alpha = texColor.a * _Color.a;
    97.                 clip( alpha - _Cutoff );
    98. #ifdef _ALPHAPREMULTIPLY_ON
    99.                 color *= alpha;
    100. #endif
    101.                 color = MixFog(color, input.fogCoord);
    102.                 return half4(color, alpha);
    103.             }
    104.             ENDHLSL
    105.         }
    106.         Pass
    107.         {
    108.             Tags{"LightMode" = "DepthOnly"}
    109.             ZWrite On
    110.             ColorMask 0
    111.             HLSLPROGRAM
    112.             // Required to compile gles 2.0 with standard srp library
    113.             #pragma prefer_hlslcc gles
    114.             #pragma exclude_renderers d3d11_9x
    115.             #pragma target 2.0
    116.             #pragma vertex DepthOnlyVertex
    117.             #pragma fragment DepthOnlyFragment
    118.             // -------------------------------------
    119.             // Material Keywords
    120.             #pragma shader_feature _ALPHATEST_ON
    121.             //--------------------------------------
    122.             // GPU Instancing
    123.             #pragma multi_compile_instancing
    124.             #include "UnlitInput.hlsl"
    125.             #include "DepthOnlyPass.hlsl"
    126.             ENDHLSL
    127.         }
    128.         // This pass it not used during regular rendering, only for lightmap baking.
    129.         Pass
    130.         {
    131.             Name "Meta"
    132.             Tags{"LightMode" = "Meta"}
    133.             Cull [_Cull]
    134.             HLSLPROGRAM
    135.             // Required to compile gles 2.0 with standard srp library
    136.             #pragma prefer_hlslcc gles
    137.             #pragma exclude_renderers d3d11_9x
    138.             #pragma vertex UniversalVertexMeta
    139.             #pragma fragment UniversalFragmentMetaUnlit
    140.             #include "UnlitInput.hlsl"
    141.             #include "UnlitMetaPass.hlsl"
    142.             ENDHLSL
    143.         }
    144.     }
    145.     FallBack "Hidden/InternalErrorShader"
    146.     Fallback "Transparent/Cutout/Diffuse"    // EXTRA
    147. //    CustomEditor "UnityEditor.Rendering.Universal.ShaderGUI.UnlitShader"
    148. }
     
    Last edited: Jan 4, 2020
  3. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    OG_oliver likes this.
  4. OG_oliver

    OG_oliver

    Joined:
    Aug 11, 2019
    Posts:
    15
    Sorry, I didn't know about this, I'll fix it. Is my first time asking for help in the forum.
     
  5. OG_oliver

    OG_oliver

    Joined:
    Aug 11, 2019
    Posts:
    15
    A solution proposed by NotSlot is to modify the default "Lit.shader" as done for the "Unlit.shader". I tried and I have to say that It works or at least partially. After changing the exact same things as for the Unlit shader (replacing BaseMap by MainTex on the .shader and all the dependency files, Zwrite On, Cull Off and commenting 'HideInInspector] _MainTex("BaseMap", 2D) = "white" {}') sprites were able to cast and receive shadows. The only problem I ran into is that the shader doesn't take into account the alpha value of the sprites. I think it's nothing too hard to fix but I don't know what to change. I think it has something to do with the 'clip( alpha - _Cutoff );' command that we have to add to "UnlitSprite.shader" but I don't know where do I'll have to place it. I'm a total noob with shaders and I don't understand them well enough to solve this problem on my own for now.

    Here I let some picks of my scene in case it can help to understand my problem better:
    on the left a sprite with the "UnlitSprite.shader" (that cast shadows but don't react to light in any other way) and in the right, the walls and the floor sprites with the "LitSrites.shader".
    upload_2020-1-6_2-27-27.png

    upload_2020-1-6_2-28-38.png

    Another problem is that since the "LitSprite.shader" isn't working properly it doesn't work on smartphones, the sprites appear as Invisibles.

    Here is the "LitSprite.shader" code:
    Code (CSharp):
    1. Shader "Universal Render Pipeline/Lit Sprite"
    2. {
    3.     Properties
    4.     {
    5.         // Unlit Srite config
    6.         [PerRendererData] _MainTex("Texture", 2D) = "white" {}            //
    7.         _Color("Tint", Color) = (1, 1, 1, 1)                            //
    8.         //[MaterialToggle] PixelSnap("Pixel snap", Float) = 0                // EXTRA
    9.         _Cutoff("AlphaCutout", Range(0.0, 1.0)) = 0.5                    //
    10.  
    11.         // Specular vs Metallic workflow
    12.         //[HideInInspector] _WorkflowMode("WorkflowMode", Float) = 1.0
    13.  
    14.         [MainColor] _BaseColor("Color", Color) = (1, 1, 1, 1) //(0.5,0.5,0.5,1)
    15.         //[MainTexture] _MainTex("Albedo", 2D) = "white" {}
    16.  
    17.         //_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 1.0
    18.  
    19.         _Smoothness("Smoothness", Range(0.0, 1.0)) = 0
    20.         _GlossMapScale("Smoothness Scale", Range(0.0, 1.0)) = 1.0
    21.         _SmoothnessTextureChannel("Smoothness texture channel", Float) = 0
    22.  
    23.         [Gamma] _Metallic("Metallic", Range(0.0, 1.0)) = 0.0
    24.         _MetallicGlossMap("Metallic", 2D) = "white" {}
    25.  
    26.         _SpecColor("Specular", Color) = (1, 1, 1, 1) // (0.2, 0.2, 0.2)
    27.         _SpecGlossMap("Specular", 2D) = "white" {}
    28.  
    29.         [ToggleOff] _SpecularHighlights("Specular Highlights", Float) = 1.0
    30.         [ToggleOff] _EnvironmentReflections("Environment Reflections", Float) = 2.0
    31.  
    32.         _BumpScale("Scale", Float) = 1.0
    33.         _BumpMap("Normal Map", 2D) = "bump" {}
    34.  
    35.         _OcclusionStrength("Strength", Range(0.0, 1.0)) = 1.0
    36.         _OcclusionMap("Occlusion", 2D) = "white" {}
    37.  
    38.         _EmissionColor("Color", Color) = (0,0,0)
    39.         _EmissionMap("Emission", 2D) = "white" {}
    40.  
    41.         // Blending state
    42.         [HideInInspector] _Surface("__surface", Float) = 0.0
    43.         [HideInInspector] _Blend("__blend", Float) = 0.0
    44.         [HideInInspector] _AlphaClip("__clip", Float) = 0.0
    45.         [HideInInspector] _SrcBlend("__src", Float) = 1.0
    46.         [HideInInspector] _DstBlend("__dst", Float) = 0.0
    47.         [HideInInspector] _ZWrite("__zw", Float) = 1.0
    48.         [HideInInspector] _Cull("__cull", Float) = 2.0
    49.  
    50.         _ReceiveShadows("Receive Shadows", Float) = 1.0
    51.         // Editmode props
    52.         [HideInInspector] _QueueOffset("Queue offset", Float) = 0.0
    53.  
    54.         // ObsoleteProperties
    55.         //[HideInInspector] _MainTex("BaseMap", 2D) = "white" {}
    56.         //[HideInInspector] _Color("Base Color", Color) = (0.5, 0.5, 0.5, 1)
    57.         [HideInInspector] _GlossMapScale("Smoothness", Float) = 0.0
    58.         [HideInInspector] _Glossiness("Smoothness", Float) = 0.0
    59.         [HideInInspector] _GlossyReflections("EnvironmentReflections", Float) = 0.0
    60.     }
    61.  
    62.     SubShader
    63.     {
    64.         // Universal Pipeline tag is required. If Universal render pipeline is not set in the graphics settings
    65.         // this Subshader will fail. One can add a subshader below or fallback to Standard built-in to make this
    66.         // material work with both Universal Render Pipeline and Builtin Unity Pipeline
    67.         Tags
    68.         {
    69.             "RenderType" = "Opaque"
    70.             "IgnoreProjector" = "True"
    71.             "RenderPipeline" = "UniversalPipeline"
    72.  
    73.             "Queue" = "Transparent"                //    EXTRA
    74.             "PreviewType" = "Plane"                //
    75.             "CanUseSpriteAtlas" = "True"        //
    76.         }
    77.         LOD 300
    78.  
    79.         Blend[_SrcBlend][_DstBlend]
    80.         ZWrite On
    81.         Cull Off
    82.         Lighting On            //    EXTRA
    83.  
    84.         // ------------------------------------------------------------------
    85.         //  Forward pass. Shades all light in a single pass. GI + emission + Fog
    86.         Pass
    87.         {
    88.             // Lightmode matches the ShaderPassName set in UniversalRenderPipeline.cs. SRPDefaultUnlit and passes with
    89.             // no LightMode tag are also rendered by Universal Render Pipeline
    90.             Name "ForwardLit"
    91.             Tags{"LightMode" = "UniversalForward"}
    92.  
    93.             Blend[_SrcBlend][_DstBlend]
    94.             ZWrite[_ZWrite]
    95.             Cull[_Cull]
    96.  
    97.             HLSLPROGRAM
    98.             // Required to compile gles 2.0 with standard SRP library
    99.             // All shaders must be compiled with HLSLcc and currently only gles is not using HLSLcc by default
    100.             #pragma prefer_hlslcc gles
    101.             #pragma exclude_renderers d3d11_9x
    102.             #pragma target 2.0
    103.  
    104.             // -------------------------------------
    105.             // Material Keywords
    106.             #pragma shader_feature _NORMALMAP
    107.             #pragma shader_feature _ALPHATEST_ON
    108.             #pragma shader_feature _ALPHAPREMULTIPLY_ON
    109.             #pragma shader_feature _EMISSION
    110.             #pragma shader_feature _METALLICSPECGLOSSMAP
    111.             #pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
    112.             #pragma shader_feature _OCCLUSIONMAP
    113.  
    114.             #pragma shader_feature _SPECULARHIGHLIGHTS_OFF
    115.             #pragma shader_feature _ENVIRONMENTREFLECTIONS_OFF
    116.             #pragma shader_feature _SPECULAR_SETUP
    117.             #pragma shader_feature _RECEIVE_SHADOWS_OFF
    118.  
    119.             // -------------------------------------
    120.             // Universal Pipeline keywords
    121.             #pragma multi_compile _ _MAIN_LIGHT_SHADOWS
    122.             #pragma multi_compile _ _MAIN_LIGHT_SHADOWS_CASCADE
    123.             #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS
    124.             #pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS
    125.             #pragma multi_compile _ _SHADOWS_SOFT
    126.             #pragma multi_compile _ _MIXED_LIGHTING_SUBTRACTIVE
    127.  
    128.             // -------------------------------------
    129.             // Unity defined keywords
    130.             #pragma multi_compile _ DIRLIGHTMAP_COMBINED
    131.             #pragma multi_compile _ LIGHTMAP_ON
    132.             #pragma multi_compile_fog
    133.  
    134.             //--------------------------------------
    135.             // GPU Instancing
    136.             #pragma multi_compile_instancing
    137.  
    138.             #pragma vertex LitPassVertex
    139.             #pragma fragment LitPassFragment
    140.  
    141.             #ifdef _ALPHAPREMULTIPLY_ON
    142.                 basecolor *= alpha;
    143.             #endif
    144.  
    145.             #include "LitInput.hlsl"
    146.             #include "LitForwardPass.hlsl"
    147.             ENDHLSL
    148.         }
    149.  
    150.         Pass
    151.         {
    152.             Name "ShadowCaster"
    153.             Tags{"LightMode" = "ShadowCaster"}
    154.  
    155.             ZWrite On
    156.             ZTest LEqual
    157.             Cull[_Cull]
    158.  
    159.             HLSLPROGRAM
    160.             // Required to compile gles 2.0 with standard srp library
    161.             #pragma prefer_hlslcc gles
    162.             #pragma exclude_renderers d3d11_9x
    163.             #pragma target 2.0
    164.  
    165.             // -------------------------------------
    166.             // Material Keywords
    167.             #pragma shader_feature _ALPHATEST_ON
    168.  
    169.             //--------------------------------------
    170.             // GPU Instancing
    171.             #pragma multi_compile_instancing
    172.             #pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
    173.  
    174.             #pragma vertex ShadowPassVertex
    175.             #pragma fragment ShadowPassFragment
    176.  
    177.             #include "LitInput.hlsl"
    178.             #include "ShadowCasterPass.hlsl"
    179.             ENDHLSL
    180.         }
    181.  
    182.         Pass
    183.         {
    184.             Name "DepthOnly"
    185.             Tags{"LightMode" = "DepthOnly"}
    186.  
    187.             ZWrite On
    188.             ColorMask 0
    189.             Cull[_Cull]
    190.  
    191.             HLSLPROGRAM
    192.             // Required to compile gles 2.0 with standard srp library
    193.             #pragma prefer_hlslcc gles
    194.             #pragma exclude_renderers d3d11_9x
    195.             #pragma target 2.0
    196.  
    197.             #pragma vertex DepthOnlyVertex
    198.             #pragma fragment DepthOnlyFragment
    199.  
    200.             // -------------------------------------
    201.             // Material Keywords
    202.             #pragma shader_feature _ALPHATEST_ON
    203.             #pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
    204.  
    205.             //--------------------------------------
    206.             // GPU Instancing
    207.             #pragma multi_compile_instancing
    208.  
    209.             #include "LitInput.hlsl"
    210.             #include "DepthOnlyPass.hlsl"
    211.             ENDHLSL
    212.         }
    213.  
    214.         // This pass it not used during regular rendering, only for lightmap baking.
    215.         Pass
    216.         {
    217.             Name "Meta"
    218.             Tags{"LightMode" = "Meta"}
    219.  
    220.             Cull Off
    221.  
    222.             HLSLPROGRAM
    223.             // Required to compile gles 2.0 with standard srp library
    224.             #pragma prefer_hlslcc gles
    225.             #pragma exclude_renderers d3d11_9x
    226.  
    227.             #pragma vertex UniversalVertexMeta
    228.             #pragma fragment UniversalFragmentMeta
    229.  
    230.             #pragma shader_feature _SPECULAR_SETUP
    231.             #pragma shader_feature _EMISSION
    232.             #pragma shader_feature _METALLICSPECGLOSSMAP
    233.             #pragma shader_feature _ALPHATEST_ON
    234.             #pragma shader_feature _ _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
    235.  
    236.             #pragma shader_feature _SPECGLOSSMAP
    237.  
    238.             #include "LitInput.hlsl"
    239.             #include "LitMetaPass.hlsl"
    240.  
    241.             ENDHLSL
    242.         }
    243.      
    244.         Pass
    245.         {
    246.             Name "Universal2D"
    247.             Tags{ "LightMode" = "Universal2D" }
    248.  
    249.             Blend[_SrcBlend][_DstBlend]
    250.             ZWrite[_ZWrite]
    251.             Cull[_Cull]
    252.  
    253.             HLSLPROGRAM
    254.             // Required to compile gles 2.0 with standard srp library
    255.             #pragma prefer_hlslcc gles
    256.             #pragma exclude_renderers d3d11_9x
    257.  
    258.             #pragma vertex vert
    259.             #pragma fragment frag
    260.             #pragma shader_feature _ALPHATEST_ON
    261.             #pragma shader_feature _ALPHAPREMULTIPLY_ON
    262.  
    263.             #include "LitInput.hlsl"
    264.             #include "Universal2D.hlsl"
    265.             ENDHLSL
    266.         }
    267.  
    268.  
    269.     }
    270.     FallBack "Hidden/InternalError"
    271.     Fallback "Transparent/Cutout/Diffuse"    // EXTRA
    272.     // CustomEditor "UnityEditor.Rendering.Universal.ShaderGUI.LitShader"
    273. }
     
    Last edited: Jan 6, 2020
  6. OG_oliver

    OG_oliver

    Joined:
    Aug 11, 2019
    Posts:
    15
    Artboard 1.png I couldn't manage to make this code work and I will do my best to learn the .shader language to maybe make it work in the future since I have some hypothesis on why it doesn't work as intended. But I've managed to achieve what I wanted with the shader graph!
    It was a little tricky at first but after 1h (yes I take time to understand simple things) I've done this graph that works fine in the URP and is easy to understand et to do.

    This shader allows the sprites that have it to behave like 3D planes to light. In other words :
    - To cast shadows (taking into account their original alpha values)
    - To receive/show shadows from other objects in front
    - React to the 3D lighting in general
    And all by using a URP shader (that works on any sprite)!!!

    By the way, the sliders are there to make it easier to modify the shader and for stability, because people said on other threads that if you use raw values it might stop working randomly. I'm completely open to an explanation to that or a working version of the .shader from a brave developer.
    Thanks in advance.
    I hope this can help someone with this particular constraint/problem in the future.
     
    Last edited: Mar 6, 2020
    shawnblais, oleksii_slipets and L_A_R like this.
  7. tfalves

    tfalves

    Joined:
    Jun 27, 2014
    Posts:
    29
    EDIT: Ignore what I wrote below, I just realised you can use _MainTex to connect it to the Sprite Renderer.
    I am trying this approach too but I have an issue: How do I use animations and animation controllers like this? Since the shader will only take a single texture.
     
    Last edited: Jul 10, 2020
    OG_oliver likes this.
  8. OG_oliver

    OG_oliver

    Joined:
    Aug 11, 2019
    Posts:
    15
    The shader will apply to the entire sprite sheet. That means that every sprite of the same sprite sheet (and so the animations) will see the shader applied to it. So you can use your animation controllers as you'll do without a shader.
     
    tfalves likes this.
  9. tfalves

    tfalves

    Joined:
    Jun 27, 2014
    Posts:
    29
    Yes, you are right, the main issue is that I did not realised what _MainTex did, hence I was trying to figure out how to connect the texture from the animation to the shader (insert facepalm).
     
    OG_oliver likes this.
  10. OG_oliver

    OG_oliver

    Joined:
    Aug 11, 2019
    Posts:
    15
    Hello everyone,
    There is something that I didn't mention earlier (because I was unable to find it). If you want to make the sprites two-sided (that you may want if they will be integrated into a 3D environment) you have to click the little gear that appears in the top right corner of the output node when you hover it. It will unfold some options that have default values (in order to maintain a certain performance). Between these options, you will find one that has to be enabled (a boolean or checkbox) that will make the shader double-sided.

    It took me weeks to find it. I don't know why the little gear is hidden by default but anyway, the credit is for this Unity forum thread: https://forum.unity.com/threads/lwrp-shader-graph-how-do-render-back-faces.671644/
     
  11. darkeonline

    darkeonline

    Joined:
    Dec 11, 2019
    Posts:
    1
    Hello, i'm late but i think i can help. I make a little demo for have that kind of look. Here my solution : don't import a sprite in 3D, make a quad and import your sprite sheet as a texture ! After that, animate the texture. That work very well, and have no problem of compatibility. I don't try in the URP mode, but i think it's work.
    A little video of that :
     
  12. seahj

    seahj

    Joined:
    May 29, 2020
    Posts:
    1
    Sorry, can you tell me how you created the shaders? I've tried the OG's solution, but it didn't work and the shadows did not show up. Your project looks great!
     
  13. tategarringer

    tategarringer

    Joined:
    Jul 12, 2018
    Posts:
    1
    Hey all, first time commenting, but this issue was such a massive headache for me that I sat down for a few hours and implemented NotSlot's suggested solution with the alpha cutout parameters that OG_Oliver was missing (by the way, thank you for pointing me in the right direction with the link to NotSlot's tutorials, never would have found it without that). I'll post the Shader and all the required dependency code below. Worth noting that if, like me, your URP implementation is from the Package Manager as opposed to starting a project with the URP option, you'll likely have some tweaking to do to your pipeline settings to get shadows to appear.

    Lit Sprite.shader:
    Code (CSharp):
    1. Shader "Universal Render Pipeline/Lit Sprite"
    2. {
    3.     Properties
    4.     {
    5.         [MainTexture] _MainTex("Albedo", 2D) = "white" {}
    6.         _Color("Tint", Color) = (1,1,1,1)
    7.         _Cutoff("AlphaCutout", Range(0.0, 1.0)) = 0.5
    8.  
    9.         [MainColor] _BaseColor("Color", Color) = (0.5,0.5,0.5,1)
    10.  
    11.         // Blending state
    12.         [HideInInspector] _Surface("__surface", Float) = 0.0
    13.         [HideInInspector] _Blend("__blend", Float) = 0.0
    14.         [HideInInspector] _AlphaClip("__clip", Float) = 0.0
    15.         [HideInInspector] _SrcBlend("__src", Float) = 1.0
    16.         [HideInInspector] _DstBlend("__dst", Float) = 0.0
    17.         [HideInInspector] _ZWrite("__zw", Float) = 1.0
    18.         [HideInInspector] _Cull("__cull", Float) = 2.0
    19.         // Editmode props
    20.         [HideInInspector] _QueueOffset("Queue offset", Float) = 0.0
    21.     }
    22.  
    23.         SubShader
    24.             {
    25.                 // Universal Pipeline tag is required. If Universal render pipeline is not set in the graphics settings
    26.                 // this Subshader will fail. One can add a subshader below or fallback to Standard built-in to make this
    27.                 // material work with both Universal Render Pipeline and Builtin Unity Pipeline
    28.                 Tags
    29.                 {
    30.                     "RenderType" = "Opaque"
    31.                     "IgnoreProjector" = "True"
    32.                     "RenderPipeline" = "UniversalPipeline"
    33.                 }
    34.                 LOD 300
    35.                 Blend[_SrcBlend][_DstBlend]
    36.                 ZWrite On
    37.                 Cull Off
    38.                 Lighting On
    39.  
    40.                 // ------------------------------------------------------------------
    41.                 //  Forward pass. Shades all light in a single pass. GI + emission + Fog
    42.                 Pass
    43.                 {
    44.                     // Lightmode matches the ShaderPassName set in UniversalRenderPipeline.cs. SRPDefaultUnlit and passes with
    45.                     // no LightMode tag are also rendered by Universal Render Pipeline
    46.                     Name "ForwardLit"
    47.                     Tags{"LightMode" = "UniversalForward"}
    48.  
    49.                     Blend[_SrcBlend][_DstBlend]
    50.                     ZWrite On
    51.                     Cull Off
    52.  
    53.                     HLSLPROGRAM
    54.                 // Required to compile gles 2.0 with standard SRP library
    55.                 // All shaders must be compiled with HLSLcc and currently only gles is not using HLSLcc by default
    56.                 #pragma prefer_hlslcc gles
    57.                 #pragma exclude_renderers d3d11_9x
    58.                 #pragma target 2.0
    59.  
    60.                 // -------------------------------------
    61.                 // Material Keywords
    62.                 #pragma shader_feature _NORMALMAP
    63.                 #pragma shader_feature _ALPHATEST_ON
    64.                 #pragma shader_feature _ALPHAPREMULTIPLY_ON
    65.                 #pragma shader_feature _EMISSION
    66.                 #pragma shader_feature _METALLICSPECGLOSSMAP
    67.                 #pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
    68.                 #pragma shader_feature _OCCLUSIONMAP
    69.  
    70.                 #pragma shader_feature _SPECULARHIGHLIGHTS_OFF
    71.                 #pragma shader_feature _ENVIRONMENTREFLECTIONS_OFF
    72.                 #pragma shader_feature _SPECULAR_SETUP
    73.                 #pragma shader_feature _RECEIVE_SHADOWS_ON
    74.  
    75.                 // -------------------------------------
    76.                 // Universal Pipeline keywords
    77.                 #pragma multi_compile _ _MAIN_LIGHT_SHADOWS
    78.                 #pragma multi_compile _ _MAIN_LIGHT_SHADOWS_CASCADE
    79.                 #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS
    80.                 #pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS
    81.                 #pragma multi_compile _ _SHADOWS_SOFT
    82.                 #pragma multi_compile _ _MIXED_LIGHTING_SUBTRACTIVE
    83.  
    84.                 // -------------------------------------
    85.                 // Unity defined keywords
    86.                 #pragma multi_compile _ DIRLIGHTMAP_COMBINED
    87.                 #pragma multi_compile _ LIGHTMAP_ON
    88.                 #pragma multi_compile_fog
    89.  
    90.                 //--------------------------------------
    91.                 // GPU Instancing
    92.                 #pragma multi_compile_instancing
    93.  
    94.                 #pragma vertex LitPassVertex
    95.                 #pragma fragment LitPassFragment
    96.  
    97.                 #ifdef _ALPHAPREMULTIPLY_ON
    98.                     basecolor *= alpha;
    99.                 #endif
    100.  
    101.                 #include "LitInput.hlsl"
    102.                 #include "LitForwardPass.hlsl"
    103.                 ENDHLSL
    104.             }
    105.  
    106.             Pass
    107.             {
    108.                 Name "ShadowCaster"
    109.                 Tags{"LightMode" = "ShadowCaster"}
    110.  
    111.                 ZWrite On
    112.                 ZTest LEqual
    113.                 Cull Off
    114.  
    115.                 HLSLPROGRAM
    116.                 // Required to compile gles 2.0 with standard srp library
    117.                 #pragma prefer_hlslcc gles
    118.                 #pragma exclude_renderers d3d11_9x
    119.                 #pragma target 2.0
    120.  
    121.                 // -------------------------------------
    122.                 // Material Keywords
    123.                 #pragma shader_feature _ALPHATEST_ON
    124.  
    125.                 //--------------------------------------
    126.                 // GPU Instancing
    127.                 #pragma multi_compile_instancing
    128.                 #pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
    129.  
    130.                 #pragma vertex ShadowPassVertex
    131.                 #pragma fragment ShadowPassFragment
    132.  
    133.                 #include "LitInput.hlsl"
    134.                 #include "ShadowCasterPass.hlsl"
    135.                 ENDHLSL
    136.             }
    137.  
    138.             Pass
    139.             {
    140.                 Name "DepthOnly"
    141.                 Tags{"LightMode" = "DepthOnly"}
    142.  
    143.                 ZWrite On
    144.                 ColorMask 0
    145.                 Cull Off
    146.  
    147.                 HLSLPROGRAM
    148.                 // Required to compile gles 2.0 with standard srp library
    149.                 #pragma prefer_hlslcc gles
    150.                 #pragma exclude_renderers d3d11_9x
    151.                 #pragma target 2.0
    152.  
    153.                 #pragma vertex DepthOnlyVertex
    154.                 #pragma fragment DepthOnlyFragment
    155.  
    156.                 // -------------------------------------
    157.                 // Material Keywords
    158.                 #pragma shader_feature _ALPHATEST_ON
    159.                 #pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
    160.  
    161.                 //--------------------------------------
    162.                 // GPU Instancing
    163.                 #pragma multi_compile_instancing
    164.  
    165.                 #include "LitInput.hlsl"
    166.                 #include "DepthOnlyPass.hlsl"
    167.                 ENDHLSL
    168.             }
    169.  
    170.                 // This pass it not used during regular rendering, only for lightmap baking.
    171.                 Pass
    172.                 {
    173.                     Name "Meta"
    174.                     Tags{"LightMode" = "Meta"}
    175.  
    176.                     Cull Off
    177.  
    178.                     HLSLPROGRAM
    179.                 // Required to compile gles 2.0 with standard srp library
    180.                 #pragma prefer_hlslcc gles
    181.                 #pragma exclude_renderers d3d11_9x
    182.  
    183.                 #pragma vertex UniversalVertexMeta
    184.                 #pragma fragment UniversalFragmentMeta
    185.  
    186.                 #pragma shader_feature _SPECULAR_SETUP
    187.                 #pragma shader_feature _EMISSION
    188.                 #pragma shader_feature _METALLICSPECGLOSSMAP
    189.                 #pragma shader_feature _ALPHATEST_ON
    190.                 #pragma shader_feature _ _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
    191.  
    192.                 #pragma shader_feature _SPECGLOSSMAP
    193.  
    194.                 #include "LitInput.hlsl"
    195.                 #include "LitMetaPass.hlsl"
    196.  
    197.                 ENDHLSL
    198.             }
    199.             Pass
    200.             {
    201.                 Name "Universal2D"
    202.                 Tags{ "LightMode" = "Universal2D" }
    203.  
    204.                 Blend[_SrcBlend][_DstBlend]
    205.                 ZWrite On
    206.                 Cull Off
    207.  
    208.                 HLSLPROGRAM
    209.                 // Required to compile gles 2.0 with standard srp library
    210.                 #pragma prefer_hlslcc gles
    211.                 #pragma exclude_renderers d3d11_9x
    212.  
    213.                 #pragma vertex vert
    214.                 #pragma fragment frag
    215.                 #pragma shader_feature _ALPHATEST_ON
    216.                 #pragma shader_feature _ALPHAPREMULTIPLY_ON
    217.  
    218.                 #include "LitInput.hlsl"
    219.                 #include "Universal2D.hlsl"
    220.                 ENDHLSL
    221.             }
    222.  
    223.  
    224.             }
    225.             FallBack "Hidden/InternalErrorShader"
    226.             Fallback "Transparent/Cutout/Diffuse"
    227. }
    DepthOnlyPass.hlsl:
    Code (CSharp):
    1. #ifndef UNIVERSAL_DEPTH_ONLY_PASS_INCLUDED
    2. #define UNIVERSAL_DEPTH_ONLY_PASS_INCLUDED
    3.  
    4. #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
    5.  
    6. struct Attributes
    7. {
    8.     float4 position     : POSITION;
    9.     float2 texcoord     : TEXCOORD0;
    10.     UNITY_VERTEX_INPUT_INSTANCE_ID
    11. };
    12.  
    13. struct Varyings
    14. {
    15.     float2 uv           : TEXCOORD0;
    16.     float4 positionCS   : SV_POSITION;
    17.     UNITY_VERTEX_INPUT_INSTANCE_ID
    18.     UNITY_VERTEX_OUTPUT_STEREO
    19. };
    20.  
    21. Varyings DepthOnlyVertex(Attributes input)
    22. {
    23.     Varyings output = (Varyings)0;
    24.     UNITY_SETUP_INSTANCE_ID(input);
    25.     UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
    26.  
    27.     output.uv = TRANSFORM_TEX(input.texcoord, _MainTex);
    28.     output.positionCS = TransformObjectToHClip(input.position.xyz);
    29.     return output;
    30. }
    31.  
    32. half4 DepthOnlyFragment(Varyings input) : SV_TARGET
    33. {
    34.     UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
    35.  
    36.     Alpha(SampleAlbedoAlpha(input.uv, TEXTURE2D_ARGS(_MainTex, sampler_MainTex)).a, _BaseColor, _Cutoff);
    37.     return 0;
    38. }
    39. #endif
    LitMetaPass.hlsl:
    Code (CSharp):
    1. #ifndef UNIVERSAL_LIT_META_PASS_INCLUDED
    2. #define UNIVERSAL_LIT_META_PASS_INCLUDED
    3.  
    4. #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/MetaInput.hlsl"
    5.  
    6. struct Attributes
    7. {
    8.     float4 positionOS   : POSITION;
    9.     float3 normalOS     : NORMAL;
    10.     float2 uv0          : TEXCOORD0;
    11.     float2 uv1          : TEXCOORD1;
    12.     float2 uv2          : TEXCOORD2;
    13. #ifdef _TANGENT_TO_WORLD
    14.     float4 tangentOS     : TANGENT;
    15. #endif
    16. };
    17.  
    18. struct Varyings
    19. {
    20.     float4 positionCS   : SV_POSITION;
    21.     float2 uv           : TEXCOORD0;
    22. };
    23.  
    24. Varyings UniversalVertexMeta(Attributes input)
    25. {
    26.     Varyings output;
    27.     output.positionCS = MetaVertexPosition(input.positionOS, input.uv1, input.uv2,
    28.         unity_LightmapST, unity_DynamicLightmapST);
    29.     output.uv = TRANSFORM_TEX(input.uv0, _MainTex);
    30.     return output;
    31. }
    32.  
    33. half4 UniversalFragmentMeta(Varyings input) : SV_Target
    34. {
    35.     SurfaceData surfaceData;
    36.     InitializeStandardLitSurfaceData(input.uv, surfaceData);
    37.  
    38.     BRDFData brdfData;
    39.     InitializeBRDFData(surfaceData.albedo, surfaceData.metallic, surfaceData.specular, surfaceData.smoothness, surfaceData.alpha, brdfData);
    40.  
    41.     MetaInput metaInput;
    42.     metaInput.Albedo = brdfData.diffuse + brdfData.specular * brdfData.roughness * 0.5;
    43.     metaInput.SpecularColor = surfaceData.specular;
    44.     metaInput.Emission = surfaceData.emission;
    45.  
    46.     return MetaFragment(metaInput);
    47. }
    48.  
    49.  
    50. //LWRP -> Universal Backwards Compatibility
    51. Varyings LightweightVertexMeta(Attributes input)
    52. {
    53.     return UniversalVertexMeta(input);
    54. }
    55.  
    56. half4 LightweightFragmentMeta(Varyings input) : SV_Target
    57. {
    58.     return UniversalFragmentMeta(input);
    59. }
    60.  
    61. #endif
    LitInput.hlsl
    Code (CSharp):
    1. #ifndef UNIVERSAL_LIT_INPUT_INCLUDED
    2. #define UNIVERSAL_LIT_INPUT_INCLUDED
    3.  
    4. #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
    5. #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonMaterial.hlsl"
    6. #include "SurfaceInput.hlsl"
    7.  
    8. CBUFFER_START(UnityPerMaterial)
    9. float4 _MainTex_ST;
    10. half4 _BaseColor;
    11. half4 _SpecColor;
    12. half4 _EmissionColor;
    13. half _Cutoff;
    14. half _Smoothness;
    15. half _Metallic;
    16. half _BumpScale;
    17. half _OcclusionStrength;
    18. CBUFFER_END
    19.  
    20. TEXTURE2D(_OcclusionMap);       SAMPLER(sampler_OcclusionMap);
    21. TEXTURE2D(_MetallicGlossMap);   SAMPLER(sampler_MetallicGlossMap);
    22. TEXTURE2D(_SpecGlossMap);       SAMPLER(sampler_SpecGlossMap);
    23.  
    24. #ifdef _SPECULAR_SETUP
    25.     #define SAMPLE_METALLICSPECULAR(uv) SAMPLE_TEXTURE2D(_SpecGlossMap, sampler_SpecGlossMap, uv)
    26. #else
    27.     #define SAMPLE_METALLICSPECULAR(uv) SAMPLE_TEXTURE2D(_MetallicGlossMap, sampler_MetallicGlossMap, uv)
    28. #endif
    29.  
    30. half4 SampleMetallicSpecGloss(float2 uv, half albedoAlpha)
    31. {
    32.     half4 specGloss;
    33.  
    34. #ifdef _METALLICSPECGLOSSMAP
    35.     specGloss = SAMPLE_METALLICSPECULAR(uv);
    36.     #ifdef _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
    37.         specGloss.a = albedoAlpha * _Smoothness;
    38.     #else
    39.         specGloss.a *= _Smoothness;
    40.     #endif
    41. #else // _METALLICSPECGLOSSMAP
    42.     #if _SPECULAR_SETUP
    43.         specGloss.rgb = _SpecColor.rgb;
    44.     #else
    45.         specGloss.rgb = _Metallic.rrr;
    46.     #endif
    47.  
    48.     #ifdef _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
    49.         specGloss.a = albedoAlpha * _Smoothness;
    50.     #else
    51.         specGloss.a = _Smoothness;
    52.     #endif
    53. #endif
    54.  
    55.     return specGloss;
    56. }
    57.  
    58. half SampleOcclusion(float2 uv)
    59. {
    60. #ifdef _OCCLUSIONMAP
    61. // TODO: Controls things like these by exposing SHADER_QUALITY levels (low, medium, high)
    62. #if defined(SHADER_API_GLES)
    63.     return SAMPLE_TEXTURE2D(_OcclusionMap, sampler_OcclusionMap, uv).g;
    64. #else
    65.     half occ = SAMPLE_TEXTURE2D(_OcclusionMap, sampler_OcclusionMap, uv).g;
    66.     return LerpWhiteTo(occ, _OcclusionStrength);
    67. #endif
    68. #else
    69.     return 1.0;
    70. #endif
    71. }
    72.  
    73. inline void InitializeStandardLitSurfaceData(float2 uv, out SurfaceData outSurfaceData)
    74. {
    75.     half4 albedoAlpha = SampleAlbedoAlpha(uv, TEXTURE2D_ARGS(_MainTex, sampler_MainTex));
    76.     outSurfaceData.alpha = Alpha(albedoAlpha.a, _BaseColor, _Cutoff);
    77.  
    78.     half4 specGloss = SampleMetallicSpecGloss(uv, albedoAlpha.a);
    79.     outSurfaceData.albedo = albedoAlpha.rgb * _BaseColor.rgb;
    80.  
    81. #if _SPECULAR_SETUP
    82.     outSurfaceData.metallic = 1.0h;
    83.     outSurfaceData.specular = specGloss.rgb;
    84. #else
    85.     outSurfaceData.metallic = specGloss.r;
    86.     outSurfaceData.specular = half3(0.0h, 0.0h, 0.0h);
    87. #endif
    88.  
    89.     outSurfaceData.smoothness = specGloss.a;
    90.     outSurfaceData.normalTS = SampleNormal(uv, TEXTURE2D_ARGS(_BumpMap, sampler_BumpMap), _BumpScale);
    91.     outSurfaceData.occlusion = SampleOcclusion(uv);
    92.     outSurfaceData.emission = SampleEmission(uv, _EmissionColor.rgb, TEXTURE2D_ARGS(_EmissionMap, sampler_EmissionMap));
    93. }
    94.  
    95. #endif // UNIVERSAL_INPUT_SURFACE_PBR_INCLUDED
    LitForwardPass:
    Code (CSharp):
    1. #ifndef UNIVERSAL_FORWARD_LIT_PASS_INCLUDED
    2. #define UNIVERSAL_FORWARD_LIT_PASS_INCLUDED
    3.  
    4. #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
    5.  
    6. struct Attributes
    7. {
    8.     float4 positionOS   : POSITION;
    9.     float3 normalOS     : NORMAL;
    10.     float4 tangentOS    : TANGENT;
    11.     float2 texcoord     : TEXCOORD0;
    12.     float2 lightmapUV   : TEXCOORD1;
    13.     UNITY_VERTEX_INPUT_INSTANCE_ID
    14. };
    15.  
    16. struct Varyings
    17. {
    18.     float2 uv                       : TEXCOORD0;
    19.     DECLARE_LIGHTMAP_OR_SH(lightmapUV, vertexSH, 1);
    20.  
    21. #if defined(REQUIRES_WORLD_SPACE_POS_INTERPOLATOR)
    22.     float3 positionWS               : TEXCOORD2;
    23. #endif
    24.  
    25. #ifdef _NORMALMAP
    26.     float4 normalWS                 : TEXCOORD3;    // xyz: normal, w: viewDir.x
    27.     float4 tangentWS                : TEXCOORD4;    // xyz: tangent, w: viewDir.y
    28.     float4 bitangentWS              : TEXCOORD5;    // xyz: bitangent, w: viewDir.z
    29. #else
    30.     float3 normalWS                 : TEXCOORD3;
    31.     float3 viewDirWS                : TEXCOORD4;
    32. #endif
    33.  
    34.     half4 fogFactorAndVertexLight   : TEXCOORD6; // x: fogFactor, yzw: vertex light
    35.  
    36. #if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
    37.     float4 shadowCoord              : TEXCOORD7;
    38. #endif
    39.  
    40.     float4 positionCS               : SV_POSITION;
    41.     UNITY_VERTEX_INPUT_INSTANCE_ID
    42.     UNITY_VERTEX_OUTPUT_STEREO
    43. };
    44.  
    45. void InitializeInputData(Varyings input, half3 normalTS, out InputData inputData)
    46. {
    47.     inputData = (InputData)0;
    48.  
    49. #if defined(REQUIRES_WORLD_SPACE_POS_INTERPOLATOR)
    50.     inputData.positionWS = input.positionWS;
    51. #endif
    52.  
    53. #ifdef _NORMALMAP
    54.     half3 viewDirWS = half3(input.normalWS.w, input.tangentWS.w, input.bitangentWS.w);
    55.     inputData.normalWS = TransformTangentToWorld(normalTS,
    56.         half3x3(input.tangentWS.xyz, input.bitangentWS.xyz, input.normalWS.xyz));
    57. #else
    58.     half3 viewDirWS = input.viewDirWS;
    59.     inputData.normalWS = input.normalWS;
    60. #endif
    61.  
    62.     inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS);
    63.     viewDirWS = SafeNormalize(viewDirWS);
    64.     inputData.viewDirectionWS = viewDirWS;
    65.  
    66. #if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
    67.     inputData.shadowCoord = input.shadowCoord;
    68. #elif defined(MAIN_LIGHT_CALCULATE_SHADOWS)
    69.     inputData.shadowCoord = TransformWorldToShadowCoord(inputData.positionWS);
    70. #else
    71.     inputData.shadowCoord = float4(0, 0, 0, 0);
    72. #endif
    73.  
    74.     inputData.fogCoord = input.fogFactorAndVertexLight.x;
    75.     inputData.vertexLighting = input.fogFactorAndVertexLight.yzw;
    76.     inputData.bakedGI = SAMPLE_GI(input.lightmapUV, input.vertexSH, inputData.normalWS);
    77. }
    78.  
    79. ///////////////////////////////////////////////////////////////////////////////
    80. //                  Vertex and Fragment functions                            //
    81. ///////////////////////////////////////////////////////////////////////////////
    82.  
    83. // Used in Standard (Physically Based) shader
    84. Varyings LitPassVertex(Attributes input)
    85. {
    86.     Varyings output = (Varyings)0;
    87.  
    88.     UNITY_SETUP_INSTANCE_ID(input);
    89.     UNITY_TRANSFER_INSTANCE_ID(input, output);
    90.     UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
    91.  
    92.     VertexPositionInputs vertexInput = GetVertexPositionInputs(input.positionOS.xyz);
    93.     VertexNormalInputs normalInput = GetVertexNormalInputs(input.normalOS, input.tangentOS);
    94.     half3 viewDirWS = GetCameraPositionWS() - vertexInput.positionWS;
    95.     half3 vertexLight = VertexLighting(vertexInput.positionWS, normalInput.normalWS);
    96.     half fogFactor = ComputeFogFactor(vertexInput.positionCS.z);
    97.  
    98.     output.uv = TRANSFORM_TEX(input.texcoord, _MainTex);
    99.  
    100. #ifdef _NORMALMAP
    101.     output.normalWS = half4(normalInput.normalWS, viewDirWS.x);
    102.     output.tangentWS = half4(normalInput.tangentWS, viewDirWS.y);
    103.     output.bitangentWS = half4(normalInput.bitangentWS, viewDirWS.z);
    104. #else
    105.     output.normalWS = NormalizeNormalPerVertex(normalInput.normalWS);
    106.     output.viewDirWS = viewDirWS;
    107. #endif
    108.  
    109.     OUTPUT_LIGHTMAP_UV(input.lightmapUV, unity_LightmapST, output.lightmapUV);
    110.     OUTPUT_SH(output.normalWS.xyz, output.vertexSH);
    111.  
    112.     output.fogFactorAndVertexLight = half4(fogFactor, vertexLight);
    113.  
    114. #if defined(REQUIRES_WORLD_SPACE_POS_INTERPOLATOR)
    115.     output.positionWS = vertexInput.positionWS;
    116. #endif
    117.  
    118. #if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
    119.     output.shadowCoord = GetShadowCoord(vertexInput);
    120. #endif
    121.  
    122.     output.positionCS = vertexInput.positionCS;
    123.  
    124.     return output;
    125. }
    126.  
    127. // Used in Standard (Physically Based) shader
    128. half4 LitPassFragment(Varyings input) : SV_Target
    129. {
    130.     UNITY_SETUP_INSTANCE_ID(input);
    131.     UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
    132.  
    133.     SurfaceData surfaceData;
    134.     InitializeStandardLitSurfaceData(input.uv, surfaceData);
    135.  
    136.     InputData inputData;
    137.     InitializeInputData(input, surfaceData.normalTS, inputData);
    138.  
    139.     half4 color = UniversalFragmentPBR(inputData, surfaceData.albedo, surfaceData.metallic, surfaceData.specular, surfaceData.smoothness, surfaceData.occlusion, surfaceData.emission, surfaceData.alpha);
    140.  
    141.     color.rgb = MixFog(color.rgb, inputData.fogCoord);
    142.     return color;
    143. }
    144.  
    145. #endif
    Universal2D.hlsl
    Code (CSharp):
    1. #ifndef UNIVERSAL_FALLBACK_2D_INCLUDED
    2. #define UNIVERSAL_FALLBACK_2D_INCLUDED
    3.  
    4. struct Attributes
    5. {
    6.     float4 positionOS       : POSITION;
    7.     float2 uv               : TEXCOORD0;
    8. };
    9.  
    10. struct Varyings
    11. {
    12.     float2 uv        : TEXCOORD0;
    13.     float4 vertex : SV_POSITION;
    14. };
    15.  
    16. Varyings vert(Attributes input)
    17. {
    18.     Varyings output = (Varyings)0;
    19.  
    20.     VertexPositionInputs vertexInput = GetVertexPositionInputs(input.positionOS.xyz);
    21.     output.vertex = vertexInput.positionCS;
    22.     output.uv = TRANSFORM_TEX(input.uv, _MainTex);
    23.  
    24.     return output;
    25. }
    26.  
    27. half4 frag(Varyings input) : SV_Target
    28. {
    29.     half2 uv = input.uv;
    30.     half4 texColor = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, uv);
    31.     half3 color = texColor.rgb * _BaseColor.rgb;
    32.     half alpha = texColor.a * _BaseColor.a;
    33.     //AlphaDiscard(alpha, _Cutoff);
    34.     clip(alpha - _Cutoff);
    35.  
    36. #ifdef _ALPHAPREMULTIPLY_ON
    37.     color *= alpha;
    38. #endif
    39.     return half4(color, alpha);
    40. }
    41.  
    42. #endif
    SurfaceInput.hlsl (this is where the 'clip(alpha - _Cutoff)' ended up going):
    Code (CSharp):
    1. #ifndef UNIVERSAL_INPUT_SURFACE_INCLUDED
    2. #define UNIVERSAL_INPUT_SURFACE_INCLUDED
    3.  
    4. #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
    5. #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Packing.hlsl"
    6. #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonMaterial.hlsl"
    7.  
    8. TEXTURE2D(_MainTex);            SAMPLER(sampler_MainTex);
    9. TEXTURE2D(_BumpMap);            SAMPLER(sampler_BumpMap);
    10. TEXTURE2D(_EmissionMap);        SAMPLER(sampler_EmissionMap);
    11.  
    12. // Must match Universal ShaderGraph master node
    13. struct SurfaceData
    14. {
    15.     half3 albedo;
    16.     half3 specular;
    17.     half  metallic;
    18.     half  smoothness;
    19.     half3 normalTS;
    20.     half3 emission;
    21.     half  occlusion;
    22.     half  alpha;
    23. };
    24.  
    25. ///////////////////////////////////////////////////////////////////////////////
    26. //                      Material Property Helpers                            //
    27. ///////////////////////////////////////////////////////////////////////////////
    28. half Alpha(half albedoAlpha, half4 color, half cutoff)
    29. {
    30. #if !defined(_SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A) && !defined(_GLOSSINESS_FROM_BASE_ALPHA)
    31.     half alpha = albedoAlpha * color.a;
    32. #else
    33.     half alpha = color.a;
    34. #endif
    35.  
    36.     clip(alpha - cutoff);
    37.     return alpha;
    38. }
    39.  
    40. half4 SampleAlbedoAlpha(float2 uv, TEXTURE2D_PARAM(albedoAlphaMap, sampler_albedoAlphaMap))
    41. {
    42.     return SAMPLE_TEXTURE2D(albedoAlphaMap, sampler_albedoAlphaMap, uv);
    43. }
    44.  
    45. half3 SampleNormal(float2 uv, TEXTURE2D_PARAM(bumpMap, sampler_bumpMap), half scale = 1.0h)
    46. {
    47. #ifdef _NORMALMAP
    48.     half4 n = SAMPLE_TEXTURE2D(bumpMap, sampler_bumpMap, uv);
    49. #if BUMP_SCALE_NOT_SUPPORTED
    50.     return UnpackNormal(n);
    51. #else
    52.     return UnpackNormalScale(n, scale);
    53. #endif
    54. #else
    55.     return half3(0.0h, 0.0h, 1.0h);
    56. #endif
    57. }
    58.  
    59. half3 SampleEmission(float2 uv, half3 emissionColor, TEXTURE2D_PARAM(emissionMap, sampler_emissionMap))
    60. {
    61. #ifndef _EMISSION
    62.     return 0;
    63. #else
    64.     return SAMPLE_TEXTURE2D(emissionMap, sampler_emissionMap, uv).rgb * emissionColor;
    65. #endif
    66. }
    67.  
    68. #endif
    ShadowCasterPass.hlsl:
    Code (CSharp):
    1. #ifndef UNIVERSAL_SHADOW_CASTER_PASS_INCLUDED
    2. #define UNIVERSAL_SHADOW_CASTER_PASS_INCLUDED
    3.  
    4. #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
    5. #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl"
    6.  
    7. float3 _LightDirection;
    8.  
    9. struct Attributes
    10. {
    11.     float4 positionOS   : POSITION;
    12.     float3 normalOS     : NORMAL;
    13.     float2 texcoord     : TEXCOORD0;
    14.     UNITY_VERTEX_INPUT_INSTANCE_ID
    15. };
    16.  
    17. struct Varyings
    18. {
    19.     float2 uv           : TEXCOORD0;
    20.     float4 positionCS   : SV_POSITION;
    21. };
    22.  
    23. float4 GetShadowPositionHClip(Attributes input)
    24. {
    25.     float3 positionWS = TransformObjectToWorld(input.positionOS.xyz);
    26.     float3 normalWS = TransformObjectToWorldNormal(input.normalOS);
    27.  
    28.     float4 positionCS = TransformWorldToHClip(ApplyShadowBias(positionWS, normalWS, _LightDirection));
    29.  
    30. #if UNITY_REVERSED_Z
    31.     positionCS.z = min(positionCS.z, positionCS.w * UNITY_NEAR_CLIP_VALUE);
    32. #else
    33.     positionCS.z = max(positionCS.z, positionCS.w * UNITY_NEAR_CLIP_VALUE);
    34. #endif
    35.  
    36.     return positionCS;
    37. }
    38.  
    39. Varyings ShadowPassVertex(Attributes input)
    40. {
    41.     Varyings output;
    42.     UNITY_SETUP_INSTANCE_ID(input);
    43.  
    44.     output.uv = TRANSFORM_TEX(input.texcoord, _MainTex);
    45.     output.positionCS = GetShadowPositionHClip(input);
    46.     return output;
    47. }
    48.  
    49. half4 ShadowPassFragment(Varyings input) : SV_TARGET
    50. {
    51.     Alpha(SampleAlbedoAlpha(input.uv, TEXTURE2D_ARGS(_MainTex, sampler_MainTex)).a, _BaseColor, _Cutoff);
    52.     return 0;
    53. }
    54.  
    55. #endif
    All of this code was pulled from the Unity-Technologies/Graphics GitHub release2019.3 branch and modified from there, mainly changes from _BaseMap to _MainTex, but I also removed unused properties from the shader file. I'm working in Unity 2020.1.17f1, so I know it's at least compatible from that range of releases. Hopefully this is helpful to someone, I know it was to me as now I have a shader that implements accurate lighting with soft, hard, or both shadows AND handles depth sorting all in one.
     
    Last edited: Dec 10, 2020
    kryzodoze, OG_oliver and Jiaquarium like this.
  14. viniciussurianolopesdasilva

    viniciussurianolopesdasilva

    Joined:
    Feb 17, 2021
    Posts:
    1
    I tryed to do the method of @tategarringer, but ocurred this...(Using Urp renderer)
    Anyone have a answer to this?
    (I'm newbie with unity)

    Shader error in 'Universal Render Pipeline/Lit Sprite': failed to open source file: 'LitForwardPass.hlsl' at line 102 (on d3d11)

    Compiling Vertex program
    Platform defines: UNITY_ENABLE_REFLECTION_BUFFERS UNITY_USE_DITHER_MASK_FOR_ALPHABLENDED_SHADOWS UNITY_PBS_USE_BRDF1 UNITY_SPECCUBE_BOX_PROJECTION UNITY_SPECCUBE_BLENDING UNITY_ENABLE_DETAIL_NORMALMAP SHADER_API_DESKTOP UNITY_COLORSPACE_GAMMA UNITY_LIGHT_PROBE_PROXY_VOLUME UNITY_LIGHTMAP_FULL_HDR
     
    Last edited: Feb 17, 2021
  15. Jiaquarium

    Jiaquarium

    Joined:
    Mar 22, 2020
    Posts:
    40
    I made a repo that implements Not Slot and tategarringer's methods to get Lighting to work on 2D Sprites in URP 3D https://github.com/strawberryjamnbutter/unity-URP-2.5D-lit-shader.

    You'll just need to comment out the line
    output.positionCS.z = BillboardVerticalZDepthVert(input, output);
    in LitForwardPass.hlsl if you don't need the clipping fix.

    Also last thing, you might need to change in the Sprite Renderer component
    Cast Shadows = On
    and
    Receive Shadows = True
    which are available in the Editor's Debug mode.
     
    Last edited: Jul 3, 2021
    kryzodoze likes this.
  16. pl0splus

    pl0splus

    Joined:
    Oct 17, 2020
    Posts:
    3
    Hi, thanks for posting that repo, just wondering where I'm supposed to put the line of code for removing the clipping fix.
    Thanks!
     
  17. Jiaquarium

    Jiaquarium

    Joined:
    Mar 22, 2020
    Posts:
    40
    It's in the LitPassVertex function in LitForwardPass.hlsl.
     
  18. facucan

    facucan

    Joined:
    Mar 8, 2017
    Posts:
    3
    Hey, first of all thank you very much for sharing your work. After some tweaking I finally got the lighting and the depth sorting working.
    But as you said, the shadows are not appearing and I don't know what I am missing. Can you point me in the right direction regarding the "tweaks" of the pipeline that you mentioned?

    Thanks in advance!