Refractor.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. ( function () {
  2. class Refractor extends THREE.Mesh {
  3. constructor( geometry, options = {} ) {
  4. super( geometry );
  5. this.type = 'Refractor';
  6. const scope = this;
  7. const color = options.color !== undefined ? new THREE.Color( options.color ) : new THREE.Color( 0x7F7F7F );
  8. const textureWidth = options.textureWidth || 512;
  9. const textureHeight = options.textureHeight || 512;
  10. const clipBias = options.clipBias || 0;
  11. const shader = options.shader || Refractor.RefractorShader; //
  12. const virtualCamera = new THREE.PerspectiveCamera();
  13. virtualCamera.matrixAutoUpdate = false;
  14. virtualCamera.userData.refractor = true; //
  15. const refractorPlane = new THREE.Plane();
  16. const textureMatrix = new THREE.Matrix4(); // render target
  17. const parameters = {
  18. minFilter: THREE.LinearFilter,
  19. magFilter: THREE.LinearFilter,
  20. format: THREE.RGBFormat
  21. };
  22. const renderTarget = new THREE.WebGLRenderTarget( textureWidth, textureHeight, parameters );
  23. if ( ! THREE.MathUtils.isPowerOfTwo( textureWidth ) || ! THREE.MathUtils.isPowerOfTwo( textureHeight ) ) {
  24. renderTarget.texture.generateMipmaps = false;
  25. } // material
  26. this.material = new THREE.ShaderMaterial( {
  27. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  28. vertexShader: shader.vertexShader,
  29. fragmentShader: shader.fragmentShader,
  30. transparent: true // ensures, refractors are drawn from farthest to closest
  31. } );
  32. this.material.uniforms[ 'color' ].value = color;
  33. this.material.uniforms[ 'tDiffuse' ].value = renderTarget.texture;
  34. this.material.uniforms[ 'textureMatrix' ].value = textureMatrix; // functions
  35. const visible = function () {
  36. const refractorWorldPosition = new THREE.Vector3();
  37. const cameraWorldPosition = new THREE.Vector3();
  38. const rotationMatrix = new THREE.Matrix4();
  39. const view = new THREE.Vector3();
  40. const normal = new THREE.Vector3();
  41. return function visible( camera ) {
  42. refractorWorldPosition.setFromMatrixPosition( scope.matrixWorld );
  43. cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  44. view.subVectors( refractorWorldPosition, cameraWorldPosition );
  45. rotationMatrix.extractRotation( scope.matrixWorld );
  46. normal.set( 0, 0, 1 );
  47. normal.applyMatrix4( rotationMatrix );
  48. return view.dot( normal ) < 0;
  49. };
  50. }();
  51. const updateRefractorPlane = function () {
  52. const normal = new THREE.Vector3();
  53. const position = new THREE.Vector3();
  54. const quaternion = new THREE.Quaternion();
  55. const scale = new THREE.Vector3();
  56. return function updateRefractorPlane() {
  57. scope.matrixWorld.decompose( position, quaternion, scale );
  58. normal.set( 0, 0, 1 ).applyQuaternion( quaternion ).normalize(); // flip the normal because we want to cull everything above the plane
  59. normal.negate();
  60. refractorPlane.setFromNormalAndCoplanarPoint( normal, position );
  61. };
  62. }();
  63. const updateVirtualCamera = function () {
  64. const clipPlane = new THREE.Plane();
  65. const clipVector = new THREE.Vector4();
  66. const q = new THREE.Vector4();
  67. return function updateVirtualCamera( camera ) {
  68. virtualCamera.matrixWorld.copy( camera.matrixWorld );
  69. virtualCamera.matrixWorldInverse.copy( virtualCamera.matrixWorld ).invert();
  70. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  71. virtualCamera.far = camera.far; // used in WebGLBackground
  72. // The following code creates an oblique view frustum for clipping.
  73. // see: Lengyel, Eric. “Oblique View Frustum Depth Projection and Clipping”.
  74. // Journal of Game Development, Vol. 1, No. 2 (2005), Charles River Media, pp. 5–16
  75. clipPlane.copy( refractorPlane );
  76. clipPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  77. clipVector.set( clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.constant ); // calculate the clip-space corner point opposite the clipping plane and
  78. // transform it into camera space by multiplying it by the inverse of the projection matrix
  79. const projectionMatrix = virtualCamera.projectionMatrix;
  80. q.x = ( Math.sign( clipVector.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  81. q.y = ( Math.sign( clipVector.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  82. q.z = - 1.0;
  83. q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ]; // calculate the scaled plane vector
  84. clipVector.multiplyScalar( 2.0 / clipVector.dot( q ) ); // replacing the third row of the projection matrix
  85. projectionMatrix.elements[ 2 ] = clipVector.x;
  86. projectionMatrix.elements[ 6 ] = clipVector.y;
  87. projectionMatrix.elements[ 10 ] = clipVector.z + 1.0 - clipBias;
  88. projectionMatrix.elements[ 14 ] = clipVector.w;
  89. };
  90. }(); // This will update the texture matrix that is used for projective texture mapping in the shader.
  91. // see: http://developer.download.nvidia.com/assets/gamedev/docs/projective_texture_mapping.pdf
  92. function updateTextureMatrix( camera ) {
  93. // this matrix does range mapping to [ 0, 1 ]
  94. textureMatrix.set( 0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0 ); // we use "Object Linear Texgen", so we need to multiply the texture matrix T
  95. // (matrix above) with the projection and view matrix of the virtual camera
  96. // and the model matrix of the refractor
  97. textureMatrix.multiply( camera.projectionMatrix );
  98. textureMatrix.multiply( camera.matrixWorldInverse );
  99. textureMatrix.multiply( scope.matrixWorld );
  100. } //
  101. function render( renderer, scene, camera ) {
  102. scope.visible = false;
  103. const currentRenderTarget = renderer.getRenderTarget();
  104. const currentXrEnabled = renderer.xr.enabled;
  105. const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
  106. renderer.xr.enabled = false; // avoid camera modification
  107. renderer.shadowMap.autoUpdate = false; // avoid re-computing shadows
  108. renderer.setRenderTarget( renderTarget );
  109. if ( renderer.autoClear === false ) renderer.clear();
  110. renderer.render( scene, virtualCamera );
  111. renderer.xr.enabled = currentXrEnabled;
  112. renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
  113. renderer.setRenderTarget( currentRenderTarget ); // restore viewport
  114. const viewport = camera.viewport;
  115. if ( viewport !== undefined ) {
  116. renderer.state.viewport( viewport );
  117. }
  118. scope.visible = true;
  119. } //
  120. this.onBeforeRender = function ( renderer, scene, camera ) {
  121. // Render
  122. renderTarget.texture.encoding = renderer.outputEncoding; // ensure refractors are rendered only once per frame
  123. if ( camera.userData.refractor === true ) return; // avoid rendering when the refractor is viewed from behind
  124. if ( ! visible( camera ) === true ) return; // update
  125. updateRefractorPlane();
  126. updateTextureMatrix( camera );
  127. updateVirtualCamera( camera );
  128. render( renderer, scene, camera );
  129. };
  130. this.getRenderTarget = function () {
  131. return renderTarget;
  132. };
  133. }
  134. }
  135. Refractor.prototype.isRefractor = true;
  136. Refractor.RefractorShader = {
  137. uniforms: {
  138. 'color': {
  139. value: null
  140. },
  141. 'tDiffuse': {
  142. value: null
  143. },
  144. 'textureMatrix': {
  145. value: null
  146. }
  147. },
  148. vertexShader:
  149. /* glsl */
  150. `
  151. uniform mat4 textureMatrix;
  152. varying vec4 vUv;
  153. void main() {
  154. vUv = textureMatrix * vec4( position, 1.0 );
  155. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  156. }`,
  157. fragmentShader:
  158. /* glsl */
  159. `
  160. uniform vec3 color;
  161. uniform sampler2D tDiffuse;
  162. varying vec4 vUv;
  163. float blendOverlay( float base, float blend ) {
  164. return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
  165. }
  166. vec3 blendOverlay( vec3 base, vec3 blend ) {
  167. return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );
  168. }
  169. void main() {
  170. vec4 base = texture2DProj( tDiffuse, vUv );
  171. gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
  172. }`
  173. };
  174. THREE.Refractor = Refractor;
  175. } )();