1
0

Refractor.js 8.0 KB

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