WebGLCubeMaps.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import { CubeReflectionMapping, CubeRefractionMapping, EquirectangularReflectionMapping, EquirectangularRefractionMapping } from '../../constants.js';
  2. import { WebGLCubeRenderTarget } from '../WebGLCubeRenderTarget.js';
  3. function WebGLCubeMaps( renderer ) {
  4. let cubemaps = new WeakMap();
  5. function mapTextureMapping( texture, mapping ) {
  6. if ( mapping === EquirectangularReflectionMapping ) {
  7. texture.mapping = CubeReflectionMapping;
  8. } else if ( mapping === EquirectangularRefractionMapping ) {
  9. texture.mapping = CubeRefractionMapping;
  10. }
  11. return texture;
  12. }
  13. function get( texture ) {
  14. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  15. const mapping = texture.mapping;
  16. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  17. if ( cubemaps.has( texture ) ) {
  18. const cubemap = cubemaps.get( texture ).texture;
  19. return mapTextureMapping( cubemap, texture.mapping );
  20. } else {
  21. const image = texture.image;
  22. if ( image && image.height > 0 ) {
  23. const currentRenderTarget = renderer.getRenderTarget();
  24. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  25. renderTarget.fromEquirectangularTexture( renderer, texture );
  26. cubemaps.set( texture, renderTarget );
  27. renderer.setRenderTarget( currentRenderTarget );
  28. texture.addEventListener( 'dispose', onTextureDispose );
  29. return mapTextureMapping( renderTarget.texture, texture.mapping );
  30. } else {
  31. // image not yet ready. try the conversion next frame
  32. return null;
  33. }
  34. }
  35. }
  36. }
  37. return texture;
  38. }
  39. function onTextureDispose( event ) {
  40. const texture = event.target;
  41. texture.removeEventListener( 'dispose', onTextureDispose );
  42. const cubemap = cubemaps.get( texture );
  43. if ( cubemap !== undefined ) {
  44. cubemaps.delete( texture );
  45. cubemap.dispose();
  46. }
  47. }
  48. function dispose() {
  49. cubemaps = new WeakMap();
  50. }
  51. return {
  52. get: get,
  53. dispose: dispose
  54. };
  55. }
  56. export { WebGLCubeMaps };