Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@loaders.gl/gltf

Package Overview
Dependencies
Maintainers
9
Versions
342
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@loaders.gl/gltf - npm Package Compare versions

Comparing version 1.3.0-beta.1 to 1.3.0-beta.2

dist/es5/lib/extensions/extensions.js

2

dist/dist.min.js

@@ -1,1 +0,1 @@

!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var s=t();for(var r in s)("object"==typeof exports?exports:e)[r]=s[r]}}(window,function(){return function(e){var t={};function s(r){if(t[r])return t[r].exports;var n=t[r]={i:r,l:!1,exports:{}};return e[r].call(n.exports,n,n.exports,s),n.l=!0,n.exports}return s.m=e,s.c=t,s.d=function(e,t,r){s.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.t=function(e,t){if(1&t&&(e=s(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(s.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)s.d(r,n,function(t){return e[t]}.bind(null,n));return r},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,"a",t),t},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="",s(s.s=12)}([function(e,t,s){"use strict";(function(e,r){s.d(t,"b",function(){return n}),s.d(t,"a",function(){return o}),s.d(t,"c",function(){return a});const n="object"!=typeof e||"[object process]"!==String(e)||e.browser,i={self:"undefined"!=typeof self&&self,window:"undefined"!=typeof window&&window,global:void 0!==r&&r,document:"undefined"!=typeof document&&document},o=i.global||i.self||i.window,u=void 0!==e&&e.version&&e.version.match(/v([0-9]*)/),a=u&&parseFloat(u[1])||0}).call(this,s(13),s(9))},,,,function(e,t){},,,,,function(e,t){var s;s=function(){return this}();try{s=s||new Function("return this")()}catch(e){"object"==typeof window&&(s=window)}e.exports=s},,,function(e,t,s){(function(t){const r=s(14),n="undefined"==typeof window?t:window;n.loaders=n.loaders||{},e.exports=Object.assign(n.loaders,r)}).call(this,s(9))},function(e,t){var s,r,n=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function u(e){if(s===setTimeout)return setTimeout(e,0);if((s===i||!s)&&setTimeout)return s=setTimeout,setTimeout(e,0);try{return s(e,0)}catch(t){try{return s.call(null,e,0)}catch(t){return s.call(this,e,0)}}}!function(){try{s="function"==typeof setTimeout?setTimeout:i}catch(e){s=i}try{r="function"==typeof clearTimeout?clearTimeout:o}catch(e){r=o}}();var a,f=[],c=!1,h=-1;function l(){c&&a&&(c=!1,a.length?f=a.concat(f):h=-1,f.length&&g())}function g(){if(!c){var e=u(l);c=!0;for(var t=f.length;t;){for(a=f,f=[];++h<t;)a&&a[h].run();h=-1,t=f.length}a=null,c=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===o||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function d(e,t){this.fun=e,this.array=t}function m(){}n.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var s=1;s<arguments.length;s++)t[s-1]=arguments[s];f.push(new d(e,t)),1!==f.length||c||u(g)},d.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.browser=!0,n.env={},n.argv=[],n.version="",n.versions={},n.on=m,n.addListener=m,n.once=m,n.off=m,n.removeListener=m,n.removeAllListeners=m,n.emit=m,n.prependListener=m,n.prependOnceListener=m,n.listeners=function(e){return[]},n.binding=function(e){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(e){throw new Error("process.chdir is not supported")},n.umask=function(){return 0}},function(e,t,s){"use strict";s.r(t);var r={};s.r(r),s.d(r,"KHR_draco_mesh_compression",function(){return H}),s.d(r,"KHR_lights_punctual",function(){return K});const n="KHR_draco_mesh_compression",i="UBER_draco_point_cloud_compression",o="KHR_lights_punctual";const u=e=>(e=>"undefined"!=typeof File&&e instanceof File)(e)||(e=>"undefined"!=typeof Blob&&e instanceof Blob)(e);let a="";const f={};function c(e){for(const t in f)if(e.startsWith(t)){const s=f[t];return e.replace(t,s)}return e+=a}function h(e,t){if(!e)throw new Error(t||"loader assertion failed.")}class l{constructor(e){this._fileOrBlob=e,this.bodyUsed=!1}get headers(){return new Headers({"Content-Length":this._fileOrBlob.size,"Content-Type":this._fileOrBlob.type})}get ok(){return!0}get status(){return 200}url(){return this._fileOrBlob.name||""}async arrayBuffer(){const{reader:e,promise:t}=this._getFileReader();return e.readAsArrayBuffer(this._fileOrBlob),t}async text(){const{reader:e,promise:t}=this._getFileReader();return e.readAsText(this._fileOrBlob),t}async json(){const e=await this.text();return JSON.parse(e)}_getFileReader(){let e;h(!this.bodyUsed),this.bodyUsed=!0;const t=new Promise((t,s)=>{try{(e=new FileReader).onerror=e=>s(new Error(e)),e.onabort=()=>s(new Error("Read aborted.")),e.onload=()=>t(e.result)}catch(e){s(e)}});return{reader:e,promise:t}}}function g(e,t){return Promise.resolve(new l(e,t))}async function d(e,t){return u(e)?g(e,t):(e=c(e),fetch(e,t))}function m(e,t){if(!e)throw new Error(t||"gltf/glb assertion failed.")}const p=["SCALAR","VEC2","VEC3","VEC4"],y=new Map([[Int8Array,5120],[Uint8Array,5121],[Int16Array,5122],[Uint16Array,5123],[Uint32Array,5125],[Float32Array,5126]]),b={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},w={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},x={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};function _(e){return p[e-1]||p[0]}function T(e){const t=y.get(e.constructor);if(!t)throw new Error("Illegal typed array");return t}function A(e,t){const s=x[e.componentType],r=b[e.type],n=w[e.componentType],i=e.count*r,o=e.count*r*n;return m(o>=0&&o<=t.byteLength),{ArrayType:s,length:i,byteLength:o}}function E(e,t){return e.startsWith("data:")||e.startsWith("http:")||e.startsWith("https:")?e:t.substr(0,t.lastIndexOf("/")+1)+e}function j(e,t){if(!e)throw new Error(t||"loader assertion failed.")}function v(e){return e+3&-4}function B(e,t,s){let r;if(e instanceof ArrayBuffer)r=new Uint8Array(e);else{const t=e.byteOffset,s=e.byteLength;r=new Uint8Array(e.buffer,t,s)}return t.set(r,s),s+v(r.byteLength)}const R=1735152710,L=12,U=8,V=1313821514,S=5130562,O=!0,M=!1;function P(e,t=0,s={}){const r=new DataView(e),{magic:n=R}=s,i=r.getUint32(t,!1);return i===n||i===R}function I(e,t,s=0,r={}){const n=new DataView(t);e.byteOffset=s,e.magic=n.getUint32(s+0,M),e.version=n.getUint32(s+4,O),e.byteLength=n.getUint32(s+8,O),e.type=function(e){return`${String.fromCharCode(e.getUint8(0))}${String.fromCharCode(e.getUint8(1))}${String.fromCharCode(e.getUint8(2))}${String.fromCharCode(e.getUint8(3))}`}(n);const{magic:i=R}=r;e.magic===R||e.magic===i||console.warn(`Invalid GLB magic string ${e.type}`),j(2===e.version,`Invalid GLB version ${e.version}. Only .glb v2 supported`),j(e.byteLength>20);const o=n.getUint32(s+12,O),u=n.getUint32(s+16,O);j(u===V||0===u,`JSON chunk format ${u}`);const a=L+U,f=new Uint8Array(t,s+a,o),c=new TextDecoder("utf8").decode(f);e.json=JSON.parse(c);const h=a+v(o);if(e.hasBinChunk=h+8<=e.byteLength,e.hasBinChunk){const t=n.getUint32(s+h+0,O),r=n.getUint32(s+h+4,O);j(r===S||1===r,`BIN chunk format ${r}`);const i=h+U;e.binChunkByteOffset=i,e.binChunkLength=t}return s+e.byteLength}const k=!1,C=!0,F=new Map([["image/png",{test:function(e){return e.byteLength>=24&&2303741511===e.getUint32(0,k)},getSize:function(e){return{width:e.getUint32(16,k),height:e.getUint32(20,k)}}}],["image/jpeg",{test:function(e){return e.byteLength>=3&&65496===e.getUint16(0,k)&&255===e.getUint8(2,k)},getSize:function(e){if(e.byteLength<2||65496!==e.getUint16(0,k))return null;const{tableMarkers:t,sofMarkers:s}=function(){const e=new Set([65499,65476,65484,65501,65534]);for(let t=65504;t<65520;++t)e.add(t);const t=new Set([65472,65473,65474,65475,65477,65478,65479,65481,65482,65483,65485,65486,65487,65502]);return{tableMarkers:e,sofMarkers:t}}();let r=2;for(;r<e.byteLength;){const n=e.getUint16(r,k);if(s.has(n))return{height:e.getUint16(r+5,k),width:e.getUint16(r+7,k)};if(!t.has(n))return null;r+=2,r+=e.getUint16(r,k)}return null}}],["image/gif",{test:function(e){return e.byteLength>=10&&1195984440===e.getUint32(0,k)},getSize:function(e){return{width:e.getUint16(6,C),height:e.getUint16(8,C)}}}],["image/bmp",{test:function(e){return e.byteLength>=2&&16973===e.getUint16(0,k)},getSize:function(e){return{width:e.getUint32(18,C),height:e.getUint32(22,C)}}}]]);const D=`Invalid MIME type. Supported MIME types are: ${Array.from(F.keys()).join(", ")}`;function $(e){const t=q(e);for(const[e,{test:s}]of F.entries())if(s(t))return e;return null}function N(e,t=null){const s=function(e,t=null){t=t||$(e);const{getSize:s}=G(t),r=s(q(e));if(!r)throw new Error(`invalid image data for type: ${t}`);return r}(e,t=t||$(e));return s.mimeType=t,s}function G(e){const t=F.get(e);if(!t)throw new Error(D);return t}function q(e){if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return new DataView(e.buffer||e);throw new Error("toDataView")}class W{constructor(e){if(e instanceof W)return e;e||(e={json:{version:2,buffers:[]},binary:null}),this.gltf=e}get json(){return this.gltf.json}getApplicationData(e){return this.json[e]}getExtraData(e){return(this.json.extras||{})[e]}getExtension(e){const t=this.getUsedExtensions().find(t=>t===e),s=this.json.extensions||{};return t?s[e]||!0:null}getRequiredExtension(e){return this.getRequiredExtensions().find(t=>t===e)?this.getExtension(e):null}getRequiredExtensions(){return this.json.extensionsRequired||[]}getUsedExtensions(){return this.json.extensionsUsed||[]}getObjectExtension(e,t){return(e.extensions||{})[t]}getScene(e){return this.getObject("scenes",e)}getNode(e){return this.getObject("nodes",e)}getSkin(e){return this.getObject("skins",e)}getMesh(e){return this.getObject("meshes",e)}getMaterial(e){return this.getObject("materials",e)}getAccessor(e){return this.getObject("accessors",e)}getCamera(e){return null}getTexture(e){return this.getObject("textures",e)}getSampler(e){return this.getObject("samplers",e)}getImage(e){return this.getObject("images",e)}getBufferView(e){return this.getObject("bufferViews",e)}getBuffer(e){return this.getObject("buffers",e)}getObject(e,t){if("object"==typeof t)return t;const s=this.gltf[e]&&this.gltf[e][t];return s||console.warn(`glTF file error: Could not find ${e}[${t}]`),s}getTypedArrayForBufferView(e){e=this.getBufferView(e);const t=this.getBuffer(e.buffer).data,s=e.byteOffset||0;return new Uint8Array(t,s,e.byteLength)}getTypedArrayForAccessor(e){e=this.getAccessor(e);const t=this.getBuffer(e.bufferView),s=this.getBuffer(t.buffer).data,{ArrayType:r,length:n}=A(e,t);return new r(s,t.byteOffset+e.byteOffset,n)}getTypedArrayForImageData(e){e=this.getAccessor(e);const t=this.getBuffer(e.bufferView),s=this.getBuffer(t.buffer).data,r=t.byteOffset||0;return new Uint8Array(s,r,t.byteLength)}addApplicationData(e,t){return this.json[e]=t,this}addExtraData(e,t){return this.json.extras=this.json.extras||{},this.json.extras[e]=t,this}addExtension(e,t){return m(t),this.json.extensions=this.json.extensions||{},this.json.extensions[e]=t,this.registerUsedExtension(e),this}addRequiredExtension(e,t){return m(t),this.addExtension(e,t),this.registerRequiredExtension(e),this}registerUsedExtension(e){this.json.extensionsUsed=this.json.extensionsUsed||[],this.json.extensionsUsed.find(t=>t===e)||this.json.extensionsUsed.push(e)}registerRequiredExtension(e){this.registerUsedExtension(e),this.json.extensionsRequired=this.json.extensionsRequired||[],this.json.extensionsRequired.find(t=>t===e)||this.json.extensionsRequired.push(e)}removeExtension(e){this.json.extensionsRequired&&this._removeStringFromArray(this.json.extensionsRequired,e),this.json.extensionsUsed&&this._removeStringFromArray(this.json.extensionsUsed,e),this.json.extensions&&delete this.json.extensions[e]}setObjectExtension(e,t,s){(e.extensions||{})[t]=s}addMesh(e,t,s=4){const r={primitives:[{attributes:this._addAttributes(e),indices:t,mode:s}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(r),this.json.meshes.length-1}addPointCloud(e){const t={primitives:[{attributes:this._addAttributes(e),mode:0}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(t),this.json.meshes.length-1}addImage(e,t){t=t||$(e);const s={bufferView:this.addBufferView(e),mimeType:t};return this.json.images=this.json.images||[],this.json.images.push(s),this.json.images.length-1}addBufferView(e){const t=e.byteLength;m(Number.isFinite(t)),this.sourceBuffers=this.sourceBuffers||[],this.sourceBuffers.push(e);const s={buffer:0,byteOffset:this.byteLength,byteLength:t};return this.byteLength+=v(t),this.json.bufferViews=this.json.bufferViews||[],this.json.bufferViews.push(s),this.json.bufferViews.length-1}addAccessor(e,t){const s={bufferView:e,type:_(t.size),componentType:t.componentType,count:t.count};return this.json.accessors=this.json.accessors||[],this.json.accessors.push(s),this.json.accessors.length-1}addBinaryBuffer(e,t={size:3}){const s=this.addBufferView(e),r={size:t.size,componentType:T(e),count:Math.round(e.length/t.size)};return this.addAccessor(s,Object.assign(r,t))}createBinaryChunk(){if(this.arrayBuffer)return;const e=this.byteLength,t=new ArrayBuffer(e),s=new Uint8Array(t);let r=0;for(let e=0;e<this.sourceBuffers.length;e++){r=B(this.sourceBuffers[e],s,r)}this.json.buffers[0].byteLength=e,this.arrayBuffer=t,this.sourceBuffers=[]}_removeStringFromArray(e,t){let s=!0;for(;s;){const r=e.indexOf(t);r>-1?e.splice(r,1):s=!1}}}function X(e){const t={};for(const s in e){const r=e[s];if("indices"!==s){const e=z(r);t[s]=e}}return t}function z(e,t){const{buffer:s,size:r,count:n}=function(e,t){let s=e,r=1,n=0;e&&e.value&&(s=e.value,r=e.size||1);s&&(ArrayBuffer.isView(s)||(s=function(e,t,s=!1){if(!e)return null;if(Array.isArray(e))return new t(e);if(s&&!(e instanceof t))return new t(e);return e}(s,Float32Array)),n=s.length/r);return{buffer:s,size:r,count:n}}(e);return{value:s,size:r,bufferView:null,byteOffset:0,count:n,type:_(r),componentType:T(s)}}class H{static get name(){return n}static decode(e,t){const s=new W(e);for(const e of s.json.meshes||[])H.decompressMesh(e,t);s.removeExtension(n)}static encode(e,t){const s=new W(e);for(const e of s.json.meshes||[])H.compressMesh(e,t),s.addRequiredExtension(n)}static compressMesh(e,t,s=4,r={}){if(!r.DracoWriter||!r.DracoLoader)throw new Error("DracoWriter/DracoLoader not available");const i=r.DracoWriter.encodeSync({attributes:e}),o=r.DracoLoader.parseSync({attributes:e}),u=r._addFauxAttributes(o.attributes),a=r.addBufferView(i);return{primitives:[{attributes:u,mode:s,extensions:{[n]:{bufferView:a,attributes:u}}}]}}static decompressMesh(e,t={}){for(const s of e.primitives)if(H._decompressMeshPrimitive(s,t),!s.attributes||0===Object.keys(s.attributes).length)throw new Error("Empty glTF primitive: decompression failure?")}static _decompressMeshPrimitive(e,t){const s=e.extensions&&e.extensions[n];if(!s)return;if(!t.DracoLoader||!t.decompress)return;delete e.extensions[n];const r=this._getBufferViewArray(s.bufferView),i=t.DracoLoader.parseSync(r);e.attributes=X(i.attributes),i.indices&&(e.indices=z(i.indices))}}class K{static get name(){return o}static decode(e,t){const s=new W(e),r=s.getExtension(o);r&&(s.json.lights=r.lights,s.removeExtension(o));for(const e of s.nodes||[]){const t=e.extensions&&e.extensions.KHR_lights_punctual;t&&(e.light=s._get("lights",t.light),delete e.extensions.KHR_lights_punctual)}}static encode(e,t){const s=new W(e),{json:r}=s;if(r.lights){const e=s.addExtensions(o);m(!e.lights),e.lights=r.lights,delete r.lights}if(s.json.lights){for(const e of s.json.lights){const t=e.node;s.addObjectExtension(t,o,e)}delete s.json.lights}}}const J={fetchLinkedResources:!1,decompress:!1,DracoLoader:null,postProcess:!0,createImages:!1,log:console},Q={fetchLinkedResources:!0,fetch:d,decompress:!1,DracoLoader:null,postProcess:!0,createImages:!1,log:console};function Y(e,t,s=0,n={}){n=Object.assign({},J,n);let i=t;if(i instanceof ArrayBuffer&&!P(i,s,n)){i=(new TextDecoder).decode(i)}if(e.buffers=[],"string"==typeof i?e.json=JSON.parse(i):i instanceof ArrayBuffer?(s=I(e,i,s,n),e.hasBinChunk&&e.buffers.push({arrayBuffer:i,byteOffset:e.binChunkByteOffset,byteLength:e.binChunkLength})):e.json=i,n.uri&&(e.baseUri=n.uri),n.fetchLinkedResources)for(const t of e.json.buffers||[])if(t.uri)throw new Error("parseGLTFSync: Cannot decode uri buffers");return function(e,t){for(const s in r){if(!(s in t&&!t[s])){r[s].decode(e,t)}}}(e,n),s}async function Z(e,t,s=0,r={}){return r=Object.assign({},Q,r),Y(e,t,s,{...r,fetchLinkedResources:!1,postProcess:!1,decompress:!1}),r.fetchLinkedResources&&await async function(e,t){for(const s of e.json.buffers)if(s.uri){const e=t.fetch||window.fetch;m(e);const r=E(s.uri,t.uri),n=await e(r),i=await n.arrayBuffer();s.data=i,delete s.uri}}(e,r),e}var ee=s(0);s(4);new Map;ee.a.TextEncoder;const te=ee.a.TextDecoder;function se(e,t,s={}){return function e(t,s,r,n={}){const i=t;const o=function(e,t){const s=function(e){if("string"==typeof e){if(0===e.indexOf("##/"))return e.slice(1);let t=e.match(/#\/([a-z]+)\/([0-9]+)/);if(t){const e=parseInt(t[2],10);return[t[1],e]}if(t=e.match(/\$\$\$([0-9]+)/)){return["accessors",parseInt(t[1],10)]}}return null}(e);if(s){const[r,n]=s,i=t[r]&&t[r][n];if(i)return i;console.error(`Invalid JSON pointer ${e}: #/${r}/${n}`)}return null}(i,r);if(o)return o;if(Array.isArray(i))return i.map(t=>e(t,s,r,n));if(null!==i&&"object"==typeof i){const t={};for(const o in i)t[o]=e(i[o],s,r,n);return t}return i}(e,e,t,s)}function re(e,t,s){s&&(e=function(e,t){const s=e.byteLength-t,r=new ArrayBuffer(s),n=new Uint8Array(e),i=new Uint8Array(r);for(let e=0;e<s;e++)i[e]=n[t+e];return r}(e,s));const r=t.bufferViews||[];for(let e=0;e<r.length;++e){m(r[e].byteLength>=0)}return{accessors:ne(e,r,t),images:ie(e,r,t)}}function ne(e,t,s){const r=s.accessors||[],n=[];for(let s=0;s<r.length;++s){const i=r[s];m(i);const o=t[i.bufferView];if(o){const{ArrayType:t,length:s}=A(i,o),r=new t(e,o.byteOffset,s);r.accessor=i,n.push(r)}}return n}function ie(e,t,s){const r=s.images||[],n=[];for(let s=0;s<r.length;++s){const i=r[s];m(i);const o=t[i.bufferView];m(o);const u=new Uint8Array(e,o.byteOffset,o.byteLength);u.imate=i,n.push(u)}return n}class oe{static isGLB(e,t={}){return P(e,0)}parse(e,t={}){return this.parseSync(e,t)}parseSync(e,t={}){if(this.glbArrayBuffer=e,this.binaryByteOffset=null,this.packedJson=null,this.json=null,null===this.json&&null===this.binaryByteOffset){const e=0;I(this,this.glbArrayBuffer,e,t),this.binaryByteOffset=this.binChunkByteOffset,this.packedJson=this.json;const s=re(this.glbArrayBuffer,this.json,this.binaryByteOffset);this.json=se(this.json,s),this.unpackedBuffers=s}return this}getApplicationData(e){return this.json[e]}getJSON(){return this.json}getArrayBuffer(){return this.glbArrayBuffer}getBinaryByteOffset(){return this.binaryByteOffset}getBufferView(e){const t=(e.byteOffset||0)+this.binaryByteOffset;return new Uint8Array(this.glbArrayBuffer,t,e.byteLength)}getBuffer(e){const t=x[e.componentType],s=b[e.type],r=w[e.componentType],n=e.count*s,i=e.count*s*r,o=this.json.bufferViews[e.bufferView];m(i>=0&&e.byteOffset+i<=o.byteLength);const u=o.byteOffset+this.binaryByteOffset+e.byteOffset;return new t(this.glbArrayBuffer,u,n)}getImageData(e){return{typedArray:this.getBufferView(e.bufferView),mimeType:e.mimeType||"image/jpeg"}}getImage(e){const t=this.getBufferView(e.bufferView),s=e.mimeType||"image/jpeg",r=new Blob([t],{type:s}),n=(self.URL||self.webkitURL).createObjectURL(r),i=new Image;return i.src=n,i}getImageAsync(e){return new Promise(t=>{const s=this.getBufferView(e.bufferView),r=e.mimeType||"image/jpeg",n=new Blob([s],{type:r}),i=(self.URL||self.webkitURL).createObjectURL(n),o=new Image;o.onload=()=>t(o),o.src=i})}}const ue={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},ae={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},fe={TEXTURE_MAG_FILTER:10240,TEXTURE_MIN_FILTER:10241,TEXTURE_WRAP_S:10242,TEXTURE_WRAP_T:10243,REPEAT:10497,LINEAR:9729,NEAREST_MIPMAP_LINEAR:9986},ce={magFilter:fe.TEXTURE_MAG_FILTER,minFilter:fe.TEXTURE_MIN_FILTER,wrapS:fe.TEXTURE_WRAP_S,wrapT:fe.TEXTURE_WRAP_T},he={[fe.TEXTURE_MAG_FILTER]:fe.LINEAR,[fe.TEXTURE_MIN_FILTER]:fe.NEAREST_MIPMAP_LINEAR,[fe.TEXTURE_WRAP_S]:fe.REPEAT,[fe.TEXTURE_WRAP_]:fe.REPEAT};class le{postProcess(e,t,s={}){return this.gltf=e,this.glbParser=t,this._resolveToTree(s),this.gltf}_resolveToTree(e={}){const{gltf:t}=this;return(t.bufferViews||[]).forEach((e,t)=>this._resolveBufferView(e,t)),(t.images||[]).forEach((t,s)=>this._resolveImage(t,s,e)),(t.samplers||[]).forEach((e,t)=>this._resolveSampler(e,t)),(t.textures||[]).forEach((e,t)=>this._resolveTexture(e,t)),(t.accessors||[]).forEach((e,t)=>this._resolveAccessor(e,t)),(t.materials||[]).forEach((e,t)=>this._resolveMaterial(e,t)),(t.meshes||[]).forEach((e,t)=>this._resolveMesh(e,t)),(t.nodes||[]).forEach((e,t)=>this._resolveNode(e,t)),(t.skins||[]).forEach((e,t)=>this._resolveSkin(e,t)),(t.scenes||[]).forEach((e,t)=>this._resolveScene(e,t)),void 0!==t.scene&&(t.scene=t.scenes[this.gltf.scene]),this._process_extension_KHR_lights_punctual(),t}getScene(e){return this._get("scenes",e)}getNode(e){return this._get("nodes",e)}getSkin(e){return this._get("skins",e)}getMesh(e){return this._get("meshes",e)}getMaterial(e){return this._get("materials",e)}getAccessor(e){return this._get("accessors",e)}getCamera(e){return null}getTexture(e){return this._get("textures",e)}getSampler(e){return this._get("samplers",e)}getImage(e){return this._get("images",e)}getBufferView(e){return this._get("bufferViews",e)}getBuffer(e){return this._get("buffers",e)}_get(e,t){if("object"==typeof t)return t;const s=this.gltf[e]&&this.gltf[e][t];return s||console.warn(`glTF file error: Could not find ${e}[${t}]`),s}_resolveScene(e,t){e.id=`scene-${t}`,e.nodes=(e.nodes||[]).map(e=>this.getNode(e))}_resolveNode(e,t){e.id=`node-${t}`,e.children=(e.children||[]).map(e=>this.getNode(e)),void 0!==e.mesh&&(e.mesh=this.getMesh(e.mesh)),void 0!==e.camera&&(e.camera=this.getCamera(e.camera)),void 0!==e.skin&&(e.skin=this.getSkin(e.skin))}_resolveSkin(e,t){e.id=`skin-${t}`,e.inverseBindMatrices=this.getAccessor(e.inverseBindMatrices)}_resolveMesh(e,t){e.id=`mesh-${t}`;for(const t of e.primitives){for(const e in t.attributes)t.attributes[e]=this.getAccessor(t.attributes[e]);void 0!==t.indices&&(t.indices=this.getAccessor(t.indices)),void 0!==t.material&&(t.material=this.getMaterial(t.material))}}_resolveMaterial(e,t){if(e.id=`material-${t}`,e.normalTexture&&(e.normalTexture.texture=this.getTexture(e.normalTexture.index)),e.occlusionTexture&&(e.occlusionTexture.texture=this.getTexture(e.occlusionTexture.index)),e.emissiveTexture&&(e.emissiveTexture.texture=this.getTexture(e.emissiveTexture.index)),e.pbrMetallicRoughness){const t=e.pbrMetallicRoughness;t.baseColorTexture&&(t.baseColorTexture.texture=this.getTexture(t.baseColorTexture.index)),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.texture=this.getTexture(t.metallicRoughnessTexture.index))}}_resolveAccessor(e,t){e.id=`accessor-${t}`,void 0!==e.bufferView&&(e.bufferView=this.getBufferView(e.bufferView)),e.bytesPerComponent=ae[e],e.components=ue[e],e.bytesPerElement=e.bytesPerComponent*e.components}_resolveTexture(e,t){e.id=`texture-${t}`,e.sampler="sampler"in e?this.getSampler(e.sampler):he,e.source=this.getImage(e.source)}_resolveSampler(e,t){e.id=`sampler-${t}`,e.parameters={};for(const t in e){const s=this._enumSamplerParameter(t);void 0!==s&&(e.parameters[s]=e[t])}}_enumSamplerParameter(e){return ce[e]}_resolveImage(e,t,s){e.id=`image-${t}`,void 0!==e.bufferView&&(e.bufferView=this.getBufferView(e.bufferView));const{createImages:r=!0}=s;r?e.image=this.glbParser.getImage(e):e.getImageAsync=()=>this.glbParser?this.glbParser.getImageAsync(e):e.uri?new Promise(t=>{const r=new Image;r.crossOrigin="anonymous",r.onload=()=>t(r),r.src=E(e.uri,s.uri)}):null}_resolveBufferView(e,t){if(e.id=`bufferView-${t}`,e.buffer=this.getBuffer(e.buffer),this.glbParser)e.data=this.glbParser.getBufferView(e);else{const t=e.byteOffset||0;e.data=new Uint8Array(e.buffer.data,t,e.byteLength)}}_resolveCamera(e){e.perspective,e.orthographic}_process_extension_KHR_lights_punctual(){const{gltf:e}=this,t=e.extensions&&e.extensions.KHR_lights_punctual;t&&(e.lights=t.lights),this._removeExtension("KHR_lights_punctual");for(const t of e.nodes||[]){const e=t.extensions&&t.extensions.KHR_lights_punctual;e&&(t.light=this._get("lights",e.light),delete t.extensions.KHR_lights_punctual)}delete e.lights}_removeExtension(e){this.gltf.extensionsRequired&&this._removeStringFromArray(this.gltf.extensionsRequired,e),this.gltf.extensionsUsed&&this._removeStringFromArray(this.gltf.extensionsUsed,e),this.gltf.extensions&&delete this.gltf.extensions[e]}_removeStringFromArray(e,t){let s=!0;for(;s;){const r=e.indexOf(t);r>-1?e.splice(r,1):s=!1}}}const ge={fetchLinkedResources:!0,fetch:d,decompress:!1,DracoLoader:null,postProcess:!0,createImages:!1,log:console};class de{async parse(e,t={}){if(t=Object.assign({},ge,t),this.parseSync(e,{...t,postProcess:!1,decompress:!1}),t.fetchLinkedResources&&await this._loadLinkedAssets(t),t.decompress&&this._decompressMeshes(t),t.postProcess){(new le).postProcess(this.gltf,this.glbParser,t)}return this.gltf}parseSync(e,t={}){if(t=Object.assign({},ge,t),e instanceof ArrayBuffer&&!oe.isGLB(e,t)){e=(new te).decode(e)}if("string"==typeof e&&(e=JSON.parse(e)),e instanceof ArrayBuffer?(this.glbParser=new oe,this.gltf=this.glbParser.parseSync(e).json,this.json=this.gltf):(this.glbParser=null,this.gltf=e,this.json=e),t.decompress&&this._decompressMeshes(t),t.postProcess){(new le).postProcess(this.gltf,this.glbParser,t)}return this.gltf}getApplicationData(e){return this.json[e]}getExtraData(e){return(this.json.extras||{})[e]}getExtension(e){const t=this.getUsedExtensions().find(t=>t===e),s=this.json.extensions||{};return t?s[e]||!0:null}getRequiredExtension(e){return this.getRequiredExtensions().find(t=>t===e)?this.getExtension(e):null}getRequiredExtensions(){return this.json.extensionsRequired||[]}getUsedExtensions(){return this.json.extensionsUsed||[]}getScene(e){return this._get("scenes",e)}getNode(e){return this._get("nodes",e)}getSkin(e){return this._get("skins",e)}getMesh(e){return this._get("meshes",e)}getMaterial(e){return this._get("materials",e)}getAccessor(e){return this._get("accessors",e)}getCamera(e){return null}getTexture(e){return this._get("textures",e)}getSampler(e){return this._get("samplers",e)}getImage(e){return this._get("images",e)}getBufferView(e){return this._get("bufferViews",e)}getBuffer(e){return this._get("buffers",e)}_get(e,t){if("object"==typeof t)return t;const s=this.gltf[e]&&this.gltf[e][t];return s||console.warn(`glTF file error: Could not find ${e}[${t}]`),s}async _loadLinkedAssets(e){return await Promise.all(this.gltf.buffers.map(t=>this._loadBuffer(t,e)))}async _loadBuffer(e,t){if(e.uri&&t.uri){const s=t.fetch||window.fetch,r=E(e.uri,t.uri),n=await s(r),i=await n.arrayBuffer();e.data=i,e.uri=null}}_decompressMeshes(e){if(e.DracoLoader&&e.decompress){for(const t of this.gltf.meshes||[])for(const s of t.primitives)if(this._decompressKhronosDracoPrimitive(s,e),this._decompressUberDracoPrimitive(s,e),!s.attributes||0===Object.keys(s.attributes).length)throw new Error("Empty glTF primitive: decompression failure?");this._removeExtension(n),this._removeExtension(i)}}_decompressKhronosDracoPrimitive(e,t){const s=e.extensions&&e.extensions[n];if(!s)return;delete e.extensions[n];const r=this._getBufferViewArray(s.bufferView),i=t.DracoLoader.parseSync(r);e.attributes=X(i.attributes),i.indices&&(e.indices=z(i.indices))}_decompressUberDracoPrimitive(e,t){const s=e.extensions&&e.extensions[i];if(!s)return;if(0!==e.mode)throw new Error(i);delete e.extensions[i];const r=this._getBufferViewArray(s.bufferView),n=t.DracoLoader.parseSync(r);e.attributes=n.attributes}_getBufferViewArray(e){const t=this.gltf.bufferViews[e];if(this.glbParser)return this.glbParser.getBufferView(t);const s=this.gltf.buffers[t.buffer].data,r=t.byteOffset||0;return new Uint8Array(s,r,t.byteLength)}_removeExtension(e){this.json.extensionsRequired&&this._removeStringFromArray(this.json.extensionsRequired,e),this.json.extensionsUsed&&this._removeStringFromArray(this.json.extensionsUsed,e),this.json.extensions&&delete this.json.extensions[e]}_removeStringFromArray(e,t){let s=!0;for(;s;){const r=e.indexOf(t);r>-1?e.splice(r,1):s=!1}}}const me={useGLTFParser:!0};var pe={name:"glTF",extensions:["gltf","glb"],text:!0,binary:!0,test:"glTF",parse:async function(e,t={}){if((t={...me,...t}).useGLTFParser){return(new de).parse(e,t)}const{byteOffset:s=0}=t,r={};return await Z(r,e,s,t),r},parseSync:function(e,t={}){if((t={...me,...t}).useGLTFParser)return(new de).parseSync(e,t);const{byteOffset:s=0}=t,r={};return Y(r,e,s,t),r},defaultOptions:me};function ye(e,t,s,r){const n=v(s.byteLength),i=n-s.byteLength;if(e){const r=new Uint8Array(e.buffer,e.byteOffset+t,s.byteLength),n=new Uint8Array(s);r.set(n);for(let r=0;r<i;++r)e.setUint8(t+s.byteLength+r,32)}return t+=n}const be=1179937895,we=1313821514,xe=5130562,_e=!0;function Te(e,t,s=0,r={}){const{magic:n=be,version:i=2,json:o={},binary:u}=e,a=s;t&&(t.setUint32(s+0,n,_e),t.setUint32(s+4,i,_e),t.setUint32(s+8,0,_e));const f=s+8,c=s+=12;if(t&&(t.setUint32(s+0,0,_e),t.setUint32(s+4,we,_e)),s=function(e,t,s,r){return t=ye(e,t,(new TextEncoder).encode(s))}(t,s+=8,JSON.stringify(o)),t){const e=s-c-8;t.setUint32(c+0,e,_e)}if(u){const e=s;if(t&&(t.setUint32(s+0,0,_e),t.setUint32(s+4,xe,_e)),s=ye(t,s+=8,u),t){const r=s-e-8;t.setUint32(e+0,r,_e)}}if(t){const e=s-a;t.setUint32(f,e,_e)}return s}function Ae(e,t,s,r){return function(e,{firstBuffer:t=0}={}){if(e.buffers&&e.buffers.length>t)throw new Error("encodeGLTF: multiple buffers not yet implemented")}(e),Te(e,t,s,r)}var Ee={name:"glTF",extensions:["glb"],encodeSync:function(e,t={}){const{byteOffset:s=0}=t,r=Ae(e,null,s,t),n=new ArrayBuffer(r);return Ae(e,new DataView(n),s,t),n},binary:!0,defaultOptions:{useGLTFBuilder:!0}},je={name:"GLB",extension:["glb"],text:!0,binary:!0,parseSync:function(e,t){const{byteOffset:s=0}=t,r={};return I(r,e,s,t),r}};var ve={name:"GLB",extensions:["glb"],encodeSync:function(e,t){const{byteOffset:s=0}=t,r=Te(e,null,s,t),n=new ArrayBuffer(r),i=new DataView(n);return Te(e,i,s,t),n},binary:!0};const Be={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Re={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},Le={TEXTURE_MAG_FILTER:10240,TEXTURE_MIN_FILTER:10241,TEXTURE_WRAP_S:10242,TEXTURE_WRAP_T:10243,REPEAT:10497,LINEAR:9729,NEAREST_MIPMAP_LINEAR:9986},Ue={magFilter:Le.TEXTURE_MAG_FILTER,minFilter:Le.TEXTURE_MIN_FILTER,wrapS:Le.TEXTURE_WRAP_S,wrapT:Le.TEXTURE_WRAP_T},Ve={[Le.TEXTURE_MAG_FILTER]:Le.LINEAR,[Le.TEXTURE_MIN_FILTER]:Le.NEAREST_MIPMAP_LINEAR,[Le.TEXTURE_WRAP_S]:Le.REPEAT,[Le.TEXTURE_WRAP_]:Le.REPEAT};class Se{postProcess(e,t={}){return this.gltf=e,this.json=e.json,this.buffers=e.buffers,this._resolveTree(e.json,t)}_resolveTree(e,t={}){return e.bufferViews&&(e.bufferViews=e.bufferViews.map((e,t)=>this._resolveBufferView(e,t))),e.images&&(e.images=e.images.map((e,s)=>this._resolveImage(e,s,t))),e.samplers&&(e.samplers=e.samplers.map((e,t)=>this._resolveSampler(e,t))),e.textures&&(e.textures=e.textures.map((e,t)=>this._resolveTexture(e,t))),e.accessors&&(e.accessors=e.accessors.map((e,t)=>this._resolveAccessor(e,t))),e.materials&&(e.materials=e.materials.map((e,t)=>this._resolveMaterial(e,t))),e.meshes&&(e.meshes=e.meshes.map((e,t)=>this._resolveMesh(e,t))),e.nodes&&(e.nodes=e.nodes.map((e,t)=>this._resolveNode(e,t))),e.skins&&(e.skins=e.skins.map((e,t)=>this._resolveSkin(e,t))),e.scenes&&(e.scenes=e.scenes.map((e,t)=>this._resolveScene(e,t))),void 0!==e.scene&&(e.scene=e.scenes[this.json.scene]),e}getScene(e){return this._get("scenes",e)}getNode(e){return this._get("nodes",e)}getSkin(e){return this._get("skins",e)}getMesh(e){return this._get("meshes",e)}getMaterial(e){return this._get("materials",e)}getAccessor(e){return this._get("accessors",e)}getCamera(e){return null}getTexture(e){return this._get("textures",e)}getSampler(e){return this._get("samplers",e)}getImage(e){return this._get("images",e)}getBufferView(e){return this._get("bufferViews",e)}getBuffer(e){return this._get("buffers",e)}_get(e,t){if("object"==typeof t)return t;const s=this.json[e]&&this.json[e][t];return s||console.warn(`glTF file error: Could not find ${e}[${t}]`),s}_resolveScene(e,t){return(e={...e}).id=e.id||`scene-${t}`,e.nodes=(e.nodes||[]).map(e=>this.getNode(e)),e}_resolveNode(e,t){return(e={...e}).id=e.id||`node-${t}`,e.children&&(e.children=e.children.map(e=>this.getNode(e))),void 0!==e.mesh&&(e.mesh=this.getMesh(e.mesh)),void 0!==e.camera&&(e.camera=this.getCamera(e.camera)),void 0!==e.skin&&(e.skin=this.getSkin(e.skin)),e}_resolveSkin(e,t){return(e={...e}).id=e.id||`skin-${t}`,e.inverseBindMatrices=this.getAccessor(e.inverseBindMatrices),e}_resolveMesh(e,t){return(e={...e}).id=e.id||`mesh-${t}`,e.primitives&&(e.primitives=e.primitives.map(e=>{const t=(e={...e}).attributes;e.attributes={};for(const s in t)e.attributes[s]=this.getAccessor(t[s]);return void 0!==e.indices&&(e.indices=this.getAccessor(e.indices)),void 0!==e.material&&(e.material=this.getMaterial(e.material)),e})),e}_resolveMaterial(e,t){if((e={...e}).id=e.id||`material-${t}`,e.normalTexture&&(e.normalTexture={...e.normalTexture},e.normalTexture.texture=this.getTexture(e.normalTexture.index)),e.occlusionTexture&&(e.occlustionTexture={...e.occlustionTexture},e.occlusionTexture.texture=this.getTexture(e.occlusionTexture.index)),e.emissiveTexture&&(e.emmisiveTexture={...e.emmisiveTexture},e.emissiveTexture.texture=this.getTexture(e.emissiveTexture.index)),e.pbrMetallicRoughness){e.pbrMetallicRoughness={...e.pbrMetallicRoughness};const t=e.pbrMetallicRoughness;t.baseColorTexture&&(t.baseColorTexture={...t.baseColorTexture},t.baseColorTexture.texture=this.getTexture(t.baseColorTexture.index)),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture={...t.metallicRoughnessTexture},t.metallicRoughnessTexture.texture=this.getTexture(t.metallicRoughnessTexture.index))}return e}_resolveAccessor(e,t){var s,r;return(e={...e}).id=e.id||`accessor-${t}`,void 0!==e.bufferView&&(e.bufferView=this.getBufferView(e.bufferView)),e.bytesPerComponent=(s=e.componentType,Re[s]),e.components=(r=e.type,Be[r]),e.bytesPerElement=e.bytesPerComponent*e.components,e}_resolveTexture(e,t){return(e={...e}).id=e.id||`texture-${t}`,e.sampler="sampler"in e?this.getSampler(e.sampler):Ve,e.source=this.getImage(e.source),e}_resolveSampler(e,t){(e={...e}).id=e.id||`sampler-${t}`,e.parameters={};for(const t in e){const s=this._enumSamplerParameter(t);void 0!==s&&(e.parameters[s]=e[t])}return e}_enumSamplerParameter(e){return Ue[e]}_resolveImage(e,t,s){if((e={...e}).id=e.id||`image-${t}`,void 0!==e.bufferView&&(e.bufferView=this.getBufferView(e.bufferView)),"uri"in e){const t=s.uri||this.gltf.baseUri;t&&(e.baseUri=t,e.fullUri=E(e.uri,t))}return e.getImageAsync=function(){return e.uri?new Promise(t=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>t(s),s.src=e.fullUri||e.uri}):null},e}_resolveBufferView(e,t){(e={...e}).id=e.id||`bufferView-${t}`;const s=e.buffer;e.buffer=this.getBuffer(s);const r=this.buffers[s].arrayBuffer;let n=this.buffers[s].byteOffset||0;return"byteOffset"in e&&(n+=e.byteOffset),e.data=new Uint8Array(r,n,e.byteLength),e}_resolveCamera(e,t){return e.id=e.id||`camera-${t}`,e.perspective,e.orthographic,e}}function Oe(e,t){return(new Se).postProcess(e,t)}function Me(e,t=Float32Array){if(0===e.length)return new Float32Array(0);if(!function e(t,s=Number.isFinite){let r=-1;for(;++r<t.length;){const n=t[r];if(Array.isArray(n)||ArrayBuffer.isView(n)){if(!e(n,s))return!1}else if(!s(n))return!1}return!0}(e))return null;const s=new t(function e(t,s=3){let r=0;let n=0;let i=-1;for(;++i<t.length;){const s=t[i];Array.isArray(s)||ArrayBuffer.isView(s)?r+=e(s):n++}return r+(0===r&&n<s?s:n)}(e));return function(e,t,s=3){(function e(t,s,r,n){let i=-1;let o=0;for(;++i<t.length;){const u=t[i];Array.isArray(u)||ArrayBuffer.isView(u)?n=e(u,s,r,n):o<r&&(s[n++]=u,o++)}o>0&&o<r&&(s[n++]=0);return n})(e,t,s,0)}(e,s),s}function Pe(e,t,s={}){const{flattenArrays:r=!1}=s;let n=e;if("string"==typeof n&&0===n.indexOf("#/"))return`#${n}`;if(Array.isArray(n)){const e=r&&Me(n);if(!e)return n.map(e=>Pe(e,t,s));n=e}if(ArrayBuffer.isView(n)&&t){if(t.isImage(n)){return`#/images/${t.addImage(n)}`}return`#/accessors/${t.addBuffer(n)}`}if(null!==n&&"object"==typeof n){const e={};for(const r in n)e[r]=Pe(n[r],t,s);return e}return n}class Ie{constructor(e={}){this.byteLength=0,this.json={buffers:[{byteLength:0}],bufferViews:[],accessors:[],images:[],meshes:[]},this.sourceBuffers=[],this.log=e.log||console}getByteLength(){return this.byteLength}isImage(e){return function(e,t){if(t){const{test:s}=G(t);return s(q(e))}return Boolean($(e))}(e)}encodeSync(e={}){return this.encodeAsGLB(e)}encodeAsGLB(e={}){this._packBinaryChunk(),e.magic&&console.warn("Custom glTF magic number no longer supported");const t={version:2,json:this.json,binary:this.arrayBuffer},s=Te(t,null,0,e),r=new ArrayBuffer(s);return Te(t,new DataView(r),0,e),r}addApplicationData(e,t,s={}){const r=s.packTypedArrays?Pe(t,this,s):t;return this.json[e]=r,this}addBuffer(e,t={size:3}){const s=this.addBufferView(e),r={size:t.size,componentType:T(e),count:Math.round(e.length/t.size)};return this.addAccessor(s,Object.assign(r,t))}addBufferView(e){const t=e.byteLength||e.length;return this.json.bufferViews.push({buffer:0,byteOffset:this.byteLength,byteLength:t}),this.byteLength+=v(t),this.sourceBuffers.push(e),this.json.bufferViews.length-1}addAccessor(e,t){return this.json.accessors.push({bufferView:e,type:_(t.size),componentType:t.componentType,count:t.count}),this.json.accessors.length-1}_pack(){return this._packBinaryChunk(),{arrayBuffer:this.arrayBuffer,json:this.json}}_packBinaryChunk(){if(this.arrayBuffer)return;const e=this.byteLength,t=new ArrayBuffer(e),s=new Uint8Array(t);let r=0;for(let e=0;e<this.sourceBuffers.length;e++){r=B(this.sourceBuffers[e],s,r)}this.json.buffers[0].byteLength=e,this.arrayBuffer=t,this.sourceBuffers=[]}_getInternalCounts(){return{buffers:this.json.buffers.length,bufferViews:this.json.bufferViews.length,accessors:this.json.accessors.length,images:this.json.images.length}}}class ke extends Ie{constructor(e={}){super(e),this.DracoWriter=e.DracoWriter,this.DracoLoader=e.DracoLoader}addApplicationData(e,t,s={}){const r=s.packTypedArrays?Pe(t,this,s):t;return this.json[e]=r,this}addExtraData(e,t,s={}){const r=s.packedTypedArrays?Pe(t,this,s):t;return this.json.extras=this.json.extras||{},this.json.extras[e]=r,this}addExtension(e,t,s={}){m(t);const r=s.packTypedArrays?Pe(t,this,s):t;return this.json.extensions=this.json.extensions||{},this.json.extensions[e]=r,this.registerUsedExtension(e),this}addRequiredExtension(e,t,s={}){m(t);const r=s.packTypedArrays?Pe(t,this,s):t;return this.addExtension(e,r),this.registerRequiredExtension(e),this}registerUsedExtension(e){this.json.extensionsUsed=this.json.extensionsUsed||[],this.json.extensionsUsed.find(t=>t===e)||this.json.extensionsUsed.push(e)}registerRequiredExtension(e){this.registerUsedExtension(e),this.json.extensionsRequired=this.json.extensionsRequired||[],this.json.extensionsRequired.find(t=>t===e)||this.json.extensionsRequired.push(e)}addMesh(e,t,s=4){const r={primitives:[{attributes:this._addAttributes(e),indices:t,mode:s}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(r),this.json.meshes.length-1}addPointCloud(e){const t={primitives:[{attributes:this._addAttributes(e),mode:0}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(t),this.json.meshes.length-1}addCompressedMesh(e,t,s=4){if(!this.DracoWriter||!this.DracoLoader)throw new Error("DracoWriter/DracoLoader not available");this.registerRequiredExtension(n);const r=this.DracoWriter.encodeSync({attributes:e}),i=this.DracoLoader.parseSync({attributes:e}),o=this._addFauxAttributes(i.attributes),u=this.addBufferView(r),a={primitives:[{attributes:o,mode:s,extensions:{[n]:{bufferView:u,attributes:o}}}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(a),this.json.meshes.length-1}addCompressedPointCloud(e){if(!this.DracoWriter||!this.DracoLoader)throw new Error("DracoWriter/DracoLoader not available");e.mode=0;const t=this.DracoWriter.encodeSync(e,{pointcloud:!0}),s=this.addBufferView(t),r={primitives:[{attributes:{},mode:0,extensions:{[i]:{bufferView:s}}}]};return this.registerRequiredExtension(i),this.json.meshes=this.json.meshes||[],this.json.meshes.push(r),this.json.meshes.length-1}addImage(e){const t=this.addBufferView(e),s=N(e)||{};if(s){const{mimeType:e,width:r,height:n}=s;this.json.images.push({bufferView:t,mimeType:e,width:r,height:n})}else this.json.images.push({bufferView:t});return this.json.images.length-1}}s.d(t,"KHR_DRACO_MESH_COMPRESSION",function(){return n}),s.d(t,"UBER_POINT_CLOUD_EXTENSION",function(){return i}),s.d(t,"GLTFLoader",function(){return pe}),s.d(t,"GLTFWriter",function(){return Ee}),s.d(t,"GLBLoader",function(){return je}),s.d(t,"GLBWriter",function(){return ve}),s.d(t,"GLTFScenegraph",function(){return W}),s.d(t,"postProcessGLTF",function(){return Oe}),s.d(t,"parseGLTFSync",function(){return Y}),s.d(t,"encodeGLTFSync",function(){return Ae}),s.d(t,"packBinaryJson",function(){return Pe}),s.d(t,"unpackBinaryJson",function(){return se}),s.d(t,"GLBParser",function(){return oe}),s.d(t,"GLBBuilder",function(){return Ie}),s.d(t,"GLTFParser",function(){return de}),s.d(t,"GLTFBuilder",function(){return ke})}])});
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r=t();for(var s in r)("object"==typeof exports?exports:e)[s]=r[s]}}(window,function(){return function(e){var t={};function r(s){if(t[s])return t[s].exports;var n=t[s]={i:s,l:!1,exports:{}};return e[s].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=e,r.c=t,r.d=function(e,t,s){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:s})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var s=Object.create(null);if(r.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)r.d(s,n,function(t){return e[t]}.bind(null,n));return s},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=13)}([function(e,t,r){"use strict";(function(e,s){r.d(t,"b",function(){return n}),r.d(t,"a",function(){return o}),r.d(t,"c",function(){return a});const n="object"!=typeof e||"[object process]"!==String(e)||e.browser,i={self:"undefined"!=typeof self&&self,window:"undefined"!=typeof window&&window,global:void 0!==s&&s,document:"undefined"!=typeof document&&document},o=i.global||i.self||i.window,u=void 0!==e&&e.version&&e.version.match(/v([0-9]*)/),a=u&&parseFloat(u[1])||0}).call(this,r(14),r(9))},,,,function(e,t){},,,,,function(e,t){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(e){"object"==typeof window&&(r=window)}e.exports=r},,,,function(e,t,r){(function(t){const s=r(15),n="undefined"==typeof window?t:window;n.loaders=n.loaders||{},e.exports=Object.assign(n.loaders,s)}).call(this,r(9))},function(e,t){var r,s,n=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function u(e){if(r===setTimeout)return setTimeout(e,0);if((r===i||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:i}catch(e){r=i}try{s="function"==typeof clearTimeout?clearTimeout:o}catch(e){s=o}}();var a,f=[],c=!1,h=-1;function l(){c&&a&&(c=!1,a.length?f=a.concat(f):h=-1,f.length&&g())}function g(){if(!c){var e=u(l);c=!0;for(var t=f.length;t;){for(a=f,f=[];++h<t;)a&&a[h].run();h=-1,t=f.length}a=null,c=!1,function(e){if(s===clearTimeout)return clearTimeout(e);if((s===o||!s)&&clearTimeout)return s=clearTimeout,clearTimeout(e);try{s(e)}catch(t){try{return s.call(null,e)}catch(t){return s.call(this,e)}}}(e)}}function d(e,t){this.fun=e,this.array=t}function y(){}n.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];f.push(new d(e,t)),1!==f.length||c||u(g)},d.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.browser=!0,n.env={},n.argv=[],n.version="",n.versions={},n.on=y,n.addListener=y,n.once=y,n.off=y,n.removeListener=y,n.removeAllListeners=y,n.emit=y,n.prependListener=y,n.prependOnceListener=y,n.listeners=function(e){return[]},n.binding=function(e){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(e){throw new Error("process.chdir is not supported")},n.umask=function(){return 0}},function(e,t,r){"use strict";r.r(t);const s="KHR_draco_mesh_compression",n="UBER_draco_point_cloud_compression",i="KHR_lights_punctual";const o=e=>"undefined"!=typeof Response&&e instanceof Response||e.arrayBuffer&&e.text&&e.json,u=e=>(e=>"undefined"!=typeof File&&e instanceof File)(e)||(e=>"undefined"!=typeof Blob&&e instanceof Blob)(e);let a="";const f={};function c(e){for(const t in f)if(e.startsWith(t)){const r=f[t];return e.replace(t,r)}return e+=a}function h(e,t){if(!e)throw new Error(t||"loader assertion failed.")}class l{constructor(e){this._fileOrBlob=e,this.bodyUsed=!1}get headers(){return new Headers({"Content-Length":this._fileOrBlob.size,"Content-Type":this._fileOrBlob.type})}get ok(){return!0}get status(){return 200}url(){return this._fileOrBlob.name||""}async arrayBuffer(){const{reader:e,promise:t}=this._getFileReader();return e.readAsArrayBuffer(this._fileOrBlob),t}async text(){const{reader:e,promise:t}=this._getFileReader();return e.readAsText(this._fileOrBlob),t}async json(){const e=await this.text();return JSON.parse(e)}_getFileReader(){let e;h(!this.bodyUsed),this.bodyUsed=!0;const t=new Promise((t,r)=>{try{(e=new FileReader).onerror=e=>r(new Error(e)),e.onabort=()=>r(new Error("Read aborted.")),e.onload=()=>t(e.result)}catch(e){r(e)}});return{reader:e,promise:t}}}function g(e,t){return Promise.resolve(new l(e,t))}async function d(e,t){return u(e)?g(e,t):(e=c(e),fetch(e,t))}function y(e,t){if(!e)throw new Error(t||"gltf/glb assertion failed.")}const m=["SCALAR","VEC2","VEC3","VEC4"],b=new Map([[Int8Array,5120],[Uint8Array,5121],[Int16Array,5122],[Uint16Array,5123],[Uint32Array,5125],[Float32Array,5126]]),p={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},w={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},x={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};function _(e){return m[e-1]||m[0]}function T(e){const t=b.get(e.constructor);if(!t)throw new Error("Illegal typed array");return t}function A(e,t){const r=x[e.componentType],s=p[e.type],n=w[e.componentType],i=e.count*s,o=e.count*s*n;return y(o>=0&&o<=t.byteLength),{ArrayType:r,length:i,byteLength:o}}function j(e,t){return e.startsWith("data:")||e.startsWith("http:")||e.startsWith("https:")?e:t.substr(0,t.lastIndexOf("/")+1)+e}const E=!1,v=!0,B=new Map([["image/png",{test:function(e){return e.byteLength>=24&&2303741511===e.getUint32(0,E)},getSize:function(e){return{width:e.getUint32(16,E),height:e.getUint32(20,E)}}}],["image/jpeg",{test:function(e){return e.byteLength>=3&&65496===e.getUint16(0,E)&&255===e.getUint8(2,E)},getSize:function(e){if(e.byteLength<2||65496!==e.getUint16(0,E))return null;const{tableMarkers:t,sofMarkers:r}=function(){const e=new Set([65499,65476,65484,65501,65534]);for(let t=65504;t<65520;++t)e.add(t);const t=new Set([65472,65473,65474,65475,65477,65478,65479,65481,65482,65483,65485,65486,65487,65502]);return{tableMarkers:e,sofMarkers:t}}();let s=2;for(;s<e.byteLength;){const n=e.getUint16(s,E);if(r.has(n))return{height:e.getUint16(s+5,E),width:e.getUint16(s+7,E)};if(!t.has(n))return null;s+=2,s+=e.getUint16(s,E)}return null}}],["image/gif",{test:function(e){return e.byteLength>=10&&1195984440===e.getUint32(0,E)},getSize:function(e){return{width:e.getUint16(6,v),height:e.getUint16(8,v)}}}],["image/bmp",{test:function(e){return e.byteLength>=2&&16973===e.getUint16(0,E)},getSize:function(e){return{width:e.getUint32(18,v),height:e.getUint32(22,v)}}}]]);const R=`Invalid MIME type. Supported MIME types are: ${Array.from(B.keys()).join(", ")}`;function L(e){const t=V(e);for(const[e,{test:r}]of B.entries())if(r(t))return e;return null}function U(e,t=null){const r=function(e,t=null){t=t||L(e);const{getSize:r}=O(t),s=r(V(e));if(!s)throw new Error(`invalid image data for type: ${t}`);return s}(e,t=t||L(e));return r.mimeType=t,r}function O(e){const t=B.get(e);if(!t)throw new Error(R);return t}function V(e){if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return new DataView(e.buffer||e);throw new Error("toDataView")}function S(e){return e+3&-4}function k(e,t,r){let s;if(e instanceof ArrayBuffer)s=new Uint8Array(e);else{const t=e.byteOffset,r=e.byteLength;s=new Uint8Array(e.buffer,t,r)}return t.set(s,r),r+S(s.byteLength)}class C{constructor(e){if(e instanceof C)return e;e||(e={json:{version:2,buffers:[]},buffers:[]}),this.gltf=e,y(this.gltf.json)}get json(){return this.gltf.json}getApplicationData(e){return this.json[e]}getExtraData(e){return(this.json.extras||{})[e]}getExtension(e){const t=this.getUsedExtensions().find(t=>t===e),r=this.json.extensions||{};return t?r[e]||!0:null}getRequiredExtension(e){return this.getRequiredExtensions().find(t=>t===e)?this.getExtension(e):null}getRequiredExtensions(){return this.json.extensionsRequired||[]}getUsedExtensions(){return this.json.extensionsUsed||[]}getObjectExtension(e,t){return(e.extensions||{})[t]}getScene(e){return this.getObject("scenes",e)}getNode(e){return this.getObject("nodes",e)}getSkin(e){return this.getObject("skins",e)}getMesh(e){return this.getObject("meshes",e)}getMaterial(e){return this.getObject("materials",e)}getAccessor(e){return this.getObject("accessors",e)}getCamera(e){return null}getTexture(e){return this.getObject("textures",e)}getSampler(e){return this.getObject("samplers",e)}getImage(e){return this.getObject("images",e)}getBufferView(e){return this.getObject("bufferViews",e)}getBuffer(e){return this.getObject("buffers",e)}getObject(e,t){if("object"==typeof t)return t;const r=this.json[e]&&this.json[e][t];if(!r)throw new Error(`glTF file error: Could not find ${e}[${t}]`);return r}getTypedArrayForBufferView(e){const t=(e=this.getBufferView(e)).buffer,r=this.gltf.buffers[t];y(r);const s=e.byteOffset||0+r.byteOffset;return new Uint8Array(r.arrayBuffer,s,e.byteLength)}getTypedArrayForAccessor(e){e=this.getAccessor(e);const t=this.getBuffer(e.bufferView),r=this.getBuffer(t.buffer).data,{ArrayType:s,length:n}=A(e,t);return new s(r,t.byteOffset+e.byteOffset,n)}getTypedArrayForImageData(e){e=this.getAccessor(e);const t=this.getBuffer(e.bufferView),r=this.getBuffer(t.buffer).data,s=t.byteOffset||0;return new Uint8Array(r,s,t.byteLength)}addApplicationData(e,t){return this.json[e]=t,this}addExtraData(e,t){return this.json.extras=this.json.extras||{},this.json.extras[e]=t,this}addExtension(e,t){return y(t),this.json.extensions=this.json.extensions||{},this.json.extensions[e]=t,this.registerUsedExtension(e),this}addRequiredExtension(e,t){return y(t),this.addExtension(e,t),this.registerRequiredExtension(e),this}registerUsedExtension(e){this.json.extensionsUsed=this.json.extensionsUsed||[],this.json.extensionsUsed.find(t=>t===e)||this.json.extensionsUsed.push(e)}registerRequiredExtension(e){this.registerUsedExtension(e),this.json.extensionsRequired=this.json.extensionsRequired||[],this.json.extensionsRequired.find(t=>t===e)||this.json.extensionsRequired.push(e)}removeExtension(e){this.json.extensionsRequired&&this._removeStringFromArray(this.json.extensionsRequired,e),this.json.extensionsUsed&&this._removeStringFromArray(this.json.extensionsUsed,e),this.json.extensions&&delete this.json.extensions[e]}setObjectExtension(e,t,r){(e.extensions||{})[t]=r}addMesh(e,t,r=4){const s={primitives:[{attributes:this._addAttributes(e),indices:t,mode:r}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(s),this.json.meshes.length-1}addPointCloud(e){const t={primitives:[{attributes:this._addAttributes(e),mode:0}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(t),this.json.meshes.length-1}addImage(e,t){t=t||L(e);const r={bufferView:this.addBufferView(e),mimeType:t};return this.json.images=this.json.images||[],this.json.images.push(r),this.json.images.length-1}addBufferView(e){const t=e.byteLength;y(Number.isFinite(t)),this.sourceBuffers=this.sourceBuffers||[],this.sourceBuffers.push(e);const r={buffer:0,byteOffset:this.byteLength,byteLength:t};return this.byteLength+=S(t),this.json.bufferViews=this.json.bufferViews||[],this.json.bufferViews.push(r),this.json.bufferViews.length-1}addAccessor(e,t){const r={bufferView:e,type:_(t.size),componentType:t.componentType,count:t.count};return this.json.accessors=this.json.accessors||[],this.json.accessors.push(r),this.json.accessors.length-1}addBinaryBuffer(e,t={size:3}){const r=this.addBufferView(e),s={size:t.size,componentType:T(e),count:Math.round(e.length/t.size)};return this.addAccessor(r,Object.assign(s,t))}createBinaryChunk(){if(this.arrayBuffer)return;const e=this.byteLength,t=new ArrayBuffer(e),r=new Uint8Array(t);let s=0;for(let e=0;e<this.sourceBuffers.length;e++){s=k(this.sourceBuffers[e],r,s)}this.json.buffers[0].byteLength=e,this.arrayBuffer=t,this.sourceBuffers=[]}_removeStringFromArray(e,t){let r=!0;for(;r;){const s=e.indexOf(t);s>-1?e.splice(s,1):r=!1}}}function P(e){const t={};for(const r in e){const s=e[r];if("indices"!==r){const e=M(s);t[r]=e}}return t}function M(e,t){const{buffer:r,size:s,count:n}=function(e,t){let r=e,s=1,n=0;e&&e.value&&(r=e.value,s=e.size||1);r&&(ArrayBuffer.isView(r)||(r=function(e,t,r=!1){if(!e)return null;if(Array.isArray(e))return new t(e);if(r&&!(e instanceof t))return new t(e);return e}(r,Float32Array)),n=r.length/s);return{buffer:r,size:s,count:n}}(e);return{value:r,size:s,bufferView:null,byteOffset:0,count:n,type:_(s),componentType:T(r)}}function I(e){if(!e)return!1;return Array.isArray(e)&&(e=e[0]),e.parseTextSync||e.parseSync||e.parse||e.loadAndParse||e.parseStream||e.parseInBatches||e.worker}function D(e){let t;return h(I(e)),Array.isArray(e)&&(t=e[1],e=e[0],e={...e,options:{...e.options,...t}}),e.extension&&(e.extensions=e.extensions||e.extension,delete e.extension),Array.isArray(e.extensions)||(e.extensions=[e.extensions]),h(e.extensions&&e.extensions.length>0&&e.extensions[0]),e.parseTextSync&&(e.text=!0),e.text||(e.binary=!0),e}let F={};const $=/[^.]+$/;function N(e,t="",r=null,{nothrow:s=!1}={}){if(t=t||"",e&&!Array.isArray(e)){const t=e;return D(t),t}(function(e){for(const t of e)D(t)})(e=e||Object.values(F)),t=t.replace(/\?.*/,"");let n=null;if(!(n=(n=n||function(e,t){const r=t.match($),s=r&&r[0];return s&&function(e,t){t=t.toLowerCase();for(const r of e)for(const e of r.extensions)if(e.toLowerCase()===t)return r;return null}(e,s)}(e,t))||function(e,t){if(!t)return null;for(const r of e)if("string"==typeof t){if(W(t,r))return r}else if(ArrayBuffer.isView(t)){if(q(t.buffer,t.byteOffset,r))return r}else if(t instanceof ArrayBuffer){if(q(t,0,r))return r}return null}(e,r))){if(s)return null;throw new Error(`No valid loader found for ${t}`)}return n}function W(e,t){return t.testText&&t.testText(e)}function q(e,t,r){switch(Array.isArray(r.test)?"array":typeof r.test){case"function":return r.test(e,r);case"string":case"array":return(Array.isArray(r.test)?r.test:[r.test]).some(r=>{return r===function(e,t,r){if(e.byteLength<=t+r)return"";const s=new DataView(e);let n="";for(let e=0;e<r;e++)n+=String.fromCharCode(s.getUint8(t+e));return n}(e,t,r.length)});default:return!1}}class G{log(){}info(){}warn(){}error(){}}function X(e,t){return null===(e=Object.assign({},t&&t.DEFAULT_OPTIONS,t&&t.defaultOptions,t&&t.options,e,{dataType:"arraybuffer"})).log&&(e.log=new G),"log"in e||(e.log=console),e}var z=r(0);const J="Cannot convert supplied data type";function H(e,t){if(t.text&&"string"==typeof e)return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){const r=e.buffer||e;if(t.text&&!t.binary){return new TextDecoder("utf8").decode(r)}return r}throw new Error(J)}async function K(e,t){const r=(e=await e)instanceof ArrayBuffer||ArrayBuffer.isView(e);if("string"==typeof e||r)return H(e,t);if(u(e)&&(e=await g(e)),o(e))return await async function(e){if(!e.ok){let t=`fetch failed ${e.status} `;try{t+=await e.text()}catch(e){}throw new Error(t)}}(e),t.binary?await e.arrayBuffer():await e.text();throw new Error(J)}var Q=r(4);function Y(e){if(Q.toArrayBuffer&&(e=Object(Q.toArrayBuffer)(e)),e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return e.buffer;if("string"==typeof e){const t=e;return(new TextEncoder).encode(t).buffer}return h(!1)}function Z(e,t=!0,r=[]){if(e){if(e instanceof ArrayBuffer)r.push(e);else if(e.buffer&&e.buffer instanceof ArrayBuffer)r.push(e.buffer);else if(t&&"object"==typeof e)for(const s in e)Z(e[s],t,r)}else;return r}const ee=new Map;let te=0;function re({data:e,resolve:t}){t(e)}class se{constructor({source:e,name:t=`web-worker-${te++}`,onMessage:r}){const s=function(e){if(h("string"==typeof e,"worker source"),e.startsWith("url(")&&e.endsWith(")"))return e.match(/^url\((.*)\)$/)[1];let t=ee.get(e);if(!t){const r=new Blob([e],{type:"application/javascript"});t=URL.createObjectURL(r),ee.set(e,t)}return t}(e);this.worker=new Worker(s,{name:t}),this.name=t,this.onMessage=r||re}async process(e){return new Promise((t,r)=>{this.worker.onmessage=e=>this.onMessage({worker:this.worker,data:e.data,resolve:t,reject:r}),this.worker.onerror=e=>r(e);const s=Z(e);this.worker.postMessage(e,s)})}destroy(){this.worker.terminate(),this.worker=null}}class ne{constructor({source:e,name:t="unnamed",maxConcurrency:r=1,onMessage:s,onDebug:n=(()=>{})}){this.source=e,this.name=t,this.maxConcurrency=r,this.onMessage=s,this.onDebug=n,this.jobQueue=[],this.idleQueue=[],this.count=0,this.isDestroyed=!1}destroy(){this.idleQueue.forEach(e=>e.destroy()),this.isDestroyed=!0}async process(e,t){return new Promise((r,s)=>{this.jobQueue.push({data:e,jobName:t,resolve:r,reject:s}),this._startQueuedJob()})}_startQueuedJob(){if(!this.jobQueue.length)return;const e=this._getAvailableWorker();if(!e)return;const t=this.jobQueue.shift();this.onDebug({message:"processing",worker:e.name,job:t.jobName,backlog:this.jobQueue.length}),e.process(t.data).then(e=>t.resolve(e)).catch(e=>t.reject(e)).then(()=>this._onWorkerDone(e))}_onWorkerDone(e){this.isDestroyed?e.destroy():(this.idleQueue.push(e),this._startQueuedJob())}_getAvailableWorker(){if(this.idleQueue.length>0)return this.idleQueue.shift();if(this.count<this.maxConcurrency){this.count++;const e=`${this.name.toLowerCase()}-worker-${this.count}-of-${this.maxConcurrency}`;return new se({source:this.source,onMessage:this.onMessage,name:e})}return null}}const ie=5;class oe{constructor({maxConcurrency:e=ie,onMessage:t,onDebug:r=(()=>{})}){this.maxConcurrency=e,this.onMessage=t,this.onDebug=r,this.workerPools=new Map}setProps(e){"maxConcurrency"in e&&(this.maxConcurrency=e.maxConcurrency),"onDebug"in e&&(this.onDebug=e.onDebug)}destroy(){this.workerPools.forEach(e=>e.destroy())}async process(e,t,r){return this._getWorkerPool(e,t).process(r)}_getWorkerPool(e,t){let r=this.workerPools.get(t);return r||(r=new ne({source:e,name:t,onMessage:this.onMessage,maxConcurrency:this.maxConcurrency,onDebug:this.onDebug}),this.workerPools.set(t,r)),r}}let ue=null;async function ae({worker:e,data:t,resolve:r,reject:s}){switch(t.type){case"done":r(t.result);break;case"process":try{const r=await ce(t.arraybuffer,t.options,t.url);e.postMessage({type:"process-done",id:t.id,result:r},Z(r))}catch(r){e.postMessage({type:"process-error",id:t.id,message:r.message})}break;case"error":s(t.message)}}function fe(e,t,r,s={}){const n=function(e={}){const t={};return e.maxConcurrency&&(t.maxConcurrency=e.maxConcurrency),e.onDebug&&(t.onDebug=e.onDebug),(ue=ue||new oe({onMessage:ae})).setProps(t),ue}(s);return s=JSON.parse(JSON.stringify(s)),n.process(e,`loaders.gl-${t}`,{arraybuffer:Y(r),options:s,source:"loaders.gl",type:"process"})}async function ce(e,t,r,s){!t||Array.isArray(t)||I(t)||(s=r,r=t,t=null),r=r||{};const n=function(e,t){return o(e)?t=t||e.url:u(t)&&(t=t.name),"string"==typeof t?t.replace(/\?.*/,""):t}(e,s),i=N(t,n,e);return r=X(r,i),await async function(e,t,r,s){return e=await K(e,t),t.parseTextSync&&"string"==typeof e?(r.dataType="text",t.parseTextSync(e,r,s,t)):t.parse?await t.parse(e,r,s,t):t.parseSync?t.parseSync(e,r,s,t):t.worker?await fe(t.worker,t.name,e,r):h(!1)}(e,i,r,n)}async function he(e,t,r){const n=t.getObjectExtension(e,s),i=t.getTypedArrayForBufferView(n.bufferView),o=new Uint8Array(i.buffer).subarray(i.byteOffset),u=new Uint8Array(o),a=await ce(u);e.attributes=P(a.attributes),a.indices&&(e.indices=M(a.indices)),function(e){if(!e.attributes&&Object.keys(e.attributes).length>0)throw new Error("Empty glTF primitive detected: Draco decompression failure?")}(e)}function le(e,t,r=4,n={}){if(!n.DracoWriter||!n.DracoLoader)throw new Error("DracoWriter/DracoLoader not available");const i=n.DracoWriter.encodeSync({attributes:e}),o=n.DracoLoader.parseSync({attributes:e}),u=n._addFauxAttributes(o.attributes),a=n.addBufferView(i);return{primitives:[{attributes:u,mode:r,extensions:{[s]:{bufferView:a,attributes:u}}}]}}const ge={KHR_draco_mesh_compression:class{static get name(){return s}static async decode(e,t={}){if(!t.decompress)return;const r=new C(e),n=[];for(const e of function*(e){for(const t of e.json.meshes||[])for(const e of t.primitives)yield e}(r))r.getObjectExtension(e,s)&&n.push(he(e,r,t));await Promise.all(n),r.removeExtension(s)}static decodeSync(e,t){if(!t.decompress)return;if(new C(e).getRequiredExtension(s))throw new Error("Cannot synchronously decode Draco")}static encode(e,t={}){const r=new C(e);for(const e of r.json.meshes||[])le(e,t),r.addRequiredExtension(s)}},KHR_lights_punctual:class{static get name(){return i}static decode(e,t){const r=new C(e),s=r.getExtension(i);s&&(r.json.lights=s.lights,r.removeExtension(i));for(const e of r.nodes||[]){const t=e.extensions&&e.extensions.KHR_lights_punctual;t&&(e.light=r._get("lights",t.light),delete e.extensions.KHR_lights_punctual)}}static encode(e,t){const r=new C(e),{json:s}=r;if(s.lights){const e=r.addExtensions(i);y(!e.lights),e.lights=s.lights,delete s.lights}if(r.json.lights){for(const e of r.json.lights){const t=e.node;r.addObjectExtension(t,i,e)}delete r.json.lights}}}};function de(e,t){if(!e)throw new Error(t||"loader assertion failed.")}const ye=1735152710,me=12,be=8,pe=1313821514,we=5130562,xe=!0;function _e(e,t=0,r={}){const s=new DataView(e),{magic:n=ye}=r,i=s.getUint32(t,!1);return i===n||i===ye}function Te(e,t,r=0,s={}){const n=new DataView(t);e.type=function(e,t=0){return`${String.fromCharCode(e.getUint8(t+0))}${String.fromCharCode(e.getUint8(t+1))}${String.fromCharCode(e.getUint8(t+2))}${String.fromCharCode(e.getUint8(t+3))}`}(n,r+0),e.version=n.getUint32(r+4,xe);const i=n.getUint32(r+8,xe);return e.header={byteOffset:r,byteLength:i},"glTF"!==e.type&&console.warn(`Invalid GLB magic string ${e.type}`),de(2===e.version,`Invalid GLB version ${e.version}. Only .glb v2 supported`),de(e.header.byteLength>me+be),e.json={},e.hasBinChunk=!1,e.binChunks=[],function(e,t,r,s){for(;r+8<=e.header.byteLength;){const n=t.getUint32(r+0,xe),i=t.getUint32(r+4,xe);switch(r+=be,i){case pe:Ae(e,t,r,n,s);break;case we:je(e,t,r,n,s)}switch(i){case 0:s.strict||Ae(e,t,r,n,s);break;case 1:s.strict||je(e,t,r,n,s)}r+=S(n)}}(e,n,r+12,s),function(e){e.byteOffset=e.header.byteOffset,e.magic=e.header.magic,e.version=e.header.version,e.byteLength=e.header.byteLength,e.hasBinChunk=e.binChunks.length>=1,e.binChunkByteOffset=e.header.hasBinChunk?e.binChunks[0].byteOffset:0,e.binChunkLength=e.header.hasBinChunk?e.binChunks[0].byteLength:0}(e),r+e.header.byteLength}function Ae(e,t,r,s,n){const i=new Uint8Array(t.buffer,r,s),o=new TextDecoder("utf8").decode(i);e.json=JSON.parse(o)}function je(e,t,r,s,n){e.header.hasBinChunk=!0,e.binChunks.push({byteOffset:r,byteLength:s,arrayBuffer:t.buffer})}const Ee={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},ve={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},Be={TEXTURE_MAG_FILTER:10240,TEXTURE_MIN_FILTER:10241,TEXTURE_WRAP_S:10242,TEXTURE_WRAP_T:10243,REPEAT:10497,LINEAR:9729,NEAREST_MIPMAP_LINEAR:9986},Re={magFilter:Be.TEXTURE_MAG_FILTER,minFilter:Be.TEXTURE_MIN_FILTER,wrapS:Be.TEXTURE_WRAP_S,wrapT:Be.TEXTURE_WRAP_T},Le={[Be.TEXTURE_MAG_FILTER]:Be.LINEAR,[Be.TEXTURE_MIN_FILTER]:Be.NEAREST_MIPMAP_LINEAR,[Be.TEXTURE_WRAP_S]:Be.REPEAT,[Be.TEXTURE_WRAP_]:Be.REPEAT};class Ue{postProcess(e,t={}){const{json:r,buffers:s=[],images:n=[],baseUri:i=""}=e;return y(r),this.baseUri=i,this.json=r,this.buffers=s,this.images=n,this._resolveTree(this.json,t),this.json}_resolveTree(e,t={}){e.bufferViews&&(e.bufferViews=e.bufferViews.map((e,t)=>this._resolveBufferView(e,t))),e.images&&(e.images=e.images.map((e,r)=>this._resolveImage(e,r,t))),e.samplers&&(e.samplers=e.samplers.map((e,t)=>this._resolveSampler(e,t))),e.textures&&(e.textures=e.textures.map((e,t)=>this._resolveTexture(e,t))),e.accessors&&(e.accessors=e.accessors.map((e,t)=>this._resolveAccessor(e,t))),e.materials&&(e.materials=e.materials.map((e,t)=>this._resolveMaterial(e,t))),e.meshes&&(e.meshes=e.meshes.map((e,t)=>this._resolveMesh(e,t))),e.nodes&&(e.nodes=e.nodes.map((e,t)=>this._resolveNode(e,t))),e.skins&&(e.skins=e.skins.map((e,t)=>this._resolveSkin(e,t))),e.scenes&&(e.scenes=e.scenes.map((e,t)=>this._resolveScene(e,t))),void 0!==e.scene&&(e.scene=e.scenes[this.json.scene])}getScene(e){return this._get("scenes",e)}getNode(e){return this._get("nodes",e)}getSkin(e){return this._get("skins",e)}getMesh(e){return this._get("meshes",e)}getMaterial(e){return this._get("materials",e)}getAccessor(e){return this._get("accessors",e)}getCamera(e){return null}getTexture(e){return this._get("textures",e)}getSampler(e){return this._get("samplers",e)}getImage(e){return this._get("images",e)}getBufferView(e){return this._get("bufferViews",e)}getBuffer(e){return this._get("buffers",e)}_get(e,t){if("object"==typeof t)return t;const r=this.json[e]&&this.json[e][t];return r||console.warn(`glTF file error: Could not find ${e}[${t}]`),r}_resolveScene(e,t){return e.id=e.id||`scene-${t}`,e.nodes=(e.nodes||[]).map(e=>this.getNode(e)),e}_resolveNode(e,t){return e.id=e.id||`node-${t}`,e.children&&(e.children=e.children.map(e=>this.getNode(e))),void 0!==e.mesh&&(e.mesh=this.getMesh(e.mesh)),void 0!==e.camera&&(e.camera=this.getCamera(e.camera)),void 0!==e.skin&&(e.skin=this.getSkin(e.skin)),e}_resolveSkin(e,t){return e.id=e.id||`skin-${t}`,e.inverseBindMatrices=this.getAccessor(e.inverseBindMatrices),e}_resolveMesh(e,t){return e.id=e.id||`mesh-${t}`,e.primitives&&(e.primitives=e.primitives.map(e=>{const t=(e={...e}).attributes;e.attributes={};for(const r in t)e.attributes[r]=this.getAccessor(t[r]);return void 0!==e.indices&&(e.indices=this.getAccessor(e.indices)),void 0!==e.material&&(e.material=this.getMaterial(e.material)),e})),e}_resolveMaterial(e,t){if(e.id=e.id||`material-${t}`,e.normalTexture&&(e.normalTexture={...e.normalTexture},e.normalTexture.texture=this.getTexture(e.normalTexture.index)),e.occlusionTexture&&(e.occlustionTexture={...e.occlustionTexture},e.occlusionTexture.texture=this.getTexture(e.occlusionTexture.index)),e.emissiveTexture&&(e.emmisiveTexture={...e.emmisiveTexture},e.emissiveTexture.texture=this.getTexture(e.emissiveTexture.index)),e.pbrMetallicRoughness){e.pbrMetallicRoughness={...e.pbrMetallicRoughness};const t=e.pbrMetallicRoughness;t.baseColorTexture&&(t.baseColorTexture={...t.baseColorTexture},t.baseColorTexture.texture=this.getTexture(t.baseColorTexture.index)),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture={...t.metallicRoughnessTexture},t.metallicRoughnessTexture.texture=this.getTexture(t.metallicRoughnessTexture.index))}return e}_resolveAccessor(e,t){var r,s;return e.id=e.id||`accessor-${t}`,void 0!==e.bufferView&&(e.bufferView=this.getBufferView(e.bufferView)),e.bytesPerComponent=(r=e.componentType,ve[r]),e.components=(s=e.type,Ee[s]),e.bytesPerElement=e.bytesPerComponent*e.components,e}_resolveTexture(e,t){return e.id=e.id||`texture-${t}`,e.sampler="sampler"in e?this.getSampler(e.sampler):Le,e.source=this.getImage(e.source),e}_resolveSampler(e,t){e.id=e.id||`sampler-${t}`,e.parameters={};for(const t in e){const r=this._enumSamplerParameter(t);void 0!==r&&(e.parameters[r]=e[t])}return e}_enumSamplerParameter(e){return Re[e]}_resolveImage(e,t,r){if(e.id=e.id||`image-${t}`,void 0!==e.bufferView&&(e.bufferView=this.getBufferView(e.bufferView)),"uri"in e){const s=this.images[t];s&&s.image&&(e.image=s.image,delete e.uri);const n=r.uri||this.baseUri;if(n){const t=e.uri;e.uri=j(e.uri,n),e.originalUri=t,e.baseUri=n,e.fullUri=e.uri}}return e.getImageAsync=()=>e.bufferView?new Promise(t=>{const r=this.getBufferView(e.bufferView),s=e.mimeType||"image/jpeg",n=new Blob([r.data],{type:s}),i=(self.URL||self.webkitURL).createObjectURL(n),o=new Image;o.onload=()=>t(o),o.src=i}):e.uri?new Promise(t=>{const r=new Image;r.crossOrigin="anonymous",r.onload=()=>t(r),r.src=e.fullUri||e.uri}):null,e}_resolveBufferView(e,t){e.id=e.id||`bufferView-${t}`;const r=e.buffer;e.buffer=this.getBuffer(r);const s=this.buffers[r].arrayBuffer;let n=this.buffers[r].byteOffset||0;return"byteOffset"in e&&(n+=e.byteOffset),e.data=new Uint8Array(s,n,e.byteLength),e}_resolveCamera(e,t){return e.id=e.id||`camera-${t}`,e.perspective,e.orthographic,e}}function Oe(e,t){return(new Ue).postProcess(e,t)}const Ve={fetchLinkedResources:!0,fetchImages:!1,createImages:!1,fetch:d,decompress:!1,DracoLoader:null,postProcess:!1,log:console};async function Se(e,t,r=0,s={}){Ce(e,t,r,s={...Ve,...s});const n=[];if(s.fetchImages){const t=async function(e,t){const r=e.json.images||[],s=[];for(let n=0;n<r.length;++n){const i=r[n];"uri"in i&&s.push(Pe(e,i,n,t))}return await Promise.all(s)}(e,s);n.push(t)}s.fetchLinkedResources&&await async function(e,t){for(let r=0;r<e.json.buffers.length;++r){const s=e.json.buffers[r];if(t.uri||console.warn("options.uri must be set to decode embedded glTF buffers"),s.uri&&t.uri){const n=t.fetch||window.fetch;y(n);const i=j(s.uri,t.uri),o=await n(i),u=await o.arrayBuffer();e.buffers[r]={arrayBuffer:u,byteOffset:0,byteLength:u.byteLength},delete s.uri}}}(e,s);const i=async function(e,t){for(const r in ge){if(!(r in t&&!t[r])){const s=ge[r];await s.decode(e,t)}}}(e,s);return n.push(i),await Promise.all(n),s.postProcess?Oe(e,s):e}function ke(e,t,r=0,s={}){return Ce(e,t,r,s={...Ve,...s}),s.fetchLinkedResources&&function(e,t){for(const t of e.json.buffers||[])if(t.uri)throw new Error("parseGLTFSync: Cannot decode uri buffers")}(e),s.decodeExtensions&&function(e,t){for(const r in ge){if(!(r in t&&!t[r])){ge[r].decodeSync(e,t)}}}(e,s),s.postProcess?Oe(e,s):e}function Ce(e,t,r,s){if(s.uri&&(e.baseUri=s.uri),t instanceof ArrayBuffer&&!_e(t,r,s)){t=(new TextDecoder).decode(t)}"string"==typeof t?e.json=JSON.parse(t):t instanceof ArrayBuffer?(e._glb={},r=Te(e._glb,t,r,s),e.json=e._glb.json):e.json=t;const n=e.json.buffers||[];e.buffers=new Array(n.length).fill({}),e._glb&&e._glb.hasBinChunk&&(e.buffers[0]={arrayBuffer:e._glb.binChunks[0].arrayBuffer,byteOffset:e._glb.binChunks[0].byteOffset,byteLength:e._glb.binChunks[0].byteLength},e.json.buffers[0].data=e.buffers[0].arrayBuffer,e.json.buffers[0].byteOffset=e.buffers[0].byteOffset);const i=e.json.images||[];e.images=new Array(i.length).fill({})}async function Pe(e,t,r,s){y(s.fetch||window.fetch);const n=j(t.uri,s.uri);e.images[r]=await new Promise((e,t)=>{const r=new Image;r.crossOrigin="anonymous",r.onload=()=>e(r),r.onerror=e=>t(e),r.src=n})}z.a.TextEncoder;const Me=z.a.TextDecoder;function Ie(e,t,r={}){return function e(t,r,s,n={}){const i=t;const o=function(e,t){const r=function(e){if("string"==typeof e){if(0===e.indexOf("##/"))return e.slice(1);let t=e.match(/#\/([a-z]+)\/([0-9]+)/);if(t){const e=parseInt(t[2],10);return[t[1],e]}if(t=e.match(/\$\$\$([0-9]+)/)){return["accessors",parseInt(t[1],10)]}}return null}(e);if(r){const[s,n]=r,i=t[s]&&t[s][n];if(i)return i;console.error(`Invalid JSON pointer ${e}: #/${s}/${n}`)}return null}(i,s);if(o)return o;if(Array.isArray(i))return i.map(t=>e(t,r,s,n));if(null!==i&&"object"==typeof i){const t={};for(const o in i)t[o]=e(i[o],r,s,n);return t}return i}(e,e,t,r)}function De(e,t,r){r&&(e=function(e,t){const r=e.byteLength-t,s=new ArrayBuffer(r),n=new Uint8Array(e),i=new Uint8Array(s);for(let e=0;e<r;e++)i[e]=n[t+e];return s}(e,r));const s=t.bufferViews||[];for(let e=0;e<s.length;++e){y(s[e].byteLength>=0)}return{accessors:Fe(e,s,t),images:$e(e,s,t)}}function Fe(e,t,r){const s=r.accessors||[],n=[];for(let r=0;r<s.length;++r){const i=s[r];y(i);const o=t[i.bufferView];if(o){const{ArrayType:t,length:r}=A(i,o),s=new t(e,o.byteOffset,r);s.accessor=i,n.push(s)}}return n}function $e(e,t,r){const s=r.images||[],n=[];for(let r=0;r<s.length;++r){const i=s[r];y(i);const o=t[i.bufferView];y(o);const u=new Uint8Array(e,o.byteOffset,o.byteLength);u.imate=i,n.push(u)}return n}class Ne{static isGLB(e,t={}){return _e(e,0)}parse(e,t={}){return this.parseSync(e,t)}parseSync(e,t={}){if(this.glbArrayBuffer=e,this.binaryByteOffset=null,this.packedJson=null,this.json=null,null===this.json&&null===this.binaryByteOffset){const e=0;Te(this,this.glbArrayBuffer,e,t),this.binaryByteOffset=this.binChunkByteOffset,this.packedJson=this.json;const r=De(this.glbArrayBuffer,this.json,this.binaryByteOffset);this.json=Ie(this.json,r),this.unpackedBuffers=r}return this}getApplicationData(e){return this.json[e]}getJSON(){return this.json}getArrayBuffer(){return this.glbArrayBuffer}getBinaryByteOffset(){return this.binaryByteOffset}getBufferView(e){const t=(e.byteOffset||0)+this.binaryByteOffset;return new Uint8Array(this.glbArrayBuffer,t,e.byteLength)}getBuffer(e){const t=x[e.componentType],r=p[e.type],s=w[e.componentType],n=e.count*r,i=e.count*r*s,o=this.json.bufferViews[e.bufferView];y(i>=0&&e.byteOffset+i<=o.byteLength);const u=o.byteOffset+this.binaryByteOffset+e.byteOffset;return new t(this.glbArrayBuffer,u,n)}getImageData(e){return{typedArray:this.getBufferView(e.bufferView),mimeType:e.mimeType||"image/jpeg"}}getImage(e){const t=this.getBufferView(e.bufferView),r=e.mimeType||"image/jpeg",s=new Blob([t],{type:r}),n=(self.URL||self.webkitURL).createObjectURL(s),i=new Image;return i.src=n,i}getImageAsync(e){return new Promise(t=>{const r=this.getBufferView(e.bufferView),s=e.mimeType||"image/jpeg",n=new Blob([r],{type:s}),i=(self.URL||self.webkitURL).createObjectURL(n),o=new Image;o.onload=()=>t(o),o.src=i})}}const We={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},qe={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},Ge={TEXTURE_MAG_FILTER:10240,TEXTURE_MIN_FILTER:10241,TEXTURE_WRAP_S:10242,TEXTURE_WRAP_T:10243,REPEAT:10497,LINEAR:9729,NEAREST_MIPMAP_LINEAR:9986},Xe={magFilter:Ge.TEXTURE_MAG_FILTER,minFilter:Ge.TEXTURE_MIN_FILTER,wrapS:Ge.TEXTURE_WRAP_S,wrapT:Ge.TEXTURE_WRAP_T},ze={[Ge.TEXTURE_MAG_FILTER]:Ge.LINEAR,[Ge.TEXTURE_MIN_FILTER]:Ge.NEAREST_MIPMAP_LINEAR,[Ge.TEXTURE_WRAP_S]:Ge.REPEAT,[Ge.TEXTURE_WRAP_]:Ge.REPEAT};class Je{postProcess(e,t,r={}){return this.gltf=e,this.glbParser=t,this._resolveToTree(r),this.gltf}_resolveToTree(e={}){const{gltf:t}=this;return(t.bufferViews||[]).forEach((e,t)=>this._resolveBufferView(e,t)),(t.images||[]).forEach((t,r)=>this._resolveImage(t,r,e)),(t.samplers||[]).forEach((e,t)=>this._resolveSampler(e,t)),(t.textures||[]).forEach((e,t)=>this._resolveTexture(e,t)),(t.accessors||[]).forEach((e,t)=>this._resolveAccessor(e,t)),(t.materials||[]).forEach((e,t)=>this._resolveMaterial(e,t)),(t.meshes||[]).forEach((e,t)=>this._resolveMesh(e,t)),(t.nodes||[]).forEach((e,t)=>this._resolveNode(e,t)),(t.skins||[]).forEach((e,t)=>this._resolveSkin(e,t)),(t.scenes||[]).forEach((e,t)=>this._resolveScene(e,t)),void 0!==t.scene&&(t.scene=t.scenes[this.gltf.scene]),this._process_extension_KHR_lights_punctual(),t}getScene(e){return this._get("scenes",e)}getNode(e){return this._get("nodes",e)}getSkin(e){return this._get("skins",e)}getMesh(e){return this._get("meshes",e)}getMaterial(e){return this._get("materials",e)}getAccessor(e){return this._get("accessors",e)}getCamera(e){return null}getTexture(e){return this._get("textures",e)}getSampler(e){return this._get("samplers",e)}getImage(e){return this._get("images",e)}getBufferView(e){return this._get("bufferViews",e)}getBuffer(e){return this._get("buffers",e)}_get(e,t){if("object"==typeof t)return t;const r=this.gltf[e]&&this.gltf[e][t];return r||console.warn(`glTF file error: Could not find ${e}[${t}]`),r}_resolveScene(e,t){e.id=`scene-${t}`,e.nodes=(e.nodes||[]).map(e=>this.getNode(e))}_resolveNode(e,t){e.id=`node-${t}`,e.children=(e.children||[]).map(e=>this.getNode(e)),void 0!==e.mesh&&(e.mesh=this.getMesh(e.mesh)),void 0!==e.camera&&(e.camera=this.getCamera(e.camera)),void 0!==e.skin&&(e.skin=this.getSkin(e.skin))}_resolveSkin(e,t){e.id=`skin-${t}`,e.inverseBindMatrices=this.getAccessor(e.inverseBindMatrices)}_resolveMesh(e,t){e.id=`mesh-${t}`;for(const t of e.primitives){for(const e in t.attributes)t.attributes[e]=this.getAccessor(t.attributes[e]);void 0!==t.indices&&(t.indices=this.getAccessor(t.indices)),void 0!==t.material&&(t.material=this.getMaterial(t.material))}}_resolveMaterial(e,t){if(e.id=`material-${t}`,e.normalTexture&&(e.normalTexture.texture=this.getTexture(e.normalTexture.index)),e.occlusionTexture&&(e.occlusionTexture.texture=this.getTexture(e.occlusionTexture.index)),e.emissiveTexture&&(e.emissiveTexture.texture=this.getTexture(e.emissiveTexture.index)),e.pbrMetallicRoughness){const t=e.pbrMetallicRoughness;t.baseColorTexture&&(t.baseColorTexture.texture=this.getTexture(t.baseColorTexture.index)),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.texture=this.getTexture(t.metallicRoughnessTexture.index))}}_resolveAccessor(e,t){e.id=`accessor-${t}`,void 0!==e.bufferView&&(e.bufferView=this.getBufferView(e.bufferView)),e.bytesPerComponent=qe[e],e.components=We[e],e.bytesPerElement=e.bytesPerComponent*e.components}_resolveTexture(e,t){e.id=`texture-${t}`,e.sampler="sampler"in e?this.getSampler(e.sampler):ze,e.source=this.getImage(e.source)}_resolveSampler(e,t){e.id=`sampler-${t}`,e.parameters={};for(const t in e){const r=this._enumSamplerParameter(t);void 0!==r&&(e.parameters[r]=e[t])}}_enumSamplerParameter(e){return Xe[e]}_resolveImage(e,t,r){e.id=`image-${t}`,void 0!==e.bufferView&&(e.bufferView=this.getBufferView(e.bufferView));const{createImages:s=!0}=r;s?e.image=this.glbParser.getImage(e):e.getImageAsync=()=>this.glbParser?this.glbParser.getImageAsync(e):e.uri?new Promise(t=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>t(s),s.src=j(e.uri,r.uri)}):null}_resolveBufferView(e,t){if(e.id=`bufferView-${t}`,e.buffer=this.getBuffer(e.buffer),this.glbParser)e.data=this.glbParser.getBufferView(e);else{const t=e.byteOffset||0;e.data=new Uint8Array(e.buffer.data,t,e.byteLength)}}_resolveCamera(e){e.perspective,e.orthographic}_process_extension_KHR_lights_punctual(){const{gltf:e}=this,t=e.extensions&&e.extensions.KHR_lights_punctual;t&&(e.lights=t.lights),this._removeExtension("KHR_lights_punctual");for(const t of e.nodes||[]){const e=t.extensions&&t.extensions.KHR_lights_punctual;e&&(t.light=this._get("lights",e.light),delete t.extensions.KHR_lights_punctual)}delete e.lights}_removeExtension(e){this.gltf.extensionsRequired&&this._removeStringFromArray(this.gltf.extensionsRequired,e),this.gltf.extensionsUsed&&this._removeStringFromArray(this.gltf.extensionsUsed,e),this.gltf.extensions&&delete this.gltf.extensions[e]}_removeStringFromArray(e,t){let r=!0;for(;r;){const s=e.indexOf(t);s>-1?e.splice(s,1):r=!1}}}const He={fetchLinkedResources:!0,fetch:d,decompress:!1,DracoLoader:null,postProcess:!0,createImages:!1,log:console};class Ke{async parse(e,t={}){if(t=Object.assign({},He,t),this.parseSync(e,{...t,postProcess:!1,decompress:!1}),t.fetchLinkedResources&&await this._loadLinkedAssets(t),t.decompress&&this._decompressMeshes(t),t.postProcess){(new Je).postProcess(this.gltf,this.glbParser,t)}return this.gltf}parseSync(e,t={}){if(t=Object.assign({},He,t),e instanceof ArrayBuffer&&!Ne.isGLB(e,t)){e=(new Me).decode(e)}if("string"==typeof e&&(e=JSON.parse(e)),e instanceof ArrayBuffer?(this.glbParser=new Ne,this.gltf=this.glbParser.parseSync(e).json,this.json=this.gltf):(this.glbParser=null,this.gltf=e,this.json=e),t.decompress&&this._decompressMeshes(t),t.postProcess){(new Je).postProcess(this.gltf,this.glbParser,t)}return this.gltf}getApplicationData(e){return this.json[e]}getExtraData(e){return(this.json.extras||{})[e]}getExtension(e){const t=this.getUsedExtensions().find(t=>t===e),r=this.json.extensions||{};return t?r[e]||!0:null}getRequiredExtension(e){return this.getRequiredExtensions().find(t=>t===e)?this.getExtension(e):null}getRequiredExtensions(){return this.json.extensionsRequired||[]}getUsedExtensions(){return this.json.extensionsUsed||[]}getScene(e){return this._get("scenes",e)}getNode(e){return this._get("nodes",e)}getSkin(e){return this._get("skins",e)}getMesh(e){return this._get("meshes",e)}getMaterial(e){return this._get("materials",e)}getAccessor(e){return this._get("accessors",e)}getCamera(e){return null}getTexture(e){return this._get("textures",e)}getSampler(e){return this._get("samplers",e)}getImage(e){return this._get("images",e)}getBufferView(e){return this._get("bufferViews",e)}getBuffer(e){return this._get("buffers",e)}_get(e,t){if("object"==typeof t)return t;const r=this.gltf[e]&&this.gltf[e][t];return r||console.warn(`glTF file error: Could not find ${e}[${t}]`),r}async _loadLinkedAssets(e){return await Promise.all(this.gltf.buffers.map(t=>this._loadBuffer(t,e)))}async _loadBuffer(e,t){if(e.uri&&t.uri){const r=t.fetch||window.fetch,s=j(e.uri,t.uri),n=await r(s),i=await n.arrayBuffer();e.data=i,e.uri=null}}_decompressMeshes(e){if(e.DracoLoader&&e.decompress){for(const t of this.gltf.meshes||[])for(const r of t.primitives)if(this._decompressKhronosDracoPrimitive(r,e),this._decompressUberDracoPrimitive(r,e),!r.attributes||0===Object.keys(r.attributes).length)throw new Error("Empty glTF primitive: decompression failure?");this._removeExtension(s),this._removeExtension(n)}}_decompressKhronosDracoPrimitive(e,t){const r=e.extensions&&e.extensions[s];if(!r)return;delete e.extensions[s];const n=this._getBufferViewArray(r.bufferView),i=t.DracoLoader.parseSync(n);e.attributes=P(i.attributes),i.indices&&(e.indices=M(i.indices))}_decompressUberDracoPrimitive(e,t){const r=e.extensions&&e.extensions[n];if(!r)return;if(0!==e.mode)throw new Error(n);delete e.extensions[n];const s=this._getBufferViewArray(r.bufferView),i=t.DracoLoader.parseSync(s);e.attributes=i.attributes}_getBufferViewArray(e){const t=this.gltf.bufferViews[e];if(this.glbParser)return this.glbParser.getBufferView(t);const r=this.gltf.buffers[t.buffer].data,s=t.byteOffset||0;return new Uint8Array(r,s,t.byteLength)}_removeExtension(e){this.json.extensionsRequired&&this._removeStringFromArray(this.json.extensionsRequired,e),this.json.extensionsUsed&&this._removeStringFromArray(this.json.extensionsUsed,e),this.json.extensions&&delete this.json.extensions[e]}_removeStringFromArray(e,t){let r=!0;for(;r;){const s=e.indexOf(t);s>-1?e.splice(s,1):r=!1}}}const Qe={gltf:{parserVersion:1},uri:""};var Ye={name:"glTF",extensions:["gltf","glb"],text:!0,binary:!0,test:"glTF",parse:async function(e,t={}){if(2!==(t={...Qe,...t}).gltf.parserVersion&&!1!==t.useGLTFParser){return(new Ke).parse(e,t)}const{byteOffset:r=0}=t;return await Se({},e,r,t)},parseSync:function(e,t={}){if(2!==(t={...Qe,...t}).gltf.parserVersion&&!1!==t.useGLTFParser)return(new Ke).parseSync(e,t);const{byteOffset:r=0}=t;return ke({},e,r,t)},defaultOptions:Qe};function Ze(e,t,r,s){const n=S(r.byteLength),i=n-r.byteLength;if(e){const s=new Uint8Array(e.buffer,e.byteOffset+t,r.byteLength),n=new Uint8Array(r);s.set(n);for(let s=0;s<i;++s)e.setUint8(t+r.byteLength+s,32)}return t+=n}const et=1179937895,tt=1313821514,rt=5130562,st=!0;function nt(e,t,r=0,s={}){const{magic:n=et,version:i=2,json:o={},binary:u}=e,a=r;t&&(t.setUint32(r+0,n,st),t.setUint32(r+4,i,st),t.setUint32(r+8,0,st));const f=r+8,c=r+=12;if(t&&(t.setUint32(r+0,0,st),t.setUint32(r+4,tt,st)),r=function(e,t,r,s){return t=Ze(e,t,(new TextEncoder).encode(r))}(t,r+=8,JSON.stringify(o)),t){const e=r-c-8;t.setUint32(c+0,e,st)}if(u){const e=r;if(t&&(t.setUint32(r+0,0,st),t.setUint32(r+4,rt,st)),r=Ze(t,r+=8,u),t){const s=r-e-8;t.setUint32(e+0,s,st)}}if(t){const e=r-a;t.setUint32(f,e,st)}return r}function it(e,t,r,s){return function(e,{firstBuffer:t=0}={}){if(e.buffers&&e.buffers.length>t)throw new Error("encodeGLTF: multiple buffers not yet implemented")}(e),nt(e,t,r,s)}var ot={name:"glTF",extensions:["glb"],encodeSync:function(e,t={}){const{byteOffset:r=0}=t,s=it(e,null,r,t),n=new ArrayBuffer(s);return it(e,new DataView(n),r,t),n},binary:!0,defaultOptions:{useGLTFBuilder:!0}},ut={name:"GLB",extension:["glb"],text:!0,binary:!0,parseSync:function(e,t){const{byteOffset:r=0}=t,s={};return Te(s,e,r,t),s},defaultOptions:{strict:!1}};var at={name:"GLB",extensions:["glb"],encodeSync:function(e,t){const{byteOffset:r=0}=t,s=nt(e,null,r,t),n=new ArrayBuffer(s),i=new DataView(n);return nt(e,i,r,t),n},binary:!0};function ft(e,t=Float32Array){if(0===e.length)return new Float32Array(0);if(!function e(t,r=Number.isFinite){let s=-1;for(;++s<t.length;){const n=t[s];if(Array.isArray(n)||ArrayBuffer.isView(n)){if(!e(n,r))return!1}else if(!r(n))return!1}return!0}(e))return null;const r=new t(function e(t,r=3){let s=0;let n=0;let i=-1;for(;++i<t.length;){const r=t[i];Array.isArray(r)||ArrayBuffer.isView(r)?s+=e(r):n++}return s+(0===s&&n<r?r:n)}(e));return function(e,t,r=3){(function e(t,r,s,n){let i=-1;let o=0;for(;++i<t.length;){const u=t[i];Array.isArray(u)||ArrayBuffer.isView(u)?n=e(u,r,s,n):o<s&&(r[n++]=u,o++)}o>0&&o<s&&(r[n++]=0);return n})(e,t,r,0)}(e,r),r}function ct(e,t,r={}){const{flattenArrays:s=!1}=r;let n=e;if("string"==typeof n&&0===n.indexOf("#/"))return`#${n}`;if(Array.isArray(n)){const e=s&&ft(n);if(!e)return n.map(e=>ct(e,t,r));n=e}if(ArrayBuffer.isView(n)&&t){if(t.isImage(n)){return`#/images/${t.addImage(n)}`}return`#/accessors/${t.addBuffer(n)}`}if(null!==n&&"object"==typeof n){const e={};for(const s in n)e[s]=ct(n[s],t,r);return e}return n}class ht{constructor(e={}){this.byteLength=0,this.json={buffers:[{byteLength:0}],bufferViews:[],accessors:[],images:[],meshes:[]},this.sourceBuffers=[],this.log=e.log||console}getByteLength(){return this.byteLength}isImage(e){return function(e,t){if(t){const{test:r}=O(t);return r(V(e))}return Boolean(L(e))}(e)}encodeSync(e={}){return this.encodeAsGLB(e)}encodeAsGLB(e={}){this._packBinaryChunk(),e.magic&&console.warn("Custom glTF magic number no longer supported");const t={version:2,json:this.json,binary:this.arrayBuffer},r=nt(t,null,0,e),s=new ArrayBuffer(r);return nt(t,new DataView(s),0,e),s}addApplicationData(e,t,r={}){const s=r.packTypedArrays?ct(t,this,r):t;return this.json[e]=s,this}addBuffer(e,t={size:3}){const r=this.addBufferView(e),s={size:t.size,componentType:T(e),count:Math.round(e.length/t.size)};return this.addAccessor(r,Object.assign(s,t))}addBufferView(e){const t=e.byteLength||e.length;return this.json.bufferViews.push({buffer:0,byteOffset:this.byteLength,byteLength:t}),this.byteLength+=S(t),this.sourceBuffers.push(e),this.json.bufferViews.length-1}addAccessor(e,t){return this.json.accessors.push({bufferView:e,type:_(t.size),componentType:t.componentType,count:t.count}),this.json.accessors.length-1}_pack(){return this._packBinaryChunk(),{arrayBuffer:this.arrayBuffer,json:this.json}}_packBinaryChunk(){if(this.arrayBuffer)return;const e=this.byteLength,t=new ArrayBuffer(e),r=new Uint8Array(t);let s=0;for(let e=0;e<this.sourceBuffers.length;e++){s=k(this.sourceBuffers[e],r,s)}this.json.buffers[0].byteLength=e,this.arrayBuffer=t,this.sourceBuffers=[]}_getInternalCounts(){return{buffers:this.json.buffers.length,bufferViews:this.json.bufferViews.length,accessors:this.json.accessors.length,images:this.json.images.length}}}class lt extends ht{constructor(e={}){super(e),this.DracoWriter=e.DracoWriter,this.DracoLoader=e.DracoLoader}addApplicationData(e,t,r={}){const s=r.packTypedArrays?ct(t,this,r):t;return this.json[e]=s,this}addExtraData(e,t,r={}){const s=r.packedTypedArrays?ct(t,this,r):t;return this.json.extras=this.json.extras||{},this.json.extras[e]=s,this}addExtension(e,t,r={}){y(t);const s=r.packTypedArrays?ct(t,this,r):t;return this.json.extensions=this.json.extensions||{},this.json.extensions[e]=s,this.registerUsedExtension(e),this}addRequiredExtension(e,t,r={}){y(t);const s=r.packTypedArrays?ct(t,this,r):t;return this.addExtension(e,s),this.registerRequiredExtension(e),this}registerUsedExtension(e){this.json.extensionsUsed=this.json.extensionsUsed||[],this.json.extensionsUsed.find(t=>t===e)||this.json.extensionsUsed.push(e)}registerRequiredExtension(e){this.registerUsedExtension(e),this.json.extensionsRequired=this.json.extensionsRequired||[],this.json.extensionsRequired.find(t=>t===e)||this.json.extensionsRequired.push(e)}addMesh(e,t,r=4){const s={primitives:[{attributes:this._addAttributes(e),indices:t,mode:r}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(s),this.json.meshes.length-1}addPointCloud(e){const t={primitives:[{attributes:this._addAttributes(e),mode:0}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(t),this.json.meshes.length-1}addCompressedMesh(e,t,r=4){if(!this.DracoWriter||!this.DracoLoader)throw new Error("DracoWriter/DracoLoader not available");this.registerRequiredExtension(s);const n=this.DracoWriter.encodeSync({attributes:e}),i=this.DracoLoader.parseSync({attributes:e}),o=this._addFauxAttributes(i.attributes),u=this.addBufferView(n),a={primitives:[{attributes:o,mode:r,extensions:{[s]:{bufferView:u,attributes:o}}}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(a),this.json.meshes.length-1}addCompressedPointCloud(e){if(!this.DracoWriter||!this.DracoLoader)throw new Error("DracoWriter/DracoLoader not available");e.mode=0;const t=this.DracoWriter.encodeSync(e,{pointcloud:!0}),r=this.addBufferView(t),s={primitives:[{attributes:{},mode:0,extensions:{[n]:{bufferView:r}}}]};return this.registerRequiredExtension(n),this.json.meshes=this.json.meshes||[],this.json.meshes.push(s),this.json.meshes.length-1}addImage(e){const t=this.addBufferView(e),r=U(e)||{};if(r){const{mimeType:e,width:s,height:n}=r;this.json.images.push({bufferView:t,mimeType:e,width:s,height:n})}else this.json.images.push({bufferView:t});return this.json.images.length-1}}r.d(t,"KHR_DRACO_MESH_COMPRESSION",function(){return s}),r.d(t,"UBER_POINT_CLOUD_EXTENSION",function(){return n}),r.d(t,"GLTFLoader",function(){return Ye}),r.d(t,"GLTFWriter",function(){return ot}),r.d(t,"GLBLoader",function(){return ut}),r.d(t,"GLBWriter",function(){return at}),r.d(t,"GLTFScenegraph",function(){return C}),r.d(t,"postProcessGLTF",function(){return Oe}),r.d(t,"parseGLTFSync",function(){return ke}),r.d(t,"encodeGLTFSync",function(){return it}),r.d(t,"packBinaryJson",function(){return ct}),r.d(t,"unpackBinaryJson",function(){return Ie}),r.d(t,"GLBParser",function(){return Ne}),r.d(t,"GLBBuilder",function(){return ht}),r.d(t,"GLTFParser",function(){return Ke}),r.d(t,"GLTFBuilder",function(){return lt})}])});

@@ -17,3 +17,6 @@ "use strict";

binary: true,
parseSync: parseSync
parseSync: parseSync,
defaultOptions: {
strict: false
}
};

@@ -20,0 +23,0 @@ exports["default"] = _default;

@@ -27,3 +27,6 @@ "use strict";

var DEFAULT_OPTIONS = {
useGLTFParser: true
gltf: {
parserVersion: 1
},
uri: ''
};

@@ -52,3 +55,3 @@

if (!options.useGLTFParser) {
if (!(options.gltf.parserVersion !== 2 && options.useGLTFParser !== false)) {
_context.next = 5;

@@ -68,3 +71,3 @@ break;

case 9:
return _context.abrupt("return", gltf);
return _context.abrupt("return", _context.sent);

@@ -85,3 +88,3 @@ case 10:

if (options.useGLTFParser) {
if (options.gltf.parserVersion !== 2 && options.useGLTFParser !== false) {
return new _gltfParser["default"]().parseSync(arrayBuffer, options);

@@ -94,4 +97,3 @@ }

var gltf = {};
(0, _parseGltf.parseGLTFSync)(gltf, arrayBuffer, byteOffset, options);
return gltf;
return (0, _parseGltf.parseGLTFSync)(gltf, arrayBuffer, byteOffset, options);
}

@@ -98,0 +100,0 @@

@@ -12,2 +12,6 @@ "use strict";

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

@@ -23,2 +27,6 @@

var _core = require("@loaders.gl/core");
var _marked = _regenerator["default"].mark(meshPrimitiveIterator);
var KHR_draco_mesh_compression = function () {

@@ -31,34 +39,116 @@ function KHR_draco_mesh_compression() {

key: "decode",
value: function decode(gltfData, options) {
var gltfScenegraph = new _gltfScenegraph["default"](gltfData);
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
value: function () {
var _decode = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee(gltfData) {
var options,
scenegraph,
promises,
_iteratorNormalCompletion,
_didIteratorError,
_iteratorError,
_iterator,
_step,
primitive,
_args = arguments;
try {
for (var _iterator = (gltfScenegraph.json.meshes || [])[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var mesh = _step.value;
KHR_draco_mesh_compression.decompressMesh(mesh, options);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"] != null) {
_iterator["return"]();
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
options = _args.length > 1 && _args[1] !== undefined ? _args[1] : {};
if (options.decompress) {
_context.next = 3;
break;
}
return _context.abrupt("return");
case 3:
scenegraph = new _gltfScenegraph["default"](gltfData);
promises = [];
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
_context.prev = 8;
for (_iterator = meshPrimitiveIterator(scenegraph)[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
primitive = _step.value;
if (scenegraph.getObjectExtension(primitive, _gltfConstants.KHR_DRACO_MESH_COMPRESSION)) {
promises.push(decompressPrimitive(primitive, scenegraph, options));
}
}
_context.next = 16;
break;
case 12:
_context.prev = 12;
_context.t0 = _context["catch"](8);
_didIteratorError = true;
_iteratorError = _context.t0;
case 16:
_context.prev = 16;
_context.prev = 17;
if (!_iteratorNormalCompletion && _iterator["return"] != null) {
_iterator["return"]();
}
case 19:
_context.prev = 19;
if (!_didIteratorError) {
_context.next = 22;
break;
}
throw _iteratorError;
case 22:
return _context.finish(19);
case 23:
return _context.finish(16);
case 24:
_context.next = 26;
return Promise.all(promises);
case 26:
scenegraph.removeExtension(_gltfConstants.KHR_DRACO_MESH_COMPRESSION);
case 27:
case "end":
return _context.stop();
}
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}, _callee, null, [[8, 12, 16, 24], [17,, 19, 23]]);
}));
function decode(_x) {
return _decode.apply(this, arguments);
}
gltfScenegraph.removeExtension(_gltfConstants.KHR_DRACO_MESH_COMPRESSION);
return decode;
}()
}, {
key: "decodeSync",
value: function decodeSync(gltfData, options) {
if (!options.decompress) {
return;
}
var scenegraph = new _gltfScenegraph["default"](gltfData);
if (scenegraph.getRequiredExtension(_gltfConstants.KHR_DRACO_MESH_COMPRESSION)) {
throw new Error('Cannot synchronously decode Draco');
}
}
}, {
key: "encode",
value: function encode(gltfData, options) {
var gltfScenegraph = new _gltfScenegraph["default"](gltfData);
value: function encode(gltfData) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var scenegraph = new _gltfScenegraph["default"](gltfData);
var _iteratorNormalCompletion2 = true;

@@ -69,6 +159,6 @@ var _didIteratorError2 = false;

try {
for (var _iterator2 = (gltfScenegraph.json.meshes || [])[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
for (var _iterator2 = (scenegraph.json.meshes || [])[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var mesh = _step2.value;
KHR_draco_mesh_compression.compressMesh(mesh, options);
gltfScenegraph.addRequiredExtension(_gltfConstants.KHR_DRACO_MESH_COMPRESSION);
compressMesh(mesh, options);
scenegraph.addRequiredExtension(_gltfConstants.KHR_DRACO_MESH_COMPRESSION);
}

@@ -91,100 +181,208 @@ } catch (err) {

}, {
key: "compressMesh",
value: function compressMesh(attributes, indices) {
var mode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 4;
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
key: "name",
get: function get() {
return _gltfConstants.KHR_DRACO_MESH_COMPRESSION;
}
}]);
return KHR_draco_mesh_compression;
}();
if (!options.DracoWriter || !options.DracoLoader) {
throw new Error('DracoWriter/DracoLoader not available');
exports["default"] = KHR_draco_mesh_compression;
function decompressPrimitive(_x2, _x3, _x4) {
return _decompressPrimitive.apply(this, arguments);
}
function _decompressPrimitive() {
_decompressPrimitive = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee2(primitive, scenegraph, options) {
var compressedPrimitive, buffer, subArray, bufferCopy, decodedData;
return _regenerator["default"].wrap(function _callee2$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
compressedPrimitive = scenegraph.getObjectExtension(primitive, _gltfConstants.KHR_DRACO_MESH_COMPRESSION);
buffer = scenegraph.getTypedArrayForBufferView(compressedPrimitive.bufferView);
subArray = new Uint8Array(buffer.buffer).subarray(buffer.byteOffset);
bufferCopy = new Uint8Array(subArray);
_context3.next = 6;
return (0, _core.parse)(bufferCopy);
case 6:
decodedData = _context3.sent;
primitive.attributes = (0, _gltfAttributeUtils.getGLTFAccessors)(decodedData.attributes);
if (decodedData.indices) {
primitive.indices = (0, _gltfAttributeUtils.getGLTFAccessor)(decodedData.indices);
}
checkPrimitive(primitive);
case 10:
case "end":
return _context3.stop();
}
}
}, _callee2);
}));
return _decompressPrimitive.apply(this, arguments);
}
var compressedData = options.DracoWriter.encodeSync({
attributes: attributes
});
var decodedData = options.DracoLoader.parseSync({
attributes: attributes
});
function compressMesh(attributes, indices) {
var mode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 4;
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var fauxAccessors = options._addFauxAttributes(decodedData.attributes);
if (!options.DracoWriter || !options.DracoLoader) {
throw new Error('DracoWriter/DracoLoader not available');
}
var bufferViewIndex = options.addBufferView(compressedData);
var glTFMesh = {
primitives: [{
attributes: fauxAccessors,
mode: mode,
extensions: (0, _defineProperty2["default"])({}, _gltfConstants.KHR_DRACO_MESH_COMPRESSION, {
bufferView: bufferViewIndex,
attributes: fauxAccessors
})
}]
};
return glTFMesh;
}
}, {
key: "decompressMesh",
value: function decompressMesh(mesh) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
var compressedData = options.DracoWriter.encodeSync({
attributes: attributes
});
var decodedData = options.DracoLoader.parseSync({
attributes: attributes
});
try {
for (var _iterator3 = mesh.primitives[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var primitive = _step3.value;
var fauxAccessors = options._addFauxAttributes(decodedData.attributes);
KHR_draco_mesh_compression._decompressMeshPrimitive(primitive, options);
var bufferViewIndex = options.addBufferView(compressedData);
var glTFMesh = {
primitives: [{
attributes: fauxAccessors,
mode: mode,
extensions: (0, _defineProperty2["default"])({}, _gltfConstants.KHR_DRACO_MESH_COMPRESSION, {
bufferView: bufferViewIndex,
attributes: fauxAccessors
})
}]
};
return glTFMesh;
}
if (!primitive.attributes || Object.keys(primitive.attributes).length === 0) {
throw new Error('Empty glTF primitive: decompression failure?');
function checkPrimitive(primitive) {
if (!primitive.attributes && Object.keys(primitive.attributes).length > 0) {
throw new Error('Empty glTF primitive detected: Draco decompression failure?');
}
}
function meshPrimitiveIterator(scenegraph) {
var _iteratorNormalCompletion3, _didIteratorError3, _iteratorError3, _iterator3, _step3, mesh, _iteratorNormalCompletion4, _didIteratorError4, _iteratorError4, _iterator4, _step4, primitive;
return _regenerator["default"].wrap(function meshPrimitiveIterator$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_iteratorNormalCompletion3 = true;
_didIteratorError3 = false;
_iteratorError3 = undefined;
_context2.prev = 3;
_iterator3 = (scenegraph.json.meshes || [])[Symbol.iterator]();
case 5:
if (_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done) {
_context2.next = 36;
break;
}
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
mesh = _step3.value;
_iteratorNormalCompletion4 = true;
_didIteratorError4 = false;
_iteratorError4 = undefined;
_context2.prev = 10;
_iterator4 = mesh.primitives[Symbol.iterator]();
case 12:
if (_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done) {
_context2.next = 19;
break;
}
primitive = _step4.value;
_context2.next = 16;
return primitive;
case 16:
_iteratorNormalCompletion4 = true;
_context2.next = 12;
break;
case 19:
_context2.next = 25;
break;
case 21:
_context2.prev = 21;
_context2.t0 = _context2["catch"](10);
_didIteratorError4 = true;
_iteratorError4 = _context2.t0;
case 25:
_context2.prev = 25;
_context2.prev = 26;
if (!_iteratorNormalCompletion4 && _iterator4["return"] != null) {
_iterator4["return"]();
}
case 28:
_context2.prev = 28;
if (!_didIteratorError4) {
_context2.next = 31;
break;
}
throw _iteratorError4;
case 31:
return _context2.finish(28);
case 32:
return _context2.finish(25);
case 33:
_iteratorNormalCompletion3 = true;
_context2.next = 5;
break;
case 36:
_context2.next = 42;
break;
case 38:
_context2.prev = 38;
_context2.t1 = _context2["catch"](3);
_didIteratorError3 = true;
_iteratorError3 = _context2.t1;
case 42:
_context2.prev = 42;
_context2.prev = 43;
if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) {
_iterator3["return"]();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
}
}, {
key: "_decompressMeshPrimitive",
value: function _decompressMeshPrimitive(primitive, options) {
var compressedPrimitive = primitive.extensions && primitive.extensions[_gltfConstants.KHR_DRACO_MESH_COMPRESSION];
if (!compressedPrimitive) {
return;
}
case 45:
_context2.prev = 45;
if (!options.DracoLoader || !options.decompress) {
return;
}
if (!_didIteratorError3) {
_context2.next = 48;
break;
}
delete primitive.extensions[_gltfConstants.KHR_DRACO_MESH_COMPRESSION];
throw _iteratorError3;
var buffer = this._getBufferViewArray(compressedPrimitive.bufferView);
case 48:
return _context2.finish(45);
var decodedData = options.DracoLoader.parseSync(buffer);
primitive.attributes = (0, _gltfAttributeUtils.getGLTFAccessors)(decodedData.attributes);
case 49:
return _context2.finish(42);
if (decodedData.indices) {
primitive.indices = (0, _gltfAttributeUtils.getGLTFAccessor)(decodedData.indices);
case 50:
case "end":
return _context2.stop();
}
}
}, {
key: "name",
get: function get() {
return _gltfConstants.KHR_DRACO_MESH_COMPRESSION;
}
}]);
return KHR_draco_mesh_compression;
}();
exports["default"] = KHR_draco_mesh_compression;
}, _marked, null, [[3, 38, 42, 50], [10, 21, 25, 33], [26,, 28, 32], [43,, 45, 49]]);
}
//# sourceMappingURL=KHR_draco_mesh_compression.js.map

@@ -38,3 +38,3 @@ "use strict";

},
binary: null
buffers: []
};

@@ -44,2 +44,3 @@ }

this.gltf = gltf;
(0, _assert["default"])(this.gltf.json);
}

@@ -159,6 +160,6 @@

var object = this.gltf[array] && this.gltf[array][index];
var object = this.json[array] && this.json[array][index];
if (!object) {
console.warn("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
throw new Error("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
}

@@ -172,6 +173,7 @@

bufferView = this.getBufferView(bufferView);
var buffer = this.getBuffer(bufferView.buffer);
var arrayBuffer = buffer.data;
var byteOffset = bufferView.byteOffset || 0;
return new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
var bufferIndex = bufferView.buffer;
var binChunk = this.gltf.buffers[bufferIndex];
(0, _assert["default"])(binChunk);
var byteOffset = bufferView.byteOffset || 0 + binChunk.byteOffset;
return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
}

@@ -178,0 +180,0 @@ }, {

@@ -17,6 +17,6 @@ "use strict";

var LE = true;
var BE = false;
function getMagicString(dataView) {
return "".concat(String.fromCharCode(dataView.getUint8(0))).concat(String.fromCharCode(dataView.getUint8(1))).concat(String.fromCharCode(dataView.getUint8(2))).concat(String.fromCharCode(dataView.getUint8(3)));
var byteOffset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
return "".concat(String.fromCharCode(dataView.getUint8(byteOffset + 0))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 1))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 2))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 3)));
}

@@ -38,12 +38,11 @@

var dataView = new DataView(arrayBuffer);
glb.byteOffset = byteOffset;
glb.magic = dataView.getUint32(byteOffset + 0, BE);
glb.type = getMagicString(dataView, byteOffset + 0);
glb.version = dataView.getUint32(byteOffset + 4, LE);
glb.byteLength = dataView.getUint32(byteOffset + 8, LE);
glb.type = getMagicString(dataView);
var _options$magic2 = options.magic,
magic = _options$magic2 === void 0 ? MAGIC_glTF : _options$magic2;
var isMagicValid = glb.magic === MAGIC_glTF || glb.magic === magic;
var byteLength = dataView.getUint32(byteOffset + 8, LE);
glb.header = {
byteOffset: byteOffset,
byteLength: byteLength
};
if (!isMagicValid) {
if (glb.type !== 'glTF') {
console.warn("Invalid GLB magic string ".concat(glb.type));

@@ -53,27 +52,79 @@ }

(0, _loaderUtils.assert)(glb.version === 2, "Invalid GLB version ".concat(glb.version, ". Only .glb v2 supported"));
(0, _loaderUtils.assert)(glb.byteLength > 20);
var jsonChunkLength = dataView.getUint32(byteOffset + 12, LE);
var jsonChunkFormat = dataView.getUint32(byteOffset + 16, LE);
var isJSONChunk = jsonChunkFormat === GLB_CHUNK_TYPE_JSON || jsonChunkFormat === 0;
(0, _loaderUtils.assert)(isJSONChunk, "JSON chunk format ".concat(jsonChunkFormat));
var jsonChunkByteOffset = GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE;
var jsonChunk = new Uint8Array(arrayBuffer, byteOffset + jsonChunkByteOffset, jsonChunkLength);
(0, _loaderUtils.assert)(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
glb.json = {};
glb.hasBinChunk = false;
glb.binChunks = [];
parseGLBChunksSync(glb, dataView, byteOffset + 12, options);
addDeprecatedFields(glb);
return byteOffset + glb.header.byteLength;
}
function parseGLBChunksSync(glb, dataView, byteOffset, options) {
while (byteOffset + 8 <= glb.header.byteLength) {
var chunkLength = dataView.getUint32(byteOffset + 0, LE);
var chunkFormat = dataView.getUint32(byteOffset + 4, LE);
byteOffset += GLB_CHUNK_HEADER_SIZE;
switch (chunkFormat) {
case GLB_CHUNK_TYPE_JSON:
parseJSONChunk(glb, dataView, byteOffset, chunkLength, options);
break;
case GLB_CHUNK_TYPE_BIN:
parseBINChunk(glb, dataView, byteOffset, chunkLength, options);
break;
default:
break;
}
switch (chunkFormat) {
case 0:
if (!options.strict) {
parseJSONChunk(glb, dataView, byteOffset, chunkLength, options);
}
break;
case 1:
if (!options.strict) {
parseBINChunk(glb, dataView, byteOffset, chunkLength, options);
}
break;
default:
}
byteOffset += (0, _loaderUtils.padTo4Bytes)(chunkLength);
}
return byteOffset;
}
function parseJSONChunk(glb, dataView, byteOffset, chunkLength, options) {
var jsonChunk = new Uint8Array(dataView.buffer, byteOffset, chunkLength);
var textDecoder = new TextDecoder('utf8');
var jsonText = textDecoder.decode(jsonChunk);
glb.json = JSON.parse(jsonText);
var binChunkStart = jsonChunkByteOffset + (0, _loaderUtils.padTo4Bytes)(jsonChunkLength);
glb.hasBinChunk = binChunkStart + 8 <= glb.byteLength;
}
if (glb.hasBinChunk) {
var binChunkLength = dataView.getUint32(byteOffset + binChunkStart + 0, LE);
var binChunkFormat = dataView.getUint32(byteOffset + binChunkStart + 4, LE);
var isBinChunk = binChunkFormat === GLB_CHUNK_TYPE_BIN || binChunkFormat === 1;
(0, _loaderUtils.assert)(isBinChunk, "BIN chunk format ".concat(binChunkFormat));
var binChunkByteOffset = binChunkStart + GLB_CHUNK_HEADER_SIZE;
glb.binChunkByteOffset = binChunkByteOffset;
glb.binChunkLength = binChunkLength;
}
function parseBINChunk(glb, dataView, byteOffset, chunkLength, options) {
glb.header.hasBinChunk = true;
glb.binChunks.push({
byteOffset: byteOffset,
byteLength: chunkLength,
arrayBuffer: dataView.buffer
});
}
return byteOffset + glb.byteLength;
function addDeprecatedFields(glb) {
glb.byteOffset = glb.header.byteOffset;
glb.magic = glb.header.magic;
glb.version = glb.header.version;
glb.byteLength = glb.header.byteLength;
glb.hasBinChunk = glb.binChunks.length >= 1;
glb.binChunkByteOffset = glb.header.hasBinChunk ? glb.binChunks[0].byteOffset : 0;
glb.binChunkLength = glb.header.hasBinChunk ? glb.binChunks[0].byteLength : 0;
}
//# sourceMappingURL=parse-glb.js.map

@@ -11,4 +11,4 @@ "use strict";

exports.isGLTF = isGLTF;
exports.parseGLTF = parseGLTF;
exports.parseGLTFSync = parseGLTFSync;
exports.parseGLTF = parseGLTF;

@@ -27,5 +27,7 @@ var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _extensions = require("./extensions/extensions");
var _parseGlb = _interopRequireWildcard(require("./parse-glb"));
var EXTENSIONS = _interopRequireWildcard(require("./extensions"));
var _postProcessGltf = _interopRequireDefault(require("./post-process-gltf"));

@@ -36,17 +38,10 @@ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

var DEFAULT_SYNC_OPTIONS = {
fetchLinkedResources: false,
decompress: false,
DracoLoader: null,
postProcess: true,
var DEFAULT_OPTIONS = {
fetchLinkedResources: true,
fetchImages: false,
createImages: false,
log: console
};
var DEFAULT_ASYNC_OPTIONS = {
fetchLinkedResources: true,
fetch: _core.fetchFile,
decompress: false,
DracoLoader: null,
postProcess: true,
createImages: false,
postProcess: false,
log: console

@@ -62,68 +57,2 @@ };

function parseGLTFSync(gltf, arrayBufferOrString) {
var byteOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
options = Object.assign({}, DEFAULT_SYNC_OPTIONS, options);
var data = arrayBufferOrString;
if (data instanceof ArrayBuffer && !(0, _parseGlb.isGLB)(data, byteOffset, options)) {
var textDecoder = new TextDecoder();
data = textDecoder.decode(data);
}
gltf.buffers = [];
if (typeof data === 'string') {
gltf.json = JSON.parse(data);
} else if (data instanceof ArrayBuffer) {
byteOffset = (0, _parseGlb["default"])(gltf, data, byteOffset, options);
if (gltf.hasBinChunk) {
gltf.buffers.push({
arrayBuffer: data,
byteOffset: gltf.binChunkByteOffset,
byteLength: gltf.binChunkLength
});
}
} else {
gltf.json = data;
}
if (options.uri) {
gltf.baseUri = options.uri;
}
if (options.fetchLinkedResources) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = (gltf.json.buffers || [])[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var buffer = _step.value;
if (buffer.uri) {
throw new Error('parseGLTFSync: Cannot decode uri buffers');
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"] != null) {
_iterator["return"]();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
decodeExtensions(gltf, options);
return byteOffset;
}
function parseGLTF(_x, _x2) {

@@ -137,3 +66,7 @@ return _parseGLTF.apply(this, arguments);

options,
promises,
_promise,
promise,
_args = arguments;
return _regenerator["default"].wrap(function _callee$(_context) {

@@ -145,21 +78,29 @@ while (1) {

options = _args.length > 3 && _args[3] !== undefined ? _args[3] : {};
options = Object.assign({}, DEFAULT_ASYNC_OPTIONS, options);
parseGLTFSync(gltf, arrayBufferOrString, byteOffset, _objectSpread({}, options, {
fetchLinkedResources: false,
postProcess: false,
decompress: false
}));
options = _objectSpread({}, DEFAULT_OPTIONS, {}, options);
parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options);
promises = [];
if (options.fetchImages) {
_promise = fetchImages(gltf, options);
promises.push(_promise);
}
if (!options.fetchLinkedResources) {
_context.next = 7;
_context.next = 9;
break;
}
_context.next = 7;
return fetchLinkedResources(gltf, options);
_context.next = 9;
return fetchBuffers(gltf, options);
case 7:
return _context.abrupt("return", gltf);
case 9:
promise = (0, _extensions.decodeExtensions)(gltf, options);
promises.push(promise);
_context.next = 13;
return Promise.all(promises);
case 8:
case 13:
return _context.abrupt("return", options.postProcess ? (0, _postProcessGltf["default"])(gltf, options) : gltf);
case 14:
case "end":

@@ -174,10 +115,63 @@ return _context.stop();

function fetchLinkedResources(_x3, _x4) {
return _fetchLinkedResources.apply(this, arguments);
function parseGLTFSync(gltf, arrayBufferOrString) {
var byteOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
options = _objectSpread({}, DEFAULT_OPTIONS, {}, options);
parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options);
if (options.fetchLinkedResources) {
fetchBuffersSync(gltf, options);
}
if (options.decodeExtensions) {
(0, _extensions.decodeExtensionsSync)(gltf, options);
}
return options.postProcess ? (0, _postProcessGltf["default"])(gltf, options) : gltf;
}
function _fetchLinkedResources() {
_fetchLinkedResources = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee2(gltf, options) {
var _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, buffer, fetch, uri, response, arrayBuffer;
function parseGLTFContainerSync(gltf, data, byteOffset, options) {
if (options.uri) {
gltf.baseUri = options.uri;
}
if (data instanceof ArrayBuffer && !(0, _parseGlb.isGLB)(data, byteOffset, options)) {
var textDecoder = new TextDecoder();
data = textDecoder.decode(data);
}
if (typeof data === 'string') {
gltf.json = JSON.parse(data);
} else if (data instanceof ArrayBuffer) {
gltf._glb = {};
byteOffset = (0, _parseGlb["default"])(gltf._glb, data, byteOffset, options);
gltf.json = gltf._glb.json;
} else {
gltf.json = data;
}
var buffers = gltf.json.buffers || [];
gltf.buffers = new Array(buffers.length).fill({});
if (gltf._glb && gltf._glb.hasBinChunk) {
gltf.buffers[0] = {
arrayBuffer: gltf._glb.binChunks[0].arrayBuffer,
byteOffset: gltf._glb.binChunks[0].byteOffset,
byteLength: gltf._glb.binChunks[0].byteLength
};
gltf.json.buffers[0].data = gltf.buffers[0].arrayBuffer;
gltf.json.buffers[0].byteOffset = gltf.buffers[0].byteOffset;
}
var images = gltf.json.images || [];
gltf.images = new Array(images.length).fill({});
}
function fetchBuffers(_x3, _x4) {
return _fetchBuffers.apply(this, arguments);
}
function _fetchBuffers() {
_fetchBuffers = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee2(gltf, options) {
var i, buffer, fetch, uri, response, arrayBuffer;
return _regenerator["default"].wrap(function _callee2$(_context2) {

@@ -187,18 +181,18 @@ while (1) {

case 0:
_iteratorNormalCompletion2 = true;
_didIteratorError2 = false;
_iteratorError2 = undefined;
_context2.prev = 3;
_iterator2 = gltf.json.buffers[Symbol.iterator]();
i = 0;
case 5:
if (_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done) {
_context2.next = 22;
case 1:
if (!(i < gltf.json.buffers.length)) {
_context2.next = 19;
break;
}
buffer = _step2.value;
buffer = gltf.json.buffers[i];
if (!buffer.uri) {
_context2.next = 19;
if (!options.uri) {
console.warn('options.uri must be set to decode embedded glTF buffers');
}
if (!(buffer.uri && options.uri)) {
_context2.next = 16;
break;

@@ -210,74 +204,143 @@ }

uri = (0, _gltfUtils.getFullUri)(buffer.uri, options.uri);
_context2.next = 13;
_context2.next = 10;
return fetch(uri);
case 13:
case 10:
response = _context2.sent;
_context2.next = 16;
_context2.next = 13;
return response.arrayBuffer();
case 16:
case 13:
arrayBuffer = _context2.sent;
buffer.data = arrayBuffer;
gltf.buffers[i] = {
arrayBuffer: arrayBuffer,
byteOffset: 0,
byteLength: arrayBuffer.byteLength
};
delete buffer.uri;
case 19:
_iteratorNormalCompletion2 = true;
_context2.next = 5;
case 16:
++i;
_context2.next = 1;
break;
case 22:
_context2.next = 28;
break;
case 19:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return _fetchBuffers.apply(this, arguments);
}
case 24:
_context2.prev = 24;
_context2.t0 = _context2["catch"](3);
_didIteratorError2 = true;
_iteratorError2 = _context2.t0;
function fetchBuffersSync(gltf, options) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
case 28:
_context2.prev = 28;
_context2.prev = 29;
try {
for (var _iterator = (gltf.json.buffers || [])[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var buffer = _step.value;
if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
_iterator2["return"]();
}
if (buffer.uri) {
throw new Error('parseGLTFSync: Cannot decode uri buffers');
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"] != null) {
_iterator["return"]();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
case 31:
_context2.prev = 31;
function fetchImages(_x5, _x6) {
return _fetchImages.apply(this, arguments);
}
if (!_didIteratorError2) {
_context2.next = 34;
break;
function _fetchImages() {
_fetchImages = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee3(gltf, options) {
var images, promises, i, image;
return _regenerator["default"].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
images = gltf.json.images || [];
promises = [];
for (i = 0; i < images.length; ++i) {
image = images[i];
if ('uri' in image) {
promises.push(fetchAndParseLinkedImage(gltf, image, i, options));
}
}
throw _iteratorError2;
_context3.next = 5;
return Promise.all(promises);
case 34:
return _context2.finish(31);
case 5:
return _context3.abrupt("return", _context3.sent);
case 35:
return _context2.finish(28);
case 36:
case 6:
case "end":
return _context2.stop();
return _context3.stop();
}
}
}, _callee2, null, [[3, 24, 28, 36], [29,, 31, 35]]);
}, _callee3);
}));
return _fetchLinkedResources.apply(this, arguments);
return _fetchImages.apply(this, arguments);
}
function decodeExtensions(gltf, options) {
for (var extensionName in EXTENSIONS) {
var disableExtension = extensionName in options && !options[extensionName];
function fetchAndParseLinkedImage(_x7, _x8, _x9, _x10) {
return _fetchAndParseLinkedImage.apply(this, arguments);
}
if (!disableExtension) {
var extension = EXTENSIONS[extensionName];
extension.decode(gltf, options);
}
}
function _fetchAndParseLinkedImage() {
_fetchAndParseLinkedImage = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee4(gltf, image, i, options) {
var fetch, uri;
return _regenerator["default"].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
fetch = options.fetch || window.fetch;
(0, _assert["default"])(fetch);
uri = (0, _gltfUtils.getFullUri)(image.uri, options.uri);
_context4.next = 5;
return new Promise(function (resolve, reject) {
var img = new Image();
img.crossOrigin = 'anonymous';
img.onload = function () {
return resolve(img);
};
img.onerror = function (error) {
return reject(error);
};
img.src = uri;
});
case 5:
gltf.images[i] = _context4.sent;
case 6:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
return _fetchAndParseLinkedImage.apply(this, arguments);
}
//# sourceMappingURL=parse-gltf.js.map

@@ -20,2 +20,4 @@ "use strict";

var _assert = _interopRequireDefault(require("./utils/assert"));
var _DEFAULT_SAMPLER;

@@ -78,6 +80,18 @@

var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
this.gltf = gltf;
this.json = gltf.json;
this.buffers = gltf.buffers;
return this._resolveTree(gltf.json, options);
var json = gltf.json,
_gltf$buffers = gltf.buffers,
buffers = _gltf$buffers === void 0 ? [] : _gltf$buffers,
_gltf$images = gltf.images,
images = _gltf$images === void 0 ? [] : _gltf$images,
_gltf$baseUri = gltf.baseUri,
baseUri = _gltf$baseUri === void 0 ? '' : _gltf$baseUri;
(0, _assert["default"])(json);
this.baseUri = baseUri;
this.json = json;
this.buffers = buffers;
this.images = images;
this._resolveTree(this.json, options);
return this.json;
}

@@ -154,4 +168,2 @@ }, {

}
return json;
}

@@ -238,3 +250,2 @@ }, {

scene = _objectSpread({}, scene);
scene.id = scene.id || "scene-".concat(index);

@@ -251,3 +262,2 @@ scene.nodes = (scene.nodes || []).map(function (node) {

node = _objectSpread({}, node);
node.id = node.id || "node-".concat(index);

@@ -278,3 +288,2 @@

value: function _resolveSkin(skin, index) {
skin = _objectSpread({}, skin);
skin.id = skin.id || "skin-".concat(index);

@@ -289,3 +298,2 @@ skin.inverseBindMatrices = this.getAccessor(skin.inverseBindMatrices);

mesh = _objectSpread({}, mesh);
mesh.id = mesh.id || "mesh-".concat(index);

@@ -320,3 +328,2 @@

value: function _resolveMaterial(material, index) {
material = _objectSpread({}, material);
material.id = material.id || "material-".concat(index);

@@ -359,3 +366,2 @@

value: function _resolveAccessor(accessor, index) {
accessor = _objectSpread({}, accessor);
accessor.id = accessor.id || "accessor-".concat(index);

@@ -375,3 +381,2 @@

value: function _resolveTexture(texture, index) {
texture = _objectSpread({}, texture);
texture.id = texture.id || "texture-".concat(index);

@@ -385,3 +390,2 @@ texture.sampler = 'sampler' in texture ? this.getSampler(texture.sampler) : DEFAULT_SAMPLER;

value: function _resolveSampler(sampler, index) {
sampler = _objectSpread({}, sampler);
sampler.id = sampler.id || "sampler-".concat(index);

@@ -408,3 +412,4 @@ sampler.parameters = {};

value: function _resolveImage(image, index, options) {
image = _objectSpread({}, image);
var _this5 = this;
image.id = image.id || "image-".concat(index);

@@ -417,15 +422,32 @@

if ('uri' in image) {
var baseUri = options.uri || this.gltf.baseUri;
var preloadedImage = this.images[index];
if (preloadedImage && preloadedImage.image) {
image.image = preloadedImage.image;
delete image.uri;
}
var baseUri = options.uri || this.baseUri;
if (baseUri) {
var uri = image.uri;
image.uri = (0, _gltfUtils.getFullUri)(image.uri, baseUri);
image.originalUri = uri;
image.baseUri = baseUri;
image.fullUri = (0, _gltfUtils.getFullUri)(image.uri, baseUri);
image.fullUri = image.uri;
}
}
function getImageAsync() {
if (image.uri) {
image.getImageAsync = function () {
if (image.bufferView) {
return new Promise(function (resolve) {
var arrayBufferView = _this5.getBufferView(image.bufferView);
var mimeType = image.mimeType || 'image/jpeg';
var blob = new Blob([arrayBufferView.data], {
type: mimeType
});
var urlCreator = self.URL || self.webkitURL;
var imageUrl = urlCreator.createObjectURL(blob);
var img = new Image();
img.crossOrigin = 'anonymous';

@@ -436,10 +458,18 @@ img.onload = function () {

img.src = image.fullUri || image.uri;
img.src = imageUrl;
});
}
return null;
}
return image.uri ? new Promise(function (resolve) {
var img = new Image();
img.crossOrigin = 'anonymous';
image.getImageAsync = getImageAsync;
img.onload = function () {
return resolve(img);
};
img.src = image.fullUri || image.uri;
}) : null;
};
return image;

@@ -450,3 +480,2 @@ }

value: function _resolveBufferView(bufferView, index) {
bufferView = _objectSpread({}, bufferView);
bufferView.id = bufferView.id || "bufferView-".concat(index);

@@ -453,0 +482,0 @@ var bufferIndex = bufferView.buffer;

@@ -1,4 +0,4 @@

var moduleExports = require('./index');
const moduleExports = require('./index');
var _global = typeof window === 'undefined' ? global : window;
const _global = typeof window === 'undefined' ? global : window;

@@ -5,0 +5,0 @@ _global.loaders = _global.loaders || {};

@@ -7,10 +7,13 @@ import parseGLBSync from './lib/parse-glb';

binary: true,
parseSync
parseSync,
defaultOptions: {
strict: false
}
};
function parseSync(arrayBuffer, options) {
var {
const {
byteOffset = 0
} = options;
var glb = {};
const glb = {};
parseGLBSync(glb, arrayBuffer, byteOffset, options);

@@ -17,0 +20,0 @@ return glb;

@@ -10,8 +10,8 @@ import encodeGLBSync from './lib/encode-glb';

function encodeSync(glb, options) {
var {
const {
byteOffset = 0
} = options;
var byteLength = encodeGLBSync(glb, null, byteOffset, options);
var arrayBuffer = new ArrayBuffer(byteLength);
var dataView = new DataView(arrayBuffer);
const byteLength = encodeGLBSync(glb, null, byteOffset, options);
const arrayBuffer = new ArrayBuffer(byteLength);
const dataView = new DataView(arrayBuffer);
encodeGLBSync(glb, dataView, byteOffset, options);

@@ -18,0 +18,0 @@ return arrayBuffer;

import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";

@@ -10,43 +9,34 @@ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

import GLTFParser from './lib/deprecated/gltf-parser';
var DEFAULT_OPTIONS = {
useGLTFParser: true
const DEFAULT_OPTIONS = {
gltf: {
parserVersion: 1
},
uri: ''
};
export function parse(_x) {
return _parse.apply(this, arguments);
}
export async function parse(arrayBuffer, options = {}) {
options = _objectSpread({}, DEFAULT_OPTIONS, {}, options);
function _parse() {
_parse = _asyncToGenerator(function* (arrayBuffer) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
options = _objectSpread({}, DEFAULT_OPTIONS, {}, options);
if (options.gltf.parserVersion !== 2 && options.useGLTFParser !== false) {
const gltfParser = new GLTFParser();
return gltfParser.parse(arrayBuffer, options);
}
if (options.useGLTFParser) {
var gltfParser = new GLTFParser();
return gltfParser.parse(arrayBuffer, options);
}
var {
byteOffset = 0
} = options;
var gltf = {};
yield parseGLTF(gltf, arrayBuffer, byteOffset, options);
return gltf;
});
return _parse.apply(this, arguments);
const {
byteOffset = 0
} = options;
const gltf = {};
return await parseGLTF(gltf, arrayBuffer, byteOffset, options);
}
export function parseSync(arrayBuffer) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
export function parseSync(arrayBuffer, options = {}) {
options = _objectSpread({}, DEFAULT_OPTIONS, {}, options);
if (options.useGLTFParser) {
if (options.gltf.parserVersion !== 2 && options.useGLTFParser !== false) {
return new GLTFParser().parseSync(arrayBuffer, options);
}
var {
const {
byteOffset = 0
} = options;
var gltf = {};
parseGLTFSync(gltf, arrayBuffer, byteOffset, options);
return gltf;
const gltf = {};
return parseGLTFSync(gltf, arrayBuffer, byteOffset, options);
}

@@ -53,0 +43,0 @@ export default {

import { encodeGLTFSync } from './lib/encode-gltf';
function encodeSync(gltf) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var {
function encodeSync(gltf, options = {}) {
const {
byteOffset = 0
} = options;
var byteLength = encodeGLTFSync(gltf, null, byteOffset, options);
var arrayBuffer = new ArrayBuffer(byteLength);
var dataView = new DataView(arrayBuffer);
const byteLength = encodeGLTFSync(gltf, null, byteOffset, options);
const arrayBuffer = new ArrayBuffer(byteLength);
const dataView = new DataView(arrayBuffer);
encodeGLTFSync(gltf, dataView, byteOffset, options);

@@ -12,0 +11,0 @@ return arrayBuffer;

@@ -7,4 +7,3 @@ import { padTo4Bytes, copyToArray } from '@loaders.gl/loader-utils';

export default class GLBBuilder {
constructor() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
constructor(options = {}) {
this.byteLength = 0;

@@ -32,10 +31,7 @@ this.json = {

encodeSync() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
encodeSync(options = {}) {
return this.encodeAsGLB(options);
}
encodeAsGLB() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
encodeAsGLB(options = {}) {
this._packBinaryChunk();

@@ -47,3 +43,3 @@

var glb = {
const glb = {
version: 2,

@@ -53,5 +49,5 @@ json: this.json,

};
var byteLength = encodeGLBSync(glb, null, 0, options);
var glbArrayBuffer = new ArrayBuffer(byteLength);
var dataView = new DataView(glbArrayBuffer);
const byteLength = encodeGLBSync(glb, null, 0, options);
const glbArrayBuffer = new ArrayBuffer(byteLength);
const dataView = new DataView(glbArrayBuffer);
encodeGLBSync(glb, dataView, 0, options);

@@ -61,5 +57,4 @@ return glbArrayBuffer;

addApplicationData(key, data) {
var packOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var jsonData = packOptions.packTypedArrays ? packBinaryJson(data, this, packOptions) : data;
addApplicationData(key, data, packOptions = {}) {
const jsonData = packOptions.packTypedArrays ? packBinaryJson(data, this, packOptions) : data;
this.json[key] = jsonData;

@@ -69,8 +64,7 @@ return this;

addBuffer(sourceBuffer) {
var accessor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
size: 3
};
var bufferViewIndex = this.addBufferView(sourceBuffer);
var accessorDefaults = {
addBuffer(sourceBuffer, accessor = {
size: 3
}) {
const bufferViewIndex = this.addBufferView(sourceBuffer);
const accessorDefaults = {
size: accessor.size,

@@ -84,3 +78,3 @@ componentType: getComponentTypeFromArray(sourceBuffer),

addBufferView(buffer) {
var byteLength = buffer.byteLength || buffer.length;
const byteLength = buffer.byteLength || buffer.length;
this.json.bufferViews.push({

@@ -120,9 +114,9 @@ buffer: 0,

var totalByteLength = this.byteLength;
var arrayBuffer = new ArrayBuffer(totalByteLength);
var targetArray = new Uint8Array(arrayBuffer);
var dstByteOffset = 0;
const totalByteLength = this.byteLength;
const arrayBuffer = new ArrayBuffer(totalByteLength);
const targetArray = new Uint8Array(arrayBuffer);
let dstByteOffset = 0;
for (var i = 0; i < this.sourceBuffers.length; i++) {
var sourceBuffer = this.sourceBuffers[i];
for (let i = 0; i < this.sourceBuffers.length; i++) {
const sourceBuffer = this.sourceBuffers[i];
dstByteOffset = copyToArray(sourceBuffer, targetArray, dstByteOffset);

@@ -129,0 +123,0 @@ }

@@ -7,15 +7,12 @@ import assert from '../utils/assert';

export default class GLBParser {
static isGLB(arrayBuffer) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var byteOffset = 0;
static isGLB(arrayBuffer, options = {}) {
const byteOffset = 0;
return isGLB(arrayBuffer, byteOffset);
}
parse(arrayBuffer) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
parse(arrayBuffer, options = {}) {
return this.parseSync(arrayBuffer, options);
}
parseSync(arrayBuffer) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
parseSync(arrayBuffer, options = {}) {
this.glbArrayBuffer = arrayBuffer;

@@ -27,7 +24,7 @@ this.binaryByteOffset = null;

if (this.json === null && this.binaryByteOffset === null) {
var byteOffset = 0;
const byteOffset = 0;
parseGLBSync(this, this.glbArrayBuffer, byteOffset, options);
this.binaryByteOffset = this.binChunkByteOffset;
this.packedJson = this.json;
var unpackedBuffers = unpackGLTFBuffers(this.glbArrayBuffer, this.json, this.binaryByteOffset);
const unpackedBuffers = unpackGLTFBuffers(this.glbArrayBuffer, this.json, this.binaryByteOffset);
this.json = unpackBinaryJson(this.json, unpackedBuffers);

@@ -57,3 +54,3 @@ this.unpackedBuffers = unpackedBuffers;

getBufferView(glTFBufferView) {
var byteOffset = (glTFBufferView.byteOffset || 0) + this.binaryByteOffset;
const byteOffset = (glTFBufferView.byteOffset || 0) + this.binaryByteOffset;
return new Uint8Array(this.glbArrayBuffer, byteOffset, glTFBufferView.byteLength);

@@ -63,10 +60,10 @@ }

getBuffer(glTFAccessor) {
var ArrayType = ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY[glTFAccessor.componentType];
var components = ATTRIBUTE_TYPE_TO_COMPONENTS[glTFAccessor.type];
var bytesPerComponent = ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE[glTFAccessor.componentType];
var length = glTFAccessor.count * components;
var byteLength = glTFAccessor.count * components * bytesPerComponent;
var glTFBufferView = this.json.bufferViews[glTFAccessor.bufferView];
const ArrayType = ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY[glTFAccessor.componentType];
const components = ATTRIBUTE_TYPE_TO_COMPONENTS[glTFAccessor.type];
const bytesPerComponent = ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE[glTFAccessor.componentType];
const length = glTFAccessor.count * components;
const byteLength = glTFAccessor.count * components * bytesPerComponent;
const glTFBufferView = this.json.bufferViews[glTFAccessor.bufferView];
assert(byteLength >= 0 && glTFAccessor.byteOffset + byteLength <= glTFBufferView.byteLength);
var byteOffset = glTFBufferView.byteOffset + this.binaryByteOffset + glTFAccessor.byteOffset;
const byteOffset = glTFBufferView.byteOffset + this.binaryByteOffset + glTFAccessor.byteOffset;
return new ArrayType(this.glbArrayBuffer, byteOffset, length);

@@ -83,10 +80,10 @@ }

getImage(glTFImage) {
var arrayBufferView = this.getBufferView(glTFImage.bufferView);
var mimeType = glTFImage.mimeType || 'image/jpeg';
var blob = new Blob([arrayBufferView], {
const arrayBufferView = this.getBufferView(glTFImage.bufferView);
const mimeType = glTFImage.mimeType || 'image/jpeg';
const blob = new Blob([arrayBufferView], {
type: mimeType
});
var urlCreator = self.URL || self.webkitURL;
var imageUrl = urlCreator.createObjectURL(blob);
var img = new Image();
const urlCreator = self.URL || self.webkitURL;
const imageUrl = urlCreator.createObjectURL(blob);
const img = new Image();
img.src = imageUrl;

@@ -98,10 +95,10 @@ return img;

return new Promise(resolve => {
var arrayBufferView = this.getBufferView(glTFImage.bufferView);
var mimeType = glTFImage.mimeType || 'image/jpeg';
var blob = new Blob([arrayBufferView], {
const arrayBufferView = this.getBufferView(glTFImage.bufferView);
const mimeType = glTFImage.mimeType || 'image/jpeg';
const blob = new Blob([arrayBufferView], {
type: mimeType
});
var urlCreator = self.URL || self.webkitURL;
var imageUrl = urlCreator.createObjectURL(blob);
var img = new Image();
const urlCreator = self.URL || self.webkitURL;
const imageUrl = urlCreator.createObjectURL(blob);
const img = new Image();

@@ -108,0 +105,0 @@ img.onload = () => resolve(img);

@@ -7,4 +7,3 @@ import { getImageMetadata } from '@loaders.gl/images';

export default class GLTFBuilder extends GLBBuilder {
constructor() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
constructor(options = {}) {
super(options);

@@ -15,5 +14,4 @@ this.DracoWriter = options.DracoWriter;

addApplicationData(key, data) {
var packOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var jsonData = packOptions.packTypedArrays ? packBinaryJson(data, this, packOptions) : data;
addApplicationData(key, data, packOptions = {}) {
const jsonData = packOptions.packTypedArrays ? packBinaryJson(data, this, packOptions) : data;
this.json[key] = jsonData;

@@ -23,5 +21,4 @@ return this;

addExtraData(key, data) {
var packOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var packedJson = packOptions.packedTypedArrays ? packBinaryJson(data, this, packOptions) : data;
addExtraData(key, data, packOptions = {}) {
const packedJson = packOptions.packedTypedArrays ? packBinaryJson(data, this, packOptions) : data;
this.json.extras = this.json.extras || {};

@@ -32,6 +29,5 @@ this.json.extras[key] = packedJson;

addExtension(extensionName, data) {
var packOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
addExtension(extensionName, data, packOptions = {}) {
assert(data);
var packedJson = packOptions.packTypedArrays ? packBinaryJson(data, this, packOptions) : data;
const packedJson = packOptions.packTypedArrays ? packBinaryJson(data, this, packOptions) : data;
this.json.extensions = this.json.extensions || {};

@@ -43,6 +39,5 @@ this.json.extensions[extensionName] = packedJson;

addRequiredExtension(extensionName, data) {
var packOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
addRequiredExtension(extensionName, data, packOptions = {}) {
assert(data);
var packedJson = packOptions.packTypedArrays ? packBinaryJson(data, this, packOptions) : data;
const packedJson = packOptions.packTypedArrays ? packBinaryJson(data, this, packOptions) : data;
this.addExtension(extensionName, packedJson);

@@ -70,8 +65,6 @@ this.registerRequiredExtension(extensionName);

addMesh(attributes, indices) {
var mode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 4;
addMesh(attributes, indices, mode = 4) {
const accessors = this._addAttributes(attributes);
var accessors = this._addAttributes(attributes);
var glTFMesh = {
const glTFMesh = {
primitives: [{

@@ -89,5 +82,5 @@ attributes: accessors,

addPointCloud(attributes) {
var accessorIndices = this._addAttributes(attributes);
const accessorIndices = this._addAttributes(attributes);
var glTFMesh = {
const glTFMesh = {
primitives: [{

@@ -103,5 +96,3 @@ attributes: accessorIndices,

addCompressedMesh(attributes, indices) {
var mode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 4;
addCompressedMesh(attributes, indices, mode = 4) {
if (!this.DracoWriter || !this.DracoLoader) {

@@ -112,13 +103,13 @@ throw new Error('DracoWriter/DracoLoader not available');

this.registerRequiredExtension(KHR_DRACO_MESH_COMPRESSION);
var compressedData = this.DracoWriter.encodeSync({
const compressedData = this.DracoWriter.encodeSync({
attributes
});
var decodedData = this.DracoLoader.parseSync({
const decodedData = this.DracoLoader.parseSync({
attributes
});
var fauxAccessors = this._addFauxAttributes(decodedData.attributes);
const fauxAccessors = this._addFauxAttributes(decodedData.attributes);
var bufferViewIndex = this.addBufferView(compressedData);
var glTFMesh = {
const bufferViewIndex = this.addBufferView(compressedData);
const glTFMesh = {
primitives: [{

@@ -146,7 +137,7 @@ attributes: fauxAccessors,

attributes.mode = 0;
var compressedData = this.DracoWriter.encodeSync(attributes, {
const compressedData = this.DracoWriter.encodeSync(attributes, {
pointcloud: true
});
var bufferViewIndex = this.addBufferView(compressedData);
var glTFMesh = {
const bufferViewIndex = this.addBufferView(compressedData);
const glTFMesh = {
primitives: [{

@@ -169,7 +160,7 @@ attributes: {},

addImage(imageData) {
var bufferViewIndex = this.addBufferView(imageData);
var sizeAndType = getImageMetadata(imageData) || {};
const bufferViewIndex = this.addBufferView(imageData);
const sizeAndType = getImageMetadata(imageData) || {};
if (sizeAndType) {
var {
const {
mimeType,

@@ -176,0 +167,0 @@ width,

import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";

@@ -14,3 +13,3 @@ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

import GLTFPostProcessorOld from './gltf-post-processor-old';
var DEFAULT_OPTIONS = {
const DEFAULT_OPTIONS = {
fetchLinkedResources: true,

@@ -25,38 +24,30 @@ fetch: fetchFile,

export default class GLTFParser {
parse(gltf) {
var _this = this,
_arguments = arguments;
async parse(gltf, options = {}) {
options = Object.assign({}, DEFAULT_OPTIONS, options);
this.parseSync(gltf, _objectSpread({}, options, {
postProcess: false,
decompress: false
}));
return _asyncToGenerator(function* () {
var options = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : {};
options = Object.assign({}, DEFAULT_OPTIONS, options);
if (options.fetchLinkedResources) {
await this._loadLinkedAssets(options);
}
_this.parseSync(gltf, _objectSpread({}, options, {
postProcess: false,
decompress: false
}));
if (options.decompress) {
this._decompressMeshes(options);
}
if (options.fetchLinkedResources) {
yield _this._loadLinkedAssets(options);
}
if (options.postProcess) {
const postProcessor = new GLTFPostProcessorOld();
postProcessor.postProcess(this.gltf, this.glbParser, options);
}
if (options.decompress) {
_this._decompressMeshes(options);
}
if (options.postProcess) {
var postProcessor = new GLTFPostProcessorOld();
postProcessor.postProcess(_this.gltf, _this.glbParser, options);
}
return _this.gltf;
})();
return this.gltf;
}
parseSync(gltf) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
parseSync(gltf, options = {}) {
options = Object.assign({}, DEFAULT_OPTIONS, options);
if (gltf instanceof ArrayBuffer && !GLBParser.isGLB(gltf, options)) {
var textDecoder = new TextDecoder();
const textDecoder = new TextDecoder();
gltf = textDecoder.decode(gltf);

@@ -84,3 +75,3 @@ }

if (options.postProcess) {
var postProcessor = new GLTFPostProcessorOld();
const postProcessor = new GLTFPostProcessorOld();
postProcessor.postProcess(this.gltf, this.glbParser, options);

@@ -93,3 +84,3 @@ }

getApplicationData(key) {
var data = this.json[key];
const data = this.json[key];
return data;

@@ -99,3 +90,3 @@ }

getExtraData(key) {
var extras = this.json.extras || {};
const extras = this.json.extras || {};
return extras[key];

@@ -105,4 +96,4 @@ }

getExtension(extensionName) {
var isExtension = this.getUsedExtensions().find(name => name === extensionName);
var extensions = this.json.extensions || {};
const isExtension = this.getUsedExtensions().find(name => name === extensionName);
const extensions = this.json.extensions || {};
return isExtension ? extensions[extensionName] || true : null;

@@ -112,3 +103,3 @@ }

getRequiredExtension(extensionName) {
var isRequired = this.getRequiredExtensions().find(name => name === extensionName);
const isRequired = this.getRequiredExtensions().find(name => name === extensionName);
return isRequired ? this.getExtension(extensionName) : null;

@@ -178,3 +169,3 @@ }

var object = this.gltf[array] && this.gltf[array][index];
const object = this.gltf[array] && this.gltf[array][index];

@@ -188,21 +179,15 @@ if (!object) {

_loadLinkedAssets(options) {
var _this2 = this;
return _asyncToGenerator(function* () {
return yield Promise.all(_this2.gltf.buffers.map(buffer => _this2._loadBuffer(buffer, options)));
})();
async _loadLinkedAssets(options) {
return await Promise.all(this.gltf.buffers.map(buffer => this._loadBuffer(buffer, options)));
}
_loadBuffer(buffer, options) {
return _asyncToGenerator(function* () {
if (buffer.uri && options.uri) {
var fetch = options.fetch || window.fetch;
var uri = getFullUri(buffer.uri, options.uri);
var response = yield fetch(uri);
var arrayBuffer = yield response.arrayBuffer();
buffer.data = arrayBuffer;
buffer.uri = null;
}
})();
async _loadBuffer(buffer, options) {
if (buffer.uri && options.uri) {
const fetch = options.fetch || window.fetch;
const uri = getFullUri(buffer.uri, options.uri);
const response = await fetch(uri);
const arrayBuffer = await response.arrayBuffer();
buffer.data = arrayBuffer;
buffer.uri = null;
}
}

@@ -215,4 +200,4 @@

for (var mesh of this.gltf.meshes || []) {
for (var primitive of mesh.primitives) {
for (const mesh of this.gltf.meshes || []) {
for (const primitive of mesh.primitives) {
this._decompressKhronosDracoPrimitive(primitive, options);

@@ -234,3 +219,3 @@

_decompressKhronosDracoPrimitive(primitive, options) {
var compressedMesh = primitive.extensions && primitive.extensions[KHR_DRACO_MESH_COMPRESSION];
const compressedMesh = primitive.extensions && primitive.extensions[KHR_DRACO_MESH_COMPRESSION];

@@ -243,5 +228,5 @@ if (!compressedMesh) {

var buffer = this._getBufferViewArray(compressedMesh.bufferView);
const buffer = this._getBufferViewArray(compressedMesh.bufferView);
var decodedData = options.DracoLoader.parseSync(buffer);
const decodedData = options.DracoLoader.parseSync(buffer);
primitive.attributes = getGLTFAccessors(decodedData.attributes);

@@ -255,3 +240,3 @@

_decompressUberDracoPrimitive(primitive, options) {
var compressedMesh = primitive.extensions && primitive.extensions[UBER_POINT_CLOUD_EXTENSION];
const compressedMesh = primitive.extensions && primitive.extensions[UBER_POINT_CLOUD_EXTENSION];

@@ -268,5 +253,5 @@ if (!compressedMesh) {

var buffer = this._getBufferViewArray(compressedMesh.bufferView);
const buffer = this._getBufferViewArray(compressedMesh.bufferView);
var decodedData = options.DracoLoader.parseSync(buffer);
const decodedData = options.DracoLoader.parseSync(buffer);
primitive.attributes = decodedData.attributes;

@@ -276,3 +261,3 @@ }

_getBufferViewArray(bufferViewIndex) {
var bufferView = this.gltf.bufferViews[bufferViewIndex];
const bufferView = this.gltf.bufferViews[bufferViewIndex];

@@ -283,4 +268,4 @@ if (this.glbParser) {

var buffer = this.gltf.buffers[bufferView.buffer].data;
var byteOffset = bufferView.byteOffset || 0;
const buffer = this.gltf.buffers[bufferView.buffer].data;
const byteOffset = bufferView.byteOffset || 0;
return new Uint8Array(buffer, byteOffset, bufferView.byteLength);

@@ -304,6 +289,6 @@ }

_removeStringFromArray(array, string) {
var found = true;
let found = true;
while (found) {
var index = array.indexOf(string);
const index = array.indexOf(string);

@@ -310,0 +295,0 @@ if (index > -1) {

import { getFullUri } from '../gltf-utils/gltf-utils';
var COMPONENTS = {
const COMPONENTS = {
SCALAR: 1,

@@ -11,3 +11,3 @@ VEC2: 2,

};
var BYTES = {
const BYTES = {
5120: 1,

@@ -20,3 +20,3 @@ 5121: 1,

};
var GL_SAMPLER = {
const GL_SAMPLER = {
TEXTURE_MAG_FILTER: 0x2800,

@@ -30,3 +30,3 @@ TEXTURE_MIN_FILTER: 0x2801,

};
var SAMPLER_PARAMETER_GLTF_TO_GL = {
const SAMPLER_PARAMETER_GLTF_TO_GL = {
magFilter: GL_SAMPLER.TEXTURE_MAG_FILTER,

@@ -37,3 +37,3 @@ minFilter: GL_SAMPLER.TEXTURE_MIN_FILTER,

};
var DEFAULT_SAMPLER = {
const DEFAULT_SAMPLER = {
[GL_SAMPLER.TEXTURE_MAG_FILTER]: GL_SAMPLER.LINEAR,

@@ -54,4 +54,3 @@ [GL_SAMPLER.TEXTURE_MIN_FILTER]: GL_SAMPLER.NEAREST_MIPMAP_LINEAR,

export default class GLTFPostProcessorOld {
postProcess(gltf, glbParser) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
postProcess(gltf, glbParser, options = {}) {
this.gltf = gltf;

@@ -65,5 +64,4 @@ this.glbParser = glbParser;

_resolveToTree() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var {
_resolveToTree(options = {}) {
const {
gltf

@@ -144,3 +142,3 @@ } = this;

var object = this.gltf[array] && this.gltf[array][index];
const object = this.gltf[array] && this.gltf[array][index];

@@ -184,4 +182,4 @@ if (!object) {

for (var primitive of mesh.primitives) {
for (var attribute in primitive.attributes) {
for (const primitive of mesh.primitives) {
for (const attribute in primitive.attributes) {
primitive.attributes[attribute] = this.getAccessor(primitive.attributes[attribute]);

@@ -216,3 +214,3 @@ }

if (material.pbrMetallicRoughness) {
var mr = material.pbrMetallicRoughness;
const mr = material.pbrMetallicRoughness;

@@ -251,4 +249,4 @@ if (mr.baseColorTexture) {

for (var key in sampler) {
var glEnum = this._enumSamplerParameter(key);
for (const key in sampler) {
const glEnum = this._enumSamplerParameter(key);

@@ -272,3 +270,3 @@ if (glEnum !== undefined) {

var {
const {
createImages = true

@@ -285,3 +283,3 @@ } = options;

return new Promise(resolve => {
var img = new Image();
const img = new Image();
img.crossOrigin = 'anonymous';

@@ -307,3 +305,3 @@

} else {
var byteOffset = bufferView.byteOffset || 0;
const byteOffset = bufferView.byteOffset || 0;
bufferView.data = new Uint8Array(bufferView.buffer.data, byteOffset, bufferView.byteLength);

@@ -320,6 +318,6 @@ }

_process_extension_KHR_lights_punctual() {
var {
const {
gltf
} = this;
var extension = gltf.extensions && gltf.extensions.KHR_lights_punctual;
const extension = gltf.extensions && gltf.extensions.KHR_lights_punctual;

@@ -332,4 +330,4 @@ if (extension) {

for (var node of gltf.nodes || []) {
var nodeExtension = node.extensions && node.extensions.KHR_lights_punctual;
for (const node of gltf.nodes || []) {
const nodeExtension = node.extensions && node.extensions.KHR_lights_punctual;

@@ -360,6 +358,6 @@ if (nodeExtension) {

_removeStringFromArray(array, string) {
var found = true;
let found = true;
while (found) {
var index = array.indexOf(string);
const index = array.indexOf(string);

@@ -366,0 +364,0 @@ if (index > -1) {

@@ -1,4 +0,2 @@

export function flattenToTypedArray(nestedArray) {
var ArrayType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Float32Array;
export function flattenToTypedArray(nestedArray, ArrayType = Float32Array) {
if (nestedArray.length === 0) {

@@ -12,4 +10,4 @@ return new Float32Array(0);

var count = countVertices(nestedArray);
var typedArray = new ArrayType(count);
const count = countVertices(nestedArray);
const typedArray = new ArrayType(count);
flattenVerticesInPlace(nestedArray, typedArray);

@@ -19,10 +17,9 @@ return typedArray;

function countVertices(nestedArray) {
var dimensions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3;
var nestedCount = 0;
var localCount = 0;
var index = -1;
function countVertices(nestedArray, dimensions = 3) {
let nestedCount = 0;
let localCount = 0;
let index = -1;
while (++index < nestedArray.length) {
var value = nestedArray[index];
const value = nestedArray[index];

@@ -39,8 +36,7 @@ if (Array.isArray(value) || ArrayBuffer.isView(value)) {

function checkVertices(nestedArray) {
var predicate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Number.isFinite;
var index = -1;
function checkVertices(nestedArray, predicate = Number.isFinite) {
let index = -1;
while (++index < nestedArray.length) {
var value = nestedArray[index];
const value = nestedArray[index];

@@ -59,4 +55,3 @@ if (Array.isArray(value) || ArrayBuffer.isView(value)) {

function flattenVerticesInPlace(nestedArray, result) {
var dimensions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 3;
function flattenVerticesInPlace(nestedArray, result, dimensions = 3) {
flattenVerticesInPlaceRecursive(nestedArray, result, dimensions, 0);

@@ -67,7 +62,7 @@ return result;

function flattenVerticesInPlaceRecursive(nestedArray, result, dimensions, insert) {
var index = -1;
var vertexLength = 0;
let index = -1;
let vertexLength = 0;
while (++index < nestedArray.length) {
var value = nestedArray[index];
const value = nestedArray[index];

@@ -74,0 +69,0 @@ if (Array.isArray(value) || ArrayBuffer.isView(value)) {

import { flattenToTypedArray } from './flatten-to-typed-array';
export default function packBinaryJson(json, glbBuilder) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var {
export default function packBinaryJson(json, glbBuilder, options = {}) {
const {
flattenArrays = false
} = options;
var object = json;
let object = json;

@@ -14,3 +13,3 @@ if (typeof object === 'string' && object.indexOf('#/') === 0) {

if (Array.isArray(object)) {
var typedArray = flattenArrays && flattenToTypedArray(object);
const typedArray = flattenArrays && flattenToTypedArray(object);

@@ -26,7 +25,7 @@ if (typedArray) {

if (glbBuilder.isImage(object)) {
var imageIndex = glbBuilder.addImage(object);
const imageIndex = glbBuilder.addImage(object);
return "#/images/".concat(imageIndex);
}
var bufferIndex = glbBuilder.addBuffer(object);
const bufferIndex = glbBuilder.addBuffer(object);
return "#/accessors/".concat(bufferIndex);

@@ -36,5 +35,5 @@ }

if (object !== null && typeof object === 'object') {
var newObject = {};
const newObject = {};
for (var key in object) {
for (const key in object) {
newObject[key] = packBinaryJson(object[key], glbBuilder, options);

@@ -41,0 +40,0 @@ }

@@ -1,10 +0,8 @@

export default function unpackJsonArrays(json, buffers) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
export default function unpackJsonArrays(json, buffers, options = {}) {
return unpackJsonArraysRecursive(json, json, buffers, options);
}
function unpackJsonArraysRecursive(json, topJson, buffers) {
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var object = json;
var buffer = decodeJSONPointer(object, buffers);
function unpackJsonArraysRecursive(json, topJson, buffers, options = {}) {
const object = json;
const buffer = decodeJSONPointer(object, buffers);

@@ -20,5 +18,5 @@ if (buffer) {

if (object !== null && typeof object === 'object') {
var newObject = {};
const newObject = {};
for (var key in object) {
for (const key in object) {
newObject[key] = unpackJsonArraysRecursive(object[key], topJson, buffers, options);

@@ -34,7 +32,7 @@ }

function decodeJSONPointer(object, buffers) {
var pointer = parseJSONPointer(object);
const pointer = parseJSONPointer(object);
if (pointer) {
var [field, index] = pointer;
var buffer = buffers[field] && buffers[field][index];
const [field, index] = pointer;
const buffer = buffers[field] && buffers[field][index];

@@ -57,6 +55,6 @@ if (buffer) {

var matches = value.match(/#\/([a-z]+)\/([0-9]+)/);
let matches = value.match(/#\/([a-z]+)\/([0-9]+)/);
if (matches) {
var index = parseInt(matches[2], 10);
const index = parseInt(matches[2], 10);
return [matches[1], index];

@@ -68,5 +66,4 @@ }

if (matches) {
var _index = parseInt(matches[1], 10);
return ['accessors', _index];
const index = parseInt(matches[1], 10);
return ['accessors', index];
}

@@ -73,0 +70,0 @@ }

@@ -8,6 +8,6 @@ import assert from '../../utils/assert';

var bufferViews = json.bufferViews || [];
const bufferViews = json.bufferViews || [];
for (var i = 0; i < bufferViews.length; ++i) {
var bufferView = bufferViews[i];
for (let i = 0; i < bufferViews.length; ++i) {
const bufferView = bufferViews[i];
assert(bufferView.byteLength >= 0);

@@ -23,16 +23,16 @@ }

function unpackAccessors(arrayBuffer, bufferViews, json) {
var accessors = json.accessors || [];
var accessorBuffers = [];
const accessors = json.accessors || [];
const accessorBuffers = [];
for (var i = 0; i < accessors.length; ++i) {
var accessor = accessors[i];
for (let i = 0; i < accessors.length; ++i) {
const accessor = accessors[i];
assert(accessor);
var bufferView = bufferViews[accessor.bufferView];
const bufferView = bufferViews[accessor.bufferView];
if (bufferView) {
var {
const {
ArrayType,
length
} = getAccessorArrayTypeAndLength(accessor, bufferView);
var array = new ArrayType(arrayBuffer, bufferView.byteOffset, length);
const array = new ArrayType(arrayBuffer, bufferView.byteOffset, length);
array.accessor = accessor;

@@ -47,11 +47,11 @@ accessorBuffers.push(array);

function unpackImages(arrayBuffer, bufferViews, json) {
var images = json.images || [];
var imageBuffers = [];
const images = json.images || [];
const imageBuffers = [];
for (var i = 0; i < images.length; ++i) {
var image = images[i];
for (let i = 0; i < images.length; ++i) {
const image = images[i];
assert(image);
var bufferView = bufferViews[image.bufferView];
const bufferView = bufferViews[image.bufferView];
assert(bufferView);
var array = new Uint8Array(arrayBuffer, bufferView.byteOffset, bufferView.byteLength);
const array = new Uint8Array(arrayBuffer, bufferView.byteOffset, bufferView.byteLength);
array.imate = image;

@@ -65,8 +65,8 @@ imageBuffers.push(array);

function getArrayBufferAtOffset(arrayBuffer, byteOffset) {
var length = arrayBuffer.byteLength - byteOffset;
var binaryBuffer = new ArrayBuffer(length);
var sourceArray = new Uint8Array(arrayBuffer);
var binaryArray = new Uint8Array(binaryBuffer);
const length = arrayBuffer.byteLength - byteOffset;
const binaryBuffer = new ArrayBuffer(length);
const sourceArray = new Uint8Array(arrayBuffer);
const binaryArray = new Uint8Array(binaryBuffer);
for (var i = 0; i < length; i++) {
for (let i = 0; i < length; i++) {
binaryArray[i] = sourceArray[byteOffset + i];

@@ -73,0 +73,0 @@ }

import { copyPaddedStringToDataView, copyPaddedArrayBufferToDataView } from '@loaders.gl/loader-utils';
var MAGIC_glTF = 0x46546c67;
var MAGIC_JSON = 0x4e4f534a;
var MAGIC_BIN = 0x004e4942;
var LE = true;
export default function encodeGLBSync(glb, dataView) {
var byteOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var {
const MAGIC_glTF = 0x46546c67;
const MAGIC_JSON = 0x4e4f534a;
const MAGIC_BIN = 0x004e4942;
const LE = true;
export default function encodeGLBSync(glb, dataView, byteOffset = 0, options = {}) {
const {
magic = MAGIC_glTF,

@@ -15,3 +13,3 @@ version = 2,

} = glb;
var byteOffsetStart = byteOffset;
const byteOffsetStart = byteOffset;

@@ -24,5 +22,5 @@ if (dataView) {

var byteOffsetFileLength = byteOffset + 8;
const byteOffsetFileLength = byteOffset + 8;
byteOffset += 12;
var byteOffsetJsonHeader = byteOffset;
const byteOffsetJsonHeader = byteOffset;

@@ -35,7 +33,7 @@ if (dataView) {

byteOffset += 8;
var jsonString = JSON.stringify(json);
const jsonString = JSON.stringify(json);
byteOffset = copyPaddedStringToDataView(dataView, byteOffset, jsonString, 4);
if (dataView) {
var jsonByteLength = byteOffset - byteOffsetJsonHeader - 8;
const jsonByteLength = byteOffset - byteOffsetJsonHeader - 8;
dataView.setUint32(byteOffsetJsonHeader + 0, jsonByteLength, LE);

@@ -45,3 +43,3 @@ }

if (binary) {
var byteOffsetBinHeader = byteOffset;
const byteOffsetBinHeader = byteOffset;

@@ -57,3 +55,3 @@ if (dataView) {

if (dataView) {
var binByteLength = byteOffset - byteOffsetBinHeader - 8;
const binByteLength = byteOffset - byteOffsetBinHeader - 8;
dataView.setUint32(byteOffsetBinHeader + 0, binByteLength, LE);

@@ -64,3 +62,3 @@ }

if (dataView) {
var fileByteLength = byteOffset - byteOffsetStart;
const fileByteLength = byteOffset - byteOffsetStart;
dataView.setUint32(byteOffsetFileLength, fileByteLength, LE);

@@ -67,0 +65,0 @@ }

@@ -7,7 +7,5 @@ import encodeGLBSync from './encode-glb';

function convertBuffersToBase64(gltf) {
var {
firstBuffer = 0
} = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
function convertBuffersToBase64(gltf, {
firstBuffer = 0
} = {}) {
if (gltf.buffers && gltf.buffers.length > firstBuffer) {

@@ -14,0 +12,0 @@ throw new Error('encodeGLTF: multiple buffers not yet implemented');

import GLTFScenegraph from '../gltf-scenegraph';
import { KHR_DRACO_MESH_COMPRESSION } from '../gltf-constants';
import { getGLTFAccessors, getGLTFAccessor } from '../gltf-utils/gltf-attribute-utils';
import { parse } from '@loaders.gl/core';
export default class KHR_draco_mesh_compression {

@@ -9,90 +10,101 @@ static get name() {

static decode(gltfData, options) {
var gltfScenegraph = new GLTFScenegraph(gltfData);
static async decode(gltfData, options = {}) {
if (!options.decompress) {
return;
}
for (var mesh of gltfScenegraph.json.meshes || []) {
KHR_draco_mesh_compression.decompressMesh(mesh, options);
const scenegraph = new GLTFScenegraph(gltfData);
const promises = [];
for (const primitive of meshPrimitiveIterator(scenegraph)) {
if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) {
promises.push(decompressPrimitive(primitive, scenegraph, options));
}
}
gltfScenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);
await Promise.all(promises);
scenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);
}
static encode(gltfData, options) {
var gltfScenegraph = new GLTFScenegraph(gltfData);
static decodeSync(gltfData, options) {
if (!options.decompress) {
return;
}
for (var mesh of gltfScenegraph.json.meshes || []) {
KHR_draco_mesh_compression.compressMesh(mesh, options);
gltfScenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);
const scenegraph = new GLTFScenegraph(gltfData);
if (scenegraph.getRequiredExtension(KHR_DRACO_MESH_COMPRESSION)) {
throw new Error('Cannot synchronously decode Draco');
}
}
static compressMesh(attributes, indices) {
var mode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 4;
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
static encode(gltfData, options = {}) {
const scenegraph = new GLTFScenegraph(gltfData);
if (!options.DracoWriter || !options.DracoLoader) {
throw new Error('DracoWriter/DracoLoader not available');
for (const mesh of scenegraph.json.meshes || []) {
compressMesh(mesh, options);
scenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);
}
}
var compressedData = options.DracoWriter.encodeSync({
attributes
});
var decodedData = options.DracoLoader.parseSync({
attributes
});
}
var fauxAccessors = options._addFauxAttributes(decodedData.attributes);
async function decompressPrimitive(primitive, scenegraph, options) {
const compressedPrimitive = scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION);
const buffer = scenegraph.getTypedArrayForBufferView(compressedPrimitive.bufferView);
const subArray = new Uint8Array(buffer.buffer).subarray(buffer.byteOffset);
const bufferCopy = new Uint8Array(subArray);
const decodedData = await parse(bufferCopy);
primitive.attributes = getGLTFAccessors(decodedData.attributes);
var bufferViewIndex = options.addBufferView(compressedData);
var glTFMesh = {
primitives: [{
attributes: fauxAccessors,
mode,
extensions: {
[KHR_DRACO_MESH_COMPRESSION]: {
bufferView: bufferViewIndex,
attributes: fauxAccessors
}
}
}]
};
return glTFMesh;
if (decodedData.indices) {
primitive.indices = getGLTFAccessor(decodedData.indices);
}
static decompressMesh(mesh) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
checkPrimitive(primitive);
}
for (var primitive of mesh.primitives) {
KHR_draco_mesh_compression._decompressMeshPrimitive(primitive, options);
if (!primitive.attributes || Object.keys(primitive.attributes).length === 0) {
throw new Error('Empty glTF primitive: decompression failure?');
}
}
function compressMesh(attributes, indices, mode = 4, options = {}) {
if (!options.DracoWriter || !options.DracoLoader) {
throw new Error('DracoWriter/DracoLoader not available');
}
static _decompressMeshPrimitive(primitive, options) {
var compressedPrimitive = primitive.extensions && primitive.extensions[KHR_DRACO_MESH_COMPRESSION];
const compressedData = options.DracoWriter.encodeSync({
attributes
});
const decodedData = options.DracoLoader.parseSync({
attributes
});
if (!compressedPrimitive) {
return;
}
const fauxAccessors = options._addFauxAttributes(decodedData.attributes);
if (!options.DracoLoader || !options.decompress) {
return;
}
const bufferViewIndex = options.addBufferView(compressedData);
const glTFMesh = {
primitives: [{
attributes: fauxAccessors,
mode,
extensions: {
[KHR_DRACO_MESH_COMPRESSION]: {
bufferView: bufferViewIndex,
attributes: fauxAccessors
}
}
}]
};
return glTFMesh;
}
delete primitive.extensions[KHR_DRACO_MESH_COMPRESSION];
function checkPrimitive(primitive) {
if (!primitive.attributes && Object.keys(primitive.attributes).length > 0) {
throw new Error('Empty glTF primitive detected: Draco decompression failure?');
}
}
var buffer = this._getBufferViewArray(compressedPrimitive.bufferView);
var decodedData = options.DracoLoader.parseSync(buffer);
primitive.attributes = getGLTFAccessors(decodedData.attributes);
if (decodedData.indices) {
primitive.indices = getGLTFAccessor(decodedData.indices);
function* meshPrimitiveIterator(scenegraph) {
for (const mesh of scenegraph.json.meshes || []) {
for (const primitive of mesh.primitives) {
yield primitive;
}
}
}
//# sourceMappingURL=KHR_draco_mesh_compression.js.map

@@ -10,4 +10,4 @@ import GLTFScenegraph from '../gltf-scenegraph';

static decode(gltfData, options) {
var gltfScenegraph = new GLTFScenegraph(gltfData);
var extension = gltfScenegraph.getExtension(KHR_LIGHTS_PUNCTUAL);
const gltfScenegraph = new GLTFScenegraph(gltfData);
const extension = gltfScenegraph.getExtension(KHR_LIGHTS_PUNCTUAL);

@@ -19,4 +19,4 @@ if (extension) {

for (var node of gltfScenegraph.nodes || []) {
var nodeExtension = node.extensions && node.extensions.KHR_lights_punctual;
for (const node of gltfScenegraph.nodes || []) {
const nodeExtension = node.extensions && node.extensions.KHR_lights_punctual;

@@ -31,4 +31,4 @@ if (nodeExtension) {

static encode(gltfData, options) {
var gltfScenegraph = new GLTFScenegraph(gltfData);
var {
const gltfScenegraph = new GLTFScenegraph(gltfData);
const {
json

@@ -38,3 +38,3 @@ } = gltfScenegraph;

if (json.lights) {
var extension = gltfScenegraph.addExtensions(KHR_LIGHTS_PUNCTUAL);
const extension = gltfScenegraph.addExtensions(KHR_LIGHTS_PUNCTUAL);
assert(!extension.lights);

@@ -46,4 +46,4 @@ extension.lights = json.lights;

if (gltfScenegraph.json.lights) {
for (var light of gltfScenegraph.json.lights) {
var node = light.node;
for (const light of gltfScenegraph.json.lights) {
const node = light.node;
gltfScenegraph.addObjectExtension(node, KHR_LIGHTS_PUNCTUAL, light);

@@ -50,0 +50,0 @@ }

@@ -1,5 +0,5 @@

export var KHR_DRACO_MESH_COMPRESSION = 'KHR_draco_mesh_compression';
export var UBER_POINT_CLOUD_EXTENSION = 'UBER_draco_point_cloud_compression';
export var KHR_LIGHTS_PUNCTUAL = 'KHR_lights_punctual';
var COMPONENTS = {
export const KHR_DRACO_MESH_COMPRESSION = 'KHR_draco_mesh_compression';
export const UBER_POINT_CLOUD_EXTENSION = 'UBER_draco_point_cloud_compression';
export const KHR_LIGHTS_PUNCTUAL = 'KHR_lights_punctual';
const COMPONENTS = {
SCALAR: 1,

@@ -13,3 +13,3 @@ VEC2: 2,

};
var BYTES = {
const BYTES = {
5120: 1,

@@ -29,7 +29,7 @@ 5121: 1,

export function getGLEnumFromSamplerParameter(parameter) {
var GL_TEXTURE_MAG_FILTER = 0x2800;
var GL_TEXTURE_MIN_FILTER = 0x2801;
var GL_TEXTURE_WRAP_S = 0x2802;
var GL_TEXTURE_WRAP_T = 0x2803;
var PARAMETER_MAP = {
const GL_TEXTURE_MAG_FILTER = 0x2800;
const GL_TEXTURE_MIN_FILTER = 0x2801;
const GL_TEXTURE_WRAP_S = 0x2802;
const GL_TEXTURE_WRAP_T = 0x2803;
const PARAMETER_MAP = {
magFilter: GL_TEXTURE_MAG_FILTER,

@@ -36,0 +36,0 @@ minFilter: GL_TEXTURE_MIN_FILTER,

@@ -17,3 +17,3 @@ import { getImageMIMEType } from '@loaders.gl/images';

},
binary: null
buffers: []
};

@@ -23,2 +23,3 @@ }

this.gltf = gltf;
assert(this.gltf.json);
}

@@ -31,3 +32,3 @@

getApplicationData(key) {
var data = this.json[key];
const data = this.json[key];
return data;

@@ -37,3 +38,3 @@ }

getExtraData(key) {
var extras = this.json.extras || {};
const extras = this.json.extras || {};
return extras[key];

@@ -43,4 +44,4 @@ }

getExtension(extensionName) {
var isExtension = this.getUsedExtensions().find(name => name === extensionName);
var extensions = this.json.extensions || {};
const isExtension = this.getUsedExtensions().find(name => name === extensionName);
const extensions = this.json.extensions || {};
return isExtension ? extensions[extensionName] || true : null;

@@ -50,3 +51,3 @@ }

getRequiredExtension(extensionName) {
var isRequired = this.getRequiredExtensions().find(name => name === extensionName);
const isRequired = this.getRequiredExtensions().find(name => name === extensionName);
return isRequired ? this.getExtension(extensionName) : null;

@@ -64,3 +65,3 @@ }

getObjectExtension(object, extensionName) {
var extensions = object.extensions || {};
const extensions = object.extensions || {};
return extensions[extensionName];

@@ -122,6 +123,6 @@ }

var object = this.gltf[array] && this.gltf[array][index];
const object = this.json[array] && this.json[array][index];
if (!object) {
console.warn("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
throw new Error("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
}

@@ -134,6 +135,7 @@

bufferView = this.getBufferView(bufferView);
var buffer = this.getBuffer(bufferView.buffer);
var arrayBuffer = buffer.data;
var byteOffset = bufferView.byteOffset || 0;
return new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
const bufferIndex = bufferView.buffer;
const binChunk = this.gltf.buffers[bufferIndex];
assert(binChunk);
const byteOffset = bufferView.byteOffset || 0 + binChunk.byteOffset;
return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
}

@@ -143,10 +145,10 @@

accessor = this.getAccessor(accessor);
var bufferView = this.getBuffer(accessor.bufferView);
var buffer = this.getBuffer(bufferView.buffer);
var arrayBuffer = buffer.data;
var {
const bufferView = this.getBuffer(accessor.bufferView);
const buffer = this.getBuffer(bufferView.buffer);
const arrayBuffer = buffer.data;
const {
ArrayType,
length
} = getAccessorArrayTypeAndLength(accessor, bufferView);
var byteOffset = bufferView.byteOffset + accessor.byteOffset;
const byteOffset = bufferView.byteOffset + accessor.byteOffset;
return new ArrayType(arrayBuffer, byteOffset, length);

@@ -157,6 +159,6 @@ }

image = this.getAccessor(image);
var bufferView = this.getBuffer(image.bufferView);
var buffer = this.getBuffer(bufferView.buffer);
var arrayBuffer = buffer.data;
var byteOffset = bufferView.byteOffset || 0;
const bufferView = this.getBuffer(image.bufferView);
const buffer = this.getBuffer(bufferView.buffer);
const arrayBuffer = buffer.data;
const byteOffset = bufferView.byteOffset || 0;
return new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);

@@ -223,12 +225,10 @@ }

setObjectExtension(object, extensionName, data) {
var extensions = object.extensions || {};
const extensions = object.extensions || {};
extensions[extensionName] = data;
}
addMesh(attributes, indices) {
var mode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 4;
addMesh(attributes, indices, mode = 4) {
const accessors = this._addAttributes(attributes);
var accessors = this._addAttributes(attributes);
var glTFMesh = {
const glTFMesh = {
primitives: [{

@@ -246,5 +246,5 @@ attributes: accessors,

addPointCloud(attributes) {
var accessorIndices = this._addAttributes(attributes);
const accessorIndices = this._addAttributes(attributes);
var glTFMesh = {
const glTFMesh = {
primitives: [{

@@ -262,4 +262,4 @@ attributes: accessorIndices,

mimeType = mimeType || getImageMIMEType(imageData);
var bufferViewIndex = this.addBufferView(imageData);
var glTFImage = {
const bufferViewIndex = this.addBufferView(imageData);
const glTFImage = {
bufferView: bufferViewIndex,

@@ -274,7 +274,7 @@ mimeType

addBufferView(buffer) {
var byteLength = buffer.byteLength;
const byteLength = buffer.byteLength;
assert(Number.isFinite(byteLength));
this.sourceBuffers = this.sourceBuffers || [];
this.sourceBuffers.push(buffer);
var glTFBufferView = {
const glTFBufferView = {
buffer: 0,

@@ -291,3 +291,3 @@ byteOffset: this.byteLength,

addAccessor(bufferViewIndex, accessor) {
var glTFAccessor = {
const glTFAccessor = {
bufferView: bufferViewIndex,

@@ -303,8 +303,7 @@ type: getAccessorTypeFromSize(accessor.size),

addBinaryBuffer(sourceBuffer) {
var accessor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
size: 3
};
var bufferViewIndex = this.addBufferView(sourceBuffer);
var accessorDefaults = {
addBinaryBuffer(sourceBuffer, accessor = {
size: 3
}) {
const bufferViewIndex = this.addBufferView(sourceBuffer);
const accessorDefaults = {
size: accessor.size,

@@ -322,9 +321,9 @@ componentType: getComponentTypeFromArray(sourceBuffer),

var totalByteLength = this.byteLength;
var arrayBuffer = new ArrayBuffer(totalByteLength);
var targetArray = new Uint8Array(arrayBuffer);
var dstByteOffset = 0;
const totalByteLength = this.byteLength;
const arrayBuffer = new ArrayBuffer(totalByteLength);
const targetArray = new Uint8Array(arrayBuffer);
let dstByteOffset = 0;
for (var i = 0; i < this.sourceBuffers.length; i++) {
var sourceBuffer = this.sourceBuffers[i];
for (let i = 0; i < this.sourceBuffers.length; i++) {
const sourceBuffer = this.sourceBuffers[i];
dstByteOffset = copyToArray(sourceBuffer, targetArray, dstByteOffset);

@@ -339,6 +338,6 @@ }

_removeStringFromArray(array, string) {
var found = true;
let found = true;
while (found) {
var index = array.indexOf(string);
const index = array.indexOf(string);

@@ -345,0 +344,0 @@ if (index > -1) {

import { getAccessorTypeFromSize, getComponentTypeFromArray } from './gltf-utils';
export function getGLTFAccessors(attributes) {
var accessors = {};
const accessors = {};
for (var name in attributes) {
var attribute = attributes[name];
for (const name in attributes) {
const attribute = attributes[name];
if (name !== 'indices') {
var glTFAccessor = getGLTFAccessor(attribute);
const glTFAccessor = getGLTFAccessor(attribute);
accessors[name] = glTFAccessor;

@@ -17,3 +17,3 @@ }

export function getGLTFAccessor(attribute, gltfAttributeName) {
var {
const {
buffer,

@@ -23,3 +23,3 @@ size,

} = getAccessorData(attribute, gltfAttributeName);
var glTFAccessor = {
const glTFAccessor = {
value: buffer,

@@ -40,5 +40,5 @@ size,

function getAccessorData(attribute, attributeName) {
var buffer = attribute;
var size = 1;
var count = 0;
let buffer = attribute;
let size = 1;
let count = 0;

@@ -65,5 +65,3 @@ if (attribute && attribute.value) {

function toTypedArray(array, ArrayType) {
var convertTypedArrays = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
function toTypedArray(array, ArrayType, convertTypedArrays = false) {
if (!array) {

@@ -70,0 +68,0 @@ return null;

import assert from '../utils/assert';
var TYPES = ['SCALAR', 'VEC2', 'VEC3', 'VEC4'];
var ARRAY_TO_COMPONENT_TYPE = new Map([[Int8Array, 5120], [Uint8Array, 5121], [Int16Array, 5122], [Uint16Array, 5123], [Uint32Array, 5125], [Float32Array, 5126]]);
export var ATTRIBUTE_TYPE_TO_COMPONENTS = {
const TYPES = ['SCALAR', 'VEC2', 'VEC3', 'VEC4'];
const ARRAY_TO_COMPONENT_TYPE = new Map([[Int8Array, 5120], [Uint8Array, 5121], [Int16Array, 5122], [Uint16Array, 5123], [Uint32Array, 5125], [Float32Array, 5126]]);
export const ATTRIBUTE_TYPE_TO_COMPONENTS = {
SCALAR: 1,

@@ -13,3 +13,3 @@ VEC2: 2,

};
export var ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE = {
export const ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE = {
5120: 1,

@@ -22,3 +22,3 @@ 5121: 1,

};
export var ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY = {
export const ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY = {
5120: Int8Array,

@@ -32,7 +32,7 @@ 5121: Uint8Array,

export function getAccessorTypeFromSize(size) {
var type = TYPES[size - 1];
const type = TYPES[size - 1];
return type || TYPES[0];
}
export function getComponentTypeFromArray(typedArray) {
var componentType = ARRAY_TO_COMPONENT_TYPE.get(typedArray.constructor);
const componentType = ARRAY_TO_COMPONENT_TYPE.get(typedArray.constructor);

@@ -46,7 +46,7 @@ if (!componentType) {

export function getAccessorArrayTypeAndLength(accessor, bufferView) {
var ArrayType = ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY[accessor.componentType];
var components = ATTRIBUTE_TYPE_TO_COMPONENTS[accessor.type];
var bytesPerComponent = ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE[accessor.componentType];
var length = accessor.count * components;
var byteLength = accessor.count * components * bytesPerComponent;
const ArrayType = ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY[accessor.componentType];
const components = ATTRIBUTE_TYPE_TO_COMPONENTS[accessor.type];
const bytesPerComponent = ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE[accessor.componentType];
const length = accessor.count * components;
const byteLength = accessor.count * components * bytesPerComponent;
assert(byteLength >= 0 && byteLength <= bufferView.byteLength);

@@ -60,5 +60,5 @@ return {

export function getFullUri(uri, base) {
var absolute = uri.startsWith('data:') || uri.startsWith('http:') || uri.startsWith('https:');
const absolute = uri.startsWith('data:') || uri.startsWith('http:') || uri.startsWith('https:');
return absolute ? uri : base.substr(0, base.lastIndexOf('/') + 1) + uri;
}
//# sourceMappingURL=gltf-utils.js.map
import { padTo4Bytes, assert } from '@loaders.gl/loader-utils';
var MAGIC_glTF = 0x676c5446;
var GLB_FILE_HEADER_SIZE = 12;
var GLB_CHUNK_HEADER_SIZE = 8;
var GLB_CHUNK_TYPE_JSON = 0x4e4f534a;
var GLB_CHUNK_TYPE_BIN = 0x004e4942;
var LE = true;
var BE = false;
const MAGIC_glTF = 0x676c5446;
const GLB_FILE_HEADER_SIZE = 12;
const GLB_CHUNK_HEADER_SIZE = 8;
const GLB_CHUNK_TYPE_JSON = 0x4e4f534a;
const GLB_CHUNK_TYPE_BIN = 0x004e4942;
const LE = true;
function getMagicString(dataView) {
return "".concat(String.fromCharCode(dataView.getUint8(0))).concat(String.fromCharCode(dataView.getUint8(1))).concat(String.fromCharCode(dataView.getUint8(2))).concat(String.fromCharCode(dataView.getUint8(3)));
function getMagicString(dataView, byteOffset = 0) {
return "".concat(String.fromCharCode(dataView.getUint8(byteOffset + 0))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 1))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 2))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 3)));
}
export function isGLB(arrayBuffer) {
var byteOffset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var dataView = new DataView(arrayBuffer);
var {
export function isGLB(arrayBuffer, byteOffset = 0, options = {}) {
const dataView = new DataView(arrayBuffer);
const {
magic = MAGIC_glTF
} = options;
var magic1 = dataView.getUint32(byteOffset, false);
const magic1 = dataView.getUint32(byteOffset, false);
return magic1 === magic || magic1 === MAGIC_glTF;
}
export default function parseGLBSync(glb, arrayBuffer) {
var byteOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var dataView = new DataView(arrayBuffer);
glb.byteOffset = byteOffset;
glb.magic = dataView.getUint32(byteOffset + 0, BE);
export default function parseGLBSync(glb, arrayBuffer, byteOffset = 0, options = {}) {
const dataView = new DataView(arrayBuffer);
glb.type = getMagicString(dataView, byteOffset + 0);
glb.version = dataView.getUint32(byteOffset + 4, LE);
glb.byteLength = dataView.getUint32(byteOffset + 8, LE);
glb.type = getMagicString(dataView);
var {
magic = MAGIC_glTF
} = options;
var isMagicValid = glb.magic === MAGIC_glTF || glb.magic === magic;
const byteLength = dataView.getUint32(byteOffset + 8, LE);
glb.header = {
byteOffset,
byteLength
};
if (!isMagicValid) {
if (glb.type !== 'glTF') {
console.warn("Invalid GLB magic string ".concat(glb.type));

@@ -43,27 +36,79 @@ }

assert(glb.version === 2, "Invalid GLB version ".concat(glb.version, ". Only .glb v2 supported"));
assert(glb.byteLength > 20);
var jsonChunkLength = dataView.getUint32(byteOffset + 12, LE);
var jsonChunkFormat = dataView.getUint32(byteOffset + 16, LE);
var isJSONChunk = jsonChunkFormat === GLB_CHUNK_TYPE_JSON || jsonChunkFormat === 0;
assert(isJSONChunk, "JSON chunk format ".concat(jsonChunkFormat));
var jsonChunkByteOffset = GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE;
var jsonChunk = new Uint8Array(arrayBuffer, byteOffset + jsonChunkByteOffset, jsonChunkLength);
var textDecoder = new TextDecoder('utf8');
var jsonText = textDecoder.decode(jsonChunk);
glb.json = JSON.parse(jsonText);
var binChunkStart = jsonChunkByteOffset + padTo4Bytes(jsonChunkLength);
glb.hasBinChunk = binChunkStart + 8 <= glb.byteLength;
assert(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
glb.json = {};
glb.hasBinChunk = false;
glb.binChunks = [];
parseGLBChunksSync(glb, dataView, byteOffset + 12, options);
addDeprecatedFields(glb);
return byteOffset + glb.header.byteLength;
}
if (glb.hasBinChunk) {
var binChunkLength = dataView.getUint32(byteOffset + binChunkStart + 0, LE);
var binChunkFormat = dataView.getUint32(byteOffset + binChunkStart + 4, LE);
var isBinChunk = binChunkFormat === GLB_CHUNK_TYPE_BIN || binChunkFormat === 1;
assert(isBinChunk, "BIN chunk format ".concat(binChunkFormat));
var binChunkByteOffset = binChunkStart + GLB_CHUNK_HEADER_SIZE;
glb.binChunkByteOffset = binChunkByteOffset;
glb.binChunkLength = binChunkLength;
function parseGLBChunksSync(glb, dataView, byteOffset, options) {
while (byteOffset + 8 <= glb.header.byteLength) {
const chunkLength = dataView.getUint32(byteOffset + 0, LE);
const chunkFormat = dataView.getUint32(byteOffset + 4, LE);
byteOffset += GLB_CHUNK_HEADER_SIZE;
switch (chunkFormat) {
case GLB_CHUNK_TYPE_JSON:
parseJSONChunk(glb, dataView, byteOffset, chunkLength, options);
break;
case GLB_CHUNK_TYPE_BIN:
parseBINChunk(glb, dataView, byteOffset, chunkLength, options);
break;
default:
break;
}
switch (chunkFormat) {
case 0:
if (!options.strict) {
parseJSONChunk(glb, dataView, byteOffset, chunkLength, options);
}
break;
case 1:
if (!options.strict) {
parseBINChunk(glb, dataView, byteOffset, chunkLength, options);
}
break;
default:
}
byteOffset += padTo4Bytes(chunkLength);
}
return byteOffset + glb.byteLength;
return byteOffset;
}
function parseJSONChunk(glb, dataView, byteOffset, chunkLength, options) {
const jsonChunk = new Uint8Array(dataView.buffer, byteOffset, chunkLength);
const textDecoder = new TextDecoder('utf8');
const jsonText = textDecoder.decode(jsonChunk);
glb.json = JSON.parse(jsonText);
}
function parseBINChunk(glb, dataView, byteOffset, chunkLength, options) {
glb.header.hasBinChunk = true;
glb.binChunks.push({
byteOffset,
byteLength: chunkLength,
arrayBuffer: dataView.buffer
});
}
function addDeprecatedFields(glb) {
glb.byteOffset = glb.header.byteOffset;
glb.magic = glb.header.magic;
glb.version = glb.header.version;
glb.byteLength = glb.header.byteLength;
glb.hasBinChunk = glb.binChunks.length >= 1;
glb.binChunkByteOffset = glb.header.hasBinChunk ? glb.binChunks[0].byteOffset : 0;
glb.binChunkLength = glb.header.hasBinChunk ? glb.binChunks[0].byteLength : 0;
}
//# sourceMappingURL=parse-glb.js.map
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";

@@ -11,52 +10,70 @@ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

import { getFullUri } from './gltf-utils/gltf-utils';
import { decodeExtensions, decodeExtensionsSync } from './extensions/extensions';
import parseGLBSync, { isGLB } from './parse-glb';
import * as EXTENSIONS from './extensions';
var DEFAULT_SYNC_OPTIONS = {
fetchLinkedResources: false,
decompress: false,
DracoLoader: null,
postProcess: true,
import postProcessGLTF from './post-process-gltf';
const DEFAULT_OPTIONS = {
fetchLinkedResources: true,
fetchImages: false,
createImages: false,
log: console
};
var DEFAULT_ASYNC_OPTIONS = {
fetchLinkedResources: true,
fetch: fetchFile,
decompress: false,
DracoLoader: null,
postProcess: true,
createImages: false,
postProcess: false,
log: console
};
export function isGLTF(arrayBuffer) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var dataView = new DataView(arrayBuffer);
var byteOffset = 0;
export function isGLTF(arrayBuffer, options = {}) {
const dataView = new DataView(arrayBuffer);
const byteOffset = 0;
return isGLB(dataView, byteOffset);
}
export function parseGLTFSync(gltf, arrayBufferOrString) {
var byteOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
options = Object.assign({}, DEFAULT_SYNC_OPTIONS, options);
var data = arrayBufferOrString;
export async function parseGLTF(gltf, arrayBufferOrString, byteOffset = 0, options = {}) {
options = _objectSpread({}, DEFAULT_OPTIONS, {}, options);
parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options);
const promises = [];
if (options.fetchImages) {
const promise = fetchImages(gltf, options);
promises.push(promise);
}
if (options.fetchLinkedResources) {
await fetchBuffers(gltf, options);
}
const promise = decodeExtensions(gltf, options);
promises.push(promise);
await Promise.all(promises);
return options.postProcess ? postProcessGLTF(gltf, options) : gltf;
}
export function parseGLTFSync(gltf, arrayBufferOrString, byteOffset = 0, options = {}) {
options = _objectSpread({}, DEFAULT_OPTIONS, {}, options);
parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options);
if (options.fetchLinkedResources) {
fetchBuffersSync(gltf, options);
}
if (options.decodeExtensions) {
decodeExtensionsSync(gltf, options);
}
return options.postProcess ? postProcessGLTF(gltf, options) : gltf;
}
function parseGLTFContainerSync(gltf, data, byteOffset, options) {
if (options.uri) {
gltf.baseUri = options.uri;
}
if (data instanceof ArrayBuffer && !isGLB(data, byteOffset, options)) {
var textDecoder = new TextDecoder();
const textDecoder = new TextDecoder();
data = textDecoder.decode(data);
}
gltf.buffers = [];
if (typeof data === 'string') {
gltf.json = JSON.parse(data);
} else if (data instanceof ArrayBuffer) {
byteOffset = parseGLBSync(gltf, data, byteOffset, options);
if (gltf.hasBinChunk) {
gltf.buffers.push({
arrayBuffer: data,
byteOffset: gltf.binChunkByteOffset,
byteLength: gltf.binChunkLength
});
}
gltf._glb = {};
byteOffset = parseGLBSync(gltf._glb, data, byteOffset, options);
gltf.json = gltf._glb.json;
} else {

@@ -66,72 +83,81 @@ gltf.json = data;

if (options.uri) {
gltf.baseUri = options.uri;
}
const buffers = gltf.json.buffers || [];
gltf.buffers = new Array(buffers.length).fill({});
if (options.fetchLinkedResources) {
for (var buffer of gltf.json.buffers || []) {
if (buffer.uri) {
throw new Error('parseGLTFSync: Cannot decode uri buffers');
}
}
if (gltf._glb && gltf._glb.hasBinChunk) {
gltf.buffers[0] = {
arrayBuffer: gltf._glb.binChunks[0].arrayBuffer,
byteOffset: gltf._glb.binChunks[0].byteOffset,
byteLength: gltf._glb.binChunks[0].byteLength
};
gltf.json.buffers[0].data = gltf.buffers[0].arrayBuffer;
gltf.json.buffers[0].byteOffset = gltf.buffers[0].byteOffset;
}
decodeExtensions(gltf, options);
return byteOffset;
const images = gltf.json.images || [];
gltf.images = new Array(images.length).fill({});
}
export function parseGLTF(_x, _x2) {
return _parseGLTF.apply(this, arguments);
}
function _parseGLTF() {
_parseGLTF = _asyncToGenerator(function* (gltf, arrayBufferOrString) {
var byteOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
options = Object.assign({}, DEFAULT_ASYNC_OPTIONS, options);
parseGLTFSync(gltf, arrayBufferOrString, byteOffset, _objectSpread({}, options, {
fetchLinkedResources: false,
postProcess: false,
decompress: false
}));
async function fetchBuffers(gltf, options) {
for (let i = 0; i < gltf.json.buffers.length; ++i) {
const buffer = gltf.json.buffers[i];
if (options.fetchLinkedResources) {
yield fetchLinkedResources(gltf, options);
if (!options.uri) {
console.warn('options.uri must be set to decode embedded glTF buffers');
}
return gltf;
});
return _parseGLTF.apply(this, arguments);
if (buffer.uri && options.uri) {
const fetch = options.fetch || window.fetch;
assert(fetch);
const uri = getFullUri(buffer.uri, options.uri);
const response = await fetch(uri);
const arrayBuffer = await response.arrayBuffer();
gltf.buffers[i] = {
arrayBuffer,
byteOffset: 0,
byteLength: arrayBuffer.byteLength
};
delete buffer.uri;
}
}
}
function fetchLinkedResources(_x3, _x4) {
return _fetchLinkedResources.apply(this, arguments);
}
function _fetchLinkedResources() {
_fetchLinkedResources = _asyncToGenerator(function* (gltf, options) {
for (var buffer of gltf.json.buffers) {
if (buffer.uri) {
var fetch = options.fetch || window.fetch;
assert(fetch);
var uri = getFullUri(buffer.uri, options.uri);
var response = yield fetch(uri);
var arrayBuffer = yield response.arrayBuffer();
buffer.data = arrayBuffer;
delete buffer.uri;
}
function fetchBuffersSync(gltf, options) {
for (const buffer of gltf.json.buffers || []) {
if (buffer.uri) {
throw new Error('parseGLTFSync: Cannot decode uri buffers');
}
});
return _fetchLinkedResources.apply(this, arguments);
}
}
function decodeExtensions(gltf, options) {
for (var extensionName in EXTENSIONS) {
var disableExtension = extensionName in options && !options[extensionName];
async function fetchImages(gltf, options) {
const images = gltf.json.images || [];
const promises = [];
if (!disableExtension) {
var extension = EXTENSIONS[extensionName];
extension.decode(gltf, options);
for (let i = 0; i < images.length; ++i) {
const image = images[i];
if ('uri' in image) {
promises.push(fetchAndParseLinkedImage(gltf, image, i, options));
}
}
return await Promise.all(promises);
}
async function fetchAndParseLinkedImage(gltf, image, i, options) {
const fetch = options.fetch || window.fetch;
assert(fetch);
const uri = getFullUri(image.uri, options.uri);
gltf.images[i] = await new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => resolve(img);
img.onerror = error => reject(error);
img.src = uri;
});
}
//# sourceMappingURL=parse-gltf.js.map

@@ -8,3 +8,4 @@ import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";

import { getFullUri } from './gltf-utils/gltf-utils';
var COMPONENTS = {
import assert from './utils/assert';
const COMPONENTS = {
SCALAR: 1,

@@ -18,3 +19,3 @@ VEC2: 2,

};
var BYTES = {
const BYTES = {
5120: 1,

@@ -27,3 +28,3 @@ 5121: 1,

};
var GL_SAMPLER = {
const GL_SAMPLER = {
TEXTURE_MAG_FILTER: 0x2800,

@@ -37,3 +38,3 @@ TEXTURE_MIN_FILTER: 0x2801,

};
var SAMPLER_PARAMETER_GLTF_TO_GL = {
const SAMPLER_PARAMETER_GLTF_TO_GL = {
magFilter: GL_SAMPLER.TEXTURE_MAG_FILTER,

@@ -44,3 +45,3 @@ minFilter: GL_SAMPLER.TEXTURE_MIN_FILTER,

};
var DEFAULT_SAMPLER = {
const DEFAULT_SAMPLER = {
[GL_SAMPLER.TEXTURE_MAG_FILTER]: GL_SAMPLER.LINEAR,

@@ -61,13 +62,21 @@ [GL_SAMPLER.TEXTURE_MIN_FILTER]: GL_SAMPLER.NEAREST_MIPMAP_LINEAR,

class GLTFPostProcessor {
postProcess(gltf) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
this.gltf = gltf;
this.json = gltf.json;
this.buffers = gltf.buffers;
return this._resolveTree(gltf.json, options);
postProcess(gltf, options = {}) {
const {
json,
buffers = [],
images = [],
baseUri = ''
} = gltf;
assert(json);
this.baseUri = baseUri;
this.json = json;
this.buffers = buffers;
this.images = images;
this._resolveTree(this.json, options);
return this.json;
}
_resolveTree(json) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_resolveTree(json, options = {}) {
if (json.bufferViews) {

@@ -116,4 +125,2 @@ json.bufferViews = json.bufferViews.map((bufView, i) => this._resolveBufferView(bufView, i));

}
return json;
}

@@ -174,3 +181,3 @@

var object = this.json[array] && this.json[array][index];
const object = this.json[array] && this.json[array][index];

@@ -185,3 +192,2 @@ if (!object) {

_resolveScene(scene, index) {
scene = _objectSpread({}, scene);
scene.id = scene.id || "scene-".concat(index);

@@ -193,3 +199,2 @@ scene.nodes = (scene.nodes || []).map(node => this.getNode(node));

_resolveNode(node, index) {
node = _objectSpread({}, node);
node.id = node.id || "node-".concat(index);

@@ -217,3 +222,2 @@

_resolveSkin(skin, index) {
skin = _objectSpread({}, skin);
skin.id = skin.id || "skin-".concat(index);

@@ -225,3 +229,2 @@ skin.inverseBindMatrices = this.getAccessor(skin.inverseBindMatrices);

_resolveMesh(mesh, index) {
mesh = _objectSpread({}, mesh);
mesh.id = mesh.id || "mesh-".concat(index);

@@ -232,6 +235,6 @@

primitive = _objectSpread({}, primitive);
var attributes = primitive.attributes;
const attributes = primitive.attributes;
primitive.attributes = {};
for (var attribute in attributes) {
for (const attribute in attributes) {
primitive.attributes[attribute] = this.getAccessor(attributes[attribute]);

@@ -256,3 +259,2 @@ }

_resolveMaterial(material, index) {
material = _objectSpread({}, material);
material.id = material.id || "material-".concat(index);

@@ -277,3 +279,3 @@

material.pbrMetallicRoughness = _objectSpread({}, material.pbrMetallicRoughness);
var mr = material.pbrMetallicRoughness;
const mr = material.pbrMetallicRoughness;

@@ -295,3 +297,2 @@ if (mr.baseColorTexture) {

_resolveAccessor(accessor, index) {
accessor = _objectSpread({}, accessor);
accessor.id = accessor.id || "accessor-".concat(index);

@@ -310,3 +311,2 @@

_resolveTexture(texture, index) {
texture = _objectSpread({}, texture);
texture.id = texture.id || "texture-".concat(index);

@@ -319,8 +319,7 @@ texture.sampler = 'sampler' in texture ? this.getSampler(texture.sampler) : DEFAULT_SAMPLER;

_resolveSampler(sampler, index) {
sampler = _objectSpread({}, sampler);
sampler.id = sampler.id || "sampler-".concat(index);
sampler.parameters = {};
for (var key in sampler) {
var glEnum = this._enumSamplerParameter(key);
for (const key in sampler) {
const glEnum = this._enumSamplerParameter(key);

@@ -340,3 +339,2 @@ if (glEnum !== undefined) {

_resolveImage(image, index, options) {
image = _objectSpread({}, image);
image.id = image.id || "image-".concat(index);

@@ -349,26 +347,48 @@

if ('uri' in image) {
var baseUri = options.uri || this.gltf.baseUri;
const preloadedImage = this.images[index];
if (preloadedImage && preloadedImage.image) {
image.image = preloadedImage.image;
delete image.uri;
}
const baseUri = options.uri || this.baseUri;
if (baseUri) {
const uri = image.uri;
image.uri = getFullUri(image.uri, baseUri);
image.originalUri = uri;
image.baseUri = baseUri;
image.fullUri = getFullUri(image.uri, baseUri);
image.fullUri = image.uri;
}
}
function getImageAsync() {
if (image.uri) {
image.getImageAsync = () => {
if (image.bufferView) {
return new Promise(resolve => {
var img = new Image();
img.crossOrigin = 'anonymous';
const arrayBufferView = this.getBufferView(image.bufferView);
const mimeType = image.mimeType || 'image/jpeg';
const blob = new Blob([arrayBufferView.data], {
type: mimeType
});
const urlCreator = self.URL || self.webkitURL;
const imageUrl = urlCreator.createObjectURL(blob);
const img = new Image();
img.onload = () => resolve(img);
img.src = image.fullUri || image.uri;
img.src = imageUrl;
});
}
return null;
}
return image.uri ? new Promise(resolve => {
const img = new Image();
img.crossOrigin = 'anonymous';
image.getImageAsync = getImageAsync;
img.onload = () => resolve(img);
img.src = image.fullUri || image.uri;
}) : null;
};
return image;

@@ -378,8 +398,7 @@ }

_resolveBufferView(bufferView, index) {
bufferView = _objectSpread({}, bufferView);
bufferView.id = bufferView.id || "bufferView-".concat(index);
var bufferIndex = bufferView.buffer;
const bufferIndex = bufferView.buffer;
bufferView.buffer = this.getBuffer(bufferIndex);
var arrayBuffer = this.buffers[bufferIndex].arrayBuffer;
var byteOffset = this.buffers[bufferIndex].byteOffset || 0;
const arrayBuffer = this.buffers[bufferIndex].arrayBuffer;
let byteOffset = this.buffers[bufferIndex].byteOffset || 0;

@@ -386,0 +405,0 @@ if ('byteOffset' in bufferView) {

@@ -7,3 +7,6 @@ import parseGLBSync from './lib/parse-glb';

binary: true,
parseSync: parseSync
parseSync: parseSync,
defaultOptions: {
strict: false
}
};

@@ -10,0 +13,0 @@

@@ -12,3 +12,6 @@ import _regeneratorRuntime from "@babel/runtime/regenerator";

var DEFAULT_OPTIONS = {
useGLTFParser: true
gltf: {
parserVersion: 1
},
uri: ''
};

@@ -36,3 +39,3 @@ export function parse(_x) {

if (!options.useGLTFParser) {
if (!(options.gltf.parserVersion !== 2 && options.useGLTFParser !== false)) {
_context.next = 5;

@@ -52,3 +55,3 @@ break;

case 9:
return _context.abrupt("return", gltf);
return _context.abrupt("return", _context.sent);

@@ -69,3 +72,3 @@ case 10:

if (options.useGLTFParser) {
if (options.gltf.parserVersion !== 2 && options.useGLTFParser !== false) {
return new GLTFParser().parseSync(arrayBuffer, options);

@@ -78,4 +81,3 @@ }

var gltf = {};
parseGLTFSync(gltf, arrayBuffer, byteOffset, options);
return gltf;
return parseGLTFSync(gltf, arrayBuffer, byteOffset, options);
}

@@ -82,0 +84,0 @@ export default {

import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
var _marked = _regeneratorRuntime.mark(meshPrimitiveIterator);
import GLTFScenegraph from '../gltf-scenegraph';
import { KHR_DRACO_MESH_COMPRESSION } from '../gltf-constants';
import { getGLTFAccessors, getGLTFAccessor } from '../gltf-utils/gltf-attribute-utils';
import { parse } from '@loaders.gl/core';

@@ -15,34 +21,116 @@ var KHR_draco_mesh_compression = function () {

key: "decode",
value: function decode(gltfData, options) {
var gltfScenegraph = new GLTFScenegraph(gltfData);
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
value: function () {
var _decode = _asyncToGenerator(_regeneratorRuntime.mark(function _callee(gltfData) {
var options,
scenegraph,
promises,
_iteratorNormalCompletion,
_didIteratorError,
_iteratorError,
_iterator,
_step,
primitive,
_args = arguments;
try {
for (var _iterator = (gltfScenegraph.json.meshes || [])[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var mesh = _step.value;
KHR_draco_mesh_compression.decompressMesh(mesh, options);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"] != null) {
_iterator["return"]();
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
options = _args.length > 1 && _args[1] !== undefined ? _args[1] : {};
if (options.decompress) {
_context.next = 3;
break;
}
return _context.abrupt("return");
case 3:
scenegraph = new GLTFScenegraph(gltfData);
promises = [];
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
_context.prev = 8;
for (_iterator = meshPrimitiveIterator(scenegraph)[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
primitive = _step.value;
if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) {
promises.push(decompressPrimitive(primitive, scenegraph, options));
}
}
_context.next = 16;
break;
case 12:
_context.prev = 12;
_context.t0 = _context["catch"](8);
_didIteratorError = true;
_iteratorError = _context.t0;
case 16:
_context.prev = 16;
_context.prev = 17;
if (!_iteratorNormalCompletion && _iterator["return"] != null) {
_iterator["return"]();
}
case 19:
_context.prev = 19;
if (!_didIteratorError) {
_context.next = 22;
break;
}
throw _iteratorError;
case 22:
return _context.finish(19);
case 23:
return _context.finish(16);
case 24:
_context.next = 26;
return Promise.all(promises);
case 26:
scenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);
case 27:
case "end":
return _context.stop();
}
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}, _callee, null, [[8, 12, 16, 24], [17,, 19, 23]]);
}));
function decode(_x) {
return _decode.apply(this, arguments);
}
gltfScenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);
return decode;
}()
}, {
key: "decodeSync",
value: function decodeSync(gltfData, options) {
if (!options.decompress) {
return;
}
var scenegraph = new GLTFScenegraph(gltfData);
if (scenegraph.getRequiredExtension(KHR_DRACO_MESH_COMPRESSION)) {
throw new Error('Cannot synchronously decode Draco');
}
}
}, {
key: "encode",
value: function encode(gltfData, options) {
var gltfScenegraph = new GLTFScenegraph(gltfData);
value: function encode(gltfData) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var scenegraph = new GLTFScenegraph(gltfData);
var _iteratorNormalCompletion2 = true;

@@ -53,6 +141,6 @@ var _didIteratorError2 = false;

try {
for (var _iterator2 = (gltfScenegraph.json.meshes || [])[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
for (var _iterator2 = (scenegraph.json.meshes || [])[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var mesh = _step2.value;
KHR_draco_mesh_compression.compressMesh(mesh, options);
gltfScenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);
compressMesh(mesh, options);
scenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);
}

@@ -75,101 +163,209 @@ } catch (err) {

}, {
key: "compressMesh",
value: function compressMesh(attributes, indices) {
var mode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 4;
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
key: "name",
get: function get() {
return KHR_DRACO_MESH_COMPRESSION;
}
}]);
if (!options.DracoWriter || !options.DracoLoader) {
throw new Error('DracoWriter/DracoLoader not available');
return KHR_draco_mesh_compression;
}();
export { KHR_draco_mesh_compression as default };
function decompressPrimitive(_x2, _x3, _x4) {
return _decompressPrimitive.apply(this, arguments);
}
function _decompressPrimitive() {
_decompressPrimitive = _asyncToGenerator(_regeneratorRuntime.mark(function _callee2(primitive, scenegraph, options) {
var compressedPrimitive, buffer, subArray, bufferCopy, decodedData;
return _regeneratorRuntime.wrap(function _callee2$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
compressedPrimitive = scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION);
buffer = scenegraph.getTypedArrayForBufferView(compressedPrimitive.bufferView);
subArray = new Uint8Array(buffer.buffer).subarray(buffer.byteOffset);
bufferCopy = new Uint8Array(subArray);
_context3.next = 6;
return parse(bufferCopy);
case 6:
decodedData = _context3.sent;
primitive.attributes = getGLTFAccessors(decodedData.attributes);
if (decodedData.indices) {
primitive.indices = getGLTFAccessor(decodedData.indices);
}
checkPrimitive(primitive);
case 10:
case "end":
return _context3.stop();
}
}
}, _callee2);
}));
return _decompressPrimitive.apply(this, arguments);
}
var compressedData = options.DracoWriter.encodeSync({
attributes: attributes
});
var decodedData = options.DracoLoader.parseSync({
attributes: attributes
});
function compressMesh(attributes, indices) {
var mode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 4;
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var fauxAccessors = options._addFauxAttributes(decodedData.attributes);
if (!options.DracoWriter || !options.DracoLoader) {
throw new Error('DracoWriter/DracoLoader not available');
}
var bufferViewIndex = options.addBufferView(compressedData);
var glTFMesh = {
primitives: [{
attributes: fauxAccessors,
mode: mode,
extensions: _defineProperty({}, KHR_DRACO_MESH_COMPRESSION, {
bufferView: bufferViewIndex,
attributes: fauxAccessors
})
}]
};
return glTFMesh;
}
}, {
key: "decompressMesh",
value: function decompressMesh(mesh) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
var compressedData = options.DracoWriter.encodeSync({
attributes: attributes
});
var decodedData = options.DracoLoader.parseSync({
attributes: attributes
});
try {
for (var _iterator3 = mesh.primitives[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var primitive = _step3.value;
var fauxAccessors = options._addFauxAttributes(decodedData.attributes);
KHR_draco_mesh_compression._decompressMeshPrimitive(primitive, options);
var bufferViewIndex = options.addBufferView(compressedData);
var glTFMesh = {
primitives: [{
attributes: fauxAccessors,
mode: mode,
extensions: _defineProperty({}, KHR_DRACO_MESH_COMPRESSION, {
bufferView: bufferViewIndex,
attributes: fauxAccessors
})
}]
};
return glTFMesh;
}
if (!primitive.attributes || Object.keys(primitive.attributes).length === 0) {
throw new Error('Empty glTF primitive: decompression failure?');
function checkPrimitive(primitive) {
if (!primitive.attributes && Object.keys(primitive.attributes).length > 0) {
throw new Error('Empty glTF primitive detected: Draco decompression failure?');
}
}
function meshPrimitiveIterator(scenegraph) {
var _iteratorNormalCompletion3, _didIteratorError3, _iteratorError3, _iterator3, _step3, mesh, _iteratorNormalCompletion4, _didIteratorError4, _iteratorError4, _iterator4, _step4, primitive;
return _regeneratorRuntime.wrap(function meshPrimitiveIterator$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_iteratorNormalCompletion3 = true;
_didIteratorError3 = false;
_iteratorError3 = undefined;
_context2.prev = 3;
_iterator3 = (scenegraph.json.meshes || [])[Symbol.iterator]();
case 5:
if (_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done) {
_context2.next = 36;
break;
}
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
mesh = _step3.value;
_iteratorNormalCompletion4 = true;
_didIteratorError4 = false;
_iteratorError4 = undefined;
_context2.prev = 10;
_iterator4 = mesh.primitives[Symbol.iterator]();
case 12:
if (_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done) {
_context2.next = 19;
break;
}
primitive = _step4.value;
_context2.next = 16;
return primitive;
case 16:
_iteratorNormalCompletion4 = true;
_context2.next = 12;
break;
case 19:
_context2.next = 25;
break;
case 21:
_context2.prev = 21;
_context2.t0 = _context2["catch"](10);
_didIteratorError4 = true;
_iteratorError4 = _context2.t0;
case 25:
_context2.prev = 25;
_context2.prev = 26;
if (!_iteratorNormalCompletion4 && _iterator4["return"] != null) {
_iterator4["return"]();
}
case 28:
_context2.prev = 28;
if (!_didIteratorError4) {
_context2.next = 31;
break;
}
throw _iteratorError4;
case 31:
return _context2.finish(28);
case 32:
return _context2.finish(25);
case 33:
_iteratorNormalCompletion3 = true;
_context2.next = 5;
break;
case 36:
_context2.next = 42;
break;
case 38:
_context2.prev = 38;
_context2.t1 = _context2["catch"](3);
_didIteratorError3 = true;
_iteratorError3 = _context2.t1;
case 42:
_context2.prev = 42;
_context2.prev = 43;
if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) {
_iterator3["return"]();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
}
}, {
key: "_decompressMeshPrimitive",
value: function _decompressMeshPrimitive(primitive, options) {
var compressedPrimitive = primitive.extensions && primitive.extensions[KHR_DRACO_MESH_COMPRESSION];
if (!compressedPrimitive) {
return;
}
case 45:
_context2.prev = 45;
if (!options.DracoLoader || !options.decompress) {
return;
}
if (!_didIteratorError3) {
_context2.next = 48;
break;
}
delete primitive.extensions[KHR_DRACO_MESH_COMPRESSION];
throw _iteratorError3;
var buffer = this._getBufferViewArray(compressedPrimitive.bufferView);
case 48:
return _context2.finish(45);
var decodedData = options.DracoLoader.parseSync(buffer);
primitive.attributes = getGLTFAccessors(decodedData.attributes);
case 49:
return _context2.finish(42);
if (decodedData.indices) {
primitive.indices = getGLTFAccessor(decodedData.indices);
case 50:
case "end":
return _context2.stop();
}
}
}, {
key: "name",
get: function get() {
return KHR_DRACO_MESH_COMPRESSION;
}
}]);
return KHR_draco_mesh_compression;
}();
export { KHR_draco_mesh_compression as default };
}, _marked, null, [[3, 38, 42, 50], [10, 21, 25, 33], [26,, 28, 32], [43,, 45, 49]]);
}
//# sourceMappingURL=KHR_draco_mesh_compression.js.map

@@ -23,3 +23,3 @@ import _typeof from "@babel/runtime/helpers/esm/typeof";

},
binary: null
buffers: []
};

@@ -29,2 +29,3 @@ }

this.gltf = gltf;
assert(this.gltf.json);
}

@@ -144,6 +145,6 @@

var object = this.gltf[array] && this.gltf[array][index];
var object = this.json[array] && this.json[array][index];
if (!object) {
console.warn("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
throw new Error("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
}

@@ -157,6 +158,7 @@

bufferView = this.getBufferView(bufferView);
var buffer = this.getBuffer(bufferView.buffer);
var arrayBuffer = buffer.data;
var byteOffset = bufferView.byteOffset || 0;
return new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
var bufferIndex = bufferView.buffer;
var binChunk = this.gltf.buffers[bufferIndex];
assert(binChunk);
var byteOffset = bufferView.byteOffset || 0 + binChunk.byteOffset;
return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
}

@@ -163,0 +165,0 @@ }, {

@@ -8,6 +8,6 @@ import { padTo4Bytes, assert } from '@loaders.gl/loader-utils';

var LE = true;
var BE = false;
function getMagicString(dataView) {
return "".concat(String.fromCharCode(dataView.getUint8(0))).concat(String.fromCharCode(dataView.getUint8(1))).concat(String.fromCharCode(dataView.getUint8(2))).concat(String.fromCharCode(dataView.getUint8(3)));
var byteOffset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
return "".concat(String.fromCharCode(dataView.getUint8(byteOffset + 0))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 1))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 2))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 3)));
}

@@ -28,12 +28,11 @@

var dataView = new DataView(arrayBuffer);
glb.byteOffset = byteOffset;
glb.magic = dataView.getUint32(byteOffset + 0, BE);
glb.type = getMagicString(dataView, byteOffset + 0);
glb.version = dataView.getUint32(byteOffset + 4, LE);
glb.byteLength = dataView.getUint32(byteOffset + 8, LE);
glb.type = getMagicString(dataView);
var _options$magic2 = options.magic,
magic = _options$magic2 === void 0 ? MAGIC_glTF : _options$magic2;
var isMagicValid = glb.magic === MAGIC_glTF || glb.magic === magic;
var byteLength = dataView.getUint32(byteOffset + 8, LE);
glb.header = {
byteOffset: byteOffset,
byteLength: byteLength
};
if (!isMagicValid) {
if (glb.type !== 'glTF') {
console.warn("Invalid GLB magic string ".concat(glb.type));

@@ -43,27 +42,79 @@ }

assert(glb.version === 2, "Invalid GLB version ".concat(glb.version, ". Only .glb v2 supported"));
assert(glb.byteLength > 20);
var jsonChunkLength = dataView.getUint32(byteOffset + 12, LE);
var jsonChunkFormat = dataView.getUint32(byteOffset + 16, LE);
var isJSONChunk = jsonChunkFormat === GLB_CHUNK_TYPE_JSON || jsonChunkFormat === 0;
assert(isJSONChunk, "JSON chunk format ".concat(jsonChunkFormat));
var jsonChunkByteOffset = GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE;
var jsonChunk = new Uint8Array(arrayBuffer, byteOffset + jsonChunkByteOffset, jsonChunkLength);
assert(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
glb.json = {};
glb.hasBinChunk = false;
glb.binChunks = [];
parseGLBChunksSync(glb, dataView, byteOffset + 12, options);
addDeprecatedFields(glb);
return byteOffset + glb.header.byteLength;
}
function parseGLBChunksSync(glb, dataView, byteOffset, options) {
while (byteOffset + 8 <= glb.header.byteLength) {
var chunkLength = dataView.getUint32(byteOffset + 0, LE);
var chunkFormat = dataView.getUint32(byteOffset + 4, LE);
byteOffset += GLB_CHUNK_HEADER_SIZE;
switch (chunkFormat) {
case GLB_CHUNK_TYPE_JSON:
parseJSONChunk(glb, dataView, byteOffset, chunkLength, options);
break;
case GLB_CHUNK_TYPE_BIN:
parseBINChunk(glb, dataView, byteOffset, chunkLength, options);
break;
default:
break;
}
switch (chunkFormat) {
case 0:
if (!options.strict) {
parseJSONChunk(glb, dataView, byteOffset, chunkLength, options);
}
break;
case 1:
if (!options.strict) {
parseBINChunk(glb, dataView, byteOffset, chunkLength, options);
}
break;
default:
}
byteOffset += padTo4Bytes(chunkLength);
}
return byteOffset;
}
function parseJSONChunk(glb, dataView, byteOffset, chunkLength, options) {
var jsonChunk = new Uint8Array(dataView.buffer, byteOffset, chunkLength);
var textDecoder = new TextDecoder('utf8');
var jsonText = textDecoder.decode(jsonChunk);
glb.json = JSON.parse(jsonText);
var binChunkStart = jsonChunkByteOffset + padTo4Bytes(jsonChunkLength);
glb.hasBinChunk = binChunkStart + 8 <= glb.byteLength;
}
if (glb.hasBinChunk) {
var binChunkLength = dataView.getUint32(byteOffset + binChunkStart + 0, LE);
var binChunkFormat = dataView.getUint32(byteOffset + binChunkStart + 4, LE);
var isBinChunk = binChunkFormat === GLB_CHUNK_TYPE_BIN || binChunkFormat === 1;
assert(isBinChunk, "BIN chunk format ".concat(binChunkFormat));
var binChunkByteOffset = binChunkStart + GLB_CHUNK_HEADER_SIZE;
glb.binChunkByteOffset = binChunkByteOffset;
glb.binChunkLength = binChunkLength;
}
function parseBINChunk(glb, dataView, byteOffset, chunkLength, options) {
glb.header.hasBinChunk = true;
glb.binChunks.push({
byteOffset: byteOffset,
byteLength: chunkLength,
arrayBuffer: dataView.buffer
});
}
return byteOffset + glb.byteLength;
function addDeprecatedFields(glb) {
glb.byteOffset = glb.header.byteOffset;
glb.magic = glb.header.magic;
glb.version = glb.header.version;
glb.byteLength = glb.header.byteLength;
glb.hasBinChunk = glb.binChunks.length >= 1;
glb.binChunkByteOffset = glb.header.hasBinChunk ? glb.binChunks[0].byteOffset : 0;
glb.binChunkLength = glb.header.hasBinChunk ? glb.binChunks[0].byteLength : 0;
}
//# sourceMappingURL=parse-glb.js.map

@@ -12,19 +12,13 @@ import _regeneratorRuntime from "@babel/runtime/regenerator";

import { getFullUri } from './gltf-utils/gltf-utils';
import { decodeExtensions, decodeExtensionsSync } from './extensions/extensions';
import parseGLBSync, { isGLB } from './parse-glb';
import * as EXTENSIONS from './extensions';
var DEFAULT_SYNC_OPTIONS = {
fetchLinkedResources: false,
decompress: false,
DracoLoader: null,
postProcess: true,
import postProcessGLTF from './post-process-gltf';
var DEFAULT_OPTIONS = {
fetchLinkedResources: true,
fetchImages: false,
createImages: false,
log: console
};
var DEFAULT_ASYNC_OPTIONS = {
fetchLinkedResources: true,
fetch: fetchFile,
decompress: false,
DracoLoader: null,
postProcess: true,
createImages: false,
postProcess: false,
log: console

@@ -38,67 +32,2 @@ };

}
export function parseGLTFSync(gltf, arrayBufferOrString) {
var byteOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
options = Object.assign({}, DEFAULT_SYNC_OPTIONS, options);
var data = arrayBufferOrString;
if (data instanceof ArrayBuffer && !isGLB(data, byteOffset, options)) {
var textDecoder = new TextDecoder();
data = textDecoder.decode(data);
}
gltf.buffers = [];
if (typeof data === 'string') {
gltf.json = JSON.parse(data);
} else if (data instanceof ArrayBuffer) {
byteOffset = parseGLBSync(gltf, data, byteOffset, options);
if (gltf.hasBinChunk) {
gltf.buffers.push({
arrayBuffer: data,
byteOffset: gltf.binChunkByteOffset,
byteLength: gltf.binChunkLength
});
}
} else {
gltf.json = data;
}
if (options.uri) {
gltf.baseUri = options.uri;
}
if (options.fetchLinkedResources) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = (gltf.json.buffers || [])[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var buffer = _step.value;
if (buffer.uri) {
throw new Error('parseGLTFSync: Cannot decode uri buffers');
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"] != null) {
_iterator["return"]();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
decodeExtensions(gltf, options);
return byteOffset;
}
export function parseGLTF(_x, _x2) {

@@ -112,3 +41,7 @@ return _parseGLTF.apply(this, arguments);

options,
promises,
_promise,
promise,
_args = arguments;
return _regeneratorRuntime.wrap(function _callee$(_context) {

@@ -120,21 +53,29 @@ while (1) {

options = _args.length > 3 && _args[3] !== undefined ? _args[3] : {};
options = Object.assign({}, DEFAULT_ASYNC_OPTIONS, options);
parseGLTFSync(gltf, arrayBufferOrString, byteOffset, _objectSpread({}, options, {
fetchLinkedResources: false,
postProcess: false,
decompress: false
}));
options = _objectSpread({}, DEFAULT_OPTIONS, {}, options);
parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options);
promises = [];
if (options.fetchImages) {
_promise = fetchImages(gltf, options);
promises.push(_promise);
}
if (!options.fetchLinkedResources) {
_context.next = 7;
_context.next = 9;
break;
}
_context.next = 7;
return fetchLinkedResources(gltf, options);
_context.next = 9;
return fetchBuffers(gltf, options);
case 7:
return _context.abrupt("return", gltf);
case 9:
promise = decodeExtensions(gltf, options);
promises.push(promise);
_context.next = 13;
return Promise.all(promises);
case 8:
case 13:
return _context.abrupt("return", options.postProcess ? postProcessGLTF(gltf, options) : gltf);
case 14:
case "end":

@@ -149,10 +90,63 @@ return _context.stop();

function fetchLinkedResources(_x3, _x4) {
return _fetchLinkedResources.apply(this, arguments);
export function parseGLTFSync(gltf, arrayBufferOrString) {
var byteOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
options = _objectSpread({}, DEFAULT_OPTIONS, {}, options);
parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options);
if (options.fetchLinkedResources) {
fetchBuffersSync(gltf, options);
}
if (options.decodeExtensions) {
decodeExtensionsSync(gltf, options);
}
return options.postProcess ? postProcessGLTF(gltf, options) : gltf;
}
function _fetchLinkedResources() {
_fetchLinkedResources = _asyncToGenerator(_regeneratorRuntime.mark(function _callee2(gltf, options) {
var _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, buffer, fetch, uri, response, arrayBuffer;
function parseGLTFContainerSync(gltf, data, byteOffset, options) {
if (options.uri) {
gltf.baseUri = options.uri;
}
if (data instanceof ArrayBuffer && !isGLB(data, byteOffset, options)) {
var textDecoder = new TextDecoder();
data = textDecoder.decode(data);
}
if (typeof data === 'string') {
gltf.json = JSON.parse(data);
} else if (data instanceof ArrayBuffer) {
gltf._glb = {};
byteOffset = parseGLBSync(gltf._glb, data, byteOffset, options);
gltf.json = gltf._glb.json;
} else {
gltf.json = data;
}
var buffers = gltf.json.buffers || [];
gltf.buffers = new Array(buffers.length).fill({});
if (gltf._glb && gltf._glb.hasBinChunk) {
gltf.buffers[0] = {
arrayBuffer: gltf._glb.binChunks[0].arrayBuffer,
byteOffset: gltf._glb.binChunks[0].byteOffset,
byteLength: gltf._glb.binChunks[0].byteLength
};
gltf.json.buffers[0].data = gltf.buffers[0].arrayBuffer;
gltf.json.buffers[0].byteOffset = gltf.buffers[0].byteOffset;
}
var images = gltf.json.images || [];
gltf.images = new Array(images.length).fill({});
}
function fetchBuffers(_x3, _x4) {
return _fetchBuffers.apply(this, arguments);
}
function _fetchBuffers() {
_fetchBuffers = _asyncToGenerator(_regeneratorRuntime.mark(function _callee2(gltf, options) {
var i, buffer, fetch, uri, response, arrayBuffer;
return _regeneratorRuntime.wrap(function _callee2$(_context2) {

@@ -162,18 +156,18 @@ while (1) {

case 0:
_iteratorNormalCompletion2 = true;
_didIteratorError2 = false;
_iteratorError2 = undefined;
_context2.prev = 3;
_iterator2 = gltf.json.buffers[Symbol.iterator]();
i = 0;
case 5:
if (_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done) {
_context2.next = 22;
case 1:
if (!(i < gltf.json.buffers.length)) {
_context2.next = 19;
break;
}
buffer = _step2.value;
buffer = gltf.json.buffers[i];
if (!buffer.uri) {
_context2.next = 19;
if (!options.uri) {
console.warn('options.uri must be set to decode embedded glTF buffers');
}
if (!(buffer.uri && options.uri)) {
_context2.next = 16;
break;

@@ -185,74 +179,143 @@ }

uri = getFullUri(buffer.uri, options.uri);
_context2.next = 13;
_context2.next = 10;
return fetch(uri);
case 13:
case 10:
response = _context2.sent;
_context2.next = 16;
_context2.next = 13;
return response.arrayBuffer();
case 16:
case 13:
arrayBuffer = _context2.sent;
buffer.data = arrayBuffer;
gltf.buffers[i] = {
arrayBuffer: arrayBuffer,
byteOffset: 0,
byteLength: arrayBuffer.byteLength
};
delete buffer.uri;
case 19:
_iteratorNormalCompletion2 = true;
_context2.next = 5;
case 16:
++i;
_context2.next = 1;
break;
case 22:
_context2.next = 28;
break;
case 19:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return _fetchBuffers.apply(this, arguments);
}
case 24:
_context2.prev = 24;
_context2.t0 = _context2["catch"](3);
_didIteratorError2 = true;
_iteratorError2 = _context2.t0;
function fetchBuffersSync(gltf, options) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
case 28:
_context2.prev = 28;
_context2.prev = 29;
try {
for (var _iterator = (gltf.json.buffers || [])[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var buffer = _step.value;
if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
_iterator2["return"]();
}
if (buffer.uri) {
throw new Error('parseGLTFSync: Cannot decode uri buffers');
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"] != null) {
_iterator["return"]();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
case 31:
_context2.prev = 31;
function fetchImages(_x5, _x6) {
return _fetchImages.apply(this, arguments);
}
if (!_didIteratorError2) {
_context2.next = 34;
break;
function _fetchImages() {
_fetchImages = _asyncToGenerator(_regeneratorRuntime.mark(function _callee3(gltf, options) {
var images, promises, i, image;
return _regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
images = gltf.json.images || [];
promises = [];
for (i = 0; i < images.length; ++i) {
image = images[i];
if ('uri' in image) {
promises.push(fetchAndParseLinkedImage(gltf, image, i, options));
}
}
throw _iteratorError2;
_context3.next = 5;
return Promise.all(promises);
case 34:
return _context2.finish(31);
case 5:
return _context3.abrupt("return", _context3.sent);
case 35:
return _context2.finish(28);
case 36:
case 6:
case "end":
return _context2.stop();
return _context3.stop();
}
}
}, _callee2, null, [[3, 24, 28, 36], [29,, 31, 35]]);
}, _callee3);
}));
return _fetchLinkedResources.apply(this, arguments);
return _fetchImages.apply(this, arguments);
}
function decodeExtensions(gltf, options) {
for (var extensionName in EXTENSIONS) {
var disableExtension = extensionName in options && !options[extensionName];
function fetchAndParseLinkedImage(_x7, _x8, _x9, _x10) {
return _fetchAndParseLinkedImage.apply(this, arguments);
}
if (!disableExtension) {
var extension = EXTENSIONS[extensionName];
extension.decode(gltf, options);
}
}
function _fetchAndParseLinkedImage() {
_fetchAndParseLinkedImage = _asyncToGenerator(_regeneratorRuntime.mark(function _callee4(gltf, image, i, options) {
var fetch, uri;
return _regeneratorRuntime.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
fetch = options.fetch || window.fetch;
assert(fetch);
uri = getFullUri(image.uri, options.uri);
_context4.next = 5;
return new Promise(function (resolve, reject) {
var img = new Image();
img.crossOrigin = 'anonymous';
img.onload = function () {
return resolve(img);
};
img.onerror = function (error) {
return reject(error);
};
img.src = uri;
});
case 5:
gltf.images[i] = _context4.sent;
case 6:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
return _fetchAndParseLinkedImage.apply(this, arguments);
}
//# sourceMappingURL=parse-gltf.js.map

@@ -13,2 +13,3 @@ import _typeof from "@babel/runtime/helpers/esm/typeof";

import { getFullUri } from './gltf-utils/gltf-utils';
import assert from './utils/assert';
var COMPONENTS = {

@@ -65,6 +66,18 @@ SCALAR: 1,

var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
this.gltf = gltf;
this.json = gltf.json;
this.buffers = gltf.buffers;
return this._resolveTree(gltf.json, options);
var json = gltf.json,
_gltf$buffers = gltf.buffers,
buffers = _gltf$buffers === void 0 ? [] : _gltf$buffers,
_gltf$images = gltf.images,
images = _gltf$images === void 0 ? [] : _gltf$images,
_gltf$baseUri = gltf.baseUri,
baseUri = _gltf$baseUri === void 0 ? '' : _gltf$baseUri;
assert(json);
this.baseUri = baseUri;
this.json = json;
this.buffers = buffers;
this.images = images;
this._resolveTree(this.json, options);
return this.json;
}

@@ -141,4 +154,2 @@ }, {

}
return json;
}

@@ -225,3 +236,2 @@ }, {

scene = _objectSpread({}, scene);
scene.id = scene.id || "scene-".concat(index);

@@ -238,3 +248,2 @@ scene.nodes = (scene.nodes || []).map(function (node) {

node = _objectSpread({}, node);
node.id = node.id || "node-".concat(index);

@@ -265,3 +274,2 @@

value: function _resolveSkin(skin, index) {
skin = _objectSpread({}, skin);
skin.id = skin.id || "skin-".concat(index);

@@ -276,3 +284,2 @@ skin.inverseBindMatrices = this.getAccessor(skin.inverseBindMatrices);

mesh = _objectSpread({}, mesh);
mesh.id = mesh.id || "mesh-".concat(index);

@@ -307,3 +314,2 @@

value: function _resolveMaterial(material, index) {
material = _objectSpread({}, material);
material.id = material.id || "material-".concat(index);

@@ -346,3 +352,2 @@

value: function _resolveAccessor(accessor, index) {
accessor = _objectSpread({}, accessor);
accessor.id = accessor.id || "accessor-".concat(index);

@@ -362,3 +367,2 @@

value: function _resolveTexture(texture, index) {
texture = _objectSpread({}, texture);
texture.id = texture.id || "texture-".concat(index);

@@ -372,3 +376,2 @@ texture.sampler = 'sampler' in texture ? this.getSampler(texture.sampler) : DEFAULT_SAMPLER;

value: function _resolveSampler(sampler, index) {
sampler = _objectSpread({}, sampler);
sampler.id = sampler.id || "sampler-".concat(index);

@@ -395,3 +398,4 @@ sampler.parameters = {};

value: function _resolveImage(image, index, options) {
image = _objectSpread({}, image);
var _this5 = this;
image.id = image.id || "image-".concat(index);

@@ -404,15 +408,32 @@

if ('uri' in image) {
var baseUri = options.uri || this.gltf.baseUri;
var preloadedImage = this.images[index];
if (preloadedImage && preloadedImage.image) {
image.image = preloadedImage.image;
delete image.uri;
}
var baseUri = options.uri || this.baseUri;
if (baseUri) {
var uri = image.uri;
image.uri = getFullUri(image.uri, baseUri);
image.originalUri = uri;
image.baseUri = baseUri;
image.fullUri = getFullUri(image.uri, baseUri);
image.fullUri = image.uri;
}
}
function getImageAsync() {
if (image.uri) {
image.getImageAsync = function () {
if (image.bufferView) {
return new Promise(function (resolve) {
var arrayBufferView = _this5.getBufferView(image.bufferView);
var mimeType = image.mimeType || 'image/jpeg';
var blob = new Blob([arrayBufferView.data], {
type: mimeType
});
var urlCreator = self.URL || self.webkitURL;
var imageUrl = urlCreator.createObjectURL(blob);
var img = new Image();
img.crossOrigin = 'anonymous';

@@ -423,10 +444,18 @@ img.onload = function () {

img.src = image.fullUri || image.uri;
img.src = imageUrl;
});
}
return null;
}
return image.uri ? new Promise(function (resolve) {
var img = new Image();
img.crossOrigin = 'anonymous';
image.getImageAsync = getImageAsync;
img.onload = function () {
return resolve(img);
};
img.src = image.fullUri || image.uri;
}) : null;
};
return image;

@@ -437,3 +466,2 @@ }

value: function _resolveBufferView(bufferView, index) {
bufferView = _objectSpread({}, bufferView);
bufferView.id = bufferView.id || "bufferView-".concat(index);

@@ -440,0 +468,0 @@ var bufferIndex = bufferView.buffer;

{
"name": "@loaders.gl/gltf",
"version": "1.3.0-beta.1",
"version": "1.3.0-beta.2",
"description": "Framework-independent loader for the glTF format",

@@ -41,7 +41,7 @@ "license": "MIT",

"dependencies": {
"@loaders.gl/core": "1.3.0-beta.1",
"@loaders.gl/images": "1.3.0-beta.1",
"@loaders.gl/loader-utils": "1.3.0-beta.1"
"@loaders.gl/core": "1.3.0-beta.2",
"@loaders.gl/images": "1.3.0-beta.2",
"@loaders.gl/loader-utils": "1.3.0-beta.2"
},
"gitHead": "deabcc69303bc19eeadb1bb6cf9082ee94e74f3e"
"gitHead": "ea8078ed5fda7d06dfaae4aed02a46ca1c181bd3"
}

@@ -10,3 +10,6 @@ // Binary container format for glTF

binary: true,
parseSync
parseSync,
defaultOptions: {
strict: false // Enables deprecated XVIZ support (illegal CHUNK formats)
}
};

@@ -13,0 +16,0 @@

@@ -7,3 +7,6 @@ // Binary container format for glTF

const DEFAULT_OPTIONS = {
useGLTFParser: true // GLTFParser will be removed in v2.
gltf: {
parserVersion: 1 // the new parser that will be the only option in V2.
},
uri: '' // base URI
};

@@ -15,3 +18,3 @@

// Deprecated: Return GLTFParser instance
if (options.useGLTFParser) {
if (options.gltf.parserVersion !== 2 && options.useGLTFParser !== false) {
const gltfParser = new GLTFParser();

@@ -24,4 +27,3 @@ return gltfParser.parse(arrayBuffer, options);

const gltf = {};
await parseGLTF(gltf, arrayBuffer, byteOffset, options);
return gltf;
return await parseGLTF(gltf, arrayBuffer, byteOffset, options);
}

@@ -34,3 +36,3 @@

// Deprecated: Return GLTFParser instance
if (options.useGLTFParser) {
if (options.gltf.parserVersion !== 2 && options.useGLTFParser !== false) {
return new GLTFParser().parseSync(arrayBuffer, options);

@@ -42,4 +44,3 @@ }

const gltf = {};
parseGLTFSync(gltf, arrayBuffer, byteOffset, options);
return gltf;
return parseGLTFSync(gltf, arrayBuffer, byteOffset, options);
}

@@ -46,0 +47,0 @@

@@ -0,1 +1,4 @@

// https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
// Only TRIANGLES: 0x0004 and TRIANGLE_STRIP: 0x0005 are supported
/* eslint-disable camelcase */

@@ -5,2 +8,3 @@ import GLTFScenegraph from '../gltf-scenegraph';

import {getGLTFAccessors, getGLTFAccessor} from '../gltf-utils/gltf-attribute-utils';
import {parse} from '@loaders.gl/core';

@@ -12,102 +16,127 @@ export default class KHR_draco_mesh_compression {

static decode(gltfData, options) {
const gltfScenegraph = new GLTFScenegraph(gltfData);
// Note: We have a "soft dependency" on Draco to avoid bundling it when not needed
static async decode(gltfData, options = {}) {
if (!options.decompress) {
return;
}
for (const mesh of gltfScenegraph.json.meshes || []) {
// eslint-disable-next-line camelcase
KHR_draco_mesh_compression.decompressMesh(mesh, options);
const scenegraph = new GLTFScenegraph(gltfData);
const promises = [];
for (const primitive of meshPrimitiveIterator(scenegraph)) {
if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) {
promises.push(decompressPrimitive(primitive, scenegraph, options));
}
}
// We have now decompressed all primitives, we can remove the top-level extensions
gltfScenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);
// Decompress meshes in parallel
await Promise.all(promises);
// We have now decompressed all primitives, so remove the top-level extensions
scenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);
}
static encode(gltfData, options) {
const gltfScenegraph = new GLTFScenegraph(gltfData);
static decodeSync(gltfData, options) {
if (!options.decompress) {
return;
}
const scenegraph = new GLTFScenegraph(gltfData);
if (scenegraph.getRequiredExtension(KHR_DRACO_MESH_COMPRESSION)) {
throw new Error('Cannot synchronously decode Draco');
}
// TODO - we can support sync decoding, let's just keep code/bundle size in check...
}
for (const mesh of gltfScenegraph.json.meshes || []) {
static encode(gltfData, options = {}) {
const scenegraph = new GLTFScenegraph(gltfData);
for (const mesh of scenegraph.json.meshes || []) {
// eslint-disable-next-line camelcase
KHR_draco_mesh_compression.compressMesh(mesh, options);
// NOTE: We only add if something was actually compressed
gltfScenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);
compressMesh(mesh, options);
// NOTE: Only add the extension if something was actually compressed
scenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);
}
}
}
// eslint-disable-next-line max-len
// https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
// Only TRIANGLES: 0x0004 and TRIANGLE_STRIP: 0x0005 are supported
static compressMesh(attributes, indices, mode = 4, options = {}) {
if (!options.DracoWriter || !options.DracoLoader) {
throw new Error('DracoWriter/DracoLoader not available');
}
// PRIVATE
const compressedData = options.DracoWriter.encodeSync({attributes});
// Unpacks one mesh primitive and removes the extension from the primitive
// DracoDecoder needs to be imported and registered by app
// Returns: Promise that resolves when all pending draco decoder jobs for this mesh complete
// Draco compression may change the order and number of vertices in a mesh.
// To satisfy the requirement that accessors properties be correct for both
// compressed and uncompressed data, generators should create uncompressed
// attributes and indices using data that has been decompressed from the Draco buffer,
// rather than the original source data.
const decodedData = options.DracoLoader.parseSync({attributes});
const fauxAccessors = options._addFauxAttributes(decodedData.attributes);
// TODO - Implement fallback behavior per KHR_DRACO_MESH_COMPRESSION spec
const bufferViewIndex = options.addBufferView(compressedData);
async function decompressPrimitive(primitive, scenegraph, options) {
const compressedPrimitive = scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION);
const glTFMesh = {
primitives: [
{
attributes: fauxAccessors, // TODO - verify with spec
mode, // GL.POINTS
extensions: {
[KHR_DRACO_MESH_COMPRESSION]: {
bufferView: bufferViewIndex,
attributes: fauxAccessors // TODO - verify with spec
}
}
}
]
};
// eslint-disable-next-line
const buffer = scenegraph.getTypedArrayForBufferView(compressedPrimitive.bufferView);
return glTFMesh;
// TODO - parse does not yet deal well with byte offsets embedded in typed arrays. Copy buffer
const subArray = new Uint8Array(buffer.buffer).subarray(buffer.byteOffset); // , buffer.byteLength);
const bufferCopy = new Uint8Array(subArray);
const decodedData = await parse(bufferCopy);
primitive.attributes = getGLTFAccessors(decodedData.attributes);
if (decodedData.indices) {
primitive.indices = getGLTFAccessor(decodedData.indices);
}
static decompressMesh(mesh, options = {}) {
// We have a "soft dependency" on Draco to avoid bundling it when not needed
// DracoEncoder needs to be imported and supplied by app
// Decompress all the primitives in a mesh
for (const primitive of mesh.primitives) {
KHR_draco_mesh_compression._decompressMeshPrimitive(primitive, options);
if (!primitive.attributes || Object.keys(primitive.attributes).length === 0) {
throw new Error('Empty glTF primitive: decompression failure?');
}
}
// Extension has been processed, delete it
// delete primitive.extensions[KHR_DRACO_MESH_COMPRESSION];
checkPrimitive(primitive);
}
// eslint-disable-next-line max-len
// Only TRIANGLES: 0x0004 and TRIANGLE_STRIP: 0x0005 are supported
function compressMesh(attributes, indices, mode = 4, options = {}) {
if (!options.DracoWriter || !options.DracoLoader) {
throw new Error('DracoWriter/DracoLoader not available');
}
// Unpacks one mesh primitive and removes the extension from the primitive
// TODO - Implement fallback behavior per KHR_DRACO_MESH_COMPRESSION spec
// TODO - Decompression could be threaded: Use DracoWorkerLoader?
//
// eslint-disable-next-line max-len
// https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
static _decompressMeshPrimitive(primitive, options) {
const compressedPrimitive =
primitive.extensions && primitive.extensions[KHR_DRACO_MESH_COMPRESSION];
if (!compressedPrimitive) {
return;
}
// TODO - use registered DracoWriter...
const compressedData = options.DracoWriter.encodeSync({attributes});
if (!options.DracoLoader || !options.decompress) {
return;
}
// Draco compression may change the order and number of vertices in a mesh.
// To satisfy the requirement that accessors properties be correct for both
// compressed and uncompressed data, generators should create uncompressed
// attributes and indices using data that has been decompressed from the Draco buffer,
// rather than the original source data.
const decodedData = options.DracoLoader.parseSync({attributes});
const fauxAccessors = options._addFauxAttributes(decodedData.attributes);
// Extension will be processed, delete it
delete primitive.extensions[KHR_DRACO_MESH_COMPRESSION];
const bufferViewIndex = options.addBufferView(compressedData);
const buffer = this._getBufferViewArray(compressedPrimitive.bufferView);
const decodedData = options.DracoLoader.parseSync(buffer);
primitive.attributes = getGLTFAccessors(decodedData.attributes);
if (decodedData.indices) {
primitive.indices = getGLTFAccessor(decodedData.indices);
const glTFMesh = {
primitives: [
{
attributes: fauxAccessors, // TODO - verify with spec
mode, // GL.POINTS
extensions: {
[KHR_DRACO_MESH_COMPRESSION]: {
bufferView: bufferViewIndex,
attributes: fauxAccessors // TODO - verify with spec
}
}
}
]
};
return glTFMesh;
}
function checkPrimitive(primitive) {
if (!primitive.attributes && Object.keys(primitive.attributes).length > 0) {
throw new Error('Empty glTF primitive detected: Draco decompression failure?');
}
}
function* meshPrimitiveIterator(scenegraph) {
for (const mesh of scenegraph.json.meshes || []) {
for (const primitive of mesh.primitives) {
yield primitive;
}
}
}

@@ -25,7 +25,9 @@ import {getImageMIMEType} from '@loaders.gl/images';

},
binary: null
buffers: []
};
}
// TODO - this is too sloppy, define inputs more clearly
this.gltf = gltf;
assert(this.gltf.json);
}

@@ -128,5 +130,5 @@

}
const object = this.gltf[array] && this.gltf[array][index];
const object = this.json[array] && this.json[array][index];
if (!object) {
console.warn(`glTF file error: Could not find ${array}[${index}]`); // eslint-disable-line
throw new Error(`glTF file error: Could not find ${array}[${index}]`); // eslint-disable-line
}

@@ -140,7 +142,11 @@ return object;

bufferView = this.getBufferView(bufferView);
const buffer = this.getBuffer(bufferView.buffer);
const arrayBuffer = buffer.data;
const bufferIndex = bufferView.buffer;
const byteOffset = bufferView.byteOffset || 0;
return new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
// Get hold of the arrayBuffer
// const buffer = this.getBuffer(bufferIndex);
const binChunk = this.gltf.buffers[bufferIndex];
assert(binChunk);
const byteOffset = bufferView.byteOffset || 0 + binChunk.byteOffset;
return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
}

@@ -147,0 +153,0 @@

@@ -14,10 +14,9 @@ /* eslint-disable camelcase, max-statements */

const LE = true; // Binary GLTF is little endian.
const BE = false; // Magic needs to be written as BE
function getMagicString(dataView) {
function getMagicString(dataView, byteOffset = 0) {
return `\
${String.fromCharCode(dataView.getUint8(0))}\
${String.fromCharCode(dataView.getUint8(1))}\
${String.fromCharCode(dataView.getUint8(2))}\
${String.fromCharCode(dataView.getUint8(3))}`;
${String.fromCharCode(dataView.getUint8(byteOffset + 0))}\
${String.fromCharCode(dataView.getUint8(byteOffset + 1))}\
${String.fromCharCode(dataView.getUint8(byteOffset + 2))}\
${String.fromCharCode(dataView.getUint8(byteOffset + 3))}`;
}

@@ -35,10 +34,14 @@

// https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#glb-file-format-specification
// Compare with GLB loader documentation
/*
Returns {
// Header
type: String,
magic: number,
header: {
type: string,
magic: number,
byteLength: number,
byteOffset: number
},
version: number,
byteLength: number,
byteOffset: number,

@@ -50,2 +53,14 @@ // JSON Chunk

hasBinChunk: boolean,
binChunks: [{
arrayBuffer,
byteOffset,
byteLength
}],
// Deprecated (duplicates header)
type: string,
magic: number,
version: number,
byteLength: number,
byteOffset: number,
binChunkByteOffset: number,

@@ -55,2 +70,3 @@ binChunkLength: number

*/
export default function parseGLBSync(glb, arrayBuffer, byteOffset = 0, options = {}) {

@@ -60,15 +76,13 @@ // Check that GLB Header starts with the magic number

glb.byteOffset = byteOffset; // Byte offset into the initial arrayBuffer
// GLB Header
glb.magic = dataView.getUint32(byteOffset + 0, BE); // Magic number (the ASCII string 'glTF').
glb.type = getMagicString(dataView, byteOffset + 0);
glb.version = dataView.getUint32(byteOffset + 4, LE); // Version 2 of binary glTF container format
glb.byteLength = dataView.getUint32(byteOffset + 8, LE); // Total byte length of generated file
const byteLength = dataView.getUint32(byteOffset + 8, LE); // Total byte length of generated file
glb.type = getMagicString(dataView);
// Less important stuff in a header
glb.header = {
byteOffset, // Byte offset into the initial arrayBuffer
byteLength
};
// TODO - switch type checks to use strings
const {magic = MAGIC_glTF} = options;
const isMagicValid = glb.magic === MAGIC_glTF || glb.magic === magic;
if (!isMagicValid) {
if (glb.type !== 'glTF') {
console.warn(`Invalid GLB magic string ${glb.type}`); // eslint-disable-line

@@ -78,47 +92,92 @@ }

assert(glb.version === 2, `Invalid GLB version ${glb.version}. Only .glb v2 supported`);
assert(glb.byteLength > 20);
assert(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
// TODO - per spec we must iterate over chunks, ignoring all except JSON and BIN
// Per spec we must iterate over chunks, ignoring all except JSON and BIN
glb.json = {};
glb.hasBinChunk = false;
glb.binChunks = [];
// Parse the JSON chunk
parseGLBChunksSync(glb, dataView, byteOffset + 12, options);
const jsonChunkLength = dataView.getUint32(byteOffset + 12, LE); // Byte length of json chunk
const jsonChunkFormat = dataView.getUint32(byteOffset + 16, LE); // Chunk format as uint32
// DEPRECATED - duplicate header fields in root of returned object
addDeprecatedFields(glb);
// Check JSON Chunk format (0 = Back compat)
const isJSONChunk = jsonChunkFormat === GLB_CHUNK_TYPE_JSON || jsonChunkFormat === 0;
assert(isJSONChunk, `JSON chunk format ${jsonChunkFormat}`);
return byteOffset + glb.header.byteLength;
}
// Create a "view" of the binary encoded JSON data
const jsonChunkByteOffset = GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE; // First headers: 20 bytes
const jsonChunk = new Uint8Array(arrayBuffer, byteOffset + jsonChunkByteOffset, jsonChunkLength);
function parseGLBChunksSync(glb, dataView, byteOffset, options) {
// Iterate as long as there is space left for another chunk header
while (byteOffset + 8 <= glb.header.byteLength) {
const chunkLength = dataView.getUint32(byteOffset + 0, LE); // Byte length of chunk
const chunkFormat = dataView.getUint32(byteOffset + 4, LE); // Chunk format as uint32
byteOffset += GLB_CHUNK_HEADER_SIZE;
// Decode the JSON binary array into clear text
const textDecoder = new TextDecoder('utf8');
const jsonText = textDecoder.decode(jsonChunk);
// Per spec we must iterate over chunks, ignoring all except JSON and BIN
switch (chunkFormat) {
case GLB_CHUNK_TYPE_JSON:
parseJSONChunk(glb, dataView, byteOffset, chunkLength, options);
break;
case GLB_CHUNK_TYPE_BIN:
parseBINChunk(glb, dataView, byteOffset, chunkLength, options);
break;
default:
// Ignore, per spec
// console.warn(`Unknown GLB chunk type`); // eslint-disable-line
break;
}
// Parse the JSON text into a JavaScript data structure
glb.json = JSON.parse(jsonText);
// DEPRECATED - Backward compatibility for very old xviz files
switch (chunkFormat) {
case 0:
if (!options.strict) {
parseJSONChunk(glb, dataView, byteOffset, chunkLength, options);
}
break;
case 1:
if (!options.strict) {
parseBINChunk(glb, dataView, byteOffset, chunkLength, options);
}
break;
default:
}
const binChunkStart = jsonChunkByteOffset + padTo4Bytes(jsonChunkLength);
byteOffset += padTo4Bytes(chunkLength);
}
// Parse and check BIN chunk header
// Note: BIN chunk can be optional
glb.hasBinChunk = binChunkStart + 8 <= glb.byteLength;
return byteOffset;
}
if (glb.hasBinChunk) {
const binChunkLength = dataView.getUint32(byteOffset + binChunkStart + 0, LE);
const binChunkFormat = dataView.getUint32(byteOffset + binChunkStart + 4, LE);
// Parse a GLB JSON chunk
function parseJSONChunk(glb, dataView, byteOffset, chunkLength, options) {
// 1. Create a "view" of the binary encoded JSON data inside the GLB
const jsonChunk = new Uint8Array(dataView.buffer, byteOffset, chunkLength);
const isBinChunk = binChunkFormat === GLB_CHUNK_TYPE_BIN || binChunkFormat === 1; // Back compat
assert(isBinChunk, `BIN chunk format ${binChunkFormat}`);
// 2. Decode the JSON binary array into clear text
const textDecoder = new TextDecoder('utf8');
const jsonText = textDecoder.decode(jsonChunk);
const binChunkByteOffset = binChunkStart + GLB_CHUNK_HEADER_SIZE;
// 3. Parse the JSON text into a JavaScript data structure
glb.json = JSON.parse(jsonText);
}
// TODO - copy or create typed array view
glb.binChunkByteOffset = binChunkByteOffset;
glb.binChunkLength = binChunkLength;
}
// Parse a GLB BIN chunk
function parseBINChunk(glb, dataView, byteOffset, chunkLength, options) {
// Note: BIN chunk can be optional
glb.header.hasBinChunk = true;
glb.binChunks.push({
byteOffset,
byteLength: chunkLength,
arrayBuffer: dataView.buffer
// TODO - copy, or create typed array view?
});
}
return byteOffset + glb.byteLength;
function addDeprecatedFields(glb) {
glb.byteOffset = glb.header.byteOffset;
glb.magic = glb.header.magic;
glb.version = glb.header.version;
glb.byteLength = glb.header.byteLength;
glb.hasBinChunk = glb.binChunks.length >= 1;
glb.binChunkByteOffset = glb.header.hasBinChunk ? glb.binChunks[0].byteOffset : 0;
glb.binChunkLength = glb.header.hasBinChunk ? glb.binChunks[0].byteLength : 0;
}

@@ -6,28 +6,14 @@ /* eslint-disable camelcase, max-statements, no-restricted-globals */

import {getFullUri} from './gltf-utils/gltf-utils';
import {decodeExtensions, decodeExtensionsSync} from './extensions/extensions';
import parseGLBSync, {isGLB} from './parse-glb';
import * as EXTENSIONS from './extensions';
import postProcessGLTF from './post-process-gltf';
// import {getGLTFAccessors, getGLTFAccessor} from './gltf-attribute-utils';
// import {
// ATTRIBUTE_TYPE_TO_COMPONENTS,
// ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE,
// ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY
// } from '../gltf/gltf-utils';
const DEFAULT_SYNC_OPTIONS = {
fetchLinkedResources: false, // Fetch any linked .BIN buffers, decode base64
decompress: false, // Decompress Draco compressed meshes (if DracoLoader available)
DracoLoader: null,
postProcess: true,
const DEFAULT_OPTIONS = {
fetchLinkedResources: true, // Fetch any linked .BIN buffers, decode base64
fetchImages: false, // Fetch any linked .BIN buffers, decode base64
createImages: false, // Create image objects
log: console // eslint-disable-line
};
const DEFAULT_ASYNC_OPTIONS = {
fetchLinkedResources: true, // Fetch any linked .BIN buffers, decode base64
fetch: fetchFile,
decompress: false, // Decompress Draco compressed meshes (if DracoLoader available)
DracoLoader: null,
postProcess: true,
createImages: false, // Create image objects
postProcess: false,
log: console // eslint-disable-line

@@ -42,10 +28,60 @@ };

export async function parseGLTF(gltf, arrayBufferOrString, byteOffset = 0, options = {}) {
options = {...DEFAULT_OPTIONS, ...options};
parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options);
const promises = [];
if (options.fetchImages) {
const promise = fetchImages(gltf, options);
promises.push(promise);
}
// Load linked buffers asynchronously and decodes base64 buffers in parallel
if (options.fetchLinkedResources) {
await fetchBuffers(gltf, options);
}
const promise = decodeExtensions(gltf, options);
promises.push(promise);
// Parallelize image loading and buffer loading/extension decoding
await Promise.all(promises);
// Post processing resolves indices to objects, buffers
return options.postProcess ? postProcessGLTF(gltf, options) : gltf;
}
// NOTE: The sync parser cannot handle linked assets or base64 encoded resources
// gtlf - input can be arrayBuffer (GLB or UTF8 encoded JSON), string (JSON), or parsed JSON.
// eslint-disable-next-line complexity
export function parseGLTFSync(gltf, arrayBufferOrString, byteOffset = 0, options = {}) {
options = Object.assign({}, DEFAULT_SYNC_OPTIONS, options);
options = {...DEFAULT_OPTIONS, ...options};
let data = arrayBufferOrString;
parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options);
// If binary is not starting with magic bytes, assume JSON and convert to string
// TODO: we could synchronously decode base64 encoded data URIs in this non-async path
if (options.fetchLinkedResources) {
fetchBuffersSync(gltf, options);
}
// Whether this is possible can depends on whether sync loaders are registered
// e.g. the `DracoWorkerLoader` cannot be called synchronously
if (options.decodeExtensions) {
decodeExtensionsSync(gltf, options);
}
// Post processing resolves indices to objects, buffers
return options.postProcess ? postProcessGLTF(gltf, options) : gltf;
}
// `data` - can be ArrayBuffer (GLB), ArrayBuffer (Binary JSON), String (JSON), or Object (parsed JSON)
function parseGLTFContainerSync(gltf, data, byteOffset, options) {
// Initialize gltf container
if (options.uri) {
gltf.baseUri = options.uri;
}
// If data is binary and starting with magic bytes, assume binary JSON text, convert to string
if (data instanceof ArrayBuffer && !isGLB(data, byteOffset, options)) {

@@ -56,64 +92,49 @@ const textDecoder = new TextDecoder();

gltf.buffers = [];
// If string, try to parse as JSON
if (typeof data === 'string') {
// If string, try to parse as JSON
gltf.json = JSON.parse(data);
} else if (data instanceof ArrayBuffer) {
// Populates JSON and some bin chunk info
byteOffset = parseGLBSync(gltf, data, byteOffset, options);
if (gltf.hasBinChunk) {
gltf.buffers.push({
arrayBuffer: data,
byteOffset: gltf.binChunkByteOffset,
byteLength: gltf.binChunkLength
});
}
// If still ArrayBuffer, parse as GLB container
gltf._glb = {};
byteOffset = parseGLBSync(gltf._glb, data, byteOffset, options);
gltf.json = gltf._glb.json;
} else {
// Assume parsed JSON
// Assume input is already parsed JSON
// TODO - should we throw instead?
gltf.json = data;
}
if (options.uri) {
gltf.baseUri = options.uri;
}
// Populate buffers
// Create an external buffers array to hold binary data
const buffers = gltf.json.buffers || [];
gltf.buffers = new Array(buffers.length).fill({});
// TODO: we could synchronously decode base64 encoded URIs in the non-async path
if (options.fetchLinkedResources) {
for (const buffer of gltf.json.buffers || []) {
if (buffer.uri) {
throw new Error('parseGLTFSync: Cannot decode uri buffers');
}
}
}
// Populates JSON and some bin chunk info
if (gltf._glb && gltf._glb.hasBinChunk) {
gltf.buffers[0] = {
// TODO - standardize on `arrayBuffer`
arrayBuffer: gltf._glb.binChunks[0].arrayBuffer,
byteOffset: gltf._glb.binChunks[0].byteOffset,
byteLength: gltf._glb.binChunks[0].byteLength
};
decodeExtensions(gltf, options);
return byteOffset;
}
export async function parseGLTF(gltf, arrayBufferOrString, byteOffset = 0, options = {}) {
options = Object.assign({}, DEFAULT_ASYNC_OPTIONS, options);
// Postpone decompressing/postprocessing to make sure we load any linked files first
// TODO - is this really needed?
parseGLTFSync(gltf, arrayBufferOrString, byteOffset, {
...options,
fetchLinkedResources: false, // We'll handle it if needed
postProcess: false, // We'll handle it if needed
decompress: false // We'll handle it if needed
});
// Load linked buffers asynchronously and decodes base64 buffers in parallel
if (options.fetchLinkedResources) {
await fetchLinkedResources(gltf, options);
gltf.json.buffers[0].data = gltf.buffers[0].arrayBuffer;
gltf.json.buffers[0].byteOffset = gltf.buffers[0].byteOffset;
}
return gltf;
// Populate images
const images = gltf.json.images || [];
gltf.images = new Array(images.length).fill({});
}
async function fetchLinkedResources(gltf, options) {
for (const buffer of gltf.json.buffers) {
if (buffer.uri) {
// Asynchronously fetch and parse buffers, store in buffers array outside of json
async function fetchBuffers(gltf, options) {
for (let i = 0; i < gltf.json.buffers.length; ++i) {
const buffer = gltf.json.buffers[i];
// TODO - remove this defensive hack and auto-infer the base URI
if (!options.uri) {
// eslint-disable-next-line
console.warn('options.uri must be set to decode embedded glTF buffers');
}
if (buffer.uri && options.uri) {
const fetch = options.fetch || window.fetch;

@@ -124,3 +145,9 @@ assert(fetch);

const arrayBuffer = await response.arrayBuffer();
buffer.data = arrayBuffer;
gltf.buffers[i] = {
arrayBuffer,
byteOffset: 0,
byteLength: arrayBuffer.byteLength
};
delete buffer.uri;

@@ -131,11 +158,59 @@ }

// TODO - async decoding for Draco
function decodeExtensions(gltf, options) {
for (const extensionName in EXTENSIONS) {
const disableExtension = extensionName in options && !options[extensionName];
if (!disableExtension) {
const extension = EXTENSIONS[extensionName];
extension.decode(gltf, options);
function fetchBuffersSync(gltf, options) {
for (const buffer of gltf.json.buffers || []) {
if (buffer.uri) {
throw new Error('parseGLTFSync: Cannot decode uri buffers');
}
}
}
async function fetchImages(gltf, options) {
const images = gltf.json.images || [];
const promises = [];
for (let i = 0; i < images.length; ++i) {
const image = images[i];
if ('uri' in image) {
promises.push(fetchAndParseLinkedImage(gltf, image, i, options));
}
}
return await Promise.all(promises);
}
// Asynchronously fetches and parses one image, store in images array outside of json
async function fetchAndParseLinkedImage(gltf, image, i, options) {
const fetch = options.fetch || window.fetch;
assert(fetch);
/*
if (image.bufferView) {
gltf.images[i] = await new Promise(resolve => {
const arrayBufferView = this.getBufferView(image.bufferView);
const mimeType = image.mimeType || 'image/jpeg';
const blob = new Blob([arrayBufferView], { type: mimeType });
const urlCreator = self.URL || self.webkitURL;
const imageUrl = urlCreator.createObjectURL(blob);
const img = new Image();
img.onload = () => resolve(img);
img.src = imageUrl;
});
}
*/
const uri = getFullUri(image.uri, options.uri);
// TODO - Call `parse` and use registered image loaders?
// const response = await fetch(uri);
// const arrayBuffer = await response.arrayBuffer();
// Create a new 'buffer' to hold the arrayBuffer?
// const image = parse(arrayBuffer);
gltf.images[i] = await new Promise((resolve, reject) => {
/* global Image */
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => resolve(img);
img.onerror = error => reject(error);
img.src = uri;
});
}
import {getFullUri} from './gltf-utils/gltf-utils';
import assert from './utils/assert';

@@ -71,6 +72,13 @@ // This is a post processor for loaded glTF files

postProcess(gltf, options = {}) {
this.gltf = gltf;
this.json = gltf.json;
this.buffers = gltf.buffers;
return this._resolveTree(gltf.json, options);
const {json, buffers = [], images = [], baseUri = ''} = gltf;
assert(json);
this.baseUri = baseUri;
this.json = json;
this.buffers = buffers;
this.images = images;
this._resolveTree(this.json, options);
return this.json;
}

@@ -115,8 +123,3 @@

}
// TODO arrays added by extensions, e.g. lights
return json;
}
/* eslint-enable complexity */

@@ -186,3 +189,3 @@ getScene(index) {

_resolveScene(scene, index) {
scene = {...scene};
// scene = {...scene};
scene.id = scene.id || `scene-${index}`;

@@ -194,3 +197,3 @@ scene.nodes = (scene.nodes || []).map(node => this.getNode(node));

_resolveNode(node, index) {
node = {...node};
// node = {...node};
node.id = node.id || `node-${index}`;

@@ -213,3 +216,3 @@ if (node.children) {

_resolveSkin(skin, index) {
skin = {...skin};
// skin = {...skin};
skin.id = skin.id || `skin-${index}`;

@@ -221,3 +224,3 @@ skin.inverseBindMatrices = this.getAccessor(skin.inverseBindMatrices);

_resolveMesh(mesh, index) {
mesh = {...mesh};
// mesh = {...mesh};
mesh.id = mesh.id || `mesh-${index}`;

@@ -245,3 +248,3 @@ if (mesh.primitives) {

_resolveMaterial(material, index) {
material = {...material};
// material = {...material};
material.id = material.id || `material-${index}`;

@@ -277,3 +280,3 @@ if (material.normalTexture) {

_resolveAccessor(accessor, index) {
accessor = {...accessor};
// accessor = {...accessor};
accessor.id = accessor.id || `accessor-${index}`;

@@ -289,2 +292,5 @@ if (accessor.bufferView !== undefined) {

accessor.bytesPerElement = accessor.bytesPerComponent * accessor.components;
// TODO - Create TypedArray for the accessor
return accessor;

@@ -294,3 +300,3 @@ }

_resolveTexture(texture, index) {
texture = {...texture};
// texture = {...texture};
texture.id = texture.id || `texture-${index}`;

@@ -303,3 +309,3 @@ texture.sampler = 'sampler' in texture ? this.getSampler(texture.sampler) : DEFAULT_SAMPLER;

_resolveSampler(sampler, index) {
sampler = {...sampler};
// sampler = {...sampler};
sampler.id = sampler.id || `sampler-${index}`;

@@ -321,6 +327,4 @@ // Map textual parameters to GL parameter values

// TODO - Handle non-binary-chunk images, data URIs, URLs etc
// TODO - Image creation could be done on getImage instead of during load
_resolveImage(image, index, options) {
image = {...image};
// image = {...image};
image.id = image.id || `image-${index}`;

@@ -332,26 +336,50 @@ if (image.bufferView !== undefined) {

if ('uri' in image) {
const baseUri = options.uri || this.gltf.baseUri;
// Check if image has been preloaded by the GLTFLoader
// If so, link it into the JSON and drop the URI
const preloadedImage = this.images[index];
if (preloadedImage && preloadedImage.image) {
image.image = preloadedImage.image;
delete image.uri;
}
// If not, resolve the relative URI using the baseName
const baseUri = options.uri || this.baseUri;
if (baseUri) {
const uri = image.uri;
image.uri = getFullUri(image.uri, baseUri);
// Deprecated
image.originalUri = uri;
image.baseUri = baseUri;
image.fullUri = getFullUri(image.uri, baseUri);
image.fullUri = image.uri;
}
}
function getImageAsync() {
if (image.uri) {
// TODO: Maybe just return the URL?
// TODO: Maybe use loaders.gl/core loadImage?
// Deprecated, use image.image or image.uri or image loaders instead
image.getImageAsync = () => {
/* global self, Blob, Image */
if (image.bufferView) {
return new Promise(resolve => {
/* global Image */
const arrayBufferView = this.getBufferView(image.bufferView);
const mimeType = image.mimeType || 'image/jpeg';
const blob = new Blob([arrayBufferView.data], {type: mimeType});
const urlCreator = self.URL || self.webkitURL;
const imageUrl = urlCreator.createObjectURL(blob);
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => resolve(img);
img.src = image.fullUri || image.uri;
img.src = imageUrl;
});
}
// cannot get image
return null;
}
image.getImageAsync = getImageAsync;
return image.uri
? new Promise(resolve => {
/* global Image */
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => resolve(img);
img.src = image.fullUri || image.uri;
})
: null;
};
return image;

@@ -361,3 +389,3 @@ }

_resolveBufferView(bufferView, index) {
bufferView = {...bufferView};
// bufferView = {...bufferView};
bufferView.id = bufferView.id || `bufferView-${index}`;

@@ -364,0 +392,0 @@ const bufferIndex = bufferView.buffer;

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc