FresnelShader.js 2.0 KB

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