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