ParallaxBarrierEffect.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import {
  2. LinearFilter,
  3. Mesh,
  4. NearestFilter,
  5. OrthographicCamera,
  6. PlaneGeometry,
  7. RGBAFormat,
  8. Scene,
  9. ShaderMaterial,
  10. StereoCamera,
  11. WebGLRenderTarget
  12. } from '../../../build/three.module.js';
  13. class ParallaxBarrierEffect {
  14. constructor( renderer ) {
  15. const _camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  16. const _scene = new Scene();
  17. const _stereo = new StereoCamera();
  18. const _params = { minFilter: LinearFilter, magFilter: NearestFilter, format: RGBAFormat };
  19. const _renderTargetL = new WebGLRenderTarget( 512, 512, _params );
  20. const _renderTargetR = new WebGLRenderTarget( 512, 512, _params );
  21. const _material = new ShaderMaterial( {
  22. uniforms: {
  23. 'mapLeft': { value: _renderTargetL.texture },
  24. 'mapRight': { value: _renderTargetR.texture }
  25. },
  26. vertexShader: [
  27. 'varying vec2 vUv;',
  28. 'void main() {',
  29. ' vUv = vec2( uv.x, uv.y );',
  30. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  31. '}'
  32. ].join( '\n' ),
  33. fragmentShader: [
  34. 'uniform sampler2D mapLeft;',
  35. 'uniform sampler2D mapRight;',
  36. 'varying vec2 vUv;',
  37. 'void main() {',
  38. ' vec2 uv = vUv;',
  39. ' if ( ( mod( gl_FragCoord.y, 2.0 ) ) > 1.00 ) {',
  40. ' gl_FragColor = texture2D( mapLeft, uv );',
  41. ' } else {',
  42. ' gl_FragColor = texture2D( mapRight, uv );',
  43. ' }',
  44. '}'
  45. ].join( '\n' )
  46. } );
  47. const mesh = new Mesh( new PlaneGeometry( 2, 2 ), _material );
  48. _scene.add( mesh );
  49. this.setSize = function ( width, height ) {
  50. renderer.setSize( width, height );
  51. const pixelRatio = renderer.getPixelRatio();
  52. _renderTargetL.setSize( width * pixelRatio, height * pixelRatio );
  53. _renderTargetR.setSize( width * pixelRatio, height * pixelRatio );
  54. };
  55. this.render = function ( scene, camera ) {
  56. scene.updateMatrixWorld();
  57. if ( camera.parent === null ) camera.updateMatrixWorld();
  58. _stereo.update( camera );
  59. renderer.setRenderTarget( _renderTargetL );
  60. renderer.clear();
  61. renderer.render( scene, _stereo.cameraL );
  62. renderer.setRenderTarget( _renderTargetR );
  63. renderer.clear();
  64. renderer.render( scene, _stereo.cameraR );
  65. renderer.setRenderTarget( null );
  66. renderer.render( _scene, _camera );
  67. };
  68. }
  69. }
  70. export { ParallaxBarrierEffect };