Source.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. import { ImageUtils } from '../extras/ImageUtils.js';
  2. import * as MathUtils from '../math/MathUtils.js';
  3. let _sourceId = 0;
  4. class Source {
  5. constructor( data = null ) {
  6. this.isSource = true;
  7. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  8. this.uuid = MathUtils.generateUUID();
  9. this.data = data;
  10. this.version = 0;
  11. }
  12. set needsUpdate( value ) {
  13. if ( value === true ) this.version ++;
  14. }
  15. toJSON( meta ) {
  16. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  17. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  18. return meta.images[ this.uuid ];
  19. }
  20. const output = {
  21. uuid: this.uuid,
  22. url: ''
  23. };
  24. const data = this.data;
  25. if ( data !== null ) {
  26. let url;
  27. if ( Array.isArray( data ) ) {
  28. // cube texture
  29. url = [];
  30. for ( let i = 0, l = data.length; i < l; i ++ ) {
  31. if ( data[ i ].isDataTexture ) {
  32. url.push( serializeImage( data[ i ].image ) );
  33. } else {
  34. url.push( serializeImage( data[ i ] ) );
  35. }
  36. }
  37. } else {
  38. // texture
  39. url = serializeImage( data );
  40. }
  41. output.url = url;
  42. }
  43. if ( ! isRootObject ) {
  44. meta.images[ this.uuid ] = output;
  45. }
  46. return output;
  47. }
  48. }
  49. function serializeImage( image ) {
  50. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  51. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  52. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  53. // default images
  54. return ImageUtils.getDataURL( image );
  55. } else {
  56. if ( image.data ) {
  57. // images of DataTexture
  58. return {
  59. data: Array.from( image.data ),
  60. width: image.width,
  61. height: image.height,
  62. type: image.data.constructor.name
  63. };
  64. } else {
  65. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  66. return {};
  67. }
  68. }
  69. }
  70. export { Source };