Refractor.js 8.0 KB

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