Refractor.js 8.1 KB

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