2
0

LightingCommon.bslinc 15 KB

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