LightingCommon.bslinc 14 KB

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