Refractor.js 7.9 KB

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