Refractor.js 8.0 KB

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