@needle-tools/gltf-progressive 2.1.6-next.fa4044e → 2.1.6
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/gltf-progressive.js +672 -663
- package/gltf-progressive.min.js +7 -7
- package/gltf-progressive.umd.cjs +8 -8
- package/lib/extension.d.ts +6 -10
- package/lib/extension.js +94 -20
- package/lib/lods_manager.d.ts +1 -6
- package/lib/lods_manager.js +10 -26
- package/lib/plugins/plugin.d.ts +2 -2
- package/package.json +2 -2
- package/lib/lods.debug.d.ts +0 -4
- package/lib/lods.debug.js +0 -41
package/gltf-progressive.min.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var He=Object.defineProperty,Ye=(t,e,s)=>e in t?He(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,d=(t,e,s)=>(Ye(t,typeof e!="symbol"?e+"":e,s),s),Ee=(t,e,s)=>{if(!e.has(t))throw TypeError("Cannot "+s)},v=(t,e,s)=>(Ee(t,e,"read from private field"),s?s.call(t):e.get(t)),H=(t,e,s)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,s)},F=(t,e,s,n)=>(Ee(t,e,"write to private field"),n?n.call(t,s):e.set(t,s),s);import{BufferGeometry as ue,Mesh as Y,Texture as se,TextureLoader as Je,Matrix4 as Pe,Clock as Qe,MeshStandardMaterial as Ze,Sphere as et,Box3 as Ie,Vector3 as z}from"three";import{GLTFLoader as xe}from"three/examples/jsm/loaders/GLTFLoader.js";import{MeshoptDecoder as tt}from"three/examples/jsm/libs/meshopt_decoder.module.js";import{DRACOLoader as st}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as rt}from"three/examples/jsm/loaders/KTX2Loader.js";const Ce="";globalThis.GLTF_PROGRESSIVE_VERSION=Ce,console.debug("[gltf-progressive] version -");let $="https://www.gstatic.com/draco/versioned/decoders/1.5.7/",Q="https://www.gstatic.com/basis-universal/versioned/2021-04-15-ba1c3e4/";const ot=$,nt=Q,Be=new URL($+"draco_decoder.js");Be.searchParams.append("range","true"),fetch(Be,{method:"GET",headers:{Range:"bytes=0-1"}}).catch(t=>{console.debug(`Failed to fetch remote Draco decoder from ${$} (offline: ${typeof navigator<"u"?navigator.onLine:"unknown"})`),$===ot&&ke("./include/draco/"),Q===nt&&Re("./include/ktx2/")}).finally(()=>{je()});function ke(t){$=t,B&&B[ye]!=$?(console.debug("Updating Draco decoder path to "+t),B[ye]=$,B.setDecoderPath($),B.preload()):console.debug("Setting Draco decoder path to "+t)}function Re(t){Q=t,G&&G.transcoderPath!=Q?(console.debug("Updating KTX2 transcoder path to "+t),G.setTranscoderPath(Q),G.init()):console.debug("Setting KTX2 transcoder path to "+t)}const ye=Symbol("dracoDecoderPath");let B,ce,G;function je(){B||(B=new st,B[ye]=$,B.setDecoderPath($),B.setDecoderConfig({type:"js"}),B.preload()),G||(G=new rt,G.setTranscoderPath(Q),G.init()),ce||(ce=tt)}function Le(t){return je(),t?G.detectSupport(t):t!==null&&console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures might fail"),{dracoLoader:B,ktx2Loader:G,meshoptDecoder:ce}}function De(t){t.dracoLoader||t.setDRACOLoader(B),t.ktx2Loader||t.setKTX2Loader(G),t.meshoptDecoder||t.setMeshoptDecoder(ce)}const Me=new WeakMap;function we(t,e){let s=Me.get(t);s?s=Object.assign(s,e):s=e,Me.set(t,s)}const Ge=xe.prototype.load;function it(...t){const e=Me.get(this);let s=t[0];const n=new URL(s,window.location.href);if(n.hostname.endsWith("needle.tools")){const r=e?.progressive!==void 0?e.progressive:!0,o=e!=null&&e.usecase?e.usecase:"default";r?this.requestHeader.Accept=`*/*;progressive=allowed;usecase=${o}`:this.requestHeader.Accept=`*/*;usecase=${o}`,s=n.toString()}return t[0]=s,Ge?.call(this,...t)}xe.prototype.load=it,re("debugprogressive");function re(t){if(typeof window>"u")return!1;const e=new URL(window.location.href).searchParams.get(t);return e==null||e==="0"||e==="false"?!1:e===""?!0:e}function at(t,e){if(e===void 0||e.startsWith("./")||e.startsWith("http")||t===void 0)return e;const s=t.lastIndexOf("/");if(s>=0){const n=t.substring(0,s+1);for(;n.endsWith("/")&&e.startsWith("/");)e=e.substring(1);return n+e}return e}let de;function lt(){return de!==void 0||(de=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent),re("debugprogressive")&&console.log("[glTF Progressive]: isMobileDevice",de)),de}const ut=typeof window>"u"&&typeof document>"u",_e=Symbol("needle:raycast-mesh");function Z(t){return t?.[_e]instanceof ue?t[_e]:null}function Ne(t,e){if((t.type==="Mesh"||t.type==="SkinnedMesh")&&!Z(t)){const s=ct(e);s.userData={isRaycastMesh:!0},t[_e]=s}}function $e(t=!0){if(t){if(oe)return;const e=oe=Y.prototype.raycast;Y.prototype.raycast=function(s,n){const r=this,o=Z(r);let i;o&&r.isMesh&&(i=r.geometry,r.geometry=o),e.call(this,s,n),i&&(r.geometry=i)}}else{if(!oe)return;Y.prototype.raycast=oe,oe=null}}let oe=null;function ct(t){const e=new ue;for(const s in t.attributes)e.setAttribute(s,t.getAttribute(s));return e.setIndex(t.getIndex()),e}const V=new Array,L=re("debugprogressive");let he,J=-1;if(L){let t=function(){J+=1,J>=e&&(J=-1),console.log(`Toggle LOD level [${J}]`)},e=6;window.addEventListener("keyup",s=>{s.key==="p"&&t(),s.key==="w"&&(he=!he,console.log(`Toggle wireframe [${he}]`));const n=parseInt(s.key);!isNaN(n)&&n>=0&&(J=n,console.log(`Set LOD level to [${J}]`))})}function We(t){if(L)if(Array.isArray(t))for(const e of t)We(e);else t&&"wireframe"in t&&(t.wireframe=he===!0)}const W="NEEDLE_progressive",be=Symbol("needle-progressive-texture"),w=class{constructor(t,e){d(this,"parser"),d(this,"url"),d(this,"_isLoadingMesh"),d(this,"loadMesh",s=>{var n,r;if(this._isLoadingMesh)return null;const o=(r=(n=this.parser.json.meshes[s])==null?void 0:n.extensions)==null?void 0:r[W];return o?(this._isLoadingMesh=!0,this.parser.getDependency("mesh",s).then(i=>{var l;return this._isLoadingMesh=!1,i&&w.registerMesh(this.url,o.guid,i,(l=o.lods)==null?void 0:l.length,0,o),i})):null}),L&&console.log("Progressive extension registered for",e),this.parser=t,this.url=e}get name(){return W}static getMeshLODExtension(t){const e=this.getAssignedLODInformation(t);return e!=null&&e.key?this.lodInfos.get(e.key):null}static getPrimitiveIndex(t){var e;return((e=this.getAssignedLODInformation(t))==null?void 0:e.index)??-1}static getMaterialMinMaxLODsCount(t,e){const s=this,n="LODS:minmax",r=t[n];if(r!=null)return r;if(e||(e={min_count:1/0,max_count:0,lods:[]}),Array.isArray(t)){for(const i of t)this.getMaterialMinMaxLODsCount(i,e);return t[n]=e,e}if(L==="verbose"&&console.log("getMaterialMinMaxLODsCount",t),t.type==="ShaderMaterial"||t.type==="RawShaderMaterial"){const i=t;for(const l of Object.keys(i.uniforms)){const u=i.uniforms[l].value;u?.isTexture===!0&&o(u,e)}}else if(t.isMaterial)for(const i of Object.keys(t)){const l=t[i];l?.isTexture===!0&&o(l,e)}return t[n]=e,e;function o(i,l){const u=s.getAssignedLODInformation(i);if(u){const a=s.lodInfos.get(u.key);if(a&&a.lods){l.min_count=Math.min(l.min_count,a.lods.length),l.max_count=Math.max(l.max_count,a.lods.length);for(let h=0;h<a.lods.length;h++){const x=a.lods[h];x.width&&(l.lods[h]=l.lods[h]||{min_height:1/0,max_height:0},l.lods[h].min_height=Math.min(l.lods[h].min_height,x.height),l.lods[h].max_height=Math.max(l.lods[h].max_height,x.height))}}}}}static hasLODLevelAvailable(t,e){var s;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 i=t[o];if(i&&i.isTexture&&this.hasLODLevelAvailable(i,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 n,r;if(t.isMesh?n=t.geometry:(t.isBufferGeometry||t.isTexture)&&(n=t),n&&(s=n?.userData)!=null&&s.LODS){const o=n.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){var s;if(!t)return Promise.resolve(null);if(t instanceof Y||t.isMesh===!0){const n=t.geometry,r=this.getAssignedLODInformation(n);if(!r)return Promise.resolve(null);for(const o of V)(s=o.onBeforeGetLODMesh)==null||s.call(o,t,e);return t["LOD:requested level"]=e,w.getOrLoadLOD(n,e).then(o=>{if(Array.isArray(o)){const i=r.index||0;o=o[i]}return t["LOD:requested level"]===e&&(delete t["LOD:requested level"],o&&n!=o&&(o?.isBufferGeometry?t.geometry=o:L&&console.error("Invalid LOD geometry",o))),o}).catch(o=>(console.error("Error loading mesh LOD",t,o),null))}else L&&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 n=new Array;for(const r of s.material){const o=this.assignTextureLOD(r,e);n.push(o)}return Promise.all(n).then(r=>{const o=new Array;for(const i of r)Array.isArray(i)&&o.push(...i);return o})}else return this.assignTextureLOD(s.material,e)}if(t.isMaterial===!0){const s=t,n=[],r=new Array;if(s.uniforms&&(s.isRawShaderMaterial||s.isShaderMaterial===!0)){const o=s;for(const i of Object.keys(o.uniforms)){const l=o.uniforms[i].value;if(l?.isTexture===!0){const u=this.assignTextureLODForSlot(l,e,s,i).then(a=>(a&&o.uniforms[i].value!=a&&(o.uniforms[i].value=a,o.uniformsNeedUpdate=!0),a));n.push(u),r.push(i)}}}else for(const o of Object.keys(s)){const i=s[o];if(i?.isTexture===!0){const l=this.assignTextureLODForSlot(i,e,s,o);n.push(l),r.push(o)}}return Promise.all(n).then(o=>{const i=new Array;for(let l=0;l<o.length;l++){const u=o[l],a=r[l];u&&u.isTexture===!0?i.push({material:s,slot:a,texture:u,level:e}):i.push({material:s,slot:a,texture:null,level:e})}return i})}if(t instanceof se||t.isTexture===!0){const s=t;return this.assignTextureLODForSlot(s,e,null,null)}return Promise.resolve(null)}static assignTextureLODForSlot(t,e,s,n){return t?.isTexture!==!0?Promise.resolve(null):n==="glyphMap"?Promise.resolve(t):w.getOrLoadLOD(t,e).then(r=>{if(Array.isArray(r))return null;if(r?.isTexture===!0){if(r!=t&&s&&n){const o=s[n];if(o&&!L){const i=this.getAssignedLODInformation(o);if(i&&i?.level<e)return L==="verbose"&&console.warn("Assigned texture level is already higher: ",i.level,e,s,o,r),null}s[n]=r}return r}else L=="verbose"&&console.warn("No LOD found for",t,e);return null}).catch(r=>(console.error("Error loading LOD",t,r),null))}afterRoot(t){var e,s;return L&&console.log("AFTER",this.url,t),(e=this.parser.json.textures)==null||e.forEach((n,r)=>{var o;if(n!=null&&n.extensions){const i=n?.extensions[W];if(i){if(!i.lods){L&&console.warn("Texture has no LODs",i);return}let l=!1;for(const u of this.parser.associations.keys())if(u.isTexture===!0){const a=this.parser.associations.get(u);a?.textures===r&&(l=!0,w.registerTexture(this.url,u,(o=i.lods)==null?void 0:o.length,r,i))}l||this.parser.getDependency("texture",r).then(u=>{var a;u&&w.registerTexture(this.url,u,(a=i.lods)==null?void 0:a.length,r,i)})}}}),(s=this.parser.json.meshes)==null||s.forEach((n,r)=>{if(n!=null&&n.extensions){const o=n?.extensions[W];if(o&&o.lods){for(const i of this.parser.associations.keys())if(i.isMesh){const l=this.parser.associations.get(i);l?.meshes===r&&w.registerMesh(this.url,o.guid,i,o.lods.length,l.primitives,o)}}}}),null}static async getOrLoadLOD(t,e){var s,n,r,o;const i=L=="verbose",l=t.userData.LODS;if(!l)return null;const u=l?.key;let a;if(t.isTexture===!0){const h=t;h.source&&h.source[be]&&(a=h.source[be])}if(a||(a=w.lodInfos.get(u)),a){if(e>0){let m=!1;const M=Array.isArray(a.lods);if(M&&e>=a.lods.length?m=!0:M||(m=!0),m)return this.lowresCache.get(u)}const h=Array.isArray(a.lods)?(s=a.lods[e])==null?void 0:s.path:a.lods;if(!h)return L&&!a["missing:uri"]&&(a["missing:uri"]=!0,console.warn("Missing uri for progressive asset for LOD "+e,a)),null;const x=at(l.url,h);if(x.endsWith(".glb")||x.endsWith(".gltf")){if(!a.guid)return console.warn("missing pointer for glb/gltf texture",a),null;const m=x+"_"+a.guid,M=this.previouslyLoaded.get(m);if(M!==void 0){i&&console.log(`LOD ${e} was already loading/loaded: ${m}`);let y=await M.catch(f=>(console.error(`Error loading LOD ${e} from ${x}
|
|
2
|
-
`,
|
|
3
|
-
`,
|
|
1
|
+
var Xe=Object.defineProperty,He=(t,e,r)=>e in t?Xe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,c=(t,e,r)=>(He(t,typeof e!="symbol"?e+"":e,r),r),Te=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},L=(t,e,r)=>(Te(t,e,"read from private field"),r?r.call(t):e.get(t)),K=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},$=(t,e,r,n)=>(Te(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r);import{BufferGeometry as le,Mesh as Y,Texture as te,TextureLoader as Ke,Matrix4 as Ee,Clock as Ye,MeshStandardMaterial as Je,Sphere as Qe,Box3 as Ae,Vector3 as F}from"three";import{GLTFLoader as me}from"three/examples/jsm/loaders/GLTFLoader.js";import{MeshoptDecoder as Ze}from"three/examples/jsm/libs/meshopt_decoder.module.js";import{DRACOLoader as et}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as tt}from"three/examples/jsm/loaders/KTX2Loader.js";const Pe="";globalThis.GLTF_PROGRESSIVE_VERSION=Pe,console.debug("[gltf-progressive] version -");let W="https://www.gstatic.com/draco/versioned/decoders/1.5.7/",Q="https://www.gstatic.com/basis-universal/versioned/2021-04-15-ba1c3e4/";const rt=W,st=Q,Ie=new URL(W+"draco_decoder.js");Ie.searchParams.append("range","true"),fetch(Ie,{method:"GET",headers:{Range:"bytes=0-1"}}).catch(t=>{console.debug(`Failed to fetch remote Draco decoder from ${W} (offline: ${typeof navigator<"u"?navigator.onLine:"unknown"})`),W===rt&&Be("./include/draco/"),Q===st&&ke("./include/ktx2/")}).finally(()=>{Ce()});function Be(t){W=t,P&&P[pe]!=W?(console.debug("Updating Draco decoder path to "+t),P[pe]=W,P.setDecoderPath(W),P.preload()):console.debug("Setting Draco decoder path to "+t)}function ke(t){Q=t,C&&C.transcoderPath!=Q?(console.debug("Updating KTX2 transcoder path to "+t),C.setTranscoderPath(Q),C.init()):console.debug("Setting KTX2 transcoder path to "+t)}const pe=Symbol("dracoDecoderPath");let P,ue,C;function Ce(){P||(P=new et,P[pe]=W,P.setDecoderPath(W),P.setDecoderConfig({type:"js"}),P.preload()),C||(C=new tt,C.setTranscoderPath(Q),C.init()),ue||(ue=Ze)}function ve(t){return Ce(),t?C.detectSupport(t):t!==null&&console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures might fail"),{dracoLoader:P,ktx2Loader:C,meshoptDecoder:ue}}function ye(t){t.dracoLoader||t.setDRACOLoader(P),t.ktx2Loader||t.setKTX2Loader(C),t.meshoptDecoder||t.setMeshoptDecoder(ue)}const xe=new WeakMap;function Le(t,e){let r=xe.get(t);r?r=Object.assign(r,e):r=e,xe.set(t,r)}const Re=me.prototype.load;function ot(...t){const e=xe.get(this);let r=t[0];const n=new URL(r,window.location.href);if(n.hostname.endsWith("needle.tools")){const s=e?.progressive!==void 0?e.progressive:!0,o=e!=null&&e.usecase?e.usecase:"default";s?this.requestHeader.Accept=`*/*;progressive=allowed;usecase=${o}`:this.requestHeader.Accept=`*/*;usecase=${o}`,r=n.toString()}return t[0]=r,Re?.call(this,...t)}me.prototype.load=ot,re("debugprogressive");function re(t){if(typeof window>"u")return!1;const e=new URL(window.location.href).searchParams.get(t);return e==null||e==="0"||e==="false"?!1:e===""?!0:e}function nt(t,e){if(e===void 0||e.startsWith("./")||e.startsWith("http")||t===void 0)return e;const r=t.lastIndexOf("/");if(r>=0){const n=t.substring(0,r+1);for(;n.endsWith("/")&&e.startsWith("/");)e=e.substring(1);return n+e}return e}let ce;function it(){return ce!==void 0||(ce=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent),re("debugprogressive")&&console.log("[glTF Progressive]: isMobileDevice",ce)),ce}const at=typeof window>"u"&&typeof document>"u",Me=Symbol("needle:raycast-mesh");function Z(t){return t?.[Me]instanceof le?t[Me]:null}function je(t,e){if((t.type==="Mesh"||t.type==="SkinnedMesh")&&!Z(t)){const r=lt(e);r.userData={isRaycastMesh:!0},t[Me]=r}}function Ne(t=!0){if(t){if(se)return;const e=se=Y.prototype.raycast;Y.prototype.raycast=function(r,n){const s=this,o=Z(s);let i;o&&s.isMesh&&(i=s.geometry,s.geometry=o),e.call(this,r,n),i&&(s.geometry=i)}}else{if(!se)return;Y.prototype.raycast=se,se=null}}let se=null;function lt(t){const e=new le;for(const r in t.attributes)e.setAttribute(r,t.getAttribute(r));return e.setIndex(t.getIndex()),e}const z=new Array,U="NEEDLE_progressive",y=re("debugprogressive"),De=Symbol("needle-progressive-texture"),oe=new Map,we=new Set;if(y){let t=function(){e+=1,console.log("Toggle LOD level",e,oe),oe.forEach((s,o)=>{for(const i of s.keys){const l=o[i];if(l!=null)if(l.isBufferGeometry===!0){const u=T.getMeshLODInformation(l),a=u?Math.min(e,u.lods.length):0;o["DEBUG:LOD"]=a,u&&(r=Math.max(r,u.lods.length-1))}else o.isMaterial===!0&&(o["DEBUG:LOD"]=e)}}),e>=r&&(e=-1)},e=-1,r=2,n=!1;window.addEventListener("keyup",s=>{s.key==="p"&&t(),s.key==="w"&&(n=!n,we&&we.forEach(o=>{o.name!="BackgroundCubeMaterial"&&o.glyphMap==null&&"wireframe"in o&&(o.wireframe=n)}))})}function Ge(t,e,r){var n;if(!y)return;oe.has(t)||oe.set(t,{keys:[],sourceId:r});const s=oe.get(t);((n=s?.keys)==null?void 0:n.includes(e))==!1&&s.keys.push(e)}const w=class{constructor(t,e){c(this,"parser"),c(this,"url"),c(this,"_isLoadingMesh"),c(this,"loadMesh",r=>{var n,s;if(this._isLoadingMesh)return null;const o=(s=(n=this.parser.json.meshes[r])==null?void 0:n.extensions)==null?void 0:s[U];return o?(this._isLoadingMesh=!0,this.parser.getDependency("mesh",r).then(i=>{var l;return this._isLoadingMesh=!1,i&&w.registerMesh(this.url,o.guid,i,(l=o.lods)==null?void 0:l.length,void 0,o),i})):null}),y&&console.log("Progressive extension registered for",e),this.parser=t,this.url=e}get name(){return U}static getMeshLODInformation(t){const e=this.getAssignedLODInformation(t);return e!=null&&e.key?this.lodInfos.get(e.key):null}static getMaterialMinMaxLODsCount(t,e){const r=this,n="LODS:minmax",s=t[n];if(s!=null)return s;if(e||(e={min_count:1/0,max_count:0,lods:[]}),Array.isArray(t)){for(const i of t)this.getMaterialMinMaxLODsCount(i,e);return t[n]=e,e}if(y==="verbose"&&console.log("getMaterialMinMaxLODsCount",t),t.type==="ShaderMaterial"||t.type==="RawShaderMaterial"){const i=t;for(const l of Object.keys(i.uniforms)){const u=i.uniforms[l].value;u?.isTexture===!0&&o(u,e)}}else if(t.isMaterial)for(const i of Object.keys(t)){const l=t[i];l?.isTexture===!0&&o(l,e)}return t[n]=e,e;function o(i,l){const u=r.getAssignedLODInformation(i);if(u){const a=r.lodInfos.get(u.key);if(a&&a.lods){l.min_count=Math.min(l.min_count,a.lods.length),l.max_count=Math.max(l.max_count,a.lods.length);for(let g=0;g<a.lods.length;g++){const f=a.lods[g];f.width&&(l.lods[g]=l.lods[g]||{min_height:1/0,max_height:0},l.lods[g].min_height=Math.min(l.lods[g].min_height,f.height),l.lods[g].max_height=Math.max(l.lods[g].max_height,f.height))}}}}}static hasLODLevelAvailable(t,e){var r;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 i=t[o];if(i&&i.isTexture&&this.hasLODLevelAvailable(i,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 n,s;if(t.isMesh?n=t.geometry:(t.isBufferGeometry||t.isTexture)&&(n=t),n&&(r=n?.userData)!=null&&r.LODS){const o=n.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){var r;if(!t)return Promise.resolve(null);if(t instanceof Y||t.isMesh===!0){const n=t.geometry,s=this.getAssignedLODInformation(n);if(!s)return Promise.resolve(null);for(const o of z)(r=o.onBeforeGetLODMesh)==null||r.call(o,t,e);return t["LOD:requested level"]=e,w.getOrLoadLOD(n,e).then(o=>{if(Array.isArray(o)){const i=s.index||0;o=o[i]}return t["LOD:requested level"]===e&&(delete t["LOD:requested level"],o&&n!=o&&(o?.isBufferGeometry?(t.geometry=o,y&&Ge(t,"geometry",s.url)):y&&console.error("Invalid LOD geometry",o))),o}).catch(o=>(console.error("Error loading mesh LOD",t,o),null))}else y&&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 r=t;if(Array.isArray(r.material)){const n=new Array;for(const s of r.material){const o=this.assignTextureLOD(s,e);n.push(o)}return Promise.all(n).then(s=>{const o=new Array;for(const i of s)Array.isArray(i)&&o.push(...i);return o})}else return this.assignTextureLOD(r.material,e)}if(t.isMaterial===!0){const r=t,n=[],s=new Array;if(y&&we.add(r),r.uniforms&&(r.isRawShaderMaterial||r.isShaderMaterial===!0)){const o=r;for(const i of Object.keys(o.uniforms)){const l=o.uniforms[i].value;if(l?.isTexture===!0){const u=this.assignTextureLODForSlot(l,e,r,i).then(a=>(a&&o.uniforms[i].value!=a&&(o.uniforms[i].value=a,o.uniformsNeedUpdate=!0),a));n.push(u),s.push(i)}}}else for(const o of Object.keys(r)){const i=r[o];if(i?.isTexture===!0){const l=this.assignTextureLODForSlot(i,e,r,o);n.push(l),s.push(o)}}return Promise.all(n).then(o=>{const i=new Array;for(let l=0;l<o.length;l++){const u=o[l],a=s[l];u&&u.isTexture===!0?i.push({material:r,slot:a,texture:u,level:e}):i.push({material:r,slot:a,texture:null,level:e})}return i})}if(t instanceof te||t.isTexture===!0){const r=t;return this.assignTextureLODForSlot(r,e,null,null)}return Promise.resolve(null)}static assignTextureLODForSlot(t,e,r,n){return t?.isTexture!==!0?Promise.resolve(null):n==="glyphMap"?Promise.resolve(t):w.getOrLoadLOD(t,e).then(s=>{if(Array.isArray(s))return null;if(s?.isTexture===!0){if(s!=t){if(r&&n){const o=r[n];if(o&&!y){const i=this.getAssignedLODInformation(o);if(i&&i?.level<e)return y==="verbose"&&console.warn("Assigned texture level is already higher: ",i.level,e,r,o,s),null}r[n]=s}if(y&&n&&r){const o=this.getAssignedLODInformation(t);o?Ge(r,n,o.url):console.warn("No LOD info for texture",t)}}return s}else y=="verbose"&&console.warn("No LOD found for",t,e);return null}).catch(s=>(console.error("Error loading LOD",t,s),null))}afterRoot(t){var e,r;return y&&console.log("AFTER",this.url,t),(e=this.parser.json.textures)==null||e.forEach((n,s)=>{var o;if(n!=null&&n.extensions){const i=n?.extensions[U];if(i){if(!i.lods){y&&console.warn("Texture has no LODs",i);return}let l=!1;for(const u of this.parser.associations.keys())if(u.isTexture===!0){const a=this.parser.associations.get(u);a?.textures===s&&(l=!0,w.registerTexture(this.url,u,(o=i.lods)==null?void 0:o.length,s,i))}l||this.parser.getDependency("texture",s).then(u=>{var a;u&&w.registerTexture(this.url,u,(a=i.lods)==null?void 0:a.length,s,i)})}}}),(r=this.parser.json.meshes)==null||r.forEach((n,s)=>{if(n!=null&&n.extensions){const o=n?.extensions[U];if(o&&o.lods){for(const i of this.parser.associations.keys())if(i.isMesh){const l=this.parser.associations.get(i);l?.meshes===s&&w.registerMesh(this.url,o.guid,i,o.lods.length,l.primitives,o)}}}}),null}static async getOrLoadLOD(t,e){var r,n,s,o;const i=y=="verbose",l=t.userData.LODS;if(!l)return null;const u=l?.key;let a;if(t.isTexture===!0){const g=t;g.source&&g.source[De]&&(a=g.source[De])}if(a||(a=w.lodInfos.get(u)),a){if(e>0){let v=!1;const A=Array.isArray(a.lods);if(A&&e>=a.lods.length?v=!0:A||(v=!0),v)return this.lowresCache.get(u)}const g=Array.isArray(a.lods)?(r=a.lods[e])==null?void 0:r.path:a.lods;if(!g)return y&&!a["missing:uri"]&&(a["missing:uri"]=!0,console.warn("Missing uri for progressive asset for LOD "+e,a)),null;const f=nt(l.url,g);if(f.endsWith(".glb")||f.endsWith(".gltf")){if(!a.guid)return console.warn("missing pointer for glb/gltf texture",a),null;const v=f+"_"+a.guid,A=this.previouslyLoaded.get(v);if(A!==void 0){i&&console.log(`LOD ${e} was already loading/loaded: ${v}`);let d=await A.catch(O=>(console.error(`Error loading LOD ${e} from ${f}
|
|
2
|
+
`,O),null)),b=!1;if(d==null||(d instanceof te&&t instanceof te?(n=d.image)!=null&&n.data||(s=d.source)!=null&&s.data?d=this.copySettings(t,d):(b=!0,this.previouslyLoaded.delete(v)):d instanceof le&&t instanceof le&&((o=d.attributes.position)!=null&&o.array||(b=!0,this.previouslyLoaded.delete(v)))),!b)return d}const D=a,x=new Promise(async(d,b)=>{const O=new me;ye(O),y&&(await new Promise(p=>setTimeout(p,1e3)),i&&console.warn("Start loading (delayed) "+f,D.guid));let B=f;if(D&&Array.isArray(D.lods)){const p=D.lods[e];p.hash&&(B+="?v="+p.hash)}const _=await O.loadAsync(B).catch(p=>(console.error(`Error loading LOD ${e} from ${f}
|
|
3
|
+
`,p),null));if(!_)return null;const k=_.parser;i&&console.log("Loading finished "+f,D.guid);let m=0;if(_.parser.json.textures){let p=!1;for(const h of _.parser.json.textures){if(h!=null&&h.extensions){const M=h?.extensions[U];if(M!=null&&M.guid&&M.guid===D.guid){p=!0;break}}m++}if(p){let h=await k.getDependency("texture",m);return h&&w.assignLODInformation(l.url,h,u,e,void 0,void 0),i&&console.log('change "'+t.name+'" \u2192 "'+h.name+'"',f,m,h,v),t instanceof te&&(h=this.copySettings(t,h)),h&&(h.guid=D.guid),d(h)}else y&&console.warn("Could not find texture with guid",D.guid,_.parser.json)}if(m=0,_.parser.json.meshes){let p=!1;for(const h of _.parser.json.meshes){if(h!=null&&h.extensions){const M=h?.extensions[U];if(M!=null&&M.guid&&M.guid===D.guid){p=!0;break}}m++}if(p){const h=await k.getDependency("mesh",m),M=D;if(i&&console.log(`Loaded Mesh "${h.name}"`,f,m,h,v),h.isMesh===!0){const S=h.geometry;return w.assignLODInformation(l.url,S,u,e,void 0,M.density),d(S)}else{const S=new Array;for(let G=0;G<h.children.length;G++){const H=h.children[G];if(H.isMesh===!0){const J=H.geometry;w.assignLODInformation(l.url,J,u,e,G,M.density),S.push(J)}}return d(S)}}else y&&console.warn("Could not find mesh with guid",D.guid,_.parser.json)}return d(null)});return this.previouslyLoaded.set(v,x),await x}else if(t instanceof te){i&&console.log("Load texture from uri: "+f);const v=await new Ke().loadAsync(f);return v?(v.guid=a.guid,v.flipY=!1,v.needsUpdate=!0,v.colorSpace=t.colorSpace,i&&console.log(a,v)):y&&console.warn("failed loading",f),v}}else y&&console.warn(`Can not load LOD ${e}: no LOD info found for "${u}" ${t.name}`,t.type);return null}static assignLODInformation(t,e,r,n,s,o){if(!e)return;e.userData||(e.userData={});const i=new ut(t,r,n,s,o);e.userData.LODS=i}static getAssignedLODInformation(t){var e;return((e=t?.userData)==null?void 0:e.LODS)||null}static copySettings(t,e){return e?(y&&console.warn(`Copy texture settings
|
|
4
4
|
`,t.uuid,`
|
|
5
|
-
`,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}};let T=w;d(T,"registerTexture",(t,e,s,n,r)=>{if(L&&console.log("> Progressive: register texture",n,e.name,e.uuid,e,r),!e){L&&console.error("gltf-progressive: Register texture without texture");return}e.source&&(e.source[be]=r);const o=r.guid;w.assignLODInformation(t,e,o,s,n),w.lodInfos.set(o,r),w.lowresCache.set(o,e)}),d(T,"registerMesh",(t,e,s,n,r,o)=>{var i;const l=s.geometry;if(!l){L&&console.warn("gltf-progressive: Register mesh without geometry");return}l.userData||(l.userData={}),L&&console.log("> Progressive: register mesh "+s.name,{index:r,uuid:s.uuid},o,s),w.assignLODInformation(t,l,e,n,r),w.lodInfos.set(e,o);let u=w.lowresCache.get(e);u?u.push(s.geometry):u=[s.geometry],w.lowresCache.set(e,u),n>0&&!Z(s)&&Ne(s,l);for(const a of V)(i=a.onRegisteredNewMesh)==null||i.call(a,s,o)}),d(T,"lodInfos",new Map),d(T,"previouslyLoaded",new Map),d(T,"lowresCache",new Map);class dt{constructor(e,s,n,r){d(this,"url"),d(this,"key"),d(this,"level"),d(this,"index"),this.url=e,this.key=s,this.level=n,r!=null&&(this.index=r)}}const N=re("debugprogressive"),ht=re("noprogressive"),Oe=Symbol("Needle:LODSManager"),Se=Symbol("Needle:LODState"),q=Symbol("Needle:CurrentLOD"),A={mesh_lod:-1,texture_lod:-1};var E,X,Te,ee,ne,ge,K;const P=class{constructor(t,e){d(this,"context"),d(this,"renderer"),d(this,"projectionScreenMatrix",new Pe),d(this,"targetTriangleDensity",2e5),d(this,"skinnedMeshAutoUpdateBoundsInterval",30),d(this,"updateInterval","auto"),H(this,E,1),d(this,"pause",!1),d(this,"manual",!1),d(this,"_lodchangedlisteners",[]),H(this,X,void 0),H(this,Te,new Qe),H(this,ee,0),H(this,ne,0),H(this,ge,0),H(this,K,0),d(this,"_fpsBuffer",[60,60,60,60,60]),d(this,"_sphere",new et),d(this,"_tempBox",new Ie),d(this,"_tempBox2",new Ie),d(this,"tempMatrix",new Pe),d(this,"_tempWorldPosition",new z),d(this,"_tempBoxSize",new z),d(this,"_tempBox2Size",new z),this.renderer=t,this.context={...e}}static getObjectLODState(t){return t[Se]}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[Oe])return console.debug("[gltf-progressive] LODsManager already exists for this renderer"),t[Oe];const s=new P(t,{engine:"unknown",...e});return t[Oe]=s,s}get plugins(){return V}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)}}enable(){if(v(this,X))return;console.debug("[gltf-progressive] Enabling LODsManager for renderer");let t=0;F(this,X,this.renderer.render);const e=this;Le(this.renderer),this.renderer.render=function(s,n){const r=e.renderer.getRenderTarget();(r==null||"isXRRenderTarget"in r&&r.isXRRenderTarget)&&(t=0,F(e,ee,v(e,ee)+1),F(e,ne,v(e,Te).getDelta()),F(e,ge,v(e,ge)+v(e,ne)),e._fpsBuffer.shift(),e._fpsBuffer.push(1/v(e,ne)),F(e,K,e._fpsBuffer.reduce((i,l)=>i+l)/e._fpsBuffer.length),N&&v(e,ee)%200===0&&console.log("FPS",Math.round(v(e,K)),"Interval:",v(e,E)));const o=t++;v(e,X).call(this,s,n),e.onAfterRender(s,n,o)}}disable(){v(this,X)&&(console.debug("[gltf-progressive] Disabling LODsManager for renderer"),this.renderer.render=v(this,X),F(this,X,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 r=!0;if(n.length===1){const o=n[0].material;(o.name==="EffectMaterial"||o.name==="CopyShader")&&(r=!1)}if((e.parent&&e.parent.type==="CubeCamera"||s>=1&&e.type==="OrthographicCamera")&&(r=!1),r){if(ht||(this.updateInterval==="auto"?v(this,K)<40&&v(this,E)<10?(F(this,E,v(this,E)+1),N&&console.warn("\u2193 Reducing LOD updates",v(this,E),v(this,K).toFixed(0))):v(this,K)>=60&&v(this,E)>1&&(F(this,E,v(this,E)-1),N&&console.warn("\u2191 Increasing LOD updates",v(this,E),v(this,K).toFixed(0))):F(this,E,this.updateInterval),v(this,E)>0&&v(this,ee)%v(this,E)!=0))return;this.internalUpdate(t,e)}}internalUpdate(t,e){var s,n;const r=this.renderer.renderLists.get(t,0),o=r.opaque;this.projectionScreenMatrix.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse);const i=this.targetTriangleDensity;for(const a of o){if(a.material&&(((s=a.geometry)==null?void 0:s.type)==="BoxGeometry"||((n=a.geometry)==null?void 0:n.type)==="BufferGeometry")&&(a.material.name==="SphericalGaussianBlur"||a.material.name=="BackgroundCubeMaterial"||a.material.name==="CubemapFromEquirect"||a.material.name==="EquirectangularToCubeUV")){N&&(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(N==="color"&&a.material&&!a.object.progressive_debug_color){a.object.progressive_debug_color=!0;const x=Math.random()*16777215,m=new Ze({color:x});a.object.material=m}const h=a.object;(h instanceof Y||h.isMesh)&&this.updateLODs(t,e,h,i)}const l=r.transparent;for(const a of l){const h=a.object;(h instanceof Y||h.isMesh)&&this.updateLODs(t,e,h,i)}const u=r.transmissive;for(const a of u){const h=a.object;(h instanceof Y||h.isMesh)&&this.updateLODs(t,e,h,i)}}updateLODs(t,e,s,n){var r,o;s.userData||(s.userData={});let i=s[Se];if(i||(i=new gt,s[Se]=i),i.frames++<2)return;for(const u of V)(r=u.onBeforeUpdateLOD)==null||r.call(u,this.renderer,t,e,s);const l=P.overrideGlobalLodLevel!==void 0?P.overrideGlobalLodLevel:J;l>=0?(A.mesh_lod=l,A.texture_lod=l):(this.calculateLodLevel(e,s,i,n,A),A.mesh_lod=Math.round(A.mesh_lod),A.texture_lod=Math.round(A.texture_lod)),A.mesh_lod>=0&&this.loadProgressiveMeshes(s,A.mesh_lod),s.material&&A.texture_lod>=0&&this.loadProgressiveTextures(s.material,A.texture_lod),L&&s.material&&!s.isGizmo&&We(s.material);for(const u of V)(o=u.onAfterUpdatedLOD)==null||o.call(u,this.renderer,t,e,s,A);i.lastLodLevel_Mesh=A.mesh_lod,i.lastLodLevel_Texture=A.texture_lod}loadProgressiveTextures(t,e){if(!t)return;if(Array.isArray(t)){for(const r of t)this.loadProgressiveTextures(r,e);return}let s=!1;(t[q]===void 0||e<t[q])&&(s=!0);const n=t["DEBUG:LOD"];n!=null&&(s=t[q]!=n,e=n),s&&(t[q]=e,T.assignTextureLOD(t,e).then(r=>{this._lodchangedlisteners.forEach(o=>o({type:"texture",level:e,object:t}))}))}loadProgressiveMeshes(t,e){if(!t)return Promise.resolve(null);let s=t[q]!==e;const n=t["DEBUG:LOD"];if(n!=null&&(s=t[q]!=n,e=n),s){t[q]=e;const r=t.geometry;return T.assignMeshLOD(t,e).then(o=>(o&&t[q]==e&&r!=t.geometry&&this._lodchangedlisteners.forEach(i=>i({type:"mesh",level:e,object:t})),o))}return Promise.resolve(null)}static isInside(t,e){const s=t.min,n=t.max,r=(s.x+n.x)*.5,o=(s.y+n.y)*.5;return this._tempPtInside.set(r,o,s.z).applyMatrix4(e).z<0}calculateLodLevel(t,e,s,n,r){var o,i,l;if(!e){r.mesh_lod=-1,r.texture_lod=-1;return}if(!t){r.mesh_lod=-1,r.texture_lod=-1;return}let u=10+1,a=!1;if(N&&e["DEBUG:LOD"]!=null)return e["DEBUG:LOD"];const h=(o=T.getMeshLODExtension(e.geometry))==null?void 0:o.lods,x=T.getPrimitiveIndex(e.geometry),m=h&&h.length>0,M=T.getMaterialMinMaxLODsCount(e.material),b=M?.min_count!=1/0&&M.min_count>0&&M.max_count>0;if(!m&&!b){r.mesh_lod=0,r.texture_lod=0;return}m||(a=!0,u=0);const R=this.renderer.domElement.clientHeight||this.renderer.domElement.height;let y=e.geometry.boundingBox;if(e.type==="SkinnedMesh"){const p=e;if(!p.boundingBox)p.computeBoundingBox();else if(this.skinnedMeshAutoUpdateBoundsInterval>0&&s.frames%this.skinnedMeshAutoUpdateBoundsInterval===0){const f=Z(p),U=p.geometry;f&&(p.geometry=f),p.computeBoundingBox(),p.geometry=U}y=p.boundingBox}if(y){const p=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 c=t.getWorldPosition(this._tempWorldPosition);if(this._sphere.containsPoint(c)){r.mesh_lod=0,r.texture_lod=0;return}}if(this._tempBox.copy(y),this._tempBox.applyMatrix4(e.matrixWorld),p.isPerspectiveCamera&&P.isInside(this._tempBox,this.projectionScreenMatrix)){r.mesh_lod=0,r.texture_lod=0;return}if(this._tempBox.applyMatrix4(this.projectionScreenMatrix),this.renderer.xr.enabled&&p.isPerspectiveCamera&&p.fov>70){const c=this._tempBox.min,g=this._tempBox.max;let S=c.x,I=c.y,C=g.x,te=g.y;const ie=2,pe=1.5,ae=(c.x+g.x)*.5,le=(c.y+g.y)*.5;S=(S-ae)*ie+ae,I=(I-le)*ie+le,C=(C-ae)*ie+ae,te=(te-le)*ie+le;const Xe=S<0&&C>0?0:Math.min(Math.abs(c.x),Math.abs(g.x)),Ke=I<0&&te>0?0:Math.min(Math.abs(c.y),Math.abs(g.y)),ve=Math.max(Xe,Ke);s.lastCentrality=(pe-ve)*(pe-ve)*(pe-ve)}else s.lastCentrality=1;const f=this._tempBox.getSize(this._tempBoxSize);f.multiplyScalar(.5),screen.availHeight>0&&R>0&&f.multiplyScalar(R/screen.availHeight),t.isPerspectiveCamera?f.x*=t.aspect:t.isOrthographicCamera;const U=t.matrixWorldInverse,_=this._tempBox2;_.copy(y),_.applyMatrix4(e.matrixWorld),_.applyMatrix4(U);const j=_.getSize(this._tempBox2Size),O=Math.max(j.x,j.y);if(Math.max(f.x,f.y)!=0&&O!=0&&(f.z=j.z/Math.max(j.x,j.y)*Math.max(f.x,f.y)),s.lastScreenCoverage=Math.max(f.x,f.y,f.z),s.lastScreenspaceVolume.copy(f),s.lastScreenCoverage*=s.lastCentrality,N&&P.debugDrawLine){const c=this.tempMatrix.copy(this.projectionScreenMatrix);c.invert();const g=P.corner0,S=P.corner1,I=P.corner2,C=P.corner3;g.copy(this._tempBox.min),S.copy(this._tempBox.max),S.x=g.x,I.copy(this._tempBox.max),I.y=g.y,C.copy(this._tempBox.max);const te=(g.z+C.z)*.5;g.z=S.z=I.z=C.z=te,g.applyMatrix4(c),S.applyMatrix4(c),I.applyMatrix4(c),C.applyMatrix4(c),P.debugDrawLine(g,S,255),P.debugDrawLine(g,I,255),P.debugDrawLine(S,C,255),P.debugDrawLine(I,C,255)}let D=999;if(h&&s.lastScreenCoverage>0)for(let c=0;c<h.length;c++){const g=h[c];if((((i=g.densities)==null?void 0:i[x])||g.density||1e-5)/s.lastScreenCoverage<n){D=c;break}}D<u&&(u=D,a=!0)}if(a?r.mesh_lod=u:r.mesh_lod=s.lastLodLevel_Mesh,N&&r.mesh_lod!=s.lastLodLevel_Mesh){const p=h?.[r.mesh_lod];p&&console.log(`Mesh LOD changed: ${s.lastLodLevel_Mesh} \u2192 ${r.mesh_lod} (${p.density.toFixed(0)}) - ${e.name}`)}if(b){const p="saveData"in globalThis.navigator&&globalThis.navigator.saveData===!0;if(s.lastLodLevel_Texture<0){if(r.texture_lod=M.max_count-1,N){const f=M.lods[M.max_count-1];N&&console.log(`First Texture LOD ${r.texture_lod} (${f.max_height}px) - ${e.name}`)}}else{const f=s.lastScreenspaceVolume.x+s.lastScreenspaceVolume.y+s.lastScreenspaceVolume.z;let U=s.lastScreenCoverage*4;((l=this.context)==null?void 0:l.engine)==="model-viewer"&&(U*=1.5);const _=R/window.devicePixelRatio*U;let j=!1;for(let O=M.lods.length-1;O>=0;O--){const D=M.lods[O];if(!(p&&D.max_height>=2048)&&!(lt()&&D.max_height>4096)&&(D.max_height>_||!j&&O===0)){if(j=!0,r.texture_lod=O,r.texture_lod<s.lastLodLevel_Texture){const c=D.max_height;N&&console.log(`Texture LOD changed: ${s.lastLodLevel_Texture} \u2192 ${r.texture_lod} = ${c}px
|
|
6
|
-
Screensize: ${
|
|
7
|
-
${e.name}`)}break}}}}else
|
|
8
|
-
`,t.getAttribute("src"));let e=null,
|
|
5
|
+
`,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}};let T=w;c(T,"registerTexture",(t,e,r,n,s)=>{if(y&&console.log("> Progressive: register texture",n,e.name,e.uuid,e,s),!e){y&&console.error("gltf-progressive: Register texture without texture");return}e.source&&(e.source[De]=s);const o=s.guid;w.assignLODInformation(t,e,o,r,n,void 0),w.lodInfos.set(o,s),w.lowresCache.set(o,e)}),c(T,"registerMesh",(t,e,r,n,s,o)=>{var i;y&&console.log("> Progressive: register mesh",s,r.name,o,r.uuid,r);const l=r.geometry;if(!l){y&&console.warn("gltf-progressive: Register mesh without geometry");return}l.userData||(l.userData={}),w.assignLODInformation(t,l,e,n,s,o.density),w.lodInfos.set(e,o);let u=w.lowresCache.get(e);u?u.push(r.geometry):u=[r.geometry],w.lowresCache.set(e,u),n>0&&!Z(r)&&je(r,l);for(const a of z)(i=a.onRegisteredNewMesh)==null||i.call(a,r,o)}),c(T,"lodInfos",new Map),c(T,"previouslyLoaded",new Map),c(T,"lowresCache",new Map);class ut{constructor(e,r,n,s,o){c(this,"url"),c(this,"key"),c(this,"level"),c(this,"index"),c(this,"density"),this.url=e,this.key=r,this.level=n,s!=null&&(this.index=s),o!=null&&(this.density=o)}}const R=re("debugprogressive"),ct=re("noprogressive"),be=Symbol("Needle:LODSManager"),Oe=Symbol("Needle:LODState"),V=Symbol("Needle:CurrentLOD"),j={mesh_lod:-1,texture_lod:-1};var E,q,_e,ee,ne,de,X;const I=class{constructor(t,e){c(this,"context"),c(this,"renderer"),c(this,"projectionScreenMatrix",new Ee),c(this,"targetTriangleDensity",2e5),c(this,"skinnedMeshAutoUpdateBoundsInterval",30),c(this,"updateInterval","auto"),K(this,E,1),c(this,"pause",!1),c(this,"manual",!1),c(this,"_lodchangedlisteners",[]),K(this,q,void 0),K(this,_e,new Ye),K(this,ee,0),K(this,ne,0),K(this,de,0),K(this,X,0),c(this,"_fpsBuffer",[60,60,60,60,60]),c(this,"_sphere",new Qe),c(this,"_tempBox",new Ae),c(this,"_tempBox2",new Ae),c(this,"tempMatrix",new Ee),c(this,"_tempWorldPosition",new F),c(this,"_tempBoxSize",new F),c(this,"_tempBox2Size",new F),this.renderer=t,this.context={...e}}static getObjectLODState(t){return t[Oe]}static addPlugin(t){z.push(t)}static removePlugin(t){const e=z.indexOf(t);e>=0&&z.splice(e,1)}static get(t,e){if(t[be])return console.debug("[gltf-progressive] LODsManager already exists for this renderer"),t[be];const r=new I(t,{engine:"unknown",...e});return t[be]=r,r}get plugins(){return z}addEventListener(t,e){t==="changed"&&this._lodchangedlisteners.push(e)}removeEventListener(t,e){if(t==="changed"){const r=this._lodchangedlisteners.indexOf(e);r>=0&&this._lodchangedlisteners.splice(r,1)}}enable(){if(L(this,q))return;console.debug("[gltf-progressive] Enabling LODsManager for renderer");let t=0;$(this,q,this.renderer.render);const e=this;ve(this.renderer),this.renderer.render=function(r,n){const s=e.renderer.getRenderTarget();(s==null||"isXRRenderTarget"in s&&s.isXRRenderTarget)&&(t=0,$(e,ee,L(e,ee)+1),$(e,ne,L(e,_e).getDelta()),$(e,de,L(e,de)+L(e,ne)),e._fpsBuffer.shift(),e._fpsBuffer.push(1/L(e,ne)),$(e,X,e._fpsBuffer.reduce((i,l)=>i+l)/e._fpsBuffer.length),R&&L(e,ee)%200===0&&console.log("FPS",Math.round(L(e,X)),"Interval:",L(e,E)));const o=t++;L(e,q).call(this,r,n),e.onAfterRender(r,n,o)}}disable(){L(this,q)&&(console.debug("[gltf-progressive] Disabling LODsManager for renderer"),this.renderer.render=L(this,q),$(this,q,void 0))}update(t,e){this.internalUpdate(t,e)}onAfterRender(t,e,r){if(this.pause)return;const n=this.renderer.renderLists.get(t,0).opaque;let s=!0;if(n.length===1){const o=n[0].material;(o.name==="EffectMaterial"||o.name==="CopyShader")&&(s=!1)}if((e.parent&&e.parent.type==="CubeCamera"||r>=1&&e.type==="OrthographicCamera")&&(s=!1),s){if(ct||(this.updateInterval==="auto"?L(this,X)<40&&L(this,E)<10?($(this,E,L(this,E)+1),R&&console.warn("\u2193 Reducing LOD updates",L(this,E),L(this,X).toFixed(0))):L(this,X)>=60&&L(this,E)>1&&($(this,E,L(this,E)-1),R&&console.warn("\u2191 Increasing LOD updates",L(this,E),L(this,X).toFixed(0))):$(this,E,this.updateInterval),L(this,E)>0&&L(this,ee)%L(this,E)!=0))return;this.internalUpdate(t,e)}}internalUpdate(t,e){var r,n;const s=this.renderer.renderLists.get(t,0),o=s.opaque;this.projectionScreenMatrix.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse);const i=this.targetTriangleDensity;for(const a of o){if(a.material&&(((r=a.geometry)==null?void 0:r.type)==="BoxGeometry"||((n=a.geometry)==null?void 0:n.type)==="BufferGeometry")&&(a.material.name==="SphericalGaussianBlur"||a.material.name=="BackgroundCubeMaterial"||a.material.name==="CubemapFromEquirect"||a.material.name==="EquirectangularToCubeUV")){R&&(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(R==="color"&&a.material&&!a.object.progressive_debug_color){a.object.progressive_debug_color=!0;const f=Math.random()*16777215,v=new Je({color:f});a.object.material=v}const g=a.object;(g instanceof Y||g.isMesh)&&this.updateLODs(t,e,g,i)}const l=s.transparent;for(const a of l){const g=a.object;(g instanceof Y||g.isMesh)&&this.updateLODs(t,e,g,i)}const u=s.transmissive;for(const a of u){const g=a.object;(g instanceof Y||g.isMesh)&&this.updateLODs(t,e,g,i)}}updateLODs(t,e,r,n){var s,o;r.userData||(r.userData={});let i=r[Oe];if(i||(i=new dt,r[Oe]=i),i.frames++<2)return;for(const u of z)(s=u.onBeforeUpdateLOD)==null||s.call(u,this.renderer,t,e,r);this.calculateLodLevel(e,r,i,n,j),j.mesh_lod=Math.round(j.mesh_lod),j.texture_lod=Math.round(j.texture_lod),j.mesh_lod>=0&&this.loadProgressiveMeshes(r,j.mesh_lod);let l=j.texture_lod;r.material&&l>=0&&this.loadProgressiveTextures(r.material,l);for(const u of z)(o=u.onAfterUpdatedLOD)==null||o.call(u,this.renderer,t,e,r,j);i.lastLodLevel_Mesh=j.mesh_lod,i.lastLodLevel_Texture=j.texture_lod}loadProgressiveTextures(t,e){if(!t)return;if(Array.isArray(t)){for(const s of t)this.loadProgressiveTextures(s,e);return}let r=!1;(t[V]===void 0||e<t[V])&&(r=!0);const n=t["DEBUG:LOD"];n!=null&&(r=t[V]!=n,e=n),r&&(t[V]=e,T.assignTextureLOD(t,e).then(s=>{this._lodchangedlisteners.forEach(o=>o({type:"texture",level:e,object:t}))}))}loadProgressiveMeshes(t,e){if(!t)return Promise.resolve(null);let r=t[V]!==e;const n=t["DEBUG:LOD"];if(n!=null&&(r=t[V]!=n,e=n),r){t[V]=e;const s=t.geometry;return T.assignMeshLOD(t,e).then(o=>(o&&t[V]==e&&s!=t.geometry&&this._lodchangedlisteners.forEach(i=>i({type:"mesh",level:e,object:t})),o))}return Promise.resolve(null)}static isInside(t,e){const r=t.min,n=t.max,s=(r.x+n.x)*.5,o=(r.y+n.y)*.5;return this._tempPtInside.set(s,o,r.z).applyMatrix4(e).z<0}calculateLodLevel(t,e,r,n,s){var o;if(!e){s.mesh_lod=-1,s.texture_lod=-1;return}if(!t){s.mesh_lod=-1,s.texture_lod=-1;return}let i=10+1,l=!1;if(R&&e["DEBUG:LOD"]!=null)return e["DEBUG:LOD"];const u=T.getMeshLODInformation(e.geometry),a=u?.lods,g=a&&a.length>0,f=T.getMaterialMinMaxLODsCount(e.material),v=f?.min_count!=1/0&&f.min_count>0&&f.max_count>0;if(!g&&!v){s.mesh_lod=0,s.texture_lod=0;return}g||(l=!0,i=0);const A=this.renderer.domElement.clientHeight||this.renderer.domElement.height;let D=e.geometry.boundingBox;if(e.type==="SkinnedMesh"){const x=e;if(!x.boundingBox)x.computeBoundingBox();else if(this.skinnedMeshAutoUpdateBoundsInterval>0&&r.frames%this.skinnedMeshAutoUpdateBoundsInterval===0){const d=Z(x),b=x.geometry;d&&(x.geometry=d),x.computeBoundingBox(),x.geometry=b}D=x.boundingBox}if(D){const x=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 m=t.getWorldPosition(this._tempWorldPosition);if(this._sphere.containsPoint(m)){s.mesh_lod=0,s.texture_lod=0;return}}if(this._tempBox.copy(D),this._tempBox.applyMatrix4(e.matrixWorld),x.isPerspectiveCamera&&I.isInside(this._tempBox,this.projectionScreenMatrix)){s.mesh_lod=0,s.texture_lod=0;return}if(this._tempBox.applyMatrix4(this.projectionScreenMatrix),this.renderer.xr.enabled&&x.isPerspectiveCamera&&x.fov>70){const m=this._tempBox.min,p=this._tempBox.max;let h=m.x,M=m.y,S=p.x,G=p.y;const H=2,J=1.5,ie=(m.x+p.x)*.5,ae=(m.y+p.y)*.5;h=(h-ie)*H+ie,M=(M-ae)*H+ae,S=(S-ie)*H+ie,G=(G-ae)*H+ae;const Ve=h<0&&S>0?0:Math.min(Math.abs(m.x),Math.abs(p.x)),qe=M<0&&G>0?0:Math.min(Math.abs(m.y),Math.abs(p.y)),fe=Math.max(Ve,qe);r.lastCentrality=(J-fe)*(J-fe)*(J-fe)}else r.lastCentrality=1;const d=this._tempBox.getSize(this._tempBoxSize);d.multiplyScalar(.5),screen.availHeight>0&&A>0&&d.multiplyScalar(A/screen.availHeight),t.isPerspectiveCamera?d.x*=t.aspect:t.isOrthographicCamera;const b=t.matrixWorldInverse,O=this._tempBox2;O.copy(D),O.applyMatrix4(e.matrixWorld),O.applyMatrix4(b);const B=O.getSize(this._tempBox2Size),_=Math.max(B.x,B.y);if(Math.max(d.x,d.y)!=0&&_!=0&&(d.z=B.z/Math.max(B.x,B.y)*Math.max(d.x,d.y)),r.lastScreenCoverage=Math.max(d.x,d.y,d.z),r.lastScreenspaceVolume.copy(d),r.lastScreenCoverage*=r.lastCentrality,R&&I.debugDrawLine){const m=this.tempMatrix.copy(this.projectionScreenMatrix);m.invert();const p=I.corner0,h=I.corner1,M=I.corner2,S=I.corner3;p.copy(this._tempBox.min),h.copy(this._tempBox.max),h.x=p.x,M.copy(this._tempBox.max),M.y=p.y,S.copy(this._tempBox.max);const G=(p.z+S.z)*.5;p.z=h.z=M.z=S.z=G,p.applyMatrix4(m),h.applyMatrix4(m),M.applyMatrix4(m),S.applyMatrix4(m),I.debugDrawLine(p,h,255),I.debugDrawLine(p,M,255),I.debugDrawLine(h,S,255),I.debugDrawLine(M,S,255)}let k=999;if(a&&r.lastScreenCoverage>0){for(let m=0;m<a.length;m++)if(a[m].density/r.lastScreenCoverage<n){k=m;break}}k<i&&(i=k,l=!0)}if(l?s.mesh_lod=i:s.mesh_lod=r.lastLodLevel_Mesh,R&&s.mesh_lod!=r.lastLodLevel_Mesh){const x=a?.[s.mesh_lod];x&&console.log(`Mesh LOD changed: ${r.lastLodLevel_Mesh} \u2192 ${s.mesh_lod} (${x.density.toFixed(0)}) - ${e.name}`)}if(v){const x="saveData"in globalThis.navigator&&globalThis.navigator.saveData===!0;if(r.lastLodLevel_Texture<0){if(s.texture_lod=f.max_count-1,R){const d=f.lods[f.max_count-1];R&&console.log(`First Texture LOD ${s.texture_lod} (${d.max_height}px) - ${e.name}`)}}else{const d=r.lastScreenspaceVolume.x+r.lastScreenspaceVolume.y+r.lastScreenspaceVolume.z;let b=r.lastScreenCoverage*4;((o=this.context)==null?void 0:o.engine)==="model-viewer"&&(b*=1.5);const O=A/window.devicePixelRatio*b;let B=!1;for(let _=f.lods.length-1;_>=0;_--){const k=f.lods[_];if(!(x&&k.max_height>=2048)&&!(it()&&k.max_height>4096)&&(k.max_height>O||!B&&_===0)){if(B=!0,s.texture_lod=_,s.texture_lod<r.lastLodLevel_Texture){const m=k.max_height;R&&console.log(`Texture LOD changed: ${r.lastLodLevel_Texture} \u2192 ${s.texture_lod} = ${m}px
|
|
6
|
+
Screensize: ${O.toFixed(0)}px, Coverage: ${(100*r.lastScreenCoverage).toFixed(2)}%, Volume ${d.toFixed(1)}
|
|
7
|
+
${e.name}`)}break}}}}else s.texture_lod=0}};let N=I;E=new WeakMap,q=new WeakMap,_e=new WeakMap,ee=new WeakMap,ne=new WeakMap,de=new WeakMap,X=new WeakMap,c(N,"debugDrawLine"),c(N,"corner0",new F),c(N,"corner1",new F),c(N,"corner2",new F),c(N,"corner3",new F),c(N,"_tempPtInside",new F);class dt{constructor(){c(this,"frames",0),c(this,"lastLodLevel_Mesh",-1),c(this,"lastLodLevel_Texture",-1),c(this,"lastScreenCoverage",0),c(this,"lastScreenspaceVolume",new F),c(this,"lastCentrality",0)}}const We=Symbol("NEEDLE_mesh_lod"),he=Symbol("NEEDLE_texture_lod");let ge=null;function Se(){const t=ht();t&&(t.mapURLs(function(e){return Ue(),e}),Ue(),ge?.disconnect(),ge=new MutationObserver(e=>{e.forEach(r=>{r.addedNodes.forEach(n=>{n instanceof HTMLElement&&n.tagName.toLowerCase()==="model-viewer"&&Fe(n)})})}),ge.observe(document,{childList:!0,subtree:!0}))}function ht(){return typeof customElements>"u"?null:customElements.get("model-viewer")||(customElements.whenDefined("model-viewer").then(()=>{console.debug("[gltf-progressive] model-viewer defined"),Se()}),null)}function Ue(){typeof document>"u"||document.querySelectorAll("model-viewer").forEach(t=>{Fe(t)})}const $e=new WeakSet;let gt=0;function Fe(t){if(!t||$e.has(t))return null;$e.add(t),console.debug("[gltf-progressive] found new model-viewer..."+ ++gt+`
|
|
8
|
+
`,t.getAttribute("src"));let e=null,r=null,n=null;for(let s=t;s!=null;s=Object.getPrototypeOf(s)){const o=Object.getOwnPropertySymbols(s),i=o.find(a=>a.toString()=="Symbol(renderer)"),l=o.find(a=>a.toString()=="Symbol(scene)"),u=o.find(a=>a.toString()=="Symbol(needsRender)");!e&&i!=null&&(e=t[i].threeRenderer),!r&&l!=null&&(r=t[l]),!n&&u!=null&&(n=t[u])}if(e&&r){let s=function(){if(n){let i=0,l=setInterval(()=>{if(i++>5){clearInterval(l);return}n?.call(t)},300)}};console.debug("[gltf-progressive] setup model-viewer");const o=N.get(e,{engine:"model-viewer"});return N.addPlugin(new ft),o.enable(),o.addEventListener("changed",()=>{n?.call(t)}),t.addEventListener("model-visibility",i=>{i.detail.visible&&n?.call(t)}),t.addEventListener("load",()=>{s()}),()=>{o.disable()}}return null}class ft{constructor(){c(this,"_didWarnAboutMissingUrl",!1)}onBeforeUpdateLOD(e,r,n,s){this.tryParseMeshLOD(r,s),this.tryParseTextureLOD(r,s)}getUrl(e){if(!e)return null;let r=e.getAttribute("src");return r||(r=e.src),r||(this._didWarnAboutMissingUrl||console.warn("No url found in modelviewer",e),this._didWarnAboutMissingUrl=!0),r}tryGetCurrentGLTF(e){return e._currentGLTF}tryGetCurrentModelViewer(e){return e.element}tryParseTextureLOD(e,r){if(r[he]==!0)return;r[he]=!0;const n=this.tryGetCurrentGLTF(e),s=this.tryGetCurrentModelViewer(e),o=this.getUrl(s);if(o&&n&&r.material){let i=function(u){var a,g,f;if(u[he]==!0)return;u[he]=!0,u.userData&&(u.userData.LOD=-1);const v=Object.keys(u);for(let A=0;A<v.length;A++){const D=v[A],x=u[D];if(x?.isTexture===!0){const d=(g=(a=x.userData)==null?void 0:a.associations)==null?void 0:g.textures;if(d==null)continue;const b=n.parser.json.textures[d];if(!b){console.warn("Texture data not found for texture index "+d);continue}if((f=b?.extensions)!=null&&f[U]){const O=b.extensions[U];O&&o&&T.registerTexture(o,x,O.lods.length,d,O)}}}};const l=r.material;if(Array.isArray(l))for(const u of l)i(u);else i(l)}}tryParseMeshLOD(e,r){var n,s;if(r[We]==!0)return;r[We]=!0;const o=this.tryGetCurrentModelViewer(e),i=this.getUrl(o);if(!i)return;const l=(s=(n=r.userData)==null?void 0:n.gltfExtensions)==null?void 0:s[U];if(l&&i){const u=r.uuid;T.registerMesh(i,u,r,0,l.lods.length,l)}}}function ze(t,e,r,n){ve(e),ye(r),Le(r,{progressive:!0,...n?.hints}),r.register(o=>new T(o,t));const s=N.get(e);return n?.enableLODsManager!==!1&&s.enable(),s}if(Se(),!at){const t={gltfProgressive:{useNeedleProgressive:ze,LODsManager:N,configureLoader:Le,getRaycastMesh:Z,useRaycastMeshes:Ne}};if(!globalThis.Needle)globalThis.Needle=t;else for(const e in t)globalThis.Needle[e]=t[e]}export{U as EXTENSION_NAME,N as LODsManager,T as NEEDLE_progressive,Pe as VERSION,ye as addDracoAndKTX2Loaders,Le as configureLoader,ve as createLoaders,Z as getRaycastMesh,Se as patchModelViewer,je as registerRaycastMesh,Be as setDracoDecoderLocation,ke as setKTX2TranscoderLocation,ze as useNeedleProgressive,Ne as useRaycastMeshes};
|
package/gltf-progressive.umd.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var Ye=Object.defineProperty;var He=(n,t,e)=>t in n?Ye(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var d=(n,t,e)=>(He(n,typeof t!="symbol"?t+"":t,e),e),Ce=(n,t,e)=>{if(!t.has(n))throw TypeError("Cannot "+e)};var L=(n,t,e)=>(Ce(n,t,"read from private field"),e?e.call(n):t.get(n)),J=(n,t,e)=>{if(t.has(n))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(n):t.set(n,e)},W=(n,t,e,r)=>(Ce(n,t,"write to private field"),r?r.call(n,e):t.set(n,e),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("three"),Se=require("three/examples/jsm/loaders/GLTFLoader.js"),je=require("three/examples/jsm/libs/meshopt_decoder.module.js"),Je=require("three/examples/jsm/loaders/DRACOLoader.js"),Qe=require("three/examples/jsm/loaders/KTX2Loader.js"),Ge="";globalThis.GLTF_PROGRESSIVE_VERSION=Ge;console.debug("[gltf-progressive] version -");let X="https://www.gstatic.com/draco/versioned/decoders/1.5.7/",te="https://www.gstatic.com/basis-universal/versioned/2021-04-15-ba1c3e4/";const Ze=X,et=te,ke=new URL(X+"draco_decoder.js");ke.searchParams.append("range","true");fetch(ke,{method:"GET",headers:{Range:"bytes=0-1"}}).catch(n=>{console.debug(`Failed to fetch remote Draco decoder from ${X} (offline: ${typeof navigator<"u"?navigator.onLine:"unknown"})`),X===Ze&&$e("./include/draco/"),te===et&&Fe("./include/ktx2/")}).finally(()=>{Ne()});function $e(n){X=n,G&&G[_e]!=X?(console.debug("Updating Draco decoder path to "+n),G[_e]=X,G.setDecoderPath(X),G.preload()):console.debug("Setting Draco decoder path to "+n)}function Fe(n){te=n,U&&U.transcoderPath!=te?(console.debug("Updating KTX2 transcoder path to "+n),U.setTranscoderPath(te),U.init()):console.debug("Setting KTX2 transcoder path to "+n)}const _e=Symbol("dracoDecoderPath");let G,pe,U;function Ne(){G||(G=new Je.DRACOLoader,G[_e]=X,G.setDecoderPath(X),G.setDecoderConfig({type:"js"}),G.preload()),U||(U=new Qe.KTX2Loader,U.setTranscoderPath(te),U.init()),pe||(pe=je.MeshoptDecoder)}function Te(n){return Ne(),n?U.detectSupport(n):n!==null&&console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures might fail"),{dracoLoader:G,ktx2Loader:U,meshoptDecoder:pe}}function Ae(n){n.dracoLoader||n.setDRACOLoader(G),n.ktx2Loader||n.setKTX2Loader(U),n.meshoptDecoder||n.setMeshoptDecoder(pe)}const Oe=new WeakMap;function Pe(n,t){let e=Oe.get(n);e?e=Object.assign(e,t):e=t,Oe.set(n,e)}const Me=Se.GLTFLoader.prototype.load;function tt(...n){const t=Oe.get(this);let e=n[0];const r=new URL(e,window.location.href);if(r.hostname.endsWith("needle.tools")){const o=(t==null?void 0:t.progressive)!==void 0?t.progressive:!0,s=t!=null&&t.usecase?t.usecase:"default";o?this.requestHeader.Accept=`*/*;progressive=allowed;usecase=${s}`:this.requestHeader.Accept=`*/*;usecase=${s}`,e=r.toString()}return n[0]=e,Me==null?void 0:Me.call(this,...n)}Se.GLTFLoader.prototype.load=tt;ce("debugprogressive");function ce(n){if(typeof window>"u")return!1;const e=new URL(window.location.href).searchParams.get(n);return e==null||e==="0"||e==="false"?!1:e===""?!0:e}function rt(n,t){if(t===void 0||t.startsWith("./")||t.startsWith("http")||n===void 0)return t;const e=n.lastIndexOf("/");if(e>=0){const r=n.substring(0,e+1);for(;r.endsWith("/")&&t.startsWith("/");)t=t.substring(1);return r+t}return t}let ne;function st(){return ne!==void 0||(ne=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent),ce("debugprogressive")&&console.log("[glTF Progressive]: isMobileDevice",ne)),ne}const ot=typeof window>"u"&&typeof document>"u",be=Symbol("needle:raycast-mesh");function oe(n){return(n==null?void 0:n[be])instanceof p.BufferGeometry?n[be]:null}function Ue(n,t){if((n.type==="Mesh"||n.type==="SkinnedMesh")&&!oe(n)){const r=it(t);r.userData={isRaycastMesh:!0},n[be]=r}}function Ve(n=!0){if(n){if(ae)return;const t=ae=p.Mesh.prototype.raycast;p.Mesh.prototype.raycast=function(e,r){const i=this,o=oe(i);let s;o&&i.isMesh&&(s=i.geometry,i.geometry=o),t.call(this,e,r),s&&(i.geometry=s)}}else{if(!ae)return;p.Mesh.prototype.raycast=ae,ae=null}}let ae=null;function it(n){const t=new p.BufferGeometry;for(const e in n.attributes)t.setAttribute(e,n.getAttribute(e));return t.setIndex(n.getIndex()),t}const Z=new Array,x=ce("debugprogressive");let ge,ee=-1;if(x){let n=function(){ee+=1,ee>=t&&(ee=-1),console.log(`Toggle LOD level [${ee}]`)},t=6;window.addEventListener("keyup",e=>{e.key==="p"&&n(),e.key==="w"&&(ge=!ge,console.log(`Toggle wireframe [${ge}]`));const r=parseInt(e.key);!isNaN(r)&&r>=0&&(ee=r,console.log(`Set LOD level to [${ee}]`))})}function ze(n){if(x)if(Array.isArray(n))for(const t of n)ze(t);else n&&"wireframe"in n&&(n.wireframe=ge===!0)}const q="NEEDLE_progressive",De=Symbol("needle-progressive-texture"),S=class{constructor(t,e){d(this,"parser");d(this,"url");d(this,"_isLoadingMesh");d(this,"loadMesh",t=>{var r,i;if(this._isLoadingMesh)return null;const e=(i=(r=this.parser.json.meshes[t])==null?void 0:r.extensions)==null?void 0:i[q];return e?(this._isLoadingMesh=!0,this.parser.getDependency("mesh",t).then(o=>{var s;return this._isLoadingMesh=!1,o&&S.registerMesh(this.url,e.guid,o,(s=e.lods)==null?void 0:s.length,0,e),o})):null});x&&console.log("Progressive extension registered for",e),this.parser=t,this.url=e}get name(){return q}static getMeshLODExtension(t){const e=this.getAssignedLODInformation(t);return e!=null&&e.key?this.lodInfos.get(e.key):null}static getPrimitiveIndex(t){var r;const e=(r=this.getAssignedLODInformation(t))==null?void 0:r.index;return e??-1}static getMaterialMinMaxLODsCount(t,e){const r=this,i="LODS:minmax",o=t[i];if(o!=null)return o;if(e||(e={min_count:1/0,max_count:0,lods:[]}),Array.isArray(t)){for(const a of t)this.getMaterialMinMaxLODsCount(a,e);return t[i]=e,e}if(x==="verbose"&&console.log("getMaterialMinMaxLODsCount",t),t.type==="ShaderMaterial"||t.type==="RawShaderMaterial"){const a=t;for(const l of Object.keys(a.uniforms)){const u=a.uniforms[l].value;(u==null?void 0:u.isTexture)===!0&&s(u,e)}}else if(t.isMaterial)for(const a of Object.keys(t)){const l=t[a];(l==null?void 0:l.isTexture)===!0&&s(l,e)}return t[i]=e,e;function s(a,l){const u=r.getAssignedLODInformation(a);if(u){const c=r.lodInfos.get(u.key);if(c&&c.lods){l.min_count=Math.min(l.min_count,c.lods.length),l.max_count=Math.max(l.max_count,c.lods.length);for(let h=0;h<c.lods.length;h++){const g=c.lods[h];g.width&&(l.lods[h]=l.lods[h]||{min_height:1/0,max_height:0},l.lods[h].min_height=Math.min(l.lods[h].min_height,g.height),l.lods[h].max_height=Math.max(l.lods[h].max_height,g.height))}}}}}static hasLODLevelAvailable(t,e){var o;if(Array.isArray(t)){for(const s of t)if(this.hasLODLevelAvailable(s,e))return!0;return!1}if(t.isMaterial===!0){for(const s of Object.keys(t)){const a=t[s];if(a&&a.isTexture&&this.hasLODLevelAvailable(a,e))return!0}return!1}else if(t.isGroup===!0){for(const s of t.children)if(s.isMesh===!0&&this.hasLODLevelAvailable(s,e))return!0}let r,i;if(t.isMesh?r=t.geometry:(t.isBufferGeometry||t.isTexture)&&(r=t),r&&(o=r==null?void 0:r.userData)!=null&&o.LODS){const s=r.userData.LODS;if(i=this.lodInfos.get(s.key),e===void 0)return i!=null;if(i)return Array.isArray(i.lods)?e<i.lods.length:e===0}return!1}static assignMeshLOD(t,e){var r;if(!t)return Promise.resolve(null);if(t instanceof p.Mesh||t.isMesh===!0){const i=t.geometry,o=this.getAssignedLODInformation(i);if(!o)return Promise.resolve(null);for(const s of Z)(r=s.onBeforeGetLODMesh)==null||r.call(s,t,e);return t["LOD:requested level"]=e,S.getOrLoadLOD(i,e).then(s=>{if(Array.isArray(s)){const a=o.index||0;s=s[a]}return t["LOD:requested level"]===e&&(delete t["LOD:requested level"],s&&i!=s&&((s==null?void 0:s.isBufferGeometry)?t.geometry=s:x&&console.error("Invalid LOD geometry",s))),s}).catch(s=>(console.error("Error loading mesh LOD",t,s),null))}else x&&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 r=t;if(Array.isArray(r.material)){const i=new Array;for(const o of r.material){const s=this.assignTextureLOD(o,e);i.push(s)}return Promise.all(i).then(o=>{const s=new Array;for(const a of o)Array.isArray(a)&&s.push(...a);return s})}else return this.assignTextureLOD(r.material,e)}if(t.isMaterial===!0){const r=t,i=[],o=new Array;if(r.uniforms&&(r.isRawShaderMaterial||r.isShaderMaterial===!0)){const s=r;for(const a of Object.keys(s.uniforms)){const l=s.uniforms[a].value;if((l==null?void 0:l.isTexture)===!0){const u=this.assignTextureLODForSlot(l,e,r,a).then(c=>(c&&s.uniforms[a].value!=c&&(s.uniforms[a].value=c,s.uniformsNeedUpdate=!0),c));i.push(u),o.push(a)}}}else for(const s of Object.keys(r)){const a=r[s];if((a==null?void 0:a.isTexture)===!0){const l=this.assignTextureLODForSlot(a,e,r,s);i.push(l),o.push(s)}}return Promise.all(i).then(s=>{const a=new Array;for(let l=0;l<s.length;l++){const u=s[l],c=o[l];u&&u.isTexture===!0?a.push({material:r,slot:c,texture:u,level:e}):a.push({material:r,slot:c,texture:null,level:e})}return a})}if(t instanceof p.Texture||t.isTexture===!0){const r=t;return this.assignTextureLODForSlot(r,e,null,null)}return Promise.resolve(null)}static assignTextureLODForSlot(t,e,r,i){return(t==null?void 0:t.isTexture)!==!0?Promise.resolve(null):i==="glyphMap"?Promise.resolve(t):S.getOrLoadLOD(t,e).then(o=>{if(Array.isArray(o))return null;if((o==null?void 0:o.isTexture)===!0){if(o!=t&&r&&i){const s=r[i];if(s&&!x){const a=this.getAssignedLODInformation(s);if(a&&(a==null?void 0:a.level)<e)return x==="verbose"&&console.warn("Assigned texture level is already higher: ",a.level,e,r,s,o),null}r[i]=o}return o}else x=="verbose"&&console.warn("No LOD found for",t,e);return null}).catch(o=>(console.error("Error loading LOD",t,o),null))}afterRoot(t){var e,r;return x&&console.log("AFTER",this.url,t),(e=this.parser.json.textures)==null||e.forEach((i,o)=>{var s;if(i!=null&&i.extensions){const a=i==null?void 0:i.extensions[q];if(a){if(!a.lods){x&&console.warn("Texture has no LODs",a);return}let l=!1;for(const u of this.parser.associations.keys())if(u.isTexture===!0){const c=this.parser.associations.get(u);(c==null?void 0:c.textures)===o&&(l=!0,S.registerTexture(this.url,u,(s=a.lods)==null?void 0:s.length,o,a))}l||this.parser.getDependency("texture",o).then(u=>{var c;u&&S.registerTexture(this.url,u,(c=a.lods)==null?void 0:c.length,o,a)})}}}),(r=this.parser.json.meshes)==null||r.forEach((i,o)=>{if(i!=null&&i.extensions){const s=i==null?void 0:i.extensions[q];if(s&&s.lods){for(const a of this.parser.associations.keys())if(a.isMesh){const l=this.parser.associations.get(a);(l==null?void 0:l.meshes)===o&&S.registerMesh(this.url,s.guid,a,s.lods.length,l.primitives,s)}}}}),null}static async getOrLoadLOD(t,e){var a,l,u,c;const r=x=="verbose",i=t.userData.LODS;if(!i)return null;const o=i==null?void 0:i.key;let s;if(t.isTexture===!0){const h=t;h.source&&h.source[De]&&(s=h.source[De])}if(s||(s=S.lodInfos.get(o)),s){if(e>0){let D=!1;const O=Array.isArray(s.lods);if(O&&e>=s.lods.length?D=!0:O||(D=!0),D)return this.lowresCache.get(o)}const h=Array.isArray(s.lods)?(a=s.lods[e])==null?void 0:a.path:s.lods;if(!h)return x&&!s["missing:uri"]&&(s["missing:uri"]=!0,console.warn("Missing uri for progressive asset for LOD "+e,s)),null;const g=rt(i.url,h);if(g.endsWith(".glb")||g.endsWith(".gltf")){if(!s.guid)return console.warn("missing pointer for glb/gltf texture",s),null;const D=g+"_"+s.guid,O=this.previouslyLoaded.get(D);if(O!==void 0){r&&console.log(`LOD ${e} was already loading/loaded: ${D}`);let v=await O.catch(y=>(console.error(`Error loading LOD ${e} from ${g}
|
|
2
|
-
`,
|
|
3
|
-
`,
|
|
4
|
-
`,
|
|
5
|
-
`,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}};let A=S;d(A,"registerTexture",(t,e,r,i,o)=>{if(x&&console.log("> Progressive: register texture",i,e.name,e.uuid,e,o),!e){x&&console.error("gltf-progressive: Register texture without texture");return}e.source&&(e.source[De]=o);const s=o.guid;S.assignLODInformation(t,e,s,r,i),S.lodInfos.set(s,o),S.lowresCache.set(s,e)}),d(A,"registerMesh",(t,e,r,i,o,s)=>{var u;const a=r.geometry;if(!a){x&&console.warn("gltf-progressive: Register mesh without geometry");return}a.userData||(a.userData={}),x&&console.log("> Progressive: register mesh "+r.name,{index:o,uuid:r.uuid},s,r),S.assignLODInformation(t,a,e,i,o),S.lodInfos.set(e,s);let l=S.lowresCache.get(e);l?l.push(r.geometry):l=[r.geometry],S.lowresCache.set(e,l),i>0&&!oe(r)&&Ue(r,a);for(const c of Z)(u=c.onRegisteredNewMesh)==null||u.call(c,r,s)}),d(A,"lodInfos",new Map),d(A,"previouslyLoaded",new Map),d(A,"lowresCache",new Map);class nt{constructor(t,e,r,i){d(this,"url");d(this,"key");d(this,"level");d(this,"index");this.url=t,this.key=e,this.level=r,i!=null&&(this.index=i)}}const N=ce("debugprogressive"),at=ce("noprogressive"),ve=Symbol("Needle:LODSManager"),we=Symbol("Needle:LODState"),Q=Symbol("Needle:CurrentLOD"),B={mesh_lod:-1,texture_lod:-1};var I,H,ye,re,se,Le,j;const P=class{constructor(t,e){d(this,"context");d(this,"renderer");d(this,"projectionScreenMatrix",new p.Matrix4);d(this,"targetTriangleDensity",2e5);d(this,"skinnedMeshAutoUpdateBoundsInterval",30);d(this,"updateInterval","auto");J(this,I,1);d(this,"pause",!1);d(this,"manual",!1);d(this,"_lodchangedlisteners",[]);J(this,H,void 0);J(this,ye,new p.Clock);J(this,re,0);J(this,se,0);J(this,Le,0);J(this,j,0);d(this,"_fpsBuffer",[60,60,60,60,60]);d(this,"_sphere",new p.Sphere);d(this,"_tempBox",new p.Box3);d(this,"_tempBox2",new p.Box3);d(this,"tempMatrix",new p.Matrix4);d(this,"_tempWorldPosition",new p.Vector3);d(this,"_tempBoxSize",new p.Vector3);d(this,"_tempBox2Size",new p.Vector3);this.renderer=t,this.context={...e}}static getObjectLODState(t){return t[we]}static addPlugin(t){Z.push(t)}static removePlugin(t){const e=Z.indexOf(t);e>=0&&Z.splice(e,1)}static get(t,e){if(t[ve])return console.debug("[gltf-progressive] LODsManager already exists for this renderer"),t[ve];const r=new P(t,{engine:"unknown",...e});return t[ve]=r,r}get plugins(){return Z}addEventListener(t,e){t==="changed"&&this._lodchangedlisteners.push(e)}removeEventListener(t,e){if(t==="changed"){const r=this._lodchangedlisteners.indexOf(e);r>=0&&this._lodchangedlisteners.splice(r,1)}}enable(){if(L(this,H))return;console.debug("[gltf-progressive] Enabling LODsManager for renderer");let t=0;W(this,H,this.renderer.render);const e=this;Te(this.renderer),this.renderer.render=function(r,i){const o=e.renderer.getRenderTarget();(o==null||"isXRRenderTarget"in o&&o.isXRRenderTarget)&&(t=0,W(e,re,L(e,re)+1),W(e,se,L(e,ye).getDelta()),W(e,Le,L(e,Le)+L(e,se)),e._fpsBuffer.shift(),e._fpsBuffer.push(1/L(e,se)),W(e,j,e._fpsBuffer.reduce((a,l)=>a+l)/e._fpsBuffer.length),N&&L(e,re)%200===0&&console.log("FPS",Math.round(L(e,j)),"Interval:",L(e,I)));const s=t++;L(e,H).call(this,r,i),e.onAfterRender(r,i,s)}}disable(){L(this,H)&&(console.debug("[gltf-progressive] Disabling LODsManager for renderer"),this.renderer.render=L(this,H),W(this,H,void 0))}update(t,e){this.internalUpdate(t,e)}onAfterRender(t,e,r){if(this.pause)return;const o=this.renderer.renderLists.get(t,0).opaque;let s=!0;if(o.length===1){const a=o[0].material;(a.name==="EffectMaterial"||a.name==="CopyShader")&&(s=!1)}if((e.parent&&e.parent.type==="CubeCamera"||r>=1&&e.type==="OrthographicCamera")&&(s=!1),s){if(at||(this.updateInterval==="auto"?L(this,j)<40&&L(this,I)<10?(W(this,I,L(this,I)+1),N&&console.warn("↓ Reducing LOD updates",L(this,I),L(this,j).toFixed(0))):L(this,j)>=60&&L(this,I)>1&&(W(this,I,L(this,I)-1),N&&console.warn("↑ Increasing LOD updates",L(this,I),L(this,j).toFixed(0))):W(this,I,this.updateInterval),L(this,I)>0&&L(this,re)%L(this,I)!=0))return;this.internalUpdate(t,e)}}internalUpdate(t,e){var l,u;const r=this.renderer.renderLists.get(t,0),i=r.opaque;this.projectionScreenMatrix.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse);const o=this.targetTriangleDensity;for(const c of i){if(c.material&&(((l=c.geometry)==null?void 0:l.type)==="BoxGeometry"||((u=c.geometry)==null?void 0:u.type)==="BufferGeometry")&&(c.material.name==="SphericalGaussianBlur"||c.material.name=="BackgroundCubeMaterial"||c.material.name==="CubemapFromEquirect"||c.material.name==="EquirectangularToCubeUV")){N&&(c.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]||(c.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]=!0,console.warn("Ignoring skybox or BLIT object",c,c.material.name,c.material.type)));continue}switch(c.material.type){case"LineBasicMaterial":case"LineDashedMaterial":case"PointsMaterial":case"ShadowMaterial":case"MeshDistanceMaterial":case"MeshDepthMaterial":continue}if(N==="color"&&c.material&&!c.object.progressive_debug_color){c.object.progressive_debug_color=!0;const g=Math.random()*16777215,D=new p.MeshStandardMaterial({color:g});c.object.material=D}const h=c.object;(h instanceof p.Mesh||h.isMesh)&&this.updateLODs(t,e,h,o)}const s=r.transparent;for(const c of s){const h=c.object;(h instanceof p.Mesh||h.isMesh)&&this.updateLODs(t,e,h,o)}const a=r.transmissive;for(const c of a){const h=c.object;(h instanceof p.Mesh||h.isMesh)&&this.updateLODs(t,e,h,o)}}updateLODs(t,e,r,i){var a,l;r.userData||(r.userData={});let o=r[we];if(o||(o=new lt,r[we]=o),o.frames++<2)return;for(const u of Z)(a=u.onBeforeUpdateLOD)==null||a.call(u,this.renderer,t,e,r);const s=P.overrideGlobalLodLevel!==void 0?P.overrideGlobalLodLevel:ee;s>=0?(B.mesh_lod=s,B.texture_lod=s):(this.calculateLodLevel(e,r,o,i,B),B.mesh_lod=Math.round(B.mesh_lod),B.texture_lod=Math.round(B.texture_lod)),B.mesh_lod>=0&&this.loadProgressiveMeshes(r,B.mesh_lod),r.material&&B.texture_lod>=0&&this.loadProgressiveTextures(r.material,B.texture_lod),x&&r.material&&!r.isGizmo&&ze(r.material);for(const u of Z)(l=u.onAfterUpdatedLOD)==null||l.call(u,this.renderer,t,e,r,B);o.lastLodLevel_Mesh=B.mesh_lod,o.lastLodLevel_Texture=B.texture_lod}loadProgressiveTextures(t,e){if(!t)return;if(Array.isArray(t)){for(const o of t)this.loadProgressiveTextures(o,e);return}let r=!1;(t[Q]===void 0||e<t[Q])&&(r=!0);const i=t["DEBUG:LOD"];i!=null&&(r=t[Q]!=i,e=i),r&&(t[Q]=e,A.assignTextureLOD(t,e).then(o=>{this._lodchangedlisteners.forEach(s=>s({type:"texture",level:e,object:t}))}))}loadProgressiveMeshes(t,e){if(!t)return Promise.resolve(null);let r=t[Q]!==e;const i=t["DEBUG:LOD"];if(i!=null&&(r=t[Q]!=i,e=i),r){t[Q]=e;const o=t.geometry;return A.assignMeshLOD(t,e).then(s=>(s&&t[Q]==e&&o!=t.geometry&&this._lodchangedlisteners.forEach(a=>a({type:"mesh",level:e,object:t})),s))}return Promise.resolve(null)}static isInside(t,e){const r=t.min,i=t.max,o=(r.x+i.x)*.5,s=(r.y+i.y)*.5;return this._tempPtInside.set(o,s,r.z).applyMatrix4(e).z<0}calculateLodLevel(t,e,r,i,o){var V,K,v;if(!e){o.mesh_lod=-1,o.texture_lod=-1;return}if(!t){o.mesh_lod=-1,o.texture_lod=-1;return}let a=10+1,l=!1;if(N&&e["DEBUG:LOD"]!=null)return e["DEBUG:LOD"];const u=(V=A.getMeshLODExtension(e.geometry))==null?void 0:V.lods,c=A.getPrimitiveIndex(e.geometry),h=u&&u.length>0,g=A.getMaterialMinMaxLODsCount(e.material),D=(g==null?void 0:g.min_count)!=1/0&&g.min_count>0&&g.max_count>0;if(!h&&!D){o.mesh_lod=0,o.texture_lod=0;return}h||(l=!0,a=0);const O=this.renderer.domElement.clientHeight||this.renderer.domElement.height;let M=e.geometry.boundingBox;if(e.type==="SkinnedMesh"){const _=e;if(!_.boundingBox)_.computeBoundingBox();else if(this.skinnedMeshAutoUpdateBoundsInterval>0&&r.frames%this.skinnedMeshAutoUpdateBoundsInterval===0){const y=oe(_),Y=_.geometry;y&&(_.geometry=y),_.computeBoundingBox(),_.geometry=Y}M=_.boundingBox}if(M){const _=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 m=t.getWorldPosition(this._tempWorldPosition);if(this._sphere.containsPoint(m)){o.mesh_lod=0,o.texture_lod=0;return}}if(this._tempBox.copy(M),this._tempBox.applyMatrix4(e.matrixWorld),_.isPerspectiveCamera&&P.isInside(this._tempBox,this.projectionScreenMatrix)){o.mesh_lod=0,o.texture_lod=0;return}if(this._tempBox.applyMatrix4(this.projectionScreenMatrix),this.renderer.xr.enabled&&_.isPerspectiveCamera&&_.fov>70){const m=this._tempBox.min,w=this._tempBox.max;let C=m.x,F=m.y,z=w.x,ie=w.y;const ue=2,me=1.5,de=(m.x+w.x)*.5,fe=(m.y+w.y)*.5;C=(C-de)*ue+de,F=(F-fe)*ue+fe,z=(z-de)*ue+de,ie=(ie-fe)*ue+fe;const Xe=C<0&&z>0?0:Math.min(Math.abs(m.x),Math.abs(w.x)),Ke=F<0&&ie>0?0:Math.min(Math.abs(m.y),Math.abs(w.y)),xe=Math.max(Xe,Ke);r.lastCentrality=(me-xe)*(me-xe)*(me-xe)}else r.lastCentrality=1;const y=this._tempBox.getSize(this._tempBoxSize);y.multiplyScalar(.5),screen.availHeight>0&&O>0&&y.multiplyScalar(O/screen.availHeight),t.isPerspectiveCamera?y.x*=t.aspect:t.isOrthographicCamera;const Y=t.matrixWorldInverse,E=this._tempBox2;E.copy(M),E.applyMatrix4(e.matrixWorld),E.applyMatrix4(Y);const $=E.getSize(this._tempBox2Size),k=Math.max($.x,$.y);if(Math.max(y.x,y.y)!=0&&k!=0&&(y.z=$.z/Math.max($.x,$.y)*Math.max(y.x,y.y)),r.lastScreenCoverage=Math.max(y.x,y.y,y.z),r.lastScreenspaceVolume.copy(y),r.lastScreenCoverage*=r.lastCentrality,N&&P.debugDrawLine){const m=this.tempMatrix.copy(this.projectionScreenMatrix);m.invert();const w=P.corner0,C=P.corner1,F=P.corner2,z=P.corner3;w.copy(this._tempBox.min),C.copy(this._tempBox.max),C.x=w.x,F.copy(this._tempBox.max),F.y=w.y,z.copy(this._tempBox.max);const ie=(w.z+z.z)*.5;w.z=C.z=F.z=z.z=ie,w.applyMatrix4(m),C.applyMatrix4(m),F.applyMatrix4(m),z.applyMatrix4(m),P.debugDrawLine(w,C,255),P.debugDrawLine(w,F,255),P.debugDrawLine(C,z,255),P.debugDrawLine(F,z,255)}let f=999;if(u&&r.lastScreenCoverage>0)for(let m=0;m<u.length;m++){const w=u[m];if((((K=w.densities)==null?void 0:K[c])||w.density||1e-5)/r.lastScreenCoverage<i){f=m;break}}f<a&&(a=f,l=!0)}if(l?o.mesh_lod=a:o.mesh_lod=r.lastLodLevel_Mesh,N&&o.mesh_lod!=r.lastLodLevel_Mesh){const y=u==null?void 0:u[o.mesh_lod];y&&console.log(`Mesh LOD changed: ${r.lastLodLevel_Mesh} → ${o.mesh_lod} (${y.density.toFixed(0)}) - ${e.name}`)}if(D){const _="saveData"in globalThis.navigator&&globalThis.navigator.saveData===!0;if(r.lastLodLevel_Texture<0){if(o.texture_lod=g.max_count-1,N){const y=g.lods[g.max_count-1];N&&console.log(`First Texture LOD ${o.texture_lod} (${y.max_height}px) - ${e.name}`)}}else{const y=r.lastScreenspaceVolume.x+r.lastScreenspaceVolume.y+r.lastScreenspaceVolume.z;let Y=r.lastScreenCoverage*4;((v=this.context)==null?void 0:v.engine)==="model-viewer"&&(Y*=1.5);const $=O/window.devicePixelRatio*Y;let k=!1;for(let b=g.lods.length-1;b>=0;b--){const f=g.lods[b];if(!(_&&f.max_height>=2048)&&!(st()&&f.max_height>4096)&&(f.max_height>$||!k&&b===0)){if(k=!0,o.texture_lod=b,o.texture_lod<r.lastLodLevel_Texture){const T=f.max_height;N&&console.log(`Texture LOD changed: ${r.lastLodLevel_Texture} → ${o.texture_lod} = ${T}px
|
|
6
|
-
Screensize: ${
|
|
7
|
-
${
|
|
8
|
-
`,
|
|
1
|
+
"use strict";var Xe=Object.defineProperty;var Ke=(i,e,t)=>e in i?Xe(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var f=(i,e,t)=>(Ke(i,typeof e!="symbol"?e+"":e,t),t),Pe=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)};var m=(i,e,t)=>(Pe(i,e,"read from private field"),t?t.call(i):e.get(i)),j=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},z=(i,e,t,s)=>(Pe(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("three"),_e=require("three/examples/jsm/loaders/GLTFLoader.js"),Ye=require("three/examples/jsm/libs/meshopt_decoder.module.js"),He=require("three/examples/jsm/loaders/DRACOLoader.js"),je=require("three/examples/jsm/loaders/KTX2Loader.js"),ke="";globalThis.GLTF_PROGRESSIVE_VERSION=ke;console.debug("[gltf-progressive] version -");let q="https://www.gstatic.com/draco/versioned/decoders/1.5.7/",Z="https://www.gstatic.com/basis-universal/versioned/2021-04-15-ba1c3e4/";const Je=q,Qe=Z,Ie=new URL(q+"draco_decoder.js");Ie.searchParams.append("range","true");fetch(Ie,{method:"GET",headers:{Range:"bytes=0-1"}}).catch(i=>{console.debug(`Failed to fetch remote Draco decoder from ${q} (offline: ${typeof navigator<"u"?navigator.onLine:"unknown"})`),q===Je&&Ge("./include/draco/"),Z===Qe&&$e("./include/ktx2/")}).finally(()=>{Ue()});function Ge(i){q=i,k&&k[De]!=q?(console.debug("Updating Draco decoder path to "+i),k[De]=q,k.setDecoderPath(q),k.preload()):console.debug("Setting Draco decoder path to "+i)}function $e(i){Z=i,F&&F.transcoderPath!=Z?(console.debug("Updating KTX2 transcoder path to "+i),F.setTranscoderPath(Z),F.init()):console.debug("Setting KTX2 transcoder path to "+i)}const De=Symbol("dracoDecoderPath");let k,fe,F;function Ue(){k||(k=new He.DRACOLoader,k[De]=q,k.setDecoderPath(q),k.setDecoderConfig({type:"js"}),k.preload()),F||(F=new je.KTX2Loader,F.setTranscoderPath(Z),F.init()),fe||(fe=Ye.MeshoptDecoder)}function be(i){return Ue(),i?F.detectSupport(i):i!==null&&console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures might fail"),{dracoLoader:k,ktx2Loader:F,meshoptDecoder:fe}}function Se(i){i.dracoLoader||i.setDRACOLoader(k),i.ktx2Loader||i.setKTX2Loader(F),i.meshoptDecoder||i.setMeshoptDecoder(fe)}const we=new WeakMap;function Te(i,e){let t=we.get(i);t?t=Object.assign(t,e):t=e,we.set(i,t)}const Le=_e.GLTFLoader.prototype.load;function Ze(...i){const e=we.get(this);let t=i[0];const s=new URL(t,window.location.href);if(s.hostname.endsWith("needle.tools")){const r=(e==null?void 0:e.progressive)!==void 0?e.progressive:!0,o=e!=null&&e.usecase?e.usecase:"default";r?this.requestHeader.Accept=`*/*;progressive=allowed;usecase=${o}`:this.requestHeader.Accept=`*/*;usecase=${o}`,t=s.toString()}return i[0]=t,Le==null?void 0:Le.call(this,...i)}_e.GLTFLoader.prototype.load=Ze;ae("debugprogressive");function ae(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 et(i,e){if(e===void 0||e.startsWith("./")||e.startsWith("http")||i===void 0)return e;const t=i.lastIndexOf("/");if(t>=0){const s=i.substring(0,t+1);for(;s.endsWith("/")&&e.startsWith("/");)e=e.substring(1);return s+e}return e}let re;function tt(){return re!==void 0||(re=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent),ae("debugprogressive")&&console.log("[glTF Progressive]: isMobileDevice",re)),re}const st=typeof window>"u"&&typeof document>"u",ve=Symbol("needle:raycast-mesh");function se(i){return(i==null?void 0:i[ve])instanceof y.BufferGeometry?i[ve]:null}function Fe(i,e){if((i.type==="Mesh"||i.type==="SkinnedMesh")&&!se(i)){const s=rt(e);s.userData={isRaycastMesh:!0},i[ve]=s}}function Ve(i=!0){if(i){if(oe)return;const e=oe=y.Mesh.prototype.raycast;y.Mesh.prototype.raycast=function(t,s){const n=this,r=se(n);let o;r&&n.isMesh&&(o=n.geometry,n.geometry=r),e.call(this,t,s),o&&(n.geometry=o)}}else{if(!oe)return;y.Mesh.prototype.raycast=oe,oe=null}}let oe=null;function rt(i){const e=new y.BufferGeometry;for(const t in i.attributes)e.setAttribute(t,i.getAttribute(t));return e.setIndex(i.getIndex()),e}const Q=new Array,W="NEEDLE_progressive",x=ae("debugprogressive"),me=Symbol("needle-progressive-texture"),ie=new Map,Oe=new Set;if(x){let i=function(){e+=1,console.log("Toggle LOD level",e,ie),ie.forEach((n,r)=>{for(const o of n.keys){const a=r[o];if(a!=null)if(a.isBufferGeometry===!0){const l=S.getMeshLODInformation(a),u=l?Math.min(e,l.lods.length):0;r["DEBUG:LOD"]=u,l&&(t=Math.max(t,l.lods.length-1))}else r.isMaterial===!0&&(r["DEBUG:LOD"]=e)}}),e>=t&&(e=-1)},e=-1,t=2,s=!1;window.addEventListener("keyup",n=>{n.key==="p"&&i(),n.key==="w"&&(s=!s,Oe&&Oe.forEach(r=>{r.name!="BackgroundCubeMaterial"&&r.glyphMap==null&&"wireframe"in r&&(r.wireframe=s)}))})}function Ee(i,e,t){var n;if(!x)return;ie.has(i)||ie.set(i,{keys:[],sourceId:t});const s=ie.get(i);((n=s==null?void 0:s.keys)==null?void 0:n.includes(e))==!1&&s.keys.push(e)}const O=class{constructor(e,t){f(this,"parser");f(this,"url");f(this,"_isLoadingMesh");f(this,"loadMesh",e=>{var s,n;if(this._isLoadingMesh)return null;const t=(n=(s=this.parser.json.meshes[e])==null?void 0:s.extensions)==null?void 0:n[W];return t?(this._isLoadingMesh=!0,this.parser.getDependency("mesh",e).then(r=>{var o;return this._isLoadingMesh=!1,r&&O.registerMesh(this.url,t.guid,r,(o=t.lods)==null?void 0:o.length,void 0,t),r})):null});x&&console.log("Progressive extension registered for",t),this.parser=e,this.url=t}get name(){return W}static getMeshLODInformation(e){const t=this.getAssignedLODInformation(e);return t!=null&&t.key?this.lodInfos.get(t.key):null}static getMaterialMinMaxLODsCount(e,t){const s=this,n="LODS:minmax",r=e[n];if(r!=null)return r;if(t||(t={min_count:1/0,max_count:0,lods:[]}),Array.isArray(e)){for(const a of e)this.getMaterialMinMaxLODsCount(a,t);return e[n]=t,t}if(x==="verbose"&&console.log("getMaterialMinMaxLODsCount",e),e.type==="ShaderMaterial"||e.type==="RawShaderMaterial"){const a=e;for(const l of Object.keys(a.uniforms)){const u=a.uniforms[l].value;(u==null?void 0:u.isTexture)===!0&&o(u,t)}}else if(e.isMaterial)for(const a of Object.keys(e)){const l=e[a];(l==null?void 0:l.isTexture)===!0&&o(l,t)}return e[n]=t,t;function o(a,l){const u=s.getAssignedLODInformation(a);if(u){const c=s.lodInfos.get(u.key);if(c&&c.lods){l.min_count=Math.min(l.min_count,c.lods.length),l.max_count=Math.max(l.max_count,c.lods.length);for(let g=0;g<c.lods.length;g++){const p=c.lods[g];p.width&&(l.lods[g]=l.lods[g]||{min_height:1/0,max_height:0},l.lods[g].min_height=Math.min(l.lods[g].min_height,p.height),l.lods[g].max_height=Math.max(l.lods[g].max_height,p.height))}}}}}static hasLODLevelAvailable(e,t){var r;if(Array.isArray(e)){for(const o of e)if(this.hasLODLevelAvailable(o,t))return!0;return!1}if(e.isMaterial===!0){for(const o of Object.keys(e)){const a=e[o];if(a&&a.isTexture&&this.hasLODLevelAvailable(a,t))return!0}return!1}else if(e.isGroup===!0){for(const o of e.children)if(o.isMesh===!0&&this.hasLODLevelAvailable(o,t))return!0}let s,n;if(e.isMesh?s=e.geometry:(e.isBufferGeometry||e.isTexture)&&(s=e),s&&(r=s==null?void 0:s.userData)!=null&&r.LODS){const o=s.userData.LODS;if(n=this.lodInfos.get(o.key),t===void 0)return n!=null;if(n)return Array.isArray(n.lods)?t<n.lods.length:t===0}return!1}static assignMeshLOD(e,t){var s;if(!e)return Promise.resolve(null);if(e instanceof y.Mesh||e.isMesh===!0){const n=e.geometry,r=this.getAssignedLODInformation(n);if(!r)return Promise.resolve(null);for(const o of Q)(s=o.onBeforeGetLODMesh)==null||s.call(o,e,t);return e["LOD:requested level"]=t,O.getOrLoadLOD(n,t).then(o=>{if(Array.isArray(o)){const a=r.index||0;o=o[a]}return e["LOD:requested level"]===t&&(delete e["LOD:requested level"],o&&n!=o&&((o==null?void 0:o.isBufferGeometry)?(e.geometry=o,x&&Ee(e,"geometry",r.url)):x&&console.error("Invalid LOD geometry",o))),o}).catch(o=>(console.error("Error loading mesh LOD",e,o),null))}else x&&console.error("Invalid call to assignMeshLOD: Request mesh LOD but the object is not a mesh",e);return Promise.resolve(null)}static assignTextureLOD(e,t=0){if(!e)return Promise.resolve(null);if(e.isMesh===!0){const s=e;if(Array.isArray(s.material)){const n=new Array;for(const r of s.material){const o=this.assignTextureLOD(r,t);n.push(o)}return Promise.all(n).then(r=>{const o=new Array;for(const a of r)Array.isArray(a)&&o.push(...a);return o})}else return this.assignTextureLOD(s.material,t)}if(e.isMaterial===!0){const s=e,n=[],r=new Array;if(x&&Oe.add(s),s.uniforms&&(s.isRawShaderMaterial||s.isShaderMaterial===!0)){const o=s;for(const a of Object.keys(o.uniforms)){const l=o.uniforms[a].value;if((l==null?void 0:l.isTexture)===!0){const u=this.assignTextureLODForSlot(l,t,s,a).then(c=>(c&&o.uniforms[a].value!=c&&(o.uniforms[a].value=c,o.uniformsNeedUpdate=!0),c));n.push(u),r.push(a)}}}else for(const o of Object.keys(s)){const a=s[o];if((a==null?void 0:a.isTexture)===!0){const l=this.assignTextureLODForSlot(a,t,s,o);n.push(l),r.push(o)}}return Promise.all(n).then(o=>{const a=new Array;for(let l=0;l<o.length;l++){const u=o[l],c=r[l];u&&u.isTexture===!0?a.push({material:s,slot:c,texture:u,level:t}):a.push({material:s,slot:c,texture:null,level:t})}return a})}if(e instanceof y.Texture||e.isTexture===!0){const s=e;return this.assignTextureLODForSlot(s,t,null,null)}return Promise.resolve(null)}static assignTextureLODForSlot(e,t,s,n){return(e==null?void 0:e.isTexture)!==!0?Promise.resolve(null):n==="glyphMap"?Promise.resolve(e):O.getOrLoadLOD(e,t).then(r=>{if(Array.isArray(r))return null;if((r==null?void 0:r.isTexture)===!0){if(r!=e){if(s&&n){const o=s[n];if(o&&!x){const a=this.getAssignedLODInformation(o);if(a&&(a==null?void 0:a.level)<t)return x==="verbose"&&console.warn("Assigned texture level is already higher: ",a.level,t,s,o,r),null}s[n]=r}if(x&&n&&s){const o=this.getAssignedLODInformation(e);o?Ee(s,n,o.url):console.warn("No LOD info for texture",e)}}return r}else x=="verbose"&&console.warn("No LOD found for",e,t);return null}).catch(r=>(console.error("Error loading LOD",e,r),null))}afterRoot(e){var t,s;return x&&console.log("AFTER",this.url,e),(t=this.parser.json.textures)==null||t.forEach((n,r)=>{var o;if(n!=null&&n.extensions){const a=n==null?void 0:n.extensions[W];if(a){if(!a.lods){x&&console.warn("Texture has no LODs",a);return}let l=!1;for(const u of this.parser.associations.keys())if(u.isTexture===!0){const c=this.parser.associations.get(u);(c==null?void 0:c.textures)===r&&(l=!0,O.registerTexture(this.url,u,(o=a.lods)==null?void 0:o.length,r,a))}l||this.parser.getDependency("texture",r).then(u=>{var c;u&&O.registerTexture(this.url,u,(c=a.lods)==null?void 0:c.length,r,a)})}}}),(s=this.parser.json.meshes)==null||s.forEach((n,r)=>{if(n!=null&&n.extensions){const o=n==null?void 0:n.extensions[W];if(o&&o.lods){for(const a of this.parser.associations.keys())if(a.isMesh){const l=this.parser.associations.get(a);(l==null?void 0:l.meshes)===r&&O.registerMesh(this.url,o.guid,a,o.lods.length,l.primitives,o)}}}}),null}static async getOrLoadLOD(e,t){var a,l,u,c;const s=x=="verbose",n=e.userData.LODS;if(!n)return null;const r=n==null?void 0:n.key;let o;if(e.isTexture===!0){const g=e;g.source&&g.source[me]&&(o=g.source[me])}if(o||(o=O.lodInfos.get(r)),o){if(t>0){let w=!1;const v=Array.isArray(o.lods);if(v&&t>=o.lods.length?w=!0:v||(w=!0),w)return this.lowresCache.get(r)}const g=Array.isArray(o.lods)?(a=o.lods[t])==null?void 0:a.path:o.lods;if(!g)return x&&!o["missing:uri"]&&(o["missing:uri"]=!0,console.warn("Missing uri for progressive asset for LOD "+t,o)),null;const p=et(n.url,g);if(p.endsWith(".glb")||p.endsWith(".gltf")){if(!o.guid)return console.warn("missing pointer for glb/gltf texture",o),null;const w=p+"_"+o.guid,v=this.previouslyLoaded.get(w);if(v!==void 0){s&&console.log(`LOD ${t} was already loading/loaded: ${w}`);let h=await v.catch(N=>(console.error(`Error loading LOD ${t} from ${p}
|
|
2
|
+
`,N),null)),I=!1;if(h==null||(h instanceof y.Texture&&e instanceof y.Texture?(l=h.image)!=null&&l.data||(u=h.source)!=null&&u.data?h=this.copySettings(e,h):(I=!0,this.previouslyLoaded.delete(w)):h instanceof y.BufferGeometry&&e instanceof y.BufferGeometry&&((c=h.attributes.position)!=null&&c.array||(I=!0,this.previouslyLoaded.delete(w)))),!I)return h}const M=o,V=new Promise(async(h,I)=>{const N=new _e.GLTFLoader;Se(N),x&&(await new Promise(T=>setTimeout(T,1e3)),s&&console.warn("Start loading (delayed) "+p,M.guid));let G=p;if(M&&Array.isArray(M.lods)){const T=M.lods[t];T.hash&&(G+="?v="+T.hash)}const P=await N.loadAsync(G).catch(T=>(console.error(`Error loading LOD ${t} from ${p}
|
|
3
|
+
`,T),null));if(!P)return null;const X=P.parser;s&&console.log("Loading finished "+p,M.guid);let b=0;if(P.parser.json.textures){let T=!1;for(const d of P.parser.json.textures){if(d!=null&&d.extensions){const L=d==null?void 0:d.extensions[W];if(L!=null&&L.guid&&L.guid===M.guid){T=!0;break}}b++}if(T){let d=await X.getDependency("texture",b);return d&&O.assignLODInformation(n.url,d,r,t,void 0,void 0),s&&console.log('change "'+e.name+'" → "'+d.name+'"',p,b,d,w),e instanceof y.Texture&&(d=this.copySettings(e,d)),d&&(d.guid=M.guid),h(d)}else x&&console.warn("Could not find texture with guid",M.guid,P.parser.json)}if(b=0,P.parser.json.meshes){let T=!1;for(const d of P.parser.json.meshes){if(d!=null&&d.extensions){const L=d==null?void 0:d.extensions[W];if(L!=null&&L.guid&&L.guid===M.guid){T=!0;break}}b++}if(T){const d=await X.getDependency("mesh",b),L=M;if(s&&console.log(`Loaded Mesh "${d.name}"`,p,b,d,w),d.isMesh===!0){const _=d.geometry;return O.assignLODInformation(n.url,_,r,t,void 0,L.density),h(_)}else{const _=new Array;for(let A=0;A<d.children.length;A++){const E=d.children[A];if(E.isMesh===!0){const H=E.geometry;O.assignLODInformation(n.url,H,r,t,A,L.density),_.push(H)}}return h(_)}}else x&&console.warn("Could not find mesh with guid",M.guid,P.parser.json)}return h(null)});return this.previouslyLoaded.set(w,V),await V}else if(e instanceof y.Texture){s&&console.log("Load texture from uri: "+p);const v=await new y.TextureLoader().loadAsync(p);return v?(v.guid=o.guid,v.flipY=!1,v.needsUpdate=!0,v.colorSpace=e.colorSpace,s&&console.log(o,v)):x&&console.warn("failed loading",p),v}}else x&&console.warn(`Can not load LOD ${t}: no LOD info found for "${r}" ${e.name}`,e.type);return null}static assignLODInformation(e,t,s,n,r,o){if(!t)return;t.userData||(t.userData={});const a=new ot(e,s,n,r,o);t.userData.LODS=a}static getAssignedLODInformation(e){var t;return((t=e==null?void 0:e.userData)==null?void 0:t.LODS)||null}static copySettings(e,t){return t?(x&&console.warn(`Copy texture settings
|
|
4
|
+
`,e.uuid,`
|
|
5
|
+
`,t.uuid),t=t.clone(),t.offset=e.offset,t.repeat=e.repeat,t.colorSpace=e.colorSpace,t.magFilter=e.magFilter,t.minFilter=e.minFilter,t.wrapS=e.wrapS,t.wrapT=e.wrapT,t.flipY=e.flipY,t.anisotropy=e.anisotropy,t.mipmaps||(t.generateMipmaps=e.generateMipmaps),t):e}};let S=O;f(S,"registerTexture",(e,t,s,n,r)=>{if(x&&console.log("> Progressive: register texture",n,t.name,t.uuid,t,r),!t){x&&console.error("gltf-progressive: Register texture without texture");return}t.source&&(t.source[me]=r);const o=r.guid;O.assignLODInformation(e,t,o,s,n,void 0),O.lodInfos.set(o,r),O.lowresCache.set(o,t)}),f(S,"registerMesh",(e,t,s,n,r,o)=>{var u;x&&console.log("> Progressive: register mesh",r,s.name,o,s.uuid,s);const a=s.geometry;if(!a){x&&console.warn("gltf-progressive: Register mesh without geometry");return}a.userData||(a.userData={}),O.assignLODInformation(e,a,t,n,r,o.density),O.lodInfos.set(t,o);let l=O.lowresCache.get(t);l?l.push(s.geometry):l=[s.geometry],O.lowresCache.set(t,l),n>0&&!se(s)&&Fe(s,a);for(const c of Q)(u=c.onRegisteredNewMesh)==null||u.call(c,s,o)}),f(S,"lodInfos",new Map),f(S,"previouslyLoaded",new Map),f(S,"lowresCache",new Map);class ot{constructor(e,t,s,n,r){f(this,"url");f(this,"key");f(this,"level");f(this,"index");f(this,"density");this.url=e,this.key=t,this.level=s,n!=null&&(this.index=n),r!=null&&(this.density=r)}}const $=ae("debugprogressive"),nt=ae("noprogressive"),xe=Symbol("Needle:LODSManager"),Me=Symbol("Needle:LODState"),J=Symbol("Needle:CurrentLOD"),U={mesh_lod:-1,texture_lod:-1};var B,K,he,ee,te,ge,Y;const C=class{constructor(e,t){f(this,"context");f(this,"renderer");f(this,"projectionScreenMatrix",new y.Matrix4);f(this,"targetTriangleDensity",2e5);f(this,"skinnedMeshAutoUpdateBoundsInterval",30);f(this,"updateInterval","auto");j(this,B,1);f(this,"pause",!1);f(this,"manual",!1);f(this,"_lodchangedlisteners",[]);j(this,K,void 0);j(this,he,new y.Clock);j(this,ee,0);j(this,te,0);j(this,ge,0);j(this,Y,0);f(this,"_fpsBuffer",[60,60,60,60,60]);f(this,"_sphere",new y.Sphere);f(this,"_tempBox",new y.Box3);f(this,"_tempBox2",new y.Box3);f(this,"tempMatrix",new y.Matrix4);f(this,"_tempWorldPosition",new y.Vector3);f(this,"_tempBoxSize",new y.Vector3);f(this,"_tempBox2Size",new y.Vector3);this.renderer=e,this.context={...t}}static getObjectLODState(e){return e[Me]}static addPlugin(e){Q.push(e)}static removePlugin(e){const t=Q.indexOf(e);t>=0&&Q.splice(t,1)}static get(e,t){if(e[xe])return console.debug("[gltf-progressive] LODsManager already exists for this renderer"),e[xe];const s=new C(e,{engine:"unknown",...t});return e[xe]=s,s}get plugins(){return Q}addEventListener(e,t){e==="changed"&&this._lodchangedlisteners.push(t)}removeEventListener(e,t){if(e==="changed"){const s=this._lodchangedlisteners.indexOf(t);s>=0&&this._lodchangedlisteners.splice(s,1)}}enable(){if(m(this,K))return;console.debug("[gltf-progressive] Enabling LODsManager for renderer");let e=0;z(this,K,this.renderer.render);const t=this;be(this.renderer),this.renderer.render=function(s,n){const r=t.renderer.getRenderTarget();(r==null||"isXRRenderTarget"in r&&r.isXRRenderTarget)&&(e=0,z(t,ee,m(t,ee)+1),z(t,te,m(t,he).getDelta()),z(t,ge,m(t,ge)+m(t,te)),t._fpsBuffer.shift(),t._fpsBuffer.push(1/m(t,te)),z(t,Y,t._fpsBuffer.reduce((a,l)=>a+l)/t._fpsBuffer.length),$&&m(t,ee)%200===0&&console.log("FPS",Math.round(m(t,Y)),"Interval:",m(t,B)));const o=e++;m(t,K).call(this,s,n),t.onAfterRender(s,n,o)}}disable(){m(this,K)&&(console.debug("[gltf-progressive] Disabling LODsManager for renderer"),this.renderer.render=m(this,K),z(this,K,void 0))}update(e,t){this.internalUpdate(e,t)}onAfterRender(e,t,s){if(this.pause)return;const r=this.renderer.renderLists.get(e,0).opaque;let o=!0;if(r.length===1){const a=r[0].material;(a.name==="EffectMaterial"||a.name==="CopyShader")&&(o=!1)}if((t.parent&&t.parent.type==="CubeCamera"||s>=1&&t.type==="OrthographicCamera")&&(o=!1),o){if(nt||(this.updateInterval==="auto"?m(this,Y)<40&&m(this,B)<10?(z(this,B,m(this,B)+1),$&&console.warn("↓ Reducing LOD updates",m(this,B),m(this,Y).toFixed(0))):m(this,Y)>=60&&m(this,B)>1&&(z(this,B,m(this,B)-1),$&&console.warn("↑ Increasing LOD updates",m(this,B),m(this,Y).toFixed(0))):z(this,B,this.updateInterval),m(this,B)>0&&m(this,ee)%m(this,B)!=0))return;this.internalUpdate(e,t)}}internalUpdate(e,t){var l,u;const s=this.renderer.renderLists.get(e,0),n=s.opaque;this.projectionScreenMatrix.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse);const r=this.targetTriangleDensity;for(const c of n){if(c.material&&(((l=c.geometry)==null?void 0:l.type)==="BoxGeometry"||((u=c.geometry)==null?void 0:u.type)==="BufferGeometry")&&(c.material.name==="SphericalGaussianBlur"||c.material.name=="BackgroundCubeMaterial"||c.material.name==="CubemapFromEquirect"||c.material.name==="EquirectangularToCubeUV")){$&&(c.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]||(c.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]=!0,console.warn("Ignoring skybox or BLIT object",c,c.material.name,c.material.type)));continue}switch(c.material.type){case"LineBasicMaterial":case"LineDashedMaterial":case"PointsMaterial":case"ShadowMaterial":case"MeshDistanceMaterial":case"MeshDepthMaterial":continue}if($==="color"&&c.material&&!c.object.progressive_debug_color){c.object.progressive_debug_color=!0;const p=Math.random()*16777215,w=new y.MeshStandardMaterial({color:p});c.object.material=w}const g=c.object;(g instanceof y.Mesh||g.isMesh)&&this.updateLODs(e,t,g,r)}const o=s.transparent;for(const c of o){const g=c.object;(g instanceof y.Mesh||g.isMesh)&&this.updateLODs(e,t,g,r)}const a=s.transmissive;for(const c of a){const g=c.object;(g instanceof y.Mesh||g.isMesh)&&this.updateLODs(e,t,g,r)}}updateLODs(e,t,s,n){var a,l;s.userData||(s.userData={});let r=s[Me];if(r||(r=new it,s[Me]=r),r.frames++<2)return;for(const u of Q)(a=u.onBeforeUpdateLOD)==null||a.call(u,this.renderer,e,t,s);this.calculateLodLevel(t,s,r,n,U),U.mesh_lod=Math.round(U.mesh_lod),U.texture_lod=Math.round(U.texture_lod),U.mesh_lod>=0&&this.loadProgressiveMeshes(s,U.mesh_lod);let o=U.texture_lod;s.material&&o>=0&&this.loadProgressiveTextures(s.material,o);for(const u of Q)(l=u.onAfterUpdatedLOD)==null||l.call(u,this.renderer,e,t,s,U);r.lastLodLevel_Mesh=U.mesh_lod,r.lastLodLevel_Texture=U.texture_lod}loadProgressiveTextures(e,t){if(!e)return;if(Array.isArray(e)){for(const r of e)this.loadProgressiveTextures(r,t);return}let s=!1;(e[J]===void 0||t<e[J])&&(s=!0);const n=e["DEBUG:LOD"];n!=null&&(s=e[J]!=n,t=n),s&&(e[J]=t,S.assignTextureLOD(e,t).then(r=>{this._lodchangedlisteners.forEach(o=>o({type:"texture",level:t,object:e}))}))}loadProgressiveMeshes(e,t){if(!e)return Promise.resolve(null);let s=e[J]!==t;const n=e["DEBUG:LOD"];if(n!=null&&(s=e[J]!=n,t=n),s){e[J]=t;const r=e.geometry;return S.assignMeshLOD(e,t).then(o=>(o&&e[J]==t&&r!=e.geometry&&this._lodchangedlisteners.forEach(a=>a({type:"mesh",level:t,object:e})),o))}return Promise.resolve(null)}static isInside(e,t){const s=e.min,n=e.max,r=(s.x+n.x)*.5,o=(s.y+n.y)*.5;return this._tempPtInside.set(r,o,s.z).applyMatrix4(t).z<0}calculateLodLevel(e,t,s,n,r){var V;if(!t){r.mesh_lod=-1,r.texture_lod=-1;return}if(!e){r.mesh_lod=-1,r.texture_lod=-1;return}let a=10+1,l=!1;if($&&t["DEBUG:LOD"]!=null)return t["DEBUG:LOD"];const u=S.getMeshLODInformation(t.geometry),c=u==null?void 0:u.lods,g=c&&c.length>0,p=S.getMaterialMinMaxLODsCount(t.material),w=(p==null?void 0:p.min_count)!=1/0&&p.min_count>0&&p.max_count>0;if(!g&&!w){r.mesh_lod=0,r.texture_lod=0;return}g||(l=!0,a=0);const v=this.renderer.domElement.clientHeight||this.renderer.domElement.height;let M=t.geometry.boundingBox;if(t.type==="SkinnedMesh"){const D=t;if(!D.boundingBox)D.computeBoundingBox();else if(this.skinnedMeshAutoUpdateBoundsInterval>0&&s.frames%this.skinnedMeshAutoUpdateBoundsInterval===0){const h=se(D),I=D.geometry;h&&(D.geometry=h),D.computeBoundingBox(),D.geometry=I}M=D.boundingBox}if(M){const D=e;if(t.geometry.attributes.color&&t.geometry.attributes.color.count<100&&t.geometry.boundingSphere){this._sphere.copy(t.geometry.boundingSphere),this._sphere.applyMatrix4(t.matrixWorld);const d=e.getWorldPosition(this._tempWorldPosition);if(this._sphere.containsPoint(d)){r.mesh_lod=0,r.texture_lod=0;return}}if(this._tempBox.copy(M),this._tempBox.applyMatrix4(t.matrixWorld),D.isPerspectiveCamera&&C.isInside(this._tempBox,this.projectionScreenMatrix)){r.mesh_lod=0,r.texture_lod=0;return}if(this._tempBox.applyMatrix4(this.projectionScreenMatrix),this.renderer.xr.enabled&&D.isPerspectiveCamera&&D.fov>70){const d=this._tempBox.min,L=this._tempBox.max;let _=d.x,A=d.y,E=L.x,H=L.y;const le=2,pe=1.5,ce=(d.x+L.x)*.5,ue=(d.y+L.y)*.5;_=(_-ce)*le+ce,A=(A-ue)*le+ue,E=(E-ce)*le+ce,H=(H-ue)*le+ue;const We=_<0&&E>0?0:Math.min(Math.abs(d.x),Math.abs(L.x)),qe=A<0&&H>0?0:Math.min(Math.abs(d.y),Math.abs(L.y)),ye=Math.max(We,qe);s.lastCentrality=(pe-ye)*(pe-ye)*(pe-ye)}else s.lastCentrality=1;const h=this._tempBox.getSize(this._tempBoxSize);h.multiplyScalar(.5),screen.availHeight>0&&v>0&&h.multiplyScalar(v/screen.availHeight),e.isPerspectiveCamera?h.x*=e.aspect:e.isOrthographicCamera;const I=e.matrixWorldInverse,N=this._tempBox2;N.copy(M),N.applyMatrix4(t.matrixWorld),N.applyMatrix4(I);const G=N.getSize(this._tempBox2Size),P=Math.max(G.x,G.y);if(Math.max(h.x,h.y)!=0&&P!=0&&(h.z=G.z/Math.max(G.x,G.y)*Math.max(h.x,h.y)),s.lastScreenCoverage=Math.max(h.x,h.y,h.z),s.lastScreenspaceVolume.copy(h),s.lastScreenCoverage*=s.lastCentrality,$&&C.debugDrawLine){const d=this.tempMatrix.copy(this.projectionScreenMatrix);d.invert();const L=C.corner0,_=C.corner1,A=C.corner2,E=C.corner3;L.copy(this._tempBox.min),_.copy(this._tempBox.max),_.x=L.x,A.copy(this._tempBox.max),A.y=L.y,E.copy(this._tempBox.max);const H=(L.z+E.z)*.5;L.z=_.z=A.z=E.z=H,L.applyMatrix4(d),_.applyMatrix4(d),A.applyMatrix4(d),E.applyMatrix4(d),C.debugDrawLine(L,_,255),C.debugDrawLine(L,A,255),C.debugDrawLine(_,E,255),C.debugDrawLine(A,E,255)}let b=999;if(c&&s.lastScreenCoverage>0){for(let d=0;d<c.length;d++)if(c[d].density/s.lastScreenCoverage<n){b=d;break}}b<a&&(a=b,l=!0)}if(l?r.mesh_lod=a:r.mesh_lod=s.lastLodLevel_Mesh,$&&r.mesh_lod!=s.lastLodLevel_Mesh){const h=c==null?void 0:c[r.mesh_lod];h&&console.log(`Mesh LOD changed: ${s.lastLodLevel_Mesh} → ${r.mesh_lod} (${h.density.toFixed(0)}) - ${t.name}`)}if(w){const D="saveData"in globalThis.navigator&&globalThis.navigator.saveData===!0;if(s.lastLodLevel_Texture<0){if(r.texture_lod=p.max_count-1,$){const h=p.lods[p.max_count-1];$&&console.log(`First Texture LOD ${r.texture_lod} (${h.max_height}px) - ${t.name}`)}}else{const h=s.lastScreenspaceVolume.x+s.lastScreenspaceVolume.y+s.lastScreenspaceVolume.z;let I=s.lastScreenCoverage*4;((V=this.context)==null?void 0:V.engine)==="model-viewer"&&(I*=1.5);const G=v/window.devicePixelRatio*I;let P=!1;for(let X=p.lods.length-1;X>=0;X--){const b=p.lods[X];if(!(D&&b.max_height>=2048)&&!(tt()&&b.max_height>4096)&&(b.max_height>G||!P&&X===0)){if(P=!0,r.texture_lod=X,r.texture_lod<s.lastLodLevel_Texture){const T=b.max_height;$&&console.log(`Texture LOD changed: ${s.lastLodLevel_Texture} → ${r.texture_lod} = ${T}px
|
|
6
|
+
Screensize: ${G.toFixed(0)}px, Coverage: ${(100*s.lastScreenCoverage).toFixed(2)}%, Volume ${h.toFixed(1)}
|
|
7
|
+
${t.name}`)}break}}}}else r.texture_lod=0}};let R=C;B=new WeakMap,K=new WeakMap,he=new WeakMap,ee=new WeakMap,te=new WeakMap,ge=new WeakMap,Y=new WeakMap,f(R,"debugDrawLine"),f(R,"corner0",new y.Vector3),f(R,"corner1",new y.Vector3),f(R,"corner2",new y.Vector3),f(R,"corner3",new y.Vector3),f(R,"_tempPtInside",new y.Vector3);class it{constructor(){f(this,"frames",0);f(this,"lastLodLevel_Mesh",-1);f(this,"lastLodLevel_Texture",-1);f(this,"lastScreenCoverage",0);f(this,"lastScreenspaceVolume",new y.Vector3);f(this,"lastCentrality",0)}}const Ce=Symbol("NEEDLE_mesh_lod"),de=Symbol("NEEDLE_texture_lod");let ne=null;function Ae(){const i=at();i&&(i.mapURLs(function(e){return Be(),e}),Be(),ne==null||ne.disconnect(),ne=new MutationObserver(e=>{e.forEach(t=>{t.addedNodes.forEach(s=>{s instanceof HTMLElement&&s.tagName.toLowerCase()==="model-viewer"&&Ne(s)})})}),ne.observe(document,{childList:!0,subtree:!0}))}function at(){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"),Ae()}),null)}function Be(){if(typeof document>"u")return;document.querySelectorAll("model-viewer").forEach(e=>{Ne(e)})}const Re=new WeakSet;let lt=0;function Ne(i){if(!i||Re.has(i))return null;Re.add(i),console.debug("[gltf-progressive] found new model-viewer..."+ ++lt+`
|
|
8
|
+
`,i.getAttribute("src"));let e=null,t=null,s=null;for(let n=i;n!=null;n=Object.getPrototypeOf(n)){const r=Object.getOwnPropertySymbols(n),o=r.find(u=>u.toString()=="Symbol(renderer)"),a=r.find(u=>u.toString()=="Symbol(scene)"),l=r.find(u=>u.toString()=="Symbol(needsRender)");!e&&o!=null&&(e=i[o].threeRenderer),!t&&a!=null&&(t=i[a]),!s&&l!=null&&(s=i[l])}if(e&&t){let n=function(){if(s){let o=0,a=setInterval(()=>{if(o++>5){clearInterval(a);return}s==null||s.call(i)},300)}};console.debug("[gltf-progressive] setup model-viewer");const r=R.get(e,{engine:"model-viewer"});return R.addPlugin(new ct),r.enable(),r.addEventListener("changed",()=>{s==null||s.call(i)}),i.addEventListener("model-visibility",o=>{o.detail.visible&&(s==null||s.call(i))}),i.addEventListener("load",()=>{n()}),()=>{r.disable()}}return null}class ct{constructor(){f(this,"_didWarnAboutMissingUrl",!1)}onBeforeUpdateLOD(e,t,s,n){this.tryParseMeshLOD(t,n),this.tryParseTextureLOD(t,n)}getUrl(e){if(!e)return null;let t=e.getAttribute("src");return t||(t=e.src),t||(this._didWarnAboutMissingUrl||console.warn("No url found in modelviewer",e),this._didWarnAboutMissingUrl=!0),t}tryGetCurrentGLTF(e){return e._currentGLTF}tryGetCurrentModelViewer(e){return e.element}tryParseTextureLOD(e,t){if(t[de]==!0)return;t[de]=!0;const s=this.tryGetCurrentGLTF(e),n=this.tryGetCurrentModelViewer(e),r=this.getUrl(n);if(r&&s&&t.material){let o=function(l){var c,g,p;if(l[de]==!0)return;l[de]=!0,l.userData&&(l.userData.LOD=-1);const u=Object.keys(l);for(let w=0;w<u.length;w++){const v=u[w],M=l[v];if((M==null?void 0:M.isTexture)===!0){const V=(g=(c=M.userData)==null?void 0:c.associations)==null?void 0:g.textures;if(V==null)continue;const D=s.parser.json.textures[V];if(!D){console.warn("Texture data not found for texture index "+V);continue}if((p=D==null?void 0:D.extensions)!=null&&p[W]){const h=D.extensions[W];h&&r&&S.registerTexture(r,M,h.lods.length,V,h)}}}};const a=t.material;if(Array.isArray(a))for(const l of a)o(l);else o(a)}}tryParseMeshLOD(e,t){var o,a;if(t[Ce]==!0)return;t[Ce]=!0;const s=this.tryGetCurrentModelViewer(e),n=this.getUrl(s);if(!n)return;const r=(a=(o=t.userData)==null?void 0:o.gltfExtensions)==null?void 0:a[W];if(r&&n){const l=t.uuid;S.registerMesh(n,l,t,0,r.lods.length,r)}}}function ze(i,e,t,s){be(e),Se(t),Te(t,{progressive:!0,...s==null?void 0:s.hints}),t.register(r=>new S(r,i));const n=R.get(e);return(s==null?void 0:s.enableLODsManager)!==!1&&n.enable(),n}Ae();if(!st){const i={gltfProgressive:{useNeedleProgressive:ze,LODsManager:R,configureLoader:Te,getRaycastMesh:se,useRaycastMeshes:Ve}};if(!globalThis.Needle)globalThis.Needle=i;else for(const e in i)globalThis.Needle[e]=i[e]}exports.EXTENSION_NAME=W;exports.LODsManager=R;exports.NEEDLE_progressive=S;exports.VERSION=ke;exports.addDracoAndKTX2Loaders=Se;exports.configureLoader=Te;exports.createLoaders=be;exports.getRaycastMesh=se;exports.patchModelViewer=Ae;exports.registerRaycastMesh=Fe;exports.setDracoDecoderLocation=Ge;exports.setKTX2TranscoderLocation=$e;exports.useNeedleProgressive=ze;exports.useRaycastMeshes=Ve;
|
package/lib/extension.d.ts
CHANGED
|
@@ -6,25 +6,22 @@ declare type NEEDLE_progressive_model_LOD = {
|
|
|
6
6
|
hash?: string;
|
|
7
7
|
};
|
|
8
8
|
/** This is the data structure we have in the NEEDLE_progressive extension */
|
|
9
|
-
declare type
|
|
9
|
+
declare type NEEDLE_progressive_model = {
|
|
10
10
|
guid: string;
|
|
11
11
|
lods: Array<NEEDLE_progressive_model_LOD>;
|
|
12
12
|
};
|
|
13
|
-
export declare type
|
|
13
|
+
export declare type NEEDLE_progressive_texture_model = NEEDLE_progressive_model & {
|
|
14
14
|
lods: Array<NEEDLE_progressive_model_LOD & {
|
|
15
15
|
width: number;
|
|
16
16
|
height: number;
|
|
17
17
|
}>;
|
|
18
18
|
};
|
|
19
|
-
export declare type
|
|
20
|
-
/** @deprecated Removed */
|
|
19
|
+
export declare type NEEDLE_progressive_mesh_model = NEEDLE_progressive_model & {
|
|
21
20
|
density: number;
|
|
22
21
|
lods: Array<NEEDLE_progressive_model_LOD & {
|
|
23
|
-
/** @deprecated Use densities with the primitive index */
|
|
24
22
|
density: number;
|
|
25
23
|
indexCount: number;
|
|
26
24
|
vertexCount: number;
|
|
27
|
-
densities: number[] | undefined;
|
|
28
25
|
}>;
|
|
29
26
|
};
|
|
30
27
|
/**
|
|
@@ -67,8 +64,7 @@ declare type TextureLODsMinMaxInfo = {
|
|
|
67
64
|
export declare class NEEDLE_progressive implements GLTFLoaderPlugin {
|
|
68
65
|
/** The name of the extension */
|
|
69
66
|
get name(): string;
|
|
70
|
-
static
|
|
71
|
-
static getPrimitiveIndex(geo: BufferGeometry): number;
|
|
67
|
+
static getMeshLODInformation(geo: BufferGeometry): NEEDLE_progressive_mesh_model | null;
|
|
72
68
|
static getMaterialMinMaxLODsCount(material: Material | Material[], minmax?: TextureLODsMinMaxInfo): TextureLODsMinMaxInfo;
|
|
73
69
|
/** Check if a LOD level is available for a mesh or a texture
|
|
74
70
|
* @param obj the mesh or texture to check
|
|
@@ -111,11 +107,11 @@ export declare class NEEDLE_progressive implements GLTFLoaderPlugin {
|
|
|
111
107
|
/**
|
|
112
108
|
* Register a texture with LOD information
|
|
113
109
|
*/
|
|
114
|
-
static registerTexture: (url: string, tex: Texture, level: number, index: number, ext:
|
|
110
|
+
static registerTexture: (url: string, tex: Texture, level: number, index: number, ext: NEEDLE_progressive_texture_model) => void;
|
|
115
111
|
/**
|
|
116
112
|
* Register a mesh with LOD information
|
|
117
113
|
*/
|
|
118
|
-
static registerMesh: (url: string, key: string, mesh: Mesh, level: number, index: number, ext:
|
|
114
|
+
static registerMesh: (url: string, key: string, mesh: Mesh, level: number, index: number | undefined, ext: NEEDLE_progressive_mesh_model) => void;
|
|
119
115
|
/** A map of key = asset uuid and value = LOD information */
|
|
120
116
|
private static readonly lodInfos;
|
|
121
117
|
/** cache of already loaded mesh lods */
|