KMZLoader.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. ( function () {
  2. class KMZLoader extends THREE.Loader {
  3. constructor( manager ) {
  4. super( manager );
  5. }
  6. load( url, onLoad, onProgress, onError ) {
  7. const scope = this;
  8. const loader = new THREE.FileLoader( scope.manager );
  9. loader.setPath( scope.path );
  10. loader.setResponseType( 'arraybuffer' );
  11. loader.setRequestHeader( scope.requestHeader );
  12. loader.setWithCredentials( scope.withCredentials );
  13. loader.load( url, function ( text ) {
  14. try {
  15. onLoad( scope.parse( text ) );
  16. } catch ( e ) {
  17. if ( onError ) {
  18. onError( e );
  19. } else {
  20. console.error( e );
  21. }
  22. scope.manager.itemError( url );
  23. }
  24. }, onProgress, onError );
  25. }
  26. parse( data ) {
  27. function findFile( url ) {
  28. for ( const path in zip ) {
  29. if ( path.substr( - url.length ) === url ) {
  30. return zip[ path ];
  31. }
  32. }
  33. }
  34. const manager = new THREE.LoadingManager();
  35. manager.setURLModifier( function ( url ) {
  36. const image = findFile( url );
  37. if ( image ) {
  38. console.log( 'Loading', url );
  39. const blob = new Blob( [ image.buffer ], {
  40. type: 'application/octet-stream'
  41. } );
  42. return URL.createObjectURL( blob );
  43. }
  44. return url;
  45. } ); //
  46. const zip = fflate.unzipSync( new Uint8Array( data ) ); // eslint-disable-line no-undef
  47. if ( zip[ 'doc.kml' ] ) {
  48. const xml = new DOMParser().parseFromString( fflate.strFromU8( zip[ 'doc.kml' ] ), 'application/xml' ); // eslint-disable-line no-undef
  49. const model = xml.querySelector( 'Placemark Model Link href' );
  50. if ( model ) {
  51. const loader = new THREE.ColladaLoader( manager );
  52. return loader.parse( fflate.strFromU8( zip[ model.textContent ] ) ); // eslint-disable-line no-undef
  53. }
  54. } else {
  55. console.warn( 'KMZLoader: Missing doc.kml file.' );
  56. for ( const path in zip ) {
  57. const extension = path.split( '.' ).pop().toLowerCase();
  58. if ( extension === 'dae' ) {
  59. const loader = new THREE.ColladaLoader( manager );
  60. return loader.parse( fflate.strFromU8( zip[ path ] ) ); // eslint-disable-line no-undef
  61. }
  62. }
  63. }
  64. console.error( 'KMZLoader: Couldn\'t find .dae file.' );
  65. return {
  66. scene: new THREE.Group()
  67. };
  68. }
  69. }
  70. THREE.KMZLoader = KMZLoader;
  71. } )();