Refractor.js 7.7 KB

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