添加实时阴影

For the sake of anyone else who is trying to write a fragment shader that receives shadows, I figured it out.

You must do these things:

  1. '#include "AutoLight.cginc"'
  2. '#include "Lighting.cginc"'
  3. Add "Tags {"LightMode" = "ForwardBase"}
  4. '#pragma multi_compile_fwdbase'
  5. Add the Unity macros to your VSOut struct, VS and PS: LIGHTING_COORDS, TRANSFER_VERTEX_TO_FRAGMENT, LIGHT_ATTENUATION.

None of this is documented in the Unity manual.

To access the primary directional light color, unity_LightColor[0] works as long as you don't add "Tags {"LightMode" = "ForwardBase"}". If you do add that line, then it doesn't work: use _LightColor0.rgb instead. Why? Who knows.. probably makes sense to someone with access to the Unity source code. Which means no one.

Good luck!

-Peter

  1. Shader "Custom/PeterShader2" {
  2. Properties
  3. {
  4. _MainTex ("Base (RGB)", 2D) = "white" {}
  5. }
  6.  
  7. CGINCLUDE
  8.  
  9. #include "UnityCG.cginc"
  10. #include "AutoLight.cginc"
  11. #include "Lighting.cginc"
  12.  
  13. uniform sampler2D _MainTex;
  14.  
  15. ENDCG
  16.  
  17. SubShader
  18. {
  19. Tags { "RenderType"="Opaque" }
  20. LOD 200
  21.  
  22. Pass
  23. {
  24. Lighting On
  25.  
  26. Tags {"LightMode" = "ForwardBase"}
  27.  
  28. CGPROGRAM
  29.  
  30. #pragma vertex vert
  31. #pragma fragment frag
  32. #pragma multi_compile_fwdbase
  33.  
  34. struct VSOut
  35. {
  36. float4 pos : SV_POSITION;
  37. float2 uv : TEXCOORD1;
  38. LIGHTING_COORDS(3,4)
  39. };
  40.  
  41. VSOut vert(appdata_tan v)
  42. {
  43. VSOut o;
  44. o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
  45. o.uv = v.texcoord.xy;
  46.  
  47. TRANSFER_VERTEX_TO_FRAGMENT(o);
  48.  
  49. return o;
  50. }
  51.  
  52. float4 frag(VSOut i) : COLOR
  53. {
  54. float3 lightColor = _LightColor0.rgb;
  55. float3 lightDir = _WorldSpaceLightPos0;
  56. float4 colorTex = tex2D(_MainTex, i.uv.xy * float2(25.0f));
  57. float atten = LIGHT_ATTENUATION(i);
  58. float3 N = float3(0.0f, 1.0f, 0.0f);
  59. float NL = saturate(dot(N, lightDir));
  60.  
  61. float3 color = colorTex.rgb * lightColor * NL * atten;
  62. return float4(color, colorTex.a);
  63. }
  64.  
  65. ENDCG
  66. }
  67. }
  68. FallBack "Diffuse"
  69. }

你可能感兴趣的:(unity)