BrdfLutGeneratorFS.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //This file is automatically rebuilt by the Cesium build process.
  2. export default "varying vec2 v_textureCoordinates;\n\
  3. const float M_PI = 3.141592653589793;\n\
  4. float vdcRadicalInverse(int i)\n\
  5. {\n\
  6. float r;\n\
  7. float base = 2.0;\n\
  8. float value = 0.0;\n\
  9. float invBase = 1.0 / base;\n\
  10. float invBi = invBase;\n\
  11. for (int x = 0; x < 100; x++)\n\
  12. {\n\
  13. if (i <= 0)\n\
  14. {\n\
  15. break;\n\
  16. }\n\
  17. r = mod(float(i), base);\n\
  18. value += r * invBi;\n\
  19. invBi *= invBase;\n\
  20. i = int(float(i) * invBase);\n\
  21. }\n\
  22. return value;\n\
  23. }\n\
  24. vec2 hammersley2D(int i, int N)\n\
  25. {\n\
  26. return vec2(float(i) / float(N), vdcRadicalInverse(i));\n\
  27. }\n\
  28. vec3 importanceSampleGGX(vec2 xi, float roughness, vec3 N)\n\
  29. {\n\
  30. float a = roughness * roughness;\n\
  31. float phi = 2.0 * M_PI * xi.x;\n\
  32. float cosTheta = sqrt((1.0 - xi.y) / (1.0 + (a * a - 1.0) * xi.y));\n\
  33. float sinTheta = sqrt(1.0 - cosTheta * cosTheta);\n\
  34. vec3 H = vec3(sinTheta * cos(phi), sinTheta * sin(phi), cosTheta);\n\
  35. vec3 upVector = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);\n\
  36. vec3 tangentX = normalize(cross(upVector, N));\n\
  37. vec3 tangentY = cross(N, tangentX);\n\
  38. return tangentX * H.x + tangentY * H.y + N * H.z;\n\
  39. }\n\
  40. float G1_Smith(float NdotV, float k)\n\
  41. {\n\
  42. return NdotV / (NdotV * (1.0 - k) + k);\n\
  43. }\n\
  44. float G_Smith(float roughness, float NdotV, float NdotL)\n\
  45. {\n\
  46. float k = roughness * roughness / 2.0;\n\
  47. return G1_Smith(NdotV, k) * G1_Smith(NdotL, k);\n\
  48. }\n\
  49. vec2 integrateBrdf(float roughness, float NdotV)\n\
  50. {\n\
  51. vec3 V = vec3(sqrt(1.0 - NdotV * NdotV), 0.0, NdotV);\n\
  52. float A = 0.0;\n\
  53. float B = 0.0;\n\
  54. const int NumSamples = 1024;\n\
  55. for (int i = 0; i < NumSamples; i++)\n\
  56. {\n\
  57. vec2 xi = hammersley2D(i, NumSamples);\n\
  58. vec3 H = importanceSampleGGX(xi, roughness, vec3(0.0, 0.0, 1.0));\n\
  59. vec3 L = 2.0 * dot(V, H) * H - V;\n\
  60. float NdotL = clamp(L.z, 0.0, 1.0);\n\
  61. float NdotH = clamp(H.z, 0.0, 1.0);\n\
  62. float VdotH = clamp(dot(V, H), 0.0, 1.0);\n\
  63. if (NdotL > 0.0)\n\
  64. {\n\
  65. float G = G_Smith(roughness, NdotV, NdotL);\n\
  66. float G_Vis = G * VdotH / (NdotH * NdotV);\n\
  67. float Fc = pow(1.0 - VdotH, 5.0);\n\
  68. A += (1.0 - Fc) * G_Vis;\n\
  69. B += Fc * G_Vis;\n\
  70. }\n\
  71. }\n\
  72. return vec2(A, B) / float(NumSamples);\n\
  73. }\n\
  74. void main()\n\
  75. {\n\
  76. gl_FragColor = vec4(integrateBrdf(v_textureCoordinates.y, v_textureCoordinates.x), 0.0, 1.0);\n\
  77. }\n\
  78. ";