LightFunctions.glsl 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. // Copyright (C) 2009-2020, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. // Contains functions for light calculations
  6. #pragma once
  7. #include <shaders/Functions.glsl>
  8. #include <shaders/Pack.glsl>
  9. #include <shaders/glsl_cpp_common/ClusteredShading.h>
  10. #include <shaders/glsl_cpp_common/Evsm.h>
  11. // Do some EVSM magic with depth
  12. Vec2 evsmProcessDepth(F32 depth)
  13. {
  14. depth = 2.0 * depth - 1.0;
  15. const F32 pos = exp(EVSM_POSITIVE_CONSTANT * depth);
  16. const F32 neg = -exp(EVSM_NEGATIVE_CONSTANT * depth);
  17. return Vec2(pos, neg);
  18. }
  19. F32 linstep(F32 a, F32 b, F32 v)
  20. {
  21. return saturate((v - a) / (b - a));
  22. }
  23. // Reduces VSM light bleedning
  24. F32 reduceLightBleeding(F32 pMax, F32 amount)
  25. {
  26. // Remove the [0, amount] tail and linearly rescale (amount, 1].
  27. return linstep(amount, 1.0, pMax);
  28. }
  29. F32 chebyshevUpperBound(Vec2 moments, F32 mean, F32 minVariance, F32 lightBleedingReduction)
  30. {
  31. // Compute variance
  32. F32 variance = moments.y - (moments.x * moments.x);
  33. variance = max(variance, minVariance);
  34. // Compute probabilistic upper bound
  35. const F32 d = mean - moments.x;
  36. F32 pMax = variance / (variance + (d * d));
  37. pMax = reduceLightBleeding(pMax, lightBleedingReduction);
  38. // One-tailed Chebyshev
  39. return (mean <= moments.x) ? 1.0 : pMax;
  40. }
  41. // Compute the shadow factor of EVSM given the 2 depths
  42. F32 evsmComputeShadowFactor(F32 occluderDepth, Vec4 shadowMapMoments)
  43. {
  44. const Vec2 evsmOccluderDepths = evsmProcessDepth(occluderDepth);
  45. const Vec2 depthScale =
  46. EVSM_BIAS * 0.01 * Vec2(EVSM_POSITIVE_CONSTANT, EVSM_NEGATIVE_CONSTANT) * evsmOccluderDepths;
  47. const Vec2 minVariance = depthScale * depthScale;
  48. #if !ANKI_EVSM4
  49. return chebyshevUpperBound(shadowMapMoments.xy, evsmOccluderDepths.x, minVariance.x, EVSM_LIGHT_BLEEDING_REDUCTION);
  50. #else
  51. const F32 pos =
  52. chebyshevUpperBound(shadowMapMoments.xy, evsmOccluderDepths.x, minVariance.x, EVSM_LIGHT_BLEEDING_REDUCTION);
  53. const F32 neg =
  54. chebyshevUpperBound(shadowMapMoments.zw, evsmOccluderDepths.y, minVariance.y, EVSM_LIGHT_BLEEDING_REDUCTION);
  55. return min(pos, neg);
  56. #endif
  57. }
  58. // Fresnel term unreal
  59. // specular: The specular color aka F0
  60. Vec3 F_Unreal(Vec3 specular, F32 VoH)
  61. {
  62. return specular + (1.0 - specular) * pow(2.0, (-5.55473 * VoH - 6.98316) * VoH);
  63. }
  64. // Fresnel Schlick: "An Inexpensive BRDF Model for Physically-Based Rendering"
  65. // It has lower VGRPs than F_Unreal
  66. // specular: The specular color aka F0
  67. Vec3 F_Schlick(Vec3 specular, F32 VoH)
  68. {
  69. const F32 a = 1.0 - VoH;
  70. const F32 a2 = a * a;
  71. const F32 a5 = a2 * a2 * a; // a5 = a^5
  72. return /*saturate(50.0 * specular.g) */ a5 + (1.0 - a5) * specular;
  73. }
  74. // D(n,h) aka NDF: GGX Trowbridge-Reitz
  75. F32 D_GGX(F32 roughness, F32 NoH)
  76. {
  77. const F32 a = roughness * roughness;
  78. const F32 a2 = a * a;
  79. const F32 D = (NoH * a2 - NoH) * NoH + 1.0;
  80. return a2 / (PI * D * D);
  81. }
  82. // Visibility term: Geometric shadowing divided by BRDF denominator
  83. F32 V_Schlick(F32 roughness, F32 NoV, F32 NoL)
  84. {
  85. const F32 k = (roughness * roughness) * 0.5;
  86. const F32 Vis_SchlickV = NoV * (1.0 - k) + k;
  87. const F32 Vis_SchlickL = NoL * (1.0 - k) + k;
  88. return 0.25 / (Vis_SchlickV * Vis_SchlickL);
  89. }
  90. Vec3 envBRDF(Vec3 specular, F32 roughness, texture2D integrationLut, sampler integrationLutSampler, F32 NoV)
  91. {
  92. const Vec2 envBRDF = textureLod(integrationLut, integrationLutSampler, Vec2(roughness, NoV), 0.0).xy;
  93. return specular * envBRDF.x + min(1.0, 50.0 * specular.g) * envBRDF.y;
  94. }
  95. Vec3 diffuseLambert(Vec3 diffuse)
  96. {
  97. return diffuse * (1.0 / PI);
  98. }
  99. // Performs BRDF specular lighting
  100. Vec3 computeSpecularColorBrdf(GbufferInfo gbuffer, Vec3 viewDir, Vec3 frag2Light)
  101. {
  102. const Vec3 H = normalize(frag2Light + viewDir);
  103. const F32 NoL = max(EPSILON, dot(gbuffer.m_normal, frag2Light));
  104. const F32 VoH = max(EPSILON, dot(viewDir, H));
  105. const F32 NoH = max(EPSILON, dot(gbuffer.m_normal, H));
  106. const F32 NoV = max(EPSILON, dot(gbuffer.m_normal, viewDir));
  107. // F
  108. #if 0
  109. const Vec3 F = F_Unreal(gbuffer.m_specular, VoH);
  110. #else
  111. const Vec3 F = F_Schlick(gbuffer.m_specular, VoH);
  112. #endif
  113. // D
  114. const F32 D = D_GGX(gbuffer.m_roughness, NoH);
  115. // Vis
  116. const F32 V = V_Schlick(gbuffer.m_roughness, NoV, NoL);
  117. return F * (V * D);
  118. }
  119. F32 computeSpotFactor(Vec3 l, F32 outerCos, F32 innerCos, Vec3 spotDir)
  120. {
  121. const F32 costheta = -dot(l, spotDir);
  122. const F32 spotFactor = smoothstep(outerCos, innerCos, costheta);
  123. return spotFactor;
  124. }
  125. U32 computeShadowSampleCount(const U32 COUNT, F32 zVSpace)
  126. {
  127. const F32 MAX_DISTANCE = 5.0;
  128. const F32 z = max(zVSpace, -MAX_DISTANCE);
  129. F32 sampleCountf = F32(COUNT) + z * (F32(COUNT) / MAX_DISTANCE);
  130. sampleCountf = max(sampleCountf, 1.0);
  131. const U32 sampleCount = U32(sampleCountf);
  132. return sampleCount;
  133. }
  134. F32 computeShadowFactorSpotLight(SpotLight light, Vec3 worldPos, texture2D spotMap, sampler spotMapSampler)
  135. {
  136. const Vec4 texCoords4 = light.m_texProjectionMat * Vec4(worldPos, 1.0);
  137. const Vec3 texCoords3 = texCoords4.xyz / texCoords4.w;
  138. const Vec4 shadowMoments = textureLod(spotMap, spotMapSampler, texCoords3.xy, 0.0);
  139. return evsmComputeShadowFactor(texCoords3.z, shadowMoments);
  140. }
  141. // Compute the shadow factor of point (omni) lights.
  142. F32 computeShadowFactorPointLight(PointLight light, Vec3 frag2Light, texture2D shadowMap, sampler shadowMapSampler)
  143. {
  144. const Vec3 dir = -frag2Light;
  145. const Vec3 dirabs = abs(dir);
  146. const F32 dist = max(dirabs.x, max(dirabs.y, dirabs.z));
  147. // 1) Project the dist to light's proj mat
  148. //
  149. const F32 near = LIGHT_FRUSTUM_NEAR_PLANE;
  150. const F32 far = light.m_radius;
  151. const F32 g = near - far;
  152. const F32 zVSpace = -dist;
  153. const F32 w = -zVSpace;
  154. F32 z = (far * zVSpace + far * near) / g;
  155. z /= w;
  156. // 2) Read shadow tex
  157. //
  158. // Convert cube coords
  159. U32 faceIdxu;
  160. Vec2 uv = convertCubeUvsu(dir, faceIdxu);
  161. // Get the atlas offset
  162. Vec2 atlasOffset;
  163. atlasOffset.x = light.m_shadowAtlasTileOffsets[faceIdxu >> 1u][(faceIdxu & 1u) << 1u];
  164. atlasOffset.y = light.m_shadowAtlasTileOffsets[faceIdxu >> 1u][((faceIdxu & 1u) << 1u) + 1u];
  165. // Compute UV
  166. uv = fma(uv, Vec2(light.m_shadowAtlasTileScale), atlasOffset);
  167. // Sample
  168. const Vec4 shadowMoments = textureLod(shadowMap, shadowMapSampler, uv, 0.0);
  169. // 3) Compare
  170. //
  171. const F32 shadowFactor = evsmComputeShadowFactor(z, shadowMoments);
  172. return shadowFactor;
  173. }
  174. // Compute the shadow factor of a directional light
  175. F32 computeShadowFactorDirLight(DirectionalLight light, U32 cascadeIdx, Vec3 worldPos, texture2D shadowMap,
  176. sampler shadowMapSampler)
  177. {
  178. #define ANKI_FAST_CASCADES_WORKAROUND 1 // Doesn't make sense but it's super fast
  179. #if ANKI_FAST_CASCADES_WORKAROUND
  180. // Assumes MAX_SHADOW_CASCADES is 4
  181. Mat4 lightProjectionMat;
  182. switch(cascadeIdx)
  183. {
  184. case 0:
  185. lightProjectionMat = light.m_textureMatrices[0];
  186. break;
  187. case 1:
  188. lightProjectionMat = light.m_textureMatrices[1];
  189. break;
  190. case 2:
  191. lightProjectionMat = light.m_textureMatrices[2];
  192. break;
  193. default:
  194. lightProjectionMat = light.m_textureMatrices[3];
  195. }
  196. #else
  197. const Mat4 lightProjectionMat = light.m_textureMatrices[cascadeIdx];
  198. #endif
  199. const Vec4 texCoords4 = lightProjectionMat * Vec4(worldPos, 1.0);
  200. const Vec3 texCoords3 = texCoords4.xyz / texCoords4.w;
  201. const Vec4 shadowMoments = textureLod(shadowMap, shadowMapSampler, texCoords3.xy, 0.0);
  202. return evsmComputeShadowFactor(texCoords3.z, shadowMoments);
  203. }
  204. // Compute the shadow factor of a directional light
  205. F32 computeShadowFactorDirLight(Mat4 lightProjectionMat, Vec3 worldPos, texture2D shadowMap,
  206. samplerShadow shadowMapSampler)
  207. {
  208. const Vec4 texCoords4 = lightProjectionMat * Vec4(worldPos, 1.0);
  209. const Vec3 texCoords3 = texCoords4.xyz / texCoords4.w;
  210. const F32 shadowFactor = textureLod(shadowMap, shadowMapSampler, texCoords3, 0.0);
  211. return shadowFactor;
  212. }
  213. // Compute the cubemap texture lookup vector given the reflection vector (r) the radius squared of the probe (R2) and
  214. // the frag pos in sphere space (f)
  215. Vec3 computeCubemapVecAccurate(Vec3 r, F32 R2, Vec3 f)
  216. {
  217. // Compute the collision of the r to the inner part of the sphere
  218. // From now on we work on the sphere's space
  219. // Project the center of the sphere (it's zero now since we are in sphere space) in ray "f,r"
  220. const Vec3 p = f - r * dot(f, r);
  221. // The collision to the sphere is point x where x = p + T * r
  222. // Because of the pythagorean theorem: R^2 = dot(p, p) + dot(T * r, T * r)
  223. // solving for T, T = R / |p|
  224. // then x becomes x = sqrt(R^2 - dot(p, p)) * r + p;
  225. F32 pp = dot(p, p);
  226. pp = min(pp, R2);
  227. const F32 sq = sqrt(R2 - pp);
  228. const Vec3 x = p + sq * r;
  229. return x;
  230. }
  231. // Cheap version of computeCubemapVecAccurate
  232. Vec3 computeCubemapVecCheap(Vec3 r, F32 R2, Vec3 f)
  233. {
  234. return r;
  235. }
  236. F32 computeAttenuationFactor(F32 squareRadiusOverOne, Vec3 frag2Light)
  237. {
  238. const F32 fragLightDist = dot(frag2Light, frag2Light);
  239. F32 att = 1.0 - fragLightDist * squareRadiusOverOne;
  240. att = max(0.0, att);
  241. return att * att;
  242. }
  243. // Given the probe properties trace a ray inside the probe and find the cube tex coordinates to sample
  244. Vec3 intersectProbe(Vec3 fragPos, // Ray origin
  245. Vec3 rayDir, // Ray direction
  246. Vec3 probeAabbMin, Vec3 probeAabbMax,
  247. Vec3 probeOrigin // Cubemap origin
  248. )
  249. {
  250. // Compute the intersection point
  251. const F32 intresectionDist = rayAabbIntersectionInside(fragPos, rayDir, probeAabbMin, probeAabbMax);
  252. const Vec3 intersectionPoint = fragPos + intresectionDist * rayDir;
  253. // Compute the cubemap vector
  254. return intersectionPoint - probeOrigin;
  255. }
  256. // Compute a weight (factor) of fragPos against some probe's bounds. The weight will be zero when fragPos is close to
  257. // AABB bounds and 1.0 at fadeDistance and less.
  258. F32 computeProbeBlendWeight(Vec3 fragPos, // Doesn't need to be inside the AABB
  259. Vec3 probeAabbMin, Vec3 probeAabbMax, F32 fadeDistance)
  260. {
  261. // Compute the min distance of fragPos from the edges of the AABB
  262. const Vec3 distFromMin = fragPos - probeAabbMin;
  263. const Vec3 distFromMax = probeAabbMax - fragPos;
  264. const Vec3 minDistVec = min(distFromMin, distFromMax);
  265. const F32 minDist = min(minDistVec.x, min(minDistVec.y, minDistVec.z));
  266. // Use saturate because minDist might be negative.
  267. return saturate(minDist / fadeDistance);
  268. }
  269. // Given the value of the 6 faces of the dice and a normal, sample the correct weighted value.
  270. // https://www.shadertoy.com/view/XtcBDB
  271. Vec3 sampleAmbientDice(Vec3 posx, Vec3 negx, Vec3 posy, Vec3 negy, Vec3 posz, Vec3 negz, Vec3 normal)
  272. {
  273. const Vec3 axisWeights = abs(normal);
  274. const Vec3 uv = NDC_TO_UV(normal);
  275. Vec3 col = mix(negx, posx, uv.x) * axisWeights.x;
  276. col += mix(negy, posy, uv.y) * axisWeights.y;
  277. col += mix(negz, posz, uv.z) * axisWeights.z;
  278. // Divide by weight
  279. col /= axisWeights.x + axisWeights.y + axisWeights.z + EPSILON;
  280. return col;
  281. }
  282. // Sample the irradiance term from the clipmap
  283. Vec3 sampleGlobalIllumination(const Vec3 worldPos, const Vec3 normal, const GlobalIlluminationProbe probe,
  284. texture3D textures[MAX_VISIBLE_GLOBAL_ILLUMINATION_PROBES], sampler linearAnyClampSampler)
  285. {
  286. // Find the UVW
  287. Vec3 uvw = (worldPos - probe.m_aabbMin) / (probe.m_aabbMax - probe.m_aabbMin);
  288. // The U contains the 6 directions so divide
  289. uvw.x /= 6.0;
  290. // Calmp it to avoid direction leaking
  291. uvw.x = clamp(uvw.x, probe.m_halfTexelSizeU, (1.0 / 6.0) - probe.m_halfTexelSizeU);
  292. // Read the irradiance
  293. Vec3 irradiancePerDir[6u];
  294. ANKI_UNROLL for(U32 dir = 0u; dir < 6u; ++dir)
  295. {
  296. // Point to the correct UV
  297. Vec3 shiftedUVw = uvw;
  298. shiftedUVw.x += (1.0 / 6.0) * F32(dir);
  299. irradiancePerDir[dir] =
  300. textureLod(textures[nonuniformEXT(probe.m_textureIndex)], linearAnyClampSampler, shiftedUVw, 0.0).rgb;
  301. }
  302. // Sample the irradiance
  303. const Vec3 irradiance = sampleAmbientDice(irradiancePerDir[0], irradiancePerDir[1], irradiancePerDir[2],
  304. irradiancePerDir[3], irradiancePerDir[4], irradiancePerDir[5], normal);
  305. return irradiance;
  306. }