FresnelShader.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * Based on Nvidia Cg tutorial
  3. */
  4. const FresnelShader = {
  5. uniforms: {
  6. 'mRefractionRatio': { value: 1.02 },
  7. 'mFresnelBias': { value: 0.1 },
  8. 'mFresnelPower': { value: 2.0 },
  9. 'mFresnelScale': { value: 1.0 },
  10. 'tCube': { value: null }
  11. },
  12. vertexShader: /* glsl */`
  13. uniform float mRefractionRatio;
  14. uniform float mFresnelBias;
  15. uniform float mFresnelScale;
  16. uniform float mFresnelPower;
  17. varying vec3 vReflect;
  18. varying vec3 vRefract[3];
  19. varying float vReflectionFactor;
  20. void main() {
  21. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  22. vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
  23. vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );
  24. vec3 I = worldPosition.xyz - cameraPosition;
  25. vReflect = reflect( I, worldNormal );
  26. vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );
  27. vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );
  28. vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );
  29. vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );
  30. gl_Position = projectionMatrix * mvPosition;
  31. }`,
  32. fragmentShader: /* glsl */`
  33. uniform samplerCube tCube;
  34. varying vec3 vReflect;
  35. varying vec3 vRefract[3];
  36. varying float vReflectionFactor;
  37. void main() {
  38. vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );
  39. vec4 refractedColor = vec4( 1.0 );
  40. refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;
  41. refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;
  42. refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;
  43. gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );
  44. }`
  45. };
  46. export { FresnelShader };