LightingCommon.bslinc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. #include "$ENGINE$\SurfaceData.bslinc"
  2. Technique
  3. : base("LightingCommon")
  4. : inherits("SurfaceData") =
  5. {
  6. Pass =
  7. {
  8. Common =
  9. {
  10. // Arbitrary limit, increase if needed
  11. #define MAX_LIGHTS 512
  12. #define PI 3.1415926
  13. #define HALF_PI 1.5707963
  14. struct LightData
  15. {
  16. float3 position;
  17. float attRadius;
  18. float srcRadius;
  19. float3 direction;
  20. float luminance;
  21. float3 spotAngles;
  22. float attRadiusSqrdInv;
  23. float3 color;
  24. float3 shiftedLightPosition;
  25. };
  26. float3 calcMicrofacetFresnelShlick(float3 F0, float LoH)
  27. {
  28. return F0 + (1.0f - F0) * pow(1.0f - LoH, 5.0f);
  29. }
  30. float calcMicrofacetShadowingSmithGGX(float roughness4, float NoV, float NoL)
  31. {
  32. // Note: It's probably better to use the joint shadowing + masking version of this function
  33. // Note: Original GGX G1 multiplied by NoV & NoL (respectively), so that the microfacet function divisor gets canceled out
  34. // Original formula being (ignoring the factor for masking negative directions):
  35. // G1(v) = 2 / (1 + sqrt(1 + roughness^4 * tan^2(v)))
  36. //
  37. // Using trig identities: tan = sin/cos & sin^2 + cos^2 = 1
  38. // G1(v) = 2 / (1 + sqrt(1 + roughness^4 * (1 - cos^2(v))/cos^2(v)))
  39. //
  40. // Multiply by cos(v) so that we cancel out the (NoL * NoV) factor in the microfacet formula divisor
  41. // G1(v) = 2 * cos(v) / (cos^2(v) + sqrt(cos^2 + roughness^4 - roughness^4 * cos^2(v)))
  42. //
  43. // Actually do the cancellation:
  44. // G1(v) = 2 / (cos^2(v) + sqrt(cos^2 + roughness^4 - roughness^4 * cos^2(v)))
  45. //
  46. // Also cancel out the 2 and the 4:
  47. // G1(v) = 1 / (cos^2(v) + sqrt(cos^2 + roughness^4 - roughness^4 * cos^2(v)))
  48. //
  49. // Final equation being:
  50. // G(v, l) = G1(v) * G1(l)
  51. //
  52. // Where cos(v) is NoV or NoL
  53. float g1V = NoV + sqrt(NoV * (NoV - NoV * roughness4) + roughness4);
  54. float g1L = NoL + sqrt(NoL * (NoL - NoL * roughness4) + roughness4);
  55. return rcp(g1V * g1L);
  56. }
  57. float calcMicrofacetDistGGX(float roughness4, float NoH)
  58. {
  59. float d = (NoH * roughness4 - NoH) * NoH + 1.0f;
  60. return roughness4 / (PI * d * d);
  61. }
  62. float3 calcDiffuseLambert(float3 color)
  63. {
  64. return color * (1.0f / PI);
  65. }
  66. float getSpotAttenuation(float3 toLight, LightData lightData)
  67. {
  68. float output = saturate((dot(toLight, -lightData.direction) - lightData.spotAngles.y) * lightData.spotAngles.z);
  69. return output * output;
  70. }
  71. // Window function to ensure the light contribution fades out to 0 at attenuation radius
  72. float getRadialAttenuation(float distance2, LightData lightData)
  73. {
  74. float radialAttenuation = distance2 * lightData.attRadiusSqrdInv;
  75. radialAttenuation *= radialAttenuation;
  76. radialAttenuation = saturate(1.0f - radialAttenuation);
  77. radialAttenuation *= radialAttenuation;
  78. return radialAttenuation;
  79. }
  80. // Calculates illuminance from a non-area point light
  81. float illuminancePointLight(float distance2, float NoL, LightData lightData)
  82. {
  83. return (lightData.luminance * NoL) / max(distance2, 0.01f*0.01f);
  84. }
  85. // Calculates illuminance scale for a sphere or a disc area light, while also handling the case when
  86. // parts of the area light are below the horizon.
  87. // Input NoL must be unclamped.
  88. // Sphere solid angle = arcsin(r / d)
  89. // Right disc solid angle = atan(r / d)
  90. // - To compensate for oriented discs, multiply by dot(diskNormal, -L)
  91. float illuminanceScaleSphereDiskAreaLight(float unclampedNoL, float sinSolidAngleSqrd)
  92. {
  93. // Handles parts of the area light below the surface horizon
  94. // See https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf for reference
  95. float sinSolidAngle = sqrt(sinSolidAngleSqrd);
  96. if(unclampedNoL < sinSolidAngle)
  97. {
  98. // Hermite spline approximation (see reference for exact formula)
  99. unclampedNoL = max(unclampedNoL, -sinSolidAngle);
  100. return ((sinSolidAngle + unclampedNoL) * (sinSolidAngle + unclampedNoL)) / (4 * sinSolidAngle);
  101. }
  102. else
  103. return PI * sinSolidAngleSqrd * saturate(unclampedNoL);
  104. }
  105. // Calculates illuminance from a sphere area light.
  106. float illuminanceSphereAreaLight(float unclampedNoL, float distToLight2, LightData lightData)
  107. {
  108. float radius2 = lightData.srcRadius * lightData.srcRadius;
  109. // Squared sine of the sphere solid angle
  110. float sinSolidAngle2 = radius2 / distToLight2;
  111. // Prevent divide by zero
  112. sinSolidAngle2 = min(sinSolidAngle2, 0.9999f);
  113. return lightData.luminance * illuminanceScaleSphereDiskAreaLight(unclampedNoL, sinSolidAngle2);
  114. }
  115. // Calculates illuminance from a disc area light.
  116. float illuminanceDiscAreaLight(float unclampedNoL, float distToLight2, float3 L, LightData lightData)
  117. {
  118. // Solid angle for right disk = atan (r / d)
  119. // atan (r / d) = asin((r / d)/sqrt((r / d)^2+1))
  120. // sinAngle = (r / d)/sqrt((r / d)^2 + 1)
  121. // sinAngle^2 = (r / d)^2 / (r / d)^2 + 1
  122. // = r^2 / (d^2 + r^2)
  123. float radius2 = lightData.srcRadius * lightData.srcRadius;
  124. // max() to prevent light penetrating object
  125. float sinSolidAngle2 = saturate(radius2 / (radius2 + max(radius2, distToLight2)));
  126. // Multiply by extra term to somewhat handle the case of the oriented disc (formula above only works
  127. // for right discs).
  128. return lightData.luminance * illuminanceScaleSphereDiskAreaLight(unclampedNoL, sinSolidAngle2 * saturate(dot(lightData.direction, -L)));
  129. }
  130. // With microfacet BRDF the BRDF lobe is not centered around the reflected (mirror) direction.
  131. // Because of NoL and shadow-masking terms the lobe gets shifted toward the normal as roughness
  132. // increases. This is called the "off-specular peak". We approximate it using this function.
  133. float3 getSpecularDominantDir(float3 N, float3 R, float roughness)
  134. {
  135. // Note: Try this formula as well:
  136. // float smoothness = 1 - roughness;
  137. // return lerp(N, R, smoothness * (sqrt(smoothness) + roughness));
  138. float r2 = roughness * roughness;
  139. return normalize(lerp(N, R, (1 - r2) * (sqrt(1 - r2) + r2)));
  140. }
  141. float3 getSurfaceShading(float3 V, float3 L, float specLobeEnergy, SurfaceData surfaceData)
  142. {
  143. float3 N = surfaceData.worldNormal.xyz;
  144. float3 H = normalize(V + L);
  145. float LoH = saturate(dot(L, H));
  146. float NoH = saturate(dot(N, H));
  147. float NoV = saturate(dot(N, V));
  148. float NoL = saturate(dot(N, L));
  149. float3 diffuseColor = lerp(surfaceData.albedo.rgb, float3(0.0f, 0.0f, 0.0f), 1.0f - surfaceData.metalness);
  150. // Note: Using a fixed F0 value of 0.04 (plastic) for dielectrics, and using albedo as specular for conductors.
  151. // For more customizability allow the user to provide separate albedo/specular colors for both types.
  152. float3 specularColor = lerp(float3(0.04f, 0.04f, 0.04f), surfaceData.albedo.rgb, surfaceData.metalness);
  153. float3 diffuse = calcDiffuseLambert(diffuseColor);
  154. float roughness = max(surfaceData.roughness, 0.04f); // Prevent NaNs
  155. float roughness2 = roughness * roughness;
  156. float roughness4 = roughness2 * roughness2;
  157. float3 specular = calcMicrofacetFresnelShlick(specularColor, LoH) *
  158. calcMicrofacetDistGGX(roughness4, NoH) *
  159. calcMicrofacetShadowingSmithGGX(roughness4, NoV, NoL);
  160. // Note: Need to add energy conservation between diffuse and specular terms?
  161. return diffuse + specular * specLobeEnergy;
  162. }
  163. StructuredBuffer<LightData> gLights;
  164. #ifdef USE_COMPUTE_INDICES
  165. groupshared uint gLightIndices[MAX_LIGHTS];
  166. #endif
  167. #ifdef USE_LIGHT_GRID_INDICES
  168. Buffer<uint> gLightIndices;
  169. #endif
  170. float4 getDirectLighting(float3 worldPos, float3 V, float3 R, SurfaceData surfaceData, uint4 lightOffsets)
  171. {
  172. float3 N = surfaceData.worldNormal.xyz;
  173. float roughness2 = max(surfaceData.roughness, 0.08f);
  174. roughness2 *= roughness2;
  175. float3 outLuminance = 0;
  176. float alpha = 0.0f;
  177. if(surfaceData.worldNormal.w > 0.0f)
  178. {
  179. // Handle directional lights
  180. for(uint i = 0; i < lightOffsets.x; ++i)
  181. {
  182. LightData lightData = gLights[i];
  183. float3 L = -lightData.direction;
  184. float NoL = saturate(dot(N, L));
  185. float specEnergy = 1.0f;
  186. // Distant disk area light. Calculate its contribution analytically by
  187. // finding the most important (least error) point on the area light and
  188. // use it as a form of importance sampling.
  189. if(lightData.srcRadius > 0)
  190. {
  191. float diskRadius = sin(lightData.srcRadius);
  192. float distanceToDisk = cos(lightData.srcRadius);
  193. // Closest point to disk (approximation for distant disks)
  194. float DoR = dot(L, R);
  195. float3 S = normalize(R - DoR * L);
  196. L = DoR < distanceToDisk ? normalize(distanceToDisk * L + S * diskRadius) : R;
  197. }
  198. float3 surfaceShading = getSurfaceShading(V, L, specEnergy, surfaceData);
  199. float illuminance = lightData.luminance * NoL;
  200. outLuminance += lightData.color * illuminance * surfaceShading;
  201. }
  202. // Handle radial lights
  203. for (uint i = lightOffsets.y; i < lightOffsets.z; ++i)
  204. {
  205. uint lightIdx = gLightIndices[i];
  206. LightData lightData = gLights[lightIdx];
  207. float3 toLight = lightData.position - worldPos;
  208. float distToLightSqrd = dot(toLight, toLight);
  209. float invDistToLight = rsqrt(distToLightSqrd);
  210. float3 L = toLight * invDistToLight;
  211. float NoL = dot(N, L);
  212. float specEnergy = 1.0f;
  213. float illuminance = 0.0f;
  214. // Sphere area light. Calculate its contribution analytically by
  215. // finding the most important (least error) point on the area light and
  216. // use it as a form of importance sampling.
  217. if(lightData.srcRadius > 0)
  218. {
  219. // Calculate illuminance depending on source size, distance and angle
  220. illuminance = illuminanceSphereAreaLight(NoL, distToLightSqrd, lightData);
  221. // Energy conservation:
  222. // We are widening the specular distribution by the sphere's subtended angle,
  223. // so we need to handle the increase in energy. It is not enough just to account
  224. // for the sphere solid angle, since the energy difference is highly dependent on
  225. // specular distribution. By accounting for this energy difference we ensure glossy
  226. // reflections have sharp edges, instead of being too blurry.
  227. // See http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf for reference
  228. float sphereAngle = saturate(lightData.srcRadius * invDistToLight);
  229. specEnergy = roughness2 / saturate(roughness2 + 0.5f * sphereAngle);
  230. specEnergy *= specEnergy;
  231. // Find closest point on sphere to ray
  232. float3 closestPointOnRay = dot(toLight, R) * R;
  233. float3 centerToRay = closestPointOnRay - toLight;
  234. float invDistToRay = rsqrt(dot(centerToRay, centerToRay));
  235. float3 closestPointOnSphere = toLight + centerToRay * saturate(lightData.srcRadius * invDistToRay);
  236. toLight = closestPointOnSphere;
  237. L = normalize(toLight);
  238. }
  239. else
  240. {
  241. NoL = saturate(NoL);
  242. illuminance = illuminancePointLight(distToLightSqrd, NoL, lightData);
  243. }
  244. float attenuation = getRadialAttenuation(distToLightSqrd, lightData);
  245. float3 surfaceShading = getSurfaceShading(V, L, specEnergy, surfaceData);
  246. outLuminance += lightData.color * illuminance * attenuation * surfaceShading;
  247. }
  248. // Handle spot lights
  249. for(uint i = lightOffsets.z; i < lightOffsets.w; ++i)
  250. {
  251. uint lightIdx = gLightIndices[i];
  252. LightData lightData = gLights[lightIdx];
  253. float3 toLight = lightData.position - worldPos;
  254. float distToLightSqrd = dot(toLight, toLight);
  255. float invDistToLight = rsqrt(distToLightSqrd);
  256. float3 L = toLight * invDistToLight;
  257. float NoL = dot(N, L);
  258. float specEnergy = 1.0f;
  259. float illuminance = 0.0f;
  260. float spotAttenuation = 1.0f;
  261. // Disc area light. Calculate its contribution analytically by
  262. // finding the most important (least error) point on the area light and
  263. // use it as a form of importance sampling.
  264. if(lightData.srcRadius > 0)
  265. {
  266. // Calculate illuminance depending on source size, distance and angle
  267. illuminance = illuminanceDiscAreaLight(NoL, distToLightSqrd, L, lightData);
  268. // Energy conservation: Similar case as with radial lights
  269. float rightDiscAngle = saturate(lightData.srcRadius * invDistToLight);
  270. // Account for disc orientation somewhat
  271. float discAngle = rightDiscAngle * saturate(dot(lightData.direction, -L));
  272. specEnergy = roughness2 / saturate(roughness2 + 0.5f * discAngle);
  273. specEnergy *= specEnergy;
  274. // Find closest point on disc to ray
  275. float3 discNormal = -lightData.direction;
  276. float distAlongLightDir = max(dot(R, discNormal), 1e-6f);
  277. float t = dot(toLight, discNormal) / distAlongLightDir;
  278. float3 closestPointOnPlane = R * t; // Relative to shaded world point
  279. float3 centerToRay = closestPointOnPlane - toLight;
  280. float invDistToRay = rsqrt(dot(centerToRay, centerToRay));
  281. float3 closestPointOnDisc = toLight + centerToRay * saturate(lightData.srcRadius * invDistToRay);
  282. toLight = closestPointOnDisc;
  283. L = normalize(toLight);
  284. // Expand spot attenuation by disc radius (not physically based)
  285. float3 toSpotEdge = normalize(lightData.shiftedLightPosition - worldPos);
  286. spotAttenuation = getSpotAttenuation(toSpotEdge, lightData);
  287. // TODO - Spot attenuation fades out the specular highlight in a noticeable way
  288. }
  289. else
  290. {
  291. NoL = saturate(NoL);
  292. illuminance = illuminancePointLight(distToLightSqrd, NoL, lightData);
  293. spotAttenuation = getSpotAttenuation(L, lightData);
  294. }
  295. float radialAttenuation = getRadialAttenuation(distToLightSqrd, lightData);
  296. float attenuation = spotAttenuation * radialAttenuation;
  297. float3 surfaceShading = getSurfaceShading(V, L, specEnergy, surfaceData);
  298. outLuminance += lightData.color * illuminance * attenuation * surfaceShading;
  299. }
  300. // Ambient term for in-editor visualization, not used in actual lighting
  301. outLuminance += surfaceData.albedo.rgb * gAmbientFactor / PI;
  302. alpha = 1.0f;
  303. }
  304. return float4(outLuminance, alpha);
  305. }
  306. };
  307. };
  308. };