Reflector.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. import {
  2. Color,
  3. Matrix4,
  4. Mesh,
  5. PerspectiveCamera,
  6. Plane,
  7. ShaderMaterial,
  8. UniformsUtils,
  9. Vector3,
  10. Vector4,
  11. WebGLRenderTarget,
  12. HalfFloatType
  13. } from 'three';
  14. /**
  15. * Can be used to create a flat, reflective surface like a mirror.
  16. *
  17. * Note that this class can only be used with {@link WebGLRenderer}.
  18. * When using {@link WebGPURenderer}, use {@link ReflectorNode}.
  19. *
  20. * ```js
  21. * const geometry = new THREE.PlaneGeometry( 100, 100 );
  22. *
  23. * const reflector = new Reflector( geometry, {
  24. * clipBias: 0.003,
  25. * textureWidth: window.innerWidth * window.devicePixelRatio,
  26. * textureHeight: window.innerHeight * window.devicePixelRatio,
  27. * color: 0xc1cbcb
  28. * } );
  29. *
  30. * scene.add( reflector );
  31. * ```
  32. *
  33. * @augments Mesh
  34. * @three_import import { Reflector } from 'three/addons/objects/Reflector.js';
  35. */
  36. class Reflector extends Mesh {
  37. /**
  38. * Constructs a new reflector.
  39. *
  40. * @param {BufferGeometry} geometry - The reflector's geometry.
  41. * @param {Reflector~Options} [options] - The configuration options.
  42. */
  43. constructor( geometry, options = {} ) {
  44. super( geometry );
  45. /**
  46. * This flag can be used for type testing.
  47. *
  48. * @type {boolean}
  49. * @readonly
  50. * @default true
  51. */
  52. this.isReflector = true;
  53. this.type = 'Reflector';
  54. /**
  55. * Whether to force an update, no matter if the reflector
  56. * is in view or not.
  57. *
  58. * @type {boolean}
  59. * @default false
  60. */
  61. this.forceUpdate = false;
  62. /**
  63. * The reflector's virtual camera. This is used to render
  64. * the scene from the mirror's point of view.
  65. *
  66. * @type {PerspectiveCamera}
  67. */
  68. this.camera = new PerspectiveCamera();
  69. const scope = this;
  70. const color = ( options.color !== undefined ) ? new Color( options.color ) : new Color( 0x7F7F7F );
  71. const textureWidth = options.textureWidth || 512;
  72. const textureHeight = options.textureHeight || 512;
  73. const clipBias = options.clipBias || 0;
  74. const shader = options.shader || Reflector.ReflectorShader;
  75. const multisample = ( options.multisample !== undefined ) ? options.multisample : 4;
  76. //
  77. const reflectorPlane = new Plane();
  78. const normal = new Vector3();
  79. const reflectorWorldPosition = new Vector3();
  80. const cameraWorldPosition = new Vector3();
  81. const rotationMatrix = new Matrix4();
  82. const lookAtPosition = new Vector3( 0, 0, - 1 );
  83. const clipPlane = new Vector4();
  84. const view = new Vector3();
  85. const target = new Vector3();
  86. const q = new Vector4();
  87. const textureMatrix = new Matrix4();
  88. const virtualCamera = this.camera;
  89. const renderTarget = new WebGLRenderTarget( textureWidth, textureHeight, { samples: multisample, type: HalfFloatType } );
  90. const material = new ShaderMaterial( {
  91. name: ( shader.name !== undefined ) ? shader.name : 'unspecified',
  92. uniforms: UniformsUtils.clone( shader.uniforms ),
  93. fragmentShader: shader.fragmentShader,
  94. vertexShader: shader.vertexShader
  95. } );
  96. material.uniforms[ 'tDiffuse' ].value = renderTarget.texture;
  97. material.uniforms[ 'color' ].value = color;
  98. material.uniforms[ 'textureMatrix' ].value = textureMatrix;
  99. this.material = material;
  100. this.onBeforeRender = function ( renderer, scene, camera ) {
  101. reflectorWorldPosition.setFromMatrixPosition( scope.matrixWorld );
  102. cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  103. rotationMatrix.extractRotation( scope.matrixWorld );
  104. normal.set( 0, 0, 1 );
  105. normal.applyMatrix4( rotationMatrix );
  106. view.subVectors( reflectorWorldPosition, cameraWorldPosition );
  107. // Avoid rendering when reflector is facing away unless forcing an update
  108. const isFacingAway = view.dot( normal ) > 0;
  109. if ( isFacingAway === true && this.forceUpdate === false ) return;
  110. view.reflect( normal ).negate();
  111. view.add( reflectorWorldPosition );
  112. rotationMatrix.extractRotation( camera.matrixWorld );
  113. lookAtPosition.set( 0, 0, - 1 );
  114. lookAtPosition.applyMatrix4( rotationMatrix );
  115. lookAtPosition.add( cameraWorldPosition );
  116. target.subVectors( reflectorWorldPosition, lookAtPosition );
  117. target.reflect( normal ).negate();
  118. target.add( reflectorWorldPosition );
  119. virtualCamera.position.copy( view );
  120. virtualCamera.up.set( 0, 1, 0 );
  121. virtualCamera.up.applyMatrix4( rotationMatrix );
  122. virtualCamera.up.reflect( normal );
  123. virtualCamera.lookAt( target );
  124. virtualCamera.far = camera.far; // Used in WebGLBackground
  125. virtualCamera.updateMatrixWorld();
  126. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  127. // Update the texture matrix
  128. textureMatrix.set(
  129. 0.5, 0.0, 0.0, 0.5,
  130. 0.0, 0.5, 0.0, 0.5,
  131. 0.0, 0.0, 0.5, 0.5,
  132. 0.0, 0.0, 0.0, 1.0
  133. );
  134. textureMatrix.multiply( virtualCamera.projectionMatrix );
  135. textureMatrix.multiply( virtualCamera.matrixWorldInverse );
  136. textureMatrix.multiply( scope.matrixWorld );
  137. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  138. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  139. reflectorPlane.setFromNormalAndCoplanarPoint( normal, reflectorWorldPosition );
  140. reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  141. clipPlane.set( reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant );
  142. const projectionMatrix = virtualCamera.projectionMatrix;
  143. q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  144. q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  145. q.z = - 1.0;
  146. q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  147. // Calculate the scaled plane vector
  148. clipPlane.multiplyScalar( 2.0 / clipPlane.dot( q ) );
  149. // Replacing the third row of the projection matrix
  150. projectionMatrix.elements[ 2 ] = clipPlane.x;
  151. projectionMatrix.elements[ 6 ] = clipPlane.y;
  152. projectionMatrix.elements[ 10 ] = clipPlane.z + 1.0 - clipBias;
  153. projectionMatrix.elements[ 14 ] = clipPlane.w;
  154. // Render
  155. scope.visible = false;
  156. const currentRenderTarget = renderer.getRenderTarget();
  157. const currentXrEnabled = renderer.xr.enabled;
  158. const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
  159. renderer.xr.enabled = false; // Avoid camera modification
  160. renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows
  161. renderer.setRenderTarget( renderTarget );
  162. renderer.state.buffers.depth.setMask( true ); // make sure the depth buffer is writable so it can be properly cleared, see #18897
  163. if ( renderer.autoClear === false ) renderer.clear();
  164. renderer.render( scene, virtualCamera );
  165. renderer.xr.enabled = currentXrEnabled;
  166. renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
  167. renderer.setRenderTarget( currentRenderTarget );
  168. // Restore viewport
  169. const viewport = camera.viewport;
  170. if ( viewport !== undefined ) {
  171. renderer.state.viewport( viewport );
  172. }
  173. scope.visible = true;
  174. this.forceUpdate = false;
  175. };
  176. /**
  177. * Returns the reflector's internal render target.
  178. *
  179. * @return {WebGLRenderTarget} The internal render target
  180. */
  181. this.getRenderTarget = function () {
  182. return renderTarget;
  183. };
  184. /**
  185. * Frees the GPU-related resources allocated by this instance. Call this
  186. * method whenever this instance is no longer used in your app.
  187. */
  188. this.dispose = function () {
  189. renderTarget.dispose();
  190. scope.material.dispose();
  191. };
  192. }
  193. }
  194. Reflector.ReflectorShader = {
  195. name: 'ReflectorShader',
  196. uniforms: {
  197. 'color': {
  198. value: null
  199. },
  200. 'tDiffuse': {
  201. value: null
  202. },
  203. 'textureMatrix': {
  204. value: null
  205. }
  206. },
  207. vertexShader: /* glsl */`
  208. uniform mat4 textureMatrix;
  209. varying vec4 vUv;
  210. #include <common>
  211. #include <logdepthbuf_pars_vertex>
  212. void main() {
  213. vUv = textureMatrix * vec4( position, 1.0 );
  214. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  215. #include <logdepthbuf_vertex>
  216. }`,
  217. fragmentShader: /* glsl */`
  218. uniform vec3 color;
  219. uniform sampler2D tDiffuse;
  220. varying vec4 vUv;
  221. #include <logdepthbuf_pars_fragment>
  222. float blendOverlay( float base, float blend ) {
  223. return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
  224. }
  225. vec3 blendOverlay( vec3 base, vec3 blend ) {
  226. return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );
  227. }
  228. void main() {
  229. #include <logdepthbuf_fragment>
  230. vec4 base = texture2DProj( tDiffuse, vUv );
  231. gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
  232. #include <tonemapping_fragment>
  233. #include <colorspace_fragment>
  234. }`
  235. };
  236. /**
  237. * Constructor options of `Reflector`.
  238. *
  239. * @typedef {Object} Reflector~Options
  240. * @property {number|Color|string} [color=0x7F7F7F] - The reflector's color.
  241. * @property {number} [textureWidth=512] - The texture width. A higher value results in more clear reflections but is also more expensive.
  242. * @property {number} [textureHeight=512] - The texture height. A higher value results in more clear reflections but is also more expensive.
  243. * @property {number} [clipBias=0] - The clip bias.
  244. * @property {Object} [shader] - Can be used to pass in a custom shader that defines how the reflective view is projected onto the reflector's geometry.
  245. * @property {number} [multisample=4] - How many samples to use for MSAA. `0` disables MSAA.
  246. **/
  247. export { Reflector };