@needle-tools/engine 4.7.4 → 4.8.0-next.9de3f45
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gltf-progressive-Bz6FXMZ1.min.js +8 -0
- package/dist/gltf-progressive-DAdiYt1v.js +1392 -0
- package/dist/gltf-progressive-D_S7mZaT.umd.cjs +8 -0
- package/dist/loader.worker-qHzhYKEC.js +1 -0
- package/dist/{needle-engine.bundle-BldBPoPh.js → needle-engine.bundle-C5vAAuK3.js} +9 -6
- package/dist/{needle-engine.bundle-ByrSH-zp.umd.cjs → needle-engine.bundle-fg0LG9Pa.umd.cjs} +6 -6
- package/dist/{needle-engine.bundle-Bb6xVcZE.min.js → needle-engine.bundle-tepIih-J.min.js} +5 -5
- package/dist/needle-engine.js +3 -3
- package/dist/needle-engine.min.js +1 -1
- package/dist/needle-engine.umd.cjs +1 -1
- package/lib/engine-components/export/usdz/extensions/behavior/Behaviour.d.ts +1 -1
- package/lib/engine-components/postprocessing/PostProcessingHandler.d.ts +1 -0
- package/lib/engine-components/postprocessing/PostProcessingHandler.js +8 -0
- package/lib/engine-components/postprocessing/PostProcessingHandler.js.map +1 -1
- package/package.json +4 -4
- package/src/engine-components/postprocessing/PostProcessingHandler.ts +14 -0
- package/dist/gltf-progressive-Bgh1c4Fd.js +0 -1224
- package/dist/gltf-progressive-D6f5talj.min.js +0 -8
- package/dist/gltf-progressive-otA_hxSA.umd.cjs +0 -8
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
var rt=Object.defineProperty,$e=r=>{throw TypeError(r)},st=(r,e,t)=>e in r?rt(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,c=(r,e,t)=>st(r,typeof e!="symbol"?e+"":e,t),Re=(r,e,t)=>e.has(r)||$e("Cannot "+t),b=(r,e,t)=>(Re(r,e,"read from private field"),t?t.call(r):e.get(r)),J=(r,e,t)=>e.has(r)?$e("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),U=(r,e,t,n)=>(Re(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t);import{BufferGeometry as oe,Mesh as Z,Box3 as be,Vector3 as G,Sphere as Ge,CompressedTexture as nt,Texture as ee,Matrix3 as ot,InterleavedBuffer as it,InterleavedBufferAttribute as at,BufferAttribute as lt,TextureLoader as ut,Matrix4 as je,Clock as dt,MeshStandardMaterial as ct}from"./three-DuDKwKB8.min.js";import{DRACOLoader as ht,KTX2Loader as gt,MeshoptDecoder as ft,GLTFLoader as Me}from"./three-examples-BMOhDaYR.min.js";const Ne="3.1.1";globalThis.GLTF_PROGRESSIVE_VERSION=Ne,console.debug(`[gltf-progressive] version ${Ne}`);let j="https://www.gstatic.com/draco/versioned/decoders/1.5.7/",te="https://www.gstatic.com/basis-universal/versioned/2021-04-15-ba1c3e4/";const mt=j,pt=te,We=new URL(j+"draco_decoder.js");We.searchParams.append("range","true"),fetch(We,{method:"GET",headers:{Range:"bytes=0-1"}}).catch(r=>{console.debug(`Failed to fetch remote Draco decoder from ${j} (offline: ${typeof navigator<"u"?navigator.onLine:"unknown"})`),j===mt&&Fe("./include/draco/"),te===pt&&Ue("./include/ktx2/")}).finally(()=>{ze()});const vt=()=>({dracoDecoderPath:j,ktx2TranscoderPath:te});function Fe(r){j=r,$&&$[Oe]!=j?(console.debug("Updating Draco decoder path to "+r),$[Oe]=j,$.setDecoderPath(j),$.preload()):console.debug("Setting Draco decoder path to "+r)}function Ue(r){te=r,N&&N.transcoderPath!=te?(console.debug("Updating KTX2 transcoder path to "+r),N.setTranscoderPath(te),N.init()):console.debug("Setting KTX2 transcoder path to "+r)}function ge(r){return ze(),r?N.detectSupport(r):r!==null&&console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures might fail"),{dracoLoader:$,ktx2Loader:N,meshoptDecoder:fe}}function De(r){r.dracoLoader||r.setDRACOLoader($),r.ktx2Loader||r.setKTX2Loader(N),r.meshoptDecoder||r.setMeshoptDecoder(fe)}const Oe=Symbol("dracoDecoderPath");let $,fe,N;function ze(){$||($=new ht,$[Oe]=j,$.setDecoderPath(j),$.setDecoderConfig({type:"js"}),$.preload()),N||(N=new gt,N.setTranscoderPath(te),N.init()),fe||(fe=ft)}const Se=new WeakMap;function Pe(r,e){let t=Se.get(r);t?t=Object.assign(t,e):t=e,Se.set(r,t)}const qe=Me.prototype.load;function xt(...r){const e=Se.get(this);let t=r[0];const n=new URL(t,window.location.href);if(n.hostname.endsWith("needle.tools")){const s=e?.progressive!==void 0?e.progressive:!0,i=e!=null&&e.usecase?e.usecase:"default";s?this.requestHeader.Accept=`*/*;progressive=allowed;usecase=${i}`:this.requestHeader.Accept=`*/*;usecase=${i}`,t=n.toString()}return r[0]=t,qe?.call(this,...r)}Me.prototype.load=xt,re("debugprogressive");function re(r){if(typeof window>"u")return!1;const e=new URL(window.location.href).searchParams.get(r);return e==null||e==="0"||e==="false"?!1:e===""?!0:e}function yt(r,e){if(e===void 0||e.startsWith("./")||e.startsWith("http")||r===void 0)return e;const t=r.lastIndexOf("/");if(t>=0){const n=r.substring(0,t+1);for(;n.endsWith("/")&&e.startsWith("/");)e=e.substring(1);return n+e}return e}let me;function Ve(){return me!==void 0||(me=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent),re("debugprogressive")&&console.log("[glTF Progressive]: isMobileDevice",me)),me}function Xe(){if(typeof window>"u")return!1;const r=new URL(window.location.href),e=r.hostname==="localhost"||/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(r.hostname);return r.hostname==="127.0.0.1"||e}class wt{constructor(e=100,t={}){c(this,"maxConcurrent"),c(this,"_running",new Map),c(this,"_queue",[]),c(this,"debug",!1),c(this,"tick",()=>{this.internalUpdate(),setTimeout(this.tick,10)}),this.maxConcurrent=e,this.debug=t.debug??!1,window.requestAnimationFrame(this.tick)}slot(e){return this.debug&&console.debug(`[PromiseQueue]: Requesting slot for key ${e}, running: ${this._running.size}, waiting: ${this._queue.length}`),new Promise(t=>{this._queue.push({key:e,resolve:t})})}add(e,t){this._running.has(e)||(this._running.set(e,t),t.finally(()=>{this._running.delete(e),this.debug&&console.debug(`[PromiseQueue]: Promise finished now running: ${this._running.size}, waiting: ${this._queue.length}. (finished ${e})`)}),this.debug&&console.debug(`[PromiseQueue]: Added new promise, now running: ${this._running.size}, waiting: ${this._queue.length}. (added ${e})`))}internalUpdate(){const e=this.maxConcurrent-this._running.size;for(let t=0;t<e&&this._queue.length>0;t++){this.debug&&console.debug(`[PromiseQueue]: Running ${this._running.size} promises, waiting for ${this._queue.length} more.`);const{key:n,resolve:s}=this._queue.shift();s({use:i=>this.add(n,i)})}}}const Lt=typeof window>"u"&&typeof document>"u",Te=Symbol("needle:raycast-mesh");function ne(r){return r?.[Te]instanceof oe?r[Te]:null}function _t(r,e){if((r.type==="Mesh"||r.type==="SkinnedMesh")&&!ne(r)){const t=Mt(e);t.userData={isRaycastMesh:!0},r[Te]=t}}function bt(r=!0){if(r){if(ie)return;const e=ie=Z.prototype.raycast;Z.prototype.raycast=function(t,n){const s=this,i=ne(s);let o;i&&s.isMesh&&(o=s.geometry,s.geometry=i),e.call(this,t,n),o&&(s.geometry=o)}}else{if(!ie)return;Z.prototype.raycast=ie,ie=null}}let ie=null;function Mt(r){const e=new oe;for(const t in r.attributes)e.setAttribute(t,r.getAttribute(t));return e.setIndex(r.getIndex()),e}const X=new Array,w=re("debugprogressive");let pe,se=-1;if(w){let r=function(){se+=1,se>=e&&(se=-1),console.log(`Toggle LOD level [${se}]`)},e=6;window.addEventListener("keyup",t=>{t.key==="p"&&r(),t.key==="w"&&(pe=!pe,console.log(`Toggle wireframe [${pe}]`));const n=parseInt(t.key);!isNaN(n)&&n>=0&&(se=n,console.log(`Set LOD level to [${se}]`))})}function He(r){if(w)if(Array.isArray(r))for(const e of r)He(e);else r&&"wireframe"in r&&(r.wireframe=pe===!0)}const ae=new Array;let Dt=0;const Ot=Ve()?2:10;function St(r){if(ae.length<Ot){const t=ae.length;w&&console.warn(`[Worker] Creating new worker #${t}`);const n=Be.createWorker(r||{});return ae.push(n),n}const e=Dt++%ae.length;return ae[e]}class Be{constructor(e,t){c(this,"worker"),c(this,"_running",[]),c(this,"_webglRenderer",null),c(this,"_debug",!1),this.worker=e,this._debug=t.debug??!1,e.onmessage=n=>{const s=n.data;switch(this._debug&&console.log("[Worker] EVENT",s),s.type){case"loaded-gltf":for(const i of this._running)if(i.url===s.result.url){Pt(s.result),i.resolve(s.result);const o=i.url;o.startsWith("blob:")&&URL.revokeObjectURL(o)}}},e.onerror=n=>{console.error("[Worker] Error in gltf-progressive worker:",n)},e.postMessage({type:"init"})}static async createWorker(e){const t=new Worker(new URL("/loader.worker-qHzhYKEC.js",import.meta.url),{type:"module"});return new Be(t,e)}async load(e,t){const n=vt();let s=t?.renderer;s||(this._webglRenderer??(this._webglRenderer=(async()=>{const{WebGLRenderer:a}=await import("./three-DuDKwKB8.min.js").then(u=>u.THREE);return new a})()),s=await this._webglRenderer);const i=ge(s).ktx2Loader.workerConfig;e instanceof URL?e=e.toString():e.startsWith("file:")?e=URL.createObjectURL(new Blob([e])):!e.startsWith("blob:")&&!e.startsWith("http:")&&!e.startsWith("https:")&&(e=new URL(e,window.location.href).toString());const o={type:"load",url:e,dracoDecoderPath:n.dracoDecoderPath,ktx2TranscoderPath:n.ktx2TranscoderPath,ktx2LoaderConfig:i};return this._debug&&console.debug("[Worker] Sending load request",o),this.worker.postMessage(o),new Promise(a=>{this._running.push({url:e.toString(),resolve:a})})}}function Pt(r){var e,t,n,s,i,o,a,u,d,h,v,x,y,O,I,M;for(const S of r.geometries){const l=S.geometry,f=new oe;if(f.name=l.name||"",l.index){const L=l.index;f.setIndex(Ae(L))}for(const L in l.attributes){const P=l.attributes[L],D=Ae(P);f.setAttribute(L,D)}if(l.morphAttributes)for(const L in l.morphAttributes){const P=l.morphAttributes[L].map(D=>Ae(D));f.morphAttributes[L]=P}if(f.morphTargetsRelative=l.morphTargetsRelative??!1,f.boundingBox=new be,f.boundingBox.min=new G((e=l.boundingBox)==null?void 0:e.min.x,(t=l.boundingBox)==null?void 0:t.min.y,(n=l.boundingBox)==null?void 0:n.min.z),f.boundingBox.max=new G((s=l.boundingBox)==null?void 0:s.max.x,(i=l.boundingBox)==null?void 0:i.max.y,(o=l.boundingBox)==null?void 0:o.max.z),f.boundingSphere=new Ge(new G((a=l.boundingSphere)==null?void 0:a.center.x,(u=l.boundingSphere)==null?void 0:u.center.y,(d=l.boundingSphere)==null?void 0:d.center.z),(h=l.boundingSphere)==null?void 0:h.radius),l.groups)for(const L of l.groups)f.addGroup(L.start,L.count,L.materialIndex);l.userData&&(f.userData=l.userData),S.geometry=f}for(const S of r.textures){const l=S.texture;let f=null;if(l.isCompressedTexture){const L=l.mipmaps,P=((v=l.image)==null?void 0:v.width)||((y=(x=l.source)==null?void 0:x.data)==null?void 0:y.width)||-1,D=((O=l.image)==null?void 0:O.height)||((M=(I=l.source)==null?void 0:I.data)==null?void 0:M.height)||-1;f=new nt(L,P,D,l.format,l.type,l.mapping,l.wrapS,l.wrapT,l.magFilter,l.minFilter,l.anisotropy,l.colorSpace)}else f=new ee(l.image,l.mapping,l.wrapS,l.wrapT,l.magFilter,l.minFilter,l.format,l.type,l.anisotropy,l.colorSpace),f.mipmaps=l.mipmaps,f.channel=l.channel,f.source.data=l.source.data,f.flipY=l.flipY,f.premultiplyAlpha=l.premultiplyAlpha,f.unpackAlignment=l.unpackAlignment,f.matrix=new ot(...l.matrix.elements);if(!f){console.error("[Worker] Failed to create new texture from received data. Texture is not a CompressedTexture or Texture.");continue}S.texture=f}return r}function Ae(r){let e=r;if("isInterleavedBufferAttribute"in r&&r.isInterleavedBufferAttribute){const t=r.data,n=t.array,s=new it(n,t.stride);e=new at(s,r.itemSize,n.byteOffset,r.normalized),e.offset=r.offset}else"isBufferAttribute"in r&&r.isBufferAttribute&&(e=new lt(r.array,r.itemSize,r.normalized),e.usage=r.usage,e.gpuType=r.gpuType,e.updateRanges=r.updateRanges);return e}const Tt=re("gltf-progressive-worker"),At=re("gltf-progressive-reduce-mipmaps"),ke=Symbol("needle-progressive-texture"),z="NEEDLE_progressive",A=class R{constructor(e,t){c(this,"parser"),c(this,"url"),c(this,"_isLoadingMesh"),c(this,"loadMesh",n=>{var s,i;if(this._isLoadingMesh)return null;const o=(i=(s=this.parser.json.meshes[n])==null?void 0:s.extensions)==null?void 0:i[z];return o?(this._isLoadingMesh=!0,this.parser.getDependency("mesh",n).then(a=>{var u;return this._isLoadingMesh=!1,a&&R.registerMesh(this.url,o.guid,a,(u=o.lods)==null?void 0:u.length,0,o),a})):null}),w&&console.log("Progressive extension registered for",t),this.parser=e,this.url=t}get name(){return z}static getMeshLODExtension(e){const t=this.getAssignedLODInformation(e);return t!=null&&t.key?this.lodInfos.get(t.key):null}static getPrimitiveIndex(e){var t;return((t=this.getAssignedLODInformation(e))==null?void 0:t.index)??-1}static getMaterialMinMaxLODsCount(e,t){const n=this,s="LODS:minmax",i=e[s];if(i!=null)return i;if(t||(t={min_count:1/0,max_count:0,lods:[]}),Array.isArray(e)){for(const a of e)this.getMaterialMinMaxLODsCount(a,t);return e[s]=t,t}if(w==="verbose"&&console.log("getMaterialMinMaxLODsCount",e),e.type==="ShaderMaterial"||e.type==="RawShaderMaterial"){const a=e;for(const u of Object.keys(a.uniforms)){const d=a.uniforms[u].value;d?.isTexture===!0&&o(d,t)}}else if(e.isMaterial)for(const a of Object.keys(e)){const u=e[a];u?.isTexture===!0&&o(u,t)}else w&&console.warn(`[getMaterialMinMaxLODsCount] Unsupported material type: ${e.type}`);return e[s]=t,t;function o(a,u){const d=n.getAssignedLODInformation(a);if(d){const h=n.lodInfos.get(d.key);if(h&&h.lods){u.min_count=Math.min(u.min_count,h.lods.length),u.max_count=Math.max(u.max_count,h.lods.length);for(let v=0;v<h.lods.length;v++){const x=h.lods[v];x.width&&(u.lods[v]=u.lods[v]||{min_height:1/0,max_height:0},u.lods[v].min_height=Math.min(u.lods[v].min_height,x.height),u.lods[v].max_height=Math.max(u.lods[v].max_height,x.height))}}}}}static hasLODLevelAvailable(e,t){var n;if(Array.isArray(e)){for(const o of e)if(this.hasLODLevelAvailable(o,t))return!0;return!1}if(e.isMaterial===!0){for(const o of Object.keys(e)){const a=e[o];if(a&&a.isTexture&&this.hasLODLevelAvailable(a,t))return!0}return!1}else if(e.isGroup===!0){for(const o of e.children)if(o.isMesh===!0&&this.hasLODLevelAvailable(o,t))return!0}let s,i;if(e.isMesh?s=e.geometry:(e.isBufferGeometry||e.isTexture)&&(s=e),s&&(n=s?.userData)!=null&&n.LODS){const o=s.userData.LODS;if(i=this.lodInfos.get(o.key),t===void 0)return i!=null;if(i)return Array.isArray(i.lods)?t<i.lods.length:t===0}return!1}static assignMeshLOD(e,t){var n;if(!e)return Promise.resolve(null);if(e instanceof Z||e.isMesh===!0){const s=e.geometry,i=this.getAssignedLODInformation(s);if(!i)return Promise.resolve(null);for(const o of X)(n=o.onBeforeGetLODMesh)==null||n.call(o,e,t);return e["LOD:requested level"]=t,R.getOrLoadLOD(s,t).then(o=>{if(Array.isArray(o)){const a=i.index||0;o=o[a]}return e["LOD:requested level"]===t&&(delete e["LOD:requested level"],o&&s!=o&&(o?.isBufferGeometry?e.geometry=o:w&&console.error("Invalid LOD geometry",o))),o}).catch(o=>(console.error("Error loading mesh LOD",e,o),null))}else w&&console.error("Invalid call to assignMeshLOD: Request mesh LOD but the object is not a mesh",e);return Promise.resolve(null)}static assignTextureLOD(e,t=0){if(!e)return Promise.resolve(null);if(e.isMesh===!0){const n=e;if(Array.isArray(n.material)){const s=new Array;for(const i of n.material){const o=this.assignTextureLOD(i,t);s.push(o)}return Promise.all(s).then(i=>{const o=new Array;for(const a of i)Array.isArray(a)&&o.push(...a);return o})}else return this.assignTextureLOD(n.material,t)}if(e.isMaterial===!0){const n=e,s=[],i=new Array;if(n.uniforms&&(n.isRawShaderMaterial||n.isShaderMaterial===!0)){const o=n;for(const a of Object.keys(o.uniforms)){const u=o.uniforms[a].value;if(u?.isTexture===!0){const d=this.assignTextureLODForSlot(u,t,n,a).then(h=>(h&&o.uniforms[a].value!=h&&(o.uniforms[a].value=h,o.uniformsNeedUpdate=!0),h));s.push(d),i.push(a)}}}else for(const o of Object.keys(n)){const a=n[o];if(a?.isTexture===!0){const u=this.assignTextureLODForSlot(a,t,n,o);s.push(u),i.push(o)}}return Promise.all(s).then(o=>{const a=new Array;for(let u=0;u<o.length;u++){const d=o[u],h=i[u];d&&d.isTexture===!0?a.push({material:n,slot:h,texture:d,level:t}):a.push({material:n,slot:h,texture:null,level:t})}return a})}if(e instanceof ee||e.isTexture===!0){const n=e;return this.assignTextureLODForSlot(n,t,null,null)}return Promise.resolve(null)}static assignTextureLODForSlot(e,t,n,s){return e?.isTexture!==!0?Promise.resolve(null):s==="glyphMap"?Promise.resolve(e):R.getOrLoadLOD(e,t).then(i=>{var o,a;if(Array.isArray(i))return console.warn("Progressive: Got an array of textures for a texture slot, this should not happen..."),null;if(i?.isTexture===!0){if(i!=e&&n&&s){const u=n[s];if(u&&!w){const d=this.getAssignedLODInformation(u);if(d&&d?.level<t)return w==="verbose"&&console.warn("Assigned texture level is already higher: ",d.level,t,n,u,i),null}if(At&&i.mipmaps){const d=i.mipmaps.length;i.mipmaps.length=Math.min(i.mipmaps.length,3),d!==i.mipmaps.length&&w&&console.debug(`Reduced mipmap count from ${d} to ${i.mipmaps.length} for ${i.uuid}: ${(o=i.image)==null?void 0:o.width}x${(a=i.image)==null?void 0:a.height}.`)}n[s]=i}return i}else w=="verbose"&&console.warn("No LOD found for",e,t);return null}).catch(i=>(console.error("Error loading LOD",e,i),null))}afterRoot(e){var t,n;return w&&console.log("AFTER",this.url,e),(t=this.parser.json.textures)==null||t.forEach((s,i)=>{var o;if(s!=null&&s.extensions){const a=s?.extensions[z];if(a){if(!a.lods){w&&console.warn("Texture has no LODs",a);return}let u=!1;for(const d of this.parser.associations.keys())if(d.isTexture===!0){const h=this.parser.associations.get(d);h?.textures===i&&(u=!0,R.registerTexture(this.url,d,(o=a.lods)==null?void 0:o.length,i,a))}u||this.parser.getDependency("texture",i).then(d=>{var h;d&&R.registerTexture(this.url,d,(h=a.lods)==null?void 0:h.length,i,a)})}}}),(n=this.parser.json.meshes)==null||n.forEach((s,i)=>{if(s!=null&&s.extensions){const o=s?.extensions[z];if(o&&o.lods){for(const a of this.parser.associations.keys())if(a.isMesh){const u=this.parser.associations.get(a);u?.meshes===i&&R.registerMesh(this.url,o.guid,a,o.lods.length,u.primitives,o)}}}}),null}static async getOrLoadLOD(e,t){var n,s,i,o;const a=w=="verbose",u=this.getAssignedLODInformation(e);if(!u)return w&&console.warn(`[gltf-progressive] No LOD information found: ${e.name}, uuid: ${e.uuid}, type: ${e.type}`,e),null;const d=u?.key;let h;if(e.isTexture===!0){const v=e;v.source&&v.source[ke]&&(h=v.source[ke])}if(h||(h=R.lodInfos.get(d)),h){if(t>0){let y=!1;const O=Array.isArray(h.lods);if(O&&t>=h.lods.length?y=!0:O||(y=!0),y)return this.lowresCache.get(d)}const v=Array.isArray(h.lods)?(n=h.lods[t])==null?void 0:n.path:h.lods;if(!v)return w&&!h["missing:uri"]&&(h["missing:uri"]=!0,console.warn("Missing uri for progressive asset for LOD "+t,h)),null;const x=yt(u.url,v);if(x.endsWith(".glb")||x.endsWith(".gltf")){if(!h.guid)return console.warn("missing pointer for glb/gltf texture",h),null;const y=x+"_"+h.guid,O=await this.queue.slot(x),I=this.previouslyLoaded.get(y);if(I!==void 0){a&&console.log(`LOD ${t} was already loading/loaded: ${y}`);let l=await I.catch(L=>(console.error(`Error loading LOD ${t} from ${x}
|
|
2
|
+
`,L),null)),f=!1;if(l==null||(l instanceof ee&&e instanceof ee?(s=l.image)!=null&&s.data||(i=l.source)!=null&&i.data?l=this.copySettings(e,l):(f=!0,this.previouslyLoaded.delete(y)):l instanceof oe&&e instanceof oe&&((o=l.attributes.position)!=null&&o.array||(f=!0,this.previouslyLoaded.delete(y)))),!f)return l}if(!O.use)return w&&console.log(`LOD ${t} was aborted: ${x}`),null;const M=h,S=new Promise(async(l,f)=>{if(Tt){const m=await(await St({})).load(x);if(m.textures.length>0)for(const g of m.textures){let p=g.texture;return R.assignLODInformation(u.url,p,d,t,void 0),e instanceof ee&&(p=this.copySettings(e,p)),p&&(p.guid=M.guid),l(p)}if(m.geometries.length>0){const g=new Array;for(const p of m.geometries){const T=p.geometry;R.assignLODInformation(u.url,T,d,t,p.primitiveIndex),g.push(T)}return l(g)}return l(null)}const L=new Me;De(L),w&&(await new Promise(m=>setTimeout(m,1e3)),a&&console.warn("Start loading (delayed) "+x,M.guid));let P=x;if(M&&Array.isArray(M.lods)){const m=M.lods[t];m.hash&&(P+="?v="+m.hash)}const D=await L.loadAsync(P).catch(m=>(console.error(`Error loading LOD ${t} from ${x}
|
|
3
|
+
`,m),l(null)));if(!D)return l(null);const F=D.parser;a&&console.log("Loading finished "+x,M.guid);let k=0;if(D.parser.json.textures){let m=!1;for(const g of D.parser.json.textures){if(g!=null&&g.extensions){const p=g?.extensions[z];if(p!=null&&p.guid&&p.guid===M.guid){m=!0;break}}k++}if(m){let g=await F.getDependency("texture",k);return g&&R.assignLODInformation(u.url,g,d,t,void 0),a&&console.log('change "'+e.name+'" \u2192 "'+g.name+'"',x,k,g,y),e instanceof ee&&(g=this.copySettings(e,g)),g&&(g.guid=M.guid),l(g)}else w&&console.warn("Could not find texture with guid",M.guid,D.parser.json)}if(k=0,D.parser.json.meshes){let m=!1;for(const g of D.parser.json.meshes){if(g!=null&&g.extensions){const p=g?.extensions[z];if(p!=null&&p.guid&&p.guid===M.guid){m=!0;break}}k++}if(m){const g=await F.getDependency("mesh",k);if(a&&console.log(`Loaded Mesh "${g.name}"`,x,k,g,y),g.isMesh===!0){const p=g.geometry;return R.assignLODInformation(u.url,p,d,t,0),l(p)}else{const p=new Array;for(let T=0;T<g.children.length;T++){const B=g.children[T];if(B.isMesh===!0){const V=B.geometry;R.assignLODInformation(u.url,V,d,t,T),p.push(V)}}return l(p)}}else w&&console.warn("Could not find mesh with guid",M.guid,D.parser.json)}return l(null)});return this.previouslyLoaded.set(y,S),O.use(S),await S}else if(e instanceof ee){a&&console.log("Load texture from uri: "+x);const y=await new ut().loadAsync(x);return y?(y.guid=h.guid,y.flipY=!1,y.needsUpdate=!0,y.colorSpace=e.colorSpace,a&&console.log(h,y)):w&&console.warn("failed loading",x),y}}else w&&console.warn(`Can not load LOD ${t}: no LOD info found for "${d}" ${e.name}`,e.type);return null}static assignLODInformation(e,t,n,s,i){if(!t)return;t.userData||(t.userData={});const o=new kt(e,n,s,i);t.userData.LODS=o,"source"in t&&typeof t.source=="object"&&(t.source.LODS=o)}static getAssignedLODInformation(e){var t,n;return e?(t=e.userData)!=null&&t.LODS?e.userData.LODS:"source"in e&&(n=e.source)!=null&&n.LODS?e.source.LODS:null:null}static copySettings(e,t){return t?(w==="verbose"&&console.debug(`Copy texture settings
|
|
4
|
+
`,e.uuid,`
|
|
5
|
+
`,t.uuid),t=t.clone(),t.offset=e.offset,t.repeat=e.repeat,t.colorSpace=e.colorSpace,t.magFilter=e.magFilter,t.minFilter=e.minFilter,t.wrapS=e.wrapS,t.wrapT=e.wrapT,t.flipY=e.flipY,t.anisotropy=e.anisotropy,t.mipmaps||(t.generateMipmaps=e.generateMipmaps),t):e}};c(A,"registerTexture",(r,e,t,n,s)=>{var i,o,a,u,d,h,v,x;if(!e){w&&console.error("gltf-progressive: Called register texture without texture");return}if(w){const O=((i=e.image)==null?void 0:i.width)||((a=(o=e.source)==null?void 0:o.data)==null?void 0:a.width)||0,I=((u=e.image)==null?void 0:u.height)||((h=(d=e.source)==null?void 0:d.data)==null?void 0:h.height)||0;console.log(`> Progressive: register texture[${n}] "${e.name||e.uuid}", Current: ${O}x${I}, Max: ${(v=s.lods[0])==null?void 0:v.width}x${(x=s.lods[0])==null?void 0:x.height}, uuid: ${e.uuid}`,s,e)}e.source&&(e.source[ke]=s);const y=s.guid;A.assignLODInformation(r,e,y,t,n),A.lodInfos.set(y,s),A.lowresCache.set(y,e)}),c(A,"registerMesh",(r,e,t,n,s,i)=>{var o;const a=t.geometry;if(!a){w&&console.warn("gltf-progressive: Register mesh without geometry");return}a.userData||(a.userData={}),w&&console.log("> Progressive: register mesh "+t.name,{index:s,uuid:t.uuid},i,t),A.assignLODInformation(r,a,e,n,s),A.lodInfos.set(e,i);let u=A.lowresCache.get(e);u?u.push(t.geometry):u=[t.geometry],A.lowresCache.set(e,u),n>0&&!ne(t)&&_t(t,a);for(const d of X)(o=d.onRegisteredNewMesh)==null||o.call(d,t,i)}),c(A,"lodInfos",new Map),c(A,"previouslyLoaded",new Map),c(A,"lowresCache",new Map),c(A,"workers",[]),c(A,"_workersIndex",0),c(A,"maxConcurrent",50),c(A,"queue",new wt(A.maxConcurrent,{debug:w!=!1}));let q=A;class kt{constructor(e,t,n,s){c(this,"url"),c(this,"key"),c(this,"level"),c(this,"index"),this.url=e,this.key=t,this.level=n,s!=null&&(this.index=s)}}class ve{constructor(e,t){c(this,"frame_start"),c(this,"frame_capture_end"),c(this,"ready"),c(this,"_resolve"),c(this,"_signal"),c(this,"_resolved",!1),c(this,"_addedCount",0),c(this,"_resolvedCount",0),c(this,"_awaiting",[]),c(this,"_maxPromisesPerObject",1),c(this,"_currentFrame",0),c(this,"_seen",new WeakMap);var n;const s=Math.max(t.frames??2,2);this.frame_start=e,this.frame_capture_end=e+s,this.ready=new Promise(i=>{this._resolve=i}),this.ready.finally(()=>{this._resolved=!0,this._awaiting.length=0}),this._signal=t.signal,(n=this._signal)==null||n.addEventListener("abort",()=>{this.resolveNow()}),this._maxPromisesPerObject=Math.max(1,t.maxPromisesPerObject??1)}get awaitedCount(){return this._addedCount}get resolvedCount(){return this._resolvedCount}get currentlyAwaiting(){return this._awaiting.length}update(e){var t;this._currentFrame=e,((t=this._signal)!=null&&t.aborted||this._currentFrame>this.frame_capture_end&&this._awaiting.length===0)&&this.resolveNow()}add(e,t,n){if(this._resolved){w&&console.warn("PromiseGroup: Trying to add a promise to a resolved group, ignoring.");return}if(!(this._currentFrame>this.frame_capture_end)){if(this._maxPromisesPerObject>=1)if(this._seen.has(t)){let s=this._seen.get(t);if(s>=this._maxPromisesPerObject){w&&console.warn("PromiseGroup: Already awaiting object ignoring new promise for it.");return}this._seen.set(t,s+1)}else this._seen.set(t,1);this._awaiting.push(n),this._addedCount++,n.finally(()=>{this._resolvedCount++,this._awaiting.splice(this._awaiting.indexOf(n),1)})}}resolveNow(){var e,t;this._resolved||(t=this._resolve)==null||t.call(this,{awaited_count:this._addedCount,resolved_count:this._resolvedCount,cancelled:((e=this._signal)==null?void 0:e.aborted)??!1})}}c(ve,"addPromise",(r,e,t,n)=>{n.forEach(s=>{s.add(r,e,t)})});const W=re("debugprogressive"),It=re("noprogressive"),Ie=Symbol("Needle:LODSManager"),Ee=Symbol("Needle:LODState"),H=Symbol("Needle:CurrentLOD"),E={mesh_lod:-1,texture_lod:-1};var _,C,K,Ce,Y,le,xe,Q;let ue=(_=class{constructor(r,e){c(this,"renderer"),c(this,"context"),c(this,"projectionScreenMatrix",new je),c(this,"targetTriangleDensity",2e5),c(this,"skinnedMeshAutoUpdateBoundsInterval",30),c(this,"updateInterval","auto"),J(this,C,1),c(this,"pause",!1),c(this,"manual",!1),c(this,"_newPromiseGroups",[]),c(this,"_promiseGroupIds",0),c(this,"_lodchangedlisteners",[]),J(this,K),J(this,Ce,new dt),J(this,Y,0),J(this,le,0),J(this,xe,0),J(this,Q,0),c(this,"_fpsBuffer",[60,60,60,60,60]),c(this,"_sphere",new Ge),c(this,"_tempBox",new be),c(this,"_tempBox2",new be),c(this,"tempMatrix",new je),c(this,"_tempWorldPosition",new G),c(this,"_tempBoxSize",new G),c(this,"_tempBox2Size",new G),this.renderer=r,this.context={...e}}static getObjectLODState(r){return r[Ee]}static addPlugin(r){X.push(r)}static removePlugin(r){const e=X.indexOf(r);e>=0&&X.splice(e,1)}static get(r,e){if(r[Ie])return console.debug("[gltf-progressive] LODsManager already exists for this renderer"),r[Ie];const t=new _(r,{engine:"unknown",...e});return r[Ie]=t,t}get plugins(){return X}awaitLoading(r){const e=this._promiseGroupIds++,t=new ve(b(this,Y),{...r});this._newPromiseGroups.push(t);const n=performance.now();return t.ready.finally(()=>{const s=this._newPromiseGroups.indexOf(t);s>=0&&(this._newPromiseGroups.splice(s,1),Xe()&&performance.measure("LODsManager:awaitLoading",{start:n,detail:{id:e,name:r?.name,awaited:t.awaitedCount,resolved:t.resolvedCount}}))}),t.ready}_postprocessPromiseGroups(){if(this._newPromiseGroups.length!==0)for(let r=this._newPromiseGroups.length-1;r>=0;r--)this._newPromiseGroups[r].update(b(this,Y))}addEventListener(r,e){r==="changed"&&this._lodchangedlisteners.push(e)}removeEventListener(r,e){if(r==="changed"){const t=this._lodchangedlisteners.indexOf(e);t>=0&&this._lodchangedlisteners.splice(t,1)}}enable(){if(b(this,K))return;console.debug("[gltf-progressive] Enabling LODsManager for renderer");let r=0;U(this,K,this.renderer.render);const e=this;ge(this.renderer),this.renderer.render=function(t,n){const s=e.renderer.getRenderTarget();(s==null||"isXRRenderTarget"in s&&s.isXRRenderTarget)&&(r=0,U(e,Y,b(e,Y)+1),U(e,le,b(e,Ce).getDelta()),U(e,xe,b(e,xe)+b(e,le)),e._fpsBuffer.shift(),e._fpsBuffer.push(1/b(e,le)),U(e,Q,e._fpsBuffer.reduce((o,a)=>o+a)/e._fpsBuffer.length),W&&b(e,Y)%200===0&&console.log("FPS",Math.round(b(e,Q)),"Interval:",b(e,C)));const i=r++;b(e,K).call(this,t,n),e.onAfterRender(t,n,i)}}disable(){b(this,K)&&(console.debug("[gltf-progressive] Disabling LODsManager for renderer"),this.renderer.render=b(this,K),U(this,K,void 0))}update(r,e){this.internalUpdate(r,e)}onAfterRender(r,e,t){if(this.pause)return;const n=this.renderer.renderLists.get(r,0).opaque;let s=!0;if(n.length===1){const i=n[0].material;(i.name==="EffectMaterial"||i.name==="CopyShader")&&(s=!1)}if((e.parent&&e.parent.type==="CubeCamera"||t>=1&&e.type==="OrthographicCamera")&&(s=!1),s){if(It||(this.updateInterval==="auto"?b(this,Q)<40&&b(this,C)<10?(U(this,C,b(this,C)+1),W&&console.warn("\u2193 Reducing LOD updates",b(this,C),b(this,Q).toFixed(0))):b(this,Q)>=60&&b(this,C)>1&&(U(this,C,b(this,C)-1),W&&console.warn("\u2191 Increasing LOD updates",b(this,C),b(this,Q).toFixed(0))):U(this,C,this.updateInterval),b(this,C)>0&&b(this,Y)%b(this,C)!=0))return;this.internalUpdate(r,e),this._postprocessPromiseGroups()}}internalUpdate(r,e){var t,n;const s=this.renderer.renderLists.get(r,0),i=s.opaque;this.projectionScreenMatrix.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse);const o=this.targetTriangleDensity;for(const d of i){if(d.material&&(((t=d.geometry)==null?void 0:t.type)==="BoxGeometry"||((n=d.geometry)==null?void 0:n.type)==="BufferGeometry")&&(d.material.name==="SphericalGaussianBlur"||d.material.name=="BackgroundCubeMaterial"||d.material.name==="CubemapFromEquirect"||d.material.name==="EquirectangularToCubeUV")){W&&(d.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]||(d.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]=!0,console.warn("Ignoring skybox or BLIT object",d,d.material.name,d.material.type)));continue}switch(d.material.type){case"LineBasicMaterial":case"LineDashedMaterial":case"PointsMaterial":case"ShadowMaterial":case"MeshDistanceMaterial":case"MeshDepthMaterial":continue}if(W==="color"&&d.material&&!d.object.progressive_debug_color){d.object.progressive_debug_color=!0;const v=Math.random()*16777215,x=new ct({color:v});d.object.material=x}const h=d.object;(h instanceof Z||h.isMesh)&&this.updateLODs(r,e,h,o)}const a=s.transparent;for(const d of a){const h=d.object;(h instanceof Z||h.isMesh)&&this.updateLODs(r,e,h,o)}const u=s.transmissive;for(const d of u){const h=d.object;(h instanceof Z||h.isMesh)&&this.updateLODs(r,e,h,o)}}updateLODs(r,e,t,n){var s,i;t.userData||(t.userData={});let o=t[Ee];if(o||(o=new Et,t[Ee]=o),o.frames++<2)return;for(const u of X)(s=u.onBeforeUpdateLOD)==null||s.call(u,this.renderer,r,e,t);const a=_.overrideGlobalLodLevel!==void 0?_.overrideGlobalLodLevel:se;a>=0?(E.mesh_lod=a,E.texture_lod=a):(this.calculateLodLevel(e,t,o,n,E),E.mesh_lod=Math.round(E.mesh_lod),E.texture_lod=Math.round(E.texture_lod)),E.mesh_lod>=0&&this.loadProgressiveMeshes(t,E.mesh_lod),t.material&&E.texture_lod>=0&&this.loadProgressiveTextures(t.material,E.texture_lod,a),w&&t.material&&!t.isGizmo&&He(t.material);for(const u of X)(i=u.onAfterUpdatedLOD)==null||i.call(u,this.renderer,r,e,t,E);o.lastLodLevel_Mesh=E.mesh_lod,o.lastLodLevel_Texture=E.texture_lod}loadProgressiveTextures(r,e,t){if(!r)return;if(Array.isArray(r)){for(const s of r)this.loadProgressiveTextures(s,e);return}let n=!1;if((r[H]===void 0||e<r[H])&&(n=!0),t!==void 0&&t>=0&&(n=r[H]!=t,e=t),n){r[H]=e;const s=q.assignTextureLOD(r,e).then(i=>{this._lodchangedlisteners.forEach(o=>o({type:"texture",level:e,object:r}))});ve.addPromise("texture",r,s,this._newPromiseGroups)}}loadProgressiveMeshes(r,e){if(!r)return Promise.resolve(null);let t=r[H]!==e;const n=r["DEBUG:LOD"];if(n!=null&&(t=r[H]!=n,e=n),t){r[H]=e;const s=r.geometry,i=q.assignMeshLOD(r,e).then(o=>(o&&r[H]==e&&s!=r.geometry&&this._lodchangedlisteners.forEach(a=>a({type:"mesh",level:e,object:r})),o));return ve.addPromise("mesh",r,i,this._newPromiseGroups),i}return Promise.resolve(null)}static isInside(r,e){const t=r.min,n=r.max,s=(t.x+n.x)*.5,i=(t.y+n.y)*.5;return this._tempPtInside.set(s,i,t.z).applyMatrix4(e).z<0}calculateLodLevel(r,e,t,n,s){var i,o,a,u;if(!e){s.mesh_lod=-1,s.texture_lod=-1;return}if(!r){s.mesh_lod=-1,s.texture_lod=-1;return}let d=10+1,h=!1;if(W&&e["DEBUG:LOD"]!=null)return e["DEBUG:LOD"];const v=(i=q.getMeshLODExtension(e.geometry))==null?void 0:i.lods,x=q.getPrimitiveIndex(e.geometry),y=v&&v.length>0,O=q.getMaterialMinMaxLODsCount(e.material),I=O.min_count!==1/0&&O.min_count>=0&&O.max_count>=0;if(!y&&!I){s.mesh_lod=0,s.texture_lod=0;return}y||(h=!0,d=0);const M=this.renderer.domElement.clientHeight||this.renderer.domElement.height;let S=e.geometry.boundingBox;if(e.type==="SkinnedMesh"){const l=e;if(!l.boundingBox)l.computeBoundingBox();else if(this.skinnedMeshAutoUpdateBoundsInterval>0){if(!l[_.$skinnedMeshBoundsOffset]){const L=_.skinnedMeshBoundsFrameOffsetCounter++;l[_.$skinnedMeshBoundsOffset]=L}const f=l[_.$skinnedMeshBoundsOffset];if((t.frames+f)%this.skinnedMeshAutoUpdateBoundsInterval===0){const L=ne(l),P=l.geometry;L&&(l.geometry=L),l.computeBoundingBox(),l.geometry=P}}S=l.boundingBox}if(S){const l=r;if(e.geometry.attributes.color&&e.geometry.attributes.color.count<100&&e.geometry.boundingSphere){this._sphere.copy(e.geometry.boundingSphere),this._sphere.applyMatrix4(e.matrixWorld);const m=r.getWorldPosition(this._tempWorldPosition);if(this._sphere.containsPoint(m)){s.mesh_lod=0,s.texture_lod=0;return}}if(this._tempBox.copy(S),this._tempBox.applyMatrix4(e.matrixWorld),l.isPerspectiveCamera&&_.isInside(this._tempBox,this.projectionScreenMatrix)){s.mesh_lod=0,s.texture_lod=0;return}if(this._tempBox.applyMatrix4(this.projectionScreenMatrix),this.renderer.xr.enabled&&l.isPerspectiveCamera&&l.fov>70){const m=this._tempBox.min,g=this._tempBox.max;let p=m.x,T=m.y,B=g.x,V=g.y;const de=2,Le=1.5,ce=(m.x+g.x)*.5,he=(m.y+g.y)*.5;p=(p-ce)*de+ce,T=(T-he)*de+he,B=(B-ce)*de+ce,V=(V-he)*de+he;const et=p<0&&B>0?0:Math.min(Math.abs(m.x),Math.abs(g.x)),tt=T<0&&V>0?0:Math.min(Math.abs(m.y),Math.abs(g.y)),_e=Math.max(et,tt);t.lastCentrality=(Le-_e)*(Le-_e)*(Le-_e)}else t.lastCentrality=1;const f=this._tempBox.getSize(this._tempBoxSize);f.multiplyScalar(.5),screen.availHeight>0&&M>0&&f.multiplyScalar(M/screen.availHeight),r.isPerspectiveCamera?f.x*=r.aspect:r.isOrthographicCamera;const L=r.matrixWorldInverse,P=this._tempBox2;P.copy(S),P.applyMatrix4(e.matrixWorld),P.applyMatrix4(L);const D=P.getSize(this._tempBox2Size),F=Math.max(D.x,D.y);if(Math.max(f.x,f.y)!=0&&F!=0&&(f.z=D.z/Math.max(D.x,D.y)*Math.max(f.x,f.y)),t.lastScreenCoverage=Math.max(f.x,f.y,f.z),t.lastScreenspaceVolume.copy(f),t.lastScreenCoverage*=t.lastCentrality,W&&_.debugDrawLine){const m=this.tempMatrix.copy(this.projectionScreenMatrix);m.invert();const g=_.corner0,p=_.corner1,T=_.corner2,B=_.corner3;g.copy(this._tempBox.min),p.copy(this._tempBox.max),p.x=g.x,T.copy(this._tempBox.max),T.y=g.y,B.copy(this._tempBox.max);const V=(g.z+B.z)*.5;g.z=p.z=T.z=B.z=V,g.applyMatrix4(m),p.applyMatrix4(m),T.applyMatrix4(m),B.applyMatrix4(m),_.debugDrawLine(g,p,255),_.debugDrawLine(g,T,255),_.debugDrawLine(p,B,255),_.debugDrawLine(T,B,255)}let k=999;if(v&&t.lastScreenCoverage>0)for(let m=0;m<v.length;m++){const g=v[m],p=(((o=g.densities)==null?void 0:o[x])||g.density||1e-5)/t.lastScreenCoverage;if(x>0&&Xe()&&!g.densities&&!globalThis["NEEDLE:MISSING_LOD_PRIMITIVE_DENSITIES"]&&(window["NEEDLE:MISSING_LOD_PRIMITIVE_DENSITIES"]=!0,console.warn("[Needle Progressive] Detected usage of mesh without primitive densities. This might cause incorrect LOD level selection: Consider re-optimizing your model by updating your Needle Integration, Needle glTF Pipeline or running optimization again on Needle Cloud.")),p<n){k=m;break}}k<d&&(d=k,h=!0)}if(h?s.mesh_lod=d:s.mesh_lod=t.lastLodLevel_Mesh,W&&s.mesh_lod!=t.lastLodLevel_Mesh){const l=v?.[s.mesh_lod];l&&console.debug(`Mesh LOD changed: ${t.lastLodLevel_Mesh} \u2192 ${s.mesh_lod} (density: ${(a=l.densities)==null?void 0:a[x].toFixed(0)}) | ${e.name}`)}if(I){const l="saveData"in globalThis.navigator&&globalThis.navigator.saveData===!0;if(t.lastLodLevel_Texture<0){if(s.texture_lod=O.max_count-1,W){const f=O.lods[O.max_count-1];W&&console.log(`First Texture LOD ${s.texture_lod} (${f.max_height}px) - ${e.name}`)}}else{const f=t.lastScreenspaceVolume.x+t.lastScreenspaceVolume.y+t.lastScreenspaceVolume.z;let L=t.lastScreenCoverage*4;((u=this.context)==null?void 0:u.engine)==="model-viewer"&&(L*=1.5);const P=M/window.devicePixelRatio*L;let D=!1;for(let F=O.lods.length-1;F>=0;F--){const k=O.lods[F];if(!(l&&k.max_height>=2048)&&!(Ve()&&k.max_height>4096)&&(k.max_height>P||!D&&F===0)){if(D=!0,s.texture_lod=F,W&&s.texture_lod<t.lastLodLevel_Texture){const m=k.max_height;console.log(`Texture LOD changed: ${t.lastLodLevel_Texture} \u2192 ${s.texture_lod} = ${m}px
|
|
6
|
+
Screensize: ${P.toFixed(0)}px, Coverage: ${(100*t.lastScreenCoverage).toFixed(2)}%, Volume ${f.toFixed(1)}
|
|
7
|
+
${e.name}`)}break}}}}else s.texture_lod=0}},C=new WeakMap,K=new WeakMap,Ce=new WeakMap,Y=new WeakMap,le=new WeakMap,xe=new WeakMap,Q=new WeakMap,c(_,"debugDrawLine"),c(_,"overrideGlobalLodLevel"),c(_,"corner0",new G),c(_,"corner1",new G),c(_,"corner2",new G),c(_,"corner3",new G),c(_,"_tempPtInside",new G),c(_,"skinnedMeshBoundsFrameOffsetCounter",0),c(_,"$skinnedMeshBoundsOffset",Symbol("gltf-progressive-skinnedMeshBoundsOffset")),_);class Et{constructor(){c(this,"frames",0),c(this,"lastLodLevel_Mesh",-1),c(this,"lastLodLevel_Texture",-1),c(this,"lastScreenCoverage",0),c(this,"lastScreenspaceVolume",new G),c(this,"lastCentrality",0)}}const Ke=Symbol("NEEDLE_mesh_lod"),ye=Symbol("NEEDLE_texture_lod");let we=null;function Ye(){const r=Ct();r&&(r.mapURLs(function(e){return Qe(),e}),Qe(),we?.disconnect(),we=new MutationObserver(e=>{e.forEach(t=>{t.addedNodes.forEach(n=>{n instanceof HTMLElement&&n.tagName.toLowerCase()==="model-viewer"&&Ze(n)})})}),we.observe(document,{childList:!0,subtree:!0}))}function Ct(){return typeof customElements>"u"?null:customElements.get("model-viewer")||(customElements.whenDefined("model-viewer").then(()=>{console.debug("[gltf-progressive] model-viewer defined"),Ye()}),null)}function Qe(){typeof document>"u"||document.querySelectorAll("model-viewer").forEach(r=>{Ze(r)})}const Je=new WeakSet;let Bt=0;function Ze(r){if(!r||Je.has(r))return null;Je.add(r),console.debug("[gltf-progressive] found new model-viewer..."+ ++Bt+`
|
|
8
|
+
`,r.getAttribute("src"));let e=null,t=null,n=null;for(let s=r;s!=null;s=Object.getPrototypeOf(s)){const i=Object.getOwnPropertySymbols(s),o=i.find(d=>d.toString()=="Symbol(renderer)"),a=i.find(d=>d.toString()=="Symbol(scene)"),u=i.find(d=>d.toString()=="Symbol(needsRender)");!e&&o!=null&&(e=r[o].threeRenderer),!t&&a!=null&&(t=r[a]),!n&&u!=null&&(n=r[u])}if(e&&t){let s=function(){if(n){let o=0,a=setInterval(()=>{if(o++>5){clearInterval(a);return}n?.call(r)},300)}};console.debug("[gltf-progressive] setup model-viewer");const i=ue.get(e,{engine:"model-viewer"});return ue.addPlugin(new $t),i.enable(),i.addEventListener("changed",()=>{n?.call(r)}),r.addEventListener("model-visibility",o=>{o.detail.visible&&n?.call(r)}),r.addEventListener("load",()=>{s()}),()=>{i.disable()}}return null}class $t{constructor(){c(this,"_didWarnAboutMissingUrl",!1)}onBeforeUpdateLOD(e,t,n,s){this.tryParseMeshLOD(t,s),this.tryParseTextureLOD(t,s)}getUrl(e){if(!e)return null;let t=e.getAttribute("src");return t||(t=e.src),t||(this._didWarnAboutMissingUrl||console.warn("No url found in modelviewer",e),this._didWarnAboutMissingUrl=!0),t}tryGetCurrentGLTF(e){return e._currentGLTF}tryGetCurrentModelViewer(e){return e.element}tryParseTextureLOD(e,t){if(t[ye]==!0)return;t[ye]=!0;const n=this.tryGetCurrentGLTF(e),s=this.tryGetCurrentModelViewer(e),i=this.getUrl(s);if(i&&n&&t.material){let o=function(u){var d,h,v;if(u[ye]==!0)return;u[ye]=!0,u.userData&&(u.userData.LOD=-1);const x=Object.keys(u);for(let y=0;y<x.length;y++){const O=x[y],I=u[O];if(I?.isTexture===!0){const M=(h=(d=I.userData)==null?void 0:d.associations)==null?void 0:h.textures;if(M==null)continue;const S=n.parser.json.textures[M];if(!S){console.warn("Texture data not found for texture index "+M);continue}if((v=S?.extensions)!=null&&v[z]){const l=S.extensions[z];l&&i&&q.registerTexture(i,I,l.lods.length,M,l)}}}};const a=t.material;if(Array.isArray(a))for(const u of a)o(u);else o(a)}}tryParseMeshLOD(e,t){var n,s;if(t[Ke]==!0)return;t[Ke]=!0;const i=this.tryGetCurrentModelViewer(e),o=this.getUrl(i);if(!o)return;const a=(s=(n=t.userData)==null?void 0:n.gltfExtensions)==null?void 0:s[z];if(a&&o){const u=t.uuid;q.registerMesh(o,u,t,0,a.lods.length,a)}}}function Rt(r,e,t,n){ge(e),De(t),Pe(t,{progressive:!0,...n?.hints}),t.register(i=>new q(i,r));const s=ue.get(e);return n?.enableLODsManager!==!1&&s.enable(),s}if(Ye(),!Lt){const r={gltfProgressive:{useNeedleProgressive:Rt,LODsManager:ue,configureLoader:Pe,getRaycastMesh:ne,useRaycastMeshes:bt}};if(!globalThis.Needle)globalThis.Needle=r;else for(const e in r)globalThis.Needle[e]=r[e]}export{ue as LODsManager,q as NEEDLE_progressive,De as addDracoAndKTX2Loaders,Pe as configureLoader,ge as createLoaders,ne as getRaycastMesh,Fe as setDracoDecoderLocation,Ue as setKTX2TranscoderLocation};
|