Refractor.js 8.1 KB

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