@needle-tools/gltf-progressive 3.5.0-rc → 3.6.0-alpha.2
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/CHANGELOG.md +14 -1
- package/LICENSE +21 -0
- package/gltf-progressive.js +896 -636
- package/gltf-progressive.min.js +9 -9
- package/gltf-progressive.umd.cjs +9 -9
- package/lib/extension.d.ts +65 -6
- package/lib/extension.js +278 -110
- package/lib/index.d.ts +1 -1
- package/lib/index.js +1 -1
- package/lib/lods.debug.js +1 -1
- package/lib/lods.manager.d.ts +90 -15
- package/lib/lods.manager.js +282 -150
- package/lib/lods.promise.js +1 -1
- package/lib/plugins/modelviewer.js +1 -1
- package/lib/version.js +1 -1
- package/package.json +4 -2
package/gltf-progressive.min.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{BufferGeometry as U,Mesh as F,Box3 as ie,Vector3 as A,Sphere as _e,CompressedTexture as je,Texture as $,Matrix3 as We,InterleavedBuffer as Ue,InterleavedBufferAttribute as Fe,BufferAttribute as ze,TextureLoader as qe,Matrix4 as be,Clock as Ve,MeshStandardMaterial as Xe}from"three";import{GLTFLoader as ae}from"three/examples/jsm/loaders/GLTFLoader.js";import{MeshoptDecoder as Ke}from"three/examples/jsm/libs/meshopt_decoder.module.js";import{DRACOLoader as Ye}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as He}from"three/examples/jsm/loaders/KTX2Loader.js";const Me="";globalThis.GLTF_PROGRESSIVE_VERSION=Me,console.debug("[gltf-progressive] version -");let k="https://www.gstatic.com/draco/versioned/decoders/1.5.7/",z="https://cdn.needle.tools/static/three/0.179.1/basis2/";const Qe=k,Je=z,De=new URL(k+"draco_decoder.js");De.searchParams.append("range","true"),fetch(De,{method:"GET",headers:{Range:"bytes=0-1"}}).catch(i=>{console.debug(`Failed to fetch remote Draco decoder from ${k} (offline: ${typeof navigator<"u"?navigator.onLine:"unknown"})`),k===Qe&&Oe("./include/draco/"),z===Je&&Se("./include/ktx2/")}).finally(()=>{Te()});const Ze=()=>({dracoDecoderPath:k,ktx2TranscoderPath:z});function Oe(i){k=i,T&&T[ue]!=k?(console.debug("Updating Draco decoder path to "+i),T[ue]=k,T.setDecoderPath(k),T.preload()):console.debug("Setting Draco decoder path to "+i)}function Se(i){z=i,I&&I.transcoderPath!=z?(console.debug("Updating KTX2 transcoder path to "+i),I.setTranscoderPath(z),I.init()):console.debug("Setting KTX2 transcoder path to "+i)}function ee(i){return Te(),i?I.detectSupport(i):i!==null&&console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures might fail"),{dracoLoader:T,ktx2Loader:I,meshoptDecoder:te}}function le(i){i.dracoLoader||i.setDRACOLoader(T),i.ktx2Loader||i.setKTX2Loader(I),i.meshoptDecoder||i.setMeshoptDecoder(te)}const ue=Symbol("dracoDecoderPath");let T,te,I;function Te(){T||(T=new Ye,T[ue]=k,T.setDecoderPath(k),T.setDecoderConfig({type:"js"}),T.preload()),I||(I=new He,I.setTranscoderPath(z),I.init()),te||(te=Ke)}const ce=new WeakMap;function de(i,t){let e=ce.get(i);e?e=Object.assign(e,t):e=t,ce.set(i,e)}const et=ae.prototype.load;function tt(...i){const t=ce.get(this);let e=i[0];const s=new URL(e,window.location.href);if(s.hostname.endsWith("needle.tools")){const o=t?.progressive!==void 0?t.progressive:!0,r=t?.usecase?t.usecase:"default";o?this.requestHeader.Accept=`*/*;progressive=allowed;usecase=${r}`:this.requestHeader.Accept=`*/*;usecase=${r}`,e=s.toString()}return i[0]=e,et?.call(this,...i)}ae.prototype.load=tt,N("debugprogressive");function N(i){if(typeof window>"u")return!1;const t=new URL(window.location.href).searchParams.get(i);return t==null||t==="0"||t==="false"?!1:t===""?!0:t}function st(i,t){if(t===void 0||i===void 0||t.startsWith("./")||t.startsWith("http")||t.startsWith("data:")||t.startsWith("blob:"))return t;const e=i.lastIndexOf("/");if(e>=0){const s=i.substring(0,e+1);for(;s.endsWith("/")&&t.startsWith("/");)t=t.substring(1);return s+t}return t}function he(){return se!==void 0||(se=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent),N("debugprogressive")&&console.log("[glTF Progressive]: isMobileDevice",se)),se}let se;function Pe(){if(typeof window>"u")return!1;const i=new URL(window.location.href),t=i.hostname==="localhost"||/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(i.hostname);return i.hostname==="127.0.0.1"||t}class rt{constructor(t,e={}){this.maxConcurrent=t,this.debug=e.debug??!1,typeof window<"u"&&window.requestAnimationFrame(this.tick)}_running=new Map;_queue=[];debug=!1;tick=()=>{this.internalUpdate(),setTimeout(this.tick,10)};slot(t){return this.debug&&console.debug(`[PromiseQueue]: Requesting slot for key ${t}, running: ${this._running.size}, waiting: ${this._queue.length}`),new Promise(e=>{this._queue.push({key:t,resolve:e})})}add(t,e){this._running.has(t)||(this._running.set(t,e),e.finally(()=>{this._running.delete(t),this.debug&&console.debug(`[PromiseQueue]: Promise finished now running: ${this._running.size}, waiting: ${this._queue.length}. (finished ${t})`)}),this.debug&&console.debug(`[PromiseQueue]: Added new promise, now running: ${this._running.size}, waiting: ${this._queue.length}. (added ${t})`))}internalUpdate(){const t=this.maxConcurrent-this._running.size;for(let e=0;e<t&&this._queue.length>0;e++){this.debug&&console.debug(`[PromiseQueue]: Running ${this._running.size} promises, waiting for ${this._queue.length} more.`);const{key:s,resolve:o}=this._queue.shift();o({use:r=>this.add(s,r)})}}}function ot(i){const t=i.image?.width??0,e=i.image?.height??0,s=i.image?.depth??1,o=Math.floor(Math.log2(Math.max(t,e,s)))+1,r=nt(i);return t*e*s*r*(1-Math.pow(.25,o))/(1-.25)}function nt(i){let t=4;const e=i.format;e===1024||e===1025?t=1:e===1026||e===1027?t=2:e===1022||e===1029?t=3:(e===1023||e===1033)&&(t=4);let s=1;const o=i.type;return o===1009||o===1010?s=1:o===1011||o===1012?s=2:o===1013||o===1014||o===1015?s=4:o===1016&&(s=2),t*s}const it=typeof window>"u"&&typeof document>"u",ge=Symbol("needle:raycast-mesh");function V(i){return i?.[ge]instanceof U?i[ge]:null}function Ce(i,t){if((i.type==="Mesh"||i.type==="SkinnedMesh")&&!V(i)){const e=at(t);e.userData={isRaycastMesh:!0},i[ge]=e}}function Ae(i=!0){if(i){if(K)return;const t=K=F.prototype.raycast;F.prototype.raycast=function(e,s){const o=this,r=V(o);let n;r&&o.isMesh&&(n=o.geometry,o.geometry=r),t.call(this,e,s),n&&(o.geometry=n)}}else{if(!K)return;F.prototype.raycast=K,K=null}}let K=null;function at(i){const t=new U;for(const e in i.attributes)t.setAttribute(e,i.getAttribute(e));return t.setIndex(i.getIndex()),t}const j=new Array,h=N("debugprogressive");let Y,q=-1;if(h){let i=function(){q+=1,q>=t&&(q=-1),console.log(`Toggle LOD level [${q}]`)},t=6;window.addEventListener("keyup",e=>{e.key==="p"&&i(),e.key==="w"&&(Y=!Y,console.log(`Toggle wireframe [${Y}]`));const s=parseInt(e.key);!isNaN(s)&&s>=0&&(q=s,console.log(`Set LOD level to [${q}]`))})}function ke(i){if(h&&Y!==void 0)if(Array.isArray(i))for(const t of i)ke(t);else i&&"wireframe"in i&&(i.wireframe=Y===!0)}const H=new Array;let lt=0;const ut=he()?2:10;function ct(i){if(H.length<ut){const e=H.length;h&&console.warn(`[Worker] Creating new worker #${e}`);const s=Le.createWorker(i||{});return H.push(s),s}const t=lt++%H.length;return H[t]}class Le{constructor(t,e){this.worker=t,this._debug=e.debug??!1,t.onmessage=s=>{const o=s.data;switch(this._debug&&console.log("[Worker] EVENT",o),o.type){case"loaded-gltf":for(const r of this._running)if(r.url===o.result.url){dt(o.result),r.resolve(o.result);const n=r.url;n.startsWith("blob:")&&URL.revokeObjectURL(n)}}},t.onerror=s=>{console.error("[Worker] Error in gltf-progressive worker:",s)},t.postMessage({type:"init"})}static async createWorker(t){const e=new Worker(new URL("/assets/gltf-progressive.worker-CCrD-Ycm.js",import.meta.url),{type:"module"});return new Le(e,t)}_running=[];_webglRenderer=null;async load(t,e){const s=Ze();let o=e?.renderer;o||(this._webglRenderer??=(async()=>{const{WebGLRenderer:l}=await import("three");return new l})(),o=await this._webglRenderer);const r=ee(o).ktx2Loader.workerConfig;t instanceof URL?t=t.toString():t.startsWith("file:")?t=URL.createObjectURL(new Blob([t])):!t.startsWith("blob:")&&!t.startsWith("http:")&&!t.startsWith("https:")&&(t=new URL(t,window.location.href).toString());const n={type:"load",url:t,dracoDecoderPath:s.dracoDecoderPath,ktx2TranscoderPath:s.ktx2TranscoderPath,ktx2LoaderConfig:r};return this._debug&&console.debug("[Worker] Sending load request",n),this.worker.postMessage(n),new Promise(l=>{this._running.push({url:t.toString(),resolve:l})})}_debug=!1}function dt(i){for(const t of i.geometries){const e=t.geometry,s=new U;if(s.name=e.name||"",e.index){const o=e.index;s.setIndex(fe(o))}for(const o in e.attributes){const r=e.attributes[o],n=fe(r);s.setAttribute(o,n)}if(e.morphAttributes)for(const o in e.morphAttributes){const r=e.morphAttributes[o].map(n=>fe(n));s.morphAttributes[o]=r}if(s.morphTargetsRelative=e.morphTargetsRelative??!1,s.boundingBox=new ie,s.boundingBox.min=new A(e.boundingBox?.min.x,e.boundingBox?.min.y,e.boundingBox?.min.z),s.boundingBox.max=new A(e.boundingBox?.max.x,e.boundingBox?.max.y,e.boundingBox?.max.z),s.boundingSphere=new _e(new A(e.boundingSphere?.center.x,e.boundingSphere?.center.y,e.boundingSphere?.center.z),e.boundingSphere?.radius),e.groups)for(const o of e.groups)s.addGroup(o.start,o.count,o.materialIndex);e.userData&&(s.userData=e.userData),t.geometry=s}for(const t of i.textures){const e=t.texture;let s=null;if(e.isCompressedTexture){const o=e.mipmaps,r=e.image?.width||e.source?.data?.width||-1,n=e.image?.height||e.source?.data?.height||-1;s=new je(o,r,n,e.format,e.type,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.anisotropy,e.colorSpace)}else s=new $(e.image,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.colorSpace),s.mipmaps=e.mipmaps,s.channel=e.channel,s.source.data=e.source.data,s.flipY=e.flipY,s.premultiplyAlpha=e.premultiplyAlpha,s.unpackAlignment=e.unpackAlignment,s.matrix=new We(...e.matrix.elements);if(!s){console.error("[Worker] Failed to create new texture from received data. Texture is not a CompressedTexture or Texture.");continue}t.texture=s}return i}function fe(i){let t=i;if("isInterleavedBufferAttribute"in i&&i.isInterleavedBufferAttribute){const e=i.data,s=e.array,o=new Ue(s,e.stride);t=new Fe(o,i.itemSize,s.byteOffset,i.normalized),t.offset=i.offset}else"isBufferAttribute"in i&&i.isBufferAttribute&&(t=new ze(i.array,i.itemSize,i.normalized),t.usage=i.usage,t.gpuType=i.gpuType,t.updateRanges=i.updateRanges);return t}const ht=N("gltf-progressive-worker");N("gltf-progressive-reduce-mipmaps");const X=N("gltf-progressive-gc"),me=Symbol("needle-progressive-texture"),B="NEEDLE_progressive";class f{get name(){return B}static getMeshLODExtension(t){const e=this.getAssignedLODInformation(t);return e?.key?this.lodInfos.get(e.key):null}static getPrimitiveIndex(t){return this.getAssignedLODInformation(t)?.index??-1}static getMaterialMinMaxLODsCount(t,e){const s=this,o="LODS:minmax",r=t[o];if(r!=null)return r;if(e||(e={min_count:1/0,max_count:0,lods:[]}),Array.isArray(t)){for(const l of t)this.getMaterialMinMaxLODsCount(l,e);return t[o]=e,e}if(h==="verbose"&&console.log("getMaterialMinMaxLODsCount",t),t.type==="ShaderMaterial"||t.type==="RawShaderMaterial"){const l=t;for(const a of Object.keys(l.uniforms)){const u=l.uniforms[a].value;u?.isTexture===!0&&n(u,e)}}else if(t.isMaterial)for(const l of Object.keys(t)){const a=t[l];a?.isTexture===!0&&n(a,e)}else h&&console.warn(`[getMaterialMinMaxLODsCount] Unsupported material type: ${t.type}`);return t[o]=e,e;function n(l,a){const u=s.getAssignedLODInformation(l);if(u){const y=s.lodInfos.get(u.key);if(y&&y.lods){a.min_count=Math.min(a.min_count,y.lods.length),a.max_count=Math.max(a.max_count,y.lods.length);for(let p=0;p<y.lods.length;p++){const w=y.lods[p];w.width&&(a.lods[p]=a.lods[p]||{min_height:1/0,max_height:0},a.lods[p].min_height=Math.min(a.lods[p].min_height,w.height),a.lods[p].max_height=Math.max(a.lods[p].max_height,w.height))}}}}}static hasLODLevelAvailable(t,e){if(Array.isArray(t)){for(const r of t)if(this.hasLODLevelAvailable(r,e))return!0;return!1}if(t.isMaterial===!0){for(const r of Object.keys(t)){const n=t[r];if(n&&n.isTexture&&this.hasLODLevelAvailable(n,e))return!0}return!1}else if(t.isGroup===!0){for(const r of t.children)if(r.isMesh===!0&&this.hasLODLevelAvailable(r,e))return!0}let s,o;if(t.isMesh?s=t.geometry:(t.isBufferGeometry||t.isTexture)&&(s=t),s&&s?.userData?.LODS){const r=s.userData.LODS;if(o=this.lodInfos.get(r.key),e===void 0)return o!=null;if(o)return Array.isArray(o.lods)?e<o.lods.length:e===0}return!1}static assignMeshLOD(t,e){if(!t)return Promise.resolve(null);if(t instanceof F||t.isMesh===!0){const s=t.geometry,o=this.getAssignedLODInformation(s);if(!o)return Promise.resolve(null);for(const r of j)r.onBeforeGetLODMesh?.(t,e);return t["LOD:requested level"]=e,f.getOrLoadLOD(s,e).then(r=>{if(Array.isArray(r)){const n=o.index||0;r=r[n]}return t["LOD:requested level"]===e&&(delete t["LOD:requested level"],r&&s!=r&&(r?.isBufferGeometry?t.geometry=r:h&&console.error("Invalid LOD geometry",r))),r}).catch(r=>(console.error("Error loading mesh LOD",t,r),null))}else h&&console.error("Invalid call to assignMeshLOD: Request mesh LOD but the object is not a mesh",t);return Promise.resolve(null)}static assignTextureLOD(t,e=0){if(!t)return Promise.resolve(null);if(t.isMesh===!0){const s=t;if(Array.isArray(s.material)){const o=new Array;for(const r of s.material){const n=this.assignTextureLOD(r,e);o.push(n)}return Promise.all(o).then(r=>{const n=new Array;for(const l of r)Array.isArray(l)&&n.push(...l);return n})}else return this.assignTextureLOD(s.material,e)}if(t.isMaterial===!0){const s=t,o=[],r=new Array;if(s.uniforms&&(s.isRawShaderMaterial||s.isShaderMaterial===!0)){const n=s;for(const l of Object.keys(n.uniforms)){const a=n.uniforms[l].value;if(a?.isTexture===!0){const u=this.assignTextureLODForSlot(a,e,s,l).then(y=>(y&&n.uniforms[l].value!=y&&(n.uniforms[l].value=y,n.uniformsNeedUpdate=!0),y));o.push(u),r.push(l)}}}else for(const n of Object.keys(s)){const l=s[n];if(l?.isTexture===!0){const a=this.assignTextureLODForSlot(l,e,s,n);o.push(a),r.push(n)}}return Promise.all(o).then(n=>{const l=new Array;for(let a=0;a<n.length;a++){const u=n[a],y=r[a];u&&u.isTexture===!0?l.push({material:s,slot:y,texture:u,level:e}):l.push({material:s,slot:y,texture:null,level:e})}return l})}if(t instanceof $||t.isTexture===!0){const s=t;return this.assignTextureLODForSlot(s,e,null,null)}return Promise.resolve(null)}static set maxConcurrentLoadingTasks(t){f.queue.maxConcurrent=t}static get maxConcurrentLoadingTasks(){return f.queue.maxConcurrent}static assignTextureLODForSlot(t,e,s,o){return t?.isTexture!==!0?Promise.resolve(null):o==="glyphMap"?Promise.resolve(t):f.getOrLoadLOD(t,e).then(r=>{if(Array.isArray(r))return console.warn("Progressive: Got an array of textures for a texture slot, this should not happen..."),null;if(r?.isTexture===!0){if(r!=t&&s&&o){const n=s[o];if(n&&!h){const l=this.getAssignedLODInformation(n);if(l&&l?.level<e)return h==="verbose"&&console.warn("Assigned texture level is already higher: ",l.level,e,s,n,r),r&&r!==n&&((h||X)&&console.log(`[gltf-progressive] Disposing rejected lower-quality texture LOD ${e} (assigned is ${l.level})`,r.uuid),r.dispose()),null}if(this.trackTextureUsage(r),n&&n!==r&&this.untrackTextureUsage(n)&&(h||X)){const l=this.getAssignedLODInformation(n);console.log(`[gltf-progressive] Disposed old texture LOD ${l?.level??"?"} \u2192 ${e} for ${s.name||s.type}.${o}`,n.uuid)}s[o]=r}return r}else h=="verbose"&&console.warn("No LOD found for",t,e);return null}).catch(r=>(console.error("Error loading LOD",t,r),null))}parser;url;constructor(t){const e=t.options.path;h&&console.log("Progressive extension registered for",e),this.parser=t,this.url=e}_isLoadingMesh;loadMesh=t=>{if(this._isLoadingMesh)return null;const e=this.parser.json.meshes[t]?.extensions?.[B];return e?(this._isLoadingMesh=!0,this.parser.getDependency("mesh",t).then(s=>(this._isLoadingMesh=!1,s&&f.registerMesh(this.url,e.guid,s,e.lods?.length,0,e),s))):null};afterRoot(t){return h&&console.log("AFTER",this.url,t),this.parser.json.textures?.forEach((e,s)=>{if(e?.extensions){const o=e?.extensions[B];if(o){if(!o.lods){h&&console.warn("Texture has no LODs",o);return}let r=!1;for(const n of this.parser.associations.keys())n.isTexture===!0&&this.parser.associations.get(n)?.textures===s&&(r=!0,f.registerTexture(this.url,n,o.lods?.length,s,o));r||this.parser.getDependency("texture",s).then(n=>{n&&f.registerTexture(this.url,n,o.lods?.length,s,o)})}}}),this.parser.json.meshes?.forEach((e,s)=>{if(e?.extensions){const o=e?.extensions[B];if(o&&o.lods){for(const r of this.parser.associations.keys())if(r.isMesh){const n=this.parser.associations.get(r);n?.meshes===s&&f.registerMesh(this.url,o.guid,r,o.lods.length,n.primitives,o)}}}}),null}static registerTexture=(t,e,s,o,r)=>{if(!e){h&&console.error("!! gltf-progressive: Called register texture without texture");return}if(h){const l=e.image?.width||e.source?.data?.width||0,a=e.image?.height||e.source?.data?.height||0;console.log(`> gltf-progressive: register texture[${o}] "${e.name||e.uuid}", Current: ${l}x${a}, Max: ${r.lods[0]?.width}x${r.lods[0]?.height}, uuid: ${e.uuid}`,r,e)}e.source&&(e.source[me]=r);const n=r.guid;f.assignLODInformation(t,e,n,s,o),f.lodInfos.set(n,r),f.lowresCache.set(n,new WeakRef(e))};static registerMesh=(t,e,s,o,r,n)=>{const l=s.geometry;if(!l){h&&console.warn("gltf-progressive: Register mesh without geometry");return}l.userData||(l.userData={}),h&&console.log("> Progressive: register mesh "+s.name,{index:r,uuid:s.uuid},n,s),f.assignLODInformation(t,l,e,o,r),f.lodInfos.set(e,n);let a=f.lowresCache.get(e)?.deref();a?a.push(s.geometry):a=[s.geometry],f.lowresCache.set(e,new WeakRef(a)),o>0&&!V(s)&&Ce(s,l);for(const u of j)u.onRegisteredNewMesh?.(s,n)};static dispose(t){if(t){this.lodInfos.delete(t);const e=this.lowresCache.get(t);if(e){const s=e.deref();if(s){if(s.isTexture){const o=s;this.textureRefCounts.delete(o.uuid),o.dispose()}else if(Array.isArray(s))for(const o of s)o.dispose()}this.lowresCache.delete(t)}for(const[s,o]of this.cache)s.includes(t)&&(this._disposeCacheEntry(o),this.cache.delete(s))}else{this.lodInfos.clear();for(const[,e]of this.lowresCache){const s=e.deref();if(s){if(s.isTexture){const o=s;this.textureRefCounts.delete(o.uuid),o.dispose()}else if(Array.isArray(s))for(const o of s)o.dispose()}}this.lowresCache.clear();for(const[,e]of this.cache)this._disposeCacheEntry(e);this.cache.clear(),this.textureRefCounts.clear()}}static _disposeCacheEntry(t){if(t instanceof WeakRef){const e=t.deref();e&&(e.isTexture&&this.textureRefCounts.delete(e.uuid),e.dispose())}else t.then(e=>{if(e)if(Array.isArray(e))for(const s of e)s.dispose();else e.isTexture&&this.textureRefCounts.delete(e.uuid),e.dispose()}).catch(()=>{})}static lodInfos=new Map;static cache=new Map;static lowresCache=new Map;static textureRefCounts=new Map;static _resourceRegistry=new FinalizationRegistry(t=>{const e=f.cache.get(t);(h||X)&&console.debug(`[gltf-progressive] Memory: Resource GC'd
|
|
2
|
-
${t}`),e instanceof WeakRef&&(e.deref()||(
|
|
3
|
-
${e}`)}}static workers=[];static _workersIndex=0;static async getOrLoadLOD(t,e){const
|
|
4
|
-
`,L),null))
|
|
5
|
-
`,
|
|
1
|
+
import{BufferGeometry as q,Mesh as z,Box3 as oe,Vector3 as S,Sphere as Oe,CompressedTexture as Ye,Texture as I,Matrix3 as Qe,InterleavedBuffer as Je,InterleavedBufferAttribute as Ze,BufferAttribute as et,TextureLoader as tt,Color as Se,Matrix4 as ke,Clock as rt}from"three";import{GLTFLoader as de}from"three/examples/jsm/loaders/GLTFLoader.js";import{MeshoptDecoder as st}from"three/examples/jsm/libs/meshopt_decoder.module.js";import{DRACOLoader as ot}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as nt}from"three/examples/jsm/loaders/KTX2Loader.js";const Ce="";globalThis.GLTF_PROGRESSIVE_VERSION=Ce,console.debug("[gltf-progressive] version -");let P="https://www.gstatic.com/draco/versioned/decoders/1.5.7/",V="https://cdn.needle.tools/static/three/0.179.1/basis2/";const it=P,at=V,Pe=new URL(P+"draco_decoder.js");Pe.searchParams.append("range","true"),fetch(Pe,{method:"GET",headers:{Range:"bytes=0-1"}}).catch(i=>{console.debug(`Failed to fetch remote Draco decoder from ${P} (offline: ${typeof navigator<"u"?navigator.onLine:"unknown"})`),P===it&&Ae("./include/draco/"),V===at&&Ee("./include/ktx2/")}).finally(()=>{Re()});const lt=()=>({dracoDecoderPath:P,ktx2TranscoderPath:V});function Ae(i){P=i,T&&T[ge]!=P?(console.debug("Updating Draco decoder path to "+i),T[ge]=P,T.setDecoderPath(P),T.preload()):console.debug("Setting Draco decoder path to "+i)}function Ee(i){V=i,A&&A.transcoderPath!=V?(console.debug("Updating KTX2 transcoder path to "+i),A.setTranscoderPath(V),A.init()):console.debug("Setting KTX2 transcoder path to "+i)}function ne(i){return Re(),i?A.detectSupport(i):i!==null&&console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures might fail"),{dracoLoader:T,ktx2Loader:A,meshoptDecoder:ie}}function he(i){i.dracoLoader||i.setDRACOLoader(T),i.ktx2Loader||i.setKTX2Loader(A),i.meshoptDecoder||i.setMeshoptDecoder(ie)}const ge=Symbol("dracoDecoderPath");let T,ie,A;function Re(){T||(T=new ot,T[ge]=P,T.setDecoderPath(P),T.setDecoderConfig({type:"js"}),T.preload()),A||(A=new nt,A.setTranscoderPath(V),A.init()),ie||(ie=st)}const fe=new WeakMap;function me(i,t){let e=fe.get(i);e?e=Object.assign(e,t):e=t,fe.set(i,e)}const ut=de.prototype.load;function ct(...i){const t=fe.get(this);let e=i[0];const r=new URL(e,window.location.href);if(r.hostname.endsWith("needle.tools")){const s=t?.progressive!==void 0?t.progressive:!0,o=t?.usecase?t.usecase:"default";s?this.requestHeader.Accept=`*/*;progressive=allowed;usecase=${o}`:this.requestHeader.Accept=`*/*;usecase=${o}`,e=r.toString()}return i[0]=e,ut?.call(this,...i)}de.prototype.load=ct,N("debugprogressive");function N(i){if(typeof window>"u")return!1;const t=new URL(window.location.href).searchParams.get(i);return t==null||t==="0"||t==="false"?!1:t===""?!0:t}function dt(i,t){if(t===void 0||i===void 0||t.startsWith("./")||t.startsWith("http")||t.startsWith("data:")||t.startsWith("blob:"))return t;const e=i.lastIndexOf("/");if(e>=0){const r=i.substring(0,e+1);for(;r.endsWith("/")&&t.startsWith("/");)t=t.substring(1);return r+t}return t}function pe(){return ae!==void 0||(ae=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent),N("debugprogressive")&&console.log("[glTF Progressive]: isMobileDevice",ae)),ae}let ae;function Ie(){if(typeof window>"u")return!1;const i=new URL(window.location.href),t=i.hostname==="localhost"||/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(i.hostname);return i.hostname==="127.0.0.1"||t}class ht{constructor(t,e={}){this.maxConcurrent=t,this.debug=e.debug??!1,typeof window<"u"&&window.requestAnimationFrame(this.tick)}_running=new Map;_queue=[];debug=!1;tick=()=>{this.internalUpdate(),setTimeout(this.tick,10)};slot(t){return this.debug&&console.debug(`[PromiseQueue]: Requesting slot for key ${t}, running: ${this._running.size}, waiting: ${this._queue.length}`),new Promise(e=>{this._queue.push({key:t,resolve:e})})}add(t,e){this._running.has(t)||(this._running.set(t,e),e.finally(()=>{this._running.delete(t),this.debug&&console.debug(`[PromiseQueue]: Promise finished now running: ${this._running.size}, waiting: ${this._queue.length}. (finished ${t})`)}),this.debug&&console.debug(`[PromiseQueue]: Added new promise, now running: ${this._running.size}, waiting: ${this._queue.length}. (added ${t})`))}internalUpdate(){const t=this.maxConcurrent-this._running.size;for(let e=0;e<t&&this._queue.length>0;e++){this.debug&&console.debug(`[PromiseQueue]: Running ${this._running.size} promises, waiting for ${this._queue.length} more.`);const{key:r,resolve:s}=this._queue.shift();s({use:o=>this.add(r,o)})}}}function gt(i){const t=i.image?.width??0,e=i.image?.height??0,r=i.image?.depth??1,s=Math.floor(Math.log2(Math.max(t,e,r)))+1,o=ft(i);return t*e*r*o*(1-Math.pow(.25,s))/(1-.25)}function ft(i){let t=4;const e=i.format;e===1024||e===1025?t=1:e===1026||e===1027?t=2:e===1022||e===1029?t=3:(e===1023||e===1033)&&(t=4);let r=1;const s=i.type;return s===1009||s===1010?r=1:s===1011||s===1012?r=2:s===1013||s===1014||s===1015?r=4:s===1016&&(r=2),t*r}const mt=typeof window>"u"&&typeof document>"u",xe=Symbol("needle:raycast-mesh");function K(i){return i?.[xe]instanceof q?i[xe]:null}function $e(i,t){if((i.type==="Mesh"||i.type==="SkinnedMesh")&&!K(i)){const e=pt(t);e.userData={isRaycastMesh:!0},i[xe]=e}}function Be(i=!0){if(i){if(Z)return;const t=Z=z.prototype.raycast;z.prototype.raycast=function(e,r){const s=this,o=K(s);let n;o&&s.isMesh&&(n=s.geometry,s.geometry=o),t.call(this,e,r),n&&(s.geometry=n)}}else{if(!Z)return;z.prototype.raycast=Z,Z=null}}let Z=null;function pt(i){const t=new q;for(const e in i.attributes)t.setAttribute(e,i.getAttribute(e));return t.setIndex(i.getIndex()),t}const W=new Array,g=N("debugprogressive");let ee,X=-1;if(g){let i=function(){X+=1,X>=t&&(X=-1),console.log(`Toggle LOD level [${X}]`)};const t=6;window.addEventListener("keyup",e=>{e.key==="p"&&i(),e.key==="w"&&(ee=!ee,console.log(`Toggle wireframe [${ee}]`));const r=parseInt(e.key);!isNaN(r)&&r>=0&&(X=r,console.log(`Set LOD level to [${X}]`))})}function Ge(i){if(g&&ee!==void 0)if(Array.isArray(i))for(const t of i)Ge(t);else i&&"wireframe"in i&&(i.wireframe=ee===!0)}const te=new Array;let xt=0;const yt=pe()?2:10;function vt(i){if(te.length<yt){const e=te.length;g&&console.warn(`[Worker] Creating new worker #${e}`);const r=Te.createWorker(i||{});return te.push(r),r}const t=xt++%te.length;return te[t]}class Te{constructor(t,e){this.worker=t,this._debug=e.debug??!1,t.onmessage=r=>{const s=r.data;switch(this._debug&&console.log("[Worker] EVENT",s),s.type){case"loaded-gltf":for(const o of this._running)if(o.url===s.result.url){wt(s.result),o.resolve(s.result);const n=o.url;n.startsWith("blob:")&&URL.revokeObjectURL(n)}}},t.onerror=r=>{console.error("[Worker] Error in gltf-progressive worker:",r)},t.postMessage({type:"init"})}static async createWorker(t){const e=new Worker(new URL("/assets/gltf-progressive.worker-CCrD-Ycm.js",import.meta.url),{type:"module"});return new Te(e,t)}_running=[];_webglRenderer=null;async load(t,e){const r=lt();let s=e?.renderer;s||(this._webglRenderer??=(async()=>{const{WebGLRenderer:u}=await import("three");return new u})(),s=await this._webglRenderer);const o=ne(s).ktx2Loader.workerConfig;t instanceof URL?t=t.toString():t.startsWith("file:")?t=URL.createObjectURL(new Blob([t])):!t.startsWith("blob:")&&!t.startsWith("http:")&&!t.startsWith("https:")&&(t=new URL(t,window.location.href).toString());const n={type:"load",url:t,dracoDecoderPath:r.dracoDecoderPath,ktx2TranscoderPath:r.ktx2TranscoderPath,ktx2LoaderConfig:o};return this._debug&&console.debug("[Worker] Sending load request",n),this.worker.postMessage(n),new Promise(u=>{this._running.push({url:t.toString(),resolve:u})})}_debug=!1}function wt(i){for(const t of i.geometries){const e=t.geometry,r=new q;if(r.name=e.name||"",e.index){const s=e.index;r.setIndex(ye(s))}for(const s in e.attributes){const o=e.attributes[s],n=ye(o);r.setAttribute(s,n)}if(e.morphAttributes)for(const s in e.morphAttributes){const o=e.morphAttributes[s].map(n=>ye(n));r.morphAttributes[s]=o}if(r.morphTargetsRelative=e.morphTargetsRelative??!1,r.boundingBox=new oe,r.boundingBox.min=new S(e.boundingBox?.min.x,e.boundingBox?.min.y,e.boundingBox?.min.z),r.boundingBox.max=new S(e.boundingBox?.max.x,e.boundingBox?.max.y,e.boundingBox?.max.z),r.boundingSphere=new Oe(new S(e.boundingSphere?.center.x,e.boundingSphere?.center.y,e.boundingSphere?.center.z),e.boundingSphere?.radius),e.groups)for(const s of e.groups)r.addGroup(s.start,s.count,s.materialIndex);e.userData&&(r.userData=e.userData),t.geometry=r}for(const t of i.textures){const e=t.texture;let r=null;if(e.isCompressedTexture){const s=e.mipmaps,o=e.image?.width||e.source?.data?.width||-1,n=e.image?.height||e.source?.data?.height||-1;r=new Ye(s,o,n,e.format,e.type,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.anisotropy,e.colorSpace)}else r=new I(e.image,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.colorSpace),r.mipmaps=e.mipmaps,r.channel=e.channel,r.source.data=e.source.data,r.flipY=e.flipY,r.premultiplyAlpha=e.premultiplyAlpha,r.unpackAlignment=e.unpackAlignment,r.matrix=new Qe(...e.matrix.elements);if(!r){console.error("[Worker] Failed to create new texture from received data. Texture is not a CompressedTexture or Texture.");continue}t.texture=r}return i}function ye(i){let t=i;if("isInterleavedBufferAttribute"in i&&i.isInterleavedBufferAttribute){const e=i.data,r=e.array,s=new Je(r,e.stride);t=new Ze(s,i.itemSize,r.byteOffset,i.normalized),t.offset=i.offset}else"isBufferAttribute"in i&&i.isBufferAttribute&&(t=new et(i.array,i.itemSize,i.normalized),t.usage=i.usage,t.gpuType=i.gpuType,t.updateRanges=i.updateRanges);return t}const Lt=N("gltf-progressive-worker");N("gltf-progressive-reduce-mipmaps");const re=N("gltf-progressive-gc"),ve=Symbol("needle-progressive-texture"),$="NEEDLE_progressive";class m{get name(){return $}static getMeshLODExtension(t){const e=this.getAssignedLODInformation(t);return e?.key?this.lodInfos.get(e.key):null}static getPrimitiveIndex(t){return this.getAssignedLODInformation(t)?.index??-1}static getMaterialMinMaxLODsCount(t,e){const r=this,s="LODS:minmax",o=t[s];if(o!=null)return o;if(e||(e={min_count:1/0,max_count:0,lods:[]}),Array.isArray(t)){for(const u of t)this.getMaterialMinMaxLODsCount(u,e);return t[s]=e,e}if(g==="verbose"&&console.log("getMaterialMinMaxLODsCount",t),t.type==="ShaderMaterial"||t.type==="RawShaderMaterial"){const u=t;for(const a of Object.keys(u.uniforms)){const l=u.uniforms[a].value;l?.isTexture===!0&&n(l,e)}}else if(t.isMaterial)for(const u of Object.keys(t)){const a=t[u];a?.isTexture===!0&&n(a,e)}else g&&console.warn(`[getMaterialMinMaxLODsCount] Unsupported material type: ${t.type}`);return t[s]=e,e;function n(u,a){const l=r.getAssignedLODInformation(u);if(l){const d=r.lodInfos.get(l.key);if(d&&d.lods){a.min_count=Math.min(a.min_count,d.lods.length),a.max_count=Math.max(a.max_count,d.lods.length);for(let h=0;h<d.lods.length;h++){const y=d.lods[h];y.width&&(a.lods[h]=a.lods[h]||{min_height:1/0,max_height:0},a.lods[h].min_height=Math.min(a.lods[h].min_height,y.height),a.lods[h].max_height=Math.max(a.lods[h].max_height,y.height))}}}}}static hasLODLevelAvailable(t,e){if(Array.isArray(t)){for(const o of t)if(this.hasLODLevelAvailable(o,e))return!0;return!1}if(t.isMaterial===!0){for(const o of Object.keys(t)){const n=t[o];if(n&&n.isTexture&&this.hasLODLevelAvailable(n,e))return!0}return!1}else if(t.isGroup===!0){for(const o of t.children)if(o.isMesh===!0&&this.hasLODLevelAvailable(o,e))return!0}let r,s;if(t.isMesh?r=t.geometry:(t.isBufferGeometry||t.isTexture)&&(r=t),r&&r?.userData?.LODS){const o=r.userData.LODS;if(s=this.lodInfos.get(o.key),e===void 0)return s!=null;if(s)return Array.isArray(s.lods)?e<s.lods.length:e===0}return!1}static assignMeshLOD(t,e,r){if(!t)return Promise.resolve(null);if(t instanceof z||t.isMesh===!0){const s=t.geometry,o=this.getAssignedLODInformation(s);if(!o)return Promise.resolve(null);for(const n of W)n.onBeforeGetLODMesh?.(t,e);return t["LOD:requested level"]=e,m.getOrLoadLOD(s,e).then(n=>{if(Array.isArray(n)){const u=o.index||0;n=n[u]}return t["LOD:requested level"]===e&&(delete t["LOD:requested level"],n&&s!=n&&(n?.isBufferGeometry?typeof r?.apply=="function"?r.apply(n,e,t):r?.apply!==!1&&(t.geometry=n):g&&console.error("Invalid LOD geometry",n))),n}).catch(n=>(console.error("Error loading mesh LOD",t,n),null))}else g&&console.error("Invalid call to assignMeshLOD: Request mesh LOD but the object is not a mesh",t);return Promise.resolve(null)}static assignTextureLOD(t,e=0,r){if(!t)return Promise.resolve(null);const s=r?.force===!0;if(t.isMesh===!0){const o=t;if(Array.isArray(o.material)){const n=new Array;for(const u of o.material){const a=this.assignTextureLOD(u,e,r);n.push(a)}return Promise.all(n).then(u=>{const a=new Array;for(const l of u)Array.isArray(l)&&a.push(...l);return a})}else return this.assignTextureLOD(o.material,e,r)}if(t.isMaterial===!0){const o=t,n=[],u=new Array;if(this.trackCurrentMaterialTextureSlots(o),o.uniforms&&(o.isRawShaderMaterial||o.isShaderMaterial===!0)){const a=o;for(const l of Object.keys(a.uniforms)){const d=a.uniforms[l].value;if(d?.isTexture===!0){const h=this.assignTextureLODForSlot(d,e,o,l,s).then(y=>(y&&a.uniforms[l].value!=y&&(a.uniforms[l].value=y,a.uniformsNeedUpdate=!0),y));n.push(h),u.push(l)}}}else for(const a of Object.keys(o)){const l=o[a];if(l?.isTexture===!0){const d=this.assignTextureLODForSlot(l,e,o,a,s);n.push(d),u.push(a)}}return Promise.all(n).then(a=>{const l=new Array;for(let d=0;d<a.length;d++){const h=a[d],y=u[d];h&&h.isTexture===!0?l.push({material:o,slot:y,texture:h,level:e}):l.push({material:o,slot:y,texture:null,level:e})}return l})}if(t instanceof I||t.isTexture===!0){const o=t;return this.assignTextureLODForSlot(o,e,null,null,s)}return Promise.resolve(null)}static set maxConcurrentLoadingTasks(t){m.queue.maxConcurrent=t}static get maxConcurrentLoadingTasks(){return m.queue.maxConcurrent}static assignTextureLODForSlot(t,e,r,s,o){if(t?.isTexture!==!0)return Promise.resolve(null);if(s==="glyphMap")return Promise.resolve(t);const n=this.getAssignedLODInformation(t);if(n&&(n.level===e||!o&&n.level<e))return Promise.resolve(t);if(r&&s){const a=this.getPendingTextureSlotRequest(r,s);if(a&&a.level===e&&a.force===o)return a.promise}const u=m.getOrLoadLOD(t,e).then(a=>{if(Array.isArray(a))return console.warn("Progressive: Got an array of textures for a texture slot, this should not happen..."),null;if(a?.isTexture===!0){if(a!=t&&r&&s){const l=this.getMaterialTextureSlot(r,s)??t;if(l&&!o){const d=this.getAssignedLODInformation(l);if(d&&d?.level<e)return g==="verbose"&&console.warn("Assigned texture level is already higher: ",d.level,e,r,l,a),null}this.assignTrackedTextureSlot(r,s,a)}return a}else g=="verbose"&&console.warn("No LOD found for",t,e);return null}).catch(a=>(console.error("Error loading LOD",t,a),null));return r&&s&&this.setPendingTextureSlotRequest(r,s,e,o,u),u}static trackedTextureSlots=new WeakMap;static pendingTextureSlotRequests=new WeakMap;static trackCurrentMaterialTextureSlots(t){if(t.uniforms&&(t.isRawShaderMaterial||t.isShaderMaterial===!0)){const e=t;for(const r of Object.keys(e.uniforms)){const s=e.uniforms[r].value;s?.isTexture===!0&&this.ensureTrackedTextureSlot(t,r,s)}return}for(const e of Object.keys(t)){const r=t[e];r?.isTexture===!0&&this.ensureTrackedTextureSlot(t,e,r)}}static getPendingTextureSlotRequest(t,e){return this.pendingTextureSlotRequests.get(t)?.get(e)}static setPendingTextureSlotRequest(t,e,r,s,o){let n=this.pendingTextureSlotRequests.get(t);n||(n=new Map,this.pendingTextureSlotRequests.set(t,n));const u={level:r,force:s,promise:o};n.set(e,u),o.finally(()=>{n.get(e)===u&&n.delete(e)})}static getMaterialTextureSlot(t,e){const r=t.uniforms?.[e];if(r?.value?.isTexture===!0)return r.value;const s=t[e];return s?.isTexture===!0?s:null}static setMaterialTextureSlot(t,e,r){const s=t.uniforms?.[e];if(s?.value?.isTexture===!0){s.value=r,t.uniformsNeedUpdate=!0;return}t[e]=r}static assignTrackedTextureSlot(t,e,r){let s=this.trackedTextureSlots.get(t);s||(s=new Map,this.trackedTextureSlots.set(t,s));const o=this.getMaterialTextureSlot(t,e);let n=s.get(e);!n&&o?n=this.ensureTrackedTextureSlot(t,e,o):n&&o&&n!==o&&(this.releaseTrackedTextureSlot(t,e,n),n=this.ensureTrackedTextureSlot(t,e,o)),!(n===r&&o===r)&&(n&&n!==r&&this.releaseTrackedTextureSlot(t,e,n),n!==r&&(this.trackTextureUsage(r),s.set(e,r)),o!==r&&this.setMaterialTextureSlot(t,e,r))}static ensureTrackedTextureSlot(t,e,r){let s=this.trackedTextureSlots.get(t);s||(s=new Map,this.trackedTextureSlots.set(t,s));const o=s.get(e);return o===r?o:(o&&this.releaseTrackedTextureSlot(t,e,o),this.trackTextureUsage(r),s.set(e,r),r)}static releaseTrackedTextureSlot(t,e,r){const s=this.trackedTextureSlots.get(t);if(s?.get(e)===r&&s.delete(e),this.untrackTextureUsage(r)&&(g||re)){const o=this.getAssignedLODInformation(r);console.log(`[gltf-progressive] Disposed old texture LOD ${o?.level??"?"} for ${t.name||t.type}.${e}`,r.uuid)}}parser;url;constructor(t){const e=t.options.path;g&&console.log("Progressive extension registered for",e),this.parser=t,this.url=e}_isLoadingMesh;loadMesh=t=>{if(this._isLoadingMesh)return null;const e=this.parser.json.meshes[t]?.extensions?.[$];return e?(this._isLoadingMesh=!0,this.parser.getDependency("mesh",t).then(r=>(this._isLoadingMesh=!1,r&&m.registerMesh(this.url,e.guid,r,e.lods?.length,0,e),r))):null};afterRoot(t){return g&&console.log("AFTER",this.url,t),this.parser.json.textures?.forEach((e,r)=>{if(e?.extensions){const s=e?.extensions[$];if(s){if(!s.lods){g&&console.warn("Texture has no LODs",s);return}let o=!1;for(const n of this.parser.associations.keys())n.isTexture===!0&&this.parser.associations.get(n)?.textures===r&&(o=!0,m.registerTexture(this.url,n,s.lods?.length,r,s));o||this.parser.getDependency("texture",r).then(n=>{n&&m.registerTexture(this.url,n,s.lods?.length,r,s)})}}}),this.parser.json.meshes?.forEach((e,r)=>{if(e?.extensions){const s=e?.extensions[$];if(s&&s.lods){for(const o of this.parser.associations.keys())if(o.isMesh){const n=this.parser.associations.get(o);n?.meshes===r&&m.registerMesh(this.url,s.guid,o,s.lods.length,n.primitives,s)}}}}),null}static registerTexture=(t,e,r,s,o)=>{if(!e){g&&console.error("!! gltf-progressive: Called register texture without texture");return}if(g){const u=e.image?.width||e.source?.data?.width||0,a=e.image?.height||e.source?.data?.height||0;console.log(`> gltf-progressive: register texture[${s}] "${e.name||e.uuid}", Current: ${u}x${a}, Max: ${o.lods[0]?.width}x${o.lods[0]?.height}, uuid: ${e.uuid}`,o,e)}e.source&&(e.source[ve]=o);const n=o.guid;m.assignLODInformation(t,e,n,r,s),m.lodInfos.set(n,o),m.lowresCache.set(n,new WeakRef(e))};static registerMesh=(t,e,r,s,o,n)=>{const u=r.geometry;if(!u){g&&console.warn("gltf-progressive: Register mesh without geometry");return}u.userData||(u.userData={}),g&&console.log("> Progressive: register mesh "+r.name,{index:o,uuid:r.uuid},n,r),m.assignLODInformation(t,u,e,s,o),m.lodInfos.set(e,n);let a=m.lowresCache.get(e)?.deref();a?a.push(r.geometry):a=[r.geometry],m.lowresCache.set(e,new WeakRef(a)),s>0&&!K(r)&&$e(r,u);for(const l of W)l.onRegisteredNewMesh?.(r,n)};static dispose(t){if(t){this.lodInfos.delete(t);const e=this.lowresCache.get(t);if(e){const r=e.deref();if(r){if(r.isTexture){const s=r;this.textureRefCounts.delete(s.uuid),s.dispose()}else if(Array.isArray(r))for(const s of r)s.dispose()}this.lowresCache.delete(t)}for(const[r,s]of this.cache)r.includes(t)&&(this._disposeCacheEntry(s),this.cache.delete(r))}else{this.lodInfos.clear();for(const[,e]of this.lowresCache){const r=e.deref();if(r){if(r.isTexture){const s=r;this.textureRefCounts.delete(s.uuid),s.dispose()}else if(Array.isArray(r))for(const s of r)s.dispose()}}this.lowresCache.clear();for(const[,e]of this.cache)this._disposeCacheEntry(e);this.cache.clear(),this.textureRefCounts.clear(),this.trackedTextureSlots=new WeakMap,this.pendingTextureSlotRequests=new WeakMap}}static _disposeCacheEntry(t){if(t instanceof WeakRef){const e=t.deref();e&&(e.isTexture&&this.textureRefCounts.delete(e.uuid),e.dispose())}else t.then(e=>{if(e)if(Array.isArray(e))for(const r of e)r.dispose();else e.isTexture&&this.textureRefCounts.delete(e.uuid),e.dispose()}).catch(()=>{})}static lodInfos=new Map;static cache=new Map;static lowresCache=new Map;static textureRefCounts=new Map;static _resourceRegistry=new FinalizationRegistry(t=>{const e=m.cache.get(t);(g||re)&&console.debug(`[gltf-progressive] Memory: Resource GC'd
|
|
2
|
+
${t}`),e instanceof WeakRef&&(e.deref()||(m.cache.delete(t),(g||re)&&console.log("[gltf-progressive] \u21AA Cache entry deleted (GC)")))});static trackTextureUsage(t){const e=t.uuid,r=this.textureRefCounts.get(e)||0;this.textureRefCounts.set(e,r+1),g==="verbose"&&console.log(`[gltf-progressive] Track texture ${e}, refCount: ${r} \u2192 ${r+1}`)}static untrackTextureUsage(t){const e=t.uuid,r=this.textureRefCounts.get(e);if(!r)return(g==="verbose"||re)&&o("[gltf-progressive] Memory: Untrack untracked texture (dispose immediately)",0),t.dispose(),!0;const s=r-1;if(s<=0)return this.textureRefCounts.delete(e),(g||re)&&o("[gltf-progressive] Memory: Dispose texture",s),t.dispose(),!0;return this.textureRefCounts.set(e,s),g==="verbose"&&o("[gltf-progressive] Memory: Untrack texture",s),!1;function o(n,u){const a=t.image?.width||t.source?.data?.width||0,l=t.image?.height||t.source?.data?.height||0,d=a&&l?`${a}x${l}`:"N/A";let h="N/A";a&&l&&(h=`~${(gt(t)/(1024*1024)).toFixed(2)} MB`),console.log(`${n} \u2014 ${t.name} ${d} (${h}), refCount: ${r} \u2192 ${u}
|
|
3
|
+
${e}`)}}static workers=[];static _workersIndex=0;static async getOrLoadLOD(t,e){const r=g=="verbose",s=this.getAssignedLODInformation(t);if(!s)return g&&console.warn(`[gltf-progressive] No LOD information found: ${t.name}, uuid: ${t.uuid}, type: ${t.type}`,t),null;const o=s?.key;let n;if(t.isTexture===!0){const u=t;u.source&&u.source[ve]&&(n=u.source[ve])}if(n||(n=m.lodInfos.get(o)),!n)g&&console.warn(`Can not load LOD ${e}: no LOD info found for "${o}" ${t.name}`,t.type,m.lodInfos);else{if(e>0){let l=!1;const d=Array.isArray(n.lods);if(d&&e>=n.lods.length?l=!0:d||(l=!0),l){const h=this.lowresCache.get(o);if(h){const y=h.deref();if(y)return y;this.lowresCache.delete(o),g&&console.log(`[gltf-progressive] Lowres cache entry was GC'd: ${o}`)}return null}}const u=Array.isArray(n.lods)?n.lods[e]?.path:n.lods;if(!u)return g&&!n["missing:uri"]&&(n["missing:uri"]=!0,console.warn("Missing uri for progressive asset for LOD "+e,n)),null;const a=dt(s.url,u);if(a.endsWith(".glb")||a.endsWith(".gltf")){if(!n.guid)return console.warn("missing pointer for glb/gltf texture",n),null;const l=a+"_"+n.guid,d=await this.tryResolveLODCacheEntry(this.cache.get(l),l,a,t,e,r);if(d.found)return d.value;const h=await this.queue.slot(a),y=await this.tryResolveLODCacheEntry(this.cache.get(l),l,a,t,e,r);if(y.found)return y.value;if(!h.use)return g&&console.log(`LOD ${e} was aborted: ${a}`),null;const f=n,M=new Promise(async(w,C)=>{if(Lt){const L=await(await vt({})).load(a);if(L.textures.length>0)for(const x of L.textures){let v=x.texture;return m.assignLODInformation(s.url,v,o,e,void 0),t instanceof I&&(v=this.copySettings(t,v)),v&&(v.guid=f.guid),w(v)}if(L.geometries.length>0){const x=new Array;for(const v of L.geometries){const O=v.geometry;m.assignLODInformation(s.url,O,o,e,v.primitiveIndex),x.push(O)}return w(x)}return w(null)}const R=new de;he(R),g&&(await new Promise(L=>setTimeout(L,1e3)),r&&console.warn("Start loading (delayed) "+a,f.guid));let B=a;if(f&&Array.isArray(f.lods)){const L=f.lods[e];L.hash&&(B+="?v="+L.hash)}const p=await R.loadAsync(B).catch(L=>(console.error(`Error loading LOD ${e} from ${a}
|
|
4
|
+
`,L),w(null)));if(!p)return w(null);const b=p.parser;r&&console.log("Loading finished "+a,f.guid);let D=0;if(p.parser.json.textures){let L=!1;for(const x of p.parser.json.textures){if(x?.extensions){const v=x?.extensions[$];if(v?.guid&&v.guid===f.guid){L=!0;break}}D++}if(L){let x=await b.getDependency("texture",D);return x&&m.assignLODInformation(s.url,x,o,e,void 0),r&&console.log('change "'+t.name+'" \u2192 "'+x.name+'"',a,D,x,l),t instanceof I&&(x=this.copySettings(t,x)),x&&(x.guid=f.guid),w(x)}else g&&console.warn("Could not find texture with guid",f.guid,p.parser.json)}if(D=0,p.parser.json.meshes){let L=!1;for(const x of p.parser.json.meshes){if(x?.extensions){const v=x?.extensions[$];if(v?.guid&&v.guid===f.guid){L=!0;break}}D++}if(L){const x=await b.getDependency("mesh",D);if(r&&console.log(`Loaded Mesh "${x.name}"`,a,D,x,l),x.isMesh===!0){const v=x.geometry;return m.assignLODInformation(s.url,v,o,e,0),w(v)}else{const v=new Array;for(let O=0;O<x.children.length;O++){const H=x.children[O];if(H.isMesh===!0){const F=H.geometry;m.assignLODInformation(s.url,F,o,e,O),v.push(F)}}return w(v)}}else g&&console.warn("Could not find mesh with guid",f.guid,p.parser.json)}return w(null)});this.cache.set(l,M),h.use(M);const c=await M;return c!=null?c instanceof I?(this.cache.set(l,new WeakRef(c)),m._resourceRegistry.register(c,l)):Array.isArray(c)?this.cache.set(l,Promise.resolve(c)):this.cache.set(l,Promise.resolve(c)):this.cache.set(l,Promise.resolve(null)),c}else if(t instanceof I){r&&console.log("Load texture from uri: "+a);const l=await new tt().loadAsync(a);return l?(l.guid=n.guid,l.flipY=!1,l.needsUpdate=!0,l.colorSpace=t.colorSpace,r&&console.log(n,l)):g&&console.warn("failed loading",a),l}}return null}static async tryResolveLODCacheEntry(t,e,r,s,o,n){if(t===void 0)return{found:!1};if(n&&console.log(`LOD ${o} was already loading/loaded: ${e}`),t instanceof WeakRef){const l=t.deref();if(l){let d=l,h=!1;if(d instanceof I&&s instanceof I?d.image?.data||d.source?.data?d=this.copySettings(s,d):h=!0:d instanceof q&&s instanceof q&&(d.attributes.position?.array||(h=!0)),!h)return{found:!0,value:d}}return this.cache.delete(e),g&&console.log(`[gltf-progressive] Re-loading GC'd/disposed resource: ${e}`),{found:!1}}let u=await t.catch(l=>(console.error(`Error loading LOD ${o} from ${r}
|
|
5
|
+
`,l),null)),a=!1;return u==null||(u instanceof I&&s instanceof I?u.image?.data||u.source?.data?u=this.copySettings(s,u):(a=!0,this.cache.delete(e)):u instanceof q&&s instanceof q&&(u.attributes.position?.array||(a=!0,this.cache.delete(e)))),a?{found:!1}:{found:!0,value:u}}static _queue;static get queue(){return this._queue??=new ht(pe()?20:50,{debug:g!=!1})}static assignLODInformation(t,e,r,s,o){if(!e)return;e.userData||(e.userData={});const n=new bt(t,r,s,o);e.userData.LODS=n,"source"in e&&typeof e.source=="object"&&(e.source.LODS=n)}static getAssignedLODInformation(t){return t?t.userData?.LODS?t.userData.LODS:"source"in t&&t.source?.LODS?t.source.LODS:null:null}static copySettings(t,e){return e?(g==="verbose"&&console.debug(`Copy texture settings
|
|
6
6
|
`,t.uuid,`
|
|
7
|
-
`,e.uuid),e=e.clone(),e.offset=t.offset,e.repeat=t.repeat,e.colorSpace=t.colorSpace,e.magFilter=t.magFilter,e.minFilter=t.minFilter,e.wrapS=t.wrapS,e.wrapT=t.wrapT,e.flipY=t.flipY,e.anisotropy=t.anisotropy,e.mipmaps||(e.generateMipmaps=t.generateMipmaps),e):t}}class gt{url;key;level;index;constructor(t,e,s,o){this.url=t,this.key=e,this.level=s,o!=null&&(this.index=o)}}class pe{static addPromise=(t,e,s,o)=>{o.forEach(r=>{r.add(t,e,s)})};ready;get awaitedCount(){return this._addedCount}get resolvedCount(){return this._resolvedCount}get currentlyAwaiting(){return this._awaiting.length}_resolve;_signal;_frame_start;_frames_to_capture;_resolved=!1;_addedCount=0;_resolvedCount=0;_awaiting=[];_maxPromisesPerObject=1;constructor(t,e){const s=Math.max(e.frames??2,2);this._frame_start=e.waitForFirstCapture?void 0:t,this._frames_to_capture=s,this.ready=new Promise(o=>{this._resolve=o}),this.ready.finally(()=>{this._resolved=!0,this._awaiting.length=0}),this._signal=e.signal,this._signal?.addEventListener("abort",()=>{this.resolveNow()}),this._maxPromisesPerObject=Math.max(1,e.maxPromisesPerObject??1)}_currentFrame=0;update(t){this._currentFrame=t,this._frame_start===void 0&&this._addedCount>0&&(this._frame_start=t),(this._signal?.aborted||this._awaiting.length===0&&this._frame_start!==void 0&&t>this._frame_start+this._frames_to_capture)&&this.resolveNow()}_seen=new WeakMap;add(t,e,s){if(this._resolved){h&&console.warn("PromiseGroup: Trying to add a promise to a resolved group, ignoring.");return}if(!(this._frame_start!==void 0&&this._currentFrame>this._frame_start+this._frames_to_capture)){if(this._maxPromisesPerObject>=1)if(this._seen.has(e)){let o=this._seen.get(e);if(o>=this._maxPromisesPerObject){h&&console.warn("PromiseGroup: Already awaiting object ignoring new promise for it.");return}this._seen.set(e,o+1)}else this._seen.set(e,1);this._awaiting.push(s),this._addedCount++,s.finally(()=>{this._resolvedCount++,this._awaiting.splice(this._awaiting.indexOf(s),1)})}}resolveNow(){this._resolved||this._resolve?.({awaited_count:this._addedCount,resolved_count:this._resolvedCount,cancelled:this._signal?.aborted??!1})}}const E=N("debugprogressive"),ft=N("noprogressive"),xe=Symbol("Needle:LODSManager"),ye=Symbol("Needle:LODState"),W=Symbol("Needle:CurrentLOD"),O={mesh_lod:-1,texture_lod:-1};class v{static debugDrawLine;static getObjectLODState(t){return t[ye]}static addPlugin(t){j.push(t)}static removePlugin(t){const e=j.indexOf(t);e>=0&&j.splice(e,1)}static get(t,e){if(t[xe])return console.debug("[gltf-progressive] LODsManager already exists for this renderer"),t[xe];const s=new v(t,{engine:"unknown",...e});return t[xe]=s,s}renderer;context;projectionScreenMatrix=new be;get plugins(){return j}overrideLodLevel=void 0;targetTriangleDensity=2e5;skinnedMeshAutoUpdateBoundsInterval=30;updateInterval="auto";#e=1;pause=!1;manual=!1;_newPromiseGroups=[];_promiseGroupIds=0;awaitLoading(t){const e=this._promiseGroupIds++,s=new pe(this.#r,{...t});this._newPromiseGroups.push(s);const o=performance.now();return s.ready.finally(()=>{const r=this._newPromiseGroups.indexOf(s);r>=0&&(this._newPromiseGroups.splice(r,1),Pe()&&performance.measure("LODsManager:awaitLoading",{start:o,detail:{id:e,name:t?.name,awaited:s.awaitedCount,resolved:s.resolvedCount}}))}),s.ready}_postprocessPromiseGroups(){if(this._newPromiseGroups.length!==0)for(let t=this._newPromiseGroups.length-1;t>=0;t--)this._newPromiseGroups[t].update(this.#r)}_lodchangedlisteners=[];addEventListener(t,e){t==="changed"&&this._lodchangedlisteners.push(e)}removeEventListener(t,e){if(t==="changed"){const s=this._lodchangedlisteners.indexOf(e);s>=0&&this._lodchangedlisteners.splice(s,1)}}constructor(t,e){this.renderer=t,this.context={...e}}#t;#n=new Ve;#r=0;#o=0;#i=0;#s=0;_fpsBuffer=[60,60,60,60,60];enable(){if(this.#t)return;console.debug("[gltf-progressive] Enabling LODsManager for renderer");let t=0;this.#t=this.renderer.render;const e=this;ee(this.renderer),this.renderer.render=function(s,o){const r=e.renderer.getRenderTarget();(r==null||"isXRRenderTarget"in r&&r.isXRRenderTarget)&&(t=0,e.#r+=1,e.#o=e.#n.getDelta(),e.#i+=e.#o,e._fpsBuffer.shift(),e._fpsBuffer.push(1/e.#o),e.#s=e._fpsBuffer.reduce((l,a)=>l+a)/e._fpsBuffer.length,E&&e.#r%200===0&&console.log("FPS",Math.round(e.#s),"Interval:",e.#e));const n=t++;e.#t.call(this,s,o),e.onAfterRender(s,o,n)}}disable(){this.#t&&(console.debug("[gltf-progressive] Disabling LODsManager for renderer"),this.renderer.render=this.#t,this.#t=void 0)}update(t,e){this.internalUpdate(t,e)}onAfterRender(t,e,s){if(this.pause)return;const o=this.renderer.renderLists.get(t,0).opaque;let r=!0;if(o.length===1){const n=o[0].material;(n.name==="EffectMaterial"||n.name==="CopyShader")&&(r=!1)}if((e.parent&&e.parent.type==="CubeCamera"||s>=1&&e.type==="OrthographicCamera")&&(r=!1),r){if(ft||(this.updateInterval==="auto"?this.#s<40&&this.#e<10?(this.#e+=1,E&&console.warn("\u2193 Reducing LOD updates",this.#e,this.#s.toFixed(0))):this.#s>=60&&this.#e>1&&(this.#e-=1,E&&console.warn("\u2191 Increasing LOD updates",this.#e,this.#s.toFixed(0))):this.#e=this.updateInterval,this.#e>0&&this.#r%this.#e!=0))return;this.internalUpdate(t,e),this._postprocessPromiseGroups()}}internalUpdate(t,e){const s=this.renderer.renderLists.get(t,0),o=s.opaque;this.projectionScreenMatrix.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse);const r=this.targetTriangleDensity;for(const a of o){if(a.material&&(a.geometry?.type==="BoxGeometry"||a.geometry?.type==="BufferGeometry")&&(a.material.name==="SphericalGaussianBlur"||a.material.name=="BackgroundCubeMaterial"||a.material.name==="CubemapFromEquirect"||a.material.name==="EquirectangularToCubeUV")){E&&(a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]||(a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]=!0,console.warn("Ignoring skybox or BLIT object",a,a.material.name,a.material.type)));continue}switch(a.material.type){case"LineBasicMaterial":case"LineDashedMaterial":case"PointsMaterial":case"ShadowMaterial":case"MeshDistanceMaterial":case"MeshDepthMaterial":continue}if(E==="color"&&a.material&&!a.object.progressive_debug_color){a.object.progressive_debug_color=!0;const y=Math.random()*16777215,p=new Xe({color:y});a.object.material=p}const u=a.object;(u instanceof F||u.isMesh)&&this.updateLODs(t,e,u,r)}const n=s.transparent;for(const a of n){const u=a.object;(u instanceof F||u.isMesh)&&this.updateLODs(t,e,u,r)}const l=s.transmissive;for(const a of l){const u=a.object;(u instanceof F||u.isMesh)&&this.updateLODs(t,e,u,r)}}updateLODs(t,e,s,o){s.userData||(s.userData={});let r=s[ye];if(r||(r=new mt,s[ye]=r),r.frames++<2)return;for(const l of j)l.onBeforeUpdateLOD?.(this.renderer,t,e,s);const n=this.overrideLodLevel!==void 0?this.overrideLodLevel:q;n>=0?(O.mesh_lod=n,O.texture_lod=n):(this.calculateLodLevel(e,s,r,o,O),O.mesh_lod=Math.round(O.mesh_lod),O.texture_lod=Math.round(O.texture_lod)),O.mesh_lod>=0&&this.loadProgressiveMeshes(s,O.mesh_lod),s.material&&O.texture_lod>=0&&this.loadProgressiveTextures(s.material,O.texture_lod,n),h&&s.material&&!s.isGizmo&&ke(s.material);for(const l of j)l.onAfterUpdatedLOD?.(this.renderer,t,e,s,O);r.lastLodLevel_Mesh=O.mesh_lod,r.lastLodLevel_Texture=O.texture_lod}loadProgressiveTextures(t,e,s){if(!t)return;if(Array.isArray(t)){for(const r of t)this.loadProgressiveTextures(r,e);return}let o=!1;if((t[W]===void 0||e<t[W])&&(o=!0),s!==void 0&&s>=0&&(o=t[W]!=s,e=s),o){t[W]=e;const r=f.assignTextureLOD(t,e).then(n=>{this._lodchangedlisteners.forEach(l=>l({type:"texture",level:e,object:t}))});pe.addPromise("texture",t,r,this._newPromiseGroups)}}loadProgressiveMeshes(t,e){if(!t)return Promise.resolve(null);let s=t[W]!==e;const o=t["DEBUG:LOD"];if(o!=null&&(s=t[W]!=o,e=o),s){t[W]=e;const r=t.geometry,n=f.assignMeshLOD(t,e).then(l=>(l&&t[W]==e&&r!=t.geometry&&this._lodchangedlisteners.forEach(a=>a({type:"mesh",level:e,object:t})),l));return pe.addPromise("mesh",t,n,this._newPromiseGroups),n}return Promise.resolve(null)}_sphere=new _e;_tempBox=new ie;_tempBox2=new ie;tempMatrix=new be;_tempWorldPosition=new A;_tempBoxSize=new A;_tempBox2Size=new A;static corner0=new A;static corner1=new A;static corner2=new A;static corner3=new A;static _tempPtInside=new A;static isInside(t,e){const s=t.min,o=t.max,r=(s.x+o.x)*.5,n=(s.y+o.y)*.5;return this._tempPtInside.set(r,n,s.z).applyMatrix4(e).z<0}static skinnedMeshBoundsFrameOffsetCounter=0;static $skinnedMeshBoundsOffset=Symbol("gltf-progressive-skinnedMeshBoundsOffset");calculateLodLevel(t,e,s,o,r){if(!e){r.mesh_lod=-1,r.texture_lod=-1;return}if(!t){r.mesh_lod=-1,r.texture_lod=-1;return}let n=11,l=!1;if(E&&e["DEBUG:LOD"]!=null)return e["DEBUG:LOD"];const a=f.getMeshLODExtension(e.geometry)?.lods,u=f.getPrimitiveIndex(e.geometry),y=a&&a.length>0,p=f.getMaterialMinMaxLODsCount(e.material),w=p.min_count!==1/0&&p.min_count>=0&&p.max_count>=0;if(!y&&!w){r.mesh_lod=0,r.texture_lod=0;return}y||(l=!0,n=0);const P=this.renderer.domElement.clientHeight||this.renderer.domElement.height;let b=e.geometry.boundingBox;if(e.type==="SkinnedMesh"){const c=e;if(!c.boundingBox)c.computeBoundingBox();else if(this.skinnedMeshAutoUpdateBoundsInterval>0){if(!c[v.$skinnedMeshBoundsOffset]){const L=v.skinnedMeshBoundsFrameOffsetCounter++;c[v.$skinnedMeshBoundsOffset]=L}const x=c[v.$skinnedMeshBoundsOffset];if((s.frames+x)%this.skinnedMeshAutoUpdateBoundsInterval===0){const L=V(c),C=c.geometry;L&&(c.geometry=L),c.computeBoundingBox(),c.geometry=C}}b=c.boundingBox}if(b){const c=t;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 g=t.getWorldPosition(this._tempWorldPosition);if(this._sphere.containsPoint(g)){r.mesh_lod=0,r.texture_lod=0;return}}if(this._tempBox.copy(b),this._tempBox.applyMatrix4(e.matrixWorld),c.isPerspectiveCamera&&v.isInside(this._tempBox,this.projectionScreenMatrix)){r.mesh_lod=0,r.texture_lod=0;return}if(this._tempBox.applyMatrix4(this.projectionScreenMatrix),this.renderer.xr.enabled&&c.isPerspectiveCamera&&c.fov>70){const g=this._tempBox.min,d=this._tempBox.max;let m=g.x,_=g.y,S=d.x,G=d.y;const Q=2,oe=1.5,J=(g.x+d.x)*.5,Z=(g.y+d.y)*.5;m=(m-J)*Q+J,_=(_-Z)*Q+Z,S=(S-J)*Q+J,G=(G-Z)*Q+Z;const Ge=m<0&&S>0?0:Math.min(Math.abs(g.x),Math.abs(d.x)),Ne=_<0&&G>0?0:Math.min(Math.abs(g.y),Math.abs(d.y)),ne=Math.max(Ge,Ne);s.lastCentrality=(oe-ne)*(oe-ne)*(oe-ne)}else s.lastCentrality=1;const x=this._tempBox.getSize(this._tempBoxSize);x.multiplyScalar(.5),screen.availHeight>0&&P>0&&x.multiplyScalar(P/screen.availHeight),t.isPerspectiveCamera?x.x*=t.aspect:t.isOrthographicCamera;const L=t.matrixWorldInverse,C=this._tempBox2;C.copy(b),C.applyMatrix4(e.matrixWorld),C.applyMatrix4(L);const M=C.getSize(this._tempBox2Size),R=Math.max(M.x,M.y);if(Math.max(x.x,x.y)!=0&&R!=0&&(x.z=M.z/Math.max(M.x,M.y)*Math.max(x.x,x.y)),s.lastScreenCoverage=Math.max(x.x,x.y,x.z),s.lastScreenspaceVolume.copy(x),s.lastScreenCoverage*=s.lastCentrality,E&&v.debugDrawLine){const g=this.tempMatrix.copy(this.projectionScreenMatrix);g.invert();const d=v.corner0,m=v.corner1,_=v.corner2,S=v.corner3;d.copy(this._tempBox.min),m.copy(this._tempBox.max),m.x=d.x,_.copy(this._tempBox.max),_.y=d.y,S.copy(this._tempBox.max);const G=(d.z+S.z)*.5;d.z=m.z=_.z=S.z=G,d.applyMatrix4(g),m.applyMatrix4(g),_.applyMatrix4(g),S.applyMatrix4(g),v.debugDrawLine(d,m,255),v.debugDrawLine(d,_,255),v.debugDrawLine(m,S,255),v.debugDrawLine(_,S,255)}let D=999;if(a&&s.lastScreenCoverage>0)for(let g=0;g<a.length;g++){const d=a[g],m=(d.densities?.[u]||d.density||1e-5)/s.lastScreenCoverage;if(u>0&&Pe()&&!d.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.")),m<o){D=g;break}}D<n&&(n=D,l=!0)}if(l?r.mesh_lod=n:r.mesh_lod=s.lastLodLevel_Mesh,E&&r.mesh_lod!=s.lastLodLevel_Mesh){const c=a?.[r.mesh_lod];c&&console.log(`Mesh LOD changed: ${s.lastLodLevel_Mesh} \u2192 ${r.mesh_lod} (density: ${c.densities?.[u].toFixed(0)}) | ${e.name}`)}if(w){const c="saveData"in globalThis.navigator&&globalThis.navigator.saveData===!0;if(s.lastLodLevel_Texture<0){if(r.texture_lod=p.max_count-1,E){const x=p.lods[p.max_count-1];E&&console.log(`First Texture LOD ${r.texture_lod} (${x.max_height}px) - ${e.name}`)}}else{const x=s.lastScreenspaceVolume.x+s.lastScreenspaceVolume.y+s.lastScreenspaceVolume.z;let L=s.lastScreenCoverage*4;this.context?.engine==="model-viewer"&&(L*=1.5);const C=P/window.devicePixelRatio*L;let M=!1;for(let R=p.lods.length-1;R>=0;R--){const D=p.lods[R];if(!(c&&D.max_height>=2048)&&!(he()&&D.max_height>4096)&&(D.max_height>C||!M&&R===0)){if(M=!0,r.texture_lod=R,E&&r.texture_lod<s.lastLodLevel_Texture){const g=D.max_height;console.log(`Texture LOD changed: ${s.lastLodLevel_Texture} \u2192 ${r.texture_lod} = ${g}px
|
|
8
|
-
Screensize: ${
|
|
9
|
-
${e.name}`)}break}}}}else
|
|
10
|
-
`,i.getAttribute("src"));let t=null,e=null,
|
|
7
|
+
`,e.uuid),e=e.clone(),e.offset=t.offset,e.repeat=t.repeat,e.colorSpace=t.colorSpace,e.magFilter=t.magFilter,e.minFilter=t.minFilter,e.wrapS=t.wrapS,e.wrapT=t.wrapT,e.flipY=t.flipY,e.anisotropy=t.anisotropy,e.mipmaps||(e.generateMipmaps=t.generateMipmaps),e):t}}class bt{url;key;level;index;constructor(t,e,r,s){this.url=t,this.key=e,this.level=r,s!=null&&(this.index=s)}}class le{static addPromise=(t,e,r,s)=>{s.forEach(o=>{o.add(t,e,r)})};ready;get awaitedCount(){return this._addedCount}get resolvedCount(){return this._resolvedCount}get currentlyAwaiting(){return this._awaiting.length}_resolve;_signal;_frame_start;_frames_to_capture;_resolved=!1;_addedCount=0;_resolvedCount=0;_awaiting=[];_maxPromisesPerObject=1;constructor(t,e){const r=Math.max(e.frames??2,2);this._frame_start=e.waitForFirstCapture?void 0:t,this._frames_to_capture=r,this.ready=new Promise(s=>{this._resolve=s}),this.ready.finally(()=>{this._resolved=!0,this._awaiting.length=0}),this._signal=e.signal,this._signal?.addEventListener("abort",()=>{this.resolveNow()}),this._maxPromisesPerObject=Math.max(1,e.maxPromisesPerObject??1)}_currentFrame=0;update(t){this._currentFrame=t,this._frame_start===void 0&&this._addedCount>0&&(this._frame_start=t),(this._signal?.aborted||this._awaiting.length===0&&this._frame_start!==void 0&&t>this._frame_start+this._frames_to_capture)&&this.resolveNow()}_seen=new WeakMap;add(t,e,r){if(this._resolved){g&&console.warn("PromiseGroup: Trying to add a promise to a resolved group, ignoring.");return}if(!(this._frame_start!==void 0&&this._currentFrame>this._frame_start+this._frames_to_capture)){if(this._maxPromisesPerObject>=1)if(this._seen.has(e)){const s=this._seen.get(e);if(s>=this._maxPromisesPerObject){g&&console.warn("PromiseGroup: Already awaiting object ignoring new promise for it.");return}this._seen.set(e,s+1)}else this._seen.set(e,1);this._awaiting.push(r),this._addedCount++,r.finally(()=>{this._resolvedCount++,this._awaiting.splice(this._awaiting.indexOf(r),1)})}}resolveNow(){this._resolved||this._resolve?.({awaited_count:this._addedCount,resolved_count:this._resolvedCount,cancelled:this._signal?.aborted??!1})}}const E=N("debugprogressive"),Mt=E==="colors",Dt=N("noprogressive"),we=Symbol("Needle:LODSManager"),Le=Symbol("Needle:LODState"),j=Symbol("Needle:CurrentLOD"),_={mesh_lod:-1,texture_lod:-1},_t=new Se,be=[3526751,11065402,15978811,15897394,15749691,11032304,4827122,3332036,16739229,7306743,14053330,3516499,12035359,14703919,3963096,42662,14100029,8344319,4633680,16229681,3120096,12076434,9083434,2060171,15751837,10182117,48121,62932,16704576,15817653,5083278,5592405],Me=new oe,U=new oe,Ne=new oe,Tt=new S,Ot=new S,St=new ke,G=new S,Y=new S,Q=new S,J=new S;function kt(i,t){const e=i.min,r=i.max,s=(e.x+r.x)*.5,o=(e.y+r.y)*.5;return G.set(s,o,e.z).applyMatrix4(t).z<0}function We(i){const{geometry:t,matrixWorld:e,camera:r,projectionScreenMatrix:s,desiredDensity:o,canvasHeight:n=0,currentLevel:u=-1,xrEnabled:a=!1,debugDrawLine:l,warnMissingPrimitiveDensities:d=!1}=i,h=m.getMeshLODExtension(t)?.lods,y=m.getPrimitiveIndex(t),f=i.target??{level:u,primitiveIndex:y,screenCoverage:0,screenspaceVolume:new S,centrality:1};if(f.level=u,f.primitiveIndex=y,f.screenCoverage=0,f.screenspaceVolume.set(0,0,0),f.centrality=1,!h?.length)return f;let M=i.boundingBox??t.boundingBox;if(M||(t.computeBoundingBox(),M=t.boundingBox),!M)return f;if(Me.copy(M).applyMatrix4(e),r.isPerspectiveCamera&&kt(Me,s))return f.level=0,f.screenCoverage=1/0,f.screenspaceVolume.set(1/0,1/0,1/0),f;if(U.copy(Me).applyMatrix4(s),a&&r.isPerspectiveCamera&&r.fov>70){const p=U.min,b=U.max;let D=p.x,L=p.y,x=b.x,v=b.y;const O=2,H=1.5,F=(p.x+b.x)*.5,se=(p.y+b.y)*.5;D=(D-F)*O+F,L=(L-se)*O+se,x=(x-F)*O+F,v=(v-se)*O+se;const He=D<0&&x>0?0:Math.min(Math.abs(p.x),Math.abs(b.x)),Ke=L<0&&v>0?0:Math.min(Math.abs(p.y),Math.abs(b.y)),ce=Math.max(He,Ke);f.centrality=(H-ce)*(H-ce)*(H-ce)}const c=U.getSize(Tt);c.multiplyScalar(.5),globalThis.screen?.availHeight>0&&n>0&&c.multiplyScalar(n/globalThis.screen.availHeight),r.isPerspectiveCamera&&(c.x*=r.aspect),Ne.copy(M).applyMatrix4(e).applyMatrix4(r.matrixWorldInverse);const w=Ne.getSize(Ot),C=Math.max(c.x,c.y),R=Math.max(w.x,w.y);C!==0&&R!==0&&(c.z=w.z/R*C);const B=Math.max(c.x,c.y,c.z)*f.centrality;if(f.screenCoverage=B,f.screenspaceVolume.copy(c),B<=0)return f;if(l){const p=St.copy(s);p.invert(),G.copy(U.min),Y.copy(U.max),Y.x=G.x,Q.copy(U.max),Q.y=G.y,J.copy(U.max);const b=(G.z+J.z)*.5;G.z=Y.z=Q.z=J.z=b,G.applyMatrix4(p),Y.applyMatrix4(p),Q.applyMatrix4(p),J.applyMatrix4(p),l(G,Y,255),l(G,Q,255),l(Y,J,255),l(Q,J,255)}for(let p=0;p<h.length;p++){const b=h[p],D=b.densities?.[y]||b.density||1e-5;if(y>0&&d&&Ie()&&!b.densities&&!globalThis["NEEDLE:MISSING_LOD_PRIMITIVE_DENSITIES"]&&(globalThis["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.")),D/B<o){f.level=p;break}}return f}class k{static debugDrawLine;static getObjectLODState(t){return t[Le]}static addPlugin(t){W.push(t)}static removePlugin(t){const e=W.indexOf(t);e>=0&&W.splice(e,1)}static get(t,e){if(t[we])return console.debug("[gltf-progressive] LODsManager already exists for this renderer"),t[we];const r=new k(t,{engine:"unknown",...e});return t[we]=r,r}renderer;context;projectionScreenMatrix=new ke;get plugins(){return W}overrideLodLevel=void 0;targetTriangleDensity=2e5;skinnedMeshAutoUpdateBoundsInterval=30;updateInterval="auto";#e=1;pause=!1;manual=!1;_newPromiseGroups=[];_promiseGroupIds=0;awaitLoading(t){const e=this._promiseGroupIds++,r=new le(this.#s,{...t});this._newPromiseGroups.push(r);const s=performance.now();return r.ready.finally(()=>{const o=this._newPromiseGroups.indexOf(r);o>=0&&(this._newPromiseGroups.splice(o,1),Ie()&&performance.measure("LODsManager:awaitLoading",{start:s,detail:{id:e,name:t?.name,awaited:r.awaitedCount,resolved:r.resolvedCount}}))}),r.ready}trackLoadingPromise(t,e,r){return le.addPromise(t,e,r,this._newPromiseGroups),r}_postprocessPromiseGroups(){if(this._newPromiseGroups.length!==0)for(let t=this._newPromiseGroups.length-1;t>=0;t--)this._newPromiseGroups[t].update(this.#s)}_lodchangedlisteners=[];addEventListener(t,e){return t==="changed"?(this._lodchangedlisteners.push(e),()=>{this.removeEventListener(t,e)}):()=>{}}removeEventListener(t,e){let r=!1;if(t==="changed"){const s=this._lodchangedlisteners.indexOf(e);s>=0&&(this._lodchangedlisteners.splice(s,1),r=!0)}return r}constructor(t,e){this.renderer=t,this.context={...e}}#t;#n=new rt;#s=0;#o=0;#i=0;#r=0;_fpsBuffer=[60,60,60,60,60];enable(){if(this.#t)return;console.debug("[gltf-progressive] Enabling LODsManager for renderer");let t=0;this.#t=this.renderer.render;const e=this;ne(this.renderer),this.renderer.render=function(r,s){const o=e.renderer.getRenderTarget();(o==null||"isXRRenderTarget"in o&&o.isXRRenderTarget)&&(t=0,e.#s+=1,e.#o=e.#n.getDelta(),e.#i+=e.#o,e._fpsBuffer.shift(),e._fpsBuffer.push(1/e.#o),e.#r=e._fpsBuffer.reduce((u,a)=>u+a)/e._fpsBuffer.length,E&&e.#s%200===0&&console.log("FPS",Math.round(e.#r),"Interval:",e.#e));const n=t++;e.#t.call(this,r,s),e.onAfterRender(r,s,n)}}disable(){this.#t&&(console.debug("[gltf-progressive] Disabling LODsManager for renderer"),this.renderer.render=this.#t,this.#t=void 0)}update(t,e){this.internalUpdate(t,e)}onAfterRender(t,e,r){if(this.pause)return;const s=this.renderer.renderLists.get(t,0).opaque;let o=!0;if(s.length===1){const n=s[0].material;(n.name==="EffectMaterial"||n.name==="CopyShader")&&(o=!1)}if((e.parent&&e.parent.type==="CubeCamera"||r>=1&&e.type==="OrthographicCamera")&&(o=!1),o){if(Dt||(this.updateInterval==="auto"?this.#r<40&&this.#e<10?(this.#e+=1,E&&console.warn("\u2193 Reducing LOD updates",this.#e,this.#r.toFixed(0))):this.#r>=60&&this.#e>1&&(this.#e-=1,E&&console.warn("\u2191 Increasing LOD updates",this.#e,this.#r.toFixed(0))):this.#e=this.updateInterval,this.#e>0&&this.#s%this.#e!=0))return;this.internalUpdate(t,e),this._postprocessPromiseGroups()}}internalUpdate(t,e){const r=this.renderer.renderLists.get(t,0),s=r.opaque;this.projectionScreenMatrix.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse);const o=this.targetTriangleDensity;for(const a of s){if(a.material&&(a.geometry?.type==="BoxGeometry"||a.geometry?.type==="BufferGeometry")&&(a.material.name==="SphericalGaussianBlur"||a.material.name=="BackgroundCubeMaterial"||a.material.name==="CubemapFromEquirect"||a.material.name==="EquirectangularToCubeUV")){E&&(a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]||(a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]=!0,console.warn("Ignoring skybox or BLIT object",a,a.material.name,a.material.type)));continue}switch(a.material.type){case"LineBasicMaterial":case"LineDashedMaterial":case"PointsMaterial":case"ShadowMaterial":case"MeshDistanceMaterial":case"MeshDepthMaterial":continue}const l=a.object;(l instanceof z||l.isMesh)&&this.updateLODs(t,e,l,o)}const n=r.transparent;for(const a of n){const l=a.object;(l instanceof z||l.isMesh)&&this.updateLODs(t,e,l,o)}const u=r.transmissive;for(const a of u){const l=a.object;(l instanceof z||l.isMesh)&&this.updateLODs(t,e,l,o)}}updateLODs(t,e,r,s){r.userData||(r.userData={});let o=r[Le];if(o||(o=new Ct,r[Le]=o),o.frames++<2)return;for(const u of W)u.onBeforeUpdateLOD?.(this.renderer,t,e,r);const n=this.overrideLodLevel!==void 0?this.overrideLodLevel:X;n>=0?(_.mesh_lod=n,_.texture_lod=n):(this.calculateLodLevel(e,r,o,s,_),_.mesh_lod=Math.round(_.mesh_lod),_.texture_lod=Math.round(_.texture_lod)),_.mesh_lod>=0&&this.loadProgressiveMeshes(r,_.mesh_lod),r.material&&_.texture_lod>=0&&this.loadProgressiveTextures(r.material,_.texture_lod,n),g&&r.material&&!r.isGizmo&&Ge(r.material),Mt&&r.material&&!r.isGizmo&&!r.isBatchedMesh&&je(r.material,_.mesh_lod);for(const u of W)u.onAfterUpdatedLOD?.(this.renderer,t,e,r,_);o.lastLodLevel_Mesh=_.mesh_lod,o.lastLodLevel_Texture=_.texture_lod}loadProgressiveTextures(t,e,r){if(!t)return;if(Array.isArray(t)){for(const n of t)this.loadProgressiveTextures(n,e,r);return}let s=!1;(t[j]===void 0||e<t[j])&&(s=!0);const o=r!==void 0&&r>=0;if(o&&(s=t[j]!=r,e=r),s){t[j]=e;const n=o?{force:!0}:void 0,u=m.assignTextureLOD(t,e,n).then(a=>{this._lodchangedlisteners.forEach(l=>l({type:"texture",level:e,object:t}))});le.addPromise("texture",t,u,this._newPromiseGroups)}}loadProgressiveMeshes(t,e){if(!t)return Promise.resolve(null);let r=t[j]!==e;const s=t["DEBUG:LOD"];if(s!=null&&(r=t[j]!=s,e=s),r){t[j]=e;const o=t.geometry,n=m.assignMeshLOD(t,e).then(u=>(u&&t[j]==e&&o!=t.geometry&&this._lodchangedlisteners.forEach(a=>a({type:"mesh",level:e,object:t})),u));return le.addPromise("mesh",t,n,this._newPromiseGroups),n}return Promise.resolve(null)}_sphere=new Oe;_tempWorldPosition=new S;static skinnedMeshBoundsFrameOffsetCounter=0;static $skinnedMeshBoundsOffset=Symbol("gltf-progressive-skinnedMeshBoundsOffset");calculateLodLevel(t,e,r,s,o){if(!e){o.mesh_lod=-1,o.texture_lod=-1;return}if(!t){o.mesh_lod=-1,o.texture_lod=-1;return}let n=11,u=!1;if(E&&e["DEBUG:LOD"]!=null)return e["DEBUG:LOD"];const a=m.getMeshLODExtension(e.geometry)?.lods,l=m.getPrimitiveIndex(e.geometry),d=a&&a.length>0,h=m.getMaterialMinMaxLODsCount(e.material),y=h.min_count!==1/0&&h.min_count>=0&&h.max_count>=0;if(!d&&!y){o.mesh_lod=0,o.texture_lod=0;return}d||(u=!0,n=0);const f=this.renderer.domElement.clientHeight||this.renderer.domElement.height;let M=e.geometry.boundingBox;if(e.type==="SkinnedMesh"){const c=e;if(!c.boundingBox)c.computeBoundingBox();else if(this.skinnedMeshAutoUpdateBoundsInterval>0){if(!c[k.$skinnedMeshBoundsOffset]){const C=k.skinnedMeshBoundsFrameOffsetCounter++;c[k.$skinnedMeshBoundsOffset]=C}const w=c[k.$skinnedMeshBoundsOffset];if((r.frames+w)%this.skinnedMeshAutoUpdateBoundsInterval===0){const C=K(c),R=c.geometry;C&&(c.geometry=C),c.computeBoundingBox(),c.geometry=R}}M=c.boundingBox}if(M){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 w=t.getWorldPosition(this._tempWorldPosition);if(this._sphere.containsPoint(w)){o.mesh_lod=0,o.texture_lod=0;return}}const c=We({geometry:e.geometry,matrixWorld:e.matrixWorld,camera:t,projectionScreenMatrix:this.projectionScreenMatrix,desiredDensity:s,canvasHeight:f,currentLevel:r.lastLodLevel_Mesh,boundingBox:M,xrEnabled:this.renderer.xr.enabled,debugDrawLine:E?k.debugDrawLine:void 0,warnMissingPrimitiveDensities:!0});if(r.lastCentrality=c.centrality,r.lastScreenCoverage=c.screenCoverage,r.lastScreenspaceVolume.copy(c.screenspaceVolume),c.screenCoverage===1/0){o.mesh_lod=0,o.texture_lod=0;return}c.level>=0&&c.level<n&&(n=c.level,u=!0)}if(u?o.mesh_lod=n:o.mesh_lod=r.lastLodLevel_Mesh,E&&o.mesh_lod!=r.lastLodLevel_Mesh){const c=a?.[o.mesh_lod];c&&console.log(`Mesh LOD changed: ${r.lastLodLevel_Mesh} \u2192 ${o.mesh_lod} (density: ${c.densities?.[l].toFixed(0)}) | ${e.name}`)}if(y){const c="saveData"in globalThis.navigator&&globalThis.navigator.saveData===!0;if(r.lastLodLevel_Texture<0){if(o.texture_lod=h.max_count-1,E){const w=h.lods[h.max_count-1];E&&console.log(`First Texture LOD ${o.texture_lod} (${w.max_height}px) - ${e.name}`)}}else{const w=r.lastScreenspaceVolume.x+r.lastScreenspaceVolume.y+r.lastScreenspaceVolume.z;let C=r.lastScreenCoverage*4;this.context?.engine==="model-viewer"&&(C*=1.5);const R=f/window.devicePixelRatio*C;let B=!1;for(let p=h.lods.length-1;p>=0;p--){const b=h.lods[p];if(!(c&&b.max_height>=2048)&&!(pe()&&b.max_height>4096)&&(b.max_height>R||!B&&p===0)){if(B=!0,o.texture_lod=p,E&&o.texture_lod<r.lastLodLevel_Texture){const D=b.max_height;console.log(`Texture LOD changed: ${r.lastLodLevel_Texture} \u2192 ${o.texture_lod} = ${D}px
|
|
8
|
+
Screensize: ${R.toFixed(0)}px, Coverage: ${(100*r.lastScreenCoverage).toFixed(2)}%, Volume ${w.toFixed(1)}
|
|
9
|
+
${e.name}`)}break}}}}else o.texture_lod=0}}class Ct{frames=0;lastLodLevel_Mesh=-1;lastLodLevel_Texture=-1;lastScreenCoverage=0;lastScreenspaceVolume=new S;lastCentrality=0}function je(i,t){if(!(t<0)){if(Array.isArray(i)){for(const e of i)je(e,t);return}"color"in i&&i.color instanceof Se&&(i.color.copy(Ue(t,_t)),i.needsUpdate=!0)}}function Ue(i,t){const e=Math.max(0,Math.min(be.length-1,Math.floor(i)));return t.setHex(be[e])}const Fe=Symbol("NEEDLE_mesh_lod"),ue=Symbol("NEEDLE_texture_lod");let De=null;function _e(){const i=Pt();i&&(i.mapURLs(function(t){return qe(),t}),qe(),De?.disconnect(),De=new MutationObserver(t=>{t.forEach(e=>{e.addedNodes.forEach(r=>{r instanceof HTMLElement&&r.tagName.toLowerCase()==="model-viewer"&&Ve(r)})})}),De.observe(document,{childList:!0,subtree:!0}))}function Pt(){return typeof customElements>"u"?null:customElements.get("model-viewer")||(customElements.whenDefined("model-viewer").then(()=>{console.debug("[gltf-progressive] model-viewer defined"),_e()}),null)}function qe(){typeof document>"u"||document.querySelectorAll("model-viewer").forEach(i=>{Ve(i)})}const ze=new WeakSet;let At=0;function Ve(i){if(!i||ze.has(i))return null;ze.add(i),console.debug("[gltf-progressive] found new model-viewer..."+ ++At+`
|
|
10
|
+
`,i.getAttribute("src"));let t=null,e=null,r=null;for(let s=i;s!=null;s=Object.getPrototypeOf(s)){const o=Object.getOwnPropertySymbols(s),n=o.find(l=>l.toString()=="Symbol(renderer)"),u=o.find(l=>l.toString()=="Symbol(scene)"),a=o.find(l=>l.toString()=="Symbol(needsRender)");!t&&n!=null&&(t=i[n].threeRenderer),!e&&u!=null&&(e=i[u]),!r&&a!=null&&(r=i[a])}if(t&&e){let s=function(){if(r){let n=0;const u=setInterval(()=>{if(n++>5){clearInterval(u);return}r?.call(i)},300)}};console.debug("[gltf-progressive] setup model-viewer");const o=k.get(t,{engine:"model-viewer"});return k.addPlugin(new Et),o.enable(),o.addEventListener("changed",()=>{r?.call(i)}),i.addEventListener("model-visibility",n=>{n.detail.visible&&r?.call(i)}),i.addEventListener("load",()=>{s()}),()=>{o.disable()}}return null}class Et{_didWarnAboutMissingUrl=!1;onBeforeUpdateLOD(t,e,r,s){this.tryParseMeshLOD(e,s),this.tryParseTextureLOD(e,s)}getUrl(t){if(!t)return null;let e=t.getAttribute("src");return e||(e=t.src),e||(this._didWarnAboutMissingUrl||console.warn("No url found in modelviewer",t),this._didWarnAboutMissingUrl=!0),e}tryGetCurrentGLTF(t){return t._currentGLTF}tryGetCurrentModelViewer(t){return t.element}tryParseTextureLOD(t,e){if(e[ue]==!0)return;e[ue]=!0;const r=this.tryGetCurrentGLTF(t),s=this.tryGetCurrentModelViewer(t),o=this.getUrl(s);if(o&&r&&e.material){let n=function(a){if(a[ue]==!0)return;a[ue]=!0,a.userData&&(a.userData.LOD=-1);const l=Object.keys(a);for(let d=0;d<l.length;d++){const h=l[d],y=a[h];if(y?.isTexture===!0){const f=y.userData?.associations?.textures;if(f==null)continue;const M=r.parser.json.textures[f];if(!M){console.warn("Texture data not found for texture index "+f);continue}if(M?.extensions?.[$]){const c=M.extensions[$];c&&o&&m.registerTexture(o,y,c.lods.length,f,c)}}}};const u=e.material;if(Array.isArray(u))for(const a of u)n(a);else n(u)}}tryParseMeshLOD(t,e){if(e[Fe]==!0)return;e[Fe]=!0;const r=this.tryGetCurrentModelViewer(t),s=this.getUrl(r);if(!s)return;const o=e.userData?.gltfExtensions?.[$];if(o&&s){const n=e.uuid;m.registerMesh(s,n,e,0,o.lods.length,o)}}}function Xe(...i){let t,e,r,s;switch(i.length){case 2:[r,e]=i,s={};break;case 3:[r,e,s]=i;break;case 4:[t,e,r,s]=i;break;default:throw new Error("Invalid arguments")}ne(e),he(r),me(r,{progressive:!0,...s?.hints}),r.register(n=>new m(n));const o=k.get(e);return s?.enableLODsManager!==!1&&o.enable(),o}if(_e(),!mt){const i={gltfProgressive:{useNeedleProgressive:Xe,LODsManager:k,configureLoader:me,getRaycastMesh:K,useRaycastMeshes:Be}};if(!globalThis.Needle)globalThis.Needle=i;else for(const t in i)globalThis.Needle[t]=i[t]}export{$ as EXTENSION_NAME,k as LODsManager,m as NEEDLE_progressive,Ce as VERSION,he as addDracoAndKTX2Loaders,We as calculateMeshLODLevel,me as configureLoader,ne as createLoaders,Ue as getLODColor,K as getRaycastMesh,be as lodDebugColors,_e as patchModelViewer,$e as registerRaycastMesh,Ae as setDracoDecoderLocation,Ee as setKTX2TranscoderLocation,Xe as useNeedleProgressive,Be as useRaycastMeshes};
|
package/gltf-progressive.umd.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var Ue=Object.create;var ve=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var qe=Object.getPrototypeOf,Ve=Object.prototype.hasOwnProperty;var Ne=(i,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ze(t))!Ve.call(i,r)&&r!==e&&ve(i,r,{get:()=>t[r],enumerable:!(s=We(t,r))||s.enumerable});return i};var Ee=(i,t,e)=>(e=i!=null?Ue(qe(i)):{},Ne(t||!i||!i.__esModule?ve(e,"default",{value:i,enumerable:!0}):e,i));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("three"),me=require("three/examples/jsm/loaders/GLTFLoader.js"),je=require("three/examples/jsm/libs/meshopt_decoder.module.js"),Xe=require("three/examples/jsm/loaders/DRACOLoader.js"),Ke=require("three/examples/jsm/loaders/KTX2Loader.js");var ne=typeof document<"u"?document.currentScript:null;const Se="";globalThis.GLTF_PROGRESSIVE_VERSION=Se;console.debug("[gltf-progressive] version -");let I="https://www.gstatic.com/draco/versioned/decoders/1.5.7/",N="https://cdn.needle.tools/static/three/0.179.1/basis2/";const Ye=I,He=N,Te=new URL(I+"draco_decoder.js");Te.searchParams.append("range","true");fetch(Te,{method:"GET",headers:{Range:"bytes=0-1"}}).catch(i=>{console.debug(`Failed to fetch remote Draco decoder from ${I} (offline: ${typeof navigator<"u"?navigator.onLine:"unknown"})`),I===Ye&&Pe("./include/draco/"),N===He&&Ce("./include/ktx2/")}).finally(()=>{Ae()});const Qe=()=>({dracoDecoderPath:I,ktx2TranscoderPath:N});function Pe(i){I=i,A&&A[he]!=I?(console.debug("Updating Draco decoder path to "+i),A[he]=I,A.setDecoderPath(I),A.preload()):console.debug("Setting Draco decoder path to "+i)}function Ce(i){N=i,$&&$.transcoderPath!=N?(console.debug("Updating KTX2 transcoder path to "+i),$.setTranscoderPath(N),$.init()):console.debug("Setting KTX2 transcoder path to "+i)}function re(i){return Ae(),i?$.detectSupport(i):i!==null&&console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures might fail"),{dracoLoader:A,ktx2Loader:$,meshoptDecoder:se}}function ye(i){i.dracoLoader||i.setDRACOLoader(A),i.ktx2Loader||i.setKTX2Loader($),i.meshoptDecoder||i.setMeshoptDecoder(se)}const he=Symbol("dracoDecoderPath");let A,se,$;function Ae(){A||(A=new Xe.DRACOLoader,A[he]=I,A.setDecoderPath(I),A.setDecoderConfig({type:"js"}),A.preload()),$||($=new Ke.KTX2Loader,$.setTranscoderPath(N),$.init()),se||(se=je.MeshoptDecoder)}const ge=new WeakMap;function xe(i,t){let e=ge.get(i);e?e=Object.assign(e,t):e=t,ge.set(i,e)}const Je=me.GLTFLoader.prototype.load;function Ze(...i){const t=ge.get(this);let e=i[0];const s=new URL(e,window.location.href);if(s.hostname.endsWith("needle.tools")){const o=t?.progressive!==void 0?t.progressive:!0,n=t?.usecase?t.usecase:"default";o?this.requestHeader.Accept=`*/*;progressive=allowed;usecase=${n}`:this.requestHeader.Accept=`*/*;usecase=${n}`,e=s.toString()}return i[0]=e,Je?.call(this,...i)}me.GLTFLoader.prototype.load=Ze;z("debugprogressive");function z(i){if(typeof window>"u")return!1;const e=new URL(window.location.href).searchParams.get(i);return e==null||e==="0"||e==="false"?!1:e===""?!0:e}function et(i,t){if(t===void 0||i===void 0||t.startsWith("./")||t.startsWith("http")||t.startsWith("data:")||t.startsWith("blob:"))return t;const e=i.lastIndexOf("/");if(e>=0){const s=i.substring(0,e+1);for(;s.endsWith("/")&&t.startsWith("/");)t=t.substring(1);return s+t}return t}function we(){return K!==void 0||(K=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent),z("debugprogressive")&&console.log("[glTF Progressive]: isMobileDevice",K)),K}let K;function Me(){if(typeof window>"u")return!1;const i=new URL(window.location.href),t=i.hostname==="localhost"||/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(i.hostname);return i.hostname==="127.0.0.1"||t}class tt{constructor(t,e={}){this.maxConcurrent=t,this.debug=e.debug??!1,typeof window<"u"&&window.requestAnimationFrame(this.tick)}_running=new Map;_queue=[];debug=!1;tick=()=>{this.internalUpdate(),setTimeout(this.tick,10)};slot(t){return this.debug&&console.debug(`[PromiseQueue]: Requesting slot for key ${t}, running: ${this._running.size}, waiting: ${this._queue.length}`),new Promise(e=>{this._queue.push({key:t,resolve:e})})}add(t,e){this._running.has(t)||(this._running.set(t,e),e.finally(()=>{this._running.delete(t),this.debug&&console.debug(`[PromiseQueue]: Promise finished now running: ${this._running.size}, waiting: ${this._queue.length}. (finished ${t})`)}),this.debug&&console.debug(`[PromiseQueue]: Added new promise, now running: ${this._running.size}, waiting: ${this._queue.length}. (added ${t})`))}internalUpdate(){const t=this.maxConcurrent-this._running.size;for(let e=0;e<t&&this._queue.length>0;e++){this.debug&&console.debug(`[PromiseQueue]: Running ${this._running.size} promises, waiting for ${this._queue.length} more.`);const{key:s,resolve:r}=this._queue.shift();r({use:o=>this.add(s,o)})}}}function st(i){const t=i.image?.width??0,e=i.image?.height??0,s=i.image?.depth??1,r=Math.floor(Math.log2(Math.max(t,e,s)))+1,o=rt(i);return t*e*s*o*(1-Math.pow(.25,r))/(1-.25)}function rt(i){let t=4;const e=i.format;e===1024||e===1025?t=1:e===1026||e===1027?t=2:e===1022||e===1029?t=3:(e===1023||e===1033)&&(t=4);let s=1;const r=i.type;return r===1009||r===1010?s=1:r===1011||r===1012?s=2:r===1013||r===1014||r===1015?s=4:r===1016&&(s=2),t*s}const ot=typeof window>"u"&&typeof document>"u",pe=Symbol("needle:raycast-mesh");function j(i){return i?.[pe]instanceof c.BufferGeometry?i[pe]:null}function Re(i,t){if((i.type==="Mesh"||i.type==="SkinnedMesh")&&!j(i)){const s=it(t);s.userData={isRaycastMesh:!0},i[pe]=s}}function ke(i=!0){if(i){if(Y)return;const t=Y=c.Mesh.prototype.raycast;c.Mesh.prototype.raycast=function(e,s){const r=this,o=j(r);let n;o&&r.isMesh&&(n=r.geometry,r.geometry=o),t.call(this,e,s),n&&(r.geometry=n)}}else{if(!Y)return;c.Mesh.prototype.raycast=Y,Y=null}}let Y=null;function it(i){const t=new c.BufferGeometry;for(const e in i.attributes)t.setAttribute(e,i.getAttribute(e));return t.setIndex(i.getIndex()),t}const W=new Array,h=z("debugprogressive");let Q,V=-1;if(h){let i=function(){V+=1,V>=t&&(V=-1),console.log(`Toggle LOD level [${V}]`)},t=6;window.addEventListener("keyup",e=>{e.key==="p"&&i(),e.key==="w"&&(Q=!Q,console.log(`Toggle wireframe [${Q}]`));const s=parseInt(e.key);!isNaN(s)&&s>=0&&(V=s,console.log(`Set LOD level to [${V}]`))})}function Ie(i){if(h&&Q!==void 0)if(Array.isArray(i))for(const t of i)Ie(t);else i&&"wireframe"in i&&(i.wireframe=Q===!0)}const H=new Array;let nt=0;const at=we()?2:10;function lt(i){if(H.length<at){const s=H.length;h&&console.warn(`[Worker] Creating new worker #${s}`);const r=Le.createWorker(i||{});return H.push(r),r}const t=nt++%H.length;return H[t]}class Le{constructor(t,e){this.worker=t,this._debug=e.debug??!1,t.onmessage=s=>{const r=s.data;switch(this._debug&&console.log("[Worker] EVENT",r),r.type){case"loaded-gltf":for(const o of this._running)if(o.url===r.result.url){ut(r.result),o.resolve(r.result);const n=o.url;n.startsWith("blob:")&&URL.revokeObjectURL(n)}}},t.onerror=s=>{console.error("[Worker] Error in gltf-progressive worker:",s)},t.postMessage({type:"init"})}static async createWorker(t){const e=new Worker(new URL("/assets/gltf-progressive.worker-CCrD-Ycm.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ne&&ne.tagName.toUpperCase()==="SCRIPT"&&ne.src||new URL("gltf-progressive.umd.cjs",document.baseURI).href),{type:"module"});return new Le(e,t)}_running=[];_webglRenderer=null;async load(t,e){const s=Qe();let r=e?.renderer;r||(this._webglRenderer??=(async()=>{const{WebGLRenderer:u}=await import("three");return new u})(),r=await this._webglRenderer);const l=re(r).ktx2Loader.workerConfig;t instanceof URL?t=t.toString():t.startsWith("file:")?t=URL.createObjectURL(new Blob([t])):!t.startsWith("blob:")&&!t.startsWith("http:")&&!t.startsWith("https:")&&(t=new URL(t,window.location.href).toString());const a={type:"load",url:t,dracoDecoderPath:s.dracoDecoderPath,ktx2TranscoderPath:s.ktx2TranscoderPath,ktx2LoaderConfig:l};return this._debug&&console.debug("[Worker] Sending load request",a),this.worker.postMessage(a),new Promise(u=>{this._running.push({url:t.toString(),resolve:u})})}_debug=!1}function ut(i){for(const t of i.geometries){const e=t.geometry,s=new c.BufferGeometry;if(s.name=e.name||"",e.index){const r=e.index;s.setIndex(ae(r))}for(const r in e.attributes){const o=e.attributes[r],n=ae(o);s.setAttribute(r,n)}if(e.morphAttributes)for(const r in e.morphAttributes){const n=e.morphAttributes[r].map(l=>ae(l));s.morphAttributes[r]=n}if(s.morphTargetsRelative=e.morphTargetsRelative??!1,s.boundingBox=new c.Box3,s.boundingBox.min=new c.Vector3(e.boundingBox?.min.x,e.boundingBox?.min.y,e.boundingBox?.min.z),s.boundingBox.max=new c.Vector3(e.boundingBox?.max.x,e.boundingBox?.max.y,e.boundingBox?.max.z),s.boundingSphere=new c.Sphere(new c.Vector3(e.boundingSphere?.center.x,e.boundingSphere?.center.y,e.boundingSphere?.center.z),e.boundingSphere?.radius),e.groups)for(const r of e.groups)s.addGroup(r.start,r.count,r.materialIndex);e.userData&&(s.userData=e.userData),t.geometry=s}for(const t of i.textures){const e=t.texture;let s=null;if(e.isCompressedTexture){const r=e.mipmaps,o=e.image?.width||e.source?.data?.width||-1,n=e.image?.height||e.source?.data?.height||-1;s=new c.CompressedTexture(r,o,n,e.format,e.type,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.anisotropy,e.colorSpace)}else s=new c.Texture(e.image,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.colorSpace),s.mipmaps=e.mipmaps,s.channel=e.channel,s.source.data=e.source.data,s.flipY=e.flipY,s.premultiplyAlpha=e.premultiplyAlpha,s.unpackAlignment=e.unpackAlignment,s.matrix=new c.Matrix3(...e.matrix.elements);if(!s){console.error("[Worker] Failed to create new texture from received data. Texture is not a CompressedTexture or Texture.");continue}t.texture=s}return i}function ae(i){let t=i;if("isInterleavedBufferAttribute"in i&&i.isInterleavedBufferAttribute){const e=i.data,s=e.array,r=new c.InterleavedBuffer(s,e.stride);t=new c.InterleavedBufferAttribute(r,i.itemSize,s.byteOffset,i.normalized),t.offset=i.offset}else"isBufferAttribute"in i&&i.isBufferAttribute&&(t=new c.BufferAttribute(i.array,i.itemSize,i.normalized),t.usage=i.usage,t.gpuType=i.gpuType,t.updateRanges=i.updateRanges);return t}const ct=z("gltf-progressive-worker");z("gltf-progressive-reduce-mipmaps");const E=z("gltf-progressive-gc"),le=Symbol("needle-progressive-texture"),F="NEEDLE_progressive";class m{get name(){return F}static getMeshLODExtension(t){const e=this.getAssignedLODInformation(t);return e?.key?this.lodInfos.get(e.key):null}static getPrimitiveIndex(t){const e=this.getAssignedLODInformation(t)?.index;return e??-1}static getMaterialMinMaxLODsCount(t,e){const s=this,r="LODS:minmax",o=t[r];if(o!=null)return o;if(e||(e={min_count:1/0,max_count:0,lods:[]}),Array.isArray(t)){for(const l of t)this.getMaterialMinMaxLODsCount(l,e);return t[r]=e,e}if(h==="verbose"&&console.log("getMaterialMinMaxLODsCount",t),t.type==="ShaderMaterial"||t.type==="RawShaderMaterial"){const l=t;for(const a of Object.keys(l.uniforms)){const u=l.uniforms[a].value;u?.isTexture===!0&&n(u,e)}}else if(t.isMaterial)for(const l of Object.keys(t)){const a=t[l];a?.isTexture===!0&&n(a,e)}else h&&console.warn(`[getMaterialMinMaxLODsCount] Unsupported material type: ${t.type}`);return t[r]=e,e;function n(l,a){const u=s.getAssignedLODInformation(l);if(u){const d=s.lodInfos.get(u.key);if(d&&d.lods){a.min_count=Math.min(a.min_count,d.lods.length),a.max_count=Math.max(a.max_count,d.lods.length);for(let x=0;x<d.lods.length;x++){const L=d.lods[x];L.width&&(a.lods[x]=a.lods[x]||{min_height:1/0,max_height:0},a.lods[x].min_height=Math.min(a.lods[x].min_height,L.height),a.lods[x].max_height=Math.max(a.lods[x].max_height,L.height))}}}}}static hasLODLevelAvailable(t,e){if(Array.isArray(t)){for(const o of t)if(this.hasLODLevelAvailable(o,e))return!0;return!1}if(t.isMaterial===!0){for(const o of Object.keys(t)){const n=t[o];if(n&&n.isTexture&&this.hasLODLevelAvailable(n,e))return!0}return!1}else if(t.isGroup===!0){for(const o of t.children)if(o.isMesh===!0&&this.hasLODLevelAvailable(o,e))return!0}let s,r;if(t.isMesh?s=t.geometry:(t.isBufferGeometry||t.isTexture)&&(s=t),s&&s?.userData?.LODS){const o=s.userData.LODS;if(r=this.lodInfos.get(o.key),e===void 0)return r!=null;if(r)return Array.isArray(r.lods)?e<r.lods.length:e===0}return!1}static assignMeshLOD(t,e){if(!t)return Promise.resolve(null);if(t instanceof c.Mesh||t.isMesh===!0){const s=t.geometry,r=this.getAssignedLODInformation(s);if(!r)return Promise.resolve(null);for(const o of W)o.onBeforeGetLODMesh?.(t,e);return t["LOD:requested level"]=e,m.getOrLoadLOD(s,e).then(o=>{if(Array.isArray(o)){const n=r.index||0;o=o[n]}return t["LOD:requested level"]===e&&(delete t["LOD:requested level"],o&&s!=o&&(o?.isBufferGeometry?t.geometry=o:h&&console.error("Invalid LOD geometry",o))),o}).catch(o=>(console.error("Error loading mesh LOD",t,o),null))}else h&&console.error("Invalid call to assignMeshLOD: Request mesh LOD but the object is not a mesh",t);return Promise.resolve(null)}static assignTextureLOD(t,e=0){if(!t)return Promise.resolve(null);if(t.isMesh===!0){const s=t;if(Array.isArray(s.material)){const r=new Array;for(const o of s.material){const n=this.assignTextureLOD(o,e);r.push(n)}return Promise.all(r).then(o=>{const n=new Array;for(const l of o)Array.isArray(l)&&n.push(...l);return n})}else return this.assignTextureLOD(s.material,e)}if(t.isMaterial===!0){const s=t,r=[],o=new Array;if(s.uniforms&&(s.isRawShaderMaterial||s.isShaderMaterial===!0)){const n=s;for(const l of Object.keys(n.uniforms)){const a=n.uniforms[l].value;if(a?.isTexture===!0){const u=this.assignTextureLODForSlot(a,e,s,l).then(d=>(d&&n.uniforms[l].value!=d&&(n.uniforms[l].value=d,n.uniformsNeedUpdate=!0),d));r.push(u),o.push(l)}}}else for(const n of Object.keys(s)){const l=s[n];if(l?.isTexture===!0){const a=this.assignTextureLODForSlot(l,e,s,n);r.push(a),o.push(n)}}return Promise.all(r).then(n=>{const l=new Array;for(let a=0;a<n.length;a++){const u=n[a],d=o[a];u&&u.isTexture===!0?l.push({material:s,slot:d,texture:u,level:e}):l.push({material:s,slot:d,texture:null,level:e})}return l})}if(t instanceof c.Texture||t.isTexture===!0){const s=t;return this.assignTextureLODForSlot(s,e,null,null)}return Promise.resolve(null)}static set maxConcurrentLoadingTasks(t){m.queue.maxConcurrent=t}static get maxConcurrentLoadingTasks(){return m.queue.maxConcurrent}static assignTextureLODForSlot(t,e,s,r){return t?.isTexture!==!0?Promise.resolve(null):r==="glyphMap"?Promise.resolve(t):m.getOrLoadLOD(t,e).then(o=>{if(Array.isArray(o))return console.warn("Progressive: Got an array of textures for a texture slot, this should not happen..."),null;if(o?.isTexture===!0){if(o!=t&&s&&r){const n=s[r];if(n&&!h){const l=this.getAssignedLODInformation(n);if(l&&l?.level<e)return h==="verbose"&&console.warn("Assigned texture level is already higher: ",l.level,e,s,n,o),o&&o!==n&&((h||E)&&console.log(`[gltf-progressive] Disposing rejected lower-quality texture LOD ${e} (assigned is ${l.level})`,o.uuid),o.dispose()),null}if(this.trackTextureUsage(o),n&&n!==o&&this.untrackTextureUsage(n)&&(h||E)){const a=this.getAssignedLODInformation(n);console.log(`[gltf-progressive] Disposed old texture LOD ${a?.level??"?"} → ${e} for ${s.name||s.type}.${r}`,n.uuid)}s[r]=o}return o}else h=="verbose"&&console.warn("No LOD found for",t,e);return null}).catch(o=>(console.error("Error loading LOD",t,o),null))}parser;url;constructor(t){const e=t.options.path;h&&console.log("Progressive extension registered for",e),this.parser=t,this.url=e}_isLoadingMesh;loadMesh=t=>{if(this._isLoadingMesh)return null;const e=this.parser.json.meshes[t]?.extensions?.[F];return e?(this._isLoadingMesh=!0,this.parser.getDependency("mesh",t).then(s=>(this._isLoadingMesh=!1,s&&m.registerMesh(this.url,e.guid,s,e.lods?.length,0,e),s))):null};afterRoot(t){return h&&console.log("AFTER",this.url,t),this.parser.json.textures?.forEach((e,s)=>{if(e?.extensions){const r=e?.extensions[F];if(r){if(!r.lods){h&&console.warn("Texture has no LODs",r);return}let o=!1;for(const n of this.parser.associations.keys())n.isTexture===!0&&this.parser.associations.get(n)?.textures===s&&(o=!0,m.registerTexture(this.url,n,r.lods?.length,s,r));o||this.parser.getDependency("texture",s).then(n=>{n&&m.registerTexture(this.url,n,r.lods?.length,s,r)})}}}),this.parser.json.meshes?.forEach((e,s)=>{if(e?.extensions){const r=e?.extensions[F];if(r&&r.lods){for(const o of this.parser.associations.keys())if(o.isMesh){const n=this.parser.associations.get(o);n?.meshes===s&&m.registerMesh(this.url,r.guid,o,r.lods.length,n.primitives,r)}}}}),null}static registerTexture=(t,e,s,r,o)=>{if(!e){h&&console.error("!! gltf-progressive: Called register texture without texture");return}if(h){const l=e.image?.width||e.source?.data?.width||0,a=e.image?.height||e.source?.data?.height||0;console.log(`> gltf-progressive: register texture[${r}] "${e.name||e.uuid}", Current: ${l}x${a}, Max: ${o.lods[0]?.width}x${o.lods[0]?.height}, uuid: ${e.uuid}`,o,e)}e.source&&(e.source[le]=o);const n=o.guid;m.assignLODInformation(t,e,n,s,r),m.lodInfos.set(n,o),m.lowresCache.set(n,new WeakRef(e))};static registerMesh=(t,e,s,r,o,n)=>{const l=s.geometry;if(!l){h&&console.warn("gltf-progressive: Register mesh without geometry");return}l.userData||(l.userData={}),h&&console.log("> Progressive: register mesh "+s.name,{index:o,uuid:s.uuid},n,s),m.assignLODInformation(t,l,e,r,o),m.lodInfos.set(e,n);let u=m.lowresCache.get(e)?.deref();u?u.push(s.geometry):u=[s.geometry],m.lowresCache.set(e,new WeakRef(u)),r>0&&!j(s)&&Re(s,l);for(const d of W)d.onRegisteredNewMesh?.(s,n)};static dispose(t){if(t){this.lodInfos.delete(t);const e=this.lowresCache.get(t);if(e){const s=e.deref();if(s){if(s.isTexture){const r=s;this.textureRefCounts.delete(r.uuid),r.dispose()}else if(Array.isArray(s))for(const r of s)r.dispose()}this.lowresCache.delete(t)}for(const[s,r]of this.cache)s.includes(t)&&(this._disposeCacheEntry(r),this.cache.delete(s))}else{this.lodInfos.clear();for(const[,e]of this.lowresCache){const s=e.deref();if(s){if(s.isTexture){const r=s;this.textureRefCounts.delete(r.uuid),r.dispose()}else if(Array.isArray(s))for(const r of s)r.dispose()}}this.lowresCache.clear();for(const[,e]of this.cache)this._disposeCacheEntry(e);this.cache.clear(),this.textureRefCounts.clear()}}static _disposeCacheEntry(t){if(t instanceof WeakRef){const e=t.deref();e&&(e.isTexture&&this.textureRefCounts.delete(e.uuid),e.dispose())}else t.then(e=>{if(e)if(Array.isArray(e))for(const s of e)s.dispose();else e.isTexture&&this.textureRefCounts.delete(e.uuid),e.dispose()}).catch(()=>{})}static lodInfos=new Map;static cache=new Map;static lowresCache=new Map;static textureRefCounts=new Map;static _resourceRegistry=new FinalizationRegistry(t=>{const e=m.cache.get(t);(h||E)&&console.debug(`[gltf-progressive] Memory: Resource GC'd
|
|
2
|
-
${t}`),e instanceof WeakRef&&(e.deref()||(
|
|
3
|
-
${e}`)}}static workers=[];static _workersIndex=0;static async getOrLoadLOD(t,e){const s=h=="verbose",r=this.getAssignedLODInformation(t);if(!r)return h&&console.warn(`[gltf-progressive] No LOD information found: ${t.name}, uuid: ${t.uuid}, type: ${t.type}`,t),null;const
|
|
4
|
-
`,
|
|
5
|
-
`,
|
|
1
|
+
"use strict";var Ne=Object.create;var De=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var je=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,Ye=Object.prototype.hasOwnProperty;var He=(i,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of je(t))!Ye.call(i,r)&&r!==e&&De(i,r,{get:()=>t[r],enumerable:!(s=Xe(t,r))||s.enumerable});return i};var Qe=(i,t,e)=>(e=i!=null?Ne(Ke(i)):{},He(t||!i||!i.__esModule?De(e,"default",{value:i,enumerable:!0}):e,i));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("three"),xe=require("three/examples/jsm/loaders/GLTFLoader.js"),Je=require("three/examples/jsm/libs/meshopt_decoder.module.js"),Ze=require("three/examples/jsm/loaders/DRACOLoader.js"),et=require("three/examples/jsm/loaders/KTX2Loader.js");var ae=typeof document<"u"?document.currentScript:null;const Ce="";globalThis.GLTF_PROGRESSIVE_VERSION=Ce;console.debug("[gltf-progressive] version -");let I="https://www.gstatic.com/draco/versioned/decoders/1.5.7/",X="https://cdn.needle.tools/static/three/0.179.1/basis2/";const tt=I,st=X,Pe=new URL(I+"draco_decoder.js");Pe.searchParams.append("range","true");fetch(Pe,{method:"GET",headers:{Range:"bytes=0-1"}}).catch(i=>{console.debug(`Failed to fetch remote Draco decoder from ${I} (offline: ${typeof navigator<"u"?navigator.onLine:"unknown"})`),I===tt&&ke("./include/draco/"),X===st&&Re("./include/ktx2/")}).finally(()=>{Ae()});const rt=()=>({dracoDecoderPath:I,ktx2TranscoderPath:X});function ke(i){I=i,k&&k[ge]!=I?(console.debug("Updating Draco decoder path to "+i),k[ge]=I,k.setDecoderPath(I),k.preload()):console.debug("Setting Draco decoder path to "+i)}function Re(i){X=i,$&&$.transcoderPath!=X?(console.debug("Updating KTX2 transcoder path to "+i),$.setTranscoderPath(X),$.init()):console.debug("Setting KTX2 transcoder path to "+i)}function oe(i){return Ae(),i?$.detectSupport(i):i!==null&&console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures might fail"),{dracoLoader:k,ktx2Loader:$,meshoptDecoder:ne}}function we(i){i.dracoLoader||i.setDRACOLoader(k),i.ktx2Loader||i.setKTX2Loader($),i.meshoptDecoder||i.setMeshoptDecoder(ne)}const ge=Symbol("dracoDecoderPath");let k,ne,$;function Ae(){k||(k=new Ze.DRACOLoader,k[ge]=I,k.setDecoderPath(I),k.setDecoderConfig({type:"js"}),k.preload()),$||($=new et.KTX2Loader,$.setTranscoderPath(X),$.init()),ne||(ne=Je.MeshoptDecoder)}const pe=new WeakMap;function Le(i,t){let e=pe.get(i);e?e=Object.assign(e,t):e=t,pe.set(i,e)}const nt=xe.GLTFLoader.prototype.load;function ot(...i){const t=pe.get(this);let e=i[0];const s=new URL(e,window.location.href);if(s.hostname.endsWith("needle.tools")){const n=t?.progressive!==void 0?t.progressive:!0,o=t?.usecase?t.usecase:"default";n?this.requestHeader.Accept=`*/*;progressive=allowed;usecase=${o}`:this.requestHeader.Accept=`*/*;usecase=${o}`,e=s.toString()}return i[0]=e,nt?.call(this,...i)}xe.GLTFLoader.prototype.load=ot;z("debugprogressive");function z(i){if(typeof window>"u")return!1;const e=new URL(window.location.href).searchParams.get(i);return e==null||e==="0"||e==="false"?!1:e===""?!0:e}function it(i,t){if(t===void 0||i===void 0||t.startsWith("./")||t.startsWith("http")||t.startsWith("data:")||t.startsWith("blob:"))return t;const e=i.lastIndexOf("/");if(e>=0){const s=i.substring(0,e+1);for(;s.endsWith("/")&&t.startsWith("/");)t=t.substring(1);return s+t}return t}function ve(){return Q!==void 0||(Q=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent),z("debugprogressive")&&console.log("[glTF Progressive]: isMobileDevice",Q)),Q}let Q;function Ie(){if(typeof window>"u")return!1;const i=new URL(window.location.href),t=i.hostname==="localhost"||/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(i.hostname);return i.hostname==="127.0.0.1"||t}class at{constructor(t,e={}){this.maxConcurrent=t,this.debug=e.debug??!1,typeof window<"u"&&window.requestAnimationFrame(this.tick)}_running=new Map;_queue=[];debug=!1;tick=()=>{this.internalUpdate(),setTimeout(this.tick,10)};slot(t){return this.debug&&console.debug(`[PromiseQueue]: Requesting slot for key ${t}, running: ${this._running.size}, waiting: ${this._queue.length}`),new Promise(e=>{this._queue.push({key:t,resolve:e})})}add(t,e){this._running.has(t)||(this._running.set(t,e),e.finally(()=>{this._running.delete(t),this.debug&&console.debug(`[PromiseQueue]: Promise finished now running: ${this._running.size}, waiting: ${this._queue.length}. (finished ${t})`)}),this.debug&&console.debug(`[PromiseQueue]: Added new promise, now running: ${this._running.size}, waiting: ${this._queue.length}. (added ${t})`))}internalUpdate(){const t=this.maxConcurrent-this._running.size;for(let e=0;e<t&&this._queue.length>0;e++){this.debug&&console.debug(`[PromiseQueue]: Running ${this._running.size} promises, waiting for ${this._queue.length} more.`);const{key:s,resolve:r}=this._queue.shift();r({use:n=>this.add(s,n)})}}}function lt(i){const t=i.image?.width??0,e=i.image?.height??0,s=i.image?.depth??1,r=Math.floor(Math.log2(Math.max(t,e,s)))+1,n=ut(i);return t*e*s*n*(1-Math.pow(.25,r))/(1-.25)}function ut(i){let t=4;const e=i.format;e===1024||e===1025?t=1:e===1026||e===1027?t=2:e===1022||e===1029?t=3:(e===1023||e===1033)&&(t=4);let s=1;const r=i.type;return r===1009||r===1010?s=1:r===1011||r===1012?s=2:r===1013||r===1014||r===1015?s=4:r===1016&&(s=2),t*s}const ct=typeof window>"u"&&typeof document>"u",me=Symbol("needle:raycast-mesh");function H(i){return i?.[me]instanceof d.BufferGeometry?i[me]:null}function $e(i,t){if((i.type==="Mesh"||i.type==="SkinnedMesh")&&!H(i)){const s=dt(t);s.userData={isRaycastMesh:!0},i[me]=s}}function Be(i=!0){if(i){if(J)return;const t=J=d.Mesh.prototype.raycast;d.Mesh.prototype.raycast=function(e,s){const r=this,n=H(r);let o;n&&r.isMesh&&(o=r.geometry,r.geometry=n),t.call(this,e,s),o&&(r.geometry=o)}}else{if(!J)return;d.Mesh.prototype.raycast=J,J=null}}let J=null;function dt(i){const t=new d.BufferGeometry;for(const e in i.attributes)t.setAttribute(e,i.getAttribute(e));return t.setIndex(i.getIndex()),t}const V=new Array,h=z("debugprogressive");let te,N=-1;if(h){let i=function(){N+=1,N>=t&&(N=-1),console.log(`Toggle LOD level [${N}]`)};const t=6;window.addEventListener("keyup",e=>{e.key==="p"&&i(),e.key==="w"&&(te=!te,console.log(`Toggle wireframe [${te}]`));const s=parseInt(e.key);!isNaN(s)&&s>=0&&(N=s,console.log(`Set LOD level to [${N}]`))})}function Ge(i){if(h&&te!==void 0)if(Array.isArray(i))for(const t of i)Ge(t);else i&&"wireframe"in i&&(i.wireframe=te===!0)}const Z=new Array;let ft=0;const ht=ve()?2:10;function gt(i){if(Z.length<ht){const s=Z.length;h&&console.warn(`[Worker] Creating new worker #${s}`);const r=_e.createWorker(i||{});return Z.push(r),r}const t=ft++%Z.length;return Z[t]}class _e{constructor(t,e){this.worker=t,this._debug=e.debug??!1,t.onmessage=s=>{const r=s.data;switch(this._debug&&console.log("[Worker] EVENT",r),r.type){case"loaded-gltf":for(const n of this._running)if(n.url===r.result.url){pt(r.result),n.resolve(r.result);const o=n.url;o.startsWith("blob:")&&URL.revokeObjectURL(o)}}},t.onerror=s=>{console.error("[Worker] Error in gltf-progressive worker:",s)},t.postMessage({type:"init"})}static async createWorker(t){const e=new Worker(new URL("/assets/gltf-progressive.worker-CCrD-Ycm.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ae&&ae.tagName.toUpperCase()==="SCRIPT"&&ae.src||new URL("gltf-progressive.umd.cjs",document.baseURI).href),{type:"module"});return new _e(e,t)}_running=[];_webglRenderer=null;async load(t,e){const s=rt();let r=e?.renderer;r||(this._webglRenderer??=(async()=>{const{WebGLRenderer:l}=await import("three");return new l})(),r=await this._webglRenderer);const u=oe(r).ktx2Loader.workerConfig;t instanceof URL?t=t.toString():t.startsWith("file:")?t=URL.createObjectURL(new Blob([t])):!t.startsWith("blob:")&&!t.startsWith("http:")&&!t.startsWith("https:")&&(t=new URL(t,window.location.href).toString());const a={type:"load",url:t,dracoDecoderPath:s.dracoDecoderPath,ktx2TranscoderPath:s.ktx2TranscoderPath,ktx2LoaderConfig:u};return this._debug&&console.debug("[Worker] Sending load request",a),this.worker.postMessage(a),new Promise(l=>{this._running.push({url:t.toString(),resolve:l})})}_debug=!1}function pt(i){for(const t of i.geometries){const e=t.geometry,s=new d.BufferGeometry;if(s.name=e.name||"",e.index){const r=e.index;s.setIndex(le(r))}for(const r in e.attributes){const n=e.attributes[r],o=le(n);s.setAttribute(r,o)}if(e.morphAttributes)for(const r in e.morphAttributes){const o=e.morphAttributes[r].map(u=>le(u));s.morphAttributes[r]=o}if(s.morphTargetsRelative=e.morphTargetsRelative??!1,s.boundingBox=new d.Box3,s.boundingBox.min=new d.Vector3(e.boundingBox?.min.x,e.boundingBox?.min.y,e.boundingBox?.min.z),s.boundingBox.max=new d.Vector3(e.boundingBox?.max.x,e.boundingBox?.max.y,e.boundingBox?.max.z),s.boundingSphere=new d.Sphere(new d.Vector3(e.boundingSphere?.center.x,e.boundingSphere?.center.y,e.boundingSphere?.center.z),e.boundingSphere?.radius),e.groups)for(const r of e.groups)s.addGroup(r.start,r.count,r.materialIndex);e.userData&&(s.userData=e.userData),t.geometry=s}for(const t of i.textures){const e=t.texture;let s=null;if(e.isCompressedTexture){const r=e.mipmaps,n=e.image?.width||e.source?.data?.width||-1,o=e.image?.height||e.source?.data?.height||-1;s=new d.CompressedTexture(r,n,o,e.format,e.type,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.anisotropy,e.colorSpace)}else s=new d.Texture(e.image,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.colorSpace),s.mipmaps=e.mipmaps,s.channel=e.channel,s.source.data=e.source.data,s.flipY=e.flipY,s.premultiplyAlpha=e.premultiplyAlpha,s.unpackAlignment=e.unpackAlignment,s.matrix=new d.Matrix3(...e.matrix.elements);if(!s){console.error("[Worker] Failed to create new texture from received data. Texture is not a CompressedTexture or Texture.");continue}t.texture=s}return i}function le(i){let t=i;if("isInterleavedBufferAttribute"in i&&i.isInterleavedBufferAttribute){const e=i.data,s=e.array,r=new d.InterleavedBuffer(s,e.stride);t=new d.InterleavedBufferAttribute(r,i.itemSize,s.byteOffset,i.normalized),t.offset=i.offset}else"isBufferAttribute"in i&&i.isBufferAttribute&&(t=new d.BufferAttribute(i.array,i.itemSize,i.normalized),t.usage=i.usage,t.gpuType=i.gpuType,t.updateRanges=i.updateRanges);return t}const mt=z("gltf-progressive-worker");z("gltf-progressive-reduce-mipmaps");const ee=z("gltf-progressive-gc"),ue=Symbol("needle-progressive-texture"),G="NEEDLE_progressive";class g{get name(){return G}static getMeshLODExtension(t){const e=this.getAssignedLODInformation(t);return e?.key?this.lodInfos.get(e.key):null}static getPrimitiveIndex(t){const e=this.getAssignedLODInformation(t)?.index;return e??-1}static getMaterialMinMaxLODsCount(t,e){const s=this,r="LODS:minmax",n=t[r];if(n!=null)return n;if(e||(e={min_count:1/0,max_count:0,lods:[]}),Array.isArray(t)){for(const u of t)this.getMaterialMinMaxLODsCount(u,e);return t[r]=e,e}if(h==="verbose"&&console.log("getMaterialMinMaxLODsCount",t),t.type==="ShaderMaterial"||t.type==="RawShaderMaterial"){const u=t;for(const a of Object.keys(u.uniforms)){const l=u.uniforms[a].value;l?.isTexture===!0&&o(l,e)}}else if(t.isMaterial)for(const u of Object.keys(t)){const a=t[u];a?.isTexture===!0&&o(a,e)}else h&&console.warn(`[getMaterialMinMaxLODsCount] Unsupported material type: ${t.type}`);return t[r]=e,e;function o(u,a){const l=s.getAssignedLODInformation(u);if(l){const c=s.lodInfos.get(l.key);if(c&&c.lods){a.min_count=Math.min(a.min_count,c.lods.length),a.max_count=Math.max(a.max_count,c.lods.length);for(let f=0;f<c.lods.length;f++){const p=c.lods[f];p.width&&(a.lods[f]=a.lods[f]||{min_height:1/0,max_height:0},a.lods[f].min_height=Math.min(a.lods[f].min_height,p.height),a.lods[f].max_height=Math.max(a.lods[f].max_height,p.height))}}}}}static hasLODLevelAvailable(t,e){if(Array.isArray(t)){for(const n of t)if(this.hasLODLevelAvailable(n,e))return!0;return!1}if(t.isMaterial===!0){for(const n of Object.keys(t)){const o=t[n];if(o&&o.isTexture&&this.hasLODLevelAvailable(o,e))return!0}return!1}else if(t.isGroup===!0){for(const n of t.children)if(n.isMesh===!0&&this.hasLODLevelAvailable(n,e))return!0}let s,r;if(t.isMesh?s=t.geometry:(t.isBufferGeometry||t.isTexture)&&(s=t),s&&s?.userData?.LODS){const n=s.userData.LODS;if(r=this.lodInfos.get(n.key),e===void 0)return r!=null;if(r)return Array.isArray(r.lods)?e<r.lods.length:e===0}return!1}static assignMeshLOD(t,e,s){if(!t)return Promise.resolve(null);if(t instanceof d.Mesh||t.isMesh===!0){const r=t.geometry,n=this.getAssignedLODInformation(r);if(!n)return Promise.resolve(null);for(const o of V)o.onBeforeGetLODMesh?.(t,e);return t["LOD:requested level"]=e,g.getOrLoadLOD(r,e).then(o=>{if(Array.isArray(o)){const u=n.index||0;o=o[u]}return t["LOD:requested level"]===e&&(delete t["LOD:requested level"],o&&r!=o&&(o?.isBufferGeometry?typeof s?.apply=="function"?s.apply(o,e,t):s?.apply!==!1&&(t.geometry=o):h&&console.error("Invalid LOD geometry",o))),o}).catch(o=>(console.error("Error loading mesh LOD",t,o),null))}else h&&console.error("Invalid call to assignMeshLOD: Request mesh LOD but the object is not a mesh",t);return Promise.resolve(null)}static assignTextureLOD(t,e=0,s){if(!t)return Promise.resolve(null);const r=s?.force===!0;if(t.isMesh===!0){const n=t;if(Array.isArray(n.material)){const o=new Array;for(const u of n.material){const a=this.assignTextureLOD(u,e,s);o.push(a)}return Promise.all(o).then(u=>{const a=new Array;for(const l of u)Array.isArray(l)&&a.push(...l);return a})}else return this.assignTextureLOD(n.material,e,s)}if(t.isMaterial===!0){const n=t,o=[],u=new Array;if(this.trackCurrentMaterialTextureSlots(n),n.uniforms&&(n.isRawShaderMaterial||n.isShaderMaterial===!0)){const a=n;for(const l of Object.keys(a.uniforms)){const c=a.uniforms[l].value;if(c?.isTexture===!0){const f=this.assignTextureLODForSlot(c,e,n,l,r).then(p=>(p&&a.uniforms[l].value!=p&&(a.uniforms[l].value=p,a.uniformsNeedUpdate=!0),p));o.push(f),u.push(l)}}}else for(const a of Object.keys(n)){const l=n[a];if(l?.isTexture===!0){const c=this.assignTextureLODForSlot(l,e,n,a,r);o.push(c),u.push(a)}}return Promise.all(o).then(a=>{const l=new Array;for(let c=0;c<a.length;c++){const f=a[c],p=u[c];f&&f.isTexture===!0?l.push({material:n,slot:p,texture:f,level:e}):l.push({material:n,slot:p,texture:null,level:e})}return l})}if(t instanceof d.Texture||t.isTexture===!0){const n=t;return this.assignTextureLODForSlot(n,e,null,null,r)}return Promise.resolve(null)}static set maxConcurrentLoadingTasks(t){g.queue.maxConcurrent=t}static get maxConcurrentLoadingTasks(){return g.queue.maxConcurrent}static assignTextureLODForSlot(t,e,s,r,n){if(t?.isTexture!==!0)return Promise.resolve(null);if(r==="glyphMap")return Promise.resolve(t);const o=this.getAssignedLODInformation(t);if(o&&(o.level===e||!n&&o.level<e))return Promise.resolve(t);if(s&&r){const a=this.getPendingTextureSlotRequest(s,r);if(a&&a.level===e&&a.force===n)return a.promise}const u=g.getOrLoadLOD(t,e).then(a=>{if(Array.isArray(a))return console.warn("Progressive: Got an array of textures for a texture slot, this should not happen..."),null;if(a?.isTexture===!0){if(a!=t&&s&&r){const l=this.getMaterialTextureSlot(s,r)??t;if(l&&!n){const c=this.getAssignedLODInformation(l);if(c&&c?.level<e)return h==="verbose"&&console.warn("Assigned texture level is already higher: ",c.level,e,s,l,a),null}this.assignTrackedTextureSlot(s,r,a)}return a}else h=="verbose"&&console.warn("No LOD found for",t,e);return null}).catch(a=>(console.error("Error loading LOD",t,a),null));return s&&r&&this.setPendingTextureSlotRequest(s,r,e,n,u),u}static trackedTextureSlots=new WeakMap;static pendingTextureSlotRequests=new WeakMap;static trackCurrentMaterialTextureSlots(t){if(t.uniforms&&(t.isRawShaderMaterial||t.isShaderMaterial===!0)){const e=t;for(const s of Object.keys(e.uniforms)){const r=e.uniforms[s].value;r?.isTexture===!0&&this.ensureTrackedTextureSlot(t,s,r)}return}for(const e of Object.keys(t)){const s=t[e];s?.isTexture===!0&&this.ensureTrackedTextureSlot(t,e,s)}}static getPendingTextureSlotRequest(t,e){return this.pendingTextureSlotRequests.get(t)?.get(e)}static setPendingTextureSlotRequest(t,e,s,r,n){let o=this.pendingTextureSlotRequests.get(t);o||(o=new Map,this.pendingTextureSlotRequests.set(t,o));const u={level:s,force:r,promise:n};o.set(e,u),n.finally(()=>{o.get(e)===u&&o.delete(e)})}static getMaterialTextureSlot(t,e){const r=t.uniforms?.[e];if(r?.value?.isTexture===!0)return r.value;const n=t[e];return n?.isTexture===!0?n:null}static setMaterialTextureSlot(t,e,s){const n=t.uniforms?.[e];if(n?.value?.isTexture===!0){n.value=s,t.uniformsNeedUpdate=!0;return}t[e]=s}static assignTrackedTextureSlot(t,e,s){let r=this.trackedTextureSlots.get(t);r||(r=new Map,this.trackedTextureSlots.set(t,r));const n=this.getMaterialTextureSlot(t,e);let o=r.get(e);!o&&n?o=this.ensureTrackedTextureSlot(t,e,n):o&&n&&o!==n&&(this.releaseTrackedTextureSlot(t,e,o),o=this.ensureTrackedTextureSlot(t,e,n)),!(o===s&&n===s)&&(o&&o!==s&&this.releaseTrackedTextureSlot(t,e,o),o!==s&&(this.trackTextureUsage(s),r.set(e,s)),n!==s&&this.setMaterialTextureSlot(t,e,s))}static ensureTrackedTextureSlot(t,e,s){let r=this.trackedTextureSlots.get(t);r||(r=new Map,this.trackedTextureSlots.set(t,r));const n=r.get(e);return n===s?n:(n&&this.releaseTrackedTextureSlot(t,e,n),this.trackTextureUsage(s),r.set(e,s),s)}static releaseTrackedTextureSlot(t,e,s){const r=this.trackedTextureSlots.get(t);if(r?.get(e)===s&&r.delete(e),this.untrackTextureUsage(s)&&(h||ee)){const o=this.getAssignedLODInformation(s);console.log(`[gltf-progressive] Disposed old texture LOD ${o?.level??"?"} for ${t.name||t.type}.${e}`,s.uuid)}}parser;url;constructor(t){const e=t.options.path;h&&console.log("Progressive extension registered for",e),this.parser=t,this.url=e}_isLoadingMesh;loadMesh=t=>{if(this._isLoadingMesh)return null;const e=this.parser.json.meshes[t]?.extensions?.[G];return e?(this._isLoadingMesh=!0,this.parser.getDependency("mesh",t).then(s=>(this._isLoadingMesh=!1,s&&g.registerMesh(this.url,e.guid,s,e.lods?.length,0,e),s))):null};afterRoot(t){return h&&console.log("AFTER",this.url,t),this.parser.json.textures?.forEach((e,s)=>{if(e?.extensions){const r=e?.extensions[G];if(r){if(!r.lods){h&&console.warn("Texture has no LODs",r);return}let n=!1;for(const o of this.parser.associations.keys())o.isTexture===!0&&this.parser.associations.get(o)?.textures===s&&(n=!0,g.registerTexture(this.url,o,r.lods?.length,s,r));n||this.parser.getDependency("texture",s).then(o=>{o&&g.registerTexture(this.url,o,r.lods?.length,s,r)})}}}),this.parser.json.meshes?.forEach((e,s)=>{if(e?.extensions){const r=e?.extensions[G];if(r&&r.lods){for(const n of this.parser.associations.keys())if(n.isMesh){const o=this.parser.associations.get(n);o?.meshes===s&&g.registerMesh(this.url,r.guid,n,r.lods.length,o.primitives,r)}}}}),null}static registerTexture=(t,e,s,r,n)=>{if(!e){h&&console.error("!! gltf-progressive: Called register texture without texture");return}if(h){const u=e.image?.width||e.source?.data?.width||0,a=e.image?.height||e.source?.data?.height||0;console.log(`> gltf-progressive: register texture[${r}] "${e.name||e.uuid}", Current: ${u}x${a}, Max: ${n.lods[0]?.width}x${n.lods[0]?.height}, uuid: ${e.uuid}`,n,e)}e.source&&(e.source[ue]=n);const o=n.guid;g.assignLODInformation(t,e,o,s,r),g.lodInfos.set(o,n),g.lowresCache.set(o,new WeakRef(e))};static registerMesh=(t,e,s,r,n,o)=>{const u=s.geometry;if(!u){h&&console.warn("gltf-progressive: Register mesh without geometry");return}u.userData||(u.userData={}),h&&console.log("> Progressive: register mesh "+s.name,{index:n,uuid:s.uuid},o,s),g.assignLODInformation(t,u,e,r,n),g.lodInfos.set(e,o);let l=g.lowresCache.get(e)?.deref();l?l.push(s.geometry):l=[s.geometry],g.lowresCache.set(e,new WeakRef(l)),r>0&&!H(s)&&$e(s,u);for(const c of V)c.onRegisteredNewMesh?.(s,o)};static dispose(t){if(t){this.lodInfos.delete(t);const e=this.lowresCache.get(t);if(e){const s=e.deref();if(s){if(s.isTexture){const r=s;this.textureRefCounts.delete(r.uuid),r.dispose()}else if(Array.isArray(s))for(const r of s)r.dispose()}this.lowresCache.delete(t)}for(const[s,r]of this.cache)s.includes(t)&&(this._disposeCacheEntry(r),this.cache.delete(s))}else{this.lodInfos.clear();for(const[,e]of this.lowresCache){const s=e.deref();if(s){if(s.isTexture){const r=s;this.textureRefCounts.delete(r.uuid),r.dispose()}else if(Array.isArray(s))for(const r of s)r.dispose()}}this.lowresCache.clear();for(const[,e]of this.cache)this._disposeCacheEntry(e);this.cache.clear(),this.textureRefCounts.clear(),this.trackedTextureSlots=new WeakMap,this.pendingTextureSlotRequests=new WeakMap}}static _disposeCacheEntry(t){if(t instanceof WeakRef){const e=t.deref();e&&(e.isTexture&&this.textureRefCounts.delete(e.uuid),e.dispose())}else t.then(e=>{if(e)if(Array.isArray(e))for(const s of e)s.dispose();else e.isTexture&&this.textureRefCounts.delete(e.uuid),e.dispose()}).catch(()=>{})}static lodInfos=new Map;static cache=new Map;static lowresCache=new Map;static textureRefCounts=new Map;static _resourceRegistry=new FinalizationRegistry(t=>{const e=g.cache.get(t);(h||ee)&&console.debug(`[gltf-progressive] Memory: Resource GC'd
|
|
2
|
+
${t}`),e instanceof WeakRef&&(e.deref()||(g.cache.delete(t),(h||ee)&&console.log("[gltf-progressive] ↪ Cache entry deleted (GC)")))});static trackTextureUsage(t){const e=t.uuid,s=this.textureRefCounts.get(e)||0;this.textureRefCounts.set(e,s+1),h==="verbose"&&console.log(`[gltf-progressive] Track texture ${e}, refCount: ${s} → ${s+1}`)}static untrackTextureUsage(t){const e=t.uuid,s=this.textureRefCounts.get(e);if(!s)return(h==="verbose"||ee)&&n("[gltf-progressive] Memory: Untrack untracked texture (dispose immediately)",0),t.dispose(),!0;const r=s-1;if(r<=0)return this.textureRefCounts.delete(e),(h||ee)&&n("[gltf-progressive] Memory: Dispose texture",r),t.dispose(),!0;return this.textureRefCounts.set(e,r),h==="verbose"&&n("[gltf-progressive] Memory: Untrack texture",r),!1;function n(o,u){const a=t.image?.width||t.source?.data?.width||0,l=t.image?.height||t.source?.data?.height||0,c=a&&l?`${a}x${l}`:"N/A";let f="N/A";a&&l&&(f=`~${(lt(t)/(1024*1024)).toFixed(2)} MB`),console.log(`${o} — ${t.name} ${c} (${f}), refCount: ${s} → ${u}
|
|
3
|
+
${e}`)}}static workers=[];static _workersIndex=0;static async getOrLoadLOD(t,e){const s=h=="verbose",r=this.getAssignedLODInformation(t);if(!r)return h&&console.warn(`[gltf-progressive] No LOD information found: ${t.name}, uuid: ${t.uuid}, type: ${t.type}`,t),null;const n=r?.key;let o;if(t.isTexture===!0){const a=t;a.source&&a.source[ue]&&(o=a.source[ue])}if(o||(o=g.lodInfos.get(n)),!o)h&&console.warn(`Can not load LOD ${e}: no LOD info found for "${n}" ${t.name}`,t.type,g.lodInfos);else{if(e>0){let c=!1;const f=Array.isArray(o.lods);if(f&&e>=o.lods.length?c=!0:f||(c=!0),c){const p=this.lowresCache.get(n);if(p){const y=p.deref();if(y)return y;this.lowresCache.delete(n),h&&console.log(`[gltf-progressive] Lowres cache entry was GC'd: ${n}`)}return null}}const a=Array.isArray(o.lods)?o.lods[e]?.path:o.lods;if(!a)return h&&!o["missing:uri"]&&(o["missing:uri"]=!0,console.warn("Missing uri for progressive asset for LOD "+e,o)),null;const l=it(r.url,a);if(l.endsWith(".glb")||l.endsWith(".gltf")){if(!o.guid)return console.warn("missing pointer for glb/gltf texture",o),null;const c=l+"_"+o.guid,f=await this.tryResolveLODCacheEntry(this.cache.get(c),c,l,t,e,s);if(f.found)return f.value;const p=await this.queue.slot(l),y=await this.tryResolveLODCacheEntry(this.cache.get(c),c,l,t,e,s);if(y.found)return y.value;if(!p.use)return h&&console.log(`LOD ${e} was aborted: ${l}`),null;const w=o,_=new Promise(async(M,P)=>{if(mt){const x=await(await gt({})).load(l);if(x.textures.length>0)for(const D of x.textures){let b=D.texture;return g.assignLODInformation(r.url,b,n,e,void 0),t instanceof d.Texture&&(b=this.copySettings(t,b)),b&&(b.guid=w.guid),M(b)}if(x.geometries.length>0){const D=new Array;for(const b of x.geometries){const B=b.geometry;g.assignLODInformation(r.url,B,n,e,b.primitiveIndex),D.push(B)}return M(D)}return M(null)}const U=new xe.GLTFLoader;we(U),h&&(await new Promise(T=>setTimeout(T,1e3)),s&&console.warn("Start loading (delayed) "+l,w.guid));let v=l;if(w&&Array.isArray(w.lods)){const T=w.lods[e];T.hash&&(v+="?v="+T.hash)}const L=await U.loadAsync(v).catch(T=>(console.error(`Error loading LOD ${e} from ${l}
|
|
4
|
+
`,T),M(null)));if(!L)return M(null);const C=L.parser;s&&console.log("Loading finished "+l,w.guid);let O=0;if(L.parser.json.textures){let T=!1;for(const x of L.parser.json.textures){if(x?.extensions){const D=x?.extensions[G];if(D?.guid&&D.guid===w.guid){T=!0;break}}O++}if(T){let x=await C.getDependency("texture",O);return x&&g.assignLODInformation(r.url,x,n,e,void 0),s&&console.log('change "'+t.name+'" → "'+x.name+'"',l,O,x,c),t instanceof d.Texture&&(x=this.copySettings(t,x)),x&&(x.guid=w.guid),M(x)}else h&&console.warn("Could not find texture with guid",w.guid,L.parser.json)}if(O=0,L.parser.json.meshes){let T=!1;for(const x of L.parser.json.meshes){if(x?.extensions){const D=x?.extensions[G];if(D?.guid&&D.guid===w.guid){T=!0;break}}O++}if(T){const x=await C.getDependency("mesh",O);if(s&&console.log(`Loaded Mesh "${x.name}"`,l,O,x,c),x.isMesh===!0){const D=x.geometry;return g.assignLODInformation(r.url,D,n,e,0),M(D)}else{const D=new Array;for(let b=0;b<x.children.length;b++){const B=x.children[b];if(B.isMesh===!0){const E=B.geometry;g.assignLODInformation(r.url,E,n,e,b),D.push(E)}}return M(D)}}else h&&console.warn("Could not find mesh with guid",w.guid,L.parser.json)}return M(null)});this.cache.set(c,_),p.use(_);const m=await _;return m!=null?m instanceof d.Texture?(this.cache.set(c,new WeakRef(m)),g._resourceRegistry.register(m,c)):Array.isArray(m)?this.cache.set(c,Promise.resolve(m)):this.cache.set(c,Promise.resolve(m)):this.cache.set(c,Promise.resolve(null)),m}else if(t instanceof d.Texture){s&&console.log("Load texture from uri: "+l);const f=await new d.TextureLoader().loadAsync(l);return f?(f.guid=o.guid,f.flipY=!1,f.needsUpdate=!0,f.colorSpace=t.colorSpace,s&&console.log(o,f)):h&&console.warn("failed loading",l),f}}return null}static async tryResolveLODCacheEntry(t,e,s,r,n,o){if(t===void 0)return{found:!1};if(o&&console.log(`LOD ${n} was already loading/loaded: ${e}`),t instanceof WeakRef){const l=t.deref();if(l){let c=l,f=!1;if(c instanceof d.Texture&&r instanceof d.Texture?c.image?.data||c.source?.data?c=this.copySettings(r,c):f=!0:c instanceof d.BufferGeometry&&r instanceof d.BufferGeometry&&(c.attributes.position?.array||(f=!0)),!f)return{found:!0,value:c}}return this.cache.delete(e),h&&console.log(`[gltf-progressive] Re-loading GC'd/disposed resource: ${e}`),{found:!1}}let u=await t.catch(l=>(console.error(`Error loading LOD ${n} from ${s}
|
|
5
|
+
`,l),null)),a=!1;return u==null||(u instanceof d.Texture&&r instanceof d.Texture?u.image?.data||u.source?.data?u=this.copySettings(r,u):(a=!0,this.cache.delete(e)):u instanceof d.BufferGeometry&&r instanceof d.BufferGeometry&&(u.attributes.position?.array||(a=!0,this.cache.delete(e)))),a?{found:!1}:{found:!0,value:u}}static _queue;static get queue(){return this._queue??=new at(ve()?20:50,{debug:h!=!1})}static assignLODInformation(t,e,s,r,n){if(!e)return;e.userData||(e.userData={});const o=new yt(t,s,r,n);e.userData.LODS=o,"source"in e&&typeof e.source=="object"&&(e.source.LODS=o)}static getAssignedLODInformation(t){return t?t.userData?.LODS?t.userData.LODS:"source"in t&&t.source?.LODS?t.source.LODS:null:null}static copySettings(t,e){return e?(h==="verbose"&&console.debug(`Copy texture settings
|
|
6
6
|
`,t.uuid,`
|
|
7
|
-
`,e.uuid),e=e.clone(),e.offset=t.offset,e.repeat=t.repeat,e.colorSpace=t.colorSpace,e.magFilter=t.magFilter,e.minFilter=t.minFilter,e.wrapS=t.wrapS,e.wrapT=t.wrapT,e.flipY=t.flipY,e.anisotropy=t.anisotropy,e.mipmaps||(e.generateMipmaps=t.generateMipmaps),e):t}}class dt{url;key;level;index;constructor(t,e,s,r){this.url=t,this.key=e,this.level=s,r!=null&&(this.index=r)}}class ue{static addPromise=(t,e,s,r)=>{r.forEach(o=>{o.add(t,e,s)})};ready;get awaitedCount(){return this._addedCount}get resolvedCount(){return this._resolvedCount}get currentlyAwaiting(){return this._awaiting.length}_resolve;_signal;_frame_start;_frames_to_capture;_resolved=!1;_addedCount=0;_resolvedCount=0;_awaiting=[];_maxPromisesPerObject=1;constructor(t,e){const r=Math.max(e.frames??2,2);this._frame_start=e.waitForFirstCapture?void 0:t,this._frames_to_capture=r,this.ready=new Promise(o=>{this._resolve=o}),this.ready.finally(()=>{this._resolved=!0,this._awaiting.length=0}),this._signal=e.signal,this._signal?.addEventListener("abort",()=>{this.resolveNow()}),this._maxPromisesPerObject=Math.max(1,e.maxPromisesPerObject??1)}_currentFrame=0;update(t){this._currentFrame=t,this._frame_start===void 0&&this._addedCount>0&&(this._frame_start=t),(this._signal?.aborted||this._awaiting.length===0&&this._frame_start!==void 0&&t>this._frame_start+this._frames_to_capture)&&this.resolveNow()}_seen=new WeakMap;add(t,e,s){if(this._resolved){h&&console.warn("PromiseGroup: Trying to add a promise to a resolved group, ignoring.");return}if(!(this._frame_start!==void 0&&this._currentFrame>this._frame_start+this._frames_to_capture)){if(this._maxPromisesPerObject>=1)if(this._seen.has(e)){let r=this._seen.get(e);if(r>=this._maxPromisesPerObject){h&&console.warn("PromiseGroup: Already awaiting object ignoring new promise for it.");return}this._seen.set(e,r+1)}else this._seen.set(e,1);this._awaiting.push(s),this._addedCount++,s.finally(()=>{this._resolvedCount++,this._awaiting.splice(this._awaiting.indexOf(s),1)})}}resolveNow(){this._resolved||this._resolve?.({awaited_count:this._addedCount,resolved_count:this._resolvedCount,cancelled:this._signal?.aborted??!1})}}const k=z("debugprogressive"),ft=z("noprogressive"),ce=Symbol("Needle:LODSManager"),de=Symbol("Needle:LODState"),U=Symbol("Needle:CurrentLOD"),C={mesh_lod:-1,texture_lod:-1};class M{static debugDrawLine;static getObjectLODState(t){return t[de]}static addPlugin(t){W.push(t)}static removePlugin(t){const e=W.indexOf(t);e>=0&&W.splice(e,1)}static get(t,e){if(t[ce])return console.debug("[gltf-progressive] LODsManager already exists for this renderer"),t[ce];const s=new M(t,{engine:"unknown",...e});return t[ce]=s,s}renderer;context;projectionScreenMatrix=new c.Matrix4;get plugins(){return W}overrideLodLevel=void 0;targetTriangleDensity=2e5;skinnedMeshAutoUpdateBoundsInterval=30;updateInterval="auto";#e=1;pause=!1;manual=!1;_newPromiseGroups=[];_promiseGroupIds=0;awaitLoading(t){const e=this._promiseGroupIds++,s=new ue(this.#r,{...t});this._newPromiseGroups.push(s);const r=performance.now();return s.ready.finally(()=>{const o=this._newPromiseGroups.indexOf(s);o>=0&&(this._newPromiseGroups.splice(o,1),Me()&&performance.measure("LODsManager:awaitLoading",{start:r,detail:{id:e,name:t?.name,awaited:s.awaitedCount,resolved:s.resolvedCount}}))}),s.ready}_postprocessPromiseGroups(){if(this._newPromiseGroups.length!==0)for(let t=this._newPromiseGroups.length-1;t>=0;t--)this._newPromiseGroups[t].update(this.#r)}_lodchangedlisteners=[];addEventListener(t,e){t==="changed"&&this._lodchangedlisteners.push(e)}removeEventListener(t,e){if(t==="changed"){const s=this._lodchangedlisteners.indexOf(e);s>=0&&this._lodchangedlisteners.splice(s,1)}}constructor(t,e){this.renderer=t,this.context={...e}}#t;#i=new c.Clock;#r=0;#o=0;#n=0;#s=0;_fpsBuffer=[60,60,60,60,60];enable(){if(this.#t)return;console.debug("[gltf-progressive] Enabling LODsManager for renderer");let t=0;this.#t=this.renderer.render;const e=this;re(this.renderer),this.renderer.render=function(s,r){const o=e.renderer.getRenderTarget();(o==null||"isXRRenderTarget"in o&&o.isXRRenderTarget)&&(t=0,e.#r+=1,e.#o=e.#i.getDelta(),e.#n+=e.#o,e._fpsBuffer.shift(),e._fpsBuffer.push(1/e.#o),e.#s=e._fpsBuffer.reduce((l,a)=>l+a)/e._fpsBuffer.length,k&&e.#r%200===0&&console.log("FPS",Math.round(e.#s),"Interval:",e.#e));const n=t++;e.#t.call(this,s,r),e.onAfterRender(s,r,n)}}disable(){this.#t&&(console.debug("[gltf-progressive] Disabling LODsManager for renderer"),this.renderer.render=this.#t,this.#t=void 0)}update(t,e){this.internalUpdate(t,e)}onAfterRender(t,e,s){if(this.pause)return;const o=this.renderer.renderLists.get(t,0).opaque;let n=!0;if(o.length===1){const l=o[0].material;(l.name==="EffectMaterial"||l.name==="CopyShader")&&(n=!1)}if((e.parent&&e.parent.type==="CubeCamera"||s>=1&&e.type==="OrthographicCamera")&&(n=!1),n){if(ft||(this.updateInterval==="auto"?this.#s<40&&this.#e<10?(this.#e+=1,k&&console.warn("↓ Reducing LOD updates",this.#e,this.#s.toFixed(0))):this.#s>=60&&this.#e>1&&(this.#e-=1,k&&console.warn("↑ Increasing LOD updates",this.#e,this.#s.toFixed(0))):this.#e=this.updateInterval,this.#e>0&&this.#r%this.#e!=0))return;this.internalUpdate(t,e),this._postprocessPromiseGroups()}}internalUpdate(t,e){const s=this.renderer.renderLists.get(t,0),r=s.opaque;this.projectionScreenMatrix.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse);const o=this.targetTriangleDensity;for(const a of r){if(a.material&&(a.geometry?.type==="BoxGeometry"||a.geometry?.type==="BufferGeometry")&&(a.material.name==="SphericalGaussianBlur"||a.material.name=="BackgroundCubeMaterial"||a.material.name==="CubemapFromEquirect"||a.material.name==="EquirectangularToCubeUV")){k&&(a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]||(a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]=!0,console.warn("Ignoring skybox or BLIT object",a,a.material.name,a.material.type)));continue}switch(a.material.type){case"LineBasicMaterial":case"LineDashedMaterial":case"PointsMaterial":case"ShadowMaterial":case"MeshDistanceMaterial":case"MeshDepthMaterial":continue}if(k==="color"&&a.material&&!a.object.progressive_debug_color){a.object.progressive_debug_color=!0;const d=Math.random()*16777215,x=new c.MeshStandardMaterial({color:d});a.object.material=x}const u=a.object;(u instanceof c.Mesh||u.isMesh)&&this.updateLODs(t,e,u,o)}const n=s.transparent;for(const a of n){const u=a.object;(u instanceof c.Mesh||u.isMesh)&&this.updateLODs(t,e,u,o)}const l=s.transmissive;for(const a of l){const u=a.object;(u instanceof c.Mesh||u.isMesh)&&this.updateLODs(t,e,u,o)}}updateLODs(t,e,s,r){s.userData||(s.userData={});let o=s[de];if(o||(o=new ht,s[de]=o),o.frames++<2)return;for(const l of W)l.onBeforeUpdateLOD?.(this.renderer,t,e,s);const n=this.overrideLodLevel!==void 0?this.overrideLodLevel:V;n>=0?(C.mesh_lod=n,C.texture_lod=n):(this.calculateLodLevel(e,s,o,r,C),C.mesh_lod=Math.round(C.mesh_lod),C.texture_lod=Math.round(C.texture_lod)),C.mesh_lod>=0&&this.loadProgressiveMeshes(s,C.mesh_lod),s.material&&C.texture_lod>=0&&this.loadProgressiveTextures(s.material,C.texture_lod,n),h&&s.material&&!s.isGizmo&&Ie(s.material);for(const l of W)l.onAfterUpdatedLOD?.(this.renderer,t,e,s,C);o.lastLodLevel_Mesh=C.mesh_lod,o.lastLodLevel_Texture=C.texture_lod}loadProgressiveTextures(t,e,s){if(!t)return;if(Array.isArray(t)){for(const o of t)this.loadProgressiveTextures(o,e);return}let r=!1;if((t[U]===void 0||e<t[U])&&(r=!0),s!==void 0&&s>=0&&(r=t[U]!=s,e=s),r){t[U]=e;const o=m.assignTextureLOD(t,e).then(n=>{this._lodchangedlisteners.forEach(l=>l({type:"texture",level:e,object:t}))});ue.addPromise("texture",t,o,this._newPromiseGroups)}}loadProgressiveMeshes(t,e){if(!t)return Promise.resolve(null);let s=t[U]!==e;const r=t["DEBUG:LOD"];if(r!=null&&(s=t[U]!=r,e=r),s){t[U]=e;const o=t.geometry,n=m.assignMeshLOD(t,e).then(l=>(l&&t[U]==e&&o!=t.geometry&&this._lodchangedlisteners.forEach(a=>a({type:"mesh",level:e,object:t})),l));return ue.addPromise("mesh",t,n,this._newPromiseGroups),n}return Promise.resolve(null)}_sphere=new c.Sphere;_tempBox=new c.Box3;_tempBox2=new c.Box3;tempMatrix=new c.Matrix4;_tempWorldPosition=new c.Vector3;_tempBoxSize=new c.Vector3;_tempBox2Size=new c.Vector3;static corner0=new c.Vector3;static corner1=new c.Vector3;static corner2=new c.Vector3;static corner3=new c.Vector3;static _tempPtInside=new c.Vector3;static isInside(t,e){const s=t.min,r=t.max,o=(s.x+r.x)*.5,n=(s.y+r.y)*.5;return this._tempPtInside.set(o,n,s.z).applyMatrix4(e).z<0}static skinnedMeshBoundsFrameOffsetCounter=0;static $skinnedMeshBoundsOffset=Symbol("gltf-progressive-skinnedMeshBoundsOffset");calculateLodLevel(t,e,s,r,o){if(!e){o.mesh_lod=-1,o.texture_lod=-1;return}if(!t){o.mesh_lod=-1,o.texture_lod=-1;return}let l=10+1,a=!1;if(k&&e["DEBUG:LOD"]!=null)return e["DEBUG:LOD"];const u=m.getMeshLODExtension(e.geometry)?.lods,d=m.getPrimitiveIndex(e.geometry),x=u&&u.length>0,L=m.getMaterialMinMaxLODsCount(e.material),_=L.min_count!==1/0&&L.min_count>=0&&L.max_count>=0;if(!x&&!_){o.mesh_lod=0,o.texture_lod=0;return}x||(a=!0,l=0);const R=this.renderer.domElement.clientHeight||this.renderer.domElement.height;let D=e.geometry.boundingBox;if(e.type==="SkinnedMesh"){const f=e;if(!f.boundingBox)f.computeBoundingBox();else if(this.skinnedMeshAutoUpdateBoundsInterval>0){if(!f[M.$skinnedMeshBoundsOffset]){const b=M.skinnedMeshBoundsFrameOffsetCounter++;f[M.$skinnedMeshBoundsOffset]=b}const p=f[M.$skinnedMeshBoundsOffset];if((s.frames+p)%this.skinnedMeshAutoUpdateBoundsInterval===0){const b=j(f),B=f.geometry;b&&(f.geometry=b),f.computeBoundingBox(),f.geometry=B}}D=f.boundingBox}if(D){const f=t;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 g=t.getWorldPosition(this._tempWorldPosition);if(this._sphere.containsPoint(g)){o.mesh_lod=0,o.texture_lod=0;return}}if(this._tempBox.copy(D),this._tempBox.applyMatrix4(e.matrixWorld),f.isPerspectiveCamera&&M.isInside(this._tempBox,this.projectionScreenMatrix)){o.mesh_lod=0,o.texture_lod=0;return}if(this._tempBox.applyMatrix4(this.projectionScreenMatrix),this.renderer.xr.enabled&&f.isPerspectiveCamera&&f.fov>70){const g=this._tempBox.min,y=this._tempBox.max;let S=g.x,T=g.y,G=y.x,X=y.y;const J=2,oe=1.5,Z=(g.x+y.x)*.5,ee=(g.y+y.y)*.5;S=(S-Z)*J+Z,T=(T-ee)*J+ee,G=(G-Z)*J+Z,X=(X-ee)*J+ee;const Ge=S<0&&G>0?0:Math.min(Math.abs(g.x),Math.abs(y.x)),Fe=T<0&&X>0?0:Math.min(Math.abs(g.y),Math.abs(y.y)),ie=Math.max(Ge,Fe);s.lastCentrality=(oe-ie)*(oe-ie)*(oe-ie)}else s.lastCentrality=1;const p=this._tempBox.getSize(this._tempBoxSize);p.multiplyScalar(.5),screen.availHeight>0&&R>0&&p.multiplyScalar(R/screen.availHeight),t.isPerspectiveCamera?p.x*=t.aspect:t.isOrthographicCamera;const b=t.matrixWorldInverse,B=this._tempBox2;B.copy(D),B.applyMatrix4(e.matrixWorld),B.applyMatrix4(b);const O=B.getSize(this._tempBox2Size),q=Math.max(O.x,O.y);if(Math.max(p.x,p.y)!=0&&q!=0&&(p.z=O.z/Math.max(O.x,O.y)*Math.max(p.x,p.y)),s.lastScreenCoverage=Math.max(p.x,p.y,p.z),s.lastScreenspaceVolume.copy(p),s.lastScreenCoverage*=s.lastCentrality,k&&M.debugDrawLine){const g=this.tempMatrix.copy(this.projectionScreenMatrix);g.invert();const y=M.corner0,S=M.corner1,T=M.corner2,G=M.corner3;y.copy(this._tempBox.min),S.copy(this._tempBox.max),S.x=y.x,T.copy(this._tempBox.max),T.y=y.y,G.copy(this._tempBox.max);const X=(y.z+G.z)*.5;y.z=S.z=T.z=G.z=X,y.applyMatrix4(g),S.applyMatrix4(g),T.applyMatrix4(g),G.applyMatrix4(g),M.debugDrawLine(y,S,255),M.debugDrawLine(y,T,255),M.debugDrawLine(S,G,255),M.debugDrawLine(T,G,255)}let v=999;if(u&&s.lastScreenCoverage>0)for(let g=0;g<u.length;g++){const y=u[g],T=(y.densities?.[d]||y.density||1e-5)/s.lastScreenCoverage;if(d>0&&Me()&&!y.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.")),T<r){v=g;break}}v<l&&(l=v,a=!0)}if(a?o.mesh_lod=l:o.mesh_lod=s.lastLodLevel_Mesh,k&&o.mesh_lod!=s.lastLodLevel_Mesh){const p=u?.[o.mesh_lod];p&&console.log(`Mesh LOD changed: ${s.lastLodLevel_Mesh} → ${o.mesh_lod} (density: ${p.densities?.[d].toFixed(0)}) | ${e.name}`)}if(_){const f="saveData"in globalThis.navigator&&globalThis.navigator.saveData===!0;if(s.lastLodLevel_Texture<0){if(o.texture_lod=L.max_count-1,k){const p=L.lods[L.max_count-1];k&&console.log(`First Texture LOD ${o.texture_lod} (${p.max_height}px) - ${e.name}`)}}else{const p=s.lastScreenspaceVolume.x+s.lastScreenspaceVolume.y+s.lastScreenspaceVolume.z;let b=s.lastScreenCoverage*4;this.context?.engine==="model-viewer"&&(b*=1.5);const O=R/window.devicePixelRatio*b;let q=!1;for(let P=L.lods.length-1;P>=0;P--){const v=L.lods[P];if(!(f&&v.max_height>=2048)&&!(we()&&v.max_height>4096)&&(v.max_height>O||!q&&P===0)){if(q=!0,o.texture_lod=P,k&&o.texture_lod<s.lastLodLevel_Texture){const w=v.max_height;console.log(`Texture LOD changed: ${s.lastLodLevel_Texture} → ${o.texture_lod} = ${w}px
|
|
8
|
-
Screensize: ${
|
|
9
|
-
${e.name}`)}break}}}}else
|
|
10
|
-
`,i.getAttribute("src"));let t=null,e=null,s=null;for(let r=i;r!=null;r=Object.getPrototypeOf(r)){const
|
|
7
|
+
`,e.uuid),e=e.clone(),e.offset=t.offset,e.repeat=t.repeat,e.colorSpace=t.colorSpace,e.magFilter=t.magFilter,e.minFilter=t.minFilter,e.wrapS=t.wrapS,e.wrapT=t.wrapT,e.flipY=t.flipY,e.anisotropy=t.anisotropy,e.mipmaps||(e.generateMipmaps=t.generateMipmaps),e):t}}class yt{url;key;level;index;constructor(t,e,s,r){this.url=t,this.key=e,this.level=s,r!=null&&(this.index=r)}}class se{static addPromise=(t,e,s,r)=>{r.forEach(n=>{n.add(t,e,s)})};ready;get awaitedCount(){return this._addedCount}get resolvedCount(){return this._resolvedCount}get currentlyAwaiting(){return this._awaiting.length}_resolve;_signal;_frame_start;_frames_to_capture;_resolved=!1;_addedCount=0;_resolvedCount=0;_awaiting=[];_maxPromisesPerObject=1;constructor(t,e){const r=Math.max(e.frames??2,2);this._frame_start=e.waitForFirstCapture?void 0:t,this._frames_to_capture=r,this.ready=new Promise(n=>{this._resolve=n}),this.ready.finally(()=>{this._resolved=!0,this._awaiting.length=0}),this._signal=e.signal,this._signal?.addEventListener("abort",()=>{this.resolveNow()}),this._maxPromisesPerObject=Math.max(1,e.maxPromisesPerObject??1)}_currentFrame=0;update(t){this._currentFrame=t,this._frame_start===void 0&&this._addedCount>0&&(this._frame_start=t),(this._signal?.aborted||this._awaiting.length===0&&this._frame_start!==void 0&&t>this._frame_start+this._frames_to_capture)&&this.resolveNow()}_seen=new WeakMap;add(t,e,s){if(this._resolved){h&&console.warn("PromiseGroup: Trying to add a promise to a resolved group, ignoring.");return}if(!(this._frame_start!==void 0&&this._currentFrame>this._frame_start+this._frames_to_capture)){if(this._maxPromisesPerObject>=1)if(this._seen.has(e)){const r=this._seen.get(e);if(r>=this._maxPromisesPerObject){h&&console.warn("PromiseGroup: Already awaiting object ignoring new promise for it.");return}this._seen.set(e,r+1)}else this._seen.set(e,1);this._awaiting.push(s),this._addedCount++,s.finally(()=>{this._resolvedCount++,this._awaiting.splice(this._awaiting.indexOf(s),1)})}}resolveNow(){this._resolved||this._resolve?.({awaited_count:this._addedCount,resolved_count:this._resolvedCount,cancelled:this._signal?.aborted??!1})}}const A=z("debugprogressive"),xt=A==="colors",wt=z("noprogressive"),ce=Symbol("Needle:LODSManager"),de=Symbol("Needle:LODState"),F=Symbol("Needle:CurrentLOD"),S={mesh_lod:-1,texture_lod:-1},Lt=new d.Color,ye=[3526751,11065402,15978811,15897394,15749691,11032304,4827122,3332036,16739229,7306743,14053330,3516499,12035359,14703919,3963096,42662,14100029,8344319,4633680,16229681,3120096,12076434,9083434,2060171,15751837,10182117,48121,62932,16704576,15817653,5083278,5592405],fe=new d.Box3,q=new d.Box3,Te=new d.Box3,vt=new d.Vector3,_t=new d.Vector3,Mt=new d.Matrix4,W=new d.Vector3,j=new d.Vector3,K=new d.Vector3,Y=new d.Vector3;function Dt(i,t){const e=i.min,s=i.max,r=(e.x+s.x)*.5,n=(e.y+s.y)*.5;return W.set(r,n,e.z).applyMatrix4(t).z<0}function Ue(i){const{geometry:t,matrixWorld:e,camera:s,projectionScreenMatrix:r,desiredDensity:n,canvasHeight:o=0,currentLevel:u=-1,xrEnabled:a=!1,debugDrawLine:l,warnMissingPrimitiveDensities:c=!1}=i,f=g.getMeshLODExtension(t)?.lods,p=g.getPrimitiveIndex(t),y=i.target??{level:u,primitiveIndex:p,screenCoverage:0,screenspaceVolume:new d.Vector3,centrality:1};if(y.level=u,y.primitiveIndex=p,y.screenCoverage=0,y.screenspaceVolume.set(0,0,0),y.centrality=1,!f?.length)return y;let w=i.boundingBox??t.boundingBox;if(w||(t.computeBoundingBox(),w=t.boundingBox),!w)return y;if(fe.copy(w).applyMatrix4(e),s.isPerspectiveCamera&&Dt(fe,r))return y.level=0,y.screenCoverage=1/0,y.screenspaceVolume.set(1/0,1/0,1/0),y;if(q.copy(fe).applyMatrix4(r),a&&s.isPerspectiveCamera&&s.fov>70){const v=q.min,L=q.max;let C=v.x,O=v.y,T=L.x,x=L.y;const D=2,b=1.5,B=(v.x+L.x)*.5,E=(v.y+L.y)*.5;C=(C-B)*D+B,O=(O-E)*D+E,T=(T-B)*D+B,x=(x-E)*D+E;const ze=C<0&&T>0?0:Math.min(Math.abs(v.x),Math.abs(L.x)),Ee=O<0&&x>0?0:Math.min(Math.abs(v.y),Math.abs(L.y)),ie=Math.max(ze,Ee);y.centrality=(b-ie)*(b-ie)*(b-ie)}const _=q.getSize(vt);_.multiplyScalar(.5),globalThis.screen?.availHeight>0&&o>0&&_.multiplyScalar(o/globalThis.screen.availHeight),s.isPerspectiveCamera&&(_.x*=s.aspect),Te.copy(w).applyMatrix4(e).applyMatrix4(s.matrixWorldInverse);const m=Te.getSize(_t),M=Math.max(_.x,_.y),P=Math.max(m.x,m.y);M!==0&&P!==0&&(_.z=m.z/P*M);const U=Math.max(_.x,_.y,_.z)*y.centrality;if(y.screenCoverage=U,y.screenspaceVolume.copy(_),U<=0)return y;if(l){const v=Mt.copy(r);v.invert(),W.copy(q.min),j.copy(q.max),j.x=W.x,K.copy(q.max),K.y=W.y,Y.copy(q.max);const L=(W.z+Y.z)*.5;W.z=j.z=K.z=Y.z=L,W.applyMatrix4(v),j.applyMatrix4(v),K.applyMatrix4(v),Y.applyMatrix4(v),l(W,j,255),l(W,K,255),l(j,Y,255),l(K,Y,255)}for(let v=0;v<f.length;v++){const L=f[v],C=L.densities?.[p]||L.density||1e-5;if(p>0&&c&&Ie()&&!L.densities&&!globalThis["NEEDLE:MISSING_LOD_PRIMITIVE_DENSITIES"]&&(globalThis["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.")),C/U<n){y.level=v;break}}return y}class R{static debugDrawLine;static getObjectLODState(t){return t[de]}static addPlugin(t){V.push(t)}static removePlugin(t){const e=V.indexOf(t);e>=0&&V.splice(e,1)}static get(t,e){if(t[ce])return console.debug("[gltf-progressive] LODsManager already exists for this renderer"),t[ce];const s=new R(t,{engine:"unknown",...e});return t[ce]=s,s}renderer;context;projectionScreenMatrix=new d.Matrix4;get plugins(){return V}overrideLodLevel=void 0;targetTriangleDensity=2e5;skinnedMeshAutoUpdateBoundsInterval=30;updateInterval="auto";#e=1;pause=!1;manual=!1;_newPromiseGroups=[];_promiseGroupIds=0;awaitLoading(t){const e=this._promiseGroupIds++,s=new se(this.#r,{...t});this._newPromiseGroups.push(s);const r=performance.now();return s.ready.finally(()=>{const n=this._newPromiseGroups.indexOf(s);n>=0&&(this._newPromiseGroups.splice(n,1),Ie()&&performance.measure("LODsManager:awaitLoading",{start:r,detail:{id:e,name:t?.name,awaited:s.awaitedCount,resolved:s.resolvedCount}}))}),s.ready}trackLoadingPromise(t,e,s){return se.addPromise(t,e,s,this._newPromiseGroups),s}_postprocessPromiseGroups(){if(this._newPromiseGroups.length!==0)for(let t=this._newPromiseGroups.length-1;t>=0;t--)this._newPromiseGroups[t].update(this.#r)}_lodchangedlisteners=[];addEventListener(t,e){return t==="changed"?(this._lodchangedlisteners.push(e),()=>{this.removeEventListener(t,e)}):()=>{}}removeEventListener(t,e){let s=!1;if(t==="changed"){const r=this._lodchangedlisteners.indexOf(e);r>=0&&(this._lodchangedlisteners.splice(r,1),s=!0)}return s}constructor(t,e){this.renderer=t,this.context={...e}}#t;#o=new d.Clock;#r=0;#n=0;#i=0;#s=0;_fpsBuffer=[60,60,60,60,60];enable(){if(this.#t)return;console.debug("[gltf-progressive] Enabling LODsManager for renderer");let t=0;this.#t=this.renderer.render;const e=this;oe(this.renderer),this.renderer.render=function(s,r){const n=e.renderer.getRenderTarget();(n==null||"isXRRenderTarget"in n&&n.isXRRenderTarget)&&(t=0,e.#r+=1,e.#n=e.#o.getDelta(),e.#i+=e.#n,e._fpsBuffer.shift(),e._fpsBuffer.push(1/e.#n),e.#s=e._fpsBuffer.reduce((u,a)=>u+a)/e._fpsBuffer.length,A&&e.#r%200===0&&console.log("FPS",Math.round(e.#s),"Interval:",e.#e));const o=t++;e.#t.call(this,s,r),e.onAfterRender(s,r,o)}}disable(){this.#t&&(console.debug("[gltf-progressive] Disabling LODsManager for renderer"),this.renderer.render=this.#t,this.#t=void 0)}update(t,e){this.internalUpdate(t,e)}onAfterRender(t,e,s){if(this.pause)return;const n=this.renderer.renderLists.get(t,0).opaque;let o=!0;if(n.length===1){const u=n[0].material;(u.name==="EffectMaterial"||u.name==="CopyShader")&&(o=!1)}if((e.parent&&e.parent.type==="CubeCamera"||s>=1&&e.type==="OrthographicCamera")&&(o=!1),o){if(wt||(this.updateInterval==="auto"?this.#s<40&&this.#e<10?(this.#e+=1,A&&console.warn("↓ Reducing LOD updates",this.#e,this.#s.toFixed(0))):this.#s>=60&&this.#e>1&&(this.#e-=1,A&&console.warn("↑ Increasing LOD updates",this.#e,this.#s.toFixed(0))):this.#e=this.updateInterval,this.#e>0&&this.#r%this.#e!=0))return;this.internalUpdate(t,e),this._postprocessPromiseGroups()}}internalUpdate(t,e){const s=this.renderer.renderLists.get(t,0),r=s.opaque;this.projectionScreenMatrix.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse);const n=this.targetTriangleDensity;for(const a of r){if(a.material&&(a.geometry?.type==="BoxGeometry"||a.geometry?.type==="BufferGeometry")&&(a.material.name==="SphericalGaussianBlur"||a.material.name=="BackgroundCubeMaterial"||a.material.name==="CubemapFromEquirect"||a.material.name==="EquirectangularToCubeUV")){A&&(a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]||(a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]=!0,console.warn("Ignoring skybox or BLIT object",a,a.material.name,a.material.type)));continue}switch(a.material.type){case"LineBasicMaterial":case"LineDashedMaterial":case"PointsMaterial":case"ShadowMaterial":case"MeshDistanceMaterial":case"MeshDepthMaterial":continue}const l=a.object;(l instanceof d.Mesh||l.isMesh)&&this.updateLODs(t,e,l,n)}const o=s.transparent;for(const a of o){const l=a.object;(l instanceof d.Mesh||l.isMesh)&&this.updateLODs(t,e,l,n)}const u=s.transmissive;for(const a of u){const l=a.object;(l instanceof d.Mesh||l.isMesh)&&this.updateLODs(t,e,l,n)}}updateLODs(t,e,s,r){s.userData||(s.userData={});let n=s[de];if(n||(n=new Tt,s[de]=n),n.frames++<2)return;for(const u of V)u.onBeforeUpdateLOD?.(this.renderer,t,e,s);const o=this.overrideLodLevel!==void 0?this.overrideLodLevel:N;o>=0?(S.mesh_lod=o,S.texture_lod=o):(this.calculateLodLevel(e,s,n,r,S),S.mesh_lod=Math.round(S.mesh_lod),S.texture_lod=Math.round(S.texture_lod)),S.mesh_lod>=0&&this.loadProgressiveMeshes(s,S.mesh_lod),s.material&&S.texture_lod>=0&&this.loadProgressiveTextures(s.material,S.texture_lod,o),h&&s.material&&!s.isGizmo&&Ge(s.material),xt&&s.material&&!s.isGizmo&&!s.isBatchedMesh&&We(s.material,S.mesh_lod);for(const u of V)u.onAfterUpdatedLOD?.(this.renderer,t,e,s,S);n.lastLodLevel_Mesh=S.mesh_lod,n.lastLodLevel_Texture=S.texture_lod}loadProgressiveTextures(t,e,s){if(!t)return;if(Array.isArray(t)){for(const o of t)this.loadProgressiveTextures(o,e,s);return}let r=!1;(t[F]===void 0||e<t[F])&&(r=!0);const n=s!==void 0&&s>=0;if(n&&(r=t[F]!=s,e=s),r){t[F]=e;const o=n?{force:!0}:void 0,u=g.assignTextureLOD(t,e,o).then(a=>{this._lodchangedlisteners.forEach(l=>l({type:"texture",level:e,object:t}))});se.addPromise("texture",t,u,this._newPromiseGroups)}}loadProgressiveMeshes(t,e){if(!t)return Promise.resolve(null);let s=t[F]!==e;const r=t["DEBUG:LOD"];if(r!=null&&(s=t[F]!=r,e=r),s){t[F]=e;const n=t.geometry,o=g.assignMeshLOD(t,e).then(u=>(u&&t[F]==e&&n!=t.geometry&&this._lodchangedlisteners.forEach(a=>a({type:"mesh",level:e,object:t})),u));return se.addPromise("mesh",t,o,this._newPromiseGroups),o}return Promise.resolve(null)}_sphere=new d.Sphere;_tempWorldPosition=new d.Vector3;static skinnedMeshBoundsFrameOffsetCounter=0;static $skinnedMeshBoundsOffset=Symbol("gltf-progressive-skinnedMeshBoundsOffset");calculateLodLevel(t,e,s,r,n){if(!e){n.mesh_lod=-1,n.texture_lod=-1;return}if(!t){n.mesh_lod=-1,n.texture_lod=-1;return}let u=10+1,a=!1;if(A&&e["DEBUG:LOD"]!=null)return e["DEBUG:LOD"];const l=g.getMeshLODExtension(e.geometry)?.lods,c=g.getPrimitiveIndex(e.geometry),f=l&&l.length>0,p=g.getMaterialMinMaxLODsCount(e.material),y=p.min_count!==1/0&&p.min_count>=0&&p.max_count>=0;if(!f&&!y){n.mesh_lod=0,n.texture_lod=0;return}f||(a=!0,u=0);const w=this.renderer.domElement.clientHeight||this.renderer.domElement.height;let _=e.geometry.boundingBox;if(e.type==="SkinnedMesh"){const m=e;if(!m.boundingBox)m.computeBoundingBox();else if(this.skinnedMeshAutoUpdateBoundsInterval>0){if(!m[R.$skinnedMeshBoundsOffset]){const P=R.skinnedMeshBoundsFrameOffsetCounter++;m[R.$skinnedMeshBoundsOffset]=P}const M=m[R.$skinnedMeshBoundsOffset];if((s.frames+M)%this.skinnedMeshAutoUpdateBoundsInterval===0){const P=H(m),U=m.geometry;P&&(m.geometry=P),m.computeBoundingBox(),m.geometry=U}}_=m.boundingBox}if(_){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 P=t.getWorldPosition(this._tempWorldPosition);if(this._sphere.containsPoint(P)){n.mesh_lod=0,n.texture_lod=0;return}}const m=Ue({geometry:e.geometry,matrixWorld:e.matrixWorld,camera:t,projectionScreenMatrix:this.projectionScreenMatrix,desiredDensity:r,canvasHeight:w,currentLevel:s.lastLodLevel_Mesh,boundingBox:_,xrEnabled:this.renderer.xr.enabled,debugDrawLine:A?R.debugDrawLine:void 0,warnMissingPrimitiveDensities:!0});if(s.lastCentrality=m.centrality,s.lastScreenCoverage=m.screenCoverage,s.lastScreenspaceVolume.copy(m.screenspaceVolume),m.screenCoverage===1/0){n.mesh_lod=0,n.texture_lod=0;return}m.level>=0&&m.level<u&&(u=m.level,a=!0)}if(a?n.mesh_lod=u:n.mesh_lod=s.lastLodLevel_Mesh,A&&n.mesh_lod!=s.lastLodLevel_Mesh){const M=l?.[n.mesh_lod];M&&console.log(`Mesh LOD changed: ${s.lastLodLevel_Mesh} → ${n.mesh_lod} (density: ${M.densities?.[c].toFixed(0)}) | ${e.name}`)}if(y){const m="saveData"in globalThis.navigator&&globalThis.navigator.saveData===!0;if(s.lastLodLevel_Texture<0){if(n.texture_lod=p.max_count-1,A){const M=p.lods[p.max_count-1];A&&console.log(`First Texture LOD ${n.texture_lod} (${M.max_height}px) - ${e.name}`)}}else{const M=s.lastScreenspaceVolume.x+s.lastScreenspaceVolume.y+s.lastScreenspaceVolume.z;let P=s.lastScreenCoverage*4;this.context?.engine==="model-viewer"&&(P*=1.5);const v=w/window.devicePixelRatio*P;let L=!1;for(let C=p.lods.length-1;C>=0;C--){const O=p.lods[C];if(!(m&&O.max_height>=2048)&&!(ve()&&O.max_height>4096)&&(O.max_height>v||!L&&C===0)){if(L=!0,n.texture_lod=C,A&&n.texture_lod<s.lastLodLevel_Texture){const T=O.max_height;console.log(`Texture LOD changed: ${s.lastLodLevel_Texture} → ${n.texture_lod} = ${T}px
|
|
8
|
+
Screensize: ${v.toFixed(0)}px, Coverage: ${(100*s.lastScreenCoverage).toFixed(2)}%, Volume ${M.toFixed(1)}
|
|
9
|
+
${e.name}`)}break}}}}else n.texture_lod=0}}class Tt{frames=0;lastLodLevel_Mesh=-1;lastLodLevel_Texture=-1;lastScreenCoverage=0;lastScreenspaceVolume=new d.Vector3;lastCentrality=0}function We(i,t){if(!(t<0)){if(Array.isArray(i)){for(const e of i)We(e,t);return}"color"in i&&i.color instanceof d.Color&&(i.color.copy(Fe(t,Lt)),i.needsUpdate=!0)}}function Fe(i,t){const e=Math.max(0,Math.min(ye.length-1,Math.floor(i)));return t.setHex(ye[e])}const be=Symbol("NEEDLE_mesh_lod"),re=Symbol("NEEDLE_texture_lod");let he=null;function Me(){const i=bt();i&&(i.mapURLs(function(t){return Oe(),t}),Oe(),he?.disconnect(),he=new MutationObserver(t=>{t.forEach(e=>{e.addedNodes.forEach(s=>{s instanceof HTMLElement&&s.tagName.toLowerCase()==="model-viewer"&&qe(s)})})}),he.observe(document,{childList:!0,subtree:!0}))}function bt(){if(typeof customElements>"u")return null;const i=customElements.get("model-viewer");return i||(customElements.whenDefined("model-viewer").then(()=>{console.debug("[gltf-progressive] model-viewer defined"),Me()}),null)}function Oe(){if(typeof document>"u")return;document.querySelectorAll("model-viewer").forEach(t=>{qe(t)})}const Se=new WeakSet;let Ot=0;function qe(i){if(!i||Se.has(i))return null;Se.add(i),console.debug("[gltf-progressive] found new model-viewer..."+ ++Ot+`
|
|
10
|
+
`,i.getAttribute("src"));let t=null,e=null,s=null;for(let r=i;r!=null;r=Object.getPrototypeOf(r)){const n=Object.getOwnPropertySymbols(r),o=n.find(l=>l.toString()=="Symbol(renderer)"),u=n.find(l=>l.toString()=="Symbol(scene)"),a=n.find(l=>l.toString()=="Symbol(needsRender)");!t&&o!=null&&(t=i[o].threeRenderer),!e&&u!=null&&(e=i[u]),!s&&a!=null&&(s=i[a])}if(t&&e){let r=function(){if(s){let o=0;const u=setInterval(()=>{if(o++>5){clearInterval(u);return}s?.call(i)},300)}};console.debug("[gltf-progressive] setup model-viewer");const n=R.get(t,{engine:"model-viewer"});return R.addPlugin(new St),n.enable(),n.addEventListener("changed",()=>{s?.call(i)}),i.addEventListener("model-visibility",o=>{o.detail.visible&&s?.call(i)}),i.addEventListener("load",()=>{r()}),()=>{n.disable()}}return null}class St{_didWarnAboutMissingUrl=!1;onBeforeUpdateLOD(t,e,s,r){this.tryParseMeshLOD(e,r),this.tryParseTextureLOD(e,r)}getUrl(t){if(!t)return null;let e=t.getAttribute("src");return e||(e=t.src),e||(this._didWarnAboutMissingUrl||console.warn("No url found in modelviewer",t),this._didWarnAboutMissingUrl=!0),e}tryGetCurrentGLTF(t){return t._currentGLTF}tryGetCurrentModelViewer(t){return t.element}tryParseTextureLOD(t,e){if(e[re]==!0)return;e[re]=!0;const s=this.tryGetCurrentGLTF(t),r=this.tryGetCurrentModelViewer(t),n=this.getUrl(r);if(n&&s&&e.material){let o=function(a){if(a[re]==!0)return;a[re]=!0,a.userData&&(a.userData.LOD=-1);const l=Object.keys(a);for(let c=0;c<l.length;c++){const f=l[c],p=a[f];if(p?.isTexture===!0){const y=p.userData?.associations?.textures;if(y==null)continue;const w=s.parser.json.textures[y];if(!w){console.warn("Texture data not found for texture index "+y);continue}if(w?.extensions?.[G]){const _=w.extensions[G];_&&n&&g.registerTexture(n,p,_.lods.length,y,_)}}}};const u=e.material;if(Array.isArray(u))for(const a of u)o(a);else o(u)}}tryParseMeshLOD(t,e){if(e[be]==!0)return;e[be]=!0;const s=this.tryGetCurrentModelViewer(t),r=this.getUrl(s);if(!r)return;const n=e.userData?.gltfExtensions?.[G];if(n&&r){const o=e.uuid;g.registerMesh(r,o,e,0,n.lods.length,n)}}}function Ve(...i){let t,e,s,r;switch(i.length){case 2:[s,e]=i,r={};break;case 3:[s,e,r]=i;break;case 4:[t,e,s,r]=i;break;default:throw new Error("Invalid arguments")}oe(e),we(s),Le(s,{progressive:!0,...r?.hints}),s.register(o=>new g(o));const n=R.get(e);return r?.enableLODsManager!==!1&&n.enable(),n}Me();if(!ct){const i={gltfProgressive:{useNeedleProgressive:Ve,LODsManager:R,configureLoader:Le,getRaycastMesh:H,useRaycastMeshes:Be}};if(!globalThis.Needle)globalThis.Needle=i;else for(const t in i)globalThis.Needle[t]=i[t]}exports.EXTENSION_NAME=G;exports.LODsManager=R;exports.NEEDLE_progressive=g;exports.VERSION=Ce;exports.addDracoAndKTX2Loaders=we;exports.calculateMeshLODLevel=Ue;exports.configureLoader=Le;exports.createLoaders=oe;exports.getLODColor=Fe;exports.getRaycastMesh=H;exports.lodDebugColors=ye;exports.patchModelViewer=Me;exports.registerRaycastMesh=$e;exports.setDracoDecoderLocation=ke;exports.setKTX2TranscoderLocation=Re;exports.useNeedleProgressive=Ve;exports.useRaycastMeshes=Be;
|