bumpFragmentMainFunctions.fx 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
  2. #if defined(TANGENT) && defined(NORMAL)
  3. varying mat3 vTBN;
  4. #endif
  5. #ifdef OBJECTSPACE_NORMALMAP
  6. uniform mat4 normalMatrix;
  7. #endif
  8. vec3 perturbNormal(mat3 cotangentFrame, vec3 textureSample, float scale)
  9. {
  10. textureSample = textureSample * 2.0 - 1.0;
  11. #ifdef NORMALXYSCALE
  12. textureSample = normalize(textureSample * vec3(scale, scale, 1.0));
  13. #endif
  14. return normalize(cotangentFrame * textureSample);
  15. }
  16. // Thanks to http://www.thetenthplanet.de/archives/1180
  17. mat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv, vec2 tangentSpaceParams)
  18. {
  19. // flip the uv for the backface
  20. uv = gl_FrontFacing ? uv : -uv;
  21. // get edge vectors of the pixel triangle
  22. vec3 dp1 = dFdx(p);
  23. vec3 dp2 = dFdy(p);
  24. vec2 duv1 = dFdx(uv);
  25. vec2 duv2 = dFdy(uv);
  26. // solve the linear system
  27. vec3 dp2perp = cross(dp2, normal);
  28. vec3 dp1perp = cross(normal, dp1);
  29. vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;
  30. vec3 bitangent = dp2perp * duv1.y + dp1perp * duv2.y;
  31. // invert the tangent/bitangent if requested
  32. tangent *= tangentSpaceParams.x;
  33. bitangent *= tangentSpaceParams.y;
  34. // construct a scale-invariant frame
  35. float invmax = inversesqrt(max(dot(tangent, tangent), dot(bitangent, bitangent)));
  36. return mat3(tangent * invmax, bitangent * invmax, normal);
  37. }
  38. #endif