Refractor.js 8.2 KB

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