Advertisement
Guest User

Shadow Pixel Shader

a guest
Dec 17th, 2015
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. //Textures
  2. Texture2D shadowMap : register(t0);
  3.  
  4. //Samplers
  5. SamplerComparisonState  SCompare : register(s0);
  6.  
  7. //Constant buffers
  8. cbuffer SPerLightCB : register(b0)
  9. {
  10.     float4 ambientColour;
  11.     float4 diffuseColour;
  12.     float3 lightPos;
  13.     float padding;
  14. };
  15.  
  16. //Input structure
  17. struct PixelIn
  18. {
  19.     float4 Pos    : SV_POSITION;
  20.     float4 WPos   : TEXCOORD0;
  21.     float4 LPos   : TEXCOORD1;
  22.     float3 Normal : NORMAL;
  23.     float2 Tex    : TEXCOORD2;
  24. };
  25.  
  26. //Constants
  27. static const float SMAP_SIZE        = 1024.0f;          //!< Shadow map size
  28. static const float SMAP_DM          = 1.0f / SMAP_SIZE;
  29.  
  30. float4 main(PixelIn pin) : SV_Target
  31. {
  32.     float4 colour = ambientColour;
  33.  
  34.     //if position is not visible to the light - dont illuminate it
  35.     //results in hard light frustum
  36.     if (pin.LPos.x < -1.0f || pin.LPos.x > 1.0f ||
  37.         pin.LPos.y < -1.0f || pin.LPos.y > 1.0f ||
  38.         pin.LPos.z < 0.0f || pin.LPos.z > 1.0f)
  39.     {
  40.         return colour;
  41.     }
  42.  
  43.     //transform clip space coords to texture space coords (-1:1 to 0:1)
  44.     pin.LPos.x = pin.LPos.x /  2.0f + 0.5f;
  45.     pin.LPos.y = pin.LPos.y / -2.0f + 0.5f;
  46.  
  47.     float3 L = normalize(lightPos - pin.WPos.xyz);
  48.     float ndotl = dot(normalize(pin.Normal), L);
  49.  
  50.     float shadowFactor = 0.0f;
  51.     if (ndotl > 0.0f)
  52.     {
  53.         //PCF Sampling
  54.         float sum = 0.0f;
  55.  
  56.         const float dm = SMAP_DM;
  57.         const float2 offsets[9] =
  58.         {
  59.             float2(-dm,  -dm), float2(0.0f,  -dm), float2(dm,  -dm),
  60.             float2(-dm, 0.0f), float2(0.0f, 0.0f), float2(dm, 0.0f),
  61.             float2(-dm,  +dm), float2(0.0f,  +dm), float2(dm,  +dm)
  62.         };
  63.  
  64.         [unroll]
  65.         for (int i = 0; i < 9; ++i)
  66.         {
  67.             sum += shadowMap.SampleCmpLevelZero(SCompare, pin.LPos.xy + offsets[i], pin.LPos.z).r;
  68.         }
  69.  
  70.         shadowFactor = sum / 9.0f;
  71.     }
  72.  
  73.     //calculate ilumination
  74.     return colour += shadowFactor * diffuseColour * ndotl;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement