@needle-tools/engine 4.7.2-next.35f7370 → 4.7.2-next.37cf642

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.
@@ -1,8 +0,0 @@
1
- var Ke=Object.defineProperty,Ee=r=>{throw TypeError(r)},He=(r,e,t)=>e in r?Ke(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,c=(r,e,t)=>He(r,typeof e!="symbol"?e+"":e,t),Ce=(r,e,t)=>e.has(r)||Ee("Cannot "+t),v=(r,e,t)=>(Ce(r,e,"read from private field"),t?t.call(r):e.get(r)),J=(r,e,t)=>e.has(r)?Ee("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),F=(r,e,t,o)=>(Ce(r,e,"write to private field"),o?o.call(r,t):e.set(r,t),t);import{BufferGeometry as de,Mesh as Q,Texture as re,TextureLoader as Ye,Matrix4 as Ie,Clock as Je,MeshStandardMaterial as Qe,Sphere as Ze,Box3 as Be,Vector3 as W}from"./three-DuDKwKB8.min.js";import{DRACOLoader as et,KTX2Loader as tt,MeshoptDecoder as rt,GLTFLoader as Le}from"./three-examples-DaDLBuy6.min.js";const st="";globalThis.GLTF_PROGRESSIVE_VERSION=st,console.debug("[gltf-progressive] version -");let $="https://www.gstatic.com/draco/versioned/decoders/1.5.7/",ee="https://www.gstatic.com/basis-universal/versioned/2021-04-15-ba1c3e4/";const ot=$,nt=ee,Ge=new URL($+"draco_decoder.js");Ge.searchParams.append("range","true"),fetch(Ge,{method:"GET",headers:{Range:"bytes=0-1"}}).catch(r=>{console.debug(`Failed to fetch remote Draco decoder from ${$} (offline: ${typeof navigator<"u"?navigator.onLine:"unknown"})`),$===ot&&ke("./include/draco/"),ee===nt&&Re("./include/ktx2/")}).finally(()=>{je()});function ke(r){$=r,A&&A[we]!=$?(console.debug("Updating Draco decoder path to "+r),A[we]=$,A.setDecoderPath($),A.preload()):console.debug("Setting Draco decoder path to "+r)}function Re(r){ee=r,B&&B.transcoderPath!=ee?(console.debug("Updating KTX2 transcoder path to "+r),B.setTranscoderPath(ee),B.init()):console.debug("Setting KTX2 transcoder path to "+r)}const we=Symbol("dracoDecoderPath");let A,ce,B;function je(){A||(A=new et,A[we]=$,A.setDecoderPath($),A.setDecoderConfig({type:"js"}),A.preload()),B||(B=new tt,B.setTranscoderPath(ee),B.init()),ce||(ce=rt)}function _e(r){return je(),r?B.detectSupport(r):r!==null&&console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures might fail"),{dracoLoader:A,ktx2Loader:B,meshoptDecoder:ce}}function De(r){r.dracoLoader||r.setDRACOLoader(A),r.ktx2Loader||r.setKTX2Loader(B),r.meshoptDecoder||r.setMeshoptDecoder(ce)}const Me=new WeakMap;function be(r,e){let t=Me.get(r);t?t=Object.assign(t,e):t=e,Me.set(r,t)}const Ne=Le.prototype.load;function it(...r){const e=Me.get(this);let t=r[0];const o=new URL(t,window.location.href);if(o.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=o.toString()}return r[0]=t,Ne?.call(this,...r)}Le.prototype.load=it,se("debugprogressive");function se(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 at(r,e){if(e===void 0||e.startsWith("./")||e.startsWith("http")||r===void 0)return e;const t=r.lastIndexOf("/");if(t>=0){const o=r.substring(0,t+1);for(;o.endsWith("/")&&e.startsWith("/");)e=e.substring(1);return o+e}return e}let he;function lt(){return he!==void 0||(he=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent),se("debugprogressive")&&console.log("[glTF Progressive]: isMobileDevice",he)),he}function ut(){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}const dt=typeof window>"u"&&typeof document>"u",Oe=Symbol("needle:raycast-mesh");function te(r){return r?.[Oe]instanceof de?r[Oe]:null}function ct(r,e){if((r.type==="Mesh"||r.type==="SkinnedMesh")&&!te(r)){const t=gt(e);t.userData={isRaycastMesh:!0},r[Oe]=t}}function ht(r=!0){if(r){if(oe)return;const e=oe=Q.prototype.raycast;Q.prototype.raycast=function(t,o){const s=this,i=te(s);let n;i&&s.isMesh&&(n=s.geometry,s.geometry=i),e.call(this,t,o),n&&(s.geometry=n)}}else{if(!oe)return;Q.prototype.raycast=oe,oe=null}}let oe=null;function gt(r){const e=new de;for(const t in r.attributes)e.setAttribute(t,r.getAttribute(t));return e.setIndex(r.getIndex()),e}const X=new Array,L=se("debugprogressive");let ge,Z=-1;if(L){let r=function(){Z+=1,Z>=e&&(Z=-1),console.log(`Toggle LOD level [${Z}]`)},e=6;window.addEventListener("keyup",t=>{t.key==="p"&&r(),t.key==="w"&&(ge=!ge,console.log(`Toggle wireframe [${ge}]`));const o=parseInt(t.key);!isNaN(o)&&o>=0&&(Z=o,console.log(`Set LOD level to [${Z}]`))})}function $e(r){if(L)if(Array.isArray(r))for(const e of r)$e(e);else r&&"wireframe"in r&&(r.wireframe=ge===!0)}const U="NEEDLE_progressive",Se=Symbol("needle-progressive-texture"),E=class k{constructor(e,t){c(this,"parser"),c(this,"url"),c(this,"_isLoadingMesh"),c(this,"loadMesh",o=>{var s,i;if(this._isLoadingMesh)return null;const n=(i=(s=this.parser.json.meshes[o])==null?void 0:s.extensions)==null?void 0:i[U];return n?(this._isLoadingMesh=!0,this.parser.getDependency("mesh",o).then(a=>{var l;return this._isLoadingMesh=!1,a&&k.registerMesh(this.url,n.guid,a,(l=n.lods)==null?void 0:l.length,0,n),a})):null}),L&&console.log("Progressive extension registered for",t),this.parser=e,this.url=t}get name(){return U}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 o=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(L==="verbose"&&console.log("getMaterialMinMaxLODsCount",e),e.type==="ShaderMaterial"||e.type==="RawShaderMaterial"){const a=e;for(const l of Object.keys(a.uniforms)){const u=a.uniforms[l].value;u?.isTexture===!0&&n(u,t)}}else if(e.isMaterial)for(const a of Object.keys(e)){const l=e[a];l?.isTexture===!0&&n(l,t)}return e[s]=t,t;function n(a,l){const u=o.getAssignedLODInformation(a);if(u){const d=o.lodInfos.get(u.key);if(d&&d.lods){l.min_count=Math.min(l.min_count,d.lods.length),l.max_count=Math.max(l.max_count,d.lods.length);for(let w=0;w<d.lods.length;w++){const y=d.lods[w];y.width&&(l.lods[w]=l.lods[w]||{min_height:1/0,max_height:0},l.lods[w].min_height=Math.min(l.lods[w].min_height,y.height),l.lods[w].max_height=Math.max(l.lods[w].max_height,y.height))}}}}}static hasLODLevelAvailable(e,t){var o;if(Array.isArray(e)){for(const n of e)if(this.hasLODLevelAvailable(n,t))return!0;return!1}if(e.isMaterial===!0){for(const n of Object.keys(e)){const a=e[n];if(a&&a.isTexture&&this.hasLODLevelAvailable(a,t))return!0}return!1}else if(e.isGroup===!0){for(const n of e.children)if(n.isMesh===!0&&this.hasLODLevelAvailable(n,t))return!0}let s,i;if(e.isMesh?s=e.geometry:(e.isBufferGeometry||e.isTexture)&&(s=e),s&&(o=s?.userData)!=null&&o.LODS){const n=s.userData.LODS;if(i=this.lodInfos.get(n.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 o;if(!e)return Promise.resolve(null);if(e instanceof Q||e.isMesh===!0){const s=e.geometry,i=this.getAssignedLODInformation(s);if(!i)return Promise.resolve(null);for(const n of X)(o=n.onBeforeGetLODMesh)==null||o.call(n,e,t);return e["LOD:requested level"]=t,k.getOrLoadLOD(s,t).then(n=>{if(Array.isArray(n)){const a=i.index||0;n=n[a]}return e["LOD:requested level"]===t&&(delete e["LOD:requested level"],n&&s!=n&&(n?.isBufferGeometry?e.geometry=n:L&&console.error("Invalid LOD geometry",n))),n}).catch(n=>(console.error("Error loading mesh LOD",e,n),null))}else L&&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 o=e;if(Array.isArray(o.material)){const s=new Array;for(const i of o.material){const n=this.assignTextureLOD(i,t);s.push(n)}return Promise.all(s).then(i=>{const n=new Array;for(const a of i)Array.isArray(a)&&n.push(...a);return n})}else return this.assignTextureLOD(o.material,t)}if(e.isMaterial===!0){const o=e,s=[],i=new Array;if(o.uniforms&&(o.isRawShaderMaterial||o.isShaderMaterial===!0)){const n=o;for(const a of Object.keys(n.uniforms)){const l=n.uniforms[a].value;if(l?.isTexture===!0){const u=this.assignTextureLODForSlot(l,t,o,a).then(d=>(d&&n.uniforms[a].value!=d&&(n.uniforms[a].value=d,n.uniformsNeedUpdate=!0),d));s.push(u),i.push(a)}}}else for(const n of Object.keys(o)){const a=o[n];if(a?.isTexture===!0){const l=this.assignTextureLODForSlot(a,t,o,n);s.push(l),i.push(n)}}return Promise.all(s).then(n=>{const a=new Array;for(let l=0;l<n.length;l++){const u=n[l],d=i[l];u&&u.isTexture===!0?a.push({material:o,slot:d,texture:u,level:t}):a.push({material:o,slot:d,texture:null,level:t})}return a})}if(e instanceof re||e.isTexture===!0){const o=e;return this.assignTextureLODForSlot(o,t,null,null)}return Promise.resolve(null)}static assignTextureLODForSlot(e,t,o,s){return e?.isTexture!==!0?Promise.resolve(null):s==="glyphMap"?Promise.resolve(e):k.getOrLoadLOD(e,t).then(i=>{if(Array.isArray(i))return null;if(i?.isTexture===!0){if(i!=e&&o&&s){const n=o[s];if(n&&!L){const a=this.getAssignedLODInformation(n);if(a&&a?.level<t)return L==="verbose"&&console.warn("Assigned texture level is already higher: ",a.level,t,o,n,i),null}o[s]=i}return i}else L=="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,o;return L&&console.log("AFTER",this.url,e),(t=this.parser.json.textures)==null||t.forEach((s,i)=>{var n;if(s!=null&&s.extensions){const a=s?.extensions[U];if(a){if(!a.lods){L&&console.warn("Texture has no LODs",a);return}let l=!1;for(const u of this.parser.associations.keys())if(u.isTexture===!0){const d=this.parser.associations.get(u);d?.textures===i&&(l=!0,k.registerTexture(this.url,u,(n=a.lods)==null?void 0:n.length,i,a))}l||this.parser.getDependency("texture",i).then(u=>{var d;u&&k.registerTexture(this.url,u,(d=a.lods)==null?void 0:d.length,i,a)})}}}),(o=this.parser.json.meshes)==null||o.forEach((s,i)=>{if(s!=null&&s.extensions){const n=s?.extensions[U];if(n&&n.lods){for(const a of this.parser.associations.keys())if(a.isMesh){const l=this.parser.associations.get(a);l?.meshes===i&&k.registerMesh(this.url,n.guid,a,n.lods.length,l.primitives,n)}}}}),null}static async getOrLoadLOD(e,t){var o,s,i,n;const a=L=="verbose",l=e.userData.LODS;if(!l)return null;const u=l?.key;let d;if(e.isTexture===!0){const w=e;w.source&&w.source[Se]&&(d=w.source[Se])}if(d||(d=k.lodInfos.get(u)),d){if(t>0){let m=!1;const R=Array.isArray(d.lods);if(R&&t>=d.lods.length?m=!0:R||(m=!0),m)return this.lowresCache.get(u)}const w=Array.isArray(d.lods)?(o=d.lods[t])==null?void 0:o.path:d.lods;if(!w)return L&&!d["missing:uri"]&&(d["missing:uri"]=!0,console.warn("Missing uri for progressive asset for LOD "+t,d)),null;const y=at(l.url,w);if(y.endsWith(".glb")||y.endsWith(".gltf")){if(!d.guid)return console.warn("missing pointer for glb/gltf texture",d),null;const m=y+"_"+d.guid,R=this.previouslyLoaded.get(m);if(R!==void 0){a&&console.log(`LOD ${t} was already loading/loaded: ${m}`);let g=await R.catch(I=>(console.error(`Error loading LOD ${t} from ${y}
2
- `,I),null)),p=!1;if(g==null||(g instanceof re&&e instanceof re?(s=g.image)!=null&&s.data||(i=g.source)!=null&&i.data?g=this.copySettings(e,g):(p=!0,this.previouslyLoaded.delete(m)):g instanceof de&&e instanceof de&&((n=g.attributes.position)!=null&&n.array||(p=!0,this.previouslyLoaded.delete(m)))),!p)return g}const D=d,C=new Promise(async(g,p)=>{const I=new Le;De(I),L&&(await new Promise(f=>setTimeout(f,1e3)),a&&console.warn("Start loading (delayed) "+y,D.guid));let j=y;if(D&&Array.isArray(D.lods)){const f=D.lods[t];f.hash&&(j+="?v="+f.hash)}const M=await I.loadAsync(j).catch(f=>(console.error(`Error loading LOD ${t} from ${y}
3
- `,f),null));if(!M)return null;const N=M.parser;a&&console.log("Loading finished "+y,D.guid);let b=0;if(M.parser.json.textures){let f=!1;for(const h of M.parser.json.textures){if(h!=null&&h.extensions){const x=h?.extensions[U];if(x!=null&&x.guid&&x.guid===D.guid){f=!0;break}}b++}if(f){let h=await N.getDependency("texture",b);return h&&k.assignLODInformation(l.url,h,u,t,void 0),a&&console.log('change "'+e.name+'" \u2192 "'+h.name+'"',y,b,h,m),e instanceof re&&(h=this.copySettings(e,h)),h&&(h.guid=D.guid),g(h)}else L&&console.warn("Could not find texture with guid",D.guid,M.parser.json)}if(b=0,M.parser.json.meshes){let f=!1;for(const h of M.parser.json.meshes){if(h!=null&&h.extensions){const x=h?.extensions[U];if(x!=null&&x.guid&&x.guid===D.guid){f=!0;break}}b++}if(f){const h=await N.getDependency("mesh",b);if(a&&console.log(`Loaded Mesh "${h.name}"`,y,b,h,m),h.isMesh===!0){const x=h.geometry;return k.assignLODInformation(l.url,x,u,t,0),g(x)}else{const x=new Array;for(let O=0;O<h.children.length;O++){const P=h.children[O];if(P.isMesh===!0){const V=P.geometry;k.assignLODInformation(l.url,V,u,t,O),x.push(V)}}return g(x)}}else L&&console.warn("Could not find mesh with guid",D.guid,M.parser.json)}return g(null)});return this.previouslyLoaded.set(m,C),await C}else if(e instanceof re){a&&console.log("Load texture from uri: "+y);const m=await new Ye().loadAsync(y);return m?(m.guid=d.guid,m.flipY=!1,m.needsUpdate=!0,m.colorSpace=e.colorSpace,a&&console.log(d,m)):L&&console.warn("failed loading",y),m}}else L&&console.warn(`Can not load LOD ${t}: no LOD info found for "${u}" ${e.name}`,e.type);return null}static assignLODInformation(e,t,o,s,i){if(!t)return;t.userData||(t.userData={});const n=new ft(e,o,s,i);t.userData.LODS=n}static getAssignedLODInformation(e){var t;return((t=e?.userData)==null?void 0:t.LODS)||null}static copySettings(e,t){return t?(L&&console.warn(`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(E,"registerTexture",(r,e,t,o,s)=>{if(L&&console.log("> Progressive: register texture",o,e.name,e.uuid,e,s),!e){L&&console.error("gltf-progressive: Register texture without texture");return}e.source&&(e.source[Se]=s);const i=s.guid;E.assignLODInformation(r,e,i,t,o),E.lodInfos.set(i,s),E.lowresCache.set(i,e)}),c(E,"registerMesh",(r,e,t,o,s,i)=>{var n;const a=t.geometry;if(!a){L&&console.warn("gltf-progressive: Register mesh without geometry");return}a.userData||(a.userData={}),L&&console.log("> Progressive: register mesh "+t.name,{index:s,uuid:t.uuid},i,t),E.assignLODInformation(r,a,e,o,s),E.lodInfos.set(e,i);let l=E.lowresCache.get(e);l?l.push(t.geometry):l=[t.geometry],E.lowresCache.set(e,l),o>0&&!te(t)&&ct(t,a);for(const u of X)(n=u.onRegisteredNewMesh)==null||n.call(u,t,i)}),c(E,"lodInfos",new Map),c(E,"previouslyLoaded",new Map),c(E,"lowresCache",new Map);let z=E;class ft{constructor(e,t,o,s){c(this,"url"),c(this,"key"),c(this,"level"),c(this,"index"),this.url=e,this.key=t,this.level=o,s!=null&&(this.index=s)}}class fe{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,"_currentFrame",0);var o;const s=e===0?2:1,i=Math.max(t.frames??s,s);this.frame_start=e,this.frame_capture_end=e+i,this.ready=new Promise(n=>{this._resolve=n}),this.ready.finally(()=>{this._resolved=!0,this._awaiting.length=0}),this._signal=t.signal,(o=this._signal)==null||o.addEventListener("abort",()=>{this.resolveNow()})}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){if(this._resolved){console.warn("PromiseGroup: Trying to add a promise to a resolved group, ignoring.");return}this._currentFrame>this.frame_capture_end||(this._awaiting.push(t),this._addedCount++,t.finally(()=>{this._resolvedCount++,this._awaiting.splice(this._awaiting.indexOf(t),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(fe,"addPromise",(r,e,t)=>{t.forEach(o=>{o.add(r,e)})});const G=se("debugprogressive"),mt=se("noprogressive"),Te=Symbol("Needle:LODSManager"),Pe=Symbol("Needle:LODState"),q=Symbol("Needle:CurrentLOD"),S={mesh_lod:-1,texture_lod:-1};var _,T,K,Ae,H,ne,me,Y;let ie=(_=class{constructor(r,e){c(this,"renderer"),c(this,"context"),c(this,"projectionScreenMatrix",new Ie),c(this,"targetTriangleDensity",2e5),c(this,"skinnedMeshAutoUpdateBoundsInterval",30),c(this,"updateInterval","auto"),J(this,T,1),c(this,"pause",!1),c(this,"manual",!1),c(this,"_newPromiseGroups",[]),c(this,"_promiseGroupIds",0),c(this,"_lodchangedlisteners",[]),J(this,K),J(this,Ae,new Je),J(this,H,0),J(this,ne,0),J(this,me,0),J(this,Y,0),c(this,"_fpsBuffer",[60,60,60,60,60]),c(this,"_sphere",new Ze),c(this,"_tempBox",new Be),c(this,"_tempBox2",new Be),c(this,"tempMatrix",new Ie),c(this,"_tempWorldPosition",new W),c(this,"_tempBoxSize",new W),c(this,"_tempBox2Size",new W),this.renderer=r,this.context={...e}}static getObjectLODState(r){return r[Pe]}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[Te])return console.debug("[gltf-progressive] LODsManager already exists for this renderer"),r[Te];const t=new _(r,{engine:"unknown",...e});return r[Te]=t,t}get plugins(){return X}awaitLoading(r){const e=this._promiseGroupIds++,t=new fe(v(this,H),{...r});this._newPromiseGroups.push(t);const o=performance.now();return t.ready.finally(()=>{const s=this._newPromiseGroups.indexOf(t);s>=0&&(this._newPromiseGroups.splice(s,1),ut()&&performance.measure("LODsManager:awaitLoading",{start:o,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(v(this,H))}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(v(this,K))return;console.debug("[gltf-progressive] Enabling LODsManager for renderer");let r=0;F(this,K,this.renderer.render);const e=this;_e(this.renderer),this.renderer.render=function(t,o){const s=e.renderer.getRenderTarget();(s==null||"isXRRenderTarget"in s&&s.isXRRenderTarget)&&(r=0,F(e,H,v(e,H)+1),F(e,ne,v(e,Ae).getDelta()),F(e,me,v(e,me)+v(e,ne)),e._fpsBuffer.shift(),e._fpsBuffer.push(1/v(e,ne)),F(e,Y,e._fpsBuffer.reduce((n,a)=>n+a)/e._fpsBuffer.length),G&&v(e,H)%200===0&&console.log("FPS",Math.round(v(e,Y)),"Interval:",v(e,T)));const i=r++;v(e,K).call(this,t,o),e.onAfterRender(t,o,i)}}disable(){v(this,K)&&(console.debug("[gltf-progressive] Disabling LODsManager for renderer"),this.renderer.render=v(this,K),F(this,K,void 0))}update(r,e){this.internalUpdate(r,e)}onAfterRender(r,e,t){if(this.pause)return;const o=this.renderer.renderLists.get(r,0).opaque;let s=!0;if(o.length===1){const i=o[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(mt||(this.updateInterval==="auto"?v(this,Y)<40&&v(this,T)<10?(F(this,T,v(this,T)+1),G&&console.warn("\u2193 Reducing LOD updates",v(this,T),v(this,Y).toFixed(0))):v(this,Y)>=60&&v(this,T)>1&&(F(this,T,v(this,T)-1),G&&console.warn("\u2191 Increasing LOD updates",v(this,T),v(this,Y).toFixed(0))):F(this,T,this.updateInterval),v(this,T)>0&&v(this,H)%v(this,T)!=0))return;this.internalUpdate(r,e),this._postprocessPromiseGroups()}}internalUpdate(r,e){var t,o;const s=this.renderer.renderLists.get(r,0),i=s.opaque;this.projectionScreenMatrix.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse);const n=this.targetTriangleDensity;for(const u of i){if(u.material&&(((t=u.geometry)==null?void 0:t.type)==="BoxGeometry"||((o=u.geometry)==null?void 0:o.type)==="BufferGeometry")&&(u.material.name==="SphericalGaussianBlur"||u.material.name=="BackgroundCubeMaterial"||u.material.name==="CubemapFromEquirect"||u.material.name==="EquirectangularToCubeUV")){G&&(u.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]||(u.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]=!0,console.warn("Ignoring skybox or BLIT object",u,u.material.name,u.material.type)));continue}switch(u.material.type){case"LineBasicMaterial":case"LineDashedMaterial":case"PointsMaterial":case"ShadowMaterial":case"MeshDistanceMaterial":case"MeshDepthMaterial":continue}if(G==="color"&&u.material&&!u.object.progressive_debug_color){u.object.progressive_debug_color=!0;const w=Math.random()*16777215,y=new Qe({color:w});u.object.material=y}const d=u.object;(d instanceof Q||d.isMesh)&&this.updateLODs(r,e,d,n)}const a=s.transparent;for(const u of a){const d=u.object;(d instanceof Q||d.isMesh)&&this.updateLODs(r,e,d,n)}const l=s.transmissive;for(const u of l){const d=u.object;(d instanceof Q||d.isMesh)&&this.updateLODs(r,e,d,n)}}updateLODs(r,e,t,o){var s,i;t.userData||(t.userData={});let n=t[Pe];if(n||(n=new pt,t[Pe]=n),n.frames++<2)return;for(const l of X)(s=l.onBeforeUpdateLOD)==null||s.call(l,this.renderer,r,e,t);const a=_.overrideGlobalLodLevel!==void 0?_.overrideGlobalLodLevel:Z;a>=0?(S.mesh_lod=a,S.texture_lod=a):(this.calculateLodLevel(e,t,n,o,S),S.mesh_lod=Math.round(S.mesh_lod),S.texture_lod=Math.round(S.texture_lod)),S.mesh_lod>=0&&this.loadProgressiveMeshes(t,S.mesh_lod),t.material&&S.texture_lod>=0&&this.loadProgressiveTextures(t.material,S.texture_lod),L&&t.material&&!t.isGizmo&&$e(t.material);for(const l of X)(i=l.onAfterUpdatedLOD)==null||i.call(l,this.renderer,r,e,t,S);n.lastLodLevel_Mesh=S.mesh_lod,n.lastLodLevel_Texture=S.texture_lod}loadProgressiveTextures(r,e){if(!r)return;if(Array.isArray(r)){for(const s of r)this.loadProgressiveTextures(s,e);return}let t=!1;(r[q]===void 0||e<r[q])&&(t=!0);const o=r["DEBUG:LOD"];if(o!=null&&(t=r[q]!=o,e=o),t){r[q]=e;const s=z.assignTextureLOD(r,e).then(i=>{this._lodchangedlisteners.forEach(n=>n({type:"texture",level:e,object:r}))});fe.addPromise("texture",s,this._newPromiseGroups)}}loadProgressiveMeshes(r,e){if(!r)return Promise.resolve(null);let t=r[q]!==e;const o=r["DEBUG:LOD"];if(o!=null&&(t=r[q]!=o,e=o),t){r[q]=e;const s=r.geometry,i=z.assignMeshLOD(r,e).then(n=>(n&&r[q]==e&&s!=r.geometry&&this._lodchangedlisteners.forEach(a=>a({type:"mesh",level:e,object:r})),n));return fe.addPromise("mesh",i,this._newPromiseGroups),i}return Promise.resolve(null)}static isInside(r,e){const t=r.min,o=r.max,s=(t.x+o.x)*.5,i=(t.y+o.y)*.5;return this._tempPtInside.set(s,i,t.z).applyMatrix4(e).z<0}calculateLodLevel(r,e,t,o,s){var i,n,a;if(!e){s.mesh_lod=-1,s.texture_lod=-1;return}if(!r){s.mesh_lod=-1,s.texture_lod=-1;return}let l=10+1,u=!1;if(G&&e["DEBUG:LOD"]!=null)return e["DEBUG:LOD"];const d=(i=z.getMeshLODExtension(e.geometry))==null?void 0:i.lods,w=z.getPrimitiveIndex(e.geometry),y=d&&d.length>0,m=z.getMaterialMinMaxLODsCount(e.material),R=m?.min_count!=1/0&&m.min_count>0&&m.max_count>0;if(!y&&!R){s.mesh_lod=0,s.texture_lod=0;return}y||(u=!0,l=0);const D=this.renderer.domElement.clientHeight||this.renderer.domElement.height;let C=e.geometry.boundingBox;if(e.type==="SkinnedMesh"){const g=e;if(!g.boundingBox)g.computeBoundingBox();else if(this.skinnedMeshAutoUpdateBoundsInterval>0&&t.frames%this.skinnedMeshAutoUpdateBoundsInterval===0){const p=te(g),I=g.geometry;p&&(g.geometry=p),g.computeBoundingBox(),g.geometry=I}C=g.boundingBox}if(C){const g=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 f=r.getWorldPosition(this._tempWorldPosition);if(this._sphere.containsPoint(f)){s.mesh_lod=0,s.texture_lod=0;return}}if(this._tempBox.copy(C),this._tempBox.applyMatrix4(e.matrixWorld),g.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&&g.isPerspectiveCamera&&g.fov>70){const f=this._tempBox.min,h=this._tempBox.max;let x=f.x,O=f.y,P=h.x,V=h.y;const ae=2,ye=1.5,le=(f.x+h.x)*.5,ue=(f.y+h.y)*.5;x=(x-le)*ae+le,O=(O-ue)*ae+ue,P=(P-le)*ae+le,V=(V-ue)*ae+ue;const Xe=x<0&&P>0?0:Math.min(Math.abs(f.x),Math.abs(h.x)),qe=O<0&&V>0?0:Math.min(Math.abs(f.y),Math.abs(h.y)),xe=Math.max(Xe,qe);t.lastCentrality=(ye-xe)*(ye-xe)*(ye-xe)}else t.lastCentrality=1;const p=this._tempBox.getSize(this._tempBoxSize);p.multiplyScalar(.5),screen.availHeight>0&&D>0&&p.multiplyScalar(D/screen.availHeight),r.isPerspectiveCamera?p.x*=r.aspect:r.isOrthographicCamera;const I=r.matrixWorldInverse,j=this._tempBox2;j.copy(C),j.applyMatrix4(e.matrixWorld),j.applyMatrix4(I);const M=j.getSize(this._tempBox2Size),N=Math.max(M.x,M.y);if(Math.max(p.x,p.y)!=0&&N!=0&&(p.z=M.z/Math.max(M.x,M.y)*Math.max(p.x,p.y)),t.lastScreenCoverage=Math.max(p.x,p.y,p.z),t.lastScreenspaceVolume.copy(p),t.lastScreenCoverage*=t.lastCentrality,G&&_.debugDrawLine){const f=this.tempMatrix.copy(this.projectionScreenMatrix);f.invert();const h=_.corner0,x=_.corner1,O=_.corner2,P=_.corner3;h.copy(this._tempBox.min),x.copy(this._tempBox.max),x.x=h.x,O.copy(this._tempBox.max),O.y=h.y,P.copy(this._tempBox.max);const V=(h.z+P.z)*.5;h.z=x.z=O.z=P.z=V,h.applyMatrix4(f),x.applyMatrix4(f),O.applyMatrix4(f),P.applyMatrix4(f),_.debugDrawLine(h,x,255),_.debugDrawLine(h,O,255),_.debugDrawLine(x,P,255),_.debugDrawLine(O,P,255)}let b=999;if(d&&t.lastScreenCoverage>0)for(let f=0;f<d.length;f++){const h=d[f];if((((n=h.densities)==null?void 0:n[w])||h.density||1e-5)/t.lastScreenCoverage<o){b=f;break}}b<l&&(l=b,u=!0)}if(u?s.mesh_lod=l:s.mesh_lod=t.lastLodLevel_Mesh,G&&s.mesh_lod!=t.lastLodLevel_Mesh){const g=d?.[s.mesh_lod];g&&console.log(`Mesh LOD changed: ${t.lastLodLevel_Mesh} \u2192 ${s.mesh_lod} (${g.density.toFixed(0)}) - ${e.name}`)}if(R){const g="saveData"in globalThis.navigator&&globalThis.navigator.saveData===!0;if(t.lastLodLevel_Texture<0){if(s.texture_lod=m.max_count-1,G){const p=m.lods[m.max_count-1];G&&console.log(`First Texture LOD ${s.texture_lod} (${p.max_height}px) - ${e.name}`)}}else{const p=t.lastScreenspaceVolume.x+t.lastScreenspaceVolume.y+t.lastScreenspaceVolume.z;let I=t.lastScreenCoverage*4;((a=this.context)==null?void 0:a.engine)==="model-viewer"&&(I*=1.5);const j=D/window.devicePixelRatio*I;let M=!1;for(let N=m.lods.length-1;N>=0;N--){const b=m.lods[N];if(!(g&&b.max_height>=2048)&&!(lt()&&b.max_height>4096)&&(b.max_height>j||!M&&N===0)){if(M=!0,s.texture_lod=N,s.texture_lod<t.lastLodLevel_Texture){const f=b.max_height;G&&console.log(`Texture LOD changed: ${t.lastLodLevel_Texture} \u2192 ${s.texture_lod} = ${f}px
6
- Screensize: ${j.toFixed(0)}px, Coverage: ${(100*t.lastScreenCoverage).toFixed(2)}%, Volume ${p.toFixed(1)}
7
- ${e.name}`)}break}}}}else s.texture_lod=0}},T=new WeakMap,K=new WeakMap,Ae=new WeakMap,H=new WeakMap,ne=new WeakMap,me=new WeakMap,Y=new WeakMap,c(_,"debugDrawLine"),c(_,"overrideGlobalLodLevel"),c(_,"corner0",new W),c(_,"corner1",new W),c(_,"corner2",new W),c(_,"corner3",new W),c(_,"_tempPtInside",new W),_);class pt{constructor(){c(this,"frames",0),c(this,"lastLodLevel_Mesh",-1),c(this,"lastLodLevel_Texture",-1),c(this,"lastScreenCoverage",0),c(this,"lastScreenspaceVolume",new W),c(this,"lastCentrality",0)}}const Fe=Symbol("NEEDLE_mesh_lod"),pe=Symbol("NEEDLE_texture_lod");let ve=null;function We(){const r=vt();r&&(r.mapURLs(function(e){return Ue(),e}),Ue(),ve?.disconnect(),ve=new MutationObserver(e=>{e.forEach(t=>{t.addedNodes.forEach(o=>{o instanceof HTMLElement&&o.tagName.toLowerCase()==="model-viewer"&&Ve(o)})})}),ve.observe(document,{childList:!0,subtree:!0}))}function vt(){return typeof customElements>"u"?null:customElements.get("model-viewer")||(customElements.whenDefined("model-viewer").then(()=>{console.debug("[gltf-progressive] model-viewer defined"),We()}),null)}function Ue(){typeof document>"u"||document.querySelectorAll("model-viewer").forEach(r=>{Ve(r)})}const ze=new WeakSet;let yt=0;function Ve(r){if(!r||ze.has(r))return null;ze.add(r),console.debug("[gltf-progressive] found new model-viewer..."+ ++yt+`
8
- `,r.getAttribute("src"));let e=null,t=null,o=null;for(let s=r;s!=null;s=Object.getPrototypeOf(s)){const i=Object.getOwnPropertySymbols(s),n=i.find(u=>u.toString()=="Symbol(renderer)"),a=i.find(u=>u.toString()=="Symbol(scene)"),l=i.find(u=>u.toString()=="Symbol(needsRender)");!e&&n!=null&&(e=r[n].threeRenderer),!t&&a!=null&&(t=r[a]),!o&&l!=null&&(o=r[l])}if(e&&t){let s=function(){if(o){let n=0,a=setInterval(()=>{if(n++>5){clearInterval(a);return}o?.call(r)},300)}};console.debug("[gltf-progressive] setup model-viewer");const i=ie.get(e,{engine:"model-viewer"});return ie.addPlugin(new xt),i.enable(),i.addEventListener("changed",()=>{o?.call(r)}),r.addEventListener("model-visibility",n=>{n.detail.visible&&o?.call(r)}),r.addEventListener("load",()=>{s()}),()=>{i.disable()}}return null}class xt{constructor(){c(this,"_didWarnAboutMissingUrl",!1)}onBeforeUpdateLOD(e,t,o,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[pe]==!0)return;t[pe]=!0;const o=this.tryGetCurrentGLTF(e),s=this.tryGetCurrentModelViewer(e),i=this.getUrl(s);if(i&&o&&t.material){let n=function(l){var u,d,w;if(l[pe]==!0)return;l[pe]=!0,l.userData&&(l.userData.LOD=-1);const y=Object.keys(l);for(let m=0;m<y.length;m++){const R=y[m],D=l[R];if(D?.isTexture===!0){const C=(d=(u=D.userData)==null?void 0:u.associations)==null?void 0:d.textures;if(C==null)continue;const g=o.parser.json.textures[C];if(!g){console.warn("Texture data not found for texture index "+C);continue}if((w=g?.extensions)!=null&&w[U]){const p=g.extensions[U];p&&i&&z.registerTexture(i,D,p.lods.length,C,p)}}}};const a=t.material;if(Array.isArray(a))for(const l of a)n(l);else n(a)}}tryParseMeshLOD(e,t){var o,s;if(t[Fe]==!0)return;t[Fe]=!0;const i=this.tryGetCurrentModelViewer(e),n=this.getUrl(i);if(!n)return;const a=(s=(o=t.userData)==null?void 0:o.gltfExtensions)==null?void 0:s[U];if(a&&n){const l=t.uuid;z.registerMesh(n,l,t,0,a.lods.length,a)}}}function Lt(r,e,t,o){_e(e),De(t),be(t,{progressive:!0,...o?.hints}),t.register(i=>new z(i,r));const s=ie.get(e);return o?.enableLODsManager!==!1&&s.enable(),s}if(We(),!dt){const r={gltfProgressive:{useNeedleProgressive:Lt,LODsManager:ie,configureLoader:be,getRaycastMesh:te,useRaycastMeshes:ht}};if(!globalThis.Needle)globalThis.Needle=r;else for(const e in r)globalThis.Needle[e]=r[e]}export{ie as LODsManager,z as NEEDLE_progressive,De as addDracoAndKTX2Loaders,be as configureLoader,_e as createLoaders,te as getRaycastMesh,ke as setDracoDecoderLocation,Re as setKTX2TranscoderLocation};