physical_fragment.glsl 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. //
  2. // Physically Based Shading of a microfacet surface material - Fragment Shader
  3. // Modified from reference implementation at https://github.com/KhronosGroup/glTF-WebGL-PBR
  4. //
  5. // References:
  6. // [1] Real Shading in Unreal Engine 4
  7. // http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  8. // [2] Physically Based Shading at Disney
  9. // http://blog.selfshadow.com/publications/s2012-shading-course/burley/s2012_pbs_disney_brdf_notes_v3.pdf
  10. // [3] README.md - Environment Maps
  11. // https://github.com/KhronosGroup/glTF-WebGL-PBR/#environment-maps
  12. // [4] "An Inexpensive BRDF Model for Physically based Rendering" by Christophe Schlick
  13. // https://www.cs.virginia.edu/~jdl/bib/appearance/analytic%20models/schlick94b.pdf
  14. //#extension GL_EXT_shader_texture_lod: enable
  15. //#extension GL_OES_standard_derivatives : enable
  16. precision highp float;
  17. //uniform vec3 u_LightDirection;
  18. //uniform vec3 u_LightColor;
  19. //#ifdef USE_IBL
  20. //uniform samplerCube u_DiffuseEnvSampler;
  21. //uniform samplerCube u_SpecularEnvSampler;
  22. //uniform sampler2D u_brdfLUT;
  23. //#endif
  24. #ifdef HAS_BASECOLORMAP
  25. uniform sampler2D u_BaseColorSampler;
  26. #endif
  27. #ifdef HAS_NORMALMAP
  28. uniform sampler2D u_NormalSampler;
  29. uniform float u_NormalScale;
  30. #endif
  31. #ifdef HAS_EMISSIVEMAP
  32. uniform sampler2D u_EmissiveSampler;
  33. uniform vec3 u_EmissiveFactor;
  34. #endif
  35. #ifdef HAS_METALROUGHNESSMAP
  36. uniform sampler2D u_MetallicRoughnessSampler;
  37. #endif
  38. #ifdef HAS_OCCLUSIONMAP
  39. uniform sampler2D u_OcclusionSampler;
  40. uniform float u_OcclusionStrength;
  41. #endif
  42. // Material parameters uniform array
  43. uniform vec4 Material[3];
  44. // Macros to access elements inside the Material array
  45. #define uBaseColor Material[0]
  46. #define uEmissiveColor Material[1]
  47. #define uMetallicFactor Material[2].x
  48. #define uRoughnessFactor Material[2].y
  49. #include <lights>
  50. // Inputs from vertex shader
  51. in vec3 Position; // Vertex position in camera coordinates.
  52. in vec3 Normal; // Vertex normal in camera coordinates.
  53. in vec3 CamDir; // Direction from vertex to camera
  54. in vec2 FragTexcoord;
  55. // Final fragment color
  56. out vec4 FragColor;
  57. // Encapsulate the various inputs used by the various functions in the shading equation
  58. // We store values in this struct to simplify the integration of alternative implementations
  59. // of the shading terms, outlined in the Readme.MD Appendix.
  60. struct PBRInfo
  61. {
  62. float NdotL; // cos angle between normal and light direction
  63. float NdotV; // cos angle between normal and view direction
  64. float NdotH; // cos angle between normal and half vector
  65. float LdotH; // cos angle between light direction and half vector
  66. float VdotH; // cos angle between view direction and half vector
  67. float perceptualRoughness; // roughness value, as authored by the model creator (input to shader)
  68. float metalness; // metallic value at the surface
  69. vec3 reflectance0; // full reflectance color (normal incidence angle)
  70. vec3 reflectance90; // reflectance color at grazing angle
  71. float alphaRoughness; // roughness mapped to a more linear change in the roughness (proposed by [2])
  72. vec3 diffuseColor; // color contribution from diffuse lighting
  73. vec3 specularColor; // color contribution from specular lighting
  74. };
  75. const float M_PI = 3.141592653589793;
  76. const float c_MinRoughness = 0.04;
  77. vec4 SRGBtoLINEAR(vec4 srgbIn) {
  78. //#ifdef MANUAL_SRGB
  79. // #ifdef SRGB_FAST_APPROXIMATION
  80. // vec3 linOut = pow(srgbIn.xyz,vec3(2.2));
  81. // #else //SRGB_FAST_APPROXIMATION
  82. // vec3 bLess = step(vec3(0.04045),srgbIn.xyz);
  83. // vec3 linOut = mix( srgbIn.xyz/vec3(12.92), pow((srgbIn.xyz+vec3(0.055))/vec3(1.055),vec3(2.4)), bLess );
  84. // #endif //SRGB_FAST_APPROXIMATION
  85. // return vec4(linOut,srgbIn.w);
  86. //#else //MANUAL_SRGB
  87. return srgbIn;
  88. //#endif //MANUAL_SRGB
  89. }
  90. // Find the normal for this fragment, pulling either from a predefined normal map
  91. // or from the interpolated mesh normal and tangent attributes.
  92. vec3 getNormal()
  93. {
  94. // Retrieve the tangent space matrix
  95. //#ifndef HAS_TANGENTS
  96. vec3 pos_dx = dFdx(Position);
  97. vec3 pos_dy = dFdy(Position);
  98. vec3 tex_dx = dFdx(vec3(FragTexcoord, 0.0));
  99. vec3 tex_dy = dFdy(vec3(FragTexcoord, 0.0));
  100. vec3 t = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t);
  101. #ifdef HAS_NORMALS
  102. vec3 ng = normalize(Normal);
  103. #else
  104. vec3 ng = cross(pos_dx, pos_dy);
  105. #endif
  106. t = normalize(t - ng * dot(ng, t));
  107. vec3 b = normalize(cross(ng, t));
  108. mat3 tbn = mat3(t, b, ng);
  109. //#else // HAS_TANGENTS
  110. // mat3 tbn = v_TBN;
  111. //#endif
  112. #ifdef HAS_NORMALMAP
  113. vec3 n = texture2D(uNormalSampler, FragTexcoord).rgb;
  114. n = normalize(tbn * ((2.0 * n - 1.0) * vec3(uNormalScale, uNormalScale, 1.0)));
  115. #else
  116. // The tbn matrix is linearly interpolated, so we need to re-normalize
  117. vec3 n = normalize(tbn[2].xyz);
  118. #endif
  119. return n;
  120. }
  121. //// Calculation of the lighting contribution from an optional Image Based Light source.
  122. //// Precomputed Environment Maps are required uniform inputs and are computed as outlined in [1].
  123. //// See our README.md on Environment Maps [3] for additional discussion.
  124. //vec3 getIBLContribution(PBRInfo pbrInputs, vec3 n, vec3 reflection)
  125. //{
  126. // float mipCount = 9.0; // resolution of 512x512
  127. // float lod = (pbrInputs.perceptualRoughness * mipCount);
  128. // // retrieve a scale and bias to F0. See [1], Figure 3
  129. // vec3 brdf = SRGBtoLINEAR(texture2D(u_brdfLUT, vec2(pbrInputs.NdotV, 1.0 - pbrInputs.perceptualRoughness))).rgb;
  130. // vec3 diffuseLight = SRGBtoLINEAR(textureCube(u_DiffuseEnvSampler, n)).rgb;
  131. //
  132. ////#ifdef USE_TEX_LOD
  133. //// vec3 specularLight = SRGBtoLINEAR(textureCubeLodEXT(u_SpecularEnvSampler, reflection, lod)).rgb;
  134. ////#else
  135. // vec3 specularLight = SRGBtoLINEAR(textureCube(u_SpecularEnvSampler, reflection)).rgb;
  136. ////#endif
  137. //
  138. // vec3 diffuse = diffuseLight * pbrInputs.diffuseColor;
  139. // vec3 specular = specularLight * (pbrInputs.specularColor * brdf.x + brdf.y);
  140. //
  141. // // For presentation, this allows us to disable IBL terms
  142. // diffuse *= u_ScaleIBLAmbient.x;
  143. // specular *= u_ScaleIBLAmbient.y;
  144. //
  145. // return diffuse + specular;
  146. //}
  147. // Basic Lambertian diffuse
  148. // Implementation from Lambert's Photometria https://archive.org/details/lambertsphotome00lambgoog
  149. // See also [1], Equation 1
  150. vec3 diffuse(PBRInfo pbrInputs)
  151. {
  152. return pbrInputs.diffuseColor / M_PI;
  153. }
  154. // The following equation models the Fresnel reflectance term of the spec equation (aka F())
  155. // Implementation of fresnel from [4], Equation 15
  156. vec3 specularReflection(PBRInfo pbrInputs)
  157. {
  158. return pbrInputs.reflectance0 + (pbrInputs.reflectance90 - pbrInputs.reflectance0) * pow(clamp(1.0 - pbrInputs.VdotH, 0.0, 1.0), 5.0);
  159. }
  160. // This calculates the specular geometric attenuation (aka G()),
  161. // where rougher material will reflect less light back to the viewer.
  162. // This implementation is based on [1] Equation 4, and we adopt their modifications to
  163. // alphaRoughness as input as originally proposed in [2].
  164. float geometricOcclusion(PBRInfo pbrInputs)
  165. {
  166. float NdotL = pbrInputs.NdotL;
  167. float NdotV = pbrInputs.NdotV;
  168. float r = pbrInputs.alphaRoughness;
  169. float attenuationL = 2.0 * NdotL / (NdotL + sqrt(r * r + (1.0 - r * r) * (NdotL * NdotL)));
  170. float attenuationV = 2.0 * NdotV / (NdotV + sqrt(r * r + (1.0 - r * r) * (NdotV * NdotV)));
  171. return attenuationL * attenuationV;
  172. }
  173. // The following equation(s) model the distribution of microfacet normals across the area being drawn (aka D())
  174. // Implementation from "Average Irregularity Representation of a Roughened Surface for Ray Reflection" by T. S. Trowbridge, and K. P. Reitz
  175. // Follows the distribution function recommended in the SIGGRAPH 2013 course notes from EPIC Games [1], Equation 3.
  176. float microfacetDistribution(PBRInfo pbrInputs)
  177. {
  178. float roughnessSq = pbrInputs.alphaRoughness * pbrInputs.alphaRoughness;
  179. float f = (pbrInputs.NdotH * roughnessSq - pbrInputs.NdotH) * pbrInputs.NdotH + 1.0;
  180. return roughnessSq / (M_PI * f * f);
  181. }
  182. void main() {
  183. float perceptualRoughness = uRoughnessFactor;
  184. float metallic = uMetallicFactor;
  185. #ifdef HAS_METALROUGHNESSMAP
  186. // Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel.
  187. // This layout intentionally reserves the 'r' channel for (optional) occlusion map data
  188. vec4 mrSample = texture2D(uMetallicRoughnessSampler, FragTexcoord);
  189. perceptualRoughness = mrSample.g * perceptualRoughness;
  190. metallic = mrSample.b * metallic;
  191. #endif
  192. perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0);
  193. metallic = clamp(metallic, 0.0, 1.0);
  194. // Roughness is authored as perceptual roughness; as is convention,
  195. // convert to material roughness by squaring the perceptual roughness [2].
  196. float alphaRoughness = perceptualRoughness * perceptualRoughness;
  197. // The albedo may be defined from a base texture or a flat color
  198. #ifdef HAS_BASECOLORMAP
  199. vec4 baseColor = SRGBtoLINEAR(texture2D(uBaseColorSampler, FragTexcoord)) * uBaseColor;
  200. #else
  201. vec4 baseColor = uBaseColor;
  202. #endif
  203. vec3 f0 = vec3(0.04);
  204. vec3 diffuseColor = baseColor.rgb * (vec3(1.0) - f0);
  205. diffuseColor *= 1.0 - metallic;
  206. vec3 specularColor = mix(f0, baseColor.rgb, uMetallicFactor);
  207. // Compute reflectance.
  208. float reflectance = max(max(specularColor.r, specularColor.g), specularColor.b);
  209. // For typical incident reflectance range (between 4% to 100%) set the grazing reflectance to 100% for typical fresnel effect.
  210. // For very low reflectance range on highly diffuse objects (below 4%), incrementally reduce grazing reflecance to 0%.
  211. float reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0);
  212. vec3 specularEnvironmentR0 = specularColor.rgb;
  213. vec3 specularEnvironmentR90 = vec3(1.0, 1.0, 1.0) * reflectance90;
  214. // TODO These are not currently uniforms - and need to support all kinds of lights!
  215. vec3 u_LightColor = vec3(1,1,1);
  216. vec3 u_LightDirection = vec3(1,0,0);
  217. vec3 n = getNormal(); // normal at surface point
  218. vec3 v = normalize(CamDir); // Vector from surface point to camera
  219. vec3 l = normalize(u_LightDirection); // Vector from surface point to light
  220. vec3 h = normalize(l+v); // Half vector between both l and v
  221. vec3 reflection = -normalize(reflect(v, n));
  222. float NdotL = clamp(dot(n, l), 0.001, 1.0);
  223. float NdotV = abs(dot(n, v)) + 0.001;
  224. float NdotH = clamp(dot(n, h), 0.0, 1.0);
  225. float LdotH = clamp(dot(l, h), 0.0, 1.0);
  226. float VdotH = clamp(dot(v, h), 0.0, 1.0);
  227. PBRInfo pbrInputs = PBRInfo(
  228. NdotL,
  229. NdotV,
  230. NdotH,
  231. LdotH,
  232. VdotH,
  233. perceptualRoughness,
  234. metallic,
  235. specularEnvironmentR0,
  236. specularEnvironmentR90,
  237. alphaRoughness,
  238. diffuseColor,
  239. specularColor
  240. );
  241. // Calculate the shading terms for the microfacet specular shading model
  242. vec3 F = specularReflection(pbrInputs);
  243. float G = geometricOcclusion(pbrInputs);
  244. float D = microfacetDistribution(pbrInputs);
  245. // Calculation of analytical lighting contribution
  246. vec3 diffuseContrib = (1.0 - F) * diffuse(pbrInputs);
  247. vec3 specContrib = F * G * D / (4.0 * NdotL * NdotV);
  248. // Obtain final intensity as reflectance (BRDF) scaled by the energy of the light (cosine law)
  249. vec3 color = NdotL * u_LightColor * (diffuseContrib + specContrib);
  250. // Calculate lighting contribution from image based lighting source (IBL)
  251. //#ifdef USE_IBL
  252. // color += getIBLContribution(pbrInputs, n, reflection);
  253. //#endif
  254. // Apply optional PBR terms for additional (optional) shading
  255. #ifdef HAS_OCCLUSIONMAP
  256. float ao = texture2D(uOcclusionSampler, v_UV).r;
  257. color = mix(color, color * ao, u_OcclusionStrength);
  258. #endif
  259. #ifdef HAS_EMISSIVEMAP
  260. vec3 emissive = SRGBtoLINEAR(texture2D(u_EmissiveSampler, v_UV)).rgb * u_EmissiveFactor;
  261. color += emissive;
  262. #endif
  263. // Final fragment color
  264. FragColor = vec4(pow(color,vec3(1.0/2.2)), baseColor.a);
  265. }