Refractor.js 7.9 KB

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