MaskPass.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import { Pass } from './Pass.js';
  2. class MaskPass extends Pass {
  3. constructor( scene, camera ) {
  4. super();
  5. this.scene = scene;
  6. this.camera = camera;
  7. this.clear = true;
  8. this.needsSwap = false;
  9. this.inverse = false;
  10. }
  11. render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
  12. const context = renderer.getContext();
  13. const state = renderer.state;
  14. // don't update color or depth
  15. state.buffers.color.setMask( false );
  16. state.buffers.depth.setMask( false );
  17. // lock buffers
  18. state.buffers.color.setLocked( true );
  19. state.buffers.depth.setLocked( true );
  20. // set up stencil
  21. let writeValue, clearValue;
  22. if ( this.inverse ) {
  23. writeValue = 0;
  24. clearValue = 1;
  25. } else {
  26. writeValue = 1;
  27. clearValue = 0;
  28. }
  29. state.buffers.stencil.setTest( true );
  30. state.buffers.stencil.setOp( context.REPLACE, context.REPLACE, context.REPLACE );
  31. state.buffers.stencil.setFunc( context.ALWAYS, writeValue, 0xffffffff );
  32. state.buffers.stencil.setClear( clearValue );
  33. state.buffers.stencil.setLocked( true );
  34. // draw into the stencil buffer
  35. renderer.setRenderTarget( readBuffer );
  36. if ( this.clear ) renderer.clear();
  37. renderer.render( this.scene, this.camera );
  38. renderer.setRenderTarget( writeBuffer );
  39. if ( this.clear ) renderer.clear();
  40. renderer.render( this.scene, this.camera );
  41. // unlock color and depth buffer for subsequent rendering
  42. state.buffers.color.setLocked( false );
  43. state.buffers.depth.setLocked( false );
  44. // only render where stencil is set to 1
  45. state.buffers.stencil.setLocked( false );
  46. state.buffers.stencil.setFunc( context.EQUAL, 1, 0xffffffff ); // draw if == 1
  47. state.buffers.stencil.setOp( context.KEEP, context.KEEP, context.KEEP );
  48. state.buffers.stencil.setLocked( true );
  49. }
  50. }
  51. class ClearMaskPass extends Pass {
  52. constructor() {
  53. super();
  54. this.needsSwap = false;
  55. }
  56. render( renderer /*, writeBuffer, readBuffer, deltaTime, maskActive */ ) {
  57. renderer.state.buffers.stencil.setLocked( false );
  58. renderer.state.buffers.stencil.setTest( false );
  59. }
  60. }
  61. export { MaskPass, ClearMaskPass };