2
0

Refractor.js 7.8 KB

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