WebGLCubeMaps.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 ) {
  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 renderTarget = new WebGLCubeRenderTarget( image.height );
  24. renderTarget.fromEquirectangularTexture( renderer, texture );
  25. cubemaps.set( texture, renderTarget );
  26. texture.addEventListener( 'dispose', onTextureDispose );
  27. return mapTextureMapping( renderTarget.texture, texture.mapping );
  28. } else {
  29. // image not yet ready. try the conversion next frame
  30. return null;
  31. }
  32. }
  33. }
  34. }
  35. return texture;
  36. }
  37. function onTextureDispose( event ) {
  38. const texture = event.target;
  39. texture.removeEventListener( 'dispose', onTextureDispose );
  40. const cubemap = cubemaps.get( texture );
  41. if ( cubemap !== undefined ) {
  42. cubemaps.delete( texture );
  43. cubemap.dispose();
  44. }
  45. }
  46. function dispose() {
  47. cubemaps = new WeakMap();
  48. }
  49. return {
  50. get: get,
  51. dispose: dispose
  52. };
  53. }
  54. export { WebGLCubeMaps };