Refractor.js 8.2 KB

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