2
0

Refractor.js 7.9 KB

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