three-live 1.2.2 → 1.2.3
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/README.md +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/three-author-engine.js +57 -39
- package/dist/three-author.cjs +52 -34
- package/dist/three-author.d.ts +2 -1
- package/dist/three-author.js +52 -34
- package/dist/three-convert.cjs +55 -37
- package/dist/three-convert.d.ts +2 -1
- package/dist/three-convert.js +55 -37
- package/dist/three-live-animation.cjs +7 -7
- package/dist/three-live-animation.d.ts +2 -1
- package/dist/three-live-animation.js +7 -7
- package/dist/three-live-animation.min.js +7 -7
- package/dist/three-live-cad.cjs +2 -2
- package/dist/three-live-cad.d.ts +2 -1
- package/dist/three-live-cad.js +2 -2
- package/dist/three-live-cad.min.js +2 -2
- package/dist/three-live-element.cjs +24 -6
- package/dist/three-live-element.d.ts +2 -1
- package/dist/three-live-element.js +24 -6
- package/dist/three-live-full.cjs +81 -63
- package/dist/three-live-full.js +81 -63
- package/dist/three-live-full.min.js +81 -63
- package/dist/three-live-studio.cjs +18 -18
- package/dist/three-live-studio.d.ts +2 -1
- package/dist/three-live-studio.js +18 -18
- package/dist/three-live-studio.min.js +18 -18
- package/dist/three-live-viewer.cjs +24 -6
- package/dist/three-live-viewer.d.ts +2 -1
- package/dist/three-live-viewer.js +24 -6
- package/dist/three-live-viewer.min.js +24 -6
- package/dist/three-live.cjs +55 -37
- package/dist/three-live.js +55 -37
- package/dist/three-live.min.js +55 -37
- package/dist/three-view.cjs +24 -6
- package/dist/three-view.d.ts +2 -1
- package/dist/three-view.js +24 -6
- package/dist/three-xr.cjs +49 -31
- package/dist/three-xr.d.ts +2 -1
- package/dist/three-xr.js +49 -31
- package/package.json +1 -1
package/dist/three-live.cjs
CHANGED
|
@@ -14,18 +14,33 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
"use strict";var
|
|
17
|
+
"use strict";var _t=Object.defineProperty;var fr=Object.getOwnPropertyDescriptor;var pr=Object.getOwnPropertyNames;var br=Object.prototype.hasOwnProperty;var yr=(n,e)=>{for(var t in e)_t(n,t,{get:e[t],enumerable:!0})},gr=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of pr(e))!br.call(n,i)&&i!==t&&_t(n,i,{get:()=>e[i],enumerable:!(r=fr(e,i))||r.enumerable});return n};var xr=n=>gr(_t({},"__esModule",{value:!0}),n);var pi={};yr(pi,{THREE:()=>Ie,ThreeLiveElement:()=>Te,ThreeView:()=>de,activateAR:()=>Et,createUSDZBlob:()=>ke,evaluateToneMapping:()=>Un,getARCapabilities:()=>St,getBestARMode:()=>dr,isQuickLookSupported:()=>vn,isSceneViewerSupported:()=>wn,isWebXRSupported:()=>An,toGLBData:()=>Ae});module.exports=xr(pi);var Ke="__THREE_LIVE_REGISTRY__";function Q(){let n=typeof globalThis<"u"?globalThis:{};if(!n[Ke]){let e={plugins:[],decoders:new Map};try{Object.defineProperty(n,Ke,{value:e,writable:!1,configurable:!1,enumerable:!1})}catch{n[Ke]=e}}return n[Ke]}var ce=Q().plugins;function Ze(n){let e=Q().plugins;e.some(t=>t.name===n.name)||e.push(n),n.onRegister?.()}function Mn(){return Q().plugins}var vr=`#version 300 es
|
|
18
18
|
layout(location=0) in vec3 aPosition;layout(location=1) in vec2 aUV;uniform mat4 uMVP;out vec2 vUV;void main(){vUV=aUV;gl_Position=uMVP*vec4(aPosition,1.);}`,wr=`#version 300 es
|
|
19
|
-
precision highp float;in vec2 vUV;uniform float uShadowIntensity,uShadowSoftness;out vec4 fragColor;void main(){vec2 p=(vUV-.5)*2.;float d=clamp(length(p),0.,1.);fragColor=vec4(0.,0.,0.,pow(1.-d*d,mix(1.2,2.8,uShadowSoftness))*smoothstep(1.,.85-uShadowSoftness*.6,d)*uShadowIntensity);}`,it=new WeakMap,Tn=new Float32Array(20);function Ft(n,e){let[t,r,i,s,o,u]=e;return[n[0]*t+n[4]*r+n[8]*i+n[12],n[1]*t+n[5]*r+n[9]*i+n[13],n[2]*t+n[6]*r+n[10]*i+n[14],Math.abs(n[0])*s+Math.abs(n[4])*o+Math.abs(n[8])*u,Math.abs(n[1])*s+Math.abs(n[5])*o+Math.abs(n[9])*u,Math.abs(n[2])*s+Math.abs(n[6])*o+Math.abs(n[10])*u]}function Ar(n){if(n._lb!==void 0)return n._lb;let e=1e9,t=1e9,r=1e9,i=-1e9,s=-1e9,o=-1e9;for(let u of n.primitives||[]){let c=u.positions;if(c)for(let a=0;a<c.length;a+=3)c[a]<e&&(e=c[a]),c[a+1]<t&&(t=c[a+1]),c[a+2]<r&&(r=c[a+2]),c[a]>i&&(i=c[a]),c[a+1]>s&&(s=c[a+1]),c[a+2]>o&&(o=c[a+2])}return n._lb=e<=i?[(e+i)*.5,(t+s)*.5,(r+o)*.5,(i-e)*.5,(s-t)*.5,(o-r)*.5]:null}function Mr(n){let e=it.get(n);if(e)return e;let t=(u,c)=>{let a=n.createShader(u);return n.shaderSource(a,c),n.compileShader(a),a},r=n.createProgram();n.attachShader(r,t(35633,vr)),n.attachShader(r,t(35632,wr)),n.linkProgram(r);let i=n.createVertexArray(),s=n.createBuffer(),o=n.createBuffer();return n.bindVertexArray(i),n.bindBuffer(34962,s),n.bufferData(34962,80,35048),n.enableVertexAttribArray(0),n.vertexAttribPointer(0,3,5126,!1,20,0),n.enableVertexAttribArray(1),n.vertexAttribPointer(1,2,5126,!1,20,12),n.bindBuffer(34963,o),n.bufferData(34963,new Uint16Array([0,1,2,0,2,3]),35044),n.bindVertexArray(null),e={prog:r,vao:i,vbo:s,ibo:o,uMVP:n.getUniformLocation(r,"uMVP"),uIntensity:n.getUniformLocation(r,"uShadowIntensity"),uSoftness:n.getUniformLocation(r,"uShadowSoftness")},it.set(n,e),e}var _n={name:"contact-shadow",onAfterRender(n,e,t){let r=e.shadowIntensity;if(r<=0||!e.bounds)return;let i=Mr(n),s=!e.xrSessionActive&&(e.backdropMeshes?.length??0)>0,o=[],u=[];for(let d of e.meshes||[]){if(!d||d.visible===!1||d.isPluginMesh||d.name==="__xr_reticle__"||d.name?.startsWith("__xr_slot_"))continue;let g=Ar(d);if(!g)continue;d.transform&&(g=Ft(d.transform,g)),e.modelRootMatrix&&(g=Ft(e.modelRootMatrix,g));let[I,P,p,M,x,w]=g,T=[I,p,M,w,P-x,P+x];/floor|table|pedestal|ground|base|plane/i.test(d.name||"")||x<.14&&Math.min(M,w)>.45?u.push(T):o.push(T)}let c=[],a=e.bounds.center||[0,0,0],l=Math.max(.05,Number(e.bounds.radius)||.5),h=e.bounds.min,m=h?[a[0],a[1],a[2],l,Math.max(.01,a[1]-h[1]),l]:[a[0],a[1],a[2],l,l,l];e.modelRootMatrix&&(m=Ft(e.modelRootMatrix,m));let b=e.xrSessionActive&&u.length===0&&String(e.container?.tagName||"").toLowerCase()==="xr-live"?(e.modelRootMatrix?e.modelRootMatrix[5]*-.25+e.modelRootMatrix[13]:-.25)+.002:m[1]-m[4]+.002;for(let[d,g,I,P,p]of o){let M=-1/0;for(let[w,T,A,y,,E]of u)p>=E-.08&&Math.abs(d-w)<=A&&Math.abs(g-T)<=y&&E+.002>M&&(M=E+.002);s&&(M=Math.max(M,d>=.04&&d<=.36&&g>=-.34&&g<=-.04&&p>=.01?.036:Math.hypot(d,g)<=.66&&p>=-.06?.003:-.477)),isFinite(M)||(M=b);let x=c.find(w=>Math.hypot(d-w[0],g-w[1])<.06&&Math.abs(M-w[5])<.05);x?(x[2]=Math.max(x[2],I*.78),x[3]=Math.max(x[3],P*.78),x[4]=Math.min(x[4],p)):c.push([d,g,I,P,p,M])}if(c.length===0){let d=Math.max(.1,m[3]*1.5)/1.45;c.push([m[0],m[2],d,d,b,b])}n.useProgram(i.prog),n.uniformMatrix4fv(i.uMVP,!1,t),n.enable(3042),(n.blendFuncSeparate||n.blendFunc).call(n,770,771,1,771),n.depthMask(!1),n.bindVertexArray(i.vao),n.bindBuffer(34962,i.vbo);for(let[d,g,I,P,p,M]of c){let x=Math.max(0,p-M),w=r/(1+x*2);if(w<.02)continue;let T=1+Math.min(.75,x*.85),A=Math.max(.045,I*1.45*T),y=Math.max(.045,P*1.45*T);Tn.set([d-A,M,g-y,0,0,d+A,M,g-y,1,0,d+A,M,g+y,1,1,d-A,M,g+y,0,1]),n.bufferSubData(34962,0,Tn),n.uniform1f(i.uIntensity,w),n.uniform1f(i.uSoftness,Math.min(1,e.shadowSoftness+Math.min(.45,x*.6))),n.drawElements(4,6,5123,0)}n.bindVertexArray(null),n.depthMask(!0),n.disable(3042)},onDestroy(n){let e=it.get(n);e&&(n.deleteVertexArray(e.vao),n.deleteBuffer(e.vbo),n.deleteBuffer(e.ibo),n.deleteProgram(e.prog),it.delete(n))}};function Cn(n,e,t){let r=[],i=new Map,s=[],o=[],u=[],c=new Map,a=p=>{let M=i.get(p);return M===void 0&&(M=r.length,r.push({op:p}),i.set(p,M)),M},l=p=>{let M=c.get(p);return M===void 0&&(M=u.length,u.push({id:p}),c.set(p,M)),M},h=(p,M={})=>s.push({declaration:a(p),...M})-1,m=(p,M,x)=>o.push({id:p,type:M,value:x})-1,v=p=>({node:p,socket:"value"}),b=t?.interactivity??t?.gltfExtensions?.KHR_interactivity;if(b&&typeof b=="object"){let p=Array.isArray(b.graphs)?b.graphs[b.graph??0]:b;if(p&&Array.isArray(p.nodes)){let M=Array.isArray(p.declarations)?p.declarations:[];for(let x of M)x?.op&&a(x.op);Array.isArray(p.variables)&&o.push(...p.variables);for(let x of p.events||[])x?.id&&l(x.id);for(let x of p.nodes){if(!x||typeof x!="object")continue;let w=x.op||(typeof x.declaration=="number"?M[x.declaration]?.op:"");s.push(w?{...x,declaration:a(w)}:{...x})}}}let d=(p,M,x="translation")=>x==="baseColorFactor"||x==="metallicFactor"||x==="roughnessFactor"?`/materials/${Math.max(0,M)}/pbrMetallicRoughness/${x}`:x==="emissiveFactor"||x==="alphaCutoff"?`/materials/${Math.max(0,M)}/${x}`:x==="visible"?`/nodes/${p}/extensions/KHR_node_visibility/visible`:`/nodes/${p}/${x}`,g=new Map;n.forEach((p,M)=>{typeof p?.name=="string"&&!g.has(p.name)&&g.set(p.name,M)});let I=(p,M)=>typeof p.target=="string"&&g.has(p.target)?g.get(p.target):typeof p.targetNode=="number"?p.targetNode:M,P=p=>{let M=n[p];return(typeof M?.mesh=="number"?e[M.mesh]?.primitives?.[0]?.material:0)??0};for(let p=0;p<n.length;p++){let M=n[p],x=M?.extras?.interactivity;if(!x||typeof x!="object")continue;let w=(typeof M.mesh=="number"?e[M.mesh]?.primitives?.[0]?.material:0)??0,T=y=>{let E=Array.isArray(y)?y:[y],f=[];for(let S=0;S<E.length;S++){let R=E[S];if(!R||typeof R!="object")continue;let F=R.action||"interpolate",D=typeof R.duration=="number"?R.duration:.35;if(F==="toggleTransform"){let U=R.property==="rotation"||R.property==="scale"?R.property:"translation",k=U==="rotation"?M.rotation||[0,0,0,1]:U==="scale"?M.scale||[1,1,1]:M.translation||[0,0,0],X=`/nodes/${p}/${U}`,B=m(`__toggle_${p}_${S}`,"bool",!1),L=h("variable/get",{configuration:{variable:B}}),O=h("math/not",{values:{a:v(L)}}),V=h("variable/set",{configuration:{variable:B},values:{value:v(O)}}),z=h("pointer/interpolate",{configuration:{pointer:X},values:{value:{value:Array.isArray(R.to)?R.to:k},duration:{value:D}}}),$=h("pointer/interpolate",{configuration:{pointer:X},values:{value:{value:Array.isArray(R.from)?R.from:k},duration:{value:D}}});s[V].flows={out:{node:h("flow/branch",{values:{condition:v(L)},flows:{true:{node:z},false:{node:$}}})}},f.push(V)}else if(F==="interpolate"){let U=R.to??R.value;if(U===void 0)continue;let k={value:{value:U},duration:{value:D}};R.from!==void 0&&(k.from={value:R.from}),f.push(h("pointer/interpolate",{configuration:{pointer:typeof R.pointer=="string"?R.pointer:d(I(R,p),P(I(R,p)),R.property)},values:k}))}else if(F==="setProperty"){if(R.value===void 0)continue;f.push(h("pointer/set",{configuration:{pointer:typeof R.pointer=="string"?R.pointer:d(I(R,p),P(I(R,p)),R.property)},values:{value:{value:R.value}}}))}else if(F==="toggleVisibility"){let U=I(R,p),k=m(`__vis_${U}_${S}`,"bool",!0),X=h("variable/get",{configuration:{variable:k}}),B=h("math/not",{values:{a:v(X)}}),L=h("variable/set",{configuration:{variable:k},values:{value:v(B)}});s[L].flows={out:{node:h("pointer/set",{configuration:{pointer:`/nodes/${U}/extensions/KHR_node_visibility/visible`},values:{value:v(X)}})}},f.push(L)}else if(F==="cycleMaterialColor"&&Array.isArray(R.colors)&&R.colors.length>0){let U=typeof R.duration=="number"?R.duration:.25,k=`/materials/${Math.max(0,w)}/pbrMetallicRoughness/baseColorFactor`,X=m(`__color_idx_${p}_${S}`,"int",0),B=h("variable/get",{configuration:{variable:X}}),L=h("math/add",{values:{a:v(B),b:{value:1}}}),O=h("math/rem",{values:{a:v(L),b:{value:R.colors.length}}}),V=h("variable/set",{configuration:{variable:X},values:{value:v(O)}}),z={};for(let $=0;$<R.colors.length;$++){let C=R.colors[$],N=Array.isArray(C)&&C.length>=3?[C[0],C[1],C[2],C[3]??1]:[1,1,1,1];z[String($)]={node:U>0?h("pointer/interpolate",{configuration:{pointer:k},values:{value:{value:N},duration:{value:U}}}):h("pointer/set",{configuration:{pointer:k},values:{value:{value:N}}})}}s[V].flows={out:{node:h("flow/switch",{values:{selection:v(B)},flows:z})}},f.push(V)}else if(F==="playAnimation")f.push(h("animation/start",{configuration:{animation:R.animation??R.clip??0}}));else if(F==="stopAnimation")f.push(h("animation/stop"));else if(F==="sendEvent"){let U={};for(let[k,X]of Object.entries(R.values||{}))U[k]={value:X};f.push(h("event/send",{configuration:{event:l(String(R.event??R.id??"custom"))},values:U}))}}if(!f.length)return null;if(f.length===1)return f[0];let _={};return f.forEach((S,R)=>{_[String(R)]={node:S}}),h("flow/sequence",{flows:_})},A=(y,E,f)=>{let _=T(E);_!==null&&h(y,{...f?{configuration:f}:{},flows:{out:{node:_}}})};if(x.onSelect&&A("pointer/onSelect",x.onSelect,{nodeIndex:p}),x.onHoverIn&&A("pointer/onHoverIn",x.onHoverIn,{nodeIndex:p}),x.onHoverOut&&A("pointer/onHoverOut",x.onHoverOut,{nodeIndex:p}),x.onStart&&A("event/onStart",x.onStart),x.onReceive&&typeof x.onReceive=="object")for(let[y,E]of Object.entries(x.onReceive))A("event/receive",E,{event:l(y)})}return s.length?{graphs:[{declarations:r,nodes:s,variables:o,events:u}],graph:0}:null}var st='SecurityError: Client-modified script compilation (Use Case 1) is disabled by default to satisfy strict CSP and Trusted Types requirements. Use script-src="..." or loadScriptFromSrc(url) for server-generated scripts (Use Case 2), or explicitly opt in via ThreeLiveElement.allowClientScripts = true (or the allow-client-scripts attribute).',ot="Security Error: client-side scripts require allow-client-scripts opt-in.";function te(){let n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n}function at(n,e,t,r,i){let s=1/Math.tan(e/2);n.fill(0),n[0]=s/t,n[5]=s,n[11]=-1;let o=1/(r-i);return n[10]=(i+r)*o,n[14]=2*i*r*o,n}function Be(n,e,t,r){let[i,s,o]=e,[u,c,a]=r,[l,h,m]=t,v=i-l,b=s-h,d=o-m,g=Math.hypot(v,b,d);g<=1e-5?(v=0,b=0,d=1):(v/=g,b/=g,d/=g);let I=c*d-a*b,P=a*v-u*d,p=u*b-c*v;g=Math.hypot(I,P,p),g<=1e-5?(I=0,P=0,p=0):(I/=g,P/=g,p/=g);let M=b*p-d*P,x=d*I-v*p,w=v*P-b*I;return g=Math.hypot(M,x,w),g<=1e-5?(M=0,x=0,w=0):(M/=g,x/=g,w/=g),n[0]=I,n[1]=M,n[2]=v,n[3]=0,n[4]=P,n[5]=x,n[6]=b,n[7]=0,n[8]=p,n[9]=w,n[10]=d,n[11]=0,n[12]=-(I*i+P*s+p*o),n[13]=-(M*i+x*s+w*o),n[14]=-(v*i+b*s+d*o),n[15]=1,n}function re(n,e,t){let r=e[0],i=e[1],s=e[2],o=e[3],u=e[4],c=e[5],a=e[6],l=e[7],h=e[8],m=e[9],v=e[10],b=e[11],d=e[12],g=e[13],I=e[14],P=e[15],p=t[0],M=t[1],x=t[2],w=t[3];return n[0]=p*r+M*u+x*h+w*d,n[1]=p*i+M*c+x*m+w*g,n[2]=p*s+M*a+x*v+w*I,n[3]=p*o+M*l+x*b+w*P,p=t[4],M=t[5],x=t[6],w=t[7],n[4]=p*r+M*u+x*h+w*d,n[5]=p*i+M*c+x*m+w*g,n[6]=p*s+M*a+x*v+w*I,n[7]=p*o+M*l+x*b+w*P,p=t[8],M=t[9],x=t[10],w=t[11],n[8]=p*r+M*u+x*h+w*d,n[9]=p*i+M*c+x*m+w*g,n[10]=p*s+M*a+x*v+w*I,n[11]=p*o+M*l+x*b+w*P,p=t[12],M=t[13],x=t[14],w=t[15],n[12]=p*r+M*u+x*h+w*d,n[13]=p*i+M*c+x*m+w*g,n[14]=p*s+M*a+x*v+w*I,n[15]=p*o+M*l+x*b+w*P,n}function Pe(n,e,t,r){let i=e[0],s=e[1],o=e[2],u=e[3],c=i+i,a=s+s,l=o+o,h=i*c,m=i*a,v=i*l,b=s*a,d=s*l,g=o*l,I=u*c,P=u*a,p=u*l,M=r[0],x=r[1],w=r[2];return n[0]=(1-(b+g))*M,n[1]=(m+p)*M,n[2]=(v-P)*M,n[3]=0,n[4]=(m-p)*x,n[5]=(1-(h+g))*x,n[6]=(d+I)*x,n[7]=0,n[8]=(v+P)*w,n[9]=(d-I)*w,n[10]=(1-(h+b))*w,n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n}function be(n,e){let t=e[0],r=e[1],i=e[2],s=e[4],o=e[5],u=e[6],c=e[8],a=e[9],l=e[10],h=l*o-u*a,m=-l*s+u*c,v=a*s-o*c,b=t*h+r*m+i*v;return b&&(b=1/b,n[0]=h*b,n[1]=m*b,n[2]=v*b,n[3]=(-l*r+i*a)*b,n[4]=(l*t-i*c)*b,n[5]=(-a*t+r*c)*b,n[6]=(u*r-i*o)*b,n[7]=(-u*t+i*s)*b,n[8]=(o*t-r*s)*b),n}function Ln(n,e){let t=e[0],r=e[1],i=e[2],s=e[3],o=e[4],u=e[5],c=e[6],a=e[7],l=e[8],h=e[9],m=e[10],v=e[11],b=e[12],d=e[13],g=e[14],I=e[15],P=t*u-r*o,p=t*c-i*o,M=t*a-s*o,x=r*c-i*u,w=r*a-s*u,T=i*a-s*c,A=l*d-h*b,y=l*g-m*b,E=l*I-v*b,f=h*g-m*d,_=h*I-v*d,S=m*I-v*g,R=P*S-p*_+M*f+x*E-w*y+T*A;return R?(R=1/R,n[0]=(u*S-c*_+a*f)*R,n[1]=(i*_-r*S-s*f)*R,n[2]=(d*T-g*w+I*x)*R,n[3]=(m*w-h*T-v*x)*R,n[4]=(c*E-o*S-a*y)*R,n[5]=(t*S-i*E+s*y)*R,n[6]=(g*M-b*T-I*p)*R,n[7]=(l*T-m*M+v*p)*R,n[8]=(o*_-u*E+a*A)*R,n[9]=(r*E-t*_-s*A)*R,n[10]=(b*w-d*M+I*P)*R,n[11]=(h*M-l*w-v*P)*R,n[12]=(u*y-o*f-c*A)*R,n[13]=(t*f-r*y+i*A)*R,n[14]=(d*p-b*x-g*P)*R,n[15]=(l*x-h*p+m*P)*R,n):null}function kt(n,e,t,r,i){let s=i[0]*e+i[4]*t+i[8]*r+i[12],o=i[1]*e+i[5]*t+i[9]*r+i[13],u=i[2]*e+i[6]*t+i[10]*r+i[14],c=i[3]*e+i[7]*t+i[11]*r+i[15],a=c!==0?1/c:1;n[0]=s*a,n[1]=o*a,n[2]=u*a}function Dn(n,e,t,r,i,s,o,u,c,a,l,h,m,v,b,d,g=0){let I=a-o,P=l-u,p=h-c,M=m-o,x=v-u,w=b-c,T=i*w-s*x,A=s*M-r*w,y=r*x-i*M,E=I*T+P*A+p*y;if(E>-1e-7&&E<1e-7)return!1;let f=1/E,_=n-o,S=e-u,R=t-c,F=f*(_*T+S*A+R*y);if(F<-g||F>1+g)return!1;let D=S*p-R*P,U=R*I-_*p,k=_*P-S*I,X=f*(r*D+i*U+s*k);if(X<-g||F+X>1+g)return!1;let B=f*(M*D+x*U+w*k);if(B>1e-4&&B<d.distance){d.distance=B,d.point=[n+r*B,e+i*B,t+s*B];let L=P*w-p*x,O=p*M-I*w,V=I*x-P*M,z=Math.hypot(L,O,V)||1;return d.normal=[L/z,O/z,V/z],!0}return!1}function ct(n,e){let t=Array.isArray(n?.nodes)?n.nodes.length:0,r=[];for(let l=0;l<t;l++)r.push(te());if(t===0)return r;let i=new Set;for(let l of n.nodes)if(Array.isArray(l.children))for(let h of l.children)i.add(h);let s=new Set,o=128,u=(l,h,m=0)=>{if(m>o||l<0||l>=t||s.has(l))return;s.add(l);let v=n.nodes[l];if(!v)return;let b=te();if(e&&e[l])b.set(e[l]);else if(v.matrix&&v.matrix.length===16)b.set(v.matrix);else{let g=v.translation||[0,0,0],I=v.rotation||[0,0,0,1],P=v.scale||[1,1,1];Pe(b,I,g,P)}let d=r[l];if(h?re(d,h,b):d.set(b),Array.isArray(v.children))for(let g of v.children)typeof g=="number"&&u(g,d,m+1)},c=[],a=n.scenes&&n.scenes[n.scene!==void 0?n.scene:0];if(a&&Array.isArray(a.nodes))c.push(...a.nodes);else for(let l=0;l<t;l++)i.has(l)||c.push(l);for(let l of c)u(l,null);for(let l=0;l<t;l++)!i.has(l)&&!c.includes(l)&&u(l,null);return r}function Sr(n){return new TextDecoder().decode(n)}var Nn=J().decoders;function Rr(n,e){Nn.set(n.toLowerCase(),e)}function Ve(n){return Nn.get(n.toLowerCase())}function kn(n){let e=ArrayBuffer.isView(n)?n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength):n,t=new DataView(e);if(e.byteLength<12)throw new Error(`Invalid GLB buffer size: ${e.byteLength} bytes`);let r=t.getUint32(0,!0);if(r!==1179937895){let m=t.getUint8(0);throw m===123||m===32||m===10||m===13?new Error("[three-live] Multi-file JSON .gltf is not supported for performance reasons. Please pack your asset into a single binary .glb file."):new Error(`Invalid GLB magic: 0x${r.toString(16)}`)}let i=t.getUint32(4,!0);if(i!==2)throw new Error(`Unsupported GLB version: ${i}`);let s=t.getUint32(8,!0),o=12,u=null,c=null;for(;o+8<=s&&o+8<=e.byteLength;){let m=t.getUint32(o,!0),v=t.getUint32(o+4,!0),b=o+8;if(b+m>e.byteLength)throw new Error(`Truncated GLB chunk: required ${b+m} bytes, buffer has ${e.byteLength}`);if(v===1313821514){let d=new Uint8Array(e,b,m),g=Sr(d);u=JSON.parse(g,(I,P)=>I==="__proto__"||I==="constructor"||I==="prototype"?void 0:P)}else v===5130562&&(c=e.slice(b,b+m));o=b+m}if(!u)throw new Error("Missing JSON chunk in GLB");let a=u.extensionsRequired||[];if(a.includes("KHR_draco_mesh_compression")&&!Ve("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");if(a.includes("EXT_meshopt_compression")&&!Ve("meshopt"))throw new Error("Model requires EXT_meshopt_compression. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).");if(a.includes("KHR_texture_basisu")&&!Ve("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let l=c||new ArrayBuffer(0),h={gltf:u,bin:l,animations:[]};for(let m of ie)m.onParseGLB?.(h);return h}function Er(n,e,t){return e%4===0?new Float32Array(n,e,t):new Float32Array(n.slice(e,e+t*4))}function Tr(n){return typeof n=="object"&&n!==null&&"gltf"in n&&typeof n.gltf=="object"&&n.gltf!==null&&"bin"in n&&(n.bin instanceof ArrayBuffer||ArrayBuffer.isView(n.bin))}function Te(n){if(Tr(n))return n;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return kn(n);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var Un=`#version 300 es
|
|
19
|
+
precision highp float;in vec2 vUV;uniform float uShadowIntensity,uShadowSoftness;out vec4 fragColor;void main(){vec2 p=(vUV-.5)*2.;float d=clamp(length(p),0.,1.);fragColor=vec4(0.,0.,0.,pow(1.-d*d,mix(1.2,2.8,uShadowSoftness))*smoothstep(1.,.85-uShadowSoftness*.6,d)*uShadowIntensity);}`,We=new WeakMap,Rn=new Float32Array(20);function Ct(n,e){let[t,r,i,s,o,c]=e;return[n[0]*t+n[4]*r+n[8]*i+n[12],n[1]*t+n[5]*r+n[9]*i+n[13],n[2]*t+n[6]*r+n[10]*i+n[14],Math.abs(n[0])*s+Math.abs(n[4])*o+Math.abs(n[8])*c,Math.abs(n[1])*s+Math.abs(n[5])*o+Math.abs(n[9])*c,Math.abs(n[2])*s+Math.abs(n[6])*o+Math.abs(n[10])*c]}function Ar(n){if(n._lb!==void 0)return n._lb;let e=1e9,t=1e9,r=1e9,i=-1e9,s=-1e9,o=-1e9;for(let c of n.primitives||[]){let a=c.positions;if(a)for(let u=0;u<a.length;u+=3)a[u]<e&&(e=a[u]),a[u+1]<t&&(t=a[u+1]),a[u+2]<r&&(r=a[u+2]),a[u]>i&&(i=a[u]),a[u+1]>s&&(s=a[u+1]),a[u+2]>o&&(o=a[u+2])}return n._lb=e<=i?[(e+i)*.5,(t+s)*.5,(r+o)*.5,(i-e)*.5,(s-t)*.5,(o-r)*.5]:null}function Mr(n){let e=We.get(n);if(e)return e;let t=(c,a)=>{let u=n.createShader(c);return n.shaderSource(u,a),n.compileShader(u),u},r=n.createProgram();n.attachShader(r,t(35633,vr)),n.attachShader(r,t(35632,wr)),n.linkProgram(r);let i=n.createVertexArray(),s=n.createBuffer(),o=n.createBuffer();return n.bindVertexArray(i),n.bindBuffer(34962,s),n.bufferData(34962,80,35048),n.enableVertexAttribArray(0),n.vertexAttribPointer(0,3,5126,!1,20,0),n.enableVertexAttribArray(1),n.vertexAttribPointer(1,2,5126,!1,20,12),n.bindBuffer(34963,o),n.bufferData(34963,new Uint16Array([0,1,2,0,2,3]),35044),n.bindVertexArray(null),e={prog:r,vao:i,vbo:s,ibo:o,uMVP:n.getUniformLocation(r,"uMVP"),uIntensity:n.getUniformLocation(r,"uShadowIntensity"),uSoftness:n.getUniformLocation(r,"uShadowSoftness")},We.set(n,e),e}var Sn={name:"contact-shadow",onContextRestored(n){We.delete(n)},onAfterRender(n,e,t){let r=e.shadowIntensity;if(r<=0||!e.bounds)return;let i=Mr(n),s=!e.xrSessionActive&&(e.backdropMeshes?.length??0)>0,o=[],c=[];for(let d of e.meshes||[]){if(!d||d.visible===!1||d.isPluginMesh||d.name==="__xr_reticle__"||d.name?.startsWith("__xr_slot_"))continue;let g=Ar(d);if(!g)continue;d.transform&&(g=Ct(d.transform,g)),e.modelRootMatrix&&(g=Ct(e.modelRootMatrix,g));let[T,P,f,M,p,S]=g,_=[T,f,M,S,P-p,P+p];/floor|table|pedestal|ground|base|plane/i.test(d.name||"")||p<.14&&Math.min(M,S)>.45?c.push(_):o.push(_)}let a=[],u=e.bounds.center||[0,0,0],l=Math.max(.05,Number(e.bounds.radius)||.5),m=e.bounds.min,h=m?[u[0],u[1],u[2],l,Math.max(.01,u[1]-m[1]),l]:[u[0],u[1],u[2],l,l,l];e.modelRootMatrix&&(h=Ct(e.modelRootMatrix,h));let b=e.xrSessionActive&&c.length===0&&String(e.container?.tagName||"").toLowerCase()==="xr-live"?(e.modelRootMatrix?e.modelRootMatrix[5]*-.25+e.modelRootMatrix[13]:-.25)+.002:h[1]-h[4]+.002;for(let[d,g,T,P,f]of o){let M=-1/0;for(let[S,_,w,A,,L]of c)f>=L-.08&&Math.abs(d-S)<=w&&Math.abs(g-_)<=A&&L+.002>M&&(M=L+.002);s&&(M=Math.max(M,d>=.04&&d<=.36&&g>=-.34&&g<=-.04&&f>=.01?.036:Math.hypot(d,g)<=.66&&f>=-.06?.003:-.477)),isFinite(M)||(M=b);let p=a.find(S=>Math.hypot(d-S[0],g-S[1])<.06&&Math.abs(M-S[5])<.05);p?(p[2]=Math.max(p[2],T*.78),p[3]=Math.max(p[3],P*.78),p[4]=Math.min(p[4],f)):a.push([d,g,T,P,f,M])}if(a.length===0){let d=Math.max(.1,h[3]*1.5)/1.45;a.push([h[0],h[2],d,d,b,b])}n.useProgram(i.prog),n.uniformMatrix4fv(i.uMVP,!1,t),n.enable(3042),(n.blendFuncSeparate||n.blendFunc).call(n,770,771,1,771),n.depthMask(!1),n.bindVertexArray(i.vao),n.bindBuffer(34962,i.vbo);for(let[d,g,T,P,f,M]of a){let p=Math.max(0,f-M),S=r/(1+p*2);if(S<.02)continue;let _=1+Math.min(.75,p*.85),w=Math.max(.045,T*1.45*_),A=Math.max(.045,P*1.45*_);Rn.set([d-w,M,g-A,0,0,d+w,M,g-A,1,0,d+w,M,g+A,1,1,d-w,M,g+A,0,1]),n.bufferSubData(34962,0,Rn),n.uniform1f(i.uIntensity,S),n.uniform1f(i.uSoftness,Math.min(1,e.shadowSoftness+Math.min(.45,p*.6))),n.drawElements(4,6,5123,0)}n.bindVertexArray(null),n.depthMask(!0),n.disable(3042)},onDestroy(n){let e=We.get(n);e&&(n.deleteVertexArray(e.vao),n.deleteBuffer(e.vbo),n.deleteBuffer(e.ibo),n.deleteProgram(e.prog),We.delete(n))}};function En(n,e,t){let r=[],i=new Map,s=[],o=[],c=[],a=new Map,u=f=>{let M=i.get(f);return M===void 0&&(M=r.length,r.push({op:f}),i.set(f,M)),M},l=f=>{let M=a.get(f);return M===void 0&&(M=c.length,c.push({id:f}),a.set(f,M)),M},m=(f,M={})=>s.push({declaration:u(f),...M})-1,h=(f,M,p)=>o.push({id:f,type:M,value:p})-1,y=f=>({node:f,socket:"value"}),b=t?.interactivity??t?.gltfExtensions?.KHR_interactivity;if(b&&typeof b=="object"){let f=Array.isArray(b.graphs)?b.graphs[b.graph??0]:b;if(f&&Array.isArray(f.nodes)){let M=Array.isArray(f.declarations)?f.declarations:[];for(let p of M)p?.op&&u(p.op);Array.isArray(f.variables)&&o.push(...f.variables);for(let p of f.events||[])p?.id&&l(p.id);for(let p of f.nodes){if(!p||typeof p!="object")continue;let S=p.op||(typeof p.declaration=="number"?M[p.declaration]?.op:"");s.push(S?{...p,declaration:u(S)}:{...p})}}}let d=(f,M,p="translation")=>p==="baseColorFactor"||p==="metallicFactor"||p==="roughnessFactor"?`/materials/${Math.max(0,M)}/pbrMetallicRoughness/${p}`:p==="emissiveFactor"||p==="alphaCutoff"?`/materials/${Math.max(0,M)}/${p}`:p==="visible"?`/nodes/${f}/extensions/KHR_node_visibility/visible`:`/nodes/${f}/${p}`,g=new Map;n.forEach((f,M)=>{typeof f?.name=="string"&&!g.has(f.name)&&g.set(f.name,M)});let T=(f,M)=>typeof f.target=="string"&&g.has(f.target)?g.get(f.target):typeof f.targetNode=="number"?f.targetNode:M,P=f=>{let M=n[f];return(typeof M?.mesh=="number"?e[M.mesh]?.primitives?.[0]?.material:0)??0};for(let f=0;f<n.length;f++){let M=n[f],p=M?.extras?.interactivity;if(!p||typeof p!="object")continue;let S=(typeof M.mesh=="number"?e[M.mesh]?.primitives?.[0]?.material:0)??0,_=A=>{let L=Array.isArray(A)?A:[A],x=[];for(let I=0;I<L.length;I++){let R=L[I];if(!R||typeof R!="object")continue;let C=R.action||"interpolate",N=typeof R.duration=="number"?R.duration:.35;if(C==="toggleTransform"){let F=R.property==="rotation"||R.property==="scale"?R.property:"translation",V=F==="rotation"?M.rotation||[0,0,0,1]:F==="scale"?M.scale||[1,1,1]:M.translation||[0,0,0],U=`/nodes/${f}/${F}`,B=h(`__toggle_${f}_${I}`,"bool",!1),D=m("variable/get",{configuration:{variable:B}}),H=m("math/not",{values:{a:y(D)}}),z=m("variable/set",{configuration:{variable:B},values:{value:y(H)}}),O=m("pointer/interpolate",{configuration:{pointer:U},values:{value:{value:Array.isArray(R.to)?R.to:V},duration:{value:N}}}),X=m("pointer/interpolate",{configuration:{pointer:U},values:{value:{value:Array.isArray(R.from)?R.from:V},duration:{value:N}}});s[z].flows={out:{node:m("flow/branch",{values:{condition:y(D)},flows:{true:{node:O},false:{node:X}}})}},x.push(z)}else if(C==="interpolate"){let F=R.to??R.value;if(F===void 0)continue;let V={value:{value:F},duration:{value:N}};R.from!==void 0&&(V.from={value:R.from}),x.push(m("pointer/interpolate",{configuration:{pointer:typeof R.pointer=="string"?R.pointer:d(T(R,f),P(T(R,f)),R.property)},values:V}))}else if(C==="setProperty"){if(R.value===void 0)continue;x.push(m("pointer/set",{configuration:{pointer:typeof R.pointer=="string"?R.pointer:d(T(R,f),P(T(R,f)),R.property)},values:{value:{value:R.value}}}))}else if(C==="toggleVisibility"){let F=T(R,f),V=h(`__vis_${F}_${I}`,"bool",!0),U=m("variable/get",{configuration:{variable:V}}),B=m("math/not",{values:{a:y(U)}}),D=m("variable/set",{configuration:{variable:V},values:{value:y(B)}});s[D].flows={out:{node:m("pointer/set",{configuration:{pointer:`/nodes/${F}/extensions/KHR_node_visibility/visible`},values:{value:y(U)}})}},x.push(D)}else if(C==="cycleMaterialColor"&&Array.isArray(R.colors)&&R.colors.length>0){let F=typeof R.duration=="number"?R.duration:.25,V=`/materials/${Math.max(0,S)}/pbrMetallicRoughness/baseColorFactor`,U=h(`__color_idx_${f}_${I}`,"int",0),B=m("variable/get",{configuration:{variable:U}}),D=m("math/add",{values:{a:y(B),b:{value:1}}}),H=m("math/rem",{values:{a:y(D),b:{value:R.colors.length}}}),z=m("variable/set",{configuration:{variable:U},values:{value:y(H)}}),O={};for(let X=0;X<R.colors.length;X++){let E=R.colors[X],k=Array.isArray(E)&&E.length>=3?[E[0],E[1],E[2],E[3]??1]:[1,1,1,1];O[String(X)]={node:F>0?m("pointer/interpolate",{configuration:{pointer:V},values:{value:{value:k},duration:{value:F}}}):m("pointer/set",{configuration:{pointer:V},values:{value:{value:k}}})}}s[z].flows={out:{node:m("flow/switch",{values:{selection:y(B)},flows:O})}},x.push(z)}else if(C==="playAnimation")x.push(m("animation/start",{configuration:{animation:R.animation??R.clip??0}}));else if(C==="stopAnimation")x.push(m("animation/stop"));else if(C==="sendEvent"){let F={};for(let[V,U]of Object.entries(R.values||{}))F[V]={value:U};x.push(m("event/send",{configuration:{event:l(String(R.event??R.id??"custom"))},values:F}))}}if(!x.length)return null;if(x.length===1)return x[0];let v={};return x.forEach((I,R)=>{v[String(R)]={node:I}}),m("flow/sequence",{flows:v})},w=(A,L,x)=>{let v=_(L);v!==null&&m(A,{...x?{configuration:x}:{},flows:{out:{node:v}}})};if(p.onSelect&&w("pointer/onSelect",p.onSelect,{nodeIndex:f}),p.onHoverIn&&w("pointer/onHoverIn",p.onHoverIn,{nodeIndex:f}),p.onHoverOut&&w("pointer/onHoverOut",p.onHoverOut,{nodeIndex:f}),p.onStart&&w("event/onStart",p.onStart),p.onReceive&&typeof p.onReceive=="object")for(let[A,L]of Object.entries(p.onReceive))w("event/receive",L,{event:l(A)})}return s.length?{graphs:[{declarations:r,nodes:s,variables:o,events:c}],graph:0}:null}var Je='SecurityError: Client-modified script compilation (Use Case 1) is disabled by default to satisfy strict CSP and Trusted Types requirements. Use script-src="..." or loadScriptFromSrc(url) for server-generated scripts (Use Case 2), or explicitly opt in via ThreeLiveElement.allowClientScripts = true (or the allow-client-scripts attribute).',Qe="Security Error: client-side scripts require allow-client-scripts opt-in.";function oe(){let n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n}function et(n,e,t,r,i){let s=1/Math.tan(e/2);n.fill(0),n[0]=s/t,n[5]=s,n[11]=-1;let o=1/(r-i);return n[10]=(i+r)*o,n[14]=2*i*r*o,n}function Fe(n,e,t,r){let[i,s,o]=e,[c,a,u]=r,[l,m,h]=t,y=i-l,b=s-m,d=o-h,g=Math.hypot(y,b,d);g<=1e-5?(y=0,b=0,d=1):(y/=g,b/=g,d/=g);let T=a*d-u*b,P=u*y-c*d,f=c*b-a*y;g=Math.hypot(T,P,f),g<=1e-5?(T=0,P=0,f=0):(T/=g,P/=g,f/=g);let M=b*f-d*P,p=d*T-y*f,S=y*P-b*T;return g=Math.hypot(M,p,S),g<=1e-5?(M=0,p=0,S=0):(M/=g,p/=g,S/=g),n[0]=T,n[1]=M,n[2]=y,n[3]=0,n[4]=P,n[5]=p,n[6]=b,n[7]=0,n[8]=f,n[9]=S,n[10]=d,n[11]=0,n[12]=-(T*i+P*s+f*o),n[13]=-(M*i+p*s+S*o),n[14]=-(y*i+b*s+d*o),n[15]=1,n}function ae(n,e,t){let r=e[0],i=e[1],s=e[2],o=e[3],c=e[4],a=e[5],u=e[6],l=e[7],m=e[8],h=e[9],y=e[10],b=e[11],d=e[12],g=e[13],T=e[14],P=e[15],f=t[0],M=t[1],p=t[2],S=t[3];return n[0]=f*r+M*c+p*m+S*d,n[1]=f*i+M*a+p*h+S*g,n[2]=f*s+M*u+p*y+S*T,n[3]=f*o+M*l+p*b+S*P,f=t[4],M=t[5],p=t[6],S=t[7],n[4]=f*r+M*c+p*m+S*d,n[5]=f*i+M*a+p*h+S*g,n[6]=f*s+M*u+p*y+S*T,n[7]=f*o+M*l+p*b+S*P,f=t[8],M=t[9],p=t[10],S=t[11],n[8]=f*r+M*c+p*m+S*d,n[9]=f*i+M*a+p*h+S*g,n[10]=f*s+M*u+p*y+S*T,n[11]=f*o+M*l+p*b+S*P,f=t[12],M=t[13],p=t[14],S=t[15],n[12]=f*r+M*c+p*m+S*d,n[13]=f*i+M*a+p*h+S*g,n[14]=f*s+M*u+p*y+S*T,n[15]=f*o+M*l+p*b+S*P,n}function _e(n,e,t,r){let i=e[0],s=e[1],o=e[2],c=e[3],a=i+i,u=s+s,l=o+o,m=i*a,h=i*u,y=i*l,b=s*u,d=s*l,g=o*l,T=c*a,P=c*u,f=c*l,M=r[0],p=r[1],S=r[2];return n[0]=(1-(b+g))*M,n[1]=(h+f)*M,n[2]=(y-P)*M,n[3]=0,n[4]=(h-f)*p,n[5]=(1-(m+g))*p,n[6]=(d+T)*p,n[7]=0,n[8]=(y+P)*S,n[9]=(d-T)*S,n[10]=(1-(m+b))*S,n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n}function ye(n,e){let t=e[0],r=e[1],i=e[2],s=e[4],o=e[5],c=e[6],a=e[8],u=e[9],l=e[10],m=l*o-c*u,h=-l*s+c*a,y=u*s-o*a,b=t*m+r*h+i*y;return b&&(b=1/b,n[0]=m*b,n[1]=h*b,n[2]=y*b,n[3]=(-l*r+i*u)*b,n[4]=(l*t-i*a)*b,n[5]=(-u*t+r*a)*b,n[6]=(c*r-i*o)*b,n[7]=(-c*t+i*s)*b,n[8]=(o*t-r*s)*b),n}function Tn(n,e){let t=e[0],r=e[1],i=e[2],s=e[3],o=e[4],c=e[5],a=e[6],u=e[7],l=e[8],m=e[9],h=e[10],y=e[11],b=e[12],d=e[13],g=e[14],T=e[15],P=t*c-r*o,f=t*a-i*o,M=t*u-s*o,p=r*a-i*c,S=r*u-s*c,_=i*u-s*a,w=l*d-m*b,A=l*g-h*b,L=l*T-y*b,x=m*g-h*d,v=m*T-y*d,I=h*T-y*g,R=P*I-f*v+M*x+p*L-S*A+_*w;return R?(R=1/R,n[0]=(c*I-a*v+u*x)*R,n[1]=(i*v-r*I-s*x)*R,n[2]=(d*_-g*S+T*p)*R,n[3]=(h*S-m*_-y*p)*R,n[4]=(a*L-o*I-u*A)*R,n[5]=(t*I-i*L+s*A)*R,n[6]=(g*M-b*_-T*f)*R,n[7]=(l*_-h*M+y*f)*R,n[8]=(o*v-c*L+u*w)*R,n[9]=(r*L-t*v-s*w)*R,n[10]=(b*S-d*M+T*P)*R,n[11]=(m*M-l*S-y*P)*R,n[12]=(c*A-o*x-a*w)*R,n[13]=(t*x-r*A+i*w)*R,n[14]=(d*f-b*p-g*P)*R,n[15]=(l*p-m*f+h*P)*R,n):null}function Dt(n,e,t,r,i){let s=i[0]*e+i[4]*t+i[8]*r+i[12],o=i[1]*e+i[5]*t+i[9]*r+i[13],c=i[2]*e+i[6]*t+i[10]*r+i[14],a=i[3]*e+i[7]*t+i[11]*r+i[15],u=a!==0?1/a:1;n[0]=s*u,n[1]=o*u,n[2]=c*u}function _n(n,e,t,r,i,s,o,c,a,u,l,m,h,y,b,d,g=0){let T=u-o,P=l-c,f=m-a,M=h-o,p=y-c,S=b-a,_=i*S-s*p,w=s*M-r*S,A=r*p-i*M,L=T*_+P*w+f*A;if(L>-1e-7&&L<1e-7)return!1;let x=1/L,v=n-o,I=e-c,R=t-a,C=x*(v*_+I*w+R*A);if(C<-g||C>1+g)return!1;let N=I*f-R*P,F=R*T-v*f,V=v*P-I*T,U=x*(r*N+i*F+s*V);if(U<-g||C+U>1+g)return!1;let B=x*(M*N+p*F+S*V);if(B>1e-4&&B<d.distance){d.distance=B,d.point=[n+r*B,e+i*B,t+s*B];let D=P*S-f*p,H=f*M-T*S,z=T*p-P*M,O=Math.hypot(D,H,z)||1;return d.normal=[D/O,H/O,z/O],!0}return!1}function tt(n,e){let t=Array.isArray(n?.nodes)?n.nodes.length:0,r=[];for(let l=0;l<t;l++)r.push(oe());if(t===0)return r;let i=new Set;for(let l of n.nodes)if(Array.isArray(l.children))for(let m of l.children)i.add(m);let s=new Set,o=128,c=(l,m,h=0)=>{if(h>o||l<0||l>=t||s.has(l))return;s.add(l);let y=n.nodes[l];if(!y)return;let b=oe();if(e&&e[l])b.set(e[l]);else if(y.matrix&&y.matrix.length===16)b.set(y.matrix);else{let g=y.translation||[0,0,0],T=y.rotation||[0,0,0,1],P=y.scale||[1,1,1];_e(b,T,g,P)}let d=r[l];if(m?ae(d,m,b):d.set(b),Array.isArray(y.children))for(let g of y.children)typeof g=="number"&&c(g,d,h+1)},a=[],u=n.scenes&&n.scenes[n.scene!==void 0?n.scene:0];if(u&&Array.isArray(u.nodes))a.push(...u.nodes);else for(let l=0;l<t;l++)i.has(l)||a.push(l);for(let l of a)c(l,null);for(let l=0;l<t;l++)!i.has(l)&&!a.includes(l)&&c(l,null);return r}var Rr={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function It(n,e,t,r){if(!t||t.bufferView===void 0)return null;let i=n.bufferViews?.[t.bufferView];if(!i)return null;let s=Number(t.count??0);if(!Number.isInteger(s)||s<=0)return null;let o=t.componentType??5126,c=Rr[o];if(!c)throw new RangeError(`glTF accessor has unsupported componentType ${o}`);let a=c*r,u=i.byteStride&&i.byteStride>0?i.byteStride:a,l=(i.byteOffset||0)+(t.byteOffset||0);if(!Number.isInteger(l)||l<0||u<a||l+(s-1)*u+a>e.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${e.byteLength} bytes)`);if(o===5126&&u===a&&l%4===0)return new Float32Array(e,l,s*r);let m=new DataView(e),h=t.normalized===!0,y=new Float32Array(s*r);for(let b=0;b<s;b++){let d=l+b*u;for(let g=0;g<r;g++){let T=d+g*c,P;switch(o){case 5126:P=m.getFloat32(T,!0);break;case 5120:P=m.getInt8(T),h&&(P=Math.max(P/127,-1));break;case 5121:P=m.getUint8(T),h&&(P/=255);break;case 5122:P=m.getInt16(T,!0),h&&(P=Math.max(P/32767,-1));break;case 5123:P=m.getUint16(T,!0),h&&(P/=65535);break;default:P=m.getUint32(T,!0),h&&(P/=4294967295)}y[b*r+g]=P}}return y}function Cn(n,e){let t=Number(e.offset?.[0]??0)||0,r=Number(e.offset?.[1]??0)||0,i=Number(e.scale?.[0]??1),s=Number(e.scale?.[1]??1),o=Number(e.rotation??0)||0,c=Math.cos(o),a=Math.sin(o),u=(Number.isFinite(i)?i:1)*c,l=(Number.isFinite(i)?i:1)*a,m=-(Number.isFinite(s)?s:1)*a,h=(Number.isFinite(s)?s:1)*c;for(let y=0;y+1<n.length;y+=2){let b=n[y],d=n[y+1];n[y]=u*b+l*d+t,n[y+1]=m*b+h*d+r}}var Pn=["neutral","reinhard","none","aces","agx"];function Ce(n){let e=String(n??"").trim().toLowerCase();return Pn.includes(e)?e:"neutral"}function Sr(n){return Pn.indexOf(Ce(n))}function Er(n){return new TextDecoder().decode(n)}var Fn=Q().decoders;function Tr(n,e){Fn.set(n.toLowerCase(),e)}function Ne(n){return Fn.get(n.toLowerCase())}function Nn(n){let e=ArrayBuffer.isView(n)?n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength):n,t=new DataView(e);if(e.byteLength<12)throw new Error(`Invalid GLB buffer size: ${e.byteLength} bytes`);let r=t.getUint32(0,!0);if(r!==1179937895){let h=t.getUint8(0);throw h===123||h===32||h===10||h===13?new Error("[three-live] Multi-file JSON .gltf is not supported for performance reasons. Please pack your asset into a single binary .glb file."):new Error(`Invalid GLB magic: 0x${r.toString(16)}`)}let i=t.getUint32(4,!0);if(i!==2)throw new Error(`Unsupported GLB version: ${i}`);let s=t.getUint32(8,!0),o=12,c=null,a=null;for(;o+8<=s&&o+8<=e.byteLength;){let h=t.getUint32(o,!0),y=t.getUint32(o+4,!0),b=o+8;if(b+h>e.byteLength)throw new Error(`Truncated GLB chunk: required ${b+h} bytes, buffer has ${e.byteLength}`);if(y===1313821514){let d=new Uint8Array(e,b,h),g=Er(d);c=JSON.parse(g,(T,P)=>T==="__proto__"||T==="constructor"||T==="prototype"?void 0:P)}else y===5130562&&(a=e.slice(b,b+h));o=b+h}if(!c)throw new Error("Missing JSON chunk in GLB");let u=c.extensionsRequired||[];if(u.includes("KHR_draco_mesh_compression")&&!Ne("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");for(let h of["EXT_meshopt_compression","KHR_meshopt_compression"])if(u.includes(h)&&!Ne("meshopt"))throw new Error(`Model requires ${h}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(u.includes("KHR_texture_basisu")&&!Ne("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let l=a||new ArrayBuffer(0),m={gltf:c,bin:l,animations:[]};for(let h of ce)h.onParseGLB?.(m);return m}function _r(n){return typeof n=="object"&&n!==null&&"gltf"in n&&typeof n.gltf=="object"&&n.gltf!==null&&"bin"in n&&(n.bin instanceof ArrayBuffer||ArrayBuffer.isView(n.bin))}function Ae(n){if(_r(n))return n;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return Nn(n);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var kn=`#version 300 es
|
|
20
20
|
layout(location=0) in vec3 aPosition;
|
|
21
21
|
layout(location=1) in vec3 aNormal;
|
|
22
22
|
layout(location=2) in vec2 aUV;
|
|
23
23
|
uniform mat4 uMVP,uModel;
|
|
24
24
|
uniform mat3 uNormalMatrix;
|
|
25
25
|
uniform vec4 uUvTransform;
|
|
26
|
+
layout(location=8) in vec4 aInst0;
|
|
27
|
+
layout(location=9) in vec4 aInst1;
|
|
28
|
+
layout(location=10) in vec4 aInst2;
|
|
29
|
+
layout(location=11) in vec4 aInst3;
|
|
30
|
+
layout(location=12) in vec4 aInstColor;
|
|
31
|
+
uniform int uInstanced;
|
|
32
|
+
uniform mat4 uViewProj;
|
|
33
|
+
out vec4 vInstTint;
|
|
34
|
+
mat4 xrModel(){return uInstanced==1?uModel*mat4(aInst0,aInst1,aInst2,aInst3):uModel;}
|
|
35
|
+
mat4 xrMVP(){return uInstanced==1?uViewProj*xrModel():uMVP;}
|
|
36
|
+
mat3 xrNormalMatrix(){return uInstanced==1?transpose(inverse(mat3(xrModel()))):uNormalMatrix;}
|
|
37
|
+
#define uModel xrModel()
|
|
38
|
+
#define uMVP xrMVP()
|
|
39
|
+
#define uNormalMatrix xrNormalMatrix()
|
|
26
40
|
out vec3 vNormal,vWorldPos;
|
|
27
41
|
out vec2 vUV;
|
|
28
42
|
void main(){
|
|
43
|
+
vInstTint=uInstanced==1?aInstColor:vec4(1.0);
|
|
29
44
|
vec3 rawN=uNormalMatrix*aNormal;
|
|
30
45
|
vNormal=length(rawN)>1e-5?normalize(rawN):vec3(0.0);
|
|
31
46
|
vec4 world=uModel*vec4(aPosition,1.0);
|
|
@@ -34,12 +49,14 @@ vec2 scaleUV=uUvTransform.zw;
|
|
|
34
49
|
if(scaleUV.x==0.0&&scaleUV.y==0.0)scaleUV=vec2(1.0);
|
|
35
50
|
vUV=aUV*scaleUV+uUvTransform.xy;
|
|
36
51
|
gl_Position=uMVP*vec4(aPosition,1.0);
|
|
37
|
-
}`,
|
|
52
|
+
}`,Cr=`#version 300 es
|
|
38
53
|
precision highp float;
|
|
39
54
|
in vec3 vNormal,vWorldPos;
|
|
40
55
|
in vec2 vUV;
|
|
41
56
|
uniform vec4 uBaseColor;
|
|
42
|
-
|
|
57
|
+
in vec4 vInstTint;
|
|
58
|
+
#define uBaseColor (uBaseColor*vInstTint)
|
|
59
|
+
uniform float uMetallic,uRoughness,uEmissive,uEnvIntensity,uExposure;
|
|
43
60
|
uniform vec2 uClearcoat;
|
|
44
61
|
uniform vec3 uCameraPos,uAmbientColor;
|
|
45
62
|
uniform sampler2D uBaseColorTexture,uMetallicRoughnessTexture,uNormalTexture,uOcclusionTexture,uEnvironmentMap;
|
|
@@ -220,19 +237,20 @@ if(uClearcoat.x>0.0){
|
|
|
220
237
|
vec3 ccF=F_SchlickRoughness(vec3(0.04),uClearcoat.y,NoV)*uClearcoat.x;
|
|
221
238
|
color=color*(vec3(1.0)-ccF)+getStudioRadiance(R,uClearcoat.y)*ccF*uEnvIntensity;
|
|
222
239
|
}
|
|
240
|
+
color*=uExposure;
|
|
223
241
|
color=applyToneMapping(color,uToneMapping);
|
|
224
242
|
float outAlpha=base.a;
|
|
225
243
|
/*XRD_O*/
|
|
226
244
|
fragColor=vec4(color,outAlpha);
|
|
227
|
-
}`;function
|
|
245
|
+
}`;function Un(n,e,t=1){e=Ce(e);let r=Number.isFinite(t)?Math.max(0,t):1,i=Math.max(0,(Number(n[0])||0)*r),s=Math.max(0,(Number(n[1])||0)*r),o=Math.max(0,(Number(n[2])||0)*r),c=T=>Math.max(0,Math.min(1,T));if(e==="none")return[c(i),c(s),c(o)];if(e==="reinhard")return[i/(i+1),s/(s+1),o/(o+1)];if(e==="aces"){let T=P=>{let f=P*.6;return c(f*(2.51*f+.03)/(f*(2.43*f+.59)+.14))};return[T(i),T(s),T(o)]}if(e==="agx"){let T=.84247906*i+.0784336*s+.07922375*o,P=.04232824*i+.87846864*s+.07916613*o,f=.04237565*i+.0784336*s+.87914297*o,M=x=>{let v=c((Math.log2(Math.max(x,1e-6))+12.47393)/16.5),I=v*v,R=I*I;return 15.5*R*I-40.14*R*v+31.96*R-6.868*I*v+.4298*I+.1191*v-.00232},p=M(T),S=M(P),_=M(f),w=1.196879*p-.09802088*S-.09902974*_,A=-.05289685*p+1.15190313*S-.09896118*_,L=-.05297164*p-.09804345*S+1.15107367*_;return[c(Math.pow(Math.max(w,0),2.2)),c(Math.pow(Math.max(A,0),2.2)),c(Math.max(0,Math.pow(Math.max(L,0),2.2)))]}let a=.76,u=.15,l=Math.min(i,s,o),m=l<.08?l-6.25*l*l:.04;i-=m,s-=m,o-=m;let h=Math.max(i,s,o);if(h<a)return[c(i),c(s),c(o)];let y=1-a,b=1-y*y/(h+y-a),d=b/h;i*=d,s*=d,o*=d;let g=1-1/(u*(h-b)+1);return[c(i+(b-i)*g),c(s+(b-s)*g),c(o+(b-o)*g)]}var Lr=`#version 300 es
|
|
228
246
|
layout(location=0) in vec3 aPosition;
|
|
229
247
|
uniform mat4 uMVP;
|
|
230
|
-
void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,
|
|
248
|
+
void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,Dr=`#version 300 es
|
|
231
249
|
precision highp float;
|
|
232
250
|
uniform vec4 uColorId;
|
|
233
251
|
out vec4 fragColor;
|
|
234
|
-
void main(){fragColor=uColorId;}`;function In(n,e,t){let r=n.createShader(e);if(n.shaderSource(r,t),n.compileShader(r),!n.getShaderParameter(r,35713)){let i=n.getShaderInfoLog(r);throw n.deleteShader(r),new Error(`Shader compile error: ${i}`)}return r}function Ot(n,e,t){let r=In(n,35633,e),i=In(n,35632,t),s=n.createProgram();if(n.attachShader(s,r),n.attachShader(s,i),n.linkProgram(s),!n.getProgramParameter(s,35714)){let o=n.getProgramInfoLog(s);throw n.deleteProgram(s),new Error(`Program link error: ${o}`)}return s}function Bt(n,e,t){let r={};for(let i of t)r[i]=n.getUniformLocation(e,i);return r}var Pn=["uMVP","uModel","uNormalMatrix","uUvTransform","uBaseColor","uMetallic","uRoughness","uClearcoat","uEmissive","uCameraPos","uBaseColorTexture","uHasTexture","uMetallicRoughnessTexture","uHasMetallicRoughnessTexture","uNormalTexture","uHasNormalTexture","uNormalScale","uOcclusionTexture","uHasOcclusionTexture","uOcclusionStrength","uToneMapping","uEnvironmentMap","uHasEnvironmentMap","uAmbientColor","uNumDirLights","uDirLightDir","uDirLightColor","uNumPointLights","uPointLightPos","uPointLightColor","uEnvIntensity","uViewportSize","uSectionPlane","uSectionEnabled"];function Bn(){let n=J().xrDepthShader;return{fs:_r.replace("/*XRD_U*/",n?.uniformsGLSL||"").replace("/*XRD_O*/",n?.occlusionGLSL||""),uniforms:n?[...Pn,...n.uniformNames]:Pn}}function Dr(n){if(typeof n!="string")return null;let e=n.trim();if(!e||/[\x00-\x1f\x7f]/.test(e))return null;let t=e.toLowerCase();return t.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(e)?e:null:t.startsWith("https://")||t.startsWith("blob:")?e:t.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(e)||/(^|[\\/])\.\.([\\/]|$)/.test(e)?null:e}function Ut(n,e,t,r,i,s,o){if(r===void 0||!e.accessors?.[r])return null;let u=e.accessors[r],c=e.bufferViews[u.bufferView],a=(c.byteOffset||0)+(u.byteOffset||0),l=c.byteStride&&c.byteStride>s*4?c.byteStride>>2:s,h;if(l===s)h=new Float32Array(t,a,u.count*s);else{h=new Float32Array(u.count*s);let v=new Float32Array(t,c.byteOffset||0,Math.floor(c.byteLength/4)),b=(u.byteOffset||0)>>2;for(let d=0;d<u.count;d++){let g=b+d*l;for(let I=0;I<s;I++)h[d*s+I]=v[g+I]}}let m=n.createBuffer();return o.push(m),n.bindBuffer(34962,m),n.bufferData(34962,h,35044),n.enableVertexAttribArray(i),n.vertexAttribPointer(i,s,5126,!1,0,0),h}var Vn=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),zn=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Fn(n,e,t=zn,r){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:i}=e,s=Ve("meshopt");s?.decodeBufferViews&&s.decodeBufferViews(i,e);let o=e.bin,u=[],c=[],a=i.extensions?.KHR_materials_variants;if(a&&Array.isArray(a.variants))for(let f of a.variants)f&&typeof f.name=="string"&&c.push(f.name);let l=ct(i),h=[];if(Array.isArray(i.nodes))for(let f=0;f<i.nodes.length;f++){let _=i.nodes[f];_.mesh!==void 0&&i.meshes&&i.meshes[_.mesh]&&h.push({node:_,nodeIdx:f,meshIdx:_.mesh})}let m=h.length>0?h:(i.meshes||[]).map((f,_)=>({node:f,nodeIdx:-1,meshIdx:_})),v=[];if(Array.isArray(e.lights)&&e.lights.length>0)v.push(...e.lights);else if(i.extensions?.KHR_lights_punctual?.lights){let f=i.extensions.KHR_lights_punctual.lights;for(let _ of f){let S=_.type==="directional"?"directional":_.type==="point"?"point":"ambient";v.push({type:S,color:_.color||[1,1,1],intensity:_.intensity!==void 0?_.intensity:1})}}if(v.length===0&&(v.push({type:"ambient",color:[1,1,1],intensity:.35}),v.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),m.length>t.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${t.maxMeshes}). Found: ${m.length}`);let b=[];if(i.textures&&i.images){if(i.textures.length>t.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${t.maxTextures}). Found: ${i.textures.length}`);for(let f=0;f<i.textures.length;f++){let _=i.textures[f],S=i.images[_.source];if(S){let R=n.createTexture();if(n.bindTexture(3553,R),n.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),n.texParameteri(3553,10242,10497),n.texParameteri(3553,10243,10497),n.texParameteri(3553,10241,9729),n.texParameteri(3553,10240,9729),S.bufferView!==void 0){let F=i.bufferViews[S.bufferView],D=o.slice(F.byteOffset||0,(F.byteOffset||0)+F.byteLength),U=new Blob([D],{type:S.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(U).then(k=>{n.bindTexture(3553,R),n.texImage2D(3553,0,6408,6408,5121,k),n.generateMipmap(3553),r?.()}).catch(()=>{})}else if(S.uri){let F=Dr(S.uri);if(F){let D=new Image;D.crossOrigin="anonymous",D.referrerPolicy="no-referrer",D.onload=()=>{n.bindTexture(3553,R),n.texImage2D(3553,0,6408,6408,5121,D),n.generateMipmap(3553),r?.()},D.src=F}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",S.uri)}b.push(R)}else b.push(null)}}let d=[1/0,1/0,1/0],g=[-1/0,-1/0,-1/0],I=0,P=0;for(let f=0;f<m.length;f++){let _=m[f],S=i.meshes[_.meshIdx],R=_.nodeIdx>=0?l[_.nodeIdx]:te(),F=new Float32Array(9);be(F,R);let D={name:_.node.name||S.name||`Mesh_${_.meshIdx}`,nodeIndex:_.nodeIdx,transform:R,normalMatrix:F,primitives:[],extras:_.node.extras||S.extras},U=_.node?.extensions?.EXT_mesh_gpu_instancing;if(U&&U.attributes&&typeof U.attributes=="object"){let k=U.attributes,X=k.TRANSLATION!==void 0?i.accessors?.[k.TRANSLATION]:null,B=k.ROTATION!==void 0?i.accessors?.[k.ROTATION]:null,L=k.SCALE!==void 0?i.accessors?.[k.SCALE]:null,O=k._COLOR_0!==void 0?i.accessors?.[k._COLOR_0]:null,V=Number(X?.count??B?.count??L?.count??0);if(!Number.isFinite(V)||V<0||V>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${V}`);if(V>0){let z=(q,K)=>{if(!q||q.bufferView===void 0||!i.bufferViews?.[q.bufferView])return null;let W=(i.bufferViews[q.bufferView].byteOffset||0)+(q.byteOffset||0);return Er(o,W,V*K)},$=z(X,3),C=z(B,4),N=z(L,3),H=O?.type==="VEC4"?4:3,G=z(O,H),Y=new Float32Array(V*16),Q=te();for(let q=0;q<V;q++){let K=$?[$[q*3],$[q*3+1],$[q*3+2]]:[0,0,0],ce=C?[C[q*4],C[q*4+1],C[q*4+2],C[q*4+3]]:[0,0,0,1],W=N?[N[q*3],N[q*3+1],N[q*3+2]]:[1,1,1];Pe(Q,ce,K,W),Y.set(Q,q*16)}if(D.instanceMatrices=Y,G){let q=new Float32Array(V*3);for(let K=0;K<V;K++)q[K*3]=G[K*H],q[K*3+1]=G[K*H+1],q[K*3+2]=G[K*H+2];D.instanceColors=q}}}for(let k of S.primitives||[]){if(k.extensions?.KHR_draco_mesh_compression){let ee=Ve("draco");ee&&ee.decodePrimitive(i,k,o)}let X=[],B=n.createVertexArray();n.bindVertexArray(B);let L=i.accessors[k.attributes.POSITION],O=Number(L?.count??0);if(!Number.isFinite(O)||O<0||I+O>t.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${t.maxVertices}).`);if(I+=O,L?.min&&L?.max){let ee=me=>{for(let de=0;de<3;de++){let we=me[12+de],Ke=me[12+de];for(let Oe=0;Oe<3;Oe++){let et=me[Oe*4+de]*L.min[Oe],tt=me[Oe*4+de]*L.max[Oe];we+=et<tt?et:tt,Ke+=et>tt?et:tt}we<d[de]&&(d[de]=we),Ke>g[de]&&(g[de]=Ke)}};if(D.instanceMatrices&&D.instanceMatrices.length>=16){let me=D.instanceMatrices.length>>4,de=te();for(let we=0;we<me;we++){let Ke=D.instanceMatrices.subarray(we*16,we*16+16);re(de,R,Ke),ee(de)}}else ee(R)}let V=Ut(n,i,o,k.attributes.POSITION,0,3,X);Ut(n,i,o,k.attributes.NORMAL,1,3,X),Ut(n,i,o,k.attributes.TEXCOORD_0,2,2,X);let z=0,$=5123,C=null;if(k.indices!==void 0){let ee=i.accessors[k.indices],de=(i.bufferViews[ee.bufferView].byteOffset||0)+(ee.byteOffset||0);if(z=Number(ee.count??0),!Number.isFinite(z)||z<0||P+z>t.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${t.maxIndices}).`);P+=z,$=ee.componentType===5125?5125||5125:5123||5123;let we=n.createBuffer();X.push(we),n.bindBuffer(34963,we),ee.componentType===5125?(C=new Uint32Array(o,de,ee.count),n.bufferData(34963,C,35044)):(C=new Uint16Array(o,de,ee.count),n.bufferData(34963,C,35044))}else z=L.count;let N={};for(let ee of ie)if(ee.onBuildPrimitiveVAO){let me=ee.onBuildPrimitiveVAO(n,B,k,i,o);me&&(N[ee.name]=me)}n.bindVertexArray(null);let H=i.materials&&k.material!==void 0?i.materials[k.material]:null,G=Bn(),Y=Un,Q=G.fs,q=!1;for(let ee of ie)if(ee.onResolveShader){let me=ee.onResolveShader(k,H,Y,Q);me&&(Y=me.vs,Q=me.fs,q=!0)}let K=q?Ot(n,Y,Q):null,ce=K?Bt(n,K,G.uniforms):null,W=H?.pbrMetallicRoughness,ue=W?.baseColorFactor||[.8,.8,.8,1],oe=W?.metallicFactor??.1,ye=W?.roughnessFactor??.5,ge=H?.extensions?.KHR_materials_clearcoat,ae=ge?ge.clearcoatFactor??1:0,ne=Math.max(.04,ge?.clearcoatRoughnessFactor??.04),xe=W?.baseColorTexture!==void 0&&b[W.baseColorTexture.index]?b[W.baseColorTexture.index]:null,pe=W?.metallicRoughnessTexture!==void 0&&b[W.metallicRoughnessTexture.index]?b[W.metallicRoughnessTexture.index]:null,ve=H?.normalTexture!==void 0&&b[H.normalTexture.index]?b[H.normalTexture.index]:null,Se=H?.normalTexture?.scale??1,Ie=H?.occlusionTexture!==void 0&&b[H.occlusionTexture.index]?b[H.occlusionTexture.index]:null,je=H?.occlusionTexture?.strength??1,mr=!!(H?.extensions?.KHR_materials_transmission||N.materials?.isTransmissive),Rn=k.extensions?.KHR_materials_variants?.mappings,dr=Array.isArray(Rn)?Rn.filter(ee=>ee&&typeof ee.material=="number"&&Array.isArray(ee.variants)).map(ee=>({material:ee.material|0,variants:ee.variants.map(me=>Number(me)|0)})):void 0;D.primitives.push({vao:B,indexCount:z,indexType:$,baseColor:ue,metallic:oe,roughness:ye,clearcoat:ae,clearcoatRoughness:ne,positions:V,indices:C,texture:xe,metallicRoughnessTexture:pe,normalTexture:ve,occlusionTexture:Ie,normalScale:Se,occlusionStrength:je,buffers:X,materialIndex:k.material,defaultMaterialIndex:k.material,variantMappings:dr,pluginData:N,customProgram:K,customUniforms:ce,isTransmissive:mr})}u.push(D)}isFinite(d[0])||(d=[-1,-1,-1]),isFinite(g[0])||(g=[1,1,1]);let p=[(d[0]+g[0])/2,(d[1]+g[1])/2,(d[2]+g[2])/2],M=g[0]-d[0],x=g[1]-d[1],w=g[2]-d[2],T=Math.max(Math.hypot(M,x,w)/2,.5),A=[d[0],d[1],d[2]],y=[g[0],g[1],g[2]],E=e.animations;if(!E){for(let f of ie)if(f.onParseGLB?.(e),e.animations){E=e.animations;break}}return E||(E=[]),{meshes:u,bounds:{center:p,radius:T,min:A,max:y},lights:v,animations:E,worldMatrices:l,gpuTextures:b,availableVariants:c}}var he=class{constructor(e,t,r){this.meshes=[];this.backdropMeshes=[];this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]};this.lights=[];this.modelRootMatrix=te();this.clearColor=[0,0,0,0];this.envIntensity=1;this.shadowIntensity=0;this.shadowSoftness=.5;this.toneMapping="neutral";this.environmentTexture=null;this.animations=[];this.currentClip=null;this.animationTime=0;this.isPlayingAnimation=!1;this.autoplay=!1;this.animationName="";this.gpuTextures=[];this.availableVariants=[];this.activeVariantName=null;this.gltf=null;this.worldMatrices=[];this.initialNodeTransforms=[];this.projMatrix=te();this.viewMatrix=te();this.modelMatrix=te();this.mvpMatrix=te();this.normalMatrix=new Float32Array(9);this.initialTheta=.6;this.initialPhi=.35;this.initialDistance=null;this.customDistance=!1;this.distanceMode="auto";this.initialCustomTarget=null;this.customTarget=null;this.fov=Math.PI/4;this.minTheta=-1/0;this.maxTheta=1/0;this.minPhi=-Math.PI*.48;this.maxPhi=Math.PI*.48;this.minDistanceLimit=null;this.maxDistanceLimit=null;this.activePointers=new Map;this.isPanning=!1;this.targetTheta=.6;this.currTheta=.6;this.targetPhi=.35;this.currPhi=.35;this.targetDistance=3;this.currDistance=3;this.autoRotate=!1;this.autoRotateSpeed=Math.PI/6;this.autoRotateDelay=3e3;this.lastInteractionTime=-1/0;this.turntableRotation=0;this.isPointerDown=!1;this.interactive=!0;this.skyboxTexture=null;this.lastPointerX=0;this.lastPointerY=0;this.totalDragDist=0;this.selectedMeshName="";this.pickFbo=null;this.pickTexture=null;this.pickDepth=null;this.pickFboWidth=0;this.pickFboHeight=0;this.animFrameId=null;this.isVisible=!0;this.xrSessionActive=!1;this.lastTime=0;this.lastReportedTheta=-999;this.lastReportedPhi=-999;this.lastReportedZoom=-999;this.boundPointerDown=null;this.boundPointerMove=null;this.boundPointerUp=null;this.boundWheel=null;this.boundKeyDown=null;this.boundContextMenu=null;this.boundSetCamera=null;this.boundResetCamera=null;this.stereoSBS=!1;this.renderErrorReported=!1;this.xrDepthState={enabled:!1,texture:null,uvTransform:te(),rawValueToMeters:.001,format:0};this.container=e;let i,s;if(t&&typeof t.getContext=="function"?(i=t,s=r):(s=t,i=s?.canvas),!i){let a=e.querySelector("canvas");a||(a=document.createElement("canvas"),a.style.width="100%",a.style.height="100%",a.style.display="block",a.style.touchAction="none",e.prepend(a)),i=a}this.canvas=i,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let o=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!o:o&&(this.autoRotate=!1),this.opts.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=this.opts.autoRotateSpeed),this.opts.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(this.opts.autoRotateDelay)||0)),this.opts.exposure!==void 0&&(this.envIntensity=Math.max(0,Number(this.opts.exposure))),this.opts.camera&&this.setInitialCamera(this.opts.camera.theta,this.opts.camera.phi,this.opts.camera.distance,this.opts.camera.zoom),this.opts.shadowIntensity!==void 0&&(this.shadowIntensity=Math.max(0,Math.min(1,Number(this.opts.shadowIntensity)||0))),this.opts.shadowSoftness!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(this.opts.shadowSoftness)||0))),this.opts.toneMapping!==void 0&&(this.toneMapping=this.opts.toneMapping),this.opts.autoplay!==void 0&&(this.autoplay=this.opts.autoplay),this.opts.animationName!==void 0&&(this.animationName=this.opts.animationName),this.opts.variantName!==void 0&&(this.activeVariantName=this.opts.variantName||null),this.opts.fieldOfView!==void 0&&(this.fov=this.opts.fieldOfView*Math.PI/180),this.opts.distanceMode!==void 0&&(this.distanceMode=this.opts.distanceMode),this.opts.cameraTarget!==void 0&&(this.setTarget(this.opts.cameraTarget[0],this.opts.cameraTarget[1],this.opts.cameraTarget[2]),this.initialCustomTarget=[...this.opts.cameraTarget]),(this.opts.minCameraOrbit||this.opts.maxCameraOrbit)&&this.setOrbitLimits({minTheta:this.opts.minCameraOrbit?.theta,maxTheta:this.opts.maxCameraOrbit?.theta,minPhi:this.opts.minCameraOrbit?.phi,maxPhi:this.opts.maxCameraOrbit?.phi,minDistance:this.opts.minCameraOrbit?.distance,maxDistance:this.opts.maxCameraOrbit?.distance});let u=i.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!u)throw new Error("WebGL2 not supported");this.gl=u;let c=Bn();this.renderProg=Ot(u,Un,c.fs),this.pickProg=Ot(u,Cr,Lr),this.uRender=Bt(u,this.renderProg,c.uniforms),this.uPick=Bt(u,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo(),this.setupEvents(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(e,t){Rr(e,t)}static getDecoder(e){return Ve(e)}setupPickingFbo(){let e=this.gl;if(typeof e.createFramebuffer!="function")return;this.pickFbo=e.createFramebuffer(),this.pickTexture=e.createTexture(),this.pickDepth=e.createRenderbuffer();let t=Math.max(1,this.canvas.width),r=Math.max(1,this.canvas.height);this.pickFboWidth=t,this.pickFboHeight=r,e.bindTexture(3553,this.pickTexture),e.texImage2D(3553,0,6408,t,r,0,6408,5121,null),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728),e.bindRenderbuffer(36161,this.pickDepth),e.renderbufferStorage(36161,33189,t,r),e.bindFramebuffer(36160,this.pickFbo),e.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),e.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),e.bindFramebuffer(36160,null)}resizePickingFbo(e,t){if(!this.pickFbo)return;let r=this.gl,i=Math.max(1,e),s=Math.max(1,t);this.pickFboWidth=i,this.pickFboHeight=s,r.bindTexture(3553,this.pickTexture),r.texImage2D(3553,0,6408,i,s,0,6408,5121,null),r.bindRenderbuffer(36161,this.pickDepth),r.renderbufferStorage(36161,33189,i,s)}loadGLBData(e,t){let{meshes:r,bounds:i,lights:s,animations:o,worldMatrices:u,gpuTextures:c,availableVariants:a}=Fn(this.gl,e,t,()=>this.render());if(this.disposeMeshGpuResources(),this.meshes=r,this.bounds=i,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=s,this.animations=o||[],this.worldMatrices=u||[],this.gpuTextures=c||[],this.availableVariants=a||[],this.gltf=e.gltf,this.activeVariantName&&this.applyVariantMaterial(this.activeVariantName),this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let h of e.gltf.nodes)this.initialNodeTransforms.push({t:h.translation?[h.translation[0],h.translation[1],h.translation[2]]:[0,0,0],r:h.rotation?[h.rotation[0],h.rotation[1],h.rotation[2],h.rotation[3]]:[0,0,0,1],s:h.scale?[h.scale[0],h.scale[1],h.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let h of ie)h.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:i.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let l=e.exposure??e.environmentIntensity??e.gltf?.extras?.exposure??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.exposure??e.gltf?.asset?.extras?.environmentIntensity;l!==void 0&&(this.envIntensity=Math.max(0,Number(l))),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(e){this.loadGLBData(kn(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(Te(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=Te(e),{meshes:i}=Fn(this.gl,r,zn,()=>this.render());if(t)for(let s of i)s.transform[12]+=t[0],s.transform[13]+=t[1],s.transform[14]+=t[2],be(s.normalMatrix,s.transform);this.backdropMeshes=i,this.update(0),this.render()}setClearColor(e,t,r,i=1){this.clearColor=[e,t,r,i]}updateMeshTransforms(e){for(let t=0;t<this.meshes.length;t++){let r=this.meshes[t],i;e instanceof Map?i=e.get(r.name)??e.get(t):Array.isArray(e)?i=e[t]:e&&typeof e=="object"&&(Object.prototype.hasOwnProperty.call(e,r.name)?i=e[r.name]:Object.prototype.hasOwnProperty.call(e,t)&&(i=e[t])),i&&i.length===16&&(r.transform.set(i),be(r.normalMatrix,r.transform))}}bindLights(e=this.uRender){let t=this.gl,r=[.28,.28,.28],i=[],s=[],o=[],u=[];for(let c of this.lights){let a=c.color||[1,1,1],l=c.intensity!==void 0?c.intensity:1;if(c.type==="ambient")r=[a[0]*l,a[1]*l,a[2]*l];else if(c.type==="directional"&&i.length<6){let h=c.direction||[.5,1,.8];i.push(h[0],h[1],h[2]),s.push(a[0]*l,a[1]*l,a[2]*l)}else if(c.type==="point"&&o.length<6){let h=c.position||[0,0,0];o.push(h[0],h[1],h[2]),u.push(a[0]*l,a[1]*l,a[2]*l)}}i.length===0&&(i.push(.5,1,.8),s.push(1,1,1)),t.uniform3fv(e.uAmbientColor,r),t.uniform1i(e.uNumDirLights,i.length/3),i.length>0&&(t.uniform3fv(e.uDirLightDir,i),t.uniform3fv(e.uDirLightColor,s)),t.uniform1i(e.uNumPointLights,o.length/3),o.length>0&&(t.uniform3fv(e.uPointLightPos,o),t.uniform3fv(e.uPointLightColor,u)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.envIntensity=Math.max(0,Number(e))}getExposure(){return this.envIntensity}setShadow(e,t){this.shadowIntensity=Math.max(0,Math.min(1,Number(e)||0)),t!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(t)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(e){this.toneMapping=e}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of ie)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of ie)if(t.setSkyboxImage){await t.setSkyboxImage(this,e);return}}setInteractive(e){this.interactive=e}isInteractive(){return this.interactive}getCameraOrbit(){let e=this.currTheta,t=this.currPhi,r=this.currDistance;return{theta:e,phi:t,radius:r,toString(){return`${e.toFixed(4)}rad ${t.toFixed(4)}rad ${r.toFixed(4)}m`}}}getCameraTarget(){let e=this.customTarget||this.bounds.center;return{x:e[0],y:e[1],z:e[2],toString(){return`${e[0].toFixed(4)}m ${e[1].toFixed(4)}m ${e[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let e=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return e.map((t,r)=>{let i=this.meshes.flatMap(l=>l.primitives.filter(h=>h.materialIndex===r||e.length===1&&h.materialIndex===void 0)),s=i[0],o=s?[...s.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],u=s?s.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,c=s?s.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,a={baseColorFactor:o,metallicFactor:u,roughnessFactor:c,setBaseColorFactor:l=>{let h=[l[0],l[1],l[2],l[3]??1];a.baseColorFactor=h,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=h);for(let m of i)m.baseColor=h;this.render()},setMetallicFactor:l=>{a.metallicFactor=l,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=l);for(let h of i)h.metallic=l;this.render()},setRoughnessFactor:l=>{a.roughnessFactor=l,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=l);for(let h of i)h.roughness=l;this.render()}};return{name:t.name||`Material_${r}`,pbrMetallicRoughness:a}})}playAnimation(e){if(this.animations.length!==0){if(e){let t=this.animations.find(r=>r.name===e);t&&(this.currentClip=t)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(e=>e.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(e){let t=this.applyVariantMaterial(e);return t&&this.gl&&this.render(),t}applyVariantMaterial(e){let t=e===null||e===""||e==="default",r=-1;if(t)this.activeVariantName=null;else{if(r=this.availableVariants.indexOf(e),r<0)return!1;this.activeVariantName=e}let i=this.gltf?.materials;if(!Array.isArray(i))return t;for(let s of this.meshes)for(let o of s.primitives){let u=o.defaultMaterialIndex;if(!t&&Array.isArray(o.variantMappings)){for(let h of o.variantMappings)if(Array.isArray(h.variants)&&h.variants.includes(r)){u=h.material;break}}if(u===void 0||!i[u]){o.materialIndex=void 0,o.baseColor=[.8,.8,.8,1],o.metallic=.1,o.roughness=.5,o.clearcoat=0,o.clearcoatRoughness=.04,o.texture=null,o.metallicRoughnessTexture=null,o.normalTexture=null,o.normalScale=1,o.occlusionTexture=null,o.occlusionStrength=1,o.isTransmissive=!1;continue}let c=i[u];o.materialIndex=u;let a=c.pbrMetallicRoughness;o.baseColor=a?.baseColorFactor?[a.baseColorFactor[0],a.baseColorFactor[1],a.baseColorFactor[2],a.baseColorFactor[3]??1]:[.8,.8,.8,1],o.metallic=a?.metallicFactor??.1,o.roughness=a?.roughnessFactor??.5;let l=c.extensions?.KHR_materials_clearcoat;o.clearcoat=l?l.clearcoatFactor??1:0,o.clearcoatRoughness=Math.max(.04,l?.clearcoatRoughnessFactor??.04),o.texture=a?.baseColorTexture!==void 0&&this.gpuTextures[a.baseColorTexture.index]?this.gpuTextures[a.baseColorTexture.index]:null,o.metallicRoughnessTexture=a?.metallicRoughnessTexture!==void 0&&this.gpuTextures[a.metallicRoughnessTexture.index]?this.gpuTextures[a.metallicRoughnessTexture.index]:null,o.normalTexture=c.normalTexture!==void 0&&this.gpuTextures[c.normalTexture.index]?this.gpuTextures[c.normalTexture.index]:null,o.normalScale=c.normalTexture?.scale??1,o.occlusionTexture=c.occlusionTexture!==void 0&&this.gpuTextures[c.occlusionTexture.index]?this.gpuTextures[c.occlusionTexture.index]:null,o.occlusionStrength=c.occlusionTexture?.strength??1,o.isTransmissive=!!(c.extensions?.KHR_materials_transmission||o.pluginData?.materials?.isTransmissive)}return!0}setAutoplay(e){this.autoplay=e,e?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(e){this.animationName=e,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(e)}evaluateAnimation(e){for(let t of ie)if(t.evaluateAnimation){t.evaluateAnimation(this,e);return}}setTarget(e,t,r){this.customTarget=[e,t,r],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(e){let t=Math.max(10,Math.min(90,e));this.fov=t*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(e){if(this.distanceMode=e,!this.customDistance){let t=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=t,this.targetDistance=t,this.currDistance=t,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(e){e.minTheta!==void 0&&(this.minTheta=e.minTheta*Math.PI/180),e.maxTheta!==void 0&&(this.maxTheta=e.maxTheta*Math.PI/180),e.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,e.minPhi*Math.PI/180)),e.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,e.maxPhi*Math.PI/180)),e.minDistance!==void 0&&(this.minDistanceLimit=e.minDistance),e.maxDistance!==void 0&&(this.maxDistanceLimit=e.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){return{minTheta:isFinite(this.minTheta)?this.minTheta*180/Math.PI:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*180/Math.PI:void 0,minPhi:this.minPhi*180/Math.PI,maxPhi:this.maxPhi*180/Math.PI,minDistance:this.minDistanceLimit!==null?this.minDistanceLimit:void 0,maxDistance:this.maxDistanceLimit!==null?this.maxDistanceLimit:void 0}}clampTheta(e){return Math.max(this.minTheta,Math.min(this.maxTheta,e))}clampPhi(e){return Math.max(this.minPhi,Math.min(this.maxPhi,e))}clampDistance(e){let t=this.minDistanceLimit!==null?this.minDistanceLimit:this.bounds?this.bounds.radius*.5:.1,r=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(t,Math.min(r,e))}setCamera(e,t,r,i){e!==void 0&&(this.targetTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.targetPhi=this.clampPhi(t*Math.PI/180)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(r)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/i))}setInitialCamera(e,t,r,i){if(e!==void 0&&(this.initialTheta=this.clampTheta(e*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),t!==void 0&&(this.initialPhi=this.clampPhi(t*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),r!==void 0&&r>0){let s=this.clampDistance(r);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else if(i!==void 0&&i>0){let s=this.clampDistance(this.bounds.radius*2.5/i);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else{this.customDistance=!1;let s=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=s,this.targetDistance=s,this.currDistance=s}this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.initialDistance!==null?this.targetDistance=this.clampDistance(this.initialDistance):this.targetDistance=this.clampDistance(this.bounds.radius*2.5),this.initialCustomTarget?this.customTarget=[...this.initialCustomTarget]:this.customTarget=null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(e,t){let r=te();re(r,this.projMatrix,this.viewMatrix);let[i,s,o]=e,u=t?t[0]:0,c=t?t[1]:0,a=t?t[2]:0,l=this.modelRootMatrix;l&&(i=l[0]*e[0]+l[4]*e[1]+l[8]*e[2]+l[12],s=l[1]*e[0]+l[5]*e[1]+l[9]*e[2]+l[13],o=l[2]*e[0]+l[6]*e[1]+l[10]*e[2]+l[14],t&&(u=l[0]*t[0]+l[4]*t[1]+l[8]*t[2],c=l[1]*t[0]+l[5]*t[1]+l[9]*t[2],a=l[2]*t[0]+l[6]*t[1]+l[10]*t[2]));let h=r[0]*i+r[4]*s+r[8]*o+r[12],m=r[1]*i+r[5]*s+r[9]*o+r[13],v=r[2]*i+r[6]*s+r[10]*o+r[14],b=r[3]*i+r[7]*s+r[11]*o+r[15];if(b<=1e-4)return{x:0,y:0,z:1,visible:!1};let d=h/b,g=m/b,I=v/b,P=this.canvas.getBoundingClientRect(),p=P.width||this.canvas.clientWidth||this.canvas.width||300,M=P.height||this.canvas.clientHeight||this.canvas.height||150,x=(d*.5+.5)*p,w=(-g*.5+.5)*M,T=d>=-1.1&&d<=1.1&&g>=-1.1&&g<=1.1&&I>=-1&&I<=1;if(T&&t){let A=this.customTarget||this.bounds.center,y=A[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),E=A[1]+this.currDistance*Math.sin(this.currPhi),f=A[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),_=[i-y,s-E,o-f];u*_[0]+c*_[1]+a*_[2]>.05&&(T=!1)}return{x,y:w,z:I,visible:T}}setSelectedMesh(e){this.selectedMeshName=e||""}getSelectedMesh(){return this.selectedMeshName}setupEvents(){let e=this.canvas;this.boundContextMenu=t=>{t.preventDefault()},e.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=t=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.lastPointerX=t.clientX,this.lastPointerY=t.clientY,this.totalDragDist=0,this.activePointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.isPanning=t.button===2||t.shiftKey||this.activePointers.size===2,e.setPointerCapture(t.pointerId))},e.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=t=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=this.activePointers.get(t.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},i=t.clientX-r.x,s=t.clientY-r.y;if(this.activePointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.lastPointerX=t.clientX,this.lastPointerY=t.clientY,this.totalDragDist+=Math.hypot(i,s),this.isPanning||t.button===2||t.shiftKey||this.activePointers.size===2){let o=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],u=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],c=this.customTarget?[...this.customTarget]:[...this.bounds.center],a=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;c[0]+=(-i*o[0]+s*u[0])*a,c[1]+=(-i*o[1]+s*u[1])*a,c[2]+=(-i*o[2]+s*u[2])*a,this.customTarget=c}else this.targetTheta=this.clampTheta(this.targetTheta-i*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=t=>{this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.activePointers.delete(t.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(t.pointerId)}catch{}if(this.totalDragDist<5&&t.button===0){let r=e.getBoundingClientRect(),i=Math.floor((t.clientX-r.left)*(e.width/Math.max(r.width,1))),s=Math.floor((t.clientY-r.top)*(e.height/Math.max(r.height,1)));this.performMeshPick(i,s,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=t=>{if(!this.interactive)return;t.preventDefault(),this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=Math.exp(t.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=t=>{let r=t.detail||{};r.reset?this.resetCamera():this.setCamera(r.theta,r.phi,r.distance,r.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),e.tabIndex!==void 0&&e.tabIndex<0&&(e.tabIndex=0),e.getAttribute?.("role")||e.setAttribute?.("role","region"),e.getAttribute?.("aria-label")||e.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=t=>{if(!this.interactive)return;let r=typeof performance<"u"?performance.now():Date.now();switch(t.key){case"ArrowLeft":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta-.1),t.preventDefault();break;case"ArrowRight":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta+.1),t.preventDefault();break;case"ArrowUp":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi+.08),t.preventDefault();break;case"ArrowDown":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi-.08),t.preventDefault();break;case"+":case"=":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*.9),t.preventDefault();break}case"-":case"_":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*1.1),t.preventDefault();break}case"Home":this.lastInteractionTime=r,this.resetCamera(),t.preventDefault();break}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=this.canvas;this.boundContextMenu&&(e.removeEventListener("contextmenu",this.boundContextMenu),this.boundContextMenu=null),this.boundPointerDown&&(e.removeEventListener("pointerdown",this.boundPointerDown),this.boundPointerDown=null),this.boundPointerMove&&(e.removeEventListener("pointermove",this.boundPointerMove),this.boundPointerMove=null),this.boundPointerUp&&(e.removeEventListener("pointerup",this.boundPointerUp),this.boundPointerUp=null),this.boundWheel&&(e.removeEventListener("wheel",this.boundWheel),this.boundWheel=null),this.boundKeyDown&&(e.removeEventListener("keydown",this.boundKeyDown),this.boundKeyDown=null),this.boundSetCamera&&(this.container.removeEventListener("setCamera",this.boundSetCamera),this.boundSetCamera=null),this.boundResetCamera&&(this.container.removeEventListener("resetCamera",this.boundResetCamera),this.boundResetCamera=null)}raycastFromScreenPoint(e,t){let r=this.canvas,i=r.getBoundingClientRect(),s=r.width||300,o=r.height||300,u=i.width>0?Math.floor((e-i.left)*(s/i.width)):Math.floor(e),c=i.height>0?Math.floor((t-i.top)*(o/i.height)):Math.floor(t);return this.performMeshPick(u,c,!1)}performMeshPick(e,t,r=!0){if(this.meshes.length===0)return null;let i=this.gl,s=Math.max(1,this.canvas.width||300),o=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,s);let u=te();re(u,this.projMatrix,this.viewMatrix);let c=[],a=Math.max(0,Math.min(s-1,e)),l=Math.max(0,Math.min(o-1,o-1-t));if(this.pickFbo&&i&&!this.xrSessionActive){(this.pickFboWidth!==s||this.pickFboHeight!==o)&&this.resizePickingFbo(s,o),i.bindFramebuffer(36160,this.pickFbo),i.viewport(0,0,s,o),i.enable(2929),i.clearColor(0,0,0,0),i.clear(16384|256),i.useProgram(this.pickProg);for(let A=0;A<this.meshes.length;A++){let y=this.meshes[A];if(y.visible===!1||y.isPluginMesh)continue;let E=A+1,f=(E&255)/255,_=(E>>8&255)/255,S=(E>>16&255)/255;i.uniform4f(this.uPick.uColorId,f,_,S,1),re(this.modelMatrix,this.modelRootMatrix,y.transform);let R=y.instanceMatrices;if(R&&R.length>=16){let F=R.length>>4,D=te();for(let U of y.primitives){i.bindVertexArray(U.vao);for(let k=0;k<F;k++)re(D,this.modelMatrix,R.subarray(k*16,k*16+16)),re(this.mvpMatrix,u,D),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),U.indices?i.drawElements(4,U.indexCount,U.indexType,0):i.drawArrays(4,0,U.indexCount)}}else{re(this.mvpMatrix,u,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let F of y.primitives)i.bindVertexArray(F.vao),F.indices?i.drawElements(4,F.indexCount,F.indexType,0):i.drawArrays(4,0,F.indexCount)}}let w=new Uint8Array(4);i.readPixels(a,l,1,1,6408,5121,w),i.bindFramebuffer(36160,null);let T=w[0]+(w[1]<<8)+(w[2]<<16);T>0&&T<=this.meshes.length&&(c=[this.meshes[T-1]])}c.length===0&&(c=this.meshes.filter(w=>w.visible!==!1));let h=null,m=1/0,v=[0,0,0],b=[0,1,0],d=this.customTarget||this.bounds.center,g=d[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),I=d[1]+this.currDistance*Math.sin(this.currPhi),P=d[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),p=te();for(let w of c){re(p,this.modelRootMatrix,w.transform);let T=w.instanceMatrices,A=T&&T.length>=16?T.length>>4:1;for(let y=0;y<A;y++){T&&T.length>=16?re(this.modelMatrix,p,T.subarray(y*16,y*16+16)):this.modelMatrix.set(p),re(this.mvpMatrix,u,this.modelMatrix);let E=te();if(!Ln(E,this.mvpMatrix))continue;let f=(a+.5)/s*2-1,_=(l+.5)/o*2-1,S=[0,0,0],R=[0,0,0];kt(S,f,_,-1,E),kt(R,f,_,1,E);let F=R[0]-S[0],D=R[1]-S[1],U=R[2]-S[2],k=Math.hypot(F,D,U)||1,X=F/k,B=D/k,L=U/k,O={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((z=>{for(let $ of w.primitives){if(!$.positions)continue;let C=$.positions,N=$.indices,H=Math.floor(N?N.length/3:C.length/9);for(let G=0;G<H;G++){let Y=N?N[G*3]:G*3,Q=N?N[G*3+1]:G*3+1,q=N?N[G*3+2]:G*3+2;Dn(S[0],S[1],S[2],X,B,L,C[Y*3],C[Y*3+1],C[Y*3+2],C[Q*3],C[Q*3+1],C[Q*3+2],C[q*3],C[q*3+1],C[q*3+2],O,z)}}})(1e-4),isFinite(O.distance)){let z=O.point[0],$=O.point[1],C=O.point[2],N=this.modelMatrix,H=N[0]*z+N[4]*$+N[8]*C+N[12],G=N[1]*z+N[5]*$+N[9]*C+N[13],Y=N[2]*z+N[6]*$+N[10]*C+N[14],Q=H-g,q=G-I,K=Y-P,ce=Math.hypot(Q,q,K);if(ce<m){be(this.normalMatrix,this.modelMatrix);let W=this.normalMatrix,ue=O.normal[0],oe=O.normal[1],ye=O.normal[2],ge=W[0]*ue+W[3]*oe+W[6]*ye,ae=W[1]*ue+W[4]*oe+W[7]*ye,ne=W[2]*ue+W[5]*oe+W[8]*ye,xe=Math.hypot(ge,ae,ne)||1;ge/=xe,ae/=xe,ne/=xe,ge*Q+ae*q+ne*K>0&&(ge=-ge,ae=-ae,ne=-ne),h=w,m=Math.round(ce*1e3)/1e3,v=[Math.round(H*1e3)/1e3,Math.round(G*1e3)/1e3,Math.round(Y*1e3)/1e3],b=[Math.round(ge*1e3)/1e3,Math.round(ae*1e3)/1e3,Math.round(ne*1e3)/1e3]}}}}if(!h)return null;let x={meshIndex:this.meshes.indexOf(h),meshName:h.name,nodeIndex:h.nodeIndex,distance:m,hitPoint:v,normal:b,screenX:e,screenY:t};if(r){for(let w of ie)w.onMeshSelect?.(this,x);this.opts.onMeshClick&&this.opts.onMeshClick(x),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:x}))}return x}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let r=Math.max(1,Math.floor(t*.5)),i=e>=r,s=i?e-r:e,o=i?Math.max(1,t-r):r,u=(s+.5)/o*2-1;return Math.floor((u*.5+1)*.5*t)}setStereoSBS(e){this.stereoSBS=!!e,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let e=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),t=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);at(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center,i=r[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),s=r[1]+this.currDistance*Math.sin(this.currPhi),o=r[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);Be(this.viewMatrix,[i,s,o],r,[0,1,0]),re(this.mvpMatrix,this.projMatrix,this.viewMatrix),be(this.normalMatrix,this.modelMatrix)}resize(){let e=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),t=this.canvas.getBoundingClientRect(),r=Math.max(1,Math.floor(t.width*e)),i=Math.max(1,Math.floor(t.height*e));this.canvas.width!==r||this.canvas.height!==i?(this.canvas.width=r,this.canvas.height=i,this.resizePickingFbo(r,i),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(e){let t=this.xrSessionActive;if(this.xrSessionActive=e,t&&!e){this.xrDepthState.enabled=!1;for(let r of ie)r.onXRSessionEnd?.(this);if(this.lastTime=typeof performance<"u"?performance.now():Date.now(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(r){this.reportRenderError(r)}}}reportRenderError(e){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",e))}stepXRUpdate(e){for(let t of ie)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let e=t=>{if(this.animFrameId===null)return;let r=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(r),this.render()}catch(i){this.reportRenderError(i)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(e))};this.animFrameId=requestAnimationFrame(e)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(e){this.autoRotate=e}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(e){this.autoRotateSpeed=e}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(e){this.autoRotateDelay=Math.max(0,Number(e)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(e=0){this.turntableRotation=Number(e)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let e=Math.cos(this.turntableRotation),t=Math.sin(this.turntableRotation),r=this.bounds.center[0],i=this.bounds.center[2],s=this.modelRootMatrix;s[0]=e,s[1]=0,s[2]=-t,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=t,s[9]=0,s[10]=e,s[11]=0,s[12]=r-(e*r+t*i),s[13]=0,s[14]=i-(-t*r+e*i),s[15]=1}setVisible(e){this.isVisible=e}update(e){for(let o of ie)o.onUpdate?.(this,e);let t=typeof performance<"u"?performance.now():Date.now();if(!this.isPointerDown&&this.autoRotate&&t-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*e,this.updateTurntableMatrix();for(let o of ie)o.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let r=Math.round((this.currTheta*180/Math.PI%360+360)%360),i=Math.round(this.currPhi*180/Math.PI),s=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(r-this.lastReportedTheta)>=1||Math.abs(i-this.lastReportedPhi)>=1||Math.abs(s-this.lastReportedZoom)>=.02){this.lastReportedTheta=r,this.lastReportedPhi=i,this.lastReportedZoom=s;let o={theta:r,phi:i,zoom:s,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(o),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:o}))}}renderXRView(e,t,r,i,s=!0,o=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let u=e?.transform?.inverse?.matrix||this.viewMatrix,c=e?.projectionMatrix||this.projMatrix,a=e?.transform?.position,l=a?[a.x,a.y,a.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):r&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:u,projMatrix:c,eyePos:l,viewport:i,eye:e?.eye||"none",clear:o>0?!1:e?.eye!=="right",isAR:s})}render(e){if(!e&&this.stereoSBS){let M=Math.max(2,this.canvas.width||2),x=Math.max(1,this.canvas.height||1),w=Math.max(1,Math.floor(M*.5)),T=Math.max(1,M-w),A=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),y=this.customTarget||this.bounds.center,E=y[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),f=y[1]+this.currDistance*Math.sin(this.currPhi),_=y[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),S=Math.cos(this.currTheta),R=-Math.sin(this.currTheta),F=.032,D=te(),U=te(),k=[E-S*F,f,_-R*F],X=[y[0]-S*F*.25,y[1],y[2]-R*F*.25];at(D,this.fov,w/x,.1,A),Be(U,k,X,[0,1,0]);let B=te(),L=te(),O=[E+S*F,f,_+R*F],V=[y[0]+S*F*.25,y[1],y[2]+R*F*.25];at(B,this.fov,T/x,.1,A),Be(L,O,V,[0,1,0]),this.render({viewMatrix:U,projMatrix:D,eyePos:k,viewport:[0,0,w,x],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:L,projMatrix:B,eyePos:O,viewport:[w,0,T,x],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,M,x);return}let t=this.gl,r=0,i=0,s=this.canvas.width,o=this.canvas.height;e?.viewport?(r=e.viewport[0],i=e.viewport[1],s=e.viewport[2],o=e.viewport[3],t.viewport(r,i,s,o)):t.viewport(0,0,this.canvas.width,this.canvas.height),t.enable(2929),(!e||e.clear!==!1)&&(e?.isAR?t.clearColor(0,0,0,0):t.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),t.clear(16384|256));let u=te(),c=e?.viewMatrix??this.viewMatrix;re(u,e?.projMatrix??this.projMatrix,c);let a=J().xrDepthShader,l=this.toneMapping==="reinhard"?1:this.toneMapping==="none"?2:this.toneMapping==="aces"?3:this.toneMapping==="agx"?4:0,h=this.customTarget||this.bounds.center,m=e?e.eyePos[0]:h[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),v=e?e.eyePos[1]:h[1]+this.currDistance*Math.sin(this.currPhi),b=e?e.eyePos[2]:h[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let M of ie)M.onBeforeDrawScene?.(this,t,u,[m,v,b],l);let d=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&d===0)return;let g=e?.eye||"none",I=!1,P=d>0?[...this.backdropMeshes,...this.meshes]:this.meshes,p=M=>{for(let x=0;x<P.length;x++){let w=P[x];if(w.visible===!1)continue;let T=this.selectedMeshName!==""&&w.name===this.selectedMeshName;x<d||w.worldSpace===!0||w.name==="__xr_reticle__"?this.modelMatrix.set(w.transform):re(this.modelMatrix,this.modelRootMatrix,w.transform),re(this.mvpMatrix,u,this.modelMatrix),be(w.normalMatrix,this.modelMatrix);let A=w.extras?.xr?.stereo||w.userData?.xr?.stereo,y=0,E=0,f=1,_=1;A==="sbs"?(f=.5,y=g==="right"?.5:0):A==="ou"&&(_=.5,E=g==="right"?.5:0);for(let S of w.primitives){let R=!!S.isTransmissive;if(!M&&R){I=!0;continue}if(M&&!R)continue;let F=S.customProgram||this.renderProg,D=S.customUniforms||this.uRender;t.useProgram(F),t.uniform1i(D.uToneMapping,l),t.uniform1f(D.uEnvIntensity,this.envIntensity),t.uniform3f(D.uCameraPos,m,v,b),t.uniform1f(D.uEmissive,T?1:0),t.uniformMatrix4fv(D.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(D.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(D.uNormalMatrix,!1,w.normalMatrix),D.uUvTransform&&t.uniform4f(D.uUvTransform,y,E,f,_),D.uViewportSize&&t.uniform2f(D.uViewportSize,Math.max(1,s),Math.max(1,o)),a?.bind(t,D,this.xrDepthState,c,[r,i,Math.max(1,s),Math.max(1,o)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(D.uEnvironmentMap,4),t.uniform1i(D.uHasEnvironmentMap,1)):t.uniform1i(D.uHasEnvironmentMap,0),this.bindLights(D),D.uSectionEnabled&&t.uniform1i(D.uSectionEnabled,0);for(let k of ie)k.onBeforeDrawPrimitive?.(t,F,S,w,this.worldMatrices||[],this.gltf);t.uniform4fv(D.uBaseColor,S.baseColor),t.uniform1f(D.uMetallic,S.metallic),t.uniform1f(D.uRoughness,S.roughness),D.uClearcoat&&t.uniform2f(D.uClearcoat,S.clearcoat??0,S.clearcoatRoughness??.04),S.texture?(t.activeTexture(33984),t.bindTexture(3553,S.texture),t.uniform1i(D.uBaseColorTexture,0),t.uniform1i(D.uHasTexture,1)):t.uniform1i(D.uHasTexture,0),S.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,S.metallicRoughnessTexture),t.uniform1i(D.uMetallicRoughnessTexture,1),t.uniform1i(D.uHasMetallicRoughnessTexture,1)):t.uniform1i(D.uHasMetallicRoughnessTexture,0),S.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,S.normalTexture),t.uniform1i(D.uNormalTexture,2),t.uniform1i(D.uHasNormalTexture,1),t.uniform1f(D.uNormalScale,S.normalScale)):t.uniform1i(D.uHasNormalTexture,0),S.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,S.occlusionTexture),t.uniform1i(D.uOcclusionTexture,3),t.uniform1i(D.uHasOcclusionTexture,1),t.uniform1f(D.uOcclusionStrength,S.occlusionStrength)):t.uniform1i(D.uHasOcclusionTexture,0),t.bindVertexArray(S.vao);let U=w.instanceMatrices;if(U&&U.length>=16){let k=U.length>>4,X=w.instanceColors,B=te(),L=new Float32Array(9),O=[S.baseColor[0],S.baseColor[1],S.baseColor[2],S.baseColor[3]];for(let V=0;V<k;V++)re(B,this.modelMatrix,U.subarray(V*16,V*16+16)),re(this.mvpMatrix,u,B),be(L,B),t.uniformMatrix4fv(D.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(D.uModel,!1,B),t.uniformMatrix3fv(D.uNormalMatrix,!1,L),X&&(O[0]=S.baseColor[0]*X[V*3],O[1]=S.baseColor[1]*X[V*3+1],O[2]=S.baseColor[2]*X[V*3+2],O[3]=S.baseColor[3],t.uniform4fv(D.uBaseColor,O)),S.indices?t.drawElements(4,S.indexCount,S.indexType,0):t.drawArrays(4,0,S.indexCount)}else S.indices?t.drawElements(4,S.indexCount,S.indexType,0):t.drawArrays(4,0,S.indexCount)}}};if(p(!1),I){for(let M of ie)M.onBeforeTransmissivePass?.(t,this);p(!0)}for(let M of ie)M.onAfterRender?.(t,this,u)}disposeMeshListGpuResources(e,t){let r=this.gl,i=new Set,s=o=>{o&&!i.has(o)&&(i.add(o),r.deleteTexture(o))};for(let o of e)for(let u of o.primitives){if(u.vao&&r.deleteVertexArray(u.vao),u.buffers)for(let c of u.buffers)r.deleteBuffer(c);s(u.texture),s(u.metallicRoughnessTexture),s(u.normalTexture),s(u.occlusionTexture),u.customProgram&&r.deleteProgram(u.customProgram)}if(t)for(let o of t)s(o)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let e=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let t of ie)t.onDestroy?.(e,this);this.environmentTexture&&(e.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&e.deleteProgram(this.renderProg),this.pickProg&&e.deleteProgram(this.pickProg),this.pickFbo&&e.deleteFramebuffer(this.pickFbo),this.pickTexture&&e.deleteTexture(this.pickTexture),this.pickDepth&&e.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};he.registerPlugin=rt,he.getRegisteredPlugins=En;function Ir(n){return n+3&-4}function Pr(n,e=0){let t=(L,O)=>typeof L=="number"&&Number.isFinite(L)?L:O,r=t(n[e+12],0),i=t(n[e+13],0),s=t(n[e+14],0),o=t(n[e+0],1),u=t(n[e+1],0),c=t(n[e+2],0),a=t(n[e+4],0),l=t(n[e+5],1),h=t(n[e+6],0),m=t(n[e+8],0),v=t(n[e+9],0),b=t(n[e+10],1),d=Math.hypot(o,u,c),g=Math.hypot(a,l,h),I=Math.hypot(m,v,b);o*(l*b-v*h)-a*(u*b-v*c)+m*(u*h-l*c)<0&&(d=-d);let p=Math.abs(d)>1e-8?1/d:0,M=Math.abs(g)>1e-8?1/g:0,x=Math.abs(I)>1e-8?1/I:0,w=o*p,T=u*p,A=c*p,y=a*M,E=l*M,f=h*M,_=m*x,S=v*x,R=b*x,F=w+E+R,D=0,U=0,k=0,X=1;if(F>0){let L=.5/Math.sqrt(F+1);X=.25/L,D=(f-S)*L,U=(_-A)*L,k=(T-y)*L}else if(w>E&&w>R){let L=2*Math.sqrt(Math.max(0,1+w-E-R));L>1e-8&&(X=(f-S)/L,D=.25*L,U=(y+T)/L,k=(_+A)/L)}else if(E>R){let L=2*Math.sqrt(Math.max(0,1+E-w-R));L>1e-8&&(X=(_-A)/L,D=(y+T)/L,U=.25*L,k=(f+S)/L)}else{let L=2*Math.sqrt(Math.max(0,1+R-w-E));L>1e-8&&(X=(T-y)/L,D=(_+A)/L,U=(f+S)/L,k=.25*L)}let B=Math.hypot(D,U,k,X);return B>1e-8&&Number.isFinite(B)?(D/=B,U/=B,k/=B,X/=B):(D=0,U=0,k=0,X=1),{t:[r,i,s],r:[D,U,k,X],s:[d,g,I]}}function Fr(n){let e={};return n.grab&&(e.interactable={mode:typeof n.grab=="string"?n.grab:"2-hand"},e.movable={scaleInZ:!!n.scale,minScale:typeof n.scale=="object"?n.scale.min??.1:.1,maxScale:typeof n.scale=="object"?n.scale.max??10:10}),n.billboard&&(e.billboard={mode:typeof n.billboard=="string"?n.billboard:"capsule"}),n.follow&&(e.follow={target:typeof n.follow=="object"?n.follow.mode??"head":n.follow}),n.anchor&&(e.anchor={plane:n.anchor}),n.physics&&n.physics!=="none"&&(e.rigidbody={type:n.physics}),e}function Ze(n,e){n.updateMatrixWorld(!0);let t=[],r=0,i=[],s=[],o=[],u=[],c=new Set,a=[],l=[],h=new Map,m=[],v=[];function b(y){let E=h.get(y);if(E!==void 0)return E;E=l.length,h.set(y,E);let f=y,_=f.color?.r??.8,S=f.color?.g??.8,R=f.color?.b??.8,F=f.opacity??1,D={name:f.name||"",pbrMetallicRoughness:{baseColorFactor:[_,S,R,F],metallicFactor:f.metalness??.1,roughnessFactor:f.roughness??.5},doubleSided:f.side===2||!!f.doubleSided};if(f.emissive&&(f.emissive.r>0||f.emissive.g>0||f.emissive.b>0)){let k=f.emissiveIntensity??1;D.emissiveFactor=[f.emissive.r*k,f.emissive.g*k,f.emissive.b*k]}let U={};return f.clearcoat&&f.clearcoat>0&&(U.KHR_materials_clearcoat={clearcoatFactor:f.clearcoat,clearcoatRoughnessFactor:f.clearcoatRoughness||0}),f.sheen&&f.sheen>0&&(U.KHR_materials_sheen={sheenColorFactor:f.sheenColor?[f.sheenColor.r,f.sheenColor.g,f.sheenColor.b]:[1,1,1],sheenRoughnessFactor:f.sheenRoughness||0}),f.transmission&&f.transmission>0&&(U.KHR_materials_transmission={transmissionFactor:f.transmission}),f.thickness&&f.thickness>0&&(U.KHR_materials_volume={thicknessFactor:f.thickness,attenuationDistance:f.attenuationDistance??1/0,attenuationColor:f.attenuationColor?[f.attenuationColor.r,f.attenuationColor.g,f.attenuationColor.b]:[1,1,1]}),f.ior!==void 0&&f.ior!==1.5&&(U.KHR_materials_ior={ior:f.ior}),f.dispersion&&f.dispersion>0&&(U.KHR_materials_dispersion={dispersion:f.dispersion}),f.iridescence&&f.iridescence>0&&(U.KHR_materials_iridescence={iridescenceFactor:f.iridescence,iridescenceIor:f.iridescenceIOR??1.3}),Object.keys(U).length>0&&(D.extensions=U),l.push(D),E}function d(y,E){let f=new Uint8Array(y.buffer,y.byteOffset,y.byteLength),_=Ir(f.byteLength),S=new Uint8Array(_);S.set(f),t.push(S);let R=i.length;return i.push({buffer:0,byteOffset:r,byteLength:f.byteLength,target:E}),r+=_,R}function g(y,E,f,_,S,R,F){let D=d(y,f),U=s.length,k={bufferView:D,byteOffset:0,componentType:_,count:S,type:E};return R&&(k.min=R),F&&(k.max=F),s.push(k),U}n.traverse(y=>{(y.isLight||y.color&&y.intensity!==void 0)&&v.push({type:y.type,color:[y.color.r,y.color.g,y.color.b],intensity:y.intensity,position:[y.position.x,y.position.y,y.position.z]})});let I=[];function P(y){let E={name:y.name||""},f=y.position,_=y.quaternion,S=y.scale;if((f.x||f.y||f.z)&&(E.translation=[f.x,f.y,f.z]),(_.x||_.y||_.z||_.w!==1)&&(E.rotation=[_.x,_.y,_.z,_.w]),(S.x!==1||S.y!==1||S.z!==1)&&(E.scale=[S.x,S.y,S.z]),y.userData&&Object.keys(y.userData).length>0&&(E.extras=JSON.parse(JSON.stringify(y.userData,(F,D)=>{if(!(F==="__proto__"||F==="prototype"||F==="constructor"))return typeof D=="function"?void 0:D})),y.userData.xr)){let F=Fr(y.userData.xr);E.extensions={...E.extensions||{},MOZ_hubs_components:F,ANDROID_xr_scenecore:F},J().xrTraitSerializer?.gltfNode(E,y.userData.xr),c.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(y.geometry){let F=y.geometry,D=F.attributes.position;if(D&&D.count>0){let U=[1/0,1/0,1/0],k=[-1/0,-1/0,-1/0];for(let z=0;z<D.count;z++){let $=D.getX(z),C=D.getY(z),N=D.getZ(z);$<U[0]&&(U[0]=$),$>k[0]&&(k[0]=$),C<U[1]&&(U[1]=C),C>k[1]&&(k[1]=C),N<U[2]&&(U[2]=N),N>k[2]&&(k[2]=N)}let B={attributes:{POSITION:g(D.array,"VEC3",34962,5126,D.count,U,k)}};if(F.attributes.normal&&(B.attributes.NORMAL=g(F.attributes.normal.array,"VEC3",34962,5126,F.attributes.normal.count)),F.attributes.uv&&(B.attributes.TEXCOORD_0=g(F.attributes.uv.array,"VEC2",34962,5126,F.attributes.uv.count)),F.index){let z=F.index.array instanceof Uint32Array;B.indices=g(F.index.array,"SCALAR",34963,z?5125:5123,F.index.count)}y.material&&(B.material=b(y.material));let L=y.userData?.variants;if(L&&typeof L=="object"){let z=new Map;for(let $ of Object.keys(L)){if(!$||$==="__proto__"||$==="constructor"||$==="prototype")continue;let C=L[$];if(!C||typeof C!="object")continue;let N=m.indexOf($);if(N===-1&&m.length<256&&(N=m.length,m.push($)),N===-1)continue;let H=b(C),G=z.get(H);G||(G=[],z.set(H,G)),G.push(N)}if(z.size>0){let $=[];for(let[C,N]of z.entries())$.push({material:C,variants:N});B.extensions={...B.extensions||{},KHR_materials_variants:{mappings:$}},c.add("KHR_materials_variants")}}let O=y;if(O.isInstancedMesh&&typeof O.count=="number"&&O.count>0&&O.instanceMatrix?.array){let z=Math.min(1e4,Math.floor(O.count)),$=O.instanceMatrix.array,C=new Float32Array(z*3),N=new Float32Array(z*4),H=new Float32Array(z*3);for(let Y=0;Y<z;Y++){let{t:Q,r:q,s:K}=Pr($,Y*16);C[Y*3]=Q[0],C[Y*3+1]=Q[1],C[Y*3+2]=Q[2],N[Y*4]=q[0],N[Y*4+1]=q[1],N[Y*4+2]=q[2],N[Y*4+3]=q[3],H[Y*3]=K[0],H[Y*3+1]=K[1],H[Y*3+2]=K[2]}let G={TRANSLATION:g(C,"VEC3",0,5126,z),ROTATION:g(N,"VEC4",0,5126,z),SCALE:g(H,"VEC3",0,5126,z)};if(O.instanceColor?.array&&O.instanceColor.array.length>=z*3){let Y=new Float32Array(O.instanceColor.array.subarray(0,z*3));G._COLOR_0=g(Y,"VEC3",0,5126,z)}E.extensions={...E.extensions||{},EXT_mesh_gpu_instancing:{attributes:G}},c.add("EXT_mesh_gpu_instancing")}let V=o.length;o.push({primitives:[B],name:y.name,...E.extras?{extras:E.extras}:{}}),E.mesh=V}}let R=u.length;if(u.push(E),a.push(y),y.children.length>0){E.children=[];for(let F of y.children)E.children.push(P(F))}return R}for(let y of n.children)I.push(P(y));let p=e?.animateCallback||e?.animateFn||(typeof n.userData?.animate=="function"?n.userData.animate:typeof n.__animateFn=="function"?n.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0),M=[];if(typeof p=="function"&&a.length>0){let y=e?.duration??4,E=e?.fps??15,f=Math.max(2,Math.round(y*E)+1),_=new Float32Array(f),S=a.map(L=>({px:L.position.x,py:L.position.y,pz:L.position.z,qx:L.quaternion.x,qy:L.quaternion.y,qz:L.quaternion.z,qw:L.quaternion.w,sx:L.scale.x,sy:L.scale.y,sz:L.scale.z})),R=a.map(()=>new Float32Array(f*3)),F=a.map(()=>new Float32Array(f*4)),D=a.map(()=>new Float32Array(f*3));for(let L=0;L<f;L++){let O=L/(f-1)*y;_[L]=O;try{p(O)}catch{}for(let V=0;V<a.length;V++){let z=a[V];R[V][L*3]=z.position.x,R[V][L*3+1]=z.position.y,R[V][L*3+2]=z.position.z,F[V][L*4]=z.quaternion.x,F[V][L*4+1]=z.quaternion.y,F[V][L*4+2]=z.quaternion.z,F[V][L*4+3]=z.quaternion.w,D[V][L*3]=z.scale.x,D[V][L*3+1]=z.scale.y,D[V][L*3+2]=z.scale.z}}for(let L=0;L<a.length;L++){let O=a[L],V=S[L];O.position.set(V.px,V.py,V.pz),O.quaternion.set(V.qx,V.qy,V.qz,V.qw),O.scale.set(V.sx,V.sy,V.sz)}n.updateMatrixWorld(!0);let U=null,k=()=>(U===null&&(U=g(_,"SCALAR",0,5126,f,[0],[y])),U),X=[],B=[];for(let L=0;L<a.length;L++){let O=S[L],V=!1,z=!1,$=!1;for(let C=0;C<f;C++)(Math.abs(R[L][C*3]-O.px)>1e-4||Math.abs(R[L][C*3+1]-O.py)>1e-4||Math.abs(R[L][C*3+2]-O.pz)>1e-4)&&(V=!0),(Math.abs(F[L][C*4]-O.qx)>1e-4||Math.abs(F[L][C*4+1]-O.qy)>1e-4||Math.abs(F[L][C*4+2]-O.qz)>1e-4||Math.abs(F[L][C*4+3]-O.qw)>1e-4)&&(z=!0),(Math.abs(D[L][C*3]-O.sx)>1e-4||Math.abs(D[L][C*3+1]-O.sy)>1e-4||Math.abs(D[L][C*3+2]-O.sz)>1e-4)&&($=!0);if(V){let C=g(R[L],"VEC3",0,5126,f),N=X.length;X.push({input:k(),interpolation:"LINEAR",output:C}),B.push({sampler:N,target:{node:L,path:"translation"}})}if(z){let C=g(F[L],"VEC4",0,5126,f),N=X.length;X.push({input:k(),interpolation:"LINEAR",output:C}),B.push({sampler:N,target:{node:L,path:"rotation"}})}if($){let C=g(D[L],"VEC3",0,5126,f),N=X.length;X.push({input:k(),interpolation:"LINEAR",output:C}),B.push({sampler:N,target:{node:L,path:"scale"}})}}B.length>0&&M.push({name:"ProceduralLoop",samplers:X,channels:B})}let x=Cn(u,o,n.userData),w={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:n.environmentIntensity}},scenes:[{nodes:I}],scene:0,nodes:u,meshes:o,materials:l,accessors:s,bufferViews:i,buffers:[{byteLength:r}],...M.length>0?{animations:M}:{},...x||c.size>0?{extensionsUsed:[...x?["KHR_interactivity"]:[],...c]}:{},...x||m.length>0?{extensions:{...x?{KHR_interactivity:x}:{},...m.length>0?{KHR_materials_variants:{variants:m.map(y=>({name:y}))}}:{}}}:{}},T=new Uint8Array(r),A=0;for(let y of t)T.set(y,A),A+=y.byteLength;return{gltf:w,bin:T.buffer,lights:v,environmentIntensity:n.environmentIntensity}}function lt(n){return new TextEncoder().encode(n)}function ht(n,e){let{gltf:t,bin:r}=Ze(n,e),i=JSON.stringify(t),s=lt(i),o=(4-s.byteLength%4)%4,u=s.byteLength+o,c=20+u+8+r.byteLength,a=new Uint8Array(c),l=new DataView(a.buffer);l.setUint32(0,1179937895,!0),l.setUint32(4,2,!0),l.setUint32(8,c,!0),l.setUint32(12,u,!0),l.setUint32(16,1313821514,!0),a.set(s,20);for(let m=0;m<o;m++)a[20+s.byteLength+m]=32;let h=20+u;return l.setUint32(h,r.byteLength,!0),l.setUint32(h+4,5130562,!0),a.set(new Uint8Array(r),h+8),a}function Nr(n,e){n.updateMatrixWorld(!0);let t=[];return n.traverse(r=>{if(r.geometry){let i=r.geometry,s=i.attributes.position;if(!s||s.count===0)return;let o=s.count,u=new Float32Array(o*3),c=r.matrixWorld.elements;for(let A=0;A<o;A++){let y=s.getX(A),E=s.getY(A),f=s.getZ(A);u[A*3]=c[0]*y+c[4]*E+c[8]*f+c[12],u[A*3+1]=c[1]*y+c[5]*E+c[9]*f+c[13],u[A*3+2]=c[2]*y+c[6]*E+c[10]*f+c[14]}let a;if(i.attributes.normal){let A=i.attributes.normal;a=new Float32Array(o*3);let y=new Float32Array(9);be(y,c);for(let E=0;E<o;E++){let f=A.getX(E),_=A.getY(E),S=A.getZ(E),R=y[0]*f+y[3]*_+y[6]*S,F=y[1]*f+y[4]*_+y[7]*S,D=y[2]*f+y[5]*_+y[8]*S,U=Math.hypot(R,F,D)||1;a[E*3]=R/U,a[E*3+1]=F/U,a[E*3+2]=D/U}}let l;if(i.attributes.uv){let A=i.attributes.uv;l=new Float32Array(o*2);for(let y=0;y<o;y++)l[y*2]=A.getX(y),l[y*2+1]=A.getY(y)}let h;if(i.index)h=i.index.array;else{h=o>65535?new Uint32Array(o):new Uint16Array(o);for(let A=0;A<o;A++)h[A]=A}let m="DefaultMaterial",v=[.8,.8,.8],b=.5,d=.1,g=0,I=0,P=1.5,p=1,M=[0,0,0];if(r.material){let A=r.material;m=A.name||`Material_${t.length}`,A.color&&(v=[A.color.r,A.color.g,A.color.b]),typeof A.roughness=="number"&&(b=A.roughness),typeof A.metalness=="number"&&(d=A.metalness),typeof A.clearcoat=="number"&&(g=A.clearcoat),typeof A.clearcoatRoughness=="number"&&(I=A.clearcoatRoughness),typeof A.ior=="number"&&(P=A.ior);let y=typeof A.opacity=="number"?A.opacity:1,E=typeof A.transmission=="number"?A.transmission:0;if(p=y*(1-E),A.emissive&&(A.emissive.r>0||A.emissive.g>0||A.emissive.b>0)){let f=A.emissiveIntensity??1;M=[A.emissive.r*f,A.emissive.g*f,A.emissive.b*f]}}let x,w=e?.animateCallback||e?.animateFn||(typeof n.userData?.animate=="function"?n.userData.animate:typeof n.__animateFn=="function"?n.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0);if(typeof w=="function"){let A=e?.duration??4,y=e?.fps??4,E=Math.max(2,Math.round(A*y)+1),f=[],_=[],S=[],R=[],F=[r.position.x,r.position.y,r.position.z],D=[r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w],U=[r.scale.x,r.scale.y,r.scale.z],k=!1;for(let X=0;X<E;X++){let B=X/(E-1)*A;f.push(B);try{w(B)}catch{}_.push([r.position.x,r.position.y,r.position.z]),S.push([r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w]),R.push([r.scale.x,r.scale.y,r.scale.z]),(Math.abs(r.position.x-F[0])>1e-4||Math.abs(r.position.y-F[1])>1e-4||Math.abs(r.position.z-F[2])>1e-4||Math.abs(r.quaternion.x-D[0])>1e-4||Math.abs(r.quaternion.y-D[1])>1e-4||Math.abs(r.quaternion.z-D[2])>1e-4||Math.abs(r.quaternion.w-D[3])>1e-4||Math.abs(r.scale.x-U[0])>1e-4)&&(k=!0)}r.position.set(F[0],F[1],F[2]),r.quaternion.set(D[0],D[1],D[2],D[3]),r.scale.set(U[0],U[1],U[2]),k&&(x={times:f,translations:_,rotations:S,scales:R})}let T=r;if(T.isInstancedMesh&&typeof T.count=="number"&&T.count>0&&T.instanceMatrix?.array){let A=Math.min(1e3,Math.floor(T.count)),y=T.instanceMatrix.array,E=T.instanceColor?.array,f=r.name||`Mesh_${t.length}`,_=new Float32Array(16),S=new Float32Array(9);for(let R=0;R<A;R++){let F=y.subarray(R*16,(R+1)*16);re(_,c,F);let D=new Float32Array(o*3);for(let B=0;B<o;B++){let L=s.getX(B),O=s.getY(B),V=s.getZ(B);D[B*3]=_[0]*L+_[4]*O+_[8]*V+_[12],D[B*3+1]=_[1]*L+_[5]*O+_[9]*V+_[13],D[B*3+2]=_[2]*L+_[6]*O+_[10]*V+_[14]}let U;if(i.attributes.normal){let B=i.attributes.normal;U=new Float32Array(o*3),be(S,_);for(let L=0;L<o;L++){let O=B.getX(L),V=B.getY(L),z=B.getZ(L),$=S[0]*O+S[3]*V+S[6]*z,C=S[1]*O+S[4]*V+S[7]*z,N=S[2]*O+S[5]*V+S[8]*z,H=Math.hypot($,C,N)||1;U[L*3]=$/H,U[L*3+1]=C/H,U[L*3+2]=N/H}}let k=v,X=m;E&&E.length>=(R+1)*3&&(k=[v[0]*E[R*3],v[1]*E[R*3+1],v[2]*E[R*3+2]],X=`${m}_inst_${R}`),t.push({name:`${f}_${R}`,positions:D,indices:h,normals:U,uvs:l,materialName:X,color:k,roughness:b,metallic:d,clearcoat:g,clearcoatRoughness:I,ior:P,opacity:p,emissiveColor:M,xrTraits:r.userData?.xr})}return}t.push({name:r.name||`Mesh_${t.length}`,positions:u,indices:h,normals:a,uvs:l,materialName:m,color:v,roughness:b,metallic:d,clearcoat:g,clearcoatRoughness:I,ior:P,opacity:p,emissiveColor:M,xrTraits:r.userData?.xr,timeSamples:x})}}),t}function Gn(n){let e=[],t=n.gltf,r=J().decoders.get("meshopt");r&&typeof r.decodeBufferViews=="function"&&r.decodeBufferViews(t,n);let i=n.bin,s=i instanceof ArrayBuffer?i:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),o=t.accessors||[],u=t.bufferViews||[],c=t.materials||[],a=t.meshes||[],l=t.nodes||[];function h(b){let d=o[b];if(!d)throw new Error(`Accessor ${b} not found`);let g=u[d.bufferView||0],I=(g.byteOffset||0)+(d.byteOffset||0),P=g.byteLength||0,p=s.slice(I,I+P);return{acc:d,buffer:p}}let m=new Map;if(l.length>0){let b=ct(t);for(let d=0;d<b.length;d++)m.set(d,b[d])}function v(b,d,g,I){let P=a[b];if(!P)return;let p=new Float32Array(9);be(p,d);for(let M=0;M<(P.primitives||[]).length;M++){let x=P.primitives[M],w=x.attributes?.POSITION;if(w===void 0)continue;let{acc:T,buffer:A}=h(w),y=new Float32Array(A,0,T.count*3),E=new Float32Array(y.length);for(let C=0;C<T.count;C++){let N=y[C*3],H=y[C*3+1],G=y[C*3+2];E[C*3]=d[0]*N+d[4]*H+d[8]*G+d[12],E[C*3+1]=d[1]*N+d[5]*H+d[9]*G+d[13],E[C*3+2]=d[2]*N+d[6]*H+d[10]*G+d[14]}let f,_=x.attributes?.NORMAL;if(_!==void 0){let{acc:C,buffer:N}=h(_),H=new Float32Array(N,0,C.count*3);f=new Float32Array(H.length);for(let G=0;G<C.count;G++){let Y=H[G*3],Q=H[G*3+1],q=H[G*3+2],K=p[0]*Y+p[3]*Q+p[6]*q,ce=p[1]*Y+p[4]*Q+p[7]*q,W=p[2]*Y+p[5]*Q+p[8]*q,ue=Math.hypot(K,ce,W)||1;f[G*3]=K/ue,f[G*3+1]=ce/ue,f[G*3+2]=W/ue}}let S,R=x.attributes?.TEXCOORD_0;if(R!==void 0){let{acc:C,buffer:N}=h(R);S=new Float32Array(N,0,C.count*2)}let F;if(x.indices!==void 0){let{acc:C,buffer:N}=h(x.indices);C.componentType===5125?F=new Uint32Array(N,0,C.count):F=new Uint16Array(N,0,C.count);let H=T.count;for(let G of F)if(G>=H)throw new Error(`SecurityError: Index buffer value (${G}) out of vertex bounds [0, ${H}).`)}else{let C=T.count;F=C>65535?new Uint32Array(C):new Uint16Array(C);for(let N=0;N<C;N++)F[N]=N}let D="DefaultMaterial",U=[.8,.8,.8],k=.5,X=.1,B=0,L=0,O=1.5,V=1,z=[0,0,0];if(x.material!==void 0&&c[x.material]){let C=c[x.material];D=C.name||`Material_${x.material}`;let N=C.pbrMetallicRoughness||{},H=1;Array.isArray(N.baseColorFactor)&&(U=[N.baseColorFactor[0],N.baseColorFactor[1],N.baseColorFactor[2]],typeof N.baseColorFactor[3]=="number"&&(H=N.baseColorFactor[3])),typeof N.roughnessFactor=="number"&&(k=N.roughnessFactor),typeof N.metallicFactor=="number"&&(X=N.metallicFactor),Array.isArray(C.emissiveFactor)&&C.emissiveFactor.length>=3&&(z=[C.emissiveFactor[0],C.emissiveFactor[1],C.emissiveFactor[2]]);let G=C.extensions||{};G.KHR_materials_clearcoat&&(B=G.KHR_materials_clearcoat.clearcoatFactor??0,L=G.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),G.KHR_materials_ior&&typeof G.KHR_materials_ior.ior=="number"&&(O=G.KHR_materials_ior.ior);let Y=G.KHR_materials_transmission?.transmissionFactor??0;V=H*(1-Y)}let $=(P.primitives||[]).length>1?`${g}_p${M}`:g;e.push({name:$,positions:E,indices:F,normals:f,uvs:S,materialName:D,color:U,roughness:k,metallic:X,clearcoat:B,clearcoatRoughness:L,ior:O,opacity:V,emissiveColor:z,xrTraits:I?.xr||P.extras?.xr})}}if(l.length>0)for(let b=0;b<l.length;b++){let d=l[b];if(d.mesh!==void 0&&d.mesh<a.length){let g=m.get(b)||te(),I=d.name||a[d.mesh].name||`Node_${b}`,P=d.extensions?.EXT_mesh_gpu_instancing?.attributes;if(P&&typeof P=="object"){let p=P.TRANSLATION,M=P.ROTATION,x=P.SCALE,w=p!==void 0?(()=>{let{acc:E,buffer:f}=h(p);return new Float32Array(f,0,E.count*3)})():null,T=M!==void 0?(()=>{let{acc:E,buffer:f}=h(M);return new Float32Array(f,0,E.count*4)})():null,A=x!==void 0?(()=>{let{acc:E,buffer:f}=h(x);return new Float32Array(f,0,E.count*3)})():null,y=Math.min(1e3,w?w.length/3:T?T.length/4:A?A.length/3:0);if(y>0){let E=new Float32Array(16),f=new Float32Array(16);for(let _=0;_<y;_++){let S=w?[w[_*3],w[_*3+1],w[_*3+2]]:[0,0,0],R=T?[T[_*4],T[_*4+1],T[_*4+2],T[_*4+3]]:[0,0,0,1],F=A?[A[_*3],A[_*3+1],A[_*3+2]]:[1,1,1];Pe(E,R,S,F),re(f,g,E),v(d.mesh,f,`${I}_${_}`,d.extras)}continue}}v(d.mesh,g,I,d.extras)}}else{let b=te();for(let d=0;d<a.length;d++){let g=a[d].name||`Mesh_${d}`;v(d,b,g,a[d].extras)}}return e}function Vt(n,e){if(!n||typeof n!="string")return e;let t=n.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(t)&&(t="_"+t),t||e}function Hn(n){return String(n??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function j(n){if(!Number.isFinite(n)||Math.abs(n)<1e-7)return"0";let e=Number(n.toFixed(5)).toString();return e.indexOf(".")===-1?`${e}.0`:e}function Xn(n){let e=n.length/3,t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${j(n[r*3])}, ${j(n[r*3+1])}, ${j(n[r*3+2])})`;return t.join(", ")}function kr(n,e){let t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${j(n[r*2])}, ${j(1-n[r*2+1])})`;return t.join(", ")}function Ur(n){return Array.from(n).join(", ")}function zt(n){let e=new Map;for(let c of n){let a=Vt(c.materialName,"DefaultMaterial");e.has(a)||e.set(a,{color:c.color||[.8,.8,.8],roughness:c.roughness??.5,metallic:c.metallic??0,clearcoat:c.clearcoat??0,clearcoatRoughness:c.clearcoatRoughness??0,ior:c.ior??1.5,opacity:c.opacity??1,emissiveColor:c.emissiveColor||[0,0,0]})}let t=0,r=null;for(let c of n){if(c.timeSamples&&c.timeSamples.times.length>0){let a=c.timeSamples.times[c.timeSamples.times.length-1];a>t&&(t=a)}c.xrTraits?.anchor&&!r&&(r=c.xrTraits.anchor==="vertical"||c.xrTraits.anchor==="wall"?"vertical":"horizontal")}let i="";t>0&&(i=`startTimeCode = 0
|
|
235
|
-
endTimeCode = ${
|
|
252
|
+
void main(){fragColor=uColorId;}`;function Ln(n,e,t){let r=n.createShader(e);if(n.shaderSource(r,t),n.compileShader(r),!n.getShaderParameter(r,35713)){let i=n.getShaderInfoLog(r);throw n.deleteShader(r),new Error(`Shader compile error: ${i}`)}return r}function Nt(n,e,t){let r=Ln(n,35633,e),i=Ln(n,35632,t),s=n.createProgram();if(n.attachShader(s,r),n.attachShader(s,i),n.linkProgram(s),!n.getProgramParameter(s,35714)){let o=n.getProgramInfoLog(s);throw n.deleteProgram(s),new Error(`Program link error: ${o}`)}return s}function kt(n,e,t){let r={};for(let i of t)r[i]=n.getUniformLocation(e,i);return r}var Dn=["uMVP","uModel","uInstanced","uViewProj","uNormalMatrix","uUvTransform","uBaseColor","uMetallic","uRoughness","uClearcoat","uEmissive","uCameraPos","uBaseColorTexture","uHasTexture","uMetallicRoughnessTexture","uHasMetallicRoughnessTexture","uNormalTexture","uHasNormalTexture","uNormalScale","uOcclusionTexture","uHasOcclusionTexture","uOcclusionStrength","uToneMapping","uEnvironmentMap","uHasEnvironmentMap","uAmbientColor","uNumDirLights","uDirLightDir","uDirLightColor","uNumPointLights","uPointLightPos","uPointLightColor","uEnvIntensity","uExposure","uViewportSize","uSectionPlane","uSectionEnabled"];function On(){let n=Q().xrDepthShader;return{fs:Cr.replace("/*XRD_U*/",n?.uniformsGLSL||"").replace("/*XRD_O*/",n?.occlusionGLSL||""),uniforms:n?[...Dn,...n.uniformNames]:Dn}}function Ir(n){if(typeof n!="string")return null;let e=n.trim();if(!e||/[\x00-\x1f\x7f]/.test(e))return null;let t=e.toLowerCase();return t.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(e)?e:null:t.startsWith("https://")||t.startsWith("blob:")?e:t.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(e)||/(^|[\\/])\.\.([\\/]|$)/.test(e)?null:e}function Pt(n,e,t,r,i,s,o,c){if(r===void 0||!e.accessors?.[r])return null;let a=It(e,t,e.accessors[r],s);if(!a)return null;c&&(a=a.slice(),Cn(a,c));let u=n.createBuffer();return o.push(u),n.bindBuffer(34962,u),n.bufferData(34962,a,35044),n.enableVertexAttribArray(i),n.vertexAttribPointer(i,s,5126,!1,0,0),a}function Ft(n){let e=Number(n);return Number.isFinite(e)?Math.max(0,e):1}function Bn(n,e,t){let r=On(),i=kn,s=r.fs,o=!1;for(let a of ce)if(a.onResolveShader){let u=a.onResolveShader(e,t,i,s);u&&(i=u.vs,s=u.fs,o=!0)}let c=o?Nt(n,i,s):null;return{program:c,uniforms:c?kt(n,c,r.uniforms):null}}function Pr(n,e,t){let r=e.instanceMatrices;if(!r||r.length<16||typeof n.vertexAttribDivisor!="function"||typeof n.drawElementsInstanced!="function")return!1;let i=r.length>>4,s=e.instanceColors,o=new Float32Array(i*20);for(let a=0;a<i;a++)o.set(r.subarray(a*16,a*16+16),a*20),o[a*20+16]=s?s[a*3]:1,o[a*20+17]=s?s[a*3+1]:1,o[a*20+18]=s?s[a*3+2]:1,o[a*20+19]=1;let c=n.createBuffer();t.push(c),n.bindBuffer(34962,c),n.bufferData(34962,o,35044);for(let a=0;a<5;a++)n.enableVertexAttribArray(8+a),n.vertexAttribPointer(8+a,4,5126,!1,80,a*16),n.vertexAttribDivisor(8+a,1);return!0}function Fr(n,e){let t=n.materials?.[e?.material];if(!t)return null;let r=[t.pbrMetallicRoughness?.baseColorTexture,t.pbrMetallicRoughness?.metallicRoughnessTexture,t.normalTexture,t.occlusionTexture,t.emissiveTexture];for(let i of r){let s=i?.extensions?.KHR_texture_transform;if(s&&typeof s=="object")return s}return null}var Vn=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),zn=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function nt(n,e){e.indices?n.drawElements(4,e.indexCount,e.indexType,0):n.drawArrays(4,0,e.indexCount)}function Hn(n,e){let t=n?.pbrMetallicRoughness,r=t?.baseColorFactor,i=n?.extensions?.KHR_materials_clearcoat,s=o=>o!==void 0&&e[o.index]?e[o.index]:null;return{baseColor:r?[r[0],r[1],r[2],r[3]??1]:[.8,.8,.8,1],metallic:t?.metallicFactor??.1,roughness:t?.roughnessFactor??.5,clearcoat:i?i.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,i?.clearcoatRoughnessFactor??.04),texture:s(t?.baseColorTexture),metallicRoughnessTexture:s(t?.metallicRoughnessTexture),normalTexture:s(n?.normalTexture),normalScale:n?.normalTexture?.scale??1,occlusionTexture:s(n?.occlusionTexture),occlusionStrength:n?.occlusionTexture?.strength??1,isTransmissive:(n?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function Gn(n,e,t){let r=new Set,i=s=>{s&&!r.has(s)&&(r.add(s),n.deleteTexture(s))};for(let s of e)for(let o of s.primitives){if(o.vao&&n.deleteVertexArray(o.vao),o.buffers)for(let a of o.buffers)n.deleteBuffer(a);i(o.texture),i(o.metallicRoughnessTexture),i(o.normalTexture),i(o.occlusionTexture);let c=new Set;o.customProgram&&c.add(o.customProgram);for(let a of o.programCache?.values()??[])a.program&&c.add(a.program);for(let a of c)n.deleteProgram(a)}if(t)for(let s of t)i(s)}function In(n,e,t=zn,r){let i={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return Nr(n,e,t,r,i)}catch(s){let o=i.mesh&&!i.meshes.includes(i.mesh)?[...i.meshes,i.mesh]:i.meshes;Gn(n,o,i.gpuTextures),i.vao&&n.deleteVertexArray(i.vao);for(let c of i.buffers)n.deleteBuffer(c);throw s}}function Nr(n,e,t,r,i){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:s}=e,o=Ne("meshopt");o?.decodeBufferViews&&o.decodeBufferViews(s,e);let c=e.bin,a=[];i.meshes=a;let u=[],l=s.extensions?.KHR_materials_variants;l&&Array.isArray(l.variants)&&l.variants.forEach((v,I)=>{u.push(typeof v?.name=="string"&&v.name?v.name:`Variant_${I}`)});let m=tt(s),h=[];if(Array.isArray(s.nodes))for(let v=0;v<s.nodes.length;v++){let I=s.nodes[v];I.mesh!==void 0&&s.meshes&&s.meshes[I.mesh]&&h.push({node:I,nodeIdx:v,meshIdx:I.mesh})}let y=h.length>0?h:(s.meshes||[]).map((v,I)=>({node:v,nodeIdx:-1,meshIdx:I})),b=[];if(Array.isArray(e.lights)&&e.lights.length>0)b.push(...e.lights);else if(s.extensions?.KHR_lights_punctual?.lights){let v=s.extensions.KHR_lights_punctual.lights;for(let I of v){let R=I.type==="directional"?"directional":I.type==="point"?"point":"ambient";b.push({type:R,color:I.color||[1,1,1],intensity:I.intensity!==void 0?I.intensity:1})}}if(b.length===0&&(b.push({type:"ambient",color:[1,1,1],intensity:.35}),b.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),y.length>t.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${t.maxMeshes}). Found: ${y.length}`);let d=[];if(i.gpuTextures=d,s.textures&&s.images){if(s.textures.length>t.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${t.maxTextures}). Found: ${s.textures.length}`);for(let v=0;v<s.textures.length;v++){let I=s.textures[v],R=s.images[I.source];if(R){let C=n.createTexture();if(n.bindTexture(3553,C),n.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),n.texParameteri(3553,10242,10497),n.texParameteri(3553,10243,10497),n.texParameteri(3553,10241,9729),n.texParameteri(3553,10240,9729),R.bufferView!==void 0){let N=s.bufferViews[R.bufferView],F=c.slice(N.byteOffset||0,(N.byteOffset||0)+N.byteLength),V=new Blob([F],{type:R.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(V).then(U=>{n.bindTexture(3553,C),n.texImage2D(3553,0,6408,6408,5121,U),n.generateMipmap(3553),r?.()}).catch(()=>{})}else if(R.uri){let N=Ir(R.uri);if(N){let F=new Image;F.crossOrigin="anonymous",F.referrerPolicy="no-referrer",F.onload=()=>{n.bindTexture(3553,C),n.texImage2D(3553,0,6408,6408,5121,F),n.generateMipmap(3553),r?.()},F.src=N}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",R.uri)}d.push(C)}else d.push(null)}}let g=[1/0,1/0,1/0],T=[-1/0,-1/0,-1/0],P=0,f=0;for(let v=0;v<y.length;v++){let I=y[v],R=s.meshes[I.meshIdx],C=I.nodeIdx>=0?m[I.nodeIdx]:oe(),N=new Float32Array(9);ye(N,C);let F={name:I.node.name||R.name||`Mesh_${I.meshIdx}`,nodeIndex:I.nodeIdx,transform:C,normalMatrix:N,primitives:[],extras:I.node.extras||R.extras};i.mesh=F;let V=I.node?.extensions?.EXT_mesh_gpu_instancing;if(V&&V.attributes&&typeof V.attributes=="object"){let U=V.attributes,B=U.TRANSLATION!==void 0?s.accessors?.[U.TRANSLATION]:null,D=U.ROTATION!==void 0?s.accessors?.[U.ROTATION]:null,H=U.SCALE!==void 0?s.accessors?.[U.SCALE]:null,z=U._COLOR_0!==void 0?s.accessors?.[U._COLOR_0]:null,O=Number(B?.count??D?.count??H?.count??0);if(!Number.isFinite(O)||O<0||O>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${O}`);if(O>0){let X=(q,Z)=>{if(!q||q.bufferView===void 0||!s.bufferViews?.[q.bufferView])return null;let Y=q.componentType??5126,ie=ne=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${ne})`),null);if(Y!==5120&&Y!==5121&&Y!==5122&&Y!==5123&&Y!==5126)return ie(`componentType ${Y}`);if(!(Number(q.count)>=O))return ie(`count ${q.count} < ${O}`);let $=null;try{$=It(s,c,{...q,count:O},Z)}catch{return ie("out of bounds")}return!$||!$.every(Number.isFinite)?ie("non-finite value"):$},E=X(B,3),k=X(D,4),G=X(H,3),W=z?.type==="VEC4"?4:3,j=X(z,W),re=new Float32Array(O*16),ue=oe();for(let q=0;q<O;q++){let Z=E?[E[q*3],E[q*3+1],E[q*3+2]]:[0,0,0],Y=k?[k[q*4],k[q*4+1],k[q*4+2],k[q*4+3]]:[0,0,0,1],ie=G?[G[q*3],G[q*3+1],G[q*3+2]]:[1,1,1];_e(ue,Y,Z,ie),re.set(ue,q*16)}if(F.instanceMatrices=re,j){let q=new Float32Array(O*3);for(let Z=0;Z<O;Z++)q[Z*3]=j[Z*W],q[Z*3+1]=j[Z*W+1],q[Z*3+2]=j[Z*W+2];F.instanceColors=q}}}for(let U of R.primitives||[]){if(U.extensions?.KHR_draco_mesh_compression){let $=Ne("draco");$&&$.decodePrimitive(s,U,c)}let B=[],D=n.createVertexArray();i.vao=D,i.buffers=B,n.bindVertexArray(D);let H=Pr(n,F,B),z=s.accessors[U.attributes.POSITION],O=Number(z?.count??0);if(!Number.isFinite(O)||O<0||P+O>t.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${t.maxVertices}).`);if(P+=O,z?.min&&z?.max){let $=ne=>{for(let te=0;te<3;te++){let ee=ne[12+te],se=ne[12+te];for(let be=0;be<3;be++){let me=ne[be*4+te]*z.min[be],fe=ne[be*4+te]*z.max[be];ee+=me<fe?me:fe,se+=me>fe?me:fe}ee<g[te]&&(g[te]=ee),se>T[te]&&(T[te]=se)}};if(F.instanceMatrices&&F.instanceMatrices.length>=16){let ne=F.instanceMatrices.length>>4,te=oe();for(let ee=0;ee<ne;ee++){let se=F.instanceMatrices.subarray(ee*16,ee*16+16);ae(te,C,se),$(te)}}else $(C)}let X=Pt(n,s,c,U.attributes.POSITION,0,3,B);Pt(n,s,c,U.attributes.NORMAL,1,3,B),Pt(n,s,c,U.attributes.TEXCOORD_0,2,2,B,Fr(s,U));let E=0,k=5123,G=null;if(U.indices!==void 0){let $=s.accessors[U.indices],te=(s.bufferViews[$.bufferView].byteOffset||0)+($.byteOffset||0);if(E=Number($.count??0),!Number.isFinite(E)||E<0||f+E>t.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${t.maxIndices}).`);f+=E,k=$.componentType===5125?5125||5125:5123||5123;let ee=n.createBuffer();B.push(ee),n.bindBuffer(34963,ee),$.componentType===5125?(G=new Uint32Array(c,te,$.count),n.bufferData(34963,G,35044)):$.componentType===5121?(G=Uint16Array.from(new Uint8Array(c,te,$.count)),n.bufferData(34963,G,35044)):(G=te%2===0?new Uint16Array(c,te,$.count):new Uint16Array(c.slice(te,te+$.count*2)),n.bufferData(34963,G,35044))}else E=z.count;let W={};for(let $ of ce)if($.onBuildPrimitiveVAO){let ne=$.onBuildPrimitiveVAO(n,D,U,s,c);ne&&(W[$.name]=ne)}n.bindVertexArray(null);let j=s.materials&&U.material!==void 0?s.materials[U.material]:null,{program:re,uniforms:ue}=Bn(n,U,j),q=Hn(j,d),Z=!!(j?.extensions?.KHR_materials_transmission||W.materials?.isTransmissive),Y=U.extensions?.KHR_materials_variants?.mappings,ie=Array.isArray(Y)?Y.filter($=>$&&typeof $.material=="number"&&Array.isArray($.variants)).map($=>({material:$.material|0,variants:$.variants.map(ne=>Number(ne)|0)})):void 0;F.primitives.push({vao:D,instanced:H,indexCount:E,indexType:k,...q,positions:X,indices:G,buffers:B,materialIndex:U.material,defaultMaterialIndex:U.material,variantMappings:ie,primitiveDef:U,programCache:new Map([[U.material??-1,{program:re,uniforms:ue}]]),pluginData:W,customProgram:re,customUniforms:ue,isTransmissive:Z})}a.push(F)}isFinite(g[0])||(g=[-1,-1,-1]),isFinite(T[0])||(T=[1,1,1]);let M=[(g[0]+T[0])/2,(g[1]+T[1])/2,(g[2]+T[2])/2],p=T[0]-g[0],S=T[1]-g[1],_=T[2]-g[2],w=Math.max(Math.hypot(p,S,_)/2,.5),A=[g[0],g[1],g[2]],L=[T[0],T[1],T[2]],x=e.animations;if(!x){for(let v of ce)if(v.onParseGLB?.(e),e.animations){x=e.animations;break}}return x||(x=[]),{meshes:a,bounds:{center:M,radius:w,min:A,max:L},lights:b,animations:x,worldMatrices:m,gpuTextures:d,availableVariants:u}}function $e(n){let e=n.customTarget||n.bounds.center,t=n.currDistance*Math.cos(n.currPhi);return[e[0]+t*Math.sin(n.currTheta),e[1]+n.currDistance*Math.sin(n.currPhi),e[2]+t*Math.cos(n.currTheta)]}var de=class{constructor(e,t,r){this.meshes=[];this.backdropMeshes=[];this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]};this.lights=[];this.modelRootMatrix=oe();this.clearColor=[0,0,0,0];this.envIntensity=1;this.exposure=1;this.shadowIntensity=0;this.shadowSoftness=.5;this.toneMapping="neutral";this.environmentTexture=null;this.animations=[];this.currentClip=null;this.animationTime=0;this.isPlayingAnimation=!1;this.autoplay=!1;this.animationName="";this.gpuTextures=[];this.availableVariants=[];this.activeVariantName=null;this.gltf=null;this.worldMatrices=[];this.initialNodeTransforms=[];this.projMatrix=oe();this.viewMatrix=oe();this.activeViewMatrix=null;this.modelMatrix=oe();this.mvpMatrix=oe();this.normalMatrix=new Float32Array(9);this.initialTheta=.6;this.initialPhi=.35;this.initialDistance=null;this.customDistance=!1;this.distanceMode="auto";this.initialCustomTarget=null;this.customTarget=null;this.fov=Math.PI/4;this.minTheta=-1/0;this.maxTheta=1/0;this.minPhi=-Math.PI*.48;this.maxPhi=Math.PI*.48;this.minDistanceLimit=null;this.maxDistanceLimit=null;this.activePointers=new Map;this.isPanning=!1;this.targetTheta=.6;this.currTheta=.6;this.targetPhi=.35;this.currPhi=.35;this.targetDistance=3;this.currDistance=3;this.autoRotate=!1;this.autoRotateSpeed=Math.PI/6;this.autoRotateDelay=3e3;this.lastInteractionTime=-1/0;this.turntableRotation=0;this.isPointerDown=!1;this.interactive=!0;this.skyboxTexture=null;this.lastPointerX=0;this.lastPointerY=0;this.totalDragDist=0;this.selectedMeshName="";this.pickFbo=null;this.pickTexture=null;this.pickDepth=null;this.pickFboWidth=0;this.pickFboHeight=0;this.animFrameId=null;this.isVisible=!0;this.xrSessionActive=!1;this.lastTime=0;this.lastReportedTheta=-999;this.lastReportedPhi=-999;this.lastReportedZoom=-999;this.boundPointerDown=null;this.boundPointerMove=null;this.boundPointerUp=null;this.boundWheel=null;this.boundKeyDown=null;this.boundContextMenu=null;this.boundSetCamera=null;this.boundResetCamera=null;this.contextLost=!1;this.lastGlbData=null;this.boundContextLost=null;this.boundContextRestored=null;this.stereoSBS=!1;this.renderErrorReported=!1;this.xrDepthState={enabled:!1,texture:null,uvTransform:oe(),rawValueToMeters:.001,format:0};this.container=e;let i,s;if(t&&typeof t.getContext=="function"?(i=t,s=r):(s=t,i=s?.canvas),!i){let a=e.querySelector("canvas");a||(a=document.createElement("canvas"),a.style.width="100%",a.style.height="100%",a.style.display="block",a.style.touchAction="none",e.prepend(a)),i=a}this.canvas=i,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let o=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!o:o&&(this.autoRotate=!1),this.opts.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=this.opts.autoRotateSpeed),this.opts.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(this.opts.autoRotateDelay)||0)),this.opts.exposure!==void 0&&(this.exposure=Ft(this.opts.exposure)),this.opts.camera&&this.setInitialCamera(this.opts.camera.theta,this.opts.camera.phi,this.opts.camera.distance,this.opts.camera.zoom),this.opts.shadowIntensity!==void 0&&(this.shadowIntensity=Math.max(0,Math.min(1,Number(this.opts.shadowIntensity)||0))),this.opts.shadowSoftness!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(this.opts.shadowSoftness)||0))),this.opts.toneMapping!==void 0&&(this.toneMapping=Ce(this.opts.toneMapping)),this.opts.autoplay!==void 0&&(this.autoplay=this.opts.autoplay),this.opts.animationName!==void 0&&(this.animationName=this.opts.animationName),this.opts.variantName!==void 0&&(this.activeVariantName=this.opts.variantName||null),this.opts.fieldOfView!==void 0&&(this.fov=this.opts.fieldOfView*Math.PI/180),this.opts.distanceMode!==void 0&&(this.distanceMode=this.opts.distanceMode),this.opts.cameraTarget!==void 0&&(this.setTarget(this.opts.cameraTarget[0],this.opts.cameraTarget[1],this.opts.cameraTarget[2]),this.initialCustomTarget=[...this.opts.cameraTarget]),(this.opts.minCameraOrbit||this.opts.maxCameraOrbit)&&this.setOrbitLimits({minTheta:this.opts.minCameraOrbit?.theta,maxTheta:this.opts.maxCameraOrbit?.theta,minPhi:this.opts.minCameraOrbit?.phi,maxPhi:this.opts.maxCameraOrbit?.phi,minDistance:this.opts.minCameraOrbit?.distance,maxDistance:this.opts.maxCameraOrbit?.distance});let c=i.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!c)throw new Error("WebGL2 not supported");this.gl=c,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(e,t){Tr(e,t)}static getDecoder(e){return Ne(e)}setupContextLossHandling(){let e=this.canvas;typeof e?.addEventListener=="function"&&(this.boundContextLost=t=>{t.preventDefault?.(),this.contextLost=!0,this.stop()},this.boundContextRestored=()=>this.restoreContext(),e.addEventListener("webglcontextlost",this.boundContextLost),e.addEventListener("webglcontextrestored",this.boundContextRestored))}initGlState(){let e=this.gl,t=On();this.renderProg=Nt(e,kn,t.fs),this.pickProg=Nt(e,Lr,Dr),this.uRender=kt(e,this.renderProg,t.uniforms),this.uPick=kt(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of ce)t.onContextRestored?.(e,this);this.meshes=[],this.gpuTextures=[],this.environmentTexture=null,this.lastGlbData&&this.loadGLBData(this.lastGlbData,this.lastLimits),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}setupPickingFbo(){let e=this.gl;if(typeof e.createFramebuffer!="function")return;this.pickFbo=e.createFramebuffer(),this.pickTexture=e.createTexture(),this.pickDepth=e.createRenderbuffer();let t=Math.max(1,this.canvas.width),r=Math.max(1,this.canvas.height);this.pickFboWidth=t,this.pickFboHeight=r,e.bindTexture(3553,this.pickTexture),e.texImage2D(3553,0,6408,t,r,0,6408,5121,null),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728),e.bindRenderbuffer(36161,this.pickDepth),e.renderbufferStorage(36161,33189,t,r),e.bindFramebuffer(36160,this.pickFbo),e.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),e.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),e.bindFramebuffer(36160,null)}resizePickingFbo(e,t){if(!this.pickFbo)return;let r=this.gl,i=Math.max(1,e),s=Math.max(1,t);this.pickFboWidth=i,this.pickFboHeight=s,r.bindTexture(3553,this.pickTexture),r.texImage2D(3553,0,6408,i,s,0,6408,5121,null),r.bindRenderbuffer(36161,this.pickDepth),r.renderbufferStorage(36161,33189,i,s)}loadGLBData(e,t){this.lastGlbData=e,this.lastLimits=t;let{meshes:r,bounds:i,lights:s,animations:o,worldMatrices:c,gpuTextures:a,availableVariants:u}=In(this.gl,e,t,()=>this.render());if(this.disposeMeshGpuResources(),this.meshes=r,this.bounds=i,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=s,this.animations=o||[],this.worldMatrices=c||[],this.gpuTextures=a||[],this.availableVariants=u||[],this.gltf=e.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let h of e.gltf.nodes)this.initialNodeTransforms.push({t:h.translation?[h.translation[0],h.translation[1],h.translation[2]]:[0,0,0],r:h.rotation?[h.rotation[0],h.rotation[1],h.rotation[2],h.rotation[3]]:[0,0,0,1],s:h.scale?[h.scale[0],h.scale[1],h.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let h of ce)h.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:i.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let l=e.exposure??e.gltf?.extras?.exposure??e.gltf?.asset?.extras?.exposure;l!==void 0&&(this.exposure=Ft(l));let m=e.environmentIntensity??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.environmentIntensity;m!==void 0&&(this.envIntensity=Math.max(0,Number(m)||0)),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(e){this.loadGLBData(Nn(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(Ae(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=Ae(e),{meshes:i}=In(this.gl,r,zn,()=>this.render());if(t)for(let s of i)s.transform[12]+=t[0],s.transform[13]+=t[1],s.transform[14]+=t[2],ye(s.normalMatrix,s.transform);this.backdropMeshes=i,this.update(0),this.render()}setClearColor(e,t,r,i=1){this.clearColor=[e,t,r,i]}updateMeshTransforms(e){for(let t=0;t<this.meshes.length;t++){let r=this.meshes[t],i;e instanceof Map?i=e.get(r.name)??e.get(t):Array.isArray(e)?i=e[t]:e&&typeof e=="object"&&(Object.prototype.hasOwnProperty.call(e,r.name)?i=e[r.name]:Object.prototype.hasOwnProperty.call(e,t)&&(i=e[t])),i&&i.length===16&&(r.transform.set(i),ye(r.normalMatrix,r.transform))}}bindLights(e=this.uRender){let t=this.gl,r=[.28,.28,.28],i=[],s=[],o=[],c=[];for(let a of this.lights){let u=a.color||[1,1,1],l=a.intensity!==void 0?a.intensity:1;if(a.type==="ambient")r=[u[0]*l,u[1]*l,u[2]*l];else if(a.type==="directional"&&i.length<6){let m=a.direction||[.5,1,.8];i.push(m[0],m[1],m[2]),s.push(u[0]*l,u[1]*l,u[2]*l)}else if(a.type==="point"&&o.length<6){let m=a.position||[0,0,0];o.push(m[0],m[1],m[2]),c.push(u[0]*l,u[1]*l,u[2]*l)}}i.length===0&&(i.push(.5,1,.8),s.push(1,1,1)),t.uniform3fv(e.uAmbientColor,r),t.uniform1i(e.uNumDirLights,i.length/3),i.length>0&&(t.uniform3fv(e.uDirLightDir,i),t.uniform3fv(e.uDirLightColor,s)),t.uniform1i(e.uNumPointLights,o.length/3),o.length>0&&(t.uniform3fv(e.uPointLightPos,o),t.uniform3fv(e.uPointLightColor,c)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=Ft(e)}getExposure(){return this.exposure}setShadow(e,t){this.shadowIntensity=Math.max(0,Math.min(1,Number(e)||0)),t!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(t)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(e){this.toneMapping=Ce(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of ce)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of ce)if(t.setSkyboxImage){await t.setSkyboxImage(this,e);return}}setInteractive(e){this.interactive=e}isInteractive(){return this.interactive}getCameraOrbit(){let e=this.currTheta,t=this.currPhi,r=this.currDistance;return{theta:e,phi:t,radius:r,toString(){return`${e.toFixed(4)}rad ${t.toFixed(4)}rad ${r.toFixed(4)}m`}}}getCameraTarget(){let e=this.customTarget||this.bounds.center;return{x:e[0],y:e[1],z:e[2],toString(){return`${e[0].toFixed(4)}m ${e[1].toFixed(4)}m ${e[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let e=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return e.map((t,r)=>{let i=this.meshes.flatMap(l=>l.primitives.filter(m=>m.materialIndex===r||e.length===1&&m.materialIndex===void 0)),s=i[0],o=s?[...s.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],c=s?s.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,a=s?s.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,u={baseColorFactor:o,metallicFactor:c,roughnessFactor:a,setBaseColorFactor:l=>{let m=[l[0],l[1],l[2],l[3]??1];u.baseColorFactor=m,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=m);for(let h of i)h.baseColor=m;this.render()},setMetallicFactor:l=>{u.metallicFactor=l,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=l);for(let m of i)m.metallic=l;this.render()},setRoughnessFactor:l=>{u.roughnessFactor=l,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=l);for(let m of i)m.roughness=l;this.render()}};return{name:t.name||`Material_${r}`,pbrMetallicRoughness:u}})}playAnimation(e){if(this.animations.length!==0){if(e){let t=this.animations.find(r=>r.name===e);t&&(this.currentClip=t)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(e=>e.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(e){let t=this.applyVariantMaterial(e);return t&&this.gl&&this.render(),t}applyVariantMaterial(e){let t=e===null||e==="",r=-1;if(t)this.activeVariantName=null;else{if(r=this.availableVariants.indexOf(e),r<0)return!1;this.activeVariantName=e}let i=this.gltf?.materials;if(!Array.isArray(i))return t;for(let s of this.meshes)for(let o of s.primitives){let c=o.defaultMaterialIndex;if(!t&&Array.isArray(o.variantMappings)){for(let u of o.variantMappings)if(Array.isArray(u.variants)&&u.variants.includes(r)){c=u.material;break}}let a=c!==void 0?i[c]:void 0;o.materialIndex=a?c:void 0,Object.assign(o,Hn(a,this.gpuTextures)),this.applyPrimitiveProgram(o,o.materialIndex,a??null)}return!0}applyPrimitiveProgram(e,t,r){if(!this.gl||!e.primitiveDef)return;e.programCache??(e.programCache=new Map);let i=t??-1,s=e.programCache.get(i);s||(s=Bn(this.gl,{...e.primitiveDef,material:t},r),e.programCache.set(i,s)),e.customProgram=s.program,e.customUniforms=s.uniforms,e.pluginData&&(e.pluginData.materials=e.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(e){this.autoplay=e,e?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(e){this.animationName=e,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(e)}evaluateAnimation(e){for(let t of ce)if(t.evaluateAnimation){t.evaluateAnimation(this,e);return}}setTarget(e,t,r){this.customTarget=[e,t,r],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(e){let t=Math.max(10,Math.min(90,e));this.fov=t*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(e){if(this.distanceMode=e,!this.customDistance){let t=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=t,this.targetDistance=t,this.currDistance=t,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(e){e.minTheta!==void 0&&(this.minTheta=e.minTheta*Math.PI/180),e.maxTheta!==void 0&&(this.maxTheta=e.maxTheta*Math.PI/180),e.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,e.minPhi*Math.PI/180)),e.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,e.maxPhi*Math.PI/180)),e.minDistance!==void 0&&(this.minDistanceLimit=e.minDistance),e.maxDistance!==void 0&&(this.maxDistanceLimit=e.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){return{minTheta:isFinite(this.minTheta)?this.minTheta*180/Math.PI:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*180/Math.PI:void 0,minPhi:this.minPhi*180/Math.PI,maxPhi:this.maxPhi*180/Math.PI,minDistance:this.minDistanceLimit!==null?this.minDistanceLimit:void 0,maxDistance:this.maxDistanceLimit!==null?this.maxDistanceLimit:void 0}}clampTheta(e){return Math.max(this.minTheta,Math.min(this.maxTheta,e))}clampPhi(e){return Math.max(this.minPhi,Math.min(this.maxPhi,e))}clampDistance(e){let t=this.minDistanceLimit!==null?this.minDistanceLimit:this.bounds?this.bounds.radius*.5:.1,r=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(t,Math.min(r,e))}setCamera(e,t,r,i){e!==void 0&&(this.targetTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.targetPhi=this.clampPhi(t*Math.PI/180)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(r)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/i))}setInitialCamera(e,t,r,i){if(e!==void 0&&(this.initialTheta=this.clampTheta(e*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),t!==void 0&&(this.initialPhi=this.clampPhi(t*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),r!==void 0&&r>0){let s=this.clampDistance(r);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else if(i!==void 0&&i>0){let s=this.clampDistance(this.bounds.radius*2.5/i);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else{this.customDistance=!1;let s=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=s,this.targetDistance=s,this.currDistance=s}this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.initialDistance!==null?this.targetDistance=this.clampDistance(this.initialDistance):this.targetDistance=this.clampDistance(this.bounds.radius*2.5),this.initialCustomTarget?this.customTarget=[...this.initialCustomTarget]:this.customTarget=null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(e,t){let r=oe();ae(r,this.projMatrix,this.viewMatrix);let[i,s,o]=e,c=t?t[0]:0,a=t?t[1]:0,u=t?t[2]:0,l=this.modelRootMatrix;l&&(i=l[0]*e[0]+l[4]*e[1]+l[8]*e[2]+l[12],s=l[1]*e[0]+l[5]*e[1]+l[9]*e[2]+l[13],o=l[2]*e[0]+l[6]*e[1]+l[10]*e[2]+l[14],t&&(c=l[0]*t[0]+l[4]*t[1]+l[8]*t[2],a=l[1]*t[0]+l[5]*t[1]+l[9]*t[2],u=l[2]*t[0]+l[6]*t[1]+l[10]*t[2]));let m=r[0]*i+r[4]*s+r[8]*o+r[12],h=r[1]*i+r[5]*s+r[9]*o+r[13],y=r[2]*i+r[6]*s+r[10]*o+r[14],b=r[3]*i+r[7]*s+r[11]*o+r[15];if(b<=1e-4)return{x:0,y:0,z:1,visible:!1};let d=m/b,g=h/b,T=y/b,P=this.canvas.getBoundingClientRect(),f=P.width||this.canvas.clientWidth||this.canvas.width||300,M=P.height||this.canvas.clientHeight||this.canvas.height||150,p=(d*.5+.5)*f,S=(-g*.5+.5)*M,_=d>=-1.1&&d<=1.1&&g>=-1.1&&g<=1.1&&T>=-1&&T<=1;if(_&&t){let[w,A,L]=$e(this),x=[i-w,s-A,o-L];c*x[0]+a*x[1]+u*x[2]>.05&&(_=!1)}return{x:p,y:S,z:T,visible:_}}setSelectedMesh(e){this.selectedMeshName=e||""}getSelectedMesh(){return this.selectedMeshName}setupEvents(){let e=this.canvas;this.boundContextMenu=t=>{t.preventDefault()},e.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=t=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.lastPointerX=t.clientX,this.lastPointerY=t.clientY,this.totalDragDist=0,this.activePointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.isPanning=t.button===2||t.shiftKey||this.activePointers.size===2,e.setPointerCapture(t.pointerId))},e.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=t=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=this.activePointers.get(t.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},i=t.clientX-r.x,s=t.clientY-r.y;if(this.activePointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.lastPointerX=t.clientX,this.lastPointerY=t.clientY,this.totalDragDist+=Math.hypot(i,s),this.isPanning||t.button===2||t.shiftKey||this.activePointers.size===2){let o=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],c=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],a=this.customTarget?[...this.customTarget]:[...this.bounds.center],u=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;a[0]+=(-i*o[0]+s*c[0])*u,a[1]+=(-i*o[1]+s*c[1])*u,a[2]+=(-i*o[2]+s*c[2])*u,this.customTarget=a}else this.targetTheta=this.clampTheta(this.targetTheta-i*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=t=>{this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.activePointers.delete(t.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(t.pointerId)}catch{}if(this.totalDragDist<5&&t.button===0){let r=e.getBoundingClientRect(),i=Math.floor((t.clientX-r.left)*(e.width/Math.max(r.width,1))),s=Math.floor((t.clientY-r.top)*(e.height/Math.max(r.height,1)));this.performMeshPick(i,s,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=t=>{if(!this.interactive)return;t.preventDefault(),this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=Math.exp(t.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=t=>{let r=t.detail||{};r.reset?this.resetCamera():this.setCamera(r.theta,r.phi,r.distance,r.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),e.tabIndex!==void 0&&e.tabIndex<0&&(e.tabIndex=0),e.getAttribute?.("role")||e.setAttribute?.("role","region"),e.getAttribute?.("aria-label")||e.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=t=>{if(!this.interactive)return;let r=typeof performance<"u"?performance.now():Date.now();switch(t.key){case"ArrowLeft":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta-.1),t.preventDefault();break;case"ArrowRight":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta+.1),t.preventDefault();break;case"ArrowUp":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi+.08),t.preventDefault();break;case"ArrowDown":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi-.08),t.preventDefault();break;case"+":case"=":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*.9),t.preventDefault();break}case"-":case"_":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*1.1),t.preventDefault();break}case"Home":this.lastInteractionTime=r,this.resetCamera(),t.preventDefault();break}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=this.canvas;this.boundContextLost&&(e.removeEventListener("webglcontextlost",this.boundContextLost),this.boundContextLost=null),this.boundContextRestored&&(e.removeEventListener("webglcontextrestored",this.boundContextRestored),this.boundContextRestored=null),this.boundContextMenu&&(e.removeEventListener("contextmenu",this.boundContextMenu),this.boundContextMenu=null),this.boundPointerDown&&(e.removeEventListener("pointerdown",this.boundPointerDown),this.boundPointerDown=null),this.boundPointerMove&&(e.removeEventListener("pointermove",this.boundPointerMove),this.boundPointerMove=null),this.boundPointerUp&&(e.removeEventListener("pointerup",this.boundPointerUp),this.boundPointerUp=null),this.boundWheel&&(e.removeEventListener("wheel",this.boundWheel),this.boundWheel=null),this.boundKeyDown&&(e.removeEventListener("keydown",this.boundKeyDown),this.boundKeyDown=null),this.boundSetCamera&&(this.container.removeEventListener("setCamera",this.boundSetCamera),this.boundSetCamera=null),this.boundResetCamera&&(this.container.removeEventListener("resetCamera",this.boundResetCamera),this.boundResetCamera=null)}raycastFromScreenPoint(e,t){let r=this.canvas,i=r.getBoundingClientRect(),s=r.width||300,o=r.height||300,c=i.width>0?Math.floor((e-i.left)*(s/i.width)):Math.floor(e),a=i.height>0?Math.floor((t-i.top)*(o/i.height)):Math.floor(t);return this.performMeshPick(c,a,!1)}performMeshPick(e,t,r=!0){if(this.meshes.length===0)return null;let i=this.gl,s=Math.max(1,this.canvas.width||300),o=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,s);let c=oe();ae(c,this.projMatrix,this.viewMatrix);let a=[],u=Math.max(0,Math.min(s-1,e)),l=Math.max(0,Math.min(o-1,o-1-t));if(this.pickFbo&&i&&!this.xrSessionActive){(this.pickFboWidth!==s||this.pickFboHeight!==o)&&this.resizePickingFbo(s,o),i.bindFramebuffer(36160,this.pickFbo),i.viewport(0,0,s,o),i.enable(2929),i.clearColor(0,0,0,0),i.clear(16384|256),i.useProgram(this.pickProg);for(let _=0;_<this.meshes.length;_++){let w=this.meshes[_];if(w.visible===!1||w.isPluginMesh)continue;let A=_+1,L=(A&255)/255,x=(A>>8&255)/255,v=(A>>16&255)/255;i.uniform4f(this.uPick.uColorId,L,x,v,1),ae(this.modelMatrix,this.modelRootMatrix,w.transform);let I=w.instanceMatrices;if(I&&I.length>=16){let R=I.length>>4,C=oe();for(let N of w.primitives){i.bindVertexArray(N.vao);for(let F=0;F<R;F++)ae(C,this.modelMatrix,I.subarray(F*16,F*16+16)),ae(this.mvpMatrix,c,C),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),nt(i,N)}}else{ae(this.mvpMatrix,c,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let R of w.primitives)i.bindVertexArray(R.vao),nt(i,R)}}let p=new Uint8Array(4);i.readPixels(u,l,1,1,6408,5121,p),i.bindFramebuffer(36160,null);let S=p[0]+(p[1]<<8)+(p[2]<<16);S>0&&S<=this.meshes.length&&(a=[this.meshes[S-1]])}a.length===0&&(a=this.meshes.filter(p=>p.visible!==!1));let m=null,h=1/0,y=[0,0,0],b=[0,1,0],[d,g,T]=$e(this),P=oe();for(let p of a){ae(P,this.modelRootMatrix,p.transform);let S=p.instanceMatrices,_=S&&S.length>=16?S.length>>4:1;for(let w=0;w<_;w++){S&&S.length>=16?ae(this.modelMatrix,P,S.subarray(w*16,w*16+16)):this.modelMatrix.set(P),ae(this.mvpMatrix,c,this.modelMatrix);let A=oe();if(!Tn(A,this.mvpMatrix))continue;let L=(u+.5)/s*2-1,x=(l+.5)/o*2-1,v=[0,0,0],I=[0,0,0];Dt(v,L,x,-1,A),Dt(I,L,x,1,A);let R=I[0]-v[0],C=I[1]-v[1],N=I[2]-v[2],F=Math.hypot(R,C,N)||1,V=R/F,U=C/F,B=N/F,D={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((z=>{for(let O of p.primitives){if(!O.positions)continue;let X=O.positions,E=O.indices,k=Math.floor(E?E.length/3:X.length/9);for(let G=0;G<k;G++){let W=E?E[G*3]:G*3,j=E?E[G*3+1]:G*3+1,re=E?E[G*3+2]:G*3+2;_n(v[0],v[1],v[2],V,U,B,X[W*3],X[W*3+1],X[W*3+2],X[j*3],X[j*3+1],X[j*3+2],X[re*3],X[re*3+1],X[re*3+2],D,z)}}})(1e-4),isFinite(D.distance)){let z=D.point[0],O=D.point[1],X=D.point[2],E=this.modelMatrix,k=E[0]*z+E[4]*O+E[8]*X+E[12],G=E[1]*z+E[5]*O+E[9]*X+E[13],W=E[2]*z+E[6]*O+E[10]*X+E[14],j=k-d,re=G-g,ue=W-T,q=Math.hypot(j,re,ue);if(q<h){ye(this.normalMatrix,this.modelMatrix);let Z=this.normalMatrix,Y=D.normal[0],ie=D.normal[1],$=D.normal[2],ne=Z[0]*Y+Z[3]*ie+Z[6]*$,te=Z[1]*Y+Z[4]*ie+Z[7]*$,ee=Z[2]*Y+Z[5]*ie+Z[8]*$,se=Math.hypot(ne,te,ee)||1;ne/=se,te/=se,ee/=se,ne*j+te*re+ee*ue>0&&(ne=-ne,te=-te,ee=-ee),m=p,h=Math.round(q*1e3)/1e3,y=[Math.round(k*1e3)/1e3,Math.round(G*1e3)/1e3,Math.round(W*1e3)/1e3],b=[Math.round(ne*1e3)/1e3,Math.round(te*1e3)/1e3,Math.round(ee*1e3)/1e3]}}}}if(!m)return null;let M={meshIndex:this.meshes.indexOf(m),meshName:m.name,nodeIndex:m.nodeIndex,distance:h,hitPoint:y,normal:b,screenX:e,screenY:t};if(r){for(let p of ce)p.onMeshSelect?.(this,M);this.opts.onMeshClick&&this.opts.onMeshClick(M),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:M}))}return M}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let r=Math.max(1,Math.floor(t*.5)),i=e>=r,s=i?e-r:e,o=i?Math.max(1,t-r):r,c=(s+.5)/o*2-1;return Math.floor((c*.5+1)*.5*t)}setStereoSBS(e){this.stereoSBS=!!e,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let e=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),t=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);et(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center;Fe(this.viewMatrix,$e(this),r,[0,1,0]),ae(this.mvpMatrix,this.projMatrix,this.viewMatrix),ye(this.normalMatrix,this.modelMatrix)}resize(){let e=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),t=this.canvas.getBoundingClientRect(),r=Math.max(1,Math.floor(t.width*e)),i=Math.max(1,Math.floor(t.height*e));this.canvas.width!==r||this.canvas.height!==i?(this.canvas.width=r,this.canvas.height=i,this.resizePickingFbo(r,i),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(e){let t=this.xrSessionActive;if(this.xrSessionActive=e,t&&!e){this.xrDepthState.enabled=!1;for(let r of ce)r.onXRSessionEnd?.(this);if(this.lastTime=typeof performance<"u"?performance.now():Date.now(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(r){this.reportRenderError(r)}}}reportRenderError(e){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",e))}stepXRUpdate(e){for(let t of ce)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let e=t=>{if(this.animFrameId===null)return;let r=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(r),this.render()}catch(i){this.reportRenderError(i)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(e))};this.animFrameId=requestAnimationFrame(e)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(e){this.autoRotate=e}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(e){this.autoRotateSpeed=e}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(e){this.autoRotateDelay=Math.max(0,Number(e)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(e=0){this.turntableRotation=Number(e)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let e=Math.cos(this.turntableRotation),t=Math.sin(this.turntableRotation),r=this.bounds.center[0],i=this.bounds.center[2],s=this.modelRootMatrix;s[0]=e,s[1]=0,s[2]=-t,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=t,s[9]=0,s[10]=e,s[11]=0,s[12]=r-(e*r+t*i),s[13]=0,s[14]=i-(-t*r+e*i),s[15]=1}setVisible(e){this.isVisible=e}update(e){for(let o of ce)o.onUpdate?.(this,e);let t=typeof performance<"u"?performance.now():Date.now();if(!this.isPointerDown&&this.autoRotate&&t-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*e,this.updateTurntableMatrix();for(let o of ce)o.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let r=Math.round((this.currTheta*180/Math.PI%360+360)%360),i=Math.round(this.currPhi*180/Math.PI),s=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(r-this.lastReportedTheta)>=1||Math.abs(i-this.lastReportedPhi)>=1||Math.abs(s-this.lastReportedZoom)>=.02){this.lastReportedTheta=r,this.lastReportedPhi=i,this.lastReportedZoom=s;let o={theta:r,phi:i,zoom:s,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(o),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:o}))}}renderXRView(e,t,r,i,s=!0,o=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let c=e?.transform?.inverse?.matrix||this.viewMatrix,a=e?.projectionMatrix||this.projMatrix,u=e?.transform?.position,l=u?[u.x,u.y,u.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):r&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:c,projMatrix:a,eyePos:l,viewport:i,eye:e?.eye||"none",clear:o>0?!1:e?.eye!=="right",isAR:s})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let f=Math.max(2,this.canvas.width||2),M=Math.max(1,this.canvas.height||1),p=Math.max(1,Math.floor(f*.5)),S=Math.max(1,f-p),_=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),w=this.customTarget||this.bounds.center,[A,L,x]=$e(this),v=Math.cos(this.currTheta),I=-Math.sin(this.currTheta),R=.032,C=oe(),N=oe(),F=[A-v*R,L,x-I*R],V=[w[0]-v*R*.25,w[1],w[2]-I*R*.25];et(C,this.fov,p/M,.1,_),Fe(N,F,V,[0,1,0]);let U=oe(),B=oe(),D=[A+v*R,L,x+I*R],H=[w[0]+v*R*.25,w[1],w[2]+I*R*.25];et(U,this.fov,S/M,.1,_),Fe(B,D,H,[0,1,0]),this.render({viewMatrix:N,projMatrix:C,eyePos:F,viewport:[0,0,p,M],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:B,projMatrix:U,eyePos:D,viewport:[p,0,S,M],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,f,M);return}let t=this.gl,r=0,i=0,s=this.canvas.width,o=this.canvas.height;e?.viewport?(r=e.viewport[0],i=e.viewport[1],s=e.viewport[2],o=e.viewport[3],t.viewport(r,i,s,o)):t.viewport(0,0,this.canvas.width,this.canvas.height),t.enable(2929),(!e||e.clear!==!1)&&(e?.isAR?t.clearColor(0,0,0,0):t.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),t.clear(16384|256));let c=oe(),a=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=a,ae(c,e?.projMatrix??this.projMatrix,a);let u=Q().xrDepthShader,l=Sr(this.toneMapping),[m,h,y]=e?e.eyePos:$e(this);for(let f of ce)f.onBeforeDrawScene?.(this,t,c,[m,h,y],l);let b=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&b===0)return;let d=e?.eye||"none",g=!1,T=b>0?[...this.backdropMeshes,...this.meshes]:this.meshes,P=f=>{for(let M=0;M<T.length;M++){let p=T[M];if(p.visible===!1)continue;let S=this.selectedMeshName!==""&&p.name===this.selectedMeshName;M<b||p.worldSpace===!0||p.name==="__xr_reticle__"?this.modelMatrix.set(p.transform):ae(this.modelMatrix,this.modelRootMatrix,p.transform),ae(this.mvpMatrix,c,this.modelMatrix),ye(p.normalMatrix,this.modelMatrix);let _=p.extras?.xr?.stereo||p.userData?.xr?.stereo,w=0,A=0,L=1,x=1;_==="sbs"?(L=.5,w=d==="right"?.5:0):_==="ou"&&(x=.5,A=d==="right"?.5:0);for(let v of p.primitives){let I=!!v.isTransmissive;if(!f&&I){g=!0;continue}if(f&&!I)continue;let R=v.customProgram||this.renderProg,C=v.customUniforms||this.uRender;t.useProgram(R),t.uniform1i(C.uToneMapping,l),t.uniform1f(C.uEnvIntensity,this.envIntensity),C.uExposure&&t.uniform1f(C.uExposure,this.exposure),t.uniform3f(C.uCameraPos,m,h,y),t.uniform1f(C.uEmissive,S?1:0),t.uniformMatrix4fv(C.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(C.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(C.uNormalMatrix,!1,p.normalMatrix),C.uUvTransform&&t.uniform4f(C.uUvTransform,w,A,L,x),C.uViewportSize&&t.uniform2f(C.uViewportSize,Math.max(1,s),Math.max(1,o)),u?.bind(t,C,this.xrDepthState,a,[r,i,Math.max(1,s),Math.max(1,o)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(C.uEnvironmentMap,4),t.uniform1i(C.uHasEnvironmentMap,1)):t.uniform1i(C.uHasEnvironmentMap,0),this.bindLights(C),C.uSectionEnabled&&t.uniform1i(C.uSectionEnabled,0);for(let F of ce)F.onBeforeDrawPrimitive?.(t,R,v,p,this.worldMatrices||[],this.gltf);t.uniform4fv(C.uBaseColor,v.baseColor),t.uniform1f(C.uMetallic,v.metallic),t.uniform1f(C.uRoughness,v.roughness),C.uClearcoat&&t.uniform2f(C.uClearcoat,v.clearcoat??0,v.clearcoatRoughness??.04),v.texture?(t.activeTexture(33984),t.bindTexture(3553,v.texture),t.uniform1i(C.uBaseColorTexture,0),t.uniform1i(C.uHasTexture,1)):t.uniform1i(C.uHasTexture,0),v.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,v.metallicRoughnessTexture),t.uniform1i(C.uMetallicRoughnessTexture,1),t.uniform1i(C.uHasMetallicRoughnessTexture,1)):t.uniform1i(C.uHasMetallicRoughnessTexture,0),v.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,v.normalTexture),t.uniform1i(C.uNormalTexture,2),t.uniform1i(C.uHasNormalTexture,1),t.uniform1f(C.uNormalScale,v.normalScale)):t.uniform1i(C.uHasNormalTexture,0),v.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,v.occlusionTexture),t.uniform1i(C.uOcclusionTexture,3),t.uniform1i(C.uHasOcclusionTexture,1),t.uniform1f(C.uOcclusionStrength,v.occlusionStrength)):t.uniform1i(C.uHasOcclusionTexture,0),t.bindVertexArray(v.vao);let N=p.instanceMatrices;if(N&&N.length>=16&&v.instanced&&C.uInstanced&&C.uViewProj){let F=N.length>>4;t.uniform1i(C.uInstanced,1),t.uniformMatrix4fv(C.uViewProj,!1,c),v.indices?t.drawElementsInstanced(4,v.indexCount,v.indexType,0,F):t.drawArraysInstanced(4,0,v.indexCount,F),t.uniform1i(C.uInstanced,0)}else if(N&&N.length>=16){let F=N.length>>4,V=p.instanceColors,U=oe(),B=new Float32Array(9),D=[v.baseColor[0],v.baseColor[1],v.baseColor[2],v.baseColor[3]];for(let H=0;H<F;H++)ae(U,this.modelMatrix,N.subarray(H*16,H*16+16)),ae(this.mvpMatrix,c,U),ye(B,U),t.uniformMatrix4fv(C.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(C.uModel,!1,U),t.uniformMatrix3fv(C.uNormalMatrix,!1,B),V&&(D[0]=v.baseColor[0]*V[H*3],D[1]=v.baseColor[1]*V[H*3+1],D[2]=v.baseColor[2]*V[H*3+2],D[3]=v.baseColor[3],t.uniform4fv(C.uBaseColor,D)),nt(t,v)}else nt(t,v)}}};if(P(!1),g){for(let f of ce)f.onBeforeTransmissivePass?.(t,this);P(!0)}for(let f of ce)f.onAfterRender?.(t,this,c)}disposeMeshListGpuResources(e,t){Gn(this.gl,e,t)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let e=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let t of ce)t.onDestroy?.(e,this);this.environmentTexture&&(e.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&e.deleteProgram(this.renderProg),this.pickProg&&e.deleteProgram(this.pickProg),this.pickFbo&&e.deleteFramebuffer(this.pickFbo),this.pickTexture&&e.deleteTexture(this.pickTexture),this.pickDepth&&e.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};de.registerPlugin=Ze,de.getRegisteredPlugins=Mn;function kr(n){return n+3&-4}function Ur(n,e=0){let t=(D,H)=>typeof D=="number"&&Number.isFinite(D)?D:H,r=t(n[e+12],0),i=t(n[e+13],0),s=t(n[e+14],0),o=t(n[e+0],1),c=t(n[e+1],0),a=t(n[e+2],0),u=t(n[e+4],0),l=t(n[e+5],1),m=t(n[e+6],0),h=t(n[e+8],0),y=t(n[e+9],0),b=t(n[e+10],1),d=Math.hypot(o,c,a),g=Math.hypot(u,l,m),T=Math.hypot(h,y,b);o*(l*b-y*m)-u*(c*b-y*a)+h*(c*m-l*a)<0&&(d=-d);let f=Math.abs(d)>1e-8?1/d:0,M=Math.abs(g)>1e-8?1/g:0,p=Math.abs(T)>1e-8?1/T:0,S=o*f,_=c*f,w=a*f,A=u*M,L=l*M,x=m*M,v=h*p,I=y*p,R=b*p,C=S+L+R,N=0,F=0,V=0,U=1;if(C>0){let D=.5/Math.sqrt(C+1);U=.25/D,N=(x-I)*D,F=(v-w)*D,V=(_-A)*D}else if(S>L&&S>R){let D=2*Math.sqrt(Math.max(0,1+S-L-R));D>1e-8&&(U=(x-I)/D,N=.25*D,F=(A+_)/D,V=(v+w)/D)}else if(L>R){let D=2*Math.sqrt(Math.max(0,1+L-S-R));D>1e-8&&(U=(v-w)/D,N=(A+_)/D,F=.25*D,V=(x+I)/D)}else{let D=2*Math.sqrt(Math.max(0,1+R-S-L));D>1e-8&&(U=(_-A)/D,N=(v+w)/D,F=(x+I)/D,V=.25*D)}let B=Math.hypot(N,F,V,U);return B>1e-8&&Number.isFinite(B)?(N/=B,F/=B,V/=B,U/=B):(N=0,F=0,V=0,U=1),{t:[r,i,s],r:[N,F,V,U],s:[d,g,T]}}function Or(n){let e={};return n.grab&&(e.interactable={mode:typeof n.grab=="string"?n.grab:"2-hand"},e.movable={scaleInZ:!!n.scale,minScale:typeof n.scale=="object"?n.scale.min??.1:.1,maxScale:typeof n.scale=="object"?n.scale.max??10:10}),n.billboard&&(e.billboard={mode:typeof n.billboard=="string"?n.billboard:"capsule"}),n.follow&&(e.follow={target:typeof n.follow=="object"?n.follow.mode??"head":n.follow}),n.anchor&&(e.anchor={plane:n.anchor}),n.physics&&n.physics!=="none"&&(e.rigidbody={type:n.physics}),e}function Ye(n,e){n.updateMatrixWorld(!0);let t=[],r=0,i=[],s=[],o=[],c=[],a=new Set,u=[],l=[],m=new Map,h=[],y=[];function b(A){let L=m.get(A);if(L!==void 0)return L;L=l.length,m.set(A,L);let x=A,v=x.color?.r??.8,I=x.color?.g??.8,R=x.color?.b??.8,C=x.opacity??1,N={name:x.name||"",pbrMetallicRoughness:{baseColorFactor:[v,I,R,C],metallicFactor:x.metalness??.1,roughnessFactor:x.roughness??.5},doubleSided:x.side===2||!!x.doubleSided};if(x.emissive&&(x.emissive.r>0||x.emissive.g>0||x.emissive.b>0)){let V=x.emissiveIntensity??1;N.emissiveFactor=[x.emissive.r*V,x.emissive.g*V,x.emissive.b*V]}let F={};return x.clearcoat&&x.clearcoat>0&&(F.KHR_materials_clearcoat={clearcoatFactor:x.clearcoat,clearcoatRoughnessFactor:x.clearcoatRoughness||0}),x.sheen&&x.sheen>0&&(F.KHR_materials_sheen={sheenColorFactor:x.sheenColor?[x.sheenColor.r,x.sheenColor.g,x.sheenColor.b]:[1,1,1],sheenRoughnessFactor:x.sheenRoughness||0}),x.transmission&&x.transmission>0&&(F.KHR_materials_transmission={transmissionFactor:x.transmission}),x.thickness&&x.thickness>0&&(F.KHR_materials_volume={thicknessFactor:x.thickness,attenuationDistance:x.attenuationDistance??1/0,attenuationColor:x.attenuationColor?[x.attenuationColor.r,x.attenuationColor.g,x.attenuationColor.b]:[1,1,1]}),x.ior!==void 0&&x.ior!==1.5&&(F.KHR_materials_ior={ior:x.ior}),x.dispersion&&x.dispersion>0&&(F.KHR_materials_dispersion={dispersion:x.dispersion}),x.iridescence&&x.iridescence>0&&(F.KHR_materials_iridescence={iridescenceFactor:x.iridescence,iridescenceIor:x.iridescenceIOR??1.3}),Object.keys(F).length>0&&(N.extensions=F),l.push(N),L}function d(A,L){let x=new Uint8Array(A.buffer,A.byteOffset,A.byteLength),v=kr(x.byteLength),I=new Uint8Array(v);I.set(x),t.push(I);let R=i.length;return i.push({buffer:0,byteOffset:r,byteLength:x.byteLength,target:L}),r+=v,R}function g(A,L,x,v,I,R,C){let N=d(A,x),F=s.length,V={bufferView:N,byteOffset:0,componentType:v,count:I,type:L};return R&&(V.min=R),C&&(V.max=C),s.push(V),F}n.traverse(A=>{(A.isLight||A.color&&A.intensity!==void 0)&&y.push({type:A.type,color:[A.color.r,A.color.g,A.color.b],intensity:A.intensity,position:[A.position.x,A.position.y,A.position.z]})});let T=[];function P(A){let L={name:A.name||""},x=A.position,v=A.quaternion,I=A.scale;if((x.x||x.y||x.z)&&(L.translation=[x.x,x.y,x.z]),(v.x||v.y||v.z||v.w!==1)&&(L.rotation=[v.x,v.y,v.z,v.w]),(I.x!==1||I.y!==1||I.z!==1)&&(L.scale=[I.x,I.y,I.z]),A.userData&&Object.keys(A.userData).length>0&&(L.extras=JSON.parse(JSON.stringify(A.userData,(C,N)=>{if(!(C==="__proto__"||C==="prototype"||C==="constructor"))return typeof N=="function"?void 0:N})),A.userData.xr)){let C=Or(A.userData.xr);L.extensions={...L.extensions||{},MOZ_hubs_components:C,ANDROID_xr_scenecore:C},Q().xrTraitSerializer?.gltfNode(L,A.userData.xr),a.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(A.geometry){let C=A.geometry,N=C.attributes.position;if(N&&N.count>0){let F=[1/0,1/0,1/0],V=[-1/0,-1/0,-1/0];for(let O=0;O<N.count;O++){let X=N.getX(O),E=N.getY(O),k=N.getZ(O);X<F[0]&&(F[0]=X),X>V[0]&&(V[0]=X),E<F[1]&&(F[1]=E),E>V[1]&&(V[1]=E),k<F[2]&&(F[2]=k),k>V[2]&&(V[2]=k)}let B={attributes:{POSITION:g(N.array,"VEC3",34962,5126,N.count,F,V)}};if(C.attributes.normal&&(B.attributes.NORMAL=g(C.attributes.normal.array,"VEC3",34962,5126,C.attributes.normal.count)),C.attributes.uv&&(B.attributes.TEXCOORD_0=g(C.attributes.uv.array,"VEC2",34962,5126,C.attributes.uv.count)),C.index){let O=C.index.array instanceof Uint32Array;B.indices=g(C.index.array,"SCALAR",34963,O?5125:5123,C.index.count)}A.material&&(B.material=b(A.material));let D=A.userData?.variants;if(D&&typeof D=="object"){let O=new Map;for(let X of Object.keys(D)){if(!X||X==="__proto__"||X==="constructor"||X==="prototype")continue;let E=D[X];if(!E||typeof E!="object")continue;let k=h.indexOf(X);if(k===-1&&h.length<256&&(k=h.length,h.push(X)),k===-1)continue;let G=b(E),W=O.get(G);W||(W=[],O.set(G,W)),W.push(k)}if(O.size>0){let X=[];for(let[E,k]of O.entries())X.push({material:E,variants:k});B.extensions={...B.extensions||{},KHR_materials_variants:{mappings:X}},a.add("KHR_materials_variants")}}let H=A;if(H.isInstancedMesh&&typeof H.count=="number"&&H.count>0&&H.instanceMatrix?.array){let O=Math.min(1e4,Math.floor(H.count)),X=H.instanceMatrix.array,E=new Float32Array(O*3),k=new Float32Array(O*4),G=new Float32Array(O*3);for(let j=0;j<O;j++){let{t:re,r:ue,s:q}=Ur(X,j*16);E[j*3]=re[0],E[j*3+1]=re[1],E[j*3+2]=re[2],k[j*4]=ue[0],k[j*4+1]=ue[1],k[j*4+2]=ue[2],k[j*4+3]=ue[3],G[j*3]=q[0],G[j*3+1]=q[1],G[j*3+2]=q[2]}let W={TRANSLATION:g(E,"VEC3",0,5126,O),ROTATION:g(k,"VEC4",0,5126,O),SCALE:g(G,"VEC3",0,5126,O)};if(H.instanceColor?.array&&H.instanceColor.array.length>=O*3){let j=new Float32Array(H.instanceColor.array.subarray(0,O*3));W._COLOR_0=g(j,"VEC3",0,5126,O)}L.extensions={...L.extensions||{},EXT_mesh_gpu_instancing:{attributes:W}},a.add("EXT_mesh_gpu_instancing")}let z=o.length;o.push({primitives:[B],name:A.name,...L.extras?{extras:L.extras}:{}}),L.mesh=z}}let R=c.length;if(c.push(L),u.push(A),A.children.length>0){L.children=[];for(let C of A.children)L.children.push(P(C))}return R}for(let A of n.children)T.push(P(A));let f=e?.animateCallback||e?.animateFn||(typeof n.userData?.animate=="function"?n.userData.animate:typeof n.__animateFn=="function"?n.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0),M=[];if(typeof f=="function"&&u.length>0){let A=e?.duration??4,L=e?.fps??15,x=Math.max(2,Math.round(A*L)+1),v=new Float32Array(x),I=u.map(D=>({px:D.position.x,py:D.position.y,pz:D.position.z,qx:D.quaternion.x,qy:D.quaternion.y,qz:D.quaternion.z,qw:D.quaternion.w,sx:D.scale.x,sy:D.scale.y,sz:D.scale.z})),R=u.map(()=>new Float32Array(x*3)),C=u.map(()=>new Float32Array(x*4)),N=u.map(()=>new Float32Array(x*3));for(let D=0;D<x;D++){let H=D/(x-1)*A;v[D]=H;try{f(H)}catch{}for(let z=0;z<u.length;z++){let O=u[z];R[z][D*3]=O.position.x,R[z][D*3+1]=O.position.y,R[z][D*3+2]=O.position.z,C[z][D*4]=O.quaternion.x,C[z][D*4+1]=O.quaternion.y,C[z][D*4+2]=O.quaternion.z,C[z][D*4+3]=O.quaternion.w,N[z][D*3]=O.scale.x,N[z][D*3+1]=O.scale.y,N[z][D*3+2]=O.scale.z}}for(let D=0;D<u.length;D++){let H=u[D],z=I[D];H.position.set(z.px,z.py,z.pz),H.quaternion.set(z.qx,z.qy,z.qz,z.qw),H.scale.set(z.sx,z.sy,z.sz)}n.updateMatrixWorld(!0);let F=null,V=()=>(F===null&&(F=g(v,"SCALAR",0,5126,x,[0],[A])),F),U=[],B=[];for(let D=0;D<u.length;D++){let H=I[D],z=!1,O=!1,X=!1;for(let E=0;E<x;E++)(Math.abs(R[D][E*3]-H.px)>1e-4||Math.abs(R[D][E*3+1]-H.py)>1e-4||Math.abs(R[D][E*3+2]-H.pz)>1e-4)&&(z=!0),(Math.abs(C[D][E*4]-H.qx)>1e-4||Math.abs(C[D][E*4+1]-H.qy)>1e-4||Math.abs(C[D][E*4+2]-H.qz)>1e-4||Math.abs(C[D][E*4+3]-H.qw)>1e-4)&&(O=!0),(Math.abs(N[D][E*3]-H.sx)>1e-4||Math.abs(N[D][E*3+1]-H.sy)>1e-4||Math.abs(N[D][E*3+2]-H.sz)>1e-4)&&(X=!0);if(z){let E=g(R[D],"VEC3",0,5126,x),k=U.length;U.push({input:V(),interpolation:"LINEAR",output:E}),B.push({sampler:k,target:{node:D,path:"translation"}})}if(O){let E=g(C[D],"VEC4",0,5126,x),k=U.length;U.push({input:V(),interpolation:"LINEAR",output:E}),B.push({sampler:k,target:{node:D,path:"rotation"}})}if(X){let E=g(N[D],"VEC3",0,5126,x),k=U.length;U.push({input:V(),interpolation:"LINEAR",output:E}),B.push({sampler:k,target:{node:D,path:"scale"}})}}B.length>0&&M.push({name:"ProceduralLoop",samplers:U,channels:B})}let p=En(c,o,n.userData),S={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:n.environmentIntensity}},scenes:[{nodes:T}],scene:0,nodes:c,meshes:o,materials:l,accessors:s,bufferViews:i,buffers:[{byteLength:r}],...M.length>0?{animations:M}:{},...p||a.size>0?{extensionsUsed:[...p?["KHR_interactivity"]:[],...a]}:{},...p||h.length>0?{extensions:{...p?{KHR_interactivity:p}:{},...h.length>0?{KHR_materials_variants:{variants:h.map(A=>({name:A}))}}:{}}}:{}},_=new Uint8Array(r),w=0;for(let A of t)_.set(A,w),w+=A.byteLength;return{gltf:S,bin:_.buffer,lights:y,environmentIntensity:n.environmentIntensity}}function it(n){return new TextEncoder().encode(n)}function st(n,e){let{gltf:t,bin:r}=Ye(n,e),i=JSON.stringify(t),s=it(i),o=(4-s.byteLength%4)%4,c=s.byteLength+o,a=20+c+8+r.byteLength,u=new Uint8Array(a),l=new DataView(u.buffer);l.setUint32(0,1179937895,!0),l.setUint32(4,2,!0),l.setUint32(8,a,!0),l.setUint32(12,c,!0),l.setUint32(16,1313821514,!0),u.set(s,20);for(let h=0;h<o;h++)u[20+s.byteLength+h]=32;let m=20+c;return l.setUint32(m,r.byteLength,!0),l.setUint32(m+4,5130562,!0),u.set(new Uint8Array(r),m+8),u}function Br(n,e){n.updateMatrixWorld(!0);let t=[];return n.traverse(r=>{if(r.geometry){let i=r.geometry,s=i.attributes.position;if(!s||s.count===0)return;let o=s.count,c=new Float32Array(o*3),a=r.matrixWorld.elements;for(let w=0;w<o;w++){let A=s.getX(w),L=s.getY(w),x=s.getZ(w);c[w*3]=a[0]*A+a[4]*L+a[8]*x+a[12],c[w*3+1]=a[1]*A+a[5]*L+a[9]*x+a[13],c[w*3+2]=a[2]*A+a[6]*L+a[10]*x+a[14]}let u;if(i.attributes.normal){let w=i.attributes.normal;u=new Float32Array(o*3);let A=new Float32Array(9);ye(A,a);for(let L=0;L<o;L++){let x=w.getX(L),v=w.getY(L),I=w.getZ(L),R=A[0]*x+A[3]*v+A[6]*I,C=A[1]*x+A[4]*v+A[7]*I,N=A[2]*x+A[5]*v+A[8]*I,F=Math.hypot(R,C,N)||1;u[L*3]=R/F,u[L*3+1]=C/F,u[L*3+2]=N/F}}let l;if(i.attributes.uv){let w=i.attributes.uv;l=new Float32Array(o*2);for(let A=0;A<o;A++)l[A*2]=w.getX(A),l[A*2+1]=w.getY(A)}let m;if(i.index)m=i.index.array;else{m=o>65535?new Uint32Array(o):new Uint16Array(o);for(let w=0;w<o;w++)m[w]=w}let h="DefaultMaterial",y=[.8,.8,.8],b=.5,d=.1,g=0,T=0,P=1.5,f=1,M=[0,0,0];if(r.material){let w=r.material;h=w.name||`Material_${t.length}`,w.color&&(y=[w.color.r,w.color.g,w.color.b]),typeof w.roughness=="number"&&(b=w.roughness),typeof w.metalness=="number"&&(d=w.metalness),typeof w.clearcoat=="number"&&(g=w.clearcoat),typeof w.clearcoatRoughness=="number"&&(T=w.clearcoatRoughness),typeof w.ior=="number"&&(P=w.ior);let A=typeof w.opacity=="number"?w.opacity:1,L=typeof w.transmission=="number"?w.transmission:0;if(f=A*(1-L),w.emissive&&(w.emissive.r>0||w.emissive.g>0||w.emissive.b>0)){let x=w.emissiveIntensity??1;M=[w.emissive.r*x,w.emissive.g*x,w.emissive.b*x]}}let p,S=e?.animateCallback||e?.animateFn||(typeof n.userData?.animate=="function"?n.userData.animate:typeof n.__animateFn=="function"?n.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0);if(typeof S=="function"){let w=e?.duration??4,A=e?.fps??4,L=Math.max(2,Math.round(w*A)+1),x=[],v=[],I=[],R=[],C=[r.position.x,r.position.y,r.position.z],N=[r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w],F=[r.scale.x,r.scale.y,r.scale.z],V=!1;for(let U=0;U<L;U++){let B=U/(L-1)*w;x.push(B);try{S(B)}catch{}v.push([r.position.x,r.position.y,r.position.z]),I.push([r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w]),R.push([r.scale.x,r.scale.y,r.scale.z]),(Math.abs(r.position.x-C[0])>1e-4||Math.abs(r.position.y-C[1])>1e-4||Math.abs(r.position.z-C[2])>1e-4||Math.abs(r.quaternion.x-N[0])>1e-4||Math.abs(r.quaternion.y-N[1])>1e-4||Math.abs(r.quaternion.z-N[2])>1e-4||Math.abs(r.quaternion.w-N[3])>1e-4||Math.abs(r.scale.x-F[0])>1e-4)&&(V=!0)}r.position.set(C[0],C[1],C[2]),r.quaternion.set(N[0],N[1],N[2],N[3]),r.scale.set(F[0],F[1],F[2]),V&&(p={times:x,translations:v,rotations:I,scales:R})}let _=r;if(_.isInstancedMesh&&typeof _.count=="number"&&_.count>0&&_.instanceMatrix?.array){let w=Math.min(1e3,Math.floor(_.count)),A=_.instanceMatrix.array,L=_.instanceColor?.array,x=r.name||`Mesh_${t.length}`,v=new Float32Array(16),I=new Float32Array(9);for(let R=0;R<w;R++){let C=A.subarray(R*16,(R+1)*16);ae(v,a,C);let N=new Float32Array(o*3);for(let B=0;B<o;B++){let D=s.getX(B),H=s.getY(B),z=s.getZ(B);N[B*3]=v[0]*D+v[4]*H+v[8]*z+v[12],N[B*3+1]=v[1]*D+v[5]*H+v[9]*z+v[13],N[B*3+2]=v[2]*D+v[6]*H+v[10]*z+v[14]}let F;if(i.attributes.normal){let B=i.attributes.normal;F=new Float32Array(o*3),ye(I,v);for(let D=0;D<o;D++){let H=B.getX(D),z=B.getY(D),O=B.getZ(D),X=I[0]*H+I[3]*z+I[6]*O,E=I[1]*H+I[4]*z+I[7]*O,k=I[2]*H+I[5]*z+I[8]*O,G=Math.hypot(X,E,k)||1;F[D*3]=X/G,F[D*3+1]=E/G,F[D*3+2]=k/G}}let V=y,U=h;L&&L.length>=(R+1)*3&&(V=[y[0]*L[R*3],y[1]*L[R*3+1],y[2]*L[R*3+2]],U=`${h}_inst_${R}`),t.push({name:`${x}_${R}`,positions:N,indices:m,normals:F,uvs:l,materialName:U,color:V,roughness:b,metallic:d,clearcoat:g,clearcoatRoughness:T,ior:P,opacity:f,emissiveColor:M,xrTraits:r.userData?.xr})}return}t.push({name:r.name||`Mesh_${t.length}`,positions:c,indices:m,normals:u,uvs:l,materialName:h,color:y,roughness:b,metallic:d,clearcoat:g,clearcoatRoughness:T,ior:P,opacity:f,emissiveColor:M,xrTraits:r.userData?.xr,timeSamples:p})}}),t}function $n(n){let e=[],t=n.gltf,r=Q().decoders.get("meshopt");r&&typeof r.decodeBufferViews=="function"&&r.decodeBufferViews(t,n);let i=n.bin,s=i instanceof ArrayBuffer?i:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),o=t.accessors||[],c=t.bufferViews||[],a=t.materials||[],u=t.meshes||[],l=t.nodes||[];function m(b){let d=o[b];if(!d)throw new Error(`Accessor ${b} not found`);let g=c[d.bufferView||0],T=(g.byteOffset||0)+(d.byteOffset||0),P=g.byteLength||0,f=s.slice(T,T+P);return{acc:d,buffer:f}}let h=new Map;if(l.length>0){let b=tt(t);for(let d=0;d<b.length;d++)h.set(d,b[d])}function y(b,d,g,T){let P=u[b];if(!P)return;let f=new Float32Array(9);ye(f,d);for(let M=0;M<(P.primitives||[]).length;M++){let p=P.primitives[M],S=p.attributes?.POSITION;if(S===void 0)continue;let{acc:_,buffer:w}=m(S),A=new Float32Array(w,0,_.count*3),L=new Float32Array(A.length);for(let E=0;E<_.count;E++){let k=A[E*3],G=A[E*3+1],W=A[E*3+2];L[E*3]=d[0]*k+d[4]*G+d[8]*W+d[12],L[E*3+1]=d[1]*k+d[5]*G+d[9]*W+d[13],L[E*3+2]=d[2]*k+d[6]*G+d[10]*W+d[14]}let x,v=p.attributes?.NORMAL;if(v!==void 0){let{acc:E,buffer:k}=m(v),G=new Float32Array(k,0,E.count*3);x=new Float32Array(G.length);for(let W=0;W<E.count;W++){let j=G[W*3],re=G[W*3+1],ue=G[W*3+2],q=f[0]*j+f[3]*re+f[6]*ue,Z=f[1]*j+f[4]*re+f[7]*ue,Y=f[2]*j+f[5]*re+f[8]*ue,ie=Math.hypot(q,Z,Y)||1;x[W*3]=q/ie,x[W*3+1]=Z/ie,x[W*3+2]=Y/ie}}let I,R=p.attributes?.TEXCOORD_0;if(R!==void 0){let{acc:E,buffer:k}=m(R);I=new Float32Array(k,0,E.count*2)}let C;if(p.indices!==void 0){let{acc:E,buffer:k}=m(p.indices);E.componentType===5125?C=new Uint32Array(k,0,E.count):C=new Uint16Array(k,0,E.count);let G=_.count;for(let W of C)if(W>=G)throw new Error(`SecurityError: Index buffer value (${W}) out of vertex bounds [0, ${G}).`)}else{let E=_.count;C=E>65535?new Uint32Array(E):new Uint16Array(E);for(let k=0;k<E;k++)C[k]=k}let N="DefaultMaterial",F=[.8,.8,.8],V=.5,U=.1,B=0,D=0,H=1.5,z=1,O=[0,0,0];if(p.material!==void 0&&a[p.material]){let E=a[p.material];N=E.name||`Material_${p.material}`;let k=E.pbrMetallicRoughness||{},G=1;Array.isArray(k.baseColorFactor)&&(F=[k.baseColorFactor[0],k.baseColorFactor[1],k.baseColorFactor[2]],typeof k.baseColorFactor[3]=="number"&&(G=k.baseColorFactor[3])),typeof k.roughnessFactor=="number"&&(V=k.roughnessFactor),typeof k.metallicFactor=="number"&&(U=k.metallicFactor),Array.isArray(E.emissiveFactor)&&E.emissiveFactor.length>=3&&(O=[E.emissiveFactor[0],E.emissiveFactor[1],E.emissiveFactor[2]]);let W=E.extensions||{};W.KHR_materials_clearcoat&&(B=W.KHR_materials_clearcoat.clearcoatFactor??0,D=W.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),W.KHR_materials_ior&&typeof W.KHR_materials_ior.ior=="number"&&(H=W.KHR_materials_ior.ior);let j=W.KHR_materials_transmission?.transmissionFactor??0;z=G*(1-j)}let X=(P.primitives||[]).length>1?`${g}_p${M}`:g;e.push({name:X,positions:L,indices:C,normals:x,uvs:I,materialName:N,color:F,roughness:V,metallic:U,clearcoat:B,clearcoatRoughness:D,ior:H,opacity:z,emissiveColor:O,xrTraits:T?.xr||P.extras?.xr})}}if(l.length>0)for(let b=0;b<l.length;b++){let d=l[b];if(d.mesh!==void 0&&d.mesh<u.length){let g=h.get(b)||oe(),T=d.name||u[d.mesh].name||`Node_${b}`,P=d.extensions?.EXT_mesh_gpu_instancing?.attributes;if(P&&typeof P=="object"){let f=P.TRANSLATION,M=P.ROTATION,p=P.SCALE,S=f!==void 0?(()=>{let{acc:L,buffer:x}=m(f);return new Float32Array(x,0,L.count*3)})():null,_=M!==void 0?(()=>{let{acc:L,buffer:x}=m(M);return new Float32Array(x,0,L.count*4)})():null,w=p!==void 0?(()=>{let{acc:L,buffer:x}=m(p);return new Float32Array(x,0,L.count*3)})():null,A=Math.min(1e3,S?S.length/3:_?_.length/4:w?w.length/3:0);if(A>0){let L=new Float32Array(16),x=new Float32Array(16);for(let v=0;v<A;v++){let I=S?[S[v*3],S[v*3+1],S[v*3+2]]:[0,0,0],R=_?[_[v*4],_[v*4+1],_[v*4+2],_[v*4+3]]:[0,0,0,1],C=w?[w[v*3],w[v*3+1],w[v*3+2]]:[1,1,1];_e(L,R,I,C),ae(x,g,L),y(d.mesh,x,`${T}_${v}`,d.extras)}continue}}y(d.mesh,g,T,d.extras)}}else{let b=oe();for(let d=0;d<u.length;d++){let g=u[d].name||`Mesh_${d}`;y(d,b,g,u[d].extras)}}return e}function Ut(n,e){if(!n||typeof n!="string")return e;let t=n.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(t)&&(t="_"+t),t||e}function Xn(n){return String(n??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function K(n){if(!Number.isFinite(n)||Math.abs(n)<1e-7)return"0";let e=Number(n.toFixed(5)).toString();return e.indexOf(".")===-1?`${e}.0`:e}function Wn(n){let e=n.length/3,t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${K(n[r*3])}, ${K(n[r*3+1])}, ${K(n[r*3+2])})`;return t.join(", ")}function Vr(n,e){let t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${K(n[r*2])}, ${K(1-n[r*2+1])})`;return t.join(", ")}function zr(n){return Array.from(n).join(", ")}function Ot(n){let e=new Map;for(let a of n){let u=Ut(a.materialName,"DefaultMaterial");e.has(u)||e.set(u,{color:a.color||[.8,.8,.8],roughness:a.roughness??.5,metallic:a.metallic??0,clearcoat:a.clearcoat??0,clearcoatRoughness:a.clearcoatRoughness??0,ior:a.ior??1.5,opacity:a.opacity??1,emissiveColor:a.emissiveColor||[0,0,0]})}let t=0,r=null;for(let a of n){if(a.timeSamples&&a.timeSamples.times.length>0){let u=a.timeSamples.times[a.timeSamples.times.length-1];u>t&&(t=u)}a.xrTraits?.anchor&&!r&&(r=a.xrTraits.anchor==="vertical"||a.xrTraits.anchor==="wall"?"vertical":"horizontal")}let i="";t>0&&(i=`startTimeCode = 0
|
|
253
|
+
endTimeCode = ${K(t)}
|
|
236
254
|
timeCodesPerSecond = 1.0
|
|
237
255
|
`);let s="";r&&(s=`uniform token preliminary:anchoring:type = "plane"
|
|
238
256
|
uniform token preliminary:planeAnchoring:alignment = "${r}"
|
|
@@ -249,61 +267,61 @@ kind = "component"
|
|
|
249
267
|
{
|
|
250
268
|
${s}def Scope "Materials"
|
|
251
269
|
{
|
|
252
|
-
`;for(let[
|
|
253
|
-
`,g+=`float inputs:clearcoatRoughness = ${
|
|
254
|
-
`),
|
|
255
|
-
`),
|
|
256
|
-
`),(
|
|
257
|
-
`),o+=`def Material "${
|
|
270
|
+
`;for(let[a,u]of e.entries()){let[l,m,h]=u.color,[y,b,d]=u.emissiveColor,g="";u.clearcoat>0&&(g+=`float inputs:clearcoat = ${K(u.clearcoat)}
|
|
271
|
+
`,g+=`float inputs:clearcoatRoughness = ${K(u.clearcoatRoughness)}
|
|
272
|
+
`),u.ior!==1.5&&(g+=`float inputs:ior = ${K(u.ior)}
|
|
273
|
+
`),u.opacity<1&&(g+=`float inputs:opacity = ${K(u.opacity)}
|
|
274
|
+
`),(y>0||b>0||d>0)&&(g+=`color3f inputs:emissiveColor = (${K(y)}, ${K(b)}, ${K(d)})
|
|
275
|
+
`),o+=`def Material "${a}"
|
|
258
276
|
{
|
|
259
277
|
def Shader "PBRShader"
|
|
260
278
|
{
|
|
261
279
|
uniform token info:id = "UsdPreviewSurface"
|
|
262
|
-
color3f inputs:diffuseColor = (${
|
|
263
|
-
float inputs:metallic = ${
|
|
264
|
-
float inputs:roughness = ${
|
|
280
|
+
color3f inputs:diffuseColor = (${K(l)}, ${K(m)}, ${K(h)})
|
|
281
|
+
float inputs:metallic = ${K(u.metallic)}
|
|
282
|
+
float inputs:roughness = ${K(u.roughness)}
|
|
265
283
|
${g}token outputs:surface
|
|
266
284
|
}
|
|
267
|
-
token outputs:surface.connect = </Root/Materials/${
|
|
285
|
+
token outputs:surface.connect = </Root/Materials/${a}/PBRShader.outputs:surface>
|
|
268
286
|
}
|
|
269
287
|
`}o+=`}
|
|
270
288
|
def Scope "Meshes"
|
|
271
289
|
{
|
|
272
|
-
`;let
|
|
290
|
+
`;let c=new Set;for(let a=0;a<n.length;a++){let u=n[a],l=u.positions.length/3,m=1/0,h=1/0,y=1/0,b=-1/0,d=-1/0,g=-1/0;for(let _=0;_<l;_++){let w=u.positions[_*3],A=u.positions[_*3+1],L=u.positions[_*3+2];w<m&&(m=w),w>b&&(b=w),A<h&&(h=A),A>d&&(d=A),L<y&&(y=L),L>g&&(g=L)}isFinite(m)||(m=h=y=-1,b=d=g=1);let T=Math.floor(u.indices.length/3),P=Ut(u.materialName,"DefaultMaterial"),f=Ut(u.name,`Mesh_${a}`);c.has(f)&&(f=`${f}_${a}`),c.add(f);let M=T>0?T===1?"3":"3, ".repeat(T-1)+"3":"",p=u.xrTraits,S="";if(p){let _=[];p.physics&&p.physics!=="none"&&_.push('prepend apiSchemas = ["PhysicsBodyAPI", "PhysicsCollisionAPI"]');let w=Q().xrTraitSerializer?.usdLines(p,Xn)??[];if(!w.length)for(let A of["grab","billboard","follow","anchor","physics"]){let L=A==="follow"&&typeof p.follow=="object"?p.follow.mode??"head":p[A];L!==void 0&&w.push(`string ${A} = "${Xn(L)}"`)}w.length>0&&_.push(`customData = {
|
|
273
291
|
dictionary xr = {
|
|
274
|
-
${
|
|
292
|
+
${w.join(`
|
|
275
293
|
`)}
|
|
276
294
|
}
|
|
277
|
-
}`),
|
|
278
|
-
${
|
|
295
|
+
}`),_.length>0&&(S=` (
|
|
296
|
+
${_.join(`
|
|
279
297
|
`)}
|
|
280
|
-
)`)}if(o+=`def Mesh "${
|
|
298
|
+
)`)}if(o+=`def Mesh "${f}"${S}
|
|
281
299
|
{
|
|
282
|
-
`,
|
|
283
|
-
bool physics:kinematicEnabled = ${
|
|
300
|
+
`,p?.physics&&p.physics!=="none"){let _=p.physics==="static"?"true":"false";o+=`bool physics:rigidBodyEnabled = true
|
|
301
|
+
bool physics:kinematicEnabled = ${_}
|
|
284
302
|
bool physics:collisionEnabled = true
|
|
285
|
-
`}if(
|
|
286
|
-
quatf xformOp:orient.timeSamples = { ${
|
|
287
|
-
double3 xformOp:scale.timeSamples = { ${
|
|
303
|
+
`}if(u.timeSamples&&u.timeSamples.times.length>0){let _=u.timeSamples,w=_.times.map((x,v)=>{let I=_.translations?.[v]||[0,0,0];return`${K(x)}: (${K(I[0])}, ${K(I[1])}, ${K(I[2])})`}).join(", "),A=_.times.map((x,v)=>{let I=_.rotations?.[v]||[0,0,0,1];return`${K(x)}: (${K(I[3])}, ${K(I[0])}, ${K(I[1])}, ${K(I[2])})`}).join(", "),L=_.times.map((x,v)=>{let I=_.scales?.[v]||[1,1,1];return`${K(x)}: (${K(I[0])}, ${K(I[1])}, ${K(I[2])})`}).join(", ");o+=`double3 xformOp:translate.timeSamples = { ${w} }
|
|
304
|
+
quatf xformOp:orient.timeSamples = { ${A} }
|
|
305
|
+
double3 xformOp:scale.timeSamples = { ${L} }
|
|
288
306
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:orient", "xformOp:scale"]
|
|
289
|
-
`}o+=`float3[] extent = [(${
|
|
307
|
+
`}o+=`float3[] extent = [(${K(m)}, ${K(h)}, ${K(y)}), (${K(b)}, ${K(d)}, ${K(g)})]
|
|
290
308
|
int[] faceVertexCounts = [${M}]
|
|
291
|
-
int[] faceVertexIndices = [${
|
|
292
|
-
point3f[] points = [${
|
|
293
|
-
`,
|
|
309
|
+
int[] faceVertexIndices = [${zr(u.indices)}]
|
|
310
|
+
point3f[] points = [${Wn(u.positions)}]
|
|
311
|
+
`,u.normals&&u.normals.length===u.positions.length&&(o+=`normal3f[] normals = [${Wn(u.normals)}] (
|
|
294
312
|
interpolation = "vertex"
|
|
295
313
|
)
|
|
296
|
-
`),
|
|
314
|
+
`),u.uvs&&u.uvs.length===l*2&&(o+=`texCoord2f[] primvars:st = [${Vr(u.uvs,l)}] (
|
|
297
315
|
interpolation = "vertex"
|
|
298
316
|
)
|
|
299
317
|
`),o+=`rel material:binding = </Root/Materials/${P}>
|
|
300
318
|
}
|
|
301
319
|
`}return o+=`}
|
|
302
320
|
}
|
|
303
|
-
`,o}function Wn(n,e){if(n&&typeof n.traverse=="function"){let i=Nr(n,e);return zt(i)}let t=Te(n),r=Gn(t);return zt(r)}var ut=null;function $n(n){if(!ut){ut=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let i=0;i<8;i++)r=r&1?3988292384^r>>>1:r>>>1;ut[t]=r}}let e=4294967295;for(let t=0;t<n.length;t++)e=ut[(e^n[t])&255]^e>>>8;return(e^4294967295)>>>0}function Ht(n){let e=[],t=0,r=[];for(let l of n){let h=lt(l.filename),m=$n(l.data),v=l.data.length,b=30+h.length,d=t+b,g=0,I=d%64;I!==0&&(g=64-I);let P=new Uint8Array(b+g),p=new DataView(P.buffer);p.setUint32(0,67324752,!0),p.setUint16(4,20,!0),p.setUint16(6,0,!0),p.setUint16(8,0,!0),p.setUint16(10,0,!0),p.setUint16(12,0,!0),p.setUint32(14,m,!0),p.setUint32(18,v,!0),p.setUint32(22,v,!0),p.setUint16(26,h.length,!0),p.setUint16(28,g,!0),P.set(h,30),g>0&&P.fill(0,30+h.length),e.push({offset:t,size:v,crc:m,filenameBytes:h,entry:l}),r.push(P),r.push(l.data),t+=P.length+l.data.length}let i=t;for(let l of e){let h=new Uint8Array(46+l.filenameBytes.length),m=new DataView(h.buffer);m.setUint32(0,33639248,!0),m.setUint16(4,20,!0),m.setUint16(6,20,!0),m.setUint16(8,0,!0),m.setUint16(10,0,!0),m.setUint16(12,0,!0),m.setUint16(14,0,!0),m.setUint32(16,l.crc,!0),m.setUint32(20,l.size,!0),m.setUint32(24,l.size,!0),m.setUint16(28,l.filenameBytes.length,!0),m.setUint16(30,0,!0),m.setUint16(32,0,!0),m.setUint16(34,0,!0),m.setUint16(36,0,!0),m.setUint32(38,0,!0),m.setUint32(42,l.offset,!0),h.set(l.filenameBytes,46),r.push(h),t+=h.length}let s=t-i,o=new Uint8Array(22),u=new DataView(o.buffer);u.setUint32(0,101010256,!0),u.setUint16(4,0,!0),u.setUint16(6,0,!0),u.setUint16(8,e.length,!0),u.setUint16(10,e.length,!0),u.setUint32(12,s,!0),u.setUint32(16,i,!0),u.setUint16(20,0,!0),r.push(o),t+=22;let c=new Uint8Array(t),a=0;for(let l of r)c.set(l,a),a+=l.length;return c}function Je(n){let e=Wn(n),t=lt(e);return Ht([{filename:"model.usda",data:t}])}function mt(n){let e=Te(n),t=Gn(e),r=zt(t),i=lt(r);return Ht([{filename:"model.usda",data:i}])}function dt(n){return n&&typeof n.toUSDZ=="function"?n.toUSDZ():n&&typeof n.traverse=="function"?Je(n):mt(n)}function ze(n){let e=dt(n);return new Blob([e],{type:"model/vnd.usdz+zip"})}var Wt=class n{constructor(e=0,t=0){this.x=Number(e),this.y=Number(t)}set(e,t){return this.x=Number(e),this.y=Number(t),this}clone(){return new n(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}sub(e){return this.x-=e.x,this.y-=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}},se=class n{constructor(e=0,t=0,r=0){this.x=Number(e),this.y=Number(t),this.z=Number(r)}set(e,t,r){return this.x=Number(e),this.y=Number(t),this.z=Number(r),this}clone(){return new n(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}length(){return Math.hypot(this.x,this.y,this.z)}normalize(){let e=this.length();return e>1e-5&&(this.x/=e,this.y/=e,this.z/=e),this}cross(e){let t=this.y*e.z-this.z*e.y,r=this.z*e.x-this.x*e.z,i=this.x*e.y-this.y*e.x;return this.x=t,this.y=r,this.z=i,this}crossVectors(e,t){let r=e.x,i=e.y,s=e.z,o=t.x,u=t.y,c=t.z;return this.x=i*c-s*u,this.y=s*o-r*c,this.z=r*u-i*o,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y,this.z-e.z)}applyMatrix4(e){let t=this.x,r=this.y,i=this.z,s=e.elements,o=1/(s[3]*t+s[7]*r+s[11]*i+s[15]);return this.x=(s[0]*t+s[4]*r+s[8]*i+s[12])*o,this.y=(s[1]*t+s[5]*r+s[9]*i+s[13])*o,this.z=(s[2]*t+s[6]*r+s[10]*i+s[14])*o,this}},$t=class{constructor(e=0,t=0,r=0,i=1){this.x=Number(e),this.y=Number(t),this.z=Number(r),this.w=Number(i)}set(e,t,r,i){return this.x=Number(e),this.y=Number(t),this.z=Number(r),this.w=Number(i),this}},bt=class n{constructor(e=0,t=0,r=0,i="XYZ"){this._onChangeCallback=null;this._x=Number(e),this._y=Number(t),this._z=Number(r),this.order=i}get x(){return this._x}set x(e){this._x=Number(e),this._onChangeCallback?.()}get y(){return this._y}set y(e){this._y=Number(e),this._onChangeCallback?.()}get z(){return this._z}set z(e){this._z=Number(e),this._onChangeCallback?.()}set(e,t,r,i=this.order){return this._x=Number(e),this._y=Number(t),this._z=Number(r),this.order=i,this._onChangeCallback?.(),this}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this.order=e.order,this._onChangeCallback?.(),this}clone(){return new n(this._x,this._y,this._z,this.order)}_onChange(e){return this._onChangeCallback=e,this}},yt=class n{constructor(e=0,t=0,r=0,i=1){this._onChangeCallback=null;this._x=Number(e),this._y=Number(t),this._z=Number(r),this._w=Number(i)}get x(){return this._x}set x(e){this._x=Number(e),this._onChangeCallback?.()}get y(){return this._y}set y(e){this._y=Number(e),this._onChangeCallback?.()}get z(){return this._z}set z(e){this._z=Number(e),this._onChangeCallback?.()}get w(){return this._w}set w(e){this._w=Number(e),this._onChangeCallback?.()}set(e,t,r,i){return this._x=Number(e),this._y=Number(t),this._z=Number(r),this._w=Number(i),this._onChangeCallback?.(),this}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback?.(),this}clone(){return new n(this._x,this._y,this._z,this._w)}setFromEuler(e,t=!0){let r=e.x,i=e.y,s=e.z,o=Math.cos(r/2),u=Math.cos(i/2),c=Math.cos(s/2),a=Math.sin(r/2),l=Math.sin(i/2),h=Math.sin(s/2);return this._x=a*u*c+o*l*h,this._y=o*l*c-a*u*h,this._z=o*u*h+a*l*c,this._w=o*u*c-a*l*h,t&&this._onChangeCallback?.(),this}setFromAxisAngle(e,t){let r=t/2,i=Math.sin(r);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(r),this._onChangeCallback?.(),this}multiply(e){return this.multiplyQuaternions(this,e)}multiplyQuaternions(e,t){let r=e.x,i=e.y,s=e.z,o=e.w,u=t.x,c=t.y,a=t.z,l=t.w;return this._x=r*l+o*u+i*a-s*c,this._y=i*l+o*c+s*u-r*a,this._z=s*l+o*a+r*c-i*u,this._w=o*l-r*u-i*c-s*a,this._onChangeCallback?.(),this}_onChange(e){return this._onChangeCallback=e,this}},He=class n{constructor(){this.elements=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}identity(){let e=this.elements;return e.fill(0),e[0]=1,e[5]=1,e[10]=1,e[15]=1,this}copy(e){return this.elements.set(e.elements),this}clone(){let e=new n;return e.copy(this),e}compose(e,t,r){return Pe(this.elements,[t.x,t.y,t.z,t.w],[e.x,e.y,e.z],[r.x,r.y,r.z]),this}multiply(e){return this.multiplyMatrices(this,e)}multiplyMatrices(e,t){return re(this.elements,e.elements,t.elements),this}lookAt(e,t,r){return Be(this.elements,[e.x,e.y,e.z],[t.x,t.y,t.z],[r.x,r.y,r.z]),this}makeRotationFromQuaternion(e){let t=new se(0,0,0),r=new se(1,1,1);return this.compose(t,e,r)}makeTranslation(e,t,r){return this.identity(),this.elements[12]=Number(e),this.elements[13]=Number(t),this.elements[14]=Number(r),this}makeScale(e,t,r){return this.identity(),this.elements[0]=Number(e),this.elements[5]=Number(t),this.elements[10]=Number(r),this}},qt=class{constructor(){this.elements=new Float32Array([1,0,0,0,1,0,0,0,1])}identity(){let e=this.elements;return e.fill(0),e[0]=1,e[4]=1,e[8]=1,this}getNormalMatrix(e){return be(this.elements,e.elements),this}},Re=class n{constructor(e,t,r){this.r=1;this.g=1;this.b=1;e!==void 0&&(t!==void 0&&r!==void 0?this.setRGB(e,t,r):this.set(e))}set(e){if(typeof e=="number")this.setHex(e);else if(typeof e=="string")if(e.startsWith("#")){let t=parseInt(e.slice(1),16);this.setHex(t)}else e==="red"?this.setRGB(1,0,0):e==="green"?this.setRGB(0,1,0):e==="blue"?this.setRGB(0,0,1):e==="white"?this.setRGB(1,1,1):e==="black"&&this.setRGB(0,0,0);else e&&typeof e=="object"&&"r"in e&&(this.r=Number(e.r),this.g=Number(e.g),this.b=Number(e.b));return this}setHex(e){let t=Math.floor(e);return this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(t&255)/255,this}setRGB(e,t,r){return this.r=Number(e),this.g=Number(t),this.b=Number(r),this}getHex(){return Math.round(Math.max(0,Math.min(1,this.r))*255)<<16|Math.round(Math.max(0,Math.min(1,this.g))*255)<<8|Math.round(Math.max(0,Math.min(1,this.b))*255)}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}clone(){return new n(this.r,this.g,this.b)}},Or={degToRad:n=>n*Math.PI/180,radToDeg:n=>n*180/Math.PI,clamp:(n,e,t)=>Math.max(e,Math.min(t,n)),lerp:(n,e,t)=>n+(e-n)*t,generateUUID:()=>Math.random().toString(36).substring(2,15),randFloat:(n,e)=>n+Math.random()*(e-n)},Z=class{constructor(e,t){this.needsUpdate=!1;if(typeof t!="number"||!Number.isInteger(t)||t<1||t>16)throw new Error(`SecurityError: BufferAttribute itemSize must be an integer in [1, 16]. Received: ${String(t)}`);Array.isArray(e)?this.array=new Float32Array(e):this.array=e,this.itemSize=t;let r=this.array?this.array.length:0;if(!Number.isFinite(r)||r<0)throw new Error(`SecurityError: BufferAttribute array has a non-finite length: ${String(r)}`);this.count=Math.floor(r/t)}getX(e){return this.array[e*this.itemSize]}getY(e){return this.array[e*this.itemSize+1]}getZ(e){return this.array[e*this.itemSize+2]}setX(e,t){return this.array[e*this.itemSize]=t,this.needsUpdate=!0,this}setY(e,t){return this.array[e*this.itemSize+1]=t,this.needsUpdate=!0,this}setZ(e,t){return this.array[e*this.itemSize+2]=t,this.needsUpdate=!0,this}setXYZ(e,t,r,i){let s=e*this.itemSize;return this.array[s]=t,this.array[s+1]=r,this.array[s+2]=i,this.needsUpdate=!0,this}},Yt=class extends Z{constructor(e,t){super(e instanceof Float32Array?e:new Float32Array(e),t)}},jt=class extends Z{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},Kt=class extends Z{constructor(e,t){super(e instanceof Uint32Array?e:new Uint32Array(e),t)}},Ae=class{constructor(){this.name="";this.attributes={};this.index=null;this.boundingBox=null}setAttribute(e,t){return this.attributes[e]=t,this}getAttribute(e){return this.attributes[e]}setIndex(e){if(e instanceof Z)this.index=e;else if(Array.isArray(e)){let t=0;for(let i=0;i<e.length;i++)e[i]>t&&(t=e[i]);let r=t>65535?new Uint32Array(e):new Uint16Array(e);this.index=new Z(r,1)}else e&&e.buffer&&(this.index=new Z(e,1));return this}computeVertexNormals(){let e=this.attributes.position;if(!e)return this;let t=e.count,r=new Float32Array(t*3),i=new se,s=new se,o=new se,u=new se,c=new se;if(this.index){let a=this.index.array;for(let l=0;l<a.length;l+=3){let h=a[l],m=a[l+1],v=a[l+2];i.set(e.getX(h),e.getY(h),e.getZ(h)),s.set(e.getX(m),e.getY(m),e.getZ(m)),o.set(e.getX(v),e.getY(v),e.getZ(v)),u.subVectors(o,s),c.subVectors(i,s),u.cross(c).normalize();for(let b of[h,m,v])r[b*3]+=u.x,r[b*3+1]+=u.y,r[b*3+2]+=u.z}}else for(let a=0;a<t;a+=3){i.set(e.getX(a),e.getY(a),e.getZ(a)),s.set(e.getX(a+1),e.getY(a+1),e.getZ(a+1)),o.set(e.getX(a+2),e.getY(a+2),e.getZ(a+2)),u.subVectors(o,s),c.subVectors(i,s),u.cross(c).normalize();for(let l=0;l<3;l++)r[(a+l)*3]=u.x,r[(a+l)*3+1]=u.y,r[(a+l)*3+2]=u.z}for(let a=0;a<t;a++){let l=r[a*3],h=r[a*3+1],m=r[a*3+2],v=Math.hypot(l,h,m)||1;r[a*3]=l/v,r[a*3+1]=h/v,r[a*3+2]=m/v}return this.setAttribute("normal",new Z(r,3)),this}setFromBuffers(e,t,r,i){this.setAttribute("position",new Z(e instanceof Float32Array?e:new Float32Array(e),3)),this.setAttribute("normal",new Z(t instanceof Float32Array?t:new Float32Array(t),3)),this.setAttribute("uv",new Z(r instanceof Float32Array?r:new Float32Array(r),2)),this.setIndex(i)}computeBoundingBox(){let e=this.attributes.position,t=new se(1/0,1/0,1/0),r=new se(-1/0,-1/0,-1/0);if(e&&e.count>0)for(let i=0;i<e.count;i++){let s=e.getX(i),o=e.getY(i),u=e.getZ(i);s<t.x&&(t.x=s),o<t.y&&(t.y=o),u<t.z&&(t.z=u),s>r.x&&(r.x=s),o>r.y&&(r.y=o),u>r.z&&(r.z=u)}else t.set(0,0,0),r.set(0,0,0);return this.boundingBox={min:t,max:r},this.boundingBox}center(){let e=this.computeBoundingBox(),t=(e.min.x+e.max.x)*.5,r=(e.min.y+e.max.y)*.5,i=(e.min.z+e.max.z)*.5,s=this.attributes.position;if(s&&s.count>0){for(let o=0;o<s.count;o++)s.setXYZ(o,s.getX(o)-t,s.getY(o)-r,s.getZ(o)-i);this.computeBoundingBox()}return this}dispose(){}},gt=class extends Ae{constructor(e=1,t=1,r=1){super();let i=e/2,s=t/2,o=r/2,u=[-i,-s,o,i,-s,o,i,s,o,-i,s,o,i,-s,-o,-i,-s,-o,-i,s,-o,i,s,-o,-i,s,o,i,s,o,i,s,-o,-i,s,-o,-i,-s,-o,i,-s,-o,i,-s,o,-i,-s,o,i,-s,o,i,-s,-o,i,s,-o,i,s,o,-i,-s,-o,-i,-s,o,-i,s,o,-i,s,-o],c=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0],a=[0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1],l=[];for(let h=0;h<6;h++){let m=h*4;l.push(m,m+1,m+2,m,m+2,m+3)}this.setAttribute("position",new Z(new Float32Array(u),3)),this.setAttribute("normal",new Z(new Float32Array(c),3)),this.setAttribute("uv",new Z(new Float32Array(a),2)),this.setIndex(l)}},Zt=class extends Ae{constructor(e=1,t=1){super();let r=e/2,i=t/2,s=[-r,i,0,r,i,0,-r,-i,0,r,-i,0],o=[0,0,1,0,0,1,0,0,1,0,0,1],u=[0,1,1,1,0,0,1,0],c=[0,2,1,2,3,1];this.setAttribute("position",new Z(new Float32Array(s),3)),this.setAttribute("normal",new Z(new Float32Array(o),3)),this.setAttribute("uv",new Z(new Float32Array(u),2)),this.setIndex(c)}},xt=class extends Ae{constructor(e=1,t=16,r=12){super(),t=Math.max(3,Math.floor(t)),r=Math.max(2,Math.floor(r));let i=[],s=[],o=[],u=[],c=[];for(let a=0;a<=r;a++){let l=[],h=a/r;for(let m=0;m<=t;m++){let v=m/t,b=v*Math.PI*2,d=h*Math.PI,g=-e*Math.cos(b)*Math.sin(d),I=e*Math.cos(d),P=e*Math.sin(b)*Math.sin(d);i.push(g,I,P);let p=Math.hypot(g,I,P)||1;s.push(g/p,I/p,P/p),o.push(v,1-h),l.push(i.length/3-1)}c.push(l)}for(let a=0;a<r;a++)for(let l=0;l<t;l++){let h=c[a][l+1],m=c[a][l],v=c[a+1][l],b=c[a+1][l+1];a!==0&&u.push(h,m,b),a!==r-1&&u.push(m,v,b)}this.setAttribute("position",new Z(new Float32Array(i),3)),this.setAttribute("normal",new Z(new Float32Array(s),3)),this.setAttribute("uv",new Z(new Float32Array(o),2)),this.setIndex(u)}},Fe=class extends Ae{constructor(e=1,t=1,r=1,i=16){super(),i=Math.max(3,Math.floor(i));let s=[],o=[],u=[],c=[],a=r/2;for(let l=0;l<=1;l++){let h=l,m=l===0?e:t,v=l===0?a:-a;for(let b=0;b<=i;b++){let d=b/i,g=d*Math.PI*2,I=Math.sin(g),P=Math.cos(g);s.push(m*I,v,m*P),o.push(I,0,P),u.push(d,1-h)}}for(let l=0;l<i;l++){let h=l,m=l+i+1,v=l+i+2,b=l+1;c.push(h,m,b,m,v,b)}if(e>0){let l=s.length/3;s.push(0,a,0),o.push(0,1,0),u.push(.5,.5);let h=s.length/3;for(let m=0;m<=i;m++){let v=m/i*Math.PI*2,b=Math.sin(v),d=Math.cos(v);s.push(e*b,a,e*d),o.push(0,1,0),u.push(d*.5+.5,b*.5+.5)}for(let m=0;m<i;m++)c.push(l,h+m,h+m+1)}if(t>0){let l=s.length/3;s.push(0,-a,0),o.push(0,-1,0),u.push(.5,.5);let h=s.length/3;for(let m=0;m<=i;m++){let v=m/i*Math.PI*2,b=Math.sin(v),d=Math.cos(v);s.push(t*b,-a,t*d),o.push(0,-1,0),u.push(d*.5+.5,1-(b*.5+.5))}for(let m=0;m<i;m++)c.push(l,h+m+1,h+m)}this.setAttribute("position",new Z(new Float32Array(s),3)),this.setAttribute("normal",new Z(new Float32Array(o),3)),this.setAttribute("uv",new Z(new Float32Array(u),2)),this.setIndex(c)}},Jt=class extends Fe{constructor(e=1,t=1,r=16){super(0,e,t,r)}},Qt=class extends Ae{constructor(e=1,t=.4,r=12,i=32){super(),r=Math.max(3,Math.floor(r)),i=Math.max(3,Math.floor(i));let s=[],o=[],u=[],c=[];for(let a=0;a<=r;a++){let l=a/r*Math.PI*2;for(let h=0;h<=i;h++){let m=h/i*Math.PI*2,v=(e+t*Math.cos(l))*Math.cos(m),b=(e+t*Math.cos(l))*Math.sin(m),d=t*Math.sin(l);s.push(v,b,d);let g=e*Math.cos(m),I=e*Math.sin(m),P=v-g,p=b-I,M=d,x=Math.hypot(P,p,M)||1;o.push(P/x,p/x,M/x),u.push(h/i,a/r)}}for(let a=1;a<=r;a++)for(let l=1;l<=i;l++){let h=(i+1)*a+l-1,m=(i+1)*(a-1)+l-1,v=(i+1)*(a-1)+l,b=(i+1)*a+l;c.push(h,m,b,m,v,b)}this.setAttribute("position",new Z(new Float32Array(s),3)),this.setAttribute("normal",new Z(new Float32Array(o),3)),this.setAttribute("uv",new Z(new Float32Array(u),2)),this.setIndex(c)}},en=class extends Ae{constructor(e=1,t=.4,r=64,i=8,s=2,o=3){super(),r=Math.floor(r),i=Math.floor(i);let u=[],c=[],a=[],l=[],h=new se,m=new se,v=new se,b=new se,d=new se;function g(p,M){let x=Math.cos(M),w=Math.sin(M),T=o/s*M,A=e*(2+Math.cos(T))*.5;p.set(A*x,A*w,e*Math.sin(T)*.5)}let I=[];for(let p=0;p<=i;++p){let M=p/i*Math.PI*2;I.push(-t*Math.cos(M),t*Math.sin(M),p/i)}for(let p=0;p<=r;++p){let M=p/r,x=M*s*Math.PI*2;g(h,x),g(m,x+.01),v.subVectors(m,h).normalize(),b.addVectors(h,m).normalize(),d.crossVectors(v,b).normalize(),b.crossVectors(d,v).normalize();for(let w=0;w<=i;++w){let T=w*3,A=I[T],y=I[T+1],E=I[T+2],f=A*b.x+y*d.x,_=A*b.y+y*d.y,S=A*b.z+y*d.z;u.push(h.x+f,h.y+_,h.z+S);let R=Math.hypot(f,_,S)||1;c.push(f/R,_/R,S/R),a.push(M,E)}}let P=i+1;for(let p=1;p<=r;p++){let M=P*(p-1),x=M+P;for(let w=1;w<=i;w++){let T=M+(w-1),A=x+(w-1),y=x+w,E=M+w;l.push(T,A,E,A,y,E)}}this.setAttribute("position",new Z(new Float32Array(u),3)),this.setAttribute("normal",new Z(new Float32Array(c),3)),this.setAttribute("uv",new Z(new Float32Array(a),2)),this.setIndex(l)}},vt=class{constructor(e=""){this.isTexture=!0;this.wrapS=10497;this.wrapT=10497;this.image=null;this.width=0;this.height=0;this.source=e,e&&typeof e=="object"&&(this.image=e)}dispose(){}},tn=class{load(e,t){let r=new vt(e);return t?.(r),r}};function fe(n,e){return n!==void 0?Number(n):e}function Xt(n,e){return n!==void 0?!!n:e}var Ce=class{constructor(e={}){this.name=e.name||"",this.color=new Re(e.color!==void 0?e.color:16777215),this.emissive=new Re(e.emissive!==void 0?e.emissive:0),this.emissiveIntensity=fe(e.emissiveIntensity,1),this.roughness=fe(e.roughness,.5),this.metalness=fe(e.metalness,.1),this.opacity=fe(e.opacity,1),this.transparent=Xt(e.transparent,!1),this.wireframe=Xt(e.wireframe,!1),this.side=fe(e.side,2),this.doubleSided=Xt(e.doubleSided,!0),this.map=e.map||null,this.clearcoat=fe(e.clearcoat,0),this.clearcoatRoughness=fe(e.clearcoatRoughness,0),this.sheen=fe(e.sheen,0),this.sheenColor=new Re(e.sheenColor!==void 0?e.sheenColor:0),this.sheenRoughness=fe(e.sheenRoughness,0),this.transmission=fe(e.transmission,0),this.thickness=fe(e.thickness,0),this.attenuationColor=new Re(e.attenuationColor!==void 0?e.attenuationColor:16777215),this.attenuationDistance=fe(e.attenuationDistance,1/0),this.ior=fe(e.ior,1.5),this.dispersion=fe(e.dispersion,0),this.iridescence=fe(e.iridescence,0),this.iridescenceIOR=fe(e.iridescenceIOR,1.3)}dispose(){}},Xe=class extends Ce{},nn=class extends Ce{},rn=class extends Ce{},sn=class extends Ce{},on=class extends Ce{},Ee=class n{constructor(){this.name="";this.matrixAutoUpdate=!0;this.visible=!0;this.castShadow=!1;this.receiveShadow=!1;this.parent=null;this.children=[];this.userData={};this.position=new se,this.rotation=new bt,this.quaternion=new yt,this.scale=new se(1,1,1),this.matrix=new He,this.matrixWorld=new He,this.rotation._onChange(()=>{this.quaternion.setFromEuler(this.rotation,!1)}),this.quaternion._onChange(()=>{let e=this.quaternion,t=Math.atan2(2*(e.w*e.x+e.y*e.z),1-2*(e.x*e.x+e.y*e.y)),r=Math.asin(Math.max(-1,Math.min(1,2*(e.w*e.y-e.z*e.x)))),i=Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z));this.rotation.set(t,r,i)})}add(...e){for(let t of e)t&&t instanceof n&&(t.parent&&t.parent.remove(t),t.parent=this,this.children.push(t));return this}remove(...e){for(let t of e){let r=this.children.indexOf(t);r!==-1&&(t.parent=null,this.children.splice(r,1))}return this}traverse(e){e(this);for(let t of this.children)t.traverse(e)}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale)}updateMatrixWorld(e=!1){Qn(this),(this.matrixAutoUpdate||e)&&this.updateMatrix(),this.parent?this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix):this.matrixWorld.copy(this.matrix);for(let t of this.children)t.updateMatrixWorld(e)}lookAt(e,t,r){let i=typeof e=="object"?e:new se(e,t,r);this.updateMatrixWorld(!0);let s=new He;s.lookAt(this.position,i,new se(0,1,0));let o=s.elements,u=o[0],c=o[4],a=o[8],l=o[1],h=o[5],m=o[9],v=o[2],b=o[6],d=o[10],g=u+h+d;if(g>0){let I=.5/Math.sqrt(g+1);this.quaternion.set((b-m)*I,(a-v)*I,(l-c)*I,.25/I)}}},an=class extends Ee{},Ge=class extends Ee{constructor(t,r){super();this.isMesh=!0;let i=Array.isArray(r)?r[0]:r;this.geometry=t instanceof Ae?t:t?(Me("unsupported geometry","BoxGeometry"),new gt(.5,.5,.5)):new Ae,this.material=i instanceof Ce?i:i?(Me("unsupported material","MeshStandardMaterial"),new Xe({color:13421772})):new Xe}};function Qn(n){let e=J().materializeDeclarativeGeometry;typeof e=="function"&&e(n)}var wt=1e4,At=class extends Ge{constructor(t,r,i=1){super(t,r);this.instanceColor=null;this.isInstancedMesh=!0;let s=Number(i);if(!Number.isFinite(s)||s<0||s>wt)throw new RangeError(`SecurityError: InstancedMesh count (${String(i)}) exceeds MAX_INSTANCES_PER_MESH (${wt})`);this.count=Math.floor(s);let o=new Float32Array(this.count*16);for(let u=0;u<this.count;u++){let c=u*16;o[c]=1,o[c+5]=1,o[c+10]=1,o[c+15]=1}this.instanceMatrix=new Z(o,16)}setMatrixAt(t,r){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!r||!r.elements)return;let s=this.instanceMatrix.array,o=i*16;if(!(o+16>s.length))for(let u=0;u<16;u++){let c=Number(r.elements[u]);s[o+u]=Number.isFinite(c)?c:u%5===0?1:0}}getMatrixAt(t,r){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!r||!r.elements)return;let s=this.instanceMatrix.array,o=i*16;if(!(o+16>s.length))for(let u=0;u<16;u++)r.elements[u]=s[o+u]}setColorAt(t,r){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!r)return;if(!this.instanceColor||this.instanceColor.array.length<this.count*3){let u=new Float32Array(this.count*3);u.fill(1),this.instanceColor=new Z(u,3)}let s=this.instanceColor.array,o=i*3;s[o]=Number.isFinite(r.r)?r.r:1,s[o+1]=Number.isFinite(r.g)?r.g:1,s[o+2]=Number.isFinite(r.b)?r.b:1}getColorAt(t,r){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!r)return;if(!this.instanceColor||this.instanceColor.array.length<(i+1)*3){r.setRGB(1,1,1);return}let s=this.instanceColor.array,o=i*3;r.setRGB(s[o],s[o+1],s[o+2])}dispose(){}},We=class extends Ee{constructor(e=16777215,t=1){super(),this.color=new Re(e),this.intensity=Number(t),this.type="directional"}},Mt=class extends We{constructor(e,t){super(e,t),this.type="ambient"}},cn=class extends We{constructor(t,r){super(t,r);this.target=new Ee;this.type="directional"}},St=class extends We{constructor(t,r,i=0,s=2){super(t,r);this.distance=0;this.decay=2;this.type="point",this.distance=i,this.decay=s}},Rt=class extends Ee{},un=class extends Rt{constructor(t=45,r=1,i=.1,s=1e3){super();this.target=new se(0,0,0);this.fov=Number(t),this.aspect=Number(r),this.near=Number(i),this.far=Number(s)}},Et=class extends Ee{constructor(){super(...arguments);this.background=null;this.environmentIntensity=1}toCanvas3D(){return _e.validate(this),Ze(this)}toGLB(){return _e.validate(this),ht(this)}toUSDZ(){return _e.validate(this),Je(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let t=new Map,r=0;return this.traverse(i=>{if(i instanceof Ge){let s=new Float32Array(i.matrixWorld.elements);t.set(r,s),i.name&&t.set(i.name,s),r++}}),t}},er=Ze,tr=ht,Br=Je;var _e=class{static validate(e){let t=0,r=0,i=0,s=new Set,o=(c,a,l)=>{throw new Error(`SecurityError: Scene exceeds SECURITY_3D_MAX_${c} (${a}). Found: ${l}`)},u=(c,a)=>{if(!Number.isFinite(a))throw new Error(`SecurityError: Scene reports a non-finite ${c} count (${String(a)}), which cannot be bounds-checked.`);return a};e.traverse(c=>{if(Qn(c),c instanceof Ge||c.geometry?.attributes?.position?.count){if(i++,i>1e3&&o("MESHES",1e3,i),c instanceof At){let l=u("instance",c.count);(l<0||l>wt)&&o("INSTANCES",wt,l)}let a=c.geometry;if(a){let l=0;if(a.attributes.position&&(l=u("vertex",a.attributes.position.count),t+=l,t>1e5&&o("VERTICES",1e5,t)),a.index){let h=u("index",a.index.count);r+=h,r>3e5&&o("INDICES",3e5,r);let m=a.index.array;if(m&&l>0){let v=Math.min(h,m.length);for(let b=0;b<v;b++){let d=m[b];if(!Number.isFinite(d)||d<0||d>=l)throw new Error(`SecurityError: Index buffer value (${String(d)}) out of vertex bounds [0, ${l}).`)}}}}if(c.material){let l=c.material;l.map&&s.add(l.map),l.normalMap&&s.add(l.normalMap),l.roughnessMap&&s.add(l.roughnessMap)}}}),s.size>16&&o("TEXTURES",16,s.size);for(let c of s){let a=c,l=a.image,h=Number(l?.width??a.width??0)||0,m=Number(l?.height??a.height??0)||0;(!Number.isFinite(h)||!Number.isFinite(m)||h>2048||m>2048)&&o("TEXTURE_DIMENSION",2048,Math.max(h,m))}}},ln=class{constructor(e={}){this.shadowMap={enabled:!1,type:0};this.capabilities={isWebGL2:!0,maxTextures:16};this.boundViewer=null;this.isSandboxed=!1;this.containerId="";this.hasInitialModelRendered=!1;this.domElement=e.canvas||(typeof document<"u"?document.createElement("canvas"):{}),e.viewer&&(this.boundViewer=e.viewer),e.container?.threeLiveViewer&&(this.boundViewer=e.container.threeLiveViewer),e.canvas?.parentElement?.threeLiveViewer&&(this.boundViewer=e.canvas.parentElement.threeLiveViewer);let t=typeof WorkerGlobalScope<"u"&&typeof self<"u"&&self instanceof WorkerGlobalScope;this.isSandboxed=e.isSandboxed||t,this.containerId=e.containerId||""}setSize(e,t){return this}setPixelRatio(e){return this}setClearColor(e,t=1){let r=new Re(e);return this.boundViewer&&typeof this.boundViewer.setClearColor=="function"&&this.boundViewer.setClearColor(r.r,r.g,r.b,t),this}clear(){return this}dispose(){}render(e,t){if(this.isSandboxed){_e.validate(e);let i=(s,o)=>{typeof self<"u"&&typeof self.postMessage=="function"&&(o&&o.length?self.postMessage(s,o):self.postMessage(s))};if(this.hasInitialModelRendered){let s=e.getMeshTransforms(),o={};for(let[u,c]of s.entries())o[u]=Array.from(c);i({type:"3D_UPDATE_TRANSFORMS",containerId:this.containerId,transforms:o})}else{this.hasInitialModelRendered=!0;let s=er(e),o=tr(e),u=(s.lights||[]).map(c=>({type:c.type,color:c.color,intensity:c.intensity,position:c.position}));i({type:"3D_MODEL_READY",containerId:this.containerId,glbBuffer:o.buffer,dynamicLights:u,camera:t?{fov:t.fov||60,position:[t.position.x,t.position.y,t.position.z]}:void 0},[o.buffer])}return}let r=this.boundViewer;!r&&this.domElement?.parentElement&&this.domElement.parentElement.threeLiveViewer&&(r=this.domElement.parentElement.threeLiveViewer,this.boundViewer=r),!r&&typeof window<"u"&&(r=window.__three_live_active_viewer__,this.boundViewer=r),r&&typeof r.loadModel=="function"&&(r._hasThreeLiveModelLoaded?typeof r.updateMeshTransforms=="function"&&r.updateMeshTransforms(e.getMeshTransforms()):(r.loadModel(e.toCanvas3D()),r._hasThreeLiveModelLoaded=!0))}};function qn(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var hn=class{constructor(e=!0){this.startTime=0;this.oldTime=0;this.elapsedTime=0;this.running=!1;this.autoStart=e,e&&this.start()}start(){this.startTime=qn(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running&&this.start(),this.running){let t=qn();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function Vr(){}var ft=new Proxy(Vr,{get:(n,e)=>{if(e==="isProxy")return!0;if(!(e==="constructor"||e==="__proto__"||e==="prototype"))return e==="domElement"?typeof document<"u"?document.createElement("canvas"):{}:e==="shadowMap"?{enabled:!1,type:0}:e==="capabilities"?{isWebGL2:!0,maxTextures:16}:e===Symbol.toPrimitive?()=>0:ft},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>ft,construct:()=>ft}),Yn=(()=>{try{if(typeof document>"u")return null;let n=document.currentScript;return n?.src?n.src:n?.textContent&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(new Blob([n.textContent],{type:"text/javascript"})):null}catch{return null}})();function Ye(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function Ne(n,e){if(!n||typeof n!="string")return!1;let t=n.trim();if(!t)return!1;try{let r=new URL(t,Ye());return!(r.protocol!=="https:"&&r.protocol!=="http:"&&r.protocol!=="blob:"||e?.requireSameOrigin&&r.protocol!=="blob:"&&typeof location<"u"&&location.origin&&location.origin!=="null"&&r.origin!==location.origin)}catch{return!1}}var jn,Qe;function zr(n){if(!Ne(n))throw new Error(`SecurityError: Refusing to create TrustedScriptURL for disallowed URL "${n}".`);let t=globalThis.trustedTypes;if(!t||typeof t.createPolicy!="function")return n;if(Qe===void 0||jn!==t){jn=t;try{Qe=t.createPolicy("three-live#worker",{createScriptURL:r=>{if(!Ne(r))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${r}".`);return r}})}catch{Qe=null}}return Qe?Qe.createScriptURL(n):n}function nr(){let n=J().sandboxEngineSrc;if(n)return n;if(Yn)return Yn;try{if(typeof document>"u")return null;let e=Ye(),t=Array.from(document.querySelectorAll("script[src]"));for(let r of t){let i=r.src;if(!i)continue;let s=new URL(i,e).pathname;if(/(?:^|\/)(?:three|xr)-live[^/]*\.js$/.test(s)&&Ne(i,{requireSameOrigin:!0}))return i}}catch{}return null}function Hr(){let n=nr();if(!n)throw new Error("Three-Live could not locate its own bundle URL, which the worker sandbox needs in order to load the THREE runtime. Set it explicitly, e.g. ThreeLiveElement.sandboxEngineSrc = new URL('three-live.min.js', import.meta.url).href. Refusing to execute the script, because unsandboxed host-realm execution is prohibited.");if(!Ne(n))throw new Error(`SecurityError: Refusing to load sandbox engine from disallowed URL "${n}". Only http:, https:, and blob: URLs are permitted.`);return new URL(n,Ye()).href}function Xr(){let n=J().sandboxIframeSrc;if(n)return n;let e=nr();if(!e||!Ne(e))return null;let t=new URL(e,Ye());return t.protocol==="blob:"?null:new URL("three-live-sandbox.html",t).href}function Gr(){let n=Xr();if(!n)throw new Error("Three-Live could not locate three-live-sandbox.html for iframe sandbox execution. Set ThreeLiveElement.sandboxIframeSrc (or ThreeLiveElement.sandboxEngineSrc) explicitly.");if(!Ne(n))throw new Error(`SecurityError: Refusing to load sandbox iframe from disallowed URL "${n}". Only http:, https:, and blob: URLs are permitted.`);return new URL(n,Ye()).href}function Wr(){return!!J().allowClientScripts}function $r(n){if(!Ne(n))throw new Error(`SecurityError: Refusing to load procedural scene script from disallowed URL "${n}". Only http:, https:, and blob: URLs are permitted.`);return new URL(n,Ye()).href}var qr=["fetch","XMLHttpRequest","WebSocket","WebSocketStream","WebTransport","EventSource","importScripts","Request","Response","Headers","navigator","WorkerNavigator","WorkerLocation","RTCPeerConnection","RTCDataChannel","FontFace","FontFaceSet","fonts","PerformanceObserver","ReportingObserver","indexedDB","IDBFactory","caches","CacheStorage","Cache","cookieStore","StorageManager","FileSystemHandle","Worker","SharedWorker","ServiceWorker","ServiceWorkerContainer","ServiceWorkerRegistration","registration","clients","BroadcastChannel","MessageChannel","MessagePort","createImageBitmap","OffscreenCanvas","WebAssembly","WorkerGlobalScope","DedicatedWorkerGlobalScope","trustedTypes","TrustedTypePolicyFactory","SharedArrayBuffer","Atomics"];function Yr(n,e){let t=self,r=n.nonce,i=n.engineSrc,s=n.allowedScriptUrl,o=n.allowClientScripts,u=n.revoked,c=t.postMessage.bind(t);function a(w){c({type:"ERROR",nonce:r,message:String(w)})}let l=typeof t.importScripts=="function"?t.importScripts.bind(t):null,h=s,m=null;try{let w=i;if(typeof t.trustedTypes<"u"&&t.trustedTypes&&typeof t.trustedTypes.createPolicy=="function")try{let T={createScriptURL:function(y){if(y!==i&&(!s||y!==s))throw new TypeError("Disallowed worker importScripts URL");return y}};o&&(T.createScript=function(y){return String(y)});let A=t.trustedTypes.createPolicy("three-live#worker-boot",T);w=A.createScriptURL(i),s&&(h=A.createScriptURL(s)),o&&typeof A.createScript=="function"&&(m=A.createScript.bind(A))}catch{}l(w)}catch(w){a('Sandbox failed to load the Three-Live engine from "'+i+'". It must be a same-origin (or CORS-enabled) IIFE bundle such as three-live.min.js. Underlying error: '+(w&&w.message||w));return}let v=t.THREE;if(!v||typeof v.Scene!="function"){a('Sandbox loaded "'+i+'" but it did not install a THREE namespace. Point sandboxEngineSrc at an IIFE build (three-live.min.js), not an ES module build.');return}if(Array.isArray(e)){let w=t.__THREE_LIVE_REGISTRY__;for(let T=0;T<e.length;T++)if(typeof e[T]=="function")try{e[T](v,w)}catch{}}for(let w=0;w<u.length;w++){let T=u[w],A=t;for(;A&&A!==Object.prototype;){if(A!==t)try{delete A[T]}catch{}try{Object.defineProperty(A,T,{value:void 0,writable:!1,configurable:!1,enumerable:!1})}catch{}try{A=Object.getPrototypeOf(A)}catch{break}}}let b=Object.freeze({now:function(){return Date.now()}}),d=t;for(;d&&d!==Object.prototype;){if(d!==t)try{delete d.performance}catch{}try{Object.defineProperty(d,"performance",{value:b,writable:!1,configurable:!1,enumerable:!1})}catch{}try{d=Object.getPrototypeOf(d)}catch{break}}let g=["3D_MODEL_READY","3D_UPDATE_TRANSFORMS"],I=!1;function P(w,T){if(w.type==="3D_MODEL_READY"){if(I)return;I=!0}w.nonce=r,T&&T.length?c(w,T):c(w)}let p=function(w,T){if(!w||g.indexOf(w.type)===-1)throw new Error("Sandboxed scripts may only post Three-Live scene messages ("+g.join(", ")+").");P(w,T)},M=t;for(;M&&M!==Object.prototype;){if(M===t||Object.prototype.hasOwnProperty.call(M,"postMessage"))try{Object.defineProperty(M,"postMessage",{value:p,writable:!1,configurable:!1})}catch{}try{M=Object.getPrototypeOf(M)}catch{break}}let x=!1;t.onmessage=function(w){let T=w&&w.data;if(!(!T||T.nonce!==r)&&!(T.type!=="EXECUTE"&&T.type!=="EXECUTE_URL")&&!x){x=!0;try{let A=new v.Scene,y=new v.PerspectiveCamera(60,1,.1,1e3),E=new v.WebGLRenderer({isSandboxed:!0});if(T.type==="EXECUTE_URL"){if(!s||T.scriptUrl!==s||typeof l!="function"){a("SecurityError: Refusing to execute unapproved script URL inside sandbox worker.");return}let f=h||s,_=l;if(l=null,h=null,t.THREE=v,t.scene=A,t.camera=y,t.renderer=E,_(f),typeof t.__THREE_LIVE_SCENE__=="function"){let S=t.__THREE_LIVE_SCENE__(v,A,y,E);S&&typeof S.toGLB=="function"&&(A=S)}else t.scene&&typeof t.scene.toGLB=="function"&&(A=t.scene)}else{if(!o){a("SecurityError: Client-modified script compilation (Use Case 1) is disabled in this sandbox worker.");return}let f=m?(0,eval)(m(`(function (THREE, scene, camera, renderer) {
|
|
321
|
+
`,o}function Yn(n,e){if(n&&typeof n.traverse=="function"){let i=Br(n,e);return Ot(i)}let t=Ae(n),r=$n(t);return Ot(r)}var rt=null;function qn(n){if(!rt){rt=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let i=0;i<8;i++)r=r&1?3988292384^r>>>1:r>>>1;rt[t]=r}}let e=4294967295;for(let t=0;t<n.length;t++)e=rt[(e^n[t])&255]^e>>>8;return(e^4294967295)>>>0}function Bt(n){let e=[],t=0,r=[];for(let l of n){let m=it(l.filename),h=qn(l.data),y=l.data.length,b=30+m.length,d=t+b,g=0,T=d%64;T!==0&&(g=64-T);let P=new Uint8Array(b+g),f=new DataView(P.buffer);f.setUint32(0,67324752,!0),f.setUint16(4,20,!0),f.setUint16(6,0,!0),f.setUint16(8,0,!0),f.setUint16(10,0,!0),f.setUint16(12,0,!0),f.setUint32(14,h,!0),f.setUint32(18,y,!0),f.setUint32(22,y,!0),f.setUint16(26,m.length,!0),f.setUint16(28,g,!0),P.set(m,30),g>0&&P.fill(0,30+m.length),e.push({offset:t,size:y,crc:h,filenameBytes:m,entry:l}),r.push(P),r.push(l.data),t+=P.length+l.data.length}let i=t;for(let l of e){let m=new Uint8Array(46+l.filenameBytes.length),h=new DataView(m.buffer);h.setUint32(0,33639248,!0),h.setUint16(4,20,!0),h.setUint16(6,20,!0),h.setUint16(8,0,!0),h.setUint16(10,0,!0),h.setUint16(12,0,!0),h.setUint16(14,0,!0),h.setUint32(16,l.crc,!0),h.setUint32(20,l.size,!0),h.setUint32(24,l.size,!0),h.setUint16(28,l.filenameBytes.length,!0),h.setUint16(30,0,!0),h.setUint16(32,0,!0),h.setUint16(34,0,!0),h.setUint16(36,0,!0),h.setUint32(38,0,!0),h.setUint32(42,l.offset,!0),m.set(l.filenameBytes,46),r.push(m),t+=m.length}let s=t-i,o=new Uint8Array(22),c=new DataView(o.buffer);c.setUint32(0,101010256,!0),c.setUint16(4,0,!0),c.setUint16(6,0,!0),c.setUint16(8,e.length,!0),c.setUint16(10,e.length,!0),c.setUint32(12,s,!0),c.setUint32(16,i,!0),c.setUint16(20,0,!0),r.push(o),t+=22;let a=new Uint8Array(t),u=0;for(let l of r)a.set(l,u),u+=l.length;return a}function qe(n){let e=Yn(n),t=it(e);return Bt([{filename:"model.usda",data:t}])}function ot(n){let e=Ae(n),t=$n(e),r=Ot(t),i=it(r);return Bt([{filename:"model.usda",data:i}])}function at(n){return n&&typeof n.toUSDZ=="function"?n.toUSDZ():n&&typeof n.traverse=="function"?qe(n):ot(n)}function ke(n){let e=at(n);return new Blob([e],{type:"model/vnd.usdz+zip"})}var Ht=class n{constructor(e=0,t=0){this.x=Number(e),this.y=Number(t)}set(e,t){return this.x=Number(e),this.y=Number(t),this}clone(){return new n(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}sub(e){return this.x-=e.x,this.y-=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}},le=class n{constructor(e=0,t=0,r=0){this.x=Number(e),this.y=Number(t),this.z=Number(r)}set(e,t,r){return this.x=Number(e),this.y=Number(t),this.z=Number(r),this}clone(){return new n(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}length(){return Math.hypot(this.x,this.y,this.z)}normalize(){let e=this.length();return e>1e-5&&(this.x/=e,this.y/=e,this.z/=e),this}cross(e){let t=this.y*e.z-this.z*e.y,r=this.z*e.x-this.x*e.z,i=this.x*e.y-this.y*e.x;return this.x=t,this.y=r,this.z=i,this}crossVectors(e,t){let r=e.x,i=e.y,s=e.z,o=t.x,c=t.y,a=t.z;return this.x=i*a-s*c,this.y=s*o-r*a,this.z=r*c-i*o,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y,this.z-e.z)}applyMatrix4(e){let t=this.x,r=this.y,i=this.z,s=e.elements,o=1/(s[3]*t+s[7]*r+s[11]*i+s[15]);return this.x=(s[0]*t+s[4]*r+s[8]*i+s[12])*o,this.y=(s[1]*t+s[5]*r+s[9]*i+s[13])*o,this.z=(s[2]*t+s[6]*r+s[10]*i+s[14])*o,this}},Gt=class{constructor(e=0,t=0,r=0,i=1){this.x=Number(e),this.y=Number(t),this.z=Number(r),this.w=Number(i)}set(e,t,r,i){return this.x=Number(e),this.y=Number(t),this.z=Number(r),this.w=Number(i),this}},lt=class n{constructor(e=0,t=0,r=0,i="XYZ"){this._onChangeCallback=null;this._x=Number(e),this._y=Number(t),this._z=Number(r),this.order=i}get x(){return this._x}set x(e){this._x=Number(e),this._onChangeCallback?.()}get y(){return this._y}set y(e){this._y=Number(e),this._onChangeCallback?.()}get z(){return this._z}set z(e){this._z=Number(e),this._onChangeCallback?.()}set(e,t,r,i=this.order){return this._x=Number(e),this._y=Number(t),this._z=Number(r),this.order=i,this._onChangeCallback?.(),this}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this.order=e.order,this._onChangeCallback?.(),this}clone(){return new n(this._x,this._y,this._z,this.order)}_onChange(e){return this._onChangeCallback=e,this}},ht=class n{constructor(e=0,t=0,r=0,i=1){this._onChangeCallback=null;this._x=Number(e),this._y=Number(t),this._z=Number(r),this._w=Number(i)}get x(){return this._x}set x(e){this._x=Number(e),this._onChangeCallback?.()}get y(){return this._y}set y(e){this._y=Number(e),this._onChangeCallback?.()}get z(){return this._z}set z(e){this._z=Number(e),this._onChangeCallback?.()}get w(){return this._w}set w(e){this._w=Number(e),this._onChangeCallback?.()}set(e,t,r,i){return this._x=Number(e),this._y=Number(t),this._z=Number(r),this._w=Number(i),this._onChangeCallback?.(),this}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback?.(),this}clone(){return new n(this._x,this._y,this._z,this._w)}setFromEuler(e,t=!0){let r=e.x,i=e.y,s=e.z,o=Math.cos(r/2),c=Math.cos(i/2),a=Math.cos(s/2),u=Math.sin(r/2),l=Math.sin(i/2),m=Math.sin(s/2);return this._x=u*c*a+o*l*m,this._y=o*l*a-u*c*m,this._z=o*c*m+u*l*a,this._w=o*c*a-u*l*m,t&&this._onChangeCallback?.(),this}setFromAxisAngle(e,t){let r=t/2,i=Math.sin(r);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(r),this._onChangeCallback?.(),this}multiply(e){return this.multiplyQuaternions(this,e)}multiplyQuaternions(e,t){let r=e.x,i=e.y,s=e.z,o=e.w,c=t.x,a=t.y,u=t.z,l=t.w;return this._x=r*l+o*c+i*u-s*a,this._y=i*l+o*a+s*c-r*u,this._z=s*l+o*u+r*a-i*c,this._w=o*l-r*c-i*a-s*u,this._onChangeCallback?.(),this}_onChange(e){return this._onChangeCallback=e,this}},Ue=class n{constructor(){this.elements=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}identity(){let e=this.elements;return e.fill(0),e[0]=1,e[5]=1,e[10]=1,e[15]=1,this}copy(e){return this.elements.set(e.elements),this}clone(){let e=new n;return e.copy(this),e}compose(e,t,r){return _e(this.elements,[t.x,t.y,t.z,t.w],[e.x,e.y,e.z],[r.x,r.y,r.z]),this}multiply(e){return this.multiplyMatrices(this,e)}multiplyMatrices(e,t){return ae(this.elements,e.elements,t.elements),this}lookAt(e,t,r){return Fe(this.elements,[e.x,e.y,e.z],[t.x,t.y,t.z],[r.x,r.y,r.z]),this}makeRotationFromQuaternion(e){let t=new le(0,0,0),r=new le(1,1,1);return this.compose(t,e,r)}makeTranslation(e,t,r){return this.identity(),this.elements[12]=Number(e),this.elements[13]=Number(t),this.elements[14]=Number(r),this}makeScale(e,t,r){return this.identity(),this.elements[0]=Number(e),this.elements[5]=Number(t),this.elements[10]=Number(r),this}},Xt=class{constructor(){this.elements=new Float32Array([1,0,0,0,1,0,0,0,1])}identity(){let e=this.elements;return e.fill(0),e[0]=1,e[4]=1,e[8]=1,this}getNormalMatrix(e){return ye(this.elements,e.elements),this}},ve=class n{constructor(e,t,r){this.r=1;this.g=1;this.b=1;e!==void 0&&(t!==void 0&&r!==void 0?this.setRGB(e,t,r):this.set(e))}set(e){if(typeof e=="number")this.setHex(e);else if(typeof e=="string")if(e.startsWith("#")){let t=parseInt(e.slice(1),16);this.setHex(t)}else e==="red"?this.setRGB(1,0,0):e==="green"?this.setRGB(0,1,0):e==="blue"?this.setRGB(0,0,1):e==="white"?this.setRGB(1,1,1):e==="black"&&this.setRGB(0,0,0);else e&&typeof e=="object"&&"r"in e&&(this.r=Number(e.r),this.g=Number(e.g),this.b=Number(e.b));return this}setHex(e){let t=Math.floor(e);return this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(t&255)/255,this}setRGB(e,t,r){return this.r=Number(e),this.g=Number(t),this.b=Number(r),this}getHex(){return Math.round(Math.max(0,Math.min(1,this.r))*255)<<16|Math.round(Math.max(0,Math.min(1,this.g))*255)<<8|Math.round(Math.max(0,Math.min(1,this.b))*255)}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}clone(){return new n(this.r,this.g,this.b)}},Hr={degToRad:n=>n*Math.PI/180,radToDeg:n=>n*180/Math.PI,clamp:(n,e,t)=>Math.max(e,Math.min(t,n)),lerp:(n,e,t)=>n+(e-n)*t,generateUUID:()=>Math.random().toString(36).substring(2,15),randFloat:(n,e)=>n+Math.random()*(e-n)},J=class{constructor(e,t){this.needsUpdate=!1;if(typeof t!="number"||!Number.isInteger(t)||t<1||t>16)throw new Error(`SecurityError: BufferAttribute itemSize must be an integer in [1, 16]. Received: ${String(t)}`);Array.isArray(e)?this.array=new Float32Array(e):this.array=e,this.itemSize=t;let r=this.array?this.array.length:0;if(!Number.isFinite(r)||r<0)throw new Error(`SecurityError: BufferAttribute array has a non-finite length: ${String(r)}`);this.count=Math.floor(r/t)}getX(e){return this.array[e*this.itemSize]}getY(e){return this.array[e*this.itemSize+1]}getZ(e){return this.array[e*this.itemSize+2]}setX(e,t){return this.array[e*this.itemSize]=t,this.needsUpdate=!0,this}setY(e,t){return this.array[e*this.itemSize+1]=t,this.needsUpdate=!0,this}setZ(e,t){return this.array[e*this.itemSize+2]=t,this.needsUpdate=!0,this}setXYZ(e,t,r,i){let s=e*this.itemSize;return this.array[s]=t,this.array[s+1]=r,this.array[s+2]=i,this.needsUpdate=!0,this}},Wt=class extends J{constructor(e,t){super(e instanceof Float32Array?e:new Float32Array(e),t)}},$t=class extends J{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},Yt=class extends J{constructor(e,t){super(e instanceof Uint32Array?e:new Uint32Array(e),t)}},ge=class{constructor(){this.name="";this.attributes={};this.index=null;this.boundingBox=null}setAttribute(e,t){return this.attributes[e]=t,this}getAttribute(e){return this.attributes[e]}setIndex(e){if(e instanceof J)this.index=e;else if(Array.isArray(e)){let t=0;for(let i=0;i<e.length;i++)e[i]>t&&(t=e[i]);let r=t>65535?new Uint32Array(e):new Uint16Array(e);this.index=new J(r,1)}else e&&e.buffer&&(this.index=new J(e,1));return this}computeVertexNormals(){let e=this.attributes.position;if(!e)return this;let t=e.count,r=new Float32Array(t*3),i=new le,s=new le,o=new le,c=new le,a=new le;if(this.index){let u=this.index.array;for(let l=0;l<u.length;l+=3){let m=u[l],h=u[l+1],y=u[l+2];i.set(e.getX(m),e.getY(m),e.getZ(m)),s.set(e.getX(h),e.getY(h),e.getZ(h)),o.set(e.getX(y),e.getY(y),e.getZ(y)),c.subVectors(o,s),a.subVectors(i,s),c.cross(a).normalize();for(let b of[m,h,y])r[b*3]+=c.x,r[b*3+1]+=c.y,r[b*3+2]+=c.z}}else for(let u=0;u<t;u+=3){i.set(e.getX(u),e.getY(u),e.getZ(u)),s.set(e.getX(u+1),e.getY(u+1),e.getZ(u+1)),o.set(e.getX(u+2),e.getY(u+2),e.getZ(u+2)),c.subVectors(o,s),a.subVectors(i,s),c.cross(a).normalize();for(let l=0;l<3;l++)r[(u+l)*3]=c.x,r[(u+l)*3+1]=c.y,r[(u+l)*3+2]=c.z}for(let u=0;u<t;u++){let l=r[u*3],m=r[u*3+1],h=r[u*3+2],y=Math.hypot(l,m,h)||1;r[u*3]=l/y,r[u*3+1]=m/y,r[u*3+2]=h/y}return this.setAttribute("normal",new J(r,3)),this}setFromBuffers(e,t,r,i){this.setAttribute("position",new J(e instanceof Float32Array?e:new Float32Array(e),3)),this.setAttribute("normal",new J(t instanceof Float32Array?t:new Float32Array(t),3)),this.setAttribute("uv",new J(r instanceof Float32Array?r:new Float32Array(r),2)),this.setIndex(i)}computeBoundingBox(){let e=this.attributes.position,t=new le(1/0,1/0,1/0),r=new le(-1/0,-1/0,-1/0);if(e&&e.count>0)for(let i=0;i<e.count;i++){let s=e.getX(i),o=e.getY(i),c=e.getZ(i);s<t.x&&(t.x=s),o<t.y&&(t.y=o),c<t.z&&(t.z=c),s>r.x&&(r.x=s),o>r.y&&(r.y=o),c>r.z&&(r.z=c)}else t.set(0,0,0),r.set(0,0,0);return this.boundingBox={min:t,max:r},this.boundingBox}center(){let e=this.computeBoundingBox(),t=(e.min.x+e.max.x)*.5,r=(e.min.y+e.max.y)*.5,i=(e.min.z+e.max.z)*.5,s=this.attributes.position;if(s&&s.count>0){for(let o=0;o<s.count;o++)s.setXYZ(o,s.getX(o)-t,s.getY(o)-r,s.getZ(o)-i);this.computeBoundingBox()}return this}dispose(){}},mt=class extends ge{constructor(e=1,t=1,r=1){super();let i=e/2,s=t/2,o=r/2,c=[-i,-s,o,i,-s,o,i,s,o,-i,s,o,i,-s,-o,-i,-s,-o,-i,s,-o,i,s,-o,-i,s,o,i,s,o,i,s,-o,-i,s,-o,-i,-s,-o,i,-s,-o,i,-s,o,-i,-s,o,i,-s,o,i,-s,-o,i,s,-o,i,s,o,-i,-s,-o,-i,-s,o,-i,s,o,-i,s,-o],a=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0],u=[0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1],l=[];for(let m=0;m<6;m++){let h=m*4;l.push(h,h+1,h+2,h,h+2,h+3)}this.setAttribute("position",new J(new Float32Array(c),3)),this.setAttribute("normal",new J(new Float32Array(a),3)),this.setAttribute("uv",new J(new Float32Array(u),2)),this.setIndex(l)}},qt=class extends ge{constructor(e=1,t=1){super();let r=e/2,i=t/2,s=[-r,i,0,r,i,0,-r,-i,0,r,-i,0],o=[0,0,1,0,0,1,0,0,1,0,0,1],c=[0,1,1,1,0,0,1,0],a=[0,2,1,2,3,1];this.setAttribute("position",new J(new Float32Array(s),3)),this.setAttribute("normal",new J(new Float32Array(o),3)),this.setAttribute("uv",new J(new Float32Array(c),2)),this.setIndex(a)}},dt=class extends ge{constructor(e=1,t=16,r=12){super(),t=Math.max(3,Math.floor(t)),r=Math.max(2,Math.floor(r));let i=[],s=[],o=[],c=[],a=[];for(let u=0;u<=r;u++){let l=[],m=u/r;for(let h=0;h<=t;h++){let y=h/t,b=y*Math.PI*2,d=m*Math.PI,g=-e*Math.cos(b)*Math.sin(d),T=e*Math.cos(d),P=e*Math.sin(b)*Math.sin(d);i.push(g,T,P);let f=Math.hypot(g,T,P)||1;s.push(g/f,T/f,P/f),o.push(y,1-m),l.push(i.length/3-1)}a.push(l)}for(let u=0;u<r;u++)for(let l=0;l<t;l++){let m=a[u][l+1],h=a[u][l],y=a[u+1][l],b=a[u+1][l+1];u!==0&&c.push(m,h,b),u!==r-1&&c.push(h,y,b)}this.setAttribute("position",new J(new Float32Array(i),3)),this.setAttribute("normal",new J(new Float32Array(s),3)),this.setAttribute("uv",new J(new Float32Array(o),2)),this.setIndex(c)}},Le=class extends ge{constructor(e=1,t=1,r=1,i=16){super(),i=Math.max(3,Math.floor(i));let s=[],o=[],c=[],a=[],u=r/2;for(let l=0;l<=1;l++){let m=l,h=l===0?e:t,y=l===0?u:-u;for(let b=0;b<=i;b++){let d=b/i,g=d*Math.PI*2,T=Math.sin(g),P=Math.cos(g);s.push(h*T,y,h*P),o.push(T,0,P),c.push(d,1-m)}}for(let l=0;l<i;l++){let m=l,h=l+i+1,y=l+i+2,b=l+1;a.push(m,h,b,h,y,b)}if(e>0){let l=s.length/3;s.push(0,u,0),o.push(0,1,0),c.push(.5,.5);let m=s.length/3;for(let h=0;h<=i;h++){let y=h/i*Math.PI*2,b=Math.sin(y),d=Math.cos(y);s.push(e*b,u,e*d),o.push(0,1,0),c.push(d*.5+.5,b*.5+.5)}for(let h=0;h<i;h++)a.push(l,m+h,m+h+1)}if(t>0){let l=s.length/3;s.push(0,-u,0),o.push(0,-1,0),c.push(.5,.5);let m=s.length/3;for(let h=0;h<=i;h++){let y=h/i*Math.PI*2,b=Math.sin(y),d=Math.cos(y);s.push(t*b,-u,t*d),o.push(0,-1,0),c.push(d*.5+.5,1-(b*.5+.5))}for(let h=0;h<i;h++)a.push(l,m+h+1,m+h)}this.setAttribute("position",new J(new Float32Array(s),3)),this.setAttribute("normal",new J(new Float32Array(o),3)),this.setAttribute("uv",new J(new Float32Array(c),2)),this.setIndex(a)}},jt=class extends Le{constructor(e=1,t=1,r=16){super(0,e,t,r)}},Kt=class extends ge{constructor(e=1,t=.4,r=12,i=32){super(),r=Math.max(3,Math.floor(r)),i=Math.max(3,Math.floor(i));let s=[],o=[],c=[],a=[];for(let u=0;u<=r;u++){let l=u/r*Math.PI*2;for(let m=0;m<=i;m++){let h=m/i*Math.PI*2,y=(e+t*Math.cos(l))*Math.cos(h),b=(e+t*Math.cos(l))*Math.sin(h),d=t*Math.sin(l);s.push(y,b,d);let g=e*Math.cos(h),T=e*Math.sin(h),P=y-g,f=b-T,M=d,p=Math.hypot(P,f,M)||1;o.push(P/p,f/p,M/p),c.push(m/i,u/r)}}for(let u=1;u<=r;u++)for(let l=1;l<=i;l++){let m=(i+1)*u+l-1,h=(i+1)*(u-1)+l-1,y=(i+1)*(u-1)+l,b=(i+1)*u+l;a.push(m,h,b,h,y,b)}this.setAttribute("position",new J(new Float32Array(s),3)),this.setAttribute("normal",new J(new Float32Array(o),3)),this.setAttribute("uv",new J(new Float32Array(c),2)),this.setIndex(a)}},Zt=class extends ge{constructor(e=1,t=.4,r=64,i=8,s=2,o=3){super(),r=Math.floor(r),i=Math.floor(i);let c=[],a=[],u=[],l=[],m=new le,h=new le,y=new le,b=new le,d=new le;function g(f,M){let p=Math.cos(M),S=Math.sin(M),_=o/s*M,w=e*(2+Math.cos(_))*.5;f.set(w*p,w*S,e*Math.sin(_)*.5)}let T=[];for(let f=0;f<=i;++f){let M=f/i*Math.PI*2;T.push(-t*Math.cos(M),t*Math.sin(M),f/i)}for(let f=0;f<=r;++f){let M=f/r,p=M*s*Math.PI*2;g(m,p),g(h,p+.01),y.subVectors(h,m).normalize(),b.addVectors(m,h).normalize(),d.crossVectors(y,b).normalize(),b.crossVectors(d,y).normalize();for(let S=0;S<=i;++S){let _=S*3,w=T[_],A=T[_+1],L=T[_+2],x=w*b.x+A*d.x,v=w*b.y+A*d.y,I=w*b.z+A*d.z;c.push(m.x+x,m.y+v,m.z+I);let R=Math.hypot(x,v,I)||1;a.push(x/R,v/R,I/R),u.push(M,L)}}let P=i+1;for(let f=1;f<=r;f++){let M=P*(f-1),p=M+P;for(let S=1;S<=i;S++){let _=M+(S-1),w=p+(S-1),A=p+S,L=M+S;l.push(_,w,L,w,A,L)}}this.setAttribute("position",new J(new Float32Array(c),3)),this.setAttribute("normal",new J(new Float32Array(a),3)),this.setAttribute("uv",new J(new Float32Array(u),2)),this.setIndex(l)}},ft=class{constructor(e=""){this.isTexture=!0;this.wrapS=10497;this.wrapT=10497;this.image=null;this.width=0;this.height=0;this.source=e,e&&typeof e=="object"&&(this.image=e)}dispose(){}},Jt=class{load(e,t){let r=new ft(e);return t?.(r),r}};function pe(n,e){return n!==void 0?Number(n):e}function Vt(n,e){return n!==void 0?!!n:e}var Re=class{constructor(e={}){this.name=e.name||"",this.color=new ve(e.color!==void 0?e.color:16777215),this.emissive=new ve(e.emissive!==void 0?e.emissive:0),this.emissiveIntensity=pe(e.emissiveIntensity,1),this.roughness=pe(e.roughness,.5),this.metalness=pe(e.metalness,.1),this.opacity=pe(e.opacity,1),this.transparent=Vt(e.transparent,!1),this.wireframe=Vt(e.wireframe,!1),this.side=pe(e.side,2),this.doubleSided=Vt(e.doubleSided,!0),this.map=e.map||null,this.clearcoat=pe(e.clearcoat,0),this.clearcoatRoughness=pe(e.clearcoatRoughness,0),this.sheen=pe(e.sheen,0),this.sheenColor=new ve(e.sheenColor!==void 0?e.sheenColor:0),this.sheenRoughness=pe(e.sheenRoughness,0),this.transmission=pe(e.transmission,0),this.thickness=pe(e.thickness,0),this.attenuationColor=new ve(e.attenuationColor!==void 0?e.attenuationColor:16777215),this.attenuationDistance=pe(e.attenuationDistance,1/0),this.ior=pe(e.ior,1.5),this.dispersion=pe(e.dispersion,0),this.iridescence=pe(e.iridescence,0),this.iridescenceIOR=pe(e.iridescenceIOR,1.3)}dispose(){}},Oe=class extends Re{},Qt=class extends Re{},en=class extends Re{},tn=class extends Re{},nn=class extends Re{},we=class n{constructor(){this.name="";this.matrixAutoUpdate=!0;this.visible=!0;this.castShadow=!1;this.receiveShadow=!1;this.parent=null;this.children=[];this.userData={};this.position=new le,this.rotation=new lt,this.quaternion=new ht,this.scale=new le(1,1,1),this.matrix=new Ue,this.matrixWorld=new Ue,this.rotation._onChange(()=>{this.quaternion.setFromEuler(this.rotation,!1)}),this.quaternion._onChange(()=>{let e=this.quaternion,t=Math.atan2(2*(e.w*e.x+e.y*e.z),1-2*(e.x*e.x+e.y*e.y)),r=Math.asin(Math.max(-1,Math.min(1,2*(e.w*e.y-e.z*e.x)))),i=Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z));this.rotation.set(t,r,i)})}add(...e){for(let t of e)t&&t instanceof n&&(t.parent&&t.parent.remove(t),t.parent=this,this.children.push(t));return this}remove(...e){for(let t of e){let r=this.children.indexOf(t);r!==-1&&(t.parent=null,this.children.splice(r,1))}return this}traverse(e){e(this);for(let t of this.children)t.traverse(e)}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale)}updateMatrixWorld(e=!1){tr(this),(this.matrixAutoUpdate||e)&&this.updateMatrix(),this.parent?this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix):this.matrixWorld.copy(this.matrix);for(let t of this.children)t.updateMatrixWorld(e)}lookAt(e,t,r){let i=typeof e=="object"?e:new le(e,t,r);this.updateMatrixWorld(!0);let s=new Ue;s.lookAt(this.position,i,new le(0,1,0));let o=s.elements,c=o[0],a=o[4],u=o[8],l=o[1],m=o[5],h=o[9],y=o[2],b=o[6],d=o[10],g=c+m+d;if(g>0){let T=.5/Math.sqrt(g+1);this.quaternion.set((b-h)*T,(u-y)*T,(l-a)*T,.25/T)}}},rn=class extends we{},Be=class extends we{constructor(t,r){super();this.isMesh=!0;let i=Array.isArray(r)?r[0]:r;this.geometry=t instanceof ge?t:t?(xe("unsupported geometry","BoxGeometry"),new mt(.5,.5,.5)):new ge,this.material=i instanceof Re?i:i?(xe("unsupported material","MeshStandardMaterial"),new Oe({color:13421772})):new Oe}};function tr(n){let e=Q().materializeDeclarativeGeometry;typeof e=="function"&&e(n)}var pt=1e4,bt=class extends Be{constructor(t,r,i=1){super(t,r);this.instanceColor=null;this.isInstancedMesh=!0;let s=Number(i);if(!Number.isFinite(s)||s<0||s>pt)throw new RangeError(`SecurityError: InstancedMesh count (${String(i)}) exceeds MAX_INSTANCES_PER_MESH (${pt})`);this.count=Math.floor(s);let o=new Float32Array(this.count*16);for(let c=0;c<this.count;c++){let a=c*16;o[a]=1,o[a+5]=1,o[a+10]=1,o[a+15]=1}this.instanceMatrix=new J(o,16)}setMatrixAt(t,r){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!r||!r.elements)return;let s=this.instanceMatrix.array,o=i*16;if(!(o+16>s.length))for(let c=0;c<16;c++){let a=Number(r.elements[c]);s[o+c]=Number.isFinite(a)?a:c%5===0?1:0}}getMatrixAt(t,r){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!r||!r.elements)return;let s=this.instanceMatrix.array,o=i*16;if(!(o+16>s.length))for(let c=0;c<16;c++)r.elements[c]=s[o+c]}setColorAt(t,r){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!r)return;if(!this.instanceColor||this.instanceColor.array.length<this.count*3){let c=new Float32Array(this.count*3);c.fill(1),this.instanceColor=new J(c,3)}let s=this.instanceColor.array,o=i*3;s[o]=Number.isFinite(r.r)?r.r:1,s[o+1]=Number.isFinite(r.g)?r.g:1,s[o+2]=Number.isFinite(r.b)?r.b:1}getColorAt(t,r){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!r)return;if(!this.instanceColor||this.instanceColor.array.length<(i+1)*3){r.setRGB(1,1,1);return}let s=this.instanceColor.array,o=i*3;r.setRGB(s[o],s[o+1],s[o+2])}dispose(){}},Ve=class extends we{constructor(e=16777215,t=1){super(),this.color=new ve(e),this.intensity=Number(t),this.type="directional"}},yt=class extends Ve{constructor(e,t){super(e,t),this.type="ambient"}},sn=class extends Ve{constructor(t,r){super(t,r);this.target=new we;this.type="directional"}},gt=class extends Ve{constructor(t,r,i=0,s=2){super(t,r);this.distance=0;this.decay=2;this.type="point",this.distance=i,this.decay=s}},xt=class extends we{},on=class extends xt{constructor(t=45,r=1,i=.1,s=1e3){super();this.target=new le(0,0,0);this.fov=Number(t),this.aspect=Number(r),this.near=Number(i),this.far=Number(s)}},vt=class extends we{constructor(){super(...arguments);this.background=null;this.environmentIntensity=1}toCanvas3D(){return Me.validate(this),Ye(this)}toGLB(){return Me.validate(this),st(this)}toUSDZ(){return Me.validate(this),qe(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let t=new Map,r=0;return this.traverse(i=>{if(i instanceof Be){let s=new Float32Array(i.matrixWorld.elements);t.set(r,s),i.name&&t.set(i.name,s),r++}}),t}},nr=Ye,rr=st,Gr=qe;var Me=class{static validate(e){let t=0,r=0,i=0,s=new Set,o=(a,u,l)=>{throw new Error(`SecurityError: Scene exceeds SECURITY_3D_MAX_${a} (${u}). Found: ${l}`)},c=(a,u)=>{if(!Number.isFinite(u))throw new Error(`SecurityError: Scene reports a non-finite ${a} count (${String(u)}), which cannot be bounds-checked.`);return u};e.traverse(a=>{if(tr(a),a instanceof Be||a.geometry?.attributes?.position?.count){if(i++,i>1e3&&o("MESHES",1e3,i),a instanceof bt){let l=c("instance",a.count);(l<0||l>pt)&&o("INSTANCES",pt,l)}let u=a.geometry;if(u){let l=0;if(u.attributes.position&&(l=c("vertex",u.attributes.position.count),t+=l,t>1e5&&o("VERTICES",1e5,t)),u.index){let m=c("index",u.index.count);r+=m,r>3e5&&o("INDICES",3e5,r);let h=u.index.array;if(h&&l>0){let y=Math.min(m,h.length);for(let b=0;b<y;b++){let d=h[b];if(!Number.isFinite(d)||d<0||d>=l)throw new Error(`SecurityError: Index buffer value (${String(d)}) out of vertex bounds [0, ${l}).`)}}}}if(a.material){let l=a.material;l.map&&s.add(l.map),l.normalMap&&s.add(l.normalMap),l.roughnessMap&&s.add(l.roughnessMap)}}}),s.size>16&&o("TEXTURES",16,s.size);for(let a of s){let u=a,l=u.image,m=Number(l?.width??u.width??0)||0,h=Number(l?.height??u.height??0)||0;(!Number.isFinite(m)||!Number.isFinite(h)||m>2048||h>2048)&&o("TEXTURE_DIMENSION",2048,Math.max(m,h))}}},an=class{constructor(e={}){this.shadowMap={enabled:!1,type:0};this.capabilities={isWebGL2:!0,maxTextures:16};this.boundViewer=null;this.isSandboxed=!1;this.containerId="";this.hasInitialModelRendered=!1;this.domElement=e.canvas||(typeof document<"u"?document.createElement("canvas"):{}),e.viewer&&(this.boundViewer=e.viewer),e.container?.threeLiveViewer&&(this.boundViewer=e.container.threeLiveViewer),e.canvas?.parentElement?.threeLiveViewer&&(this.boundViewer=e.canvas.parentElement.threeLiveViewer);let t=typeof WorkerGlobalScope<"u"&&typeof self<"u"&&self instanceof WorkerGlobalScope;this.isSandboxed=e.isSandboxed||t,this.containerId=e.containerId||""}setSize(e,t){return this}setPixelRatio(e){return this}setClearColor(e,t=1){let r=new ve(e);return this.boundViewer&&typeof this.boundViewer.setClearColor=="function"&&this.boundViewer.setClearColor(r.r,r.g,r.b,t),this}clear(){return this}dispose(){}render(e,t){if(this.isSandboxed){Me.validate(e);let i=(s,o)=>{typeof self<"u"&&typeof self.postMessage=="function"&&(o&&o.length?self.postMessage(s,o):self.postMessage(s))};if(this.hasInitialModelRendered){let s=e.getMeshTransforms(),o={};for(let[c,a]of s.entries())o[c]=Array.from(a);i({type:"3D_UPDATE_TRANSFORMS",containerId:this.containerId,transforms:o})}else{this.hasInitialModelRendered=!0;let s=nr(e),o=rr(e),c=(s.lights||[]).map(a=>({type:a.type,color:a.color,intensity:a.intensity,position:a.position}));i({type:"3D_MODEL_READY",containerId:this.containerId,glbBuffer:o.buffer,dynamicLights:c,camera:t?{fov:t.fov||60,position:[t.position.x,t.position.y,t.position.z]}:void 0},[o.buffer])}return}let r=this.boundViewer;!r&&this.domElement?.parentElement&&this.domElement.parentElement.threeLiveViewer&&(r=this.domElement.parentElement.threeLiveViewer,this.boundViewer=r),!r&&typeof window<"u"&&(r=window.__three_live_active_viewer__,this.boundViewer=r),r&&typeof r.loadModel=="function"&&(r._hasThreeLiveModelLoaded?typeof r.updateMeshTransforms=="function"&&r.updateMeshTransforms(e.getMeshTransforms()):(r.loadModel(e.toCanvas3D()),r._hasThreeLiveModelLoaded=!0))}};function jn(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var cn=class{constructor(e=!0){this.startTime=0;this.oldTime=0;this.elapsedTime=0;this.running=!1;this.autoStart=e,e&&this.start()}start(){this.startTime=jn(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running&&this.start(),this.running){let t=jn();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function Xr(){}var ct=new Proxy(Xr,{get:(n,e)=>{if(e==="isProxy")return!0;if(!(e==="constructor"||e==="__proto__"||e==="prototype"))return e==="domElement"?typeof document<"u"?document.createElement("canvas"):{}:e==="shadowMap"?{enabled:!1,type:0}:e==="capabilities"?{isWebGL2:!0,maxTextures:16}:e===Symbol.toPrimitive?()=>0:ct},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>ct,construct:()=>ct}),Kn=(()=>{try{if(typeof document>"u")return null;let n=document.currentScript;return n?.src?n.src:n?.textContent&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(new Blob([n.textContent],{type:"text/javascript"})):null}catch{return null}})();function Ge(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function De(n,e){if(!n||typeof n!="string")return!1;let t=n.trim();if(!t)return!1;try{let r=new URL(t,Ge());return!(r.protocol!=="https:"&&r.protocol!=="http:"&&r.protocol!=="blob:"||e?.requireSameOrigin&&r.protocol!=="blob:"&&typeof location<"u"&&location.origin&&location.origin!=="null"&&r.origin!==location.origin)}catch{return!1}}var Zn,je;function Wr(n){if(!De(n))throw new Error(`SecurityError: Refusing to create TrustedScriptURL for disallowed URL "${n}".`);let t=globalThis.trustedTypes;if(!t||typeof t.createPolicy!="function")return n;if(je===void 0||Zn!==t){Zn=t;try{je=t.createPolicy("three-live#worker",{createScriptURL:r=>{if(!De(r))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${r}".`);return r}})}catch{je=null}}return je?je.createScriptURL(n):n}function ir(){let n=Q().sandboxEngineSrc;if(n)return n;if(Kn)return Kn;try{if(typeof document>"u")return null;let e=Ge(),t=Array.from(document.querySelectorAll("script[src]"));for(let r of t){let i=r.src;if(!i)continue;let s=new URL(i,e).pathname;if(/(?:^|\/)(?:three|xr)-live[^/]*\.js$/.test(s)&&De(i,{requireSameOrigin:!0}))return i}}catch{}return null}function $r(){let n=ir();if(!n)throw new Error("Three-Live could not locate its own bundle URL, which the worker sandbox needs in order to load the THREE runtime. Set it explicitly, e.g. ThreeLiveElement.sandboxEngineSrc = new URL('three-live.min.js', import.meta.url).href. Refusing to execute the script, because unsandboxed host-realm execution is prohibited.");if(!De(n))throw new Error(`SecurityError: Refusing to load sandbox engine from disallowed URL "${n}". Only http:, https:, and blob: URLs are permitted.`);return new URL(n,Ge()).href}function Yr(){let n=Q().sandboxIframeSrc;if(n)return n;let e=ir();if(!e||!De(e))return null;let t=new URL(e,Ge());return t.protocol==="blob:"?null:new URL("three-live-sandbox.html",t).href}function qr(){let n=Yr();if(!n)throw new Error("Three-Live could not locate three-live-sandbox.html for iframe sandbox execution. Set ThreeLiveElement.sandboxIframeSrc (or ThreeLiveElement.sandboxEngineSrc) explicitly.");if(!De(n))throw new Error(`SecurityError: Refusing to load sandbox iframe from disallowed URL "${n}". Only http:, https:, and blob: URLs are permitted.`);return new URL(n,Ge()).href}function jr(){return!!Q().allowClientScripts}function Kr(n){if(!De(n))throw new Error(`SecurityError: Refusing to load procedural scene script from disallowed URL "${n}". Only http:, https:, and blob: URLs are permitted.`);return new URL(n,Ge()).href}var Zr=["fetch","XMLHttpRequest","WebSocket","WebSocketStream","WebTransport","EventSource","importScripts","Request","Response","Headers","navigator","WorkerNavigator","WorkerLocation","RTCPeerConnection","RTCDataChannel","FontFace","FontFaceSet","fonts","PerformanceObserver","ReportingObserver","indexedDB","IDBFactory","caches","CacheStorage","Cache","cookieStore","StorageManager","FileSystemHandle","Worker","SharedWorker","ServiceWorker","ServiceWorkerContainer","ServiceWorkerRegistration","registration","clients","BroadcastChannel","MessageChannel","MessagePort","createImageBitmap","OffscreenCanvas","WebAssembly","WorkerGlobalScope","DedicatedWorkerGlobalScope","trustedTypes","TrustedTypePolicyFactory","SharedArrayBuffer","Atomics"];function Jr(n,e){let t=self,r=n.nonce,i=n.engineSrc,s=n.allowedScriptUrl,o=n.allowClientScripts,c=n.revoked,a=t.postMessage.bind(t);function u(S){a({type:"ERROR",nonce:r,message:String(S)})}let l=typeof t.importScripts=="function"?t.importScripts.bind(t):null,m=s,h=null;try{let S=i;if(typeof t.trustedTypes<"u"&&t.trustedTypes&&typeof t.trustedTypes.createPolicy=="function")try{let _={createScriptURL:function(A){if(A!==i&&(!s||A!==s))throw new TypeError("Disallowed worker importScripts URL");return A}};o&&(_.createScript=function(A){return String(A)});let w=t.trustedTypes.createPolicy("three-live#worker-boot",_);S=w.createScriptURL(i),s&&(m=w.createScriptURL(s)),o&&typeof w.createScript=="function"&&(h=w.createScript.bind(w))}catch{}l(S)}catch(S){u('Sandbox failed to load the Three-Live engine from "'+i+'". It must be a same-origin (or CORS-enabled) IIFE bundle such as three-live.min.js. Underlying error: '+(S&&S.message||S));return}let y=t.THREE;if(!y||typeof y.Scene!="function"){u('Sandbox loaded "'+i+'" but it did not install a THREE namespace. Point sandboxEngineSrc at an IIFE build (three-live.min.js), not an ES module build.');return}if(Array.isArray(e)){let S=t.__THREE_LIVE_REGISTRY__;for(let _=0;_<e.length;_++)if(typeof e[_]=="function")try{e[_](y,S)}catch{}}for(let S=0;S<c.length;S++){let _=c[S],w=t;for(;w&&w!==Object.prototype;){if(w!==t)try{delete w[_]}catch{}try{Object.defineProperty(w,_,{value:void 0,writable:!1,configurable:!1,enumerable:!1})}catch{}try{w=Object.getPrototypeOf(w)}catch{break}}}let b=Object.freeze({now:function(){return Date.now()}}),d=t;for(;d&&d!==Object.prototype;){if(d!==t)try{delete d.performance}catch{}try{Object.defineProperty(d,"performance",{value:b,writable:!1,configurable:!1,enumerable:!1})}catch{}try{d=Object.getPrototypeOf(d)}catch{break}}let g=["3D_MODEL_READY","3D_UPDATE_TRANSFORMS"],T=!1;function P(S,_){if(S.type==="3D_MODEL_READY"){if(T)return;T=!0}S.nonce=r,_&&_.length?a(S,_):a(S)}let f=function(S,_){if(!S||g.indexOf(S.type)===-1)throw new Error("Sandboxed scripts may only post Three-Live scene messages ("+g.join(", ")+").");P(S,_)},M=t;for(;M&&M!==Object.prototype;){if(M===t||Object.prototype.hasOwnProperty.call(M,"postMessage"))try{Object.defineProperty(M,"postMessage",{value:f,writable:!1,configurable:!1})}catch{}try{M=Object.getPrototypeOf(M)}catch{break}}let p=!1;t.onmessage=function(S){let _=S&&S.data;if(!(!_||_.nonce!==r)&&!(_.type!=="EXECUTE"&&_.type!=="EXECUTE_URL")&&!p){p=!0;try{let w=new y.Scene,A=new y.PerspectiveCamera(60,1,.1,1e3),L=new y.WebGLRenderer({isSandboxed:!0});if(_.type==="EXECUTE_URL"){if(!s||_.scriptUrl!==s||typeof l!="function"){u("SecurityError: Refusing to execute unapproved script URL inside sandbox worker.");return}let x=m||s,v=l;if(l=null,m=null,t.THREE=y,t.scene=w,t.camera=A,t.renderer=L,v(x),typeof t.__THREE_LIVE_SCENE__=="function"){let I=t.__THREE_LIVE_SCENE__(y,w,A,L);I&&typeof I.toGLB=="function"&&(w=I)}else t.scene&&typeof t.scene.toGLB=="function"&&(w=t.scene)}else{if(!o){u("SecurityError: Client-modified script compilation (Use Case 1) is disabled in this sandbox worker.");return}let x=h?(0,eval)(h(`(function (THREE, scene, camera, renderer) {
|
|
304
322
|
return (function () {
|
|
305
|
-
`+
|
|
323
|
+
`+_.script+`
|
|
306
324
|
})();
|
|
307
325
|
})`)):new Function("THREE","scene","camera","renderer",`return (function () {
|
|
308
|
-
`+
|
|
309
|
-
})();`);m=null;let _=f(v,A,y,E);_&&typeof _.toGLB=="function"&&(A=_)}if(!I){v.SceneQuotaValidator&&v.SceneQuotaValidator.validate(A);let f=A.toGLB(),_=f instanceof ArrayBuffer?f:f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength);P({type:"3D_MODEL_READY",glbBuffer:_},[_])}c({type:"DONE",nonce:r})}catch(A){a(A&&A.message||A)}}},c({type:"READY",nonce:r})}function rr(n,e,t){let r=t?.allowedScriptUrl??null,i=t?.allowClientScripts??r===null,s={nonce:e,engineSrc:n,allowedScriptUrl:r,allowClientScripts:i,revoked:qr},o=(J().workerExtensionInstallers??[]).map(u=>`(${u.toString()})`).join(",");return`'use strict';(${Yr.toString()})(${JSON.stringify(s)},[${o}]);`}function ir(n){n.onError?.(new Error("SecurityError: Sandboxed script exceeded SECURITY_3D_SANDBOX_TIMEOUT_MS (3000 ms) and was terminated.")),n.onToast?.("Security Error: script timed out and was stopped.")}var Le=0;function sr(){try{let n=new Uint32Array(4);return globalThis.crypto?.getRandomValues(n),Array.from(n,t=>t.toString(16).padStart(8,"0")).join("")}catch{return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}}function jr(n){try{return new TextEncoder().encode(n).length}catch{return n.length}}var Kr=1024,Zr=256;function Kn(n){if(!Array.isArray(n)&&!(n instanceof Float32Array)||n.length!==16)return!1;for(let e=0;e<16;e++){let t=n[e];if(typeof t!="number"||!Number.isFinite(t))return!1}return!0}function or(n,e){if(!n||typeof n!="object")return null;let t=n;if(t.nonce!==e)return null;switch(t.type){case"READY":return{type:"READY"};case"DONE":return{type:"DONE"};case"ERROR":return{type:"ERROR",message:(typeof t.message=="string"?t.message:String(t.message??"Unknown worker error")).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").slice(0,Kr)};case"3D_UPDATE_TRANSFORMS":{let i=t.transforms;if(Array.isArray(i)){if(i.length>1e3)return null;for(let s of i)if(!Kn(s))return null;return{type:"3D_UPDATE_TRANSFORMS",transforms:i}}if(i&&typeof i=="object"){let s=Object.keys(i);if(s.length>1e3)return null;let o=Object.create(null),u=i;for(let c of s){if(c.length>Zr||c==="__proto__"||c==="constructor"||c==="prototype")return null;let a=u[c];if(!Kn(a))return null;o[c]=a}return{type:"3D_UPDATE_TRANSFORMS",transforms:o}}return null}case"3D_MODEL_READY":{let i=t.glbBuffer;return!(i instanceof ArrayBuffer)||i.byteLength>16777216?null:{type:"3D_MODEL_READY",payload:i}}default:return null}}function Jr(n){let e=jr(n);if(e>1048576)throw new Error(`SecurityError: Script length (${e} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function ar(n,e,t,r){switch(n.type){case"READY":return;case"3D_UPDATE_TRANSFORMS":e.onUpdateTransforms?.(n.transforms);return;case"3D_MODEL_READY":if(r.modelDispatched)return;r.modelDispatched=!0,e.onModelReady(n.payload);return;case"DONE":t();return;case"ERROR":t(),e.onError?.(new Error(`Worker script error: ${n.message}`));return;default:return n}}function Qr(n,e,t,r){let i=sr(),s=rr(e,i,n.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:n.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),o=document.createElement("iframe");o.setAttribute("sandbox","allow-scripts"),o.setAttribute("aria-hidden","true"),o.tabIndex=-1,o.style.display="none",o.src=t,Le++;let u=!1,c=!1,a={modelDispatched:!1},l,h=()=>{if(u||c)return;let d=o.contentWindow;!d||typeof d.postMessage!="function"||(c=!0,d.postMessage(n.kind==="url"?{type:"SANDBOX_RUN",nonce:i,workerSource:s,scriptUrl:n.scriptUrl}:{type:"SANDBOX_RUN",nonce:i,workerSource:s,script:n.script},"*"))},m=()=>{},v=d=>{if(u||!o.contentWindow||d.source!==o.contentWindow)return;let g=d.data;if(g&&typeof g=="object"&&g.type==="IFRAME_READY"){h();return}let I=or(g,i);I&&ar(I,r,m,a)};m=()=>{u||(u=!0,l!==void 0&&clearTimeout(l),Le=Math.max(0,Le-1),typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("message",v),typeof o.remove=="function"?o.remove():o.parentNode&&o.parentNode.removeChild(o))},l=setTimeout(()=>{u||(m(),ir(r))},3e3),typeof globalThis.addEventListener=="function"&&globalThis.addEventListener("message",v),o.onload=()=>{h()},o.onerror=()=>{m(),r.onError?.(new Error(`Sandbox iframe failed to load "${t}". Verify that three-live-sandbox.html is served at that URL.`))};let b=document.body||document.documentElement;if(!b||typeof b.appendChild!="function"){m();let d=new Error("SecurityError: Cannot mount sandbox iframe because document.body is unavailable.");throw r.onError?.(d),d}return b.appendChild(o),{terminate:m}}function Zn(n,e,t,r){if(e==="worker"&&typeof Worker>"u")return r("Sandboxed procedural execution requires Web Workers, but Workers are unavailable in this environment. For host security, Three-Live prohibits unsandboxed in-process evaluation.","Security Error: Web Workers unavailable. Script execution aborted.");if(e==="iframe"&&(typeof document>"u"||typeof document.createElement!="function"))return r("Sandboxed iframe execution requires a DOM environment with document.createElement. Refusing to evaluate in the host realm.","Security Error: DOM unavailable for iframe sandbox.");if(Le>=32)return r(`SecurityError: ${Le} sandbox workers are already running, which meets SECURITY_3D_MAX_CONCURRENT_TASKS (32). Refusing to start another.`,"Security Error: too many concurrent sandboxed scripts.");let i;try{i=Hr()}catch(m){let v=m instanceof Error?m.message:String(m);return r(v,"Security Error: sandbox engine URL is not configured.")}if(e==="iframe"){let m;try{m=Gr()}catch(v){let b=v instanceof Error?v.message:String(v);return r(b,"Security Error: sandbox iframe URL is not configured.")}try{return Promise.resolve(Qr(n,i,m,t))}catch(v){return Promise.reject(v)}}let s=sr(),o=rr(i,s,n.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:n.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),u;try{let m=new Blob([o],{type:"application/javascript"}),v=URL.createObjectURL(m);try{let b=zr(v);u=new Worker(b)}finally{URL.revokeObjectURL(v)}}catch(m){let v=m instanceof Error?m.message:String(m);return r(`Failed to initialize Web Worker for sandboxed execution (CSP may block blob workers): ${v}`,"Security Error: Failed to start Worker sandbox.")}Le++;let c=!1,a={modelDispatched:!1},l,h=()=>{c||(c=!0,l!==void 0&&clearTimeout(l),Le=Math.max(0,Le-1),u.terminate())};return l=setTimeout(()=>{c||(h(),ir(t))},3e3),u.onmessage=m=>{let v=or(m.data,s);v&&ar(v,t,h,a)},u.onerror=m=>{h(),t.onError?.(new Error(`Worker execution error: ${m.message}`))},n.kind==="url"?u.postMessage({type:"EXECUTE_URL",scriptUrl:n.scriptUrl,nonce:s}):u.postMessage({type:"EXECUTE",script:n.script,nonce:s}),Promise.resolve({terminate:h})}function Jn(n,e){return n==="none"||n==="unsafe-host-realm"?e(`SecurityError: sandbox="${n}" is prohibited. Sandboxing is mandatory for live compilation and cannot be bypassed. Use sandbox="worker" (default) or sandbox="iframe".`,`Security Error: sandbox="${n}" is not permitted.`):n!=="worker"&&n!=="iframe"?e(`SecurityError: Unsupported sandbox mode "${n}". Live compilation requires sandbox="worker" or sandbox="iframe".`,"Security Error: unsupported sandbox mode."):null}var vn={execute(n,e,t,r){let i=(u,c)=>{let a=new Error(u);return t.onError?.(a),c&&t.onToast?.(c),Promise.reject(a)},s=Jn(e,i);if(s)return s;try{Jr(n)}catch(u){let c=u instanceof Error?u.message:String(u);return i(c,"Security Error: script exceeds the size limit.")}return r?.allowClientScripts??Wr()?Zn({kind:"script",script:n},e,t,i):i(st,ot)},executeUrl(n,e,t){let r=(o,u)=>{let c=new Error(o);return t.onError?.(c),u&&t.onToast?.(u),Promise.reject(c)},i=Jn(e,r);if(i)return i;let s;try{s=$r(n)}catch(o){let u=o instanceof Error?o.message:String(o);return r(u,"Security Error: disallowed scene script URL.")}return Zn({kind:"url",scriptUrl:s},e,t,r)}},Tt=new Set;function Me(n,e){let t=`[three-live] ${n} is unsupported; degraded to ${e}.`;Tt.has(t)||(Tt.add(t),typeof console<"u"&&typeof console.warn=="function"&&console.warn(t))}function ei(){return Array.from(Tt)}function ti(){Tt.clear()}var _t=class extends Xe{constructor(e={}){Me("ShaderMaterial","MeshStandardMaterial");let t=e.uniforms||{},r=t.color?.value??t.uColor?.value??t.diffuse?.value??e.color;super({color:r!==void 0?r:8421504,opacity:t.opacity?.value??e.opacity??1,transparent:!!e.transparent,wireframe:!!e.wireframe,side:e.side}),this.uniforms=t}},ni=_t,$e=class extends xt{constructor(e=1,t=0,r="PolyhedronGeometry"){Me(r,"SphereGeometry");let i=Math.max(4,Math.min(32,4<<Math.min(t,3)));super(e,i,i)}},mn=class extends $e{constructor(e=1,t=0){super(e,t,"IcosahedronGeometry")}},dn=class extends $e{constructor(e=1,t=0){super(e,t,"OctahedronGeometry")}},fn=class extends $e{constructor(e=1,t=0){super(e,t,"DodecahedronGeometry")}},pn=class extends $e{constructor(e=1,t=0){super(e,t,"TetrahedronGeometry")}},bn=class extends Fe{constructor(e=1,t=1,r=4,i=8){Me("CapsuleGeometry","CylinderGeometry"),super(e,e,t+e*2,i)}},yn=class extends Fe{constructor(e=.5,t=1,r=16){Me("RingGeometry","CylinderGeometry"),super(t,t,.01,Math.max(8,r))}},gn=class extends Fe{constructor(e=1,t=16){Me("CircleGeometry","CylinderGeometry"),super(e,e,.01,Math.max(8,t))}},xn=class extends St{constructor(t,r,i=0,s=Math.PI/3,o=0,u=2){Me("SpotLight","PointLight");super(t,r,i,u);this.target=new Ee;this.angle=Math.PI/3;this.penumbra=0;this.angle=s,this.penumbra=o}},Ct=class extends Mt{constructor(e,t,r){Me("HemisphereLight","AmbientLight"),super(e,r),this.groundColor=new Re(t??4473924)}},ri=Ct,cr={Vector2:Wt,Vector3:se,Vector4:$t,Euler:bt,Quaternion:yt,Matrix4:He,Matrix3:qt,Color:Re,MathUtils:Or,BufferAttribute:Z,Float32BufferAttribute:Yt,Uint16BufferAttribute:jt,Uint32BufferAttribute:Kt,BufferGeometry:Ae,BoxGeometry:gt,PlaneGeometry:Zt,SphereGeometry:xt,CylinderGeometry:Fe,ConeGeometry:Jt,TorusGeometry:Qt,TorusKnotGeometry:en,IcosahedronGeometry:mn,OctahedronGeometry:dn,DodecahedronGeometry:fn,TetrahedronGeometry:pn,CapsuleGeometry:bn,RingGeometry:yn,CircleGeometry:gn,Texture:vt,TextureLoader:tn,Material:Ce,MeshStandardMaterial:Xe,MeshBasicMaterial:nn,MeshLambertMaterial:rn,MeshPhongMaterial:sn,MeshPhysicalMaterial:on,ShaderMaterial:_t,RawShaderMaterial:ni,Object3D:Ee,Group:an,Mesh:Ge,InstancedMesh:At,Light:We,AmbientLight:Mt,DirectionalLight:cn,PointLight:St,SpotLight:xn,HemisphereLight:Ct,RectAreaLight:ri,Camera:Rt,PerspectiveCamera:un,Scene:Et,WebGLRenderer:ln,Clock:hn,SceneQuotaValidator:_e,exportSceneToCanvas3D:er,exportSceneToGLB:tr,exportSceneToUSDZ:Br,generateUSDZ:dt,glbToUSDZ:mt,sceneToCanvas3D:Ze,sceneToGLB:ht,sceneToUSDZ:Je,authorScriptRunner:vn,getAuthorWarnings:ei,clearAuthorWarnings:ti};Object.freeze(_e);Object.freeze(_e.prototype);Object.freeze(Et.prototype);Object.freeze(cr);var ke=new Proxy(cr,{get:(n,e)=>{if(e in n)return n[e];let t=J().authorNamespace;return t&&typeof e=="string"&&e in t?t[e]:(typeof e=="string"&&e!=="then"&&e!=="toJSON"&&!e.startsWith("__")&&Me(`THREE.${e}`,"no-op proxy"),ft)},has:(n,e)=>{if(e in n)return!0;let t=J().authorNamespace;return!!(t&&typeof e=="string"&&e in t)},set:(n,e)=>{throw new TypeError(`Cannot assign to read only property '${String(e)}' of #<THREE>`)},defineProperty:(n,e)=>{throw new TypeError(`Cannot define property '${String(e)}', object is not extensible`)},deleteProperty:(n,e)=>{throw new TypeError(`Cannot delete property '${String(e)}' of #<THREE>`)},setPrototypeOf:()=>{throw new TypeError("#<THREE> is not extensible")}}),pt=J();pt.threeNamespace=ke;if(pt.workerExtensionInstallers)for(let n of pt.workerExtensionInstallers)n(ke,pt);var Gt={name:"three_author",THREE:ke};var qe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;typeof qe.THREE>"u"&&(qe.THREE=ke);typeof qe.requestAnimationFrame!="function"&&(qe.requestAnimationFrame=()=>(Me("requestAnimationFrame","single-frame static evaluation"),0));typeof qe.cancelAnimationFrame!="function"&&(qe.cancelAnimationFrame=()=>{});if(typeof window<"u"){let n=window;n.ThreeLive=n.ThreeLive||{},n.ThreeLive.THREE=ke,n.ThreeLivePlugins=n.ThreeLivePlugins||{},n.ThreeLivePlugins.threeAuthor=Gt,n.ThreeLivePlugins.three_author=Gt,n.ThreeLivePlugins["three-author"]=Gt}var ii=typeof HTMLElement<"u"?HTMLElement:class{};typeof CustomEvent>"u"&&typeof Event<"u"&&(globalThis.CustomEvent=class extends Event{constructor(n,e){super(n,e),this.detail=e?.detail??null}});var le=class le extends ii{constructor(){super(...arguments);this.viewer=null;this.canvas=null;this.posterEl=null;this.arButton=null;this.currentModel=null;this.activeXRSession=null;this.toastTimer=null;this.currentModelLimits=void 0;this.isModelLoaded=!1;this.scriptHandle=null;this.resizeObserver=null;this.mutationObserver=null}static get arProvider(){return J().arProvider}static set arProvider(t){J().arProvider=t}static get scriptRunner(){return J().scriptRunner}static set scriptRunner(t){J().scriptRunner=t}static get sandboxEngineSrc(){return J().sandboxEngineSrc??null}static set sandboxEngineSrc(t){J().sandboxEngineSrc=t}static get sandboxIframeSrc(){return J().sandboxIframeSrc??null}static set sandboxIframeSrc(t){J().sandboxIframeSrc=t}static get allowClientScripts(){return!!J().allowClientScripts}static set allowClientScripts(t){J().allowClientScripts=t}static registerScriptRunner(t){le.scriptRunner=t}static registerDecoder(t,r){he.registerDecoder(t,r)}static getDecoder(t){return he.getDecoder(t)}static registerAR(t){typeof t=="function"?le.arProvider={activateAR:t}:le.arProvider=t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(i=>{i instanceof le&&i.updateARButtonVisibility()})}static isARSupported(){return!!le.arProvider}getLoadedModel(){return this.currentModel}connectedCallback(){if(typeof document>"u")return;(!this.style.display||this.style.display==="inline")&&(this.style.display="block"),getComputedStyle(this).position==="static"&&(this.style.position="relative"),this.style.overflow="hidden",this.setupDOM(),this.initViewer(),this.setupResizeObserver();let t=this.getAttribute("src"),r=this.getAttribute("script-src");if(t)this.loadModelFromSrc(t).catch(()=>{});else if(r)this.loadScriptFromSrc(r).catch(()=>{});else{let i=this.querySelector('script[type="text/three"], script[type="text/three-live"]');i&&i.textContent&&this.executeScript(i.textContent).catch(()=>{})}for(let i of he.getRegisteredPlugins())i.onElementConnected?.(this)}disconnectedCallback(){for(let t of he.getRegisteredPlugins())t.onElementDisconnected?.(this);this.scriptHandle&&(this.scriptHandle.terminate(),this.scriptHandle=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.activeXRSession&&(this.activeXRSession.stop?.().catch?.(()=>{}),this.activeXRSession=null),this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=null),this.viewer&&(this.viewer.destroy(),this.viewer=null),this.isModelLoaded=!1}attributeChangedCallback(t,r,i){if(r!==i){switch(t){case"src":i&&this.loadModelFromSrc(i).catch(()=>{});break;case"camera-target":this.applyCameraTarget(i);break;case"min-camera-orbit":case"max-camera-orbit":this.applyOrbitLimits();break;case"field-of-view":this.applyFieldOfView(i);break;case"script-src":i&&this.loadScriptFromSrc(i).catch(()=>{});break;case"sandbox":case"allow-client-scripts":case"ios-src":break;case"poster":this.updatePoster(i);break;case"camera-orbit":this.applyCameraOrbit(i);break;case"selected-mesh":this.viewer&&i!==null&&this.viewer.setSelectedMesh(i);break;case"exposure":if(this.viewer&&i!==null){let s=parseFloat(i);isNaN(s)||this.viewer.setExposure(s)}break;case"shadow-intensity":case"shadow-softness":this.viewer&&this.viewer.setShadow(this.shadowIntensity,this.shadowSoftness);break;case"tone-mapping":this.viewer&&i&&this.viewer.setToneMapping(i);break;case"environment-image":this.viewer&&this.viewer.setEnvironmentImage(i).catch(()=>{});break;case"skybox-image":this.viewer&&this.viewer.setSkyboxImage?.(i)?.catch?.(()=>{});break;case"camera-controls":{let s=this.cameraControls;this.viewer&&this.viewer.setInteractive?.(s),this.canvas&&(this.canvas.style.touchAction=s?"none":"auto");break}case"autoplay":this.viewer&&this.viewer.setAutoplay(i!==null&&i!=="false");break;case"animation-name":this.viewer&&i!==null&&this.viewer.setAnimationName(i);break;case"variant-name":this.viewer&&this.selectVariant(i);break;case"auto-rotate":this.viewer&&this.viewer.setAutoRotate(i!==null&&i!=="false");break;case"auto-rotate-delay":this.viewer&&this.viewer.setAutoRotateDelay(this.autoRotateDelay);break;case"rotation-per-second":this.viewer&&this.viewer.setAutoRotateSpeed(this.parseRotationPerSecond(i));break;case"ar":this.updateARButtonVisibility();break}for(let s of he.getRegisteredPlugins())s.onAttributeChanged?.(this,t,r,i)}}getAttr(t){return this.getAttribute(t)}setAttr(t,r){r!==null?this.setAttribute(t,r):this.removeAttribute(t)}getBoolAttr(t){return this.hasAttribute(t)&&this.getAttribute(t)!=="false"}setBoolAttr(t,r){r?this.setAttribute(t,""):this.removeAttribute(t)}getFloatAttr(t,r){let i=this.getAttribute(t);return i!==null?parseFloat(i):r}get src(){return this.getAttr("src")}set src(t){this.setAttr("src",t)}get cameraControls(){return this.getBoolAttr("camera-controls")}set cameraControls(t){this.setBoolAttr("camera-controls",t)}get cameraOrbit(){return this.getAttr("camera-orbit")}set cameraOrbit(t){this.setAttr("camera-orbit",t)}get cameraTarget(){return this.getAttr("camera-target")}set cameraTarget(t){this.setAttr("camera-target",t)}get minCameraOrbit(){return this.getAttr("min-camera-orbit")}set minCameraOrbit(t){this.setAttr("min-camera-orbit",t)}get maxCameraOrbit(){return this.getAttr("max-camera-orbit")}set maxCameraOrbit(t){this.setAttr("max-camera-orbit",t)}get fieldOfView(){return this.getAttr("field-of-view")}set fieldOfView(t){this.setAttr("field-of-view",t)}get iosSrc(){return this.getAttr("ios-src")}set iosSrc(t){this.setAttr("ios-src",t)}get scriptSrc(){return this.getAttr("script-src")}set scriptSrc(t){this.setAttr("script-src",t)}get sandbox(){return this.getAttribute("sandbox")||(J().sandboxIframeSrc?"iframe":"worker")}set sandbox(t){this.setAttribute("sandbox",t)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||le.allowClientScripts}set allowClientScripts(t){this.setBoolAttr("allow-client-scripts",t)}get poster(){return this.getAttr("poster")}set poster(t){this.setAttr("poster",t)}get selectedMesh(){return this.getAttr("selected-mesh")}set selectedMesh(t){this.setAttr("selected-mesh",t)}get exposure(){return this.getFloatAttr("exposure",1)}set exposure(t){this.setAttribute("exposure",String(t))}get autoRotate(){return this.getBoolAttr("auto-rotate")}set autoRotate(t){this.setBoolAttr("auto-rotate",t)}get autoRotateDelay(){return this.getFloatAttr("auto-rotate-delay",3e3)}set autoRotateDelay(t){this.setAttribute("auto-rotate-delay",String(t))}get rotationPerSecond(){return this.getAttr("rotation-per-second")||"30deg"}set rotationPerSecond(t){this.setAttr("rotation-per-second",t)}get turntableRotation(){return this.viewer?this.viewer.turntableRotation:0}get ar(){return this.hasAttribute("ar")}set ar(t){this.setBoolAttr("ar",t)}get arScale(){return this.getAttribute("ar-scale")||"auto"}set arScale(t){this.setAttribute("ar-scale",t)}get arPlacement(){return this.getAttribute("ar-placement")||"floor"}set arPlacement(t){this.setAttribute("ar-placement",t)}get canActivateAR(){return le.isARSupported()}get shadowIntensity(){return this.getFloatAttr("shadow-intensity",0)}set shadowIntensity(t){this.setAttribute("shadow-intensity",String(t))}get shadowSoftness(){return this.getFloatAttr("shadow-softness",.5)}set shadowSoftness(t){this.setAttribute("shadow-softness",String(t))}get toneMapping(){return this.getAttribute("tone-mapping")||"neutral"}set toneMapping(t){this.setAttribute("tone-mapping",t)}get bloom(){return this.getFloatAttr("bloom",0)}set bloom(t){this.setAttribute("bloom",String(t))}get bloomThreshold(){return this.getFloatAttr("bloom-threshold",.8)}set bloomThreshold(t){this.setAttribute("bloom-threshold",String(t))}get bloomRadius(){return this.getFloatAttr("bloom-radius",.5)}set bloomRadius(t){this.setAttribute("bloom-radius",String(t))}get outlineSelected(){return this.getBoolAttr("outline-selected")}set outlineSelected(t){this.setBoolAttr("outline-selected",t)}get outlineColor(){return this.getAttr("outline-color")||"#38bdf8"}set outlineColor(t){this.setAttr("outline-color",t)}get environmentImage(){return this.getAttr("environment-image")}set environmentImage(t){this.setAttr("environment-image",t)}get skyboxImage(){return this.getAttr("skybox-image")}set skyboxImage(t){this.setAttr("skybox-image",t)}get autoplay(){return this.getBoolAttr("autoplay")}set autoplay(t){this.setBoolAttr("autoplay",t)}get animationName(){return this.getAttr("animation-name")}set animationName(t){this.setAttr("animation-name",t)}get availableAnimations(){return this.viewer?this.viewer.getAvailableAnimations():[]}get variantName(){return this.viewer?this.viewer.getVariantName():this.getAttr("variant-name")}set variantName(t){this.setAttr("variant-name",t)}get availableVariants(){return this.viewer?this.viewer.getAvailableVariants():[]}selectVariant(t){if(!this.viewer)return!1;let r=this.viewer.selectVariant(t);return r&&this.dispatchEvent(new CustomEvent("variant-applied",{bubbles:!0,composed:!0,detail:{variantName:this.viewer.getVariantName()}})),r}get model(){let t=this.viewer?this.viewer.getModelMaterials():[];return{materials:t,getMaterialByName(r){return t.find(i=>i.name===r)??null}}}play(){this.viewer&&this.viewer.playAnimation(this.animationName||void 0)}pause(){this.viewer&&this.viewer.pauseAnimation()}resetCamera(){this.viewer?.resetCamera()}resetTurntableRotation(t=0){this.viewer?.resetTurntableRotation(t)}setCamera(t,r,i,s){this.viewer&&this.viewer.setCamera(t,r,i,s)}getCameraOrbit(){return this.viewer?this.viewer.getCameraOrbit():{theta:0,phi:0,radius:3,toString(){return"0rad 0rad 3m"}}}getCameraTarget(){return this.viewer?this.viewer.getCameraTarget():{x:0,y:0,z:0,toString(){return"0m 0m 0m"}}}getFieldOfView(){return this.viewer?this.viewer.getFieldOfView():45}jumpCameraToGoal(){this.viewer?.jumpCameraToGoal()}toDataURL(t,r){return this.viewer&&this.viewer.render?.(),this.canvas?this.canvas.toDataURL(t,r):""}toBlob(t){return this.viewer&&this.viewer.render?.(),new Promise((r,i)=>{if(!this.canvas||typeof this.canvas.toBlob!="function"){i(new Error("Canvas toBlob is not supported in this environment."));return}this.canvas.toBlob(s=>{s?r(s):i(new Error("Failed to capture canvas blob."))},t?.mimeType,t?.qualityArgument)})}positionAndNormalFromPoint(t,r){if(!this.viewer)return null;let i=this.viewer.raycastFromScreenPoint(t,r);if(!i)return null;let[s,o,u]=i.hitPoint||i.point,[c,a,l]=i.normal;return{position:{x:s,y:o,z:u,toString(){return`${s}m ${o}m ${u}m`}},normal:{x:c,y:a,z:l,toString(){return`${c}m ${a}m ${l}m`}}}}async loadModel(t){return this.loadModelWithLimits(t)}async loadModelWithLimits(t,r){if(!this.viewer){this.currentModel=t,this.currentModelLimits=r;return}try{let i;if(typeof t=="string"){this.isModelLoaded=!1,this.viewer?.clearScene?.();let c=await fetch(t);if(!c.ok)throw new Error(`Failed to load 3D model from "${t}": HTTP ${c.status}`);i=await c.arrayBuffer()}else i=t;let s=Te(i);this.viewer.loadGLBData(s,r),this.currentModel=s,this.currentModelLimits=r,this.isModelLoaded=!0,this.hidePoster(),this.updateHotspots();let o=this.getAttribute("selected-mesh");o&&this.viewer.setSelectedMesh(o);let u=this.getAttribute("variant-name");u&&this.selectVariant(u),this.dispatchEvent(new CustomEvent("load",{bubbles:!0,composed:!0,detail:{model:s}}))}catch(i){throw this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:i}})),i}}showToast(t,r=4500){if(typeof document>"u")return;let i=this.querySelector(".three-live-toast");i||(i=document.createElement("div"),i.className="three-live-toast",i.style.cssText="position:absolute;bottom:70px;left:50%;transform:translateX(-50%) translateY(10px);z-index:10;padding:10px 16px;background-color:rgba(15,23,42,0.94);color:#f8fafc;border:1px solid rgba(56,189,248,0.45);border-radius:14px;font:500 13px/1.35 system-ui,-apple-system,sans-serif;box-shadow:0 10px 25px rgba(0,0,0,0.45);backdrop-filter:blur(12px);pointer-events:none;opacity:0;transition:opacity .25s ease,transform .25s ease;max-width:88%;text-align:center;white-space:normal;word-break:break-word",this.appendChild(i)),i.textContent=t,this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=null),typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{i&&(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)")}):(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)"),this.toastTimer=setTimeout(()=>{i&&(i.style.opacity="0",i.style.transform="translateX(-50%) translateY(10px)"),this.toastTimer=null},r)}async activateAR(){if(this.activeXRSession&&typeof this.activeXRSession.isSessionActive=="function"&&this.activeXRSession.isSessionActive()&&(await this.activeXRSession.stop().catch(()=>{}),this.activeXRSession=null),!this.currentModel){let i=new Error("No 3D model is loaded in <three-live>.");throw this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(i.message,6e3),i}if(!le.arProvider){let i=new Error("AR module not bundled. Use the default 'three-live' bundle or call ThreeLiveElement.registerAR().");throw this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(i.message,6e3),i}let t=this.getAttribute("ios-src"),r=(this.getAttribute("ar-modes")||"").split(/\s+/).filter(Boolean);try{this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"session-started"}}));let i=await le.arProvider.activateAR({model:t||this.currentModel,glbUrl:typeof this.currentModel=="string"?this.currentModel:void 0,view:this.viewer||void 0,element:this,preferredModes:r.length>0?r:void 0,arScale:this.arScale,arPlacement:this.arPlacement,webXROptions:{onExit:()=>{this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"not-presenting"}}))},onError:s=>{this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:s}})),this.showToast(`AR error: ${s.message}`,6e3)}}});if(i.success)i.session&&(this.activeXRSession=i.session),i.mode==="quick-look"?this.showToast("Opening Apple AR Quick Look..."):i.mode==="scene-viewer"?this.showToast("Opening Google Scene Viewer..."):i.mode==="webxr"&&this.showToast("WebXR AR session started.");else{let s=typeof navigator<"u"&&navigator.userAgent||"",o=/Macintosh/i.test(s)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1),u=/Android|iPhone|iPad|iPod/i.test(s);if(o&&!u&&typeof document<"u"&&this.currentModel&&le.arProvider.createUSDZBlob)try{let c=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:le.arProvider.createUSDZBlob(this.currentModel),a=URL.createObjectURL(c),l=document.createElement("a");l.href=a,l.download="three_live_model.usdz",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(a),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.",6e3)}else this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.",6e3);i.error&&this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i.error}}))}return i}catch(i){throw this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(`AR error: ${i.message||String(i)}`,6e3),i}}setupDOM(){let t=this.querySelector("canvas");t||(t=document.createElement("canvas"),t.style.width="100%",t.style.height="100%",t.style.display="block",t.style.touchAction=this.cameraControls?"none":"auto",t.style.outline="none",this.appendChild(t)),this.canvas=t;let r=this.getAttribute("poster");r&&this.updatePoster(r),this.createARButton(),typeof MutationObserver<"u"&&!this.mutationObserver&&(this.mutationObserver=new MutationObserver(()=>{this.updateARButtonVisibility()}),this.mutationObserver.observe(this,{childList:!0}))}initViewer(){if(!this.canvas)return;let t=this.autoRotate,r=this.exposure,i=this.parseOrbitLimit(this.getAttribute("min-camera-orbit")),s=this.parseOrbitLimit(this.getAttribute("max-camera-orbit")),o=this.parseCameraTarget(this.getAttribute("camera-target")),u=this.parseFieldOfView(this.getAttribute("field-of-view"));this.viewer=new he(this,this.canvas,{autoRotate:t,autoRotateDelay:this.autoRotateDelay,autoRotateSpeed:this.parseRotationPerSecond(this.getAttribute("rotation-per-second")),exposure:r,shadowIntensity:this.shadowIntensity,shadowSoftness:this.shadowSoftness,toneMapping:this.toneMapping,environmentImage:this.environmentImage,autoplay:this.autoplay,animationName:this.animationName||void 0,variantName:this.getAttribute("variant-name")||void 0,fieldOfView:u,cameraTarget:o,minCameraOrbit:i,maxCameraOrbit:s,onMeshClick:a=>{this.dispatchEvent(new CustomEvent("meshclick",{bubbles:!0,composed:!0,detail:a}))},onCameraChange:a=>{this.updateHotspots();for(let l of he.getRegisteredPlugins())l.onCameraChange?.(this.viewer,this);this.dispatchEvent(new CustomEvent("camera-change",{bubbles:!0,composed:!0,detail:a}))}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let c=this.getAttribute("camera-orbit");c&&this.applyCameraOrbit(c),this.currentModel&&this.loadModelWithLimits(this.currentModel,this.currentModelLimits)}setupResizeObserver(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>{this.viewer&&(this.viewer.resize(),this.viewer.render(),this.updateHotspots())}),this.resizeObserver.observe(this))}updatePoster(t){if(!(typeof document>"u")){if(!t){this.posterEl&&(this.posterEl.remove(),this.posterEl=null);return}this.posterEl||(this.posterEl=document.createElement("img"),this.posterEl.setAttribute("alt","3D Scene Preview"),this.posterEl.style.position="absolute",this.posterEl.style.inset="0",this.posterEl.style.width="100%",this.posterEl.style.height="100%",this.posterEl.style.objectFit="cover",this.posterEl.style.transition="opacity 0.35s ease-out",this.posterEl.style.pointerEvents="none",this.posterEl.style.zIndex="1",this.appendChild(this.posterEl)),this.posterEl.src=t,this.isModelLoaded||(this.posterEl.style.opacity="1")}}hidePoster(){this.posterEl&&(this.posterEl.style.opacity="0",setTimeout(()=>{this.isModelLoaded&&this.posterEl&&(this.posterEl.remove(),this.posterEl=null)},400))}createARButton(){if(!(typeof document>"u")){if(!this.arButton){let t=document.createElement("button");t.setAttribute("type","button"),t.setAttribute("aria-label","View in Augmented Reality"),t.className="three-live-ar-button",t.setAttribute("part","default-ar-button");let r="http://www.w3.org/2000/svg";if(typeof document.createElementNS=="function"){let s=document.createElementNS(r,"svg");s.setAttribute("width","20"),s.setAttribute("height","20"),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke","currentColor"),s.setAttribute("stroke-width","2"),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.style.marginRight="6px";let o=document.createElementNS(r,"path");o.setAttribute("d","M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z");let u=document.createElementNS(r,"polyline");u.setAttribute("points","3.27 6.96 12 12.01 20.73 6.96");let c=document.createElementNS(r,"line");c.setAttribute("x1","12"),c.setAttribute("y1","22.08"),c.setAttribute("x2","12"),c.setAttribute("y2","12"),s.appendChild(o),s.appendChild(u),s.appendChild(c),t.appendChild(s)}let i=document.createElement("span");i.textContent="View in AR",t.appendChild(i),t.style.cssText="position:absolute;right:16px;bottom:16px;z-index:2;align-items:center;justify-content:center;padding:8px 16px;background-color:rgba(15,23,42,0.85);color:#fff;border:1px solid rgba(255,255,255,0.15);border-radius:9999px;font:600 13px system-ui,-apple-system,sans-serif;cursor:pointer;backdrop-filter:blur(8px);box-shadow:0 4px 12px rgba(0,0,0,0.25);transition:transform .15s ease,background-color .15s ease;display:none",t.addEventListener("mouseenter",()=>{t.style.backgroundColor="rgba(30, 41, 59, 0.95)",t.style.transform="scale(1.04)"}),t.addEventListener("mouseleave",()=>{t.style.backgroundColor="rgba(15, 23, 42, 0.85)",t.style.transform="scale(1)"}),t.addEventListener("click",s=>{s.stopPropagation(),this.activateAR()}),this.arButton=t,this.appendChild(t)}this.updateARButtonVisibility()}}updateARButtonVisibility(){let t=this.hasAttribute("ar")&&!!le.arProvider,r=typeof this.querySelector=="function"?this.querySelector('[slot="ar-button"]'):null;r?(this.arButton&&(this.arButton.style.display="none"),r.__tlARBound||(r.__tlARBound=!0,r.addEventListener("click",i=>{i.stopPropagation(),this.activateAR()})),r.dataset.tlOrigDisplay===void 0&&(r.dataset.tlOrigDisplay=r.style.display==="none"?"":r.style.display),r.style.display=t?r.dataset.tlOrigDisplay||"":"none"):this.arButton&&(this.arButton.style.display=t?"flex":"none")}applyCameraOrbit(t){if(!(!t||!this.viewer))try{let r=JSON.parse(t);this.viewer.setInitialCamera(r.theta,r.phi,r.distance,r.zoom)}catch{let r=t.trim().split(/\s+/);if(r.length>=2){let i=c=>c.endsWith("rad")?parseFloat(c)*180/Math.PI:parseFloat(c.replace(/deg$/,"")),s=r[0]==="auto"?void 0:i(r[0]),o=r[1]==="auto"?void 0:i(r[1]),u;r.length>=3&&r[2]!=="auto"&&(u=parseFloat(r[2].replace(/m$/,""))),(s!==void 0&&!isNaN(s)||o!==void 0&&!isNaN(o))&&this.viewer.setInitialCamera(s!==void 0&&!isNaN(s)?s:void 0,o!==void 0&&!isNaN(o)?o:void 0,u!==void 0&&!isNaN(u)?u:void 0)}}}parseOrbitLimit(t){if(!t)return{};let r=t.trim().split(/\s+/),i={};if(r.length>0&&r[0]!=="auto"){let s=r[0].endsWith("rad")?parseFloat(r[0])*180/Math.PI:parseFloat(r[0].replace(/deg$/,""));isNaN(s)||(i.theta=s)}if(r.length>1&&r[1]!=="auto"){let s=r[1].endsWith("rad")?parseFloat(r[1])*180/Math.PI:parseFloat(r[1].replace(/deg$/,""));isNaN(s)||(i.phi=s)}if(r.length>2&&r[2]!=="auto"){let s=parseFloat(r[2].replace(/m$/,""));isNaN(s)||(i.distance=s)}return i}applyOrbitLimits(){if(!this.viewer)return;let t=this.parseOrbitLimit(this.getAttribute("min-camera-orbit")),r=this.parseOrbitLimit(this.getAttribute("max-camera-orbit"));this.viewer.setOrbitLimits({minTheta:t.theta,maxTheta:r.theta,minPhi:t.phi,maxPhi:r.phi,minDistance:t.distance,maxDistance:r.distance})}parseCameraTarget(t){if(!t)return;let r=t.trim().split(/\s+/).map(i=>parseFloat(i.replace(/m$/,"")));return r.length>=3&&!r.some(isNaN)?[r[0],r[1],r[2]]:void 0}parseFieldOfView(t){if(!t)return;let r=t.endsWith("rad")?parseFloat(t)*180/Math.PI:parseFloat(t.replace(/deg$/,""));return isNaN(r)?void 0:r}parseRotationPerSecond(t){if(!t)return Math.PI/6;let r=t.trim(),i=parseFloat(r);return isNaN(i)?Math.PI/6:r.endsWith("rad")?i:r.endsWith("%")?i/100*Math.PI*2:i*Math.PI/180}applyCameraTarget(t){let r=this.parseCameraTarget(t);this.viewer&&r&&this.viewer.setTarget(r[0],r[1],r[2])}applyFieldOfView(t){let r=this.parseFieldOfView(t);this.viewer&&r!==void 0&&this.viewer.setFieldOfView(r)}updateHotspot(t){let r=this.querySelector(`[slot="${t.name}"]`);r&&(t.position!==void 0&&r.setAttribute("data-position",t.position),t.normal!==void 0&&r.setAttribute("data-normal",t.normal)),this.updateHotspots()}updateHotspots(){for(let t of he.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}async loadModelFromSrc(t){await this.loadModel(t)}runWithScriptRunner(t){let r=le.scriptRunner;if(!r){let i=new Error('Procedural script execution requires "three-live/full" or ThreeLiveElement.registerScriptRunner().');return this.showToast(i.message),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:i}})),Promise.reject(i)}return this.scriptHandle&&(this.scriptHandle.terminate(),this.scriptHandle=null),this.isModelLoaded=!1,this.viewer?.clearScene?.(),new Promise((i,s)=>{let o=!1;t(r,{onModelReady:c=>{this.loadModelWithLimits(c,Vn).then(()=>{o||(o=!0,i(c))},a=>{let l=a instanceof Error?a.message:String(a);this.showToast(l),o||(o=!0,s(a))})},onUpdateTransforms:c=>this.viewer?.updateMeshTransforms(c),onError:c=>{this.showToast(c.message),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:c}})),o||(o=!0,s(c))},onToast:c=>this.showToast(c)}).then(c=>{c&&(this.scriptHandle=c)},c=>{c instanceof Error&&c.message&&this.showToast(c.message),o||(o=!0,s(c))})})}loadScriptFromSrc(t){return this.runWithScriptRunner((r,i)=>{if(typeof r.executeUrl!="function"){let s=new Error("Registered ScriptRunner does not support executeUrl() for server-generated scripts.");return i.onError?.(s),Promise.reject(s)}return r.executeUrl(t,this.sandbox,i)})}executeScript(t){if(!le.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(st);return this.showToast(ot),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:r}})),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(t,this.sandbox,i,{allowClientScripts:!0}))}};le.observedAttributes=["src","ios-src","script-src","sandbox","allow-client-scripts","poster","camera-controls","camera-orbit","camera-target","min-camera-orbit","max-camera-orbit","field-of-view","selected-mesh","ar","ar-modes","ar-scale","ar-placement","exposure","shadow-intensity","shadow-softness","tone-mapping","bloom","bloom-threshold","bloom-radius","outline","outline-selected","outline-color","environment-image","skybox-image","autoplay","animation-name","variant-name","auto-rotate","auto-rotate-delay","rotation-per-second"],le.registerPlugin=he.registerPlugin,le.getRegisteredPlugins=he.getRegisteredPlugins;var De=le;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",De);function An(){if(typeof window>"u"||typeof navigator>"u")return!1;let n=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(n)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))return!1;let t=document.createElement("a");return t.relList!==void 0&&t.relList.supports!==void 0&&t.relList.supports("ar")}function Mn(){if(typeof navigator>"u")return!1;let n=navigator.userAgent||"";return/android/i.test(n)}async function Sn(){if(typeof navigator>"u")return!1;let n=navigator;if(!n.xr||typeof n.xr.isSessionSupported!="function")return!1;try{return await n.xr.isSessionSupported("immersive-ar")?!0:await n.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function hr(){return(await Dt()).bestMode}async function Dt(){let[n,e,t]=await Promise.all([Sn(),Promise.resolve(An()),Promise.resolve(Mn())]),r=[];e&&r.push("quick-look"),n&&r.push("webxr"),t&&r.push("scene-viewer");let i=null;return e?i="quick-look":n?i="webxr":t&&(i="scene-viewer"),{webxr:n,quickLook:e,sceneViewer:t,availableModes:r,bestMode:i}}function ur(n,e={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let t,r=!1;if(typeof n=="string"){if(t=si(n),!t)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else t=URL.createObjectURL(n),r=!0;let i=[];if(e.allowScale===!1&&i.push("allowsContentScaling=0"),e.canonicalWebPageUrl){let u=Lt(e.canonicalWebPageUrl,!1);u&&i.push(`canonicalWebPageURL=${encodeURIComponent(u)}`)}e.checkoutTitle&&i.push(`checkoutTitle=${encodeURIComponent(e.checkoutTitle)}`),e.checkoutSubtitle&&i.push(`checkoutSubtitle=${encodeURIComponent(e.checkoutSubtitle)}`),e.price&&i.push(`price=${encodeURIComponent(e.price)}`),i.length>0&&(t+=`#${i.join("&")}`);let s=document.createElement("a");s.setAttribute("rel","ar"),s.setAttribute("href",t);let o=document.createElement("img");o.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),o.style.display="none",s.appendChild(o),document.body.appendChild(s),s.click(),setTimeout(()=>{document.body.removeChild(s),r&&URL.revokeObjectURL(t.split("#")[0])},3e3)}function Lt(n,e=!1){if(typeof n!="string")return"";let t=n.replace(/[\x00-\x1f\x7f]+/g,"").trim();if(!t)return"";if(/^[\\/]{2}/.test(t))throw new Error(`[XR-Live Security] Rejected protocol-relative URL in Scene Viewer intent: ${t.slice(0,32)}`);let r=t.toLowerCase();if(r.startsWith("https://")||r.startsWith("http://")||e&&r.startsWith("blob:")||!/^[a-z][a-z0-9+.-]*:/i.test(t))return t;throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Scene Viewer intent: ${t.slice(0,32)}`)}function si(n){try{return Lt(n,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(n||"").trim().slice(0,32)}`)}}function oi(n,e={}){let t=Lt(n,!0),r=e.mode||"ar_preferred",i=new URLSearchParams({file:t,mode:r,resizable:e.resizable!==!1?"true":"false",enable_vertical_placement:e.enableVerticalPlacement?"true":"false"});return e.title&&i.set("title",e.title),e.link&&i.set("link",Lt(e.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${i.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function ai(n,e={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let t=oi(n,e);window.location.href=t}var Ue=null;function ci(n,e){let r=new Float32Array(144),i=new Float32Array(24*6),s=new Float32Array(24*4),o=new Uint16Array(24*6);for(let h=0;h<24;h++){let m=h/24*Math.PI*2,v=Math.cos(m),b=Math.sin(m),d=h*2,g=d+1,I=(h+1)%24*2;r[d*3]=v*.11,r[d*3+1]=.002,r[d*3+2]=b*.11,r[g*3]=v*.145,r[g*3+1]=.002,r[g*3+2]=b*.145,i[d*3+1]=i[g*3+1]=1,o.set([d,I,g,g,I,I+1],h*6)}let u=n.createVertexArray();n.bindVertexArray(u);let c=(h,m,v)=>{let b=n.createBuffer();return n.bindBuffer(34962,b),n.bufferData(34962,h,35044),n.enableVertexAttribArray(m),n.vertexAttribPointer(m,v,5126,!1,0,0),b},a=[c(r,0,3),c(i,1,3),c(s,2,2)],l=n.createBuffer();return a.push(l),n.bindBuffer(34963,l),n.bufferData(34963,o,35044),n.bindVertexArray(null),{name:"__xr_reticle__",nodeIndex:-1,worldSpace:!0,visible:!1,transform:new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),normalMatrix:new Float32Array([1,0,0,0,1,0,0,0,1]),primitives:[{vao:u,indexCount:o.length,indexType:5123,baseColor:e&&e.length>=3?[e[0],e[1],e[2],e[3]??.95]:[.22,.74,.97,.95],metallic:0,roughness:.2,positions:r,indices:o,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:a}]}}function lr(n,e,t,r,i){let s=Math.cos(r),o=Math.sin(r),u=Math.max(.01,i);n.fill(0),n[0]=u*s,n[2]=-u*o,n[5]=u,n[8]=u*o,n[10]=u*s,n[12]=e[0]-u*(s*t[0]+o*t[2]),n[13]=e[1]-u*t[1],n[14]=e[2]-u*(-o*t[0]+s*t[2]),n[15]=1}var wn=class{constructor(e={}){this.s=null;this.placed=!1;this.placedMat=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);this.cleanFn=null;this.opts=e}isSessionActive(){return this.s!==null}hasPlacedModel(){return this.placed}getPlacedMatrix(){return this.placedMat}async start(e,t){if(typeof navigator>"u"||!navigator.xr)throw new Error("WebXR is not supported on this browser.");Ue&&Ue!==this&&Ue.isSessionActive()&&await Ue.stop().catch(()=>{});let r=navigator.xr,i=this.opts,s=t||e?.container,o=String(s?.tagName||"").toLowerCase()==="xr-live",u=e?.bounds,c=Number(u?.radius)||1,a=Array.isArray(u?.center)?u.center:[0,0,0],l=Array.isArray(u?.min)?u.min:[-.5,-.5,-.5],h=typeof navigator<"u"&&navigator.userAgent||"",m=/Android|iPhone|iPad|iPod/i.test(h)&&!/Quest|Oculus|Pico|Vision/i.test(h),v=o?i.arScale==="fixed"?1:m?.55:1:i.arScale==="fixed"?1:c>.45?.3/c:c<.05?.12/Math.max(c,.001):1,b=o?[0,-.25,0]:[a[0]||0,i.arPlacement==="wall"?a[1]:l[1]??0,a[2]||0],d="immersive-ar";try{await r.isSessionSupported("immersive-ar")||(d="immersive-vr")}catch{d="immersive-vr"}let g=s?.querySelector?.('[slot="ar-overlay"]')||null,I=!1,P=null,p=()=>{I&&g?.parentNode&&g.parentNode.removeChild(g),g=null,P=null,I=!1};if(d==="immersive-ar"){if(g)g.addEventListener?.("beforexrselect",C=>C.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let C=document.createElement("div");C.style.cssText="position:fixed;inset:0;pointer-events:none;background:transparent!important;z-index:2147483647;font-family:system-ui,sans-serif;user-select:none";let N=document.createElement("button");N.type="button",N.textContent="\u2715 Exit AR",N.style.cssText="position:absolute;top:max(16px,env(safe-area-inset-top,16px));right:16px;pointer-events:auto;padding:8px 14px;border-radius:99px;border:1px solid rgba(255,255,255,.3);background:rgba(15,23,42,.8);color:#f8fafc;font:600 13px system-ui,sans-serif",N.addEventListener("beforexrselect",H=>H.preventDefault()),N.addEventListener("click",H=>{H.stopPropagation(),this.stop().catch(()=>{})}),P=document.createElement("div"),P.style.cssText="position:absolute;bottom:max(28px,env(safe-area-inset-bottom,28px));left:50%;transform:translateX(-50%);padding:8px 15px;border-radius:99px;border:1px solid rgba(56,189,248,.4);background:rgba(15,23,42,.82);color:#f8fafc;font:500 12.5px system-ui,sans-serif;text-align:center;max-width:88vw",P.textContent="Move phone to detect a surface \u2022 Tap to place",C.appendChild(N),C.appendChild(P),document.body.appendChild(C),g=C,I=!0}}let M=new Set(i.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),x={requiredFeatures:i.requiredFeatures?[...i.requiredFeatures]:[],optionalFeatures:Array.from(M)};g&&(M.add("dom-overlay"),x.optionalFeatures=Array.from(M),x.domOverlay={root:g});for(let C of ie)C.onConfigureXRSessionInit?.(s,x);Array.isArray(x.optionalFeatures)&&x.optionalFeatures.includes("dom-overlay")&&!x.domOverlay?.root&&(x.optionalFeatures=x.optionalFeatures.filter(C=>C!=="dom-overlay"));let w=C=>{let N=String(C?.name||"");return N==="NotAllowedError"||N==="SecurityError"};try{this.s=await r.requestSession(d,x)}catch(C){if(p(),w(C))throw i.onError?.(C),C;try{this.s=await r.requestSession(d,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(N){if(w(N))throw i.onError?.(N),N;try{this.s=await r.requestSession(d)}catch(H){throw i.onError?.(H),H}}}let T=this.s;Ue=this,this.placed=!1;let A=null,y=null,E=null,f=null,_=null,S=[0,-.25,-1.2],R=[0,-.25,-1.2],F=new Float32Array(16),D=new Float32Array(16),U=!1,k=1,X=0,B=!1,L=null,O=null,V=0,z=null,$=()=>{Ue===this&&(Ue=null),z?.(),z=null;try{y?.cancel?.()}catch{}if(y=null,E){let C=e?.meshes;if(Array.isArray(C)){let H=C.indexOf(E);H!==-1&&C.splice(H,1)}let N=e.getGLContext?.()||e?.gl;if(N)for(let H of E.primitives||[]){N.deleteVertexArray?.(H.vao);for(let G of H.buffers||[])N.deleteBuffer?.(G)}E=null}e?.setXRSessionActive?.(!1),p(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=$,T.addEventListener("end",()=>{$(),i.onExit?.()}),T.addEventListener("select",()=>{if(!this.placed){let C=_||S;R=[C[0],C[1],C[2]],lr(this.placedMat,R,b,X,v*k),this.placed=!0,E&&(E.visible=!1),P&&(P.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),i.onPlaced?.(this.placedMat)}});try{let C=e.getGLContext?.()||e?.gl;C&&typeof C.makeXRCompatible=="function"&&await C.makeXRCompatible();let N=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;C&&typeof N=="function"&&typeof T.updateRenderState=="function"&&T.updateRenderState({baseLayer:new N(T,C,{alpha:!0})});try{A=await T.requestReferenceSpace("local")}catch{try{A=await T.requestReferenceSpace("local-floor")}catch{A=await T.requestReferenceSpace("viewer")}}let H=await T.requestReferenceSpace("viewer").catch(()=>A);if(typeof T.requestHitTestSource=="function"&&H&&(y=await T.requestHitTestSource({space:H}).catch(()=>null)),d==="immersive-ar"&&C&&typeof C.createVertexArray=="function"&&Array.isArray(e.meshes)&&(E=ci(C,i.reticleColor),e.meshes.push(E)),typeof window<"u"&&typeof window.addEventListener=="function"){let Y=W=>Math.hypot(W.touches[1].clientX-W.touches[0].clientX,W.touches[1].clientY-W.touches[0].clientY),Q=W=>Math.atan2(W.touches[1].clientY-W.touches[0].clientY,W.touches[1].clientX-W.touches[0].clientX),q=W=>{this.s&&(W.touches.length===1&&this.placed?B=!0:W.touches.length>=2&&(B=!1,L=Y(W),O=Q(W)))},K=W=>{if(!this.s||W.touches.length<2)return;let ue=Y(W),oe=Q(W);if(L&&L>4&&i.arScale!=="fixed"&&(k=Math.max(.15,Math.min(6,k*(ue/L)))),O!==null){let ye=oe-O;ye>Math.PI&&(ye-=Math.PI*2),ye<-Math.PI&&(ye+=Math.PI*2),X-=ye}L=ue,O=oe},ce=W=>{(!W.touches||W.touches.length===0)&&(B=!1),(!W.touches||W.touches.length<2)&&(L=null,O=null)};window.addEventListener("touchstart",q,{passive:!0}),window.addEventListener("touchmove",K,{passive:!0}),window.addEventListener("touchend",ce,{passive:!0}),window.addEventListener("touchcancel",ce,{passive:!0}),z=()=>{window.removeEventListener("touchstart",q),window.removeEventListener("touchmove",K),window.removeEventListener("touchend",ce),window.removeEventListener("touchcancel",ce)}}e.setXRSessionActive?.(!0);let G=(Y,Q)=>{if(this.s!==T)return;T.requestAnimationFrame(G);let q=V>0?Math.min(Math.max((Y-V)/1e3,0),.1):1/60;V=Y,e?.stepXRUpdate?.(q);let K=Q.getViewerPose(A);if(!K)return;let ce=K.views?.[0];if(!U&&ce?.transform){let ae=ce.transform.position,ne=ce.transform.matrix,xe=ae?.x??(ne?ne[12]:0),pe=ae?.y??(ne?ne[13]:0),ve=ae?.z??(ne?ne[14]:0),Se=ne?-ne[8]:0,Ie=ne?-ne[10]:-1,je=Math.hypot(Se,Ie);je>1e-4?(Se/=je,Ie/=je):(Se=0,Ie=-1),S=[xe+Se*1.2,pe-.25,ve+Ie*1.2],X=Math.atan2(-Se,-Ie),U=!0}if(y&&typeof Q.getHitTestResults=="function"&&(!this.placed||B)){let ae=Q.getHitTestResults(y)||[],ne=!1;for(let xe of ae){let pe=xe.getPose(A);if(pe?.transform?.matrix){let ve=pe.transform.matrix,Se=ve[5];if(i.arPlacement==="wall"&&Math.abs(Se)>.35||i.arPlacement==="floor"&&Math.abs(Se)<.65)continue;f||(f=new Float32Array(16)),f.set(ve),_=[ve[12],ve[13],ve[14]],this.placed&&B&&(R=[ve[12],ve[13],ve[14]]),E&&(E.visible=!this.placed||B,E.transform.set(ve)),!this.placed&&P&&(P.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),i.onHit?.(f),ne=!0;break}}!ne&&E&&(E.visible=!1)}lr(F,this.placed?R:_||S,b,X,v*k),this.placed&&this.placedMat.set(F);let W=e.xrRigMatrix;W instanceof Float32Array&&W.length===16?re(D,W,F):D.set(F),e.modelRootMatrix&&e.modelRootMatrix.set(D);for(let ae of ie)ae.onXRFrame?.(e,T,Q,A);let ue=e.getGLContext?.()||e?.gl,oe=T.renderState?.baseLayer;ue&&oe&&oe.framebuffer!==void 0&&ue.bindFramebuffer(36160,oe.framebuffer);let ye=d==="immersive-ar",ge=K.views||[];for(let ae=0;ae<ge.length;ae++){let ne=ge[ae];if(typeof e.renderXRView=="function"){let xe;if(oe&&typeof oe.getViewport=="function"){let pe=oe.getViewport(ne);pe&&pe.width>0&&pe.height>0&&(xe=[pe.x,pe.y,pe.width,pe.height])}else oe?.framebufferWidth>0&&oe?.framebufferHeight>0&&(xe=[0,0,oe.framebufferWidth,oe.framebufferHeight]);e.renderXRView(ne,D,this.placed,xe,ye,ae)}}ue&&oe&&oe.framebuffer&&ue.bindFramebuffer(36160,null)};T.requestAnimationFrame(G)}catch(C){throw typeof T.end=="function"&&await T.end().catch(()=>{}),$(),i.onError?.(C),C}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function It(n){let e=await Dt(),t=n.preferredModes||["quick-look","webxr","scene-viewer"],r=null;for(let u of t)if(e.availableModes.includes(u)){r=u;break}if(r||(r=e.bestMode),!r)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let i={...n.quickLookOptions,allowScale:n.arScale==="fixed"?!1:n.quickLookOptions?.allowScale},s={...n.sceneViewerOptions,resizable:n.arScale==="fixed"?!1:n.sceneViewerOptions?.resizable,enableVerticalPlacement:n.arPlacement==="wall"?!0:n.sceneViewerOptions?.enableVerticalPlacement},o={...n.webXROptions,arScale:n.arScale||n.webXROptions?.arScale,arPlacement:n.arPlacement||n.webXROptions?.arPlacement};try{if(r==="quick-look"){let u;if(n.model instanceof Blob&&n.model.type==="model/vnd.usdz+zip")u=n.model;else{if(typeof n.model=="string")return ur(n.model,i),{mode:"quick-look",success:!0};u=ze(n.model)}return ur(u,i),{mode:"quick-look",success:!0}}if(r==="scene-viewer"){let u=n.glbUrl||(typeof n.model=="string"?n.model:null);if(!u)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return ai(u,s),{mode:"scene-viewer",success:!0}}if(r==="webxr"){if(!n.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let u=new wn(o);return await u.start(n.view,n.element),{mode:"webxr",success:!0,session:u}}}catch(u){return{mode:r,success:!1,error:u}}return{mode:r,success:!1,error:new Error(`Unhandled AR mode: ${r}`)}}De.registerAR({activateAR:It,createUSDZBlob:ze});De.registerScriptRunner(vn);rt(_n);
|
|
326
|
+
`+_.script+`
|
|
327
|
+
})();`);h=null;let v=x(y,w,A,L);v&&typeof v.toGLB=="function"&&(w=v)}if(!T){y.SceneQuotaValidator&&y.SceneQuotaValidator.validate(w);let x=w.toGLB(),v=x instanceof ArrayBuffer?x:x.buffer.slice(x.byteOffset,x.byteOffset+x.byteLength);P({type:"3D_MODEL_READY",glbBuffer:v},[v])}a({type:"DONE",nonce:r})}catch(w){u(w&&w.message||w)}}},a({type:"READY",nonce:r})}function sr(n,e,t){let r=t?.allowedScriptUrl??null,i=t?.allowClientScripts??r===null,s={nonce:e,engineSrc:n,allowedScriptUrl:r,allowClientScripts:i,revoked:Zr},o=(Q().workerExtensionInstallers??[]).map(c=>`(${c.toString()})`).join(",");return`'use strict';(${Jr.toString()})(${JSON.stringify(s)},[${o}]);`}function or(n){n.onError?.(new Error("SecurityError: Sandboxed script exceeded SECURITY_3D_SANDBOX_TIMEOUT_MS (3000 ms) and was terminated.")),n.onToast?.("Security Error: script timed out and was stopped.")}var Ee=0;function ar(){try{let n=new Uint32Array(4);return globalThis.crypto?.getRandomValues(n),Array.from(n,t=>t.toString(16).padStart(8,"0")).join("")}catch{return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}}function Qr(n){try{return new TextEncoder().encode(n).length}catch{return n.length}}var ei=1024,ti=256;function Jn(n){if(!Array.isArray(n)&&!(n instanceof Float32Array)||n.length!==16)return!1;for(let e=0;e<16;e++){let t=n[e];if(typeof t!="number"||!Number.isFinite(t))return!1}return!0}function cr(n,e){if(!n||typeof n!="object")return null;let t=n;if(t.nonce!==e)return null;switch(t.type){case"READY":return{type:"READY"};case"DONE":return{type:"DONE"};case"ERROR":return{type:"ERROR",message:(typeof t.message=="string"?t.message:String(t.message??"Unknown worker error")).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").slice(0,ei)};case"3D_UPDATE_TRANSFORMS":{let i=t.transforms;if(Array.isArray(i)){if(i.length>1e3)return null;for(let s of i)if(!Jn(s))return null;return{type:"3D_UPDATE_TRANSFORMS",transforms:i}}if(i&&typeof i=="object"){let s=Object.keys(i);if(s.length>1e3)return null;let o=Object.create(null),c=i;for(let a of s){if(a.length>ti||a==="__proto__"||a==="constructor"||a==="prototype")return null;let u=c[a];if(!Jn(u))return null;o[a]=u}return{type:"3D_UPDATE_TRANSFORMS",transforms:o}}return null}case"3D_MODEL_READY":{let i=t.glbBuffer;return!(i instanceof ArrayBuffer)||i.byteLength>16777216?null:{type:"3D_MODEL_READY",payload:i}}default:return null}}function ni(n){let e=Qr(n);if(e>1048576)throw new Error(`SecurityError: Script length (${e} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function ur(n,e,t,r){switch(n.type){case"READY":return;case"3D_UPDATE_TRANSFORMS":e.onUpdateTransforms?.(n.transforms);return;case"3D_MODEL_READY":if(r.modelDispatched)return;r.modelDispatched=!0,e.onModelReady(n.payload);return;case"DONE":t();return;case"ERROR":t(),e.onError?.(new Error(`Worker script error: ${n.message}`));return;default:return n}}function ri(n,e,t,r){let i=ar(),s=sr(e,i,n.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:n.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),o=document.createElement("iframe");o.setAttribute("sandbox","allow-scripts"),o.setAttribute("aria-hidden","true"),o.tabIndex=-1,o.style.display="none",o.src=t,Ee++;let c=!1,a=!1,u={modelDispatched:!1},l,m=()=>{if(c||a)return;let d=o.contentWindow;!d||typeof d.postMessage!="function"||(a=!0,d.postMessage(n.kind==="url"?{type:"SANDBOX_RUN",nonce:i,workerSource:s,scriptUrl:n.scriptUrl}:{type:"SANDBOX_RUN",nonce:i,workerSource:s,script:n.script},"*"))},h=()=>{},y=d=>{if(c||!o.contentWindow||d.source!==o.contentWindow)return;let g=d.data;if(g&&typeof g=="object"&&g.type==="IFRAME_READY"){m();return}let T=cr(g,i);T&&ur(T,r,h,u)};h=()=>{c||(c=!0,l!==void 0&&clearTimeout(l),Ee=Math.max(0,Ee-1),typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("message",y),typeof o.remove=="function"?o.remove():o.parentNode&&o.parentNode.removeChild(o))},l=setTimeout(()=>{c||(h(),or(r))},3e3),typeof globalThis.addEventListener=="function"&&globalThis.addEventListener("message",y),o.onload=()=>{m()},o.onerror=()=>{h(),r.onError?.(new Error(`Sandbox iframe failed to load "${t}". Verify that three-live-sandbox.html is served at that URL.`))};let b=document.body||document.documentElement;if(!b||typeof b.appendChild!="function"){h();let d=new Error("SecurityError: Cannot mount sandbox iframe because document.body is unavailable.");throw r.onError?.(d),d}return b.appendChild(o),{terminate:h}}function Qn(n,e,t,r){if(e==="worker"&&typeof Worker>"u")return r("Sandboxed procedural execution requires Web Workers, but Workers are unavailable in this environment. For host security, Three-Live prohibits unsandboxed in-process evaluation.","Security Error: Web Workers unavailable. Script execution aborted.");if(e==="iframe"&&(typeof document>"u"||typeof document.createElement!="function"))return r("Sandboxed iframe execution requires a DOM environment with document.createElement. Refusing to evaluate in the host realm.","Security Error: DOM unavailable for iframe sandbox.");if(Ee>=32)return r(`SecurityError: ${Ee} sandbox workers are already running, which meets SECURITY_3D_MAX_CONCURRENT_TASKS (32). Refusing to start another.`,"Security Error: too many concurrent sandboxed scripts.");let i;try{i=$r()}catch(h){let y=h instanceof Error?h.message:String(h);return r(y,"Security Error: sandbox engine URL is not configured.")}if(e==="iframe"){let h;try{h=qr()}catch(y){let b=y instanceof Error?y.message:String(y);return r(b,"Security Error: sandbox iframe URL is not configured.")}try{return Promise.resolve(ri(n,i,h,t))}catch(y){return Promise.reject(y)}}let s=ar(),o=sr(i,s,n.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:n.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),c;try{let h=new Blob([o],{type:"application/javascript"}),y=URL.createObjectURL(h);try{let b=Wr(y);c=new Worker(b)}finally{URL.revokeObjectURL(y)}}catch(h){let y=h instanceof Error?h.message:String(h);return r(`Failed to initialize Web Worker for sandboxed execution (CSP may block blob workers): ${y}`,"Security Error: Failed to start Worker sandbox.")}Ee++;let a=!1,u={modelDispatched:!1},l,m=()=>{a||(a=!0,l!==void 0&&clearTimeout(l),Ee=Math.max(0,Ee-1),c.terminate())};return l=setTimeout(()=>{a||(m(),or(t))},3e3),c.onmessage=h=>{let y=cr(h.data,s);y&&ur(y,t,m,u)},c.onerror=h=>{m(),t.onError?.(new Error(`Worker execution error: ${h.message}`))},n.kind==="url"?c.postMessage({type:"EXECUTE_URL",scriptUrl:n.scriptUrl,nonce:s}):c.postMessage({type:"EXECUTE",script:n.script,nonce:s}),Promise.resolve({terminate:m})}function er(n,e){return n==="none"||n==="unsafe-host-realm"?e(`SecurityError: sandbox="${n}" is prohibited. Sandboxing is mandatory for live compilation and cannot be bypassed. Use sandbox="worker" (default) or sandbox="iframe".`,`Security Error: sandbox="${n}" is not permitted.`):n!=="worker"&&n!=="iframe"?e(`SecurityError: Unsupported sandbox mode "${n}". Live compilation requires sandbox="worker" or sandbox="iframe".`,"Security Error: unsupported sandbox mode."):null}var yn={execute(n,e,t,r){let i=(c,a)=>{let u=new Error(c);return t.onError?.(u),a&&t.onToast?.(a),Promise.reject(u)},s=er(e,i);if(s)return s;try{ni(n)}catch(c){let a=c instanceof Error?c.message:String(c);return i(a,"Security Error: script exceeds the size limit.")}return r?.allowClientScripts??jr()?Qn({kind:"script",script:n},e,t,i):i(Je,Qe)},executeUrl(n,e,t){let r=(o,c)=>{let a=new Error(o);return t.onError?.(a),c&&t.onToast?.(c),Promise.reject(a)},i=er(e,r);if(i)return i;let s;try{s=Kr(n)}catch(o){let c=o instanceof Error?o.message:String(o);return r(c,"Security Error: disallowed scene script URL.")}return Qn({kind:"url",scriptUrl:s},e,t,r)}},wt=new Set;function xe(n,e){let t=`[three-live] ${n} is unsupported; degraded to ${e}.`;wt.has(t)||(wt.add(t),typeof console<"u"&&typeof console.warn=="function"&&console.warn(t))}function ii(){return Array.from(wt)}function si(){wt.clear()}var At=class extends Oe{constructor(e={}){xe("ShaderMaterial","MeshStandardMaterial");let t=e.uniforms||{},r=t.color?.value??t.uColor?.value??t.diffuse?.value??e.color;super({color:r!==void 0?r:8421504,opacity:t.opacity?.value??e.opacity??1,transparent:!!e.transparent,wireframe:!!e.wireframe,side:e.side}),this.uniforms=t}},oi=At,ze=class extends dt{constructor(e=1,t=0,r="PolyhedronGeometry"){xe(r,"SphereGeometry");let i=Math.max(4,Math.min(32,4<<Math.min(t,3)));super(e,i,i)}},un=class extends ze{constructor(e=1,t=0){super(e,t,"IcosahedronGeometry")}},ln=class extends ze{constructor(e=1,t=0){super(e,t,"OctahedronGeometry")}},hn=class extends ze{constructor(e=1,t=0){super(e,t,"DodecahedronGeometry")}},mn=class extends ze{constructor(e=1,t=0){super(e,t,"TetrahedronGeometry")}},dn=class extends Le{constructor(e=1,t=1,r=4,i=8){xe("CapsuleGeometry","CylinderGeometry"),super(e,e,t+e*2,i)}},fn=class extends Le{constructor(e=.5,t=1,r=16){xe("RingGeometry","CylinderGeometry"),super(t,t,.01,Math.max(8,r))}},pn=class extends Le{constructor(e=1,t=16){xe("CircleGeometry","CylinderGeometry"),super(e,e,.01,Math.max(8,t))}},bn=class extends gt{constructor(t,r,i=0,s=Math.PI/3,o=0,c=2){xe("SpotLight","PointLight");super(t,r,i,c);this.target=new we;this.angle=Math.PI/3;this.penumbra=0;this.angle=s,this.penumbra=o}},Mt=class extends yt{constructor(e,t,r){xe("HemisphereLight","AmbientLight"),super(e,r),this.groundColor=new ve(t??4473924)}},ai=Mt,lr={Vector2:Ht,Vector3:le,Vector4:Gt,Euler:lt,Quaternion:ht,Matrix4:Ue,Matrix3:Xt,Color:ve,MathUtils:Hr,BufferAttribute:J,Float32BufferAttribute:Wt,Uint16BufferAttribute:$t,Uint32BufferAttribute:Yt,BufferGeometry:ge,BoxGeometry:mt,PlaneGeometry:qt,SphereGeometry:dt,CylinderGeometry:Le,ConeGeometry:jt,TorusGeometry:Kt,TorusKnotGeometry:Zt,IcosahedronGeometry:un,OctahedronGeometry:ln,DodecahedronGeometry:hn,TetrahedronGeometry:mn,CapsuleGeometry:dn,RingGeometry:fn,CircleGeometry:pn,Texture:ft,TextureLoader:Jt,Material:Re,MeshStandardMaterial:Oe,MeshBasicMaterial:Qt,MeshLambertMaterial:en,MeshPhongMaterial:tn,MeshPhysicalMaterial:nn,ShaderMaterial:At,RawShaderMaterial:oi,Object3D:we,Group:rn,Mesh:Be,InstancedMesh:bt,Light:Ve,AmbientLight:yt,DirectionalLight:sn,PointLight:gt,SpotLight:bn,HemisphereLight:Mt,RectAreaLight:ai,Camera:xt,PerspectiveCamera:on,Scene:vt,WebGLRenderer:an,Clock:cn,SceneQuotaValidator:Me,exportSceneToCanvas3D:nr,exportSceneToGLB:rr,exportSceneToUSDZ:Gr,generateUSDZ:at,glbToUSDZ:ot,sceneToCanvas3D:Ye,sceneToGLB:st,sceneToUSDZ:qe,authorScriptRunner:yn,getAuthorWarnings:ii,clearAuthorWarnings:si};Object.freeze(Me);Object.freeze(Me.prototype);Object.freeze(vt.prototype);Object.freeze(lr);var Ie=new Proxy(lr,{get:(n,e)=>{if(e in n)return n[e];let t=Q().authorNamespace;return t&&typeof e=="string"&&e in t?t[e]:(typeof e=="string"&&e!=="then"&&e!=="toJSON"&&!e.startsWith("__")&&xe(`THREE.${e}`,"no-op proxy"),ct)},has:(n,e)=>{if(e in n)return!0;let t=Q().authorNamespace;return!!(t&&typeof e=="string"&&e in t)},set:(n,e)=>{throw new TypeError(`Cannot assign to read only property '${String(e)}' of #<THREE>`)},defineProperty:(n,e)=>{throw new TypeError(`Cannot define property '${String(e)}', object is not extensible`)},deleteProperty:(n,e)=>{throw new TypeError(`Cannot delete property '${String(e)}' of #<THREE>`)},setPrototypeOf:()=>{throw new TypeError("#<THREE> is not extensible")}}),ut=Q();ut.threeNamespace=Ie;if(ut.workerExtensionInstallers)for(let n of ut.workerExtensionInstallers)n(Ie,ut);var zt={name:"three_author",THREE:Ie};var He=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;typeof He.THREE>"u"&&(He.THREE=Ie);typeof He.requestAnimationFrame!="function"&&(He.requestAnimationFrame=()=>(xe("requestAnimationFrame","single-frame static evaluation"),0));typeof He.cancelAnimationFrame!="function"&&(He.cancelAnimationFrame=()=>{});if(typeof window<"u"){let n=window;n.ThreeLive=n.ThreeLive||{},n.ThreeLive.THREE=Ie,n.ThreeLivePlugins=n.ThreeLivePlugins||{},n.ThreeLivePlugins.threeAuthor=zt,n.ThreeLivePlugins.three_author=zt,n.ThreeLivePlugins["three-author"]=zt}function gn(n,e){let t=n?.trim(),r=t?Number(t):NaN;return Number.isFinite(r)?r:e}var li=typeof HTMLElement<"u"?HTMLElement:class{};typeof CustomEvent>"u"&&typeof Event<"u"&&(globalThis.CustomEvent=class extends Event{constructor(n,e){super(n,e),this.detail=e?.detail??null}});var he=class he extends li{constructor(){super(...arguments);this.viewer=null;this.canvas=null;this.posterEl=null;this.arButton=null;this.currentModel=null;this.activeXRSession=null;this.toastTimer=null;this.currentModelLimits=void 0;this.isModelLoaded=!1;this.scriptHandle=null;this.resizeObserver=null;this.mutationObserver=null}static get arProvider(){return Q().arProvider}static set arProvider(t){Q().arProvider=t}static get scriptRunner(){return Q().scriptRunner}static set scriptRunner(t){Q().scriptRunner=t}static get sandboxEngineSrc(){return Q().sandboxEngineSrc??null}static set sandboxEngineSrc(t){Q().sandboxEngineSrc=t}static get sandboxIframeSrc(){return Q().sandboxIframeSrc??null}static set sandboxIframeSrc(t){Q().sandboxIframeSrc=t}static get allowClientScripts(){return!!Q().allowClientScripts}static set allowClientScripts(t){Q().allowClientScripts=t}static registerScriptRunner(t){he.scriptRunner=t}static registerDecoder(t,r){de.registerDecoder(t,r)}static getDecoder(t){return de.getDecoder(t)}static registerAR(t){typeof t=="function"?he.arProvider={activateAR:t}:he.arProvider=t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(i=>{i instanceof he&&i.updateARButtonVisibility()})}static isARSupported(){return!!he.arProvider}getLoadedModel(){return this.currentModel}connectedCallback(){if(typeof document>"u")return;(!this.style.display||this.style.display==="inline")&&(this.style.display="block"),getComputedStyle(this).position==="static"&&(this.style.position="relative"),this.style.overflow="hidden",this.setupDOM(),this.initViewer(),this.setupResizeObserver();let t=this.getAttribute("src"),r=this.getAttribute("script-src");if(t)this.loadModel(t).catch(()=>{});else if(r)this.loadScriptFromSrc(r).catch(()=>{});else{let i=this.querySelector('script[type="text/three"], script[type="text/three-live"]');i&&i.textContent&&this.executeScript(i.textContent).catch(()=>{})}for(let i of de.getRegisteredPlugins())i.onElementConnected?.(this)}disconnectedCallback(){for(let t of de.getRegisteredPlugins())t.onElementDisconnected?.(this);this.scriptHandle&&(this.scriptHandle.terminate(),this.scriptHandle=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.activeXRSession&&(this.activeXRSession.stop?.().catch?.(()=>{}),this.activeXRSession=null),this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=null),this.viewer&&(this.viewer.destroy(),this.viewer=null),this.isModelLoaded=!1}attributeChangedCallback(t,r,i){if(r!==i){switch(t){case"src":i&&this.loadModel(i).catch(()=>{});break;case"camera-target":this.applyCameraTarget(i);break;case"min-camera-orbit":case"max-camera-orbit":this.applyOrbitLimits();break;case"field-of-view":this.applyFieldOfView(i);break;case"script-src":i&&this.loadScriptFromSrc(i).catch(()=>{});break;case"sandbox":case"allow-client-scripts":case"ios-src":break;case"poster":this.updatePoster(i);break;case"camera-orbit":this.applyCameraOrbit(i);break;case"selected-mesh":this.viewer&&i!==null&&this.viewer.setSelectedMesh(i);break;case"exposure":if(this.viewer&&i!==null){let s=parseFloat(i);isNaN(s)||this.viewer.setExposure(s)}break;case"shadow-intensity":case"shadow-softness":this.viewer&&this.viewer.setShadow(this.shadowIntensity,this.shadowSoftness);break;case"tone-mapping":this.viewer?.setToneMapping(Ce(i));break;case"environment-image":this.viewer&&this.viewer.setEnvironmentImage(i).catch(()=>{});break;case"skybox-image":this.viewer&&this.viewer.setSkyboxImage?.(i)?.catch?.(()=>{});break;case"camera-controls":{let s=this.cameraControls;this.viewer&&this.viewer.setInteractive?.(s),this.canvas&&(this.canvas.style.touchAction=s?"none":"auto");break}case"autoplay":this.viewer&&this.viewer.setAutoplay(i!==null&&i!=="false");break;case"animation-name":this.viewer&&i!==null&&this.viewer.setAnimationName(i);break;case"variant-name":this.viewer&&this.selectVariant(i);break;case"auto-rotate":this.viewer&&this.viewer.setAutoRotate(i!==null&&i!=="false");break;case"auto-rotate-delay":this.viewer&&this.viewer.setAutoRotateDelay(this.autoRotateDelay);break;case"rotation-per-second":this.viewer&&this.viewer.setAutoRotateSpeed(this.parseRotationPerSecond(i));break;case"ar":this.updateARButtonVisibility();break}for(let s of de.getRegisteredPlugins())s.onAttributeChanged?.(this,t,r,i)}}getAttr(t){return this.getAttribute(t)}setAttr(t,r){r!==null?this.setAttribute(t,r):this.removeAttribute(t)}getBoolAttr(t){return this.hasAttribute(t)&&this.getAttribute(t)!=="false"}setBoolAttr(t,r){r?this.setAttribute(t,""):this.removeAttribute(t)}getFloatAttr(t,r){let i=this.getAttribute(t);return i!==null?parseFloat(i):r}get src(){return this.getAttr("src")}set src(t){this.setAttr("src",t)}get cameraControls(){return this.getBoolAttr("camera-controls")}set cameraControls(t){this.setBoolAttr("camera-controls",t)}get cameraOrbit(){return this.getAttr("camera-orbit")}set cameraOrbit(t){this.setAttr("camera-orbit",t)}get cameraTarget(){return this.getAttr("camera-target")}set cameraTarget(t){this.setAttr("camera-target",t)}get minCameraOrbit(){return this.getAttr("min-camera-orbit")}set minCameraOrbit(t){this.setAttr("min-camera-orbit",t)}get maxCameraOrbit(){return this.getAttr("max-camera-orbit")}set maxCameraOrbit(t){this.setAttr("max-camera-orbit",t)}get fieldOfView(){return this.getAttr("field-of-view")}set fieldOfView(t){this.setAttr("field-of-view",t)}get iosSrc(){return this.getAttr("ios-src")}set iosSrc(t){this.setAttr("ios-src",t)}get scriptSrc(){return this.getAttr("script-src")}set scriptSrc(t){this.setAttr("script-src",t)}get sandbox(){return this.getAttribute("sandbox")||(Q().sandboxIframeSrc?"iframe":"worker")}set sandbox(t){this.setAttribute("sandbox",t)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||he.allowClientScripts}set allowClientScripts(t){this.setBoolAttr("allow-client-scripts",t)}get poster(){return this.getAttr("poster")}set poster(t){this.setAttr("poster",t)}get selectedMesh(){return this.getAttr("selected-mesh")}set selectedMesh(t){this.setAttr("selected-mesh",t)}get exposure(){return this.getFloatAttr("exposure",1)}set exposure(t){this.setAttribute("exposure",String(t))}get autoRotate(){return this.getBoolAttr("auto-rotate")}set autoRotate(t){this.setBoolAttr("auto-rotate",t)}get autoRotateDelay(){return this.getFloatAttr("auto-rotate-delay",3e3)}set autoRotateDelay(t){this.setAttribute("auto-rotate-delay",String(t))}get rotationPerSecond(){return this.getAttr("rotation-per-second")||"30deg"}set rotationPerSecond(t){this.setAttr("rotation-per-second",t)}get turntableRotation(){return this.viewer?this.viewer.turntableRotation:0}get ar(){return this.hasAttribute("ar")}set ar(t){this.setBoolAttr("ar",t)}get arScale(){return this.getAttribute("ar-scale")||"auto"}set arScale(t){this.setAttribute("ar-scale",t)}get arPlacement(){return this.getAttribute("ar-placement")||"floor"}set arPlacement(t){this.setAttribute("ar-placement",t)}get canActivateAR(){return he.isARSupported()}get shadowIntensity(){return this.getFloatAttr("shadow-intensity",0)}set shadowIntensity(t){this.setAttribute("shadow-intensity",String(t))}get shadowSoftness(){return this.getFloatAttr("shadow-softness",.5)}set shadowSoftness(t){this.setAttribute("shadow-softness",String(t))}get toneMapping(){return Ce(this.getAttribute("tone-mapping"))}set toneMapping(t){this.setAttribute("tone-mapping",t)}get bloom(){return this.getFloatAttr("bloom",0)}set bloom(t){this.setAttribute("bloom",String(t))}get bloomThreshold(){return gn(this.getAttribute("bloom-threshold"),.62)}set bloomThreshold(t){this.setAttribute("bloom-threshold",String(t))}get bloomRadius(){return gn(this.getAttribute("bloom-radius"),.75)}set bloomRadius(t){this.setAttribute("bloom-radius",String(t))}get outlineSelected(){return this.getBoolAttr("outline-selected")}set outlineSelected(t){this.setBoolAttr("outline-selected",t)}get outlineColor(){return this.getAttr("outline-color")||"#38bdf8"}set outlineColor(t){this.setAttr("outline-color",t)}get environmentImage(){return this.getAttr("environment-image")}set environmentImage(t){this.setAttr("environment-image",t)}get skyboxImage(){return this.getAttr("skybox-image")}set skyboxImage(t){this.setAttr("skybox-image",t)}get autoplay(){return this.getBoolAttr("autoplay")}set autoplay(t){this.setBoolAttr("autoplay",t)}get animationName(){return this.getAttr("animation-name")}set animationName(t){this.setAttr("animation-name",t)}get availableAnimations(){return this.viewer?this.viewer.getAvailableAnimations():[]}get variantName(){return this.viewer?this.viewer.getVariantName():this.getAttr("variant-name")}set variantName(t){this.setAttr("variant-name",t)}get availableVariants(){return this.viewer?this.viewer.getAvailableVariants():[]}selectVariant(t){if(!this.viewer)return!1;let r=this.viewer.selectVariant(t);return r&&this.dispatchEvent(new CustomEvent("variant-applied",{bubbles:!0,composed:!0,detail:{variantName:this.viewer.getVariantName()}})),r}get model(){let t=this.viewer?this.viewer.getModelMaterials():[];return{materials:t,getMaterialByName(r){return t.find(i=>i.name===r)??null}}}play(){this.viewer&&this.viewer.playAnimation(this.animationName||void 0)}pause(){this.viewer&&this.viewer.pauseAnimation()}resetCamera(){this.viewer?.resetCamera()}resetTurntableRotation(t=0){this.viewer?.resetTurntableRotation(t)}setCamera(t,r,i,s){this.viewer&&this.viewer.setCamera(t,r,i,s)}getCameraOrbit(){return this.viewer?this.viewer.getCameraOrbit():{theta:0,phi:0,radius:3,toString(){return"0rad 0rad 3m"}}}getCameraTarget(){return this.viewer?this.viewer.getCameraTarget():{x:0,y:0,z:0,toString(){return"0m 0m 0m"}}}getFieldOfView(){return this.viewer?this.viewer.getFieldOfView():45}jumpCameraToGoal(){this.viewer?.jumpCameraToGoal()}toDataURL(t,r){return this.viewer&&this.viewer.render?.(),this.canvas?this.canvas.toDataURL(t,r):""}toBlob(t){return this.viewer&&this.viewer.render?.(),new Promise((r,i)=>{if(!this.canvas||typeof this.canvas.toBlob!="function"){i(new Error("Canvas toBlob is not supported in this environment."));return}this.canvas.toBlob(s=>{s?r(s):i(new Error("Failed to capture canvas blob."))},t?.mimeType,t?.qualityArgument)})}positionAndNormalFromPoint(t,r){if(!this.viewer)return null;let i=this.viewer.raycastFromScreenPoint(t,r);if(!i)return null;let[s,o,c]=i.hitPoint||i.point,[a,u,l]=i.normal;return{position:{x:s,y:o,z:c,toString(){return`${s}m ${o}m ${c}m`}},normal:{x:a,y:u,z:l,toString(){return`${a}m ${u}m ${l}m`}}}}async loadModel(t){return this.loadModelWithLimits(t)}async loadModelWithLimits(t,r){if(!this.viewer){this.currentModel=t,this.currentModelLimits=r;return}try{let i;if(typeof t=="string"){this.isModelLoaded=!1,this.viewer?.clearScene?.();let a=await fetch(t);if(!a.ok)throw new Error(`Failed to load 3D model from "${t}": HTTP ${a.status}`);i=await a.arrayBuffer()}else i=t;let s=Ae(i);this.viewer.loadGLBData(s,r),this.currentModel=s,this.currentModelLimits=r,this.isModelLoaded=!0,this.hidePoster(),this.updateHotspots();let o=this.getAttribute("selected-mesh");o&&this.viewer.setSelectedMesh(o);let c=this.getAttribute("variant-name");c&&this.selectVariant(c),this.dispatchEvent(new CustomEvent("load",{bubbles:!0,composed:!0,detail:{model:s}}))}catch(i){throw this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:i}})),i}}showToast(t,r=4500){if(typeof document>"u")return;let i=this.querySelector(".three-live-toast");i||(i=document.createElement("div"),i.className="three-live-toast",i.style.cssText="position:absolute;bottom:70px;left:50%;transform:translateX(-50%) translateY(10px);z-index:10;padding:10px 16px;background-color:rgba(15,23,42,0.94);color:#f8fafc;border:1px solid rgba(56,189,248,0.45);border-radius:14px;font:500 13px/1.35 system-ui,-apple-system,sans-serif;box-shadow:0 10px 25px rgba(0,0,0,0.45);backdrop-filter:blur(12px);pointer-events:none;opacity:0;transition:opacity .25s ease,transform .25s ease;max-width:88%;text-align:center;white-space:normal;word-break:break-word",this.appendChild(i)),i.textContent=t,this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=null),typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{i&&(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)")}):(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)"),this.toastTimer=setTimeout(()=>{i&&(i.style.opacity="0",i.style.transform="translateX(-50%) translateY(10px)"),this.toastTimer=null},r)}async activateAR(){if(this.activeXRSession&&typeof this.activeXRSession.isSessionActive=="function"&&this.activeXRSession.isSessionActive()&&(await this.activeXRSession.stop().catch(()=>{}),this.activeXRSession=null),!this.currentModel){let i=new Error("No 3D model is loaded in <three-live>.");throw this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(i.message,6e3),i}if(!he.arProvider){let i=new Error("AR module not bundled. Use the default 'three-live' bundle or call ThreeLiveElement.registerAR().");throw this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(i.message,6e3),i}let t=this.getAttribute("ios-src"),r=(this.getAttribute("ar-modes")||"").split(/\s+/).filter(Boolean);try{this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"session-started"}}));let i=await he.arProvider.activateAR({model:t||this.currentModel,glbUrl:typeof this.currentModel=="string"?this.currentModel:void 0,view:this.viewer||void 0,element:this,preferredModes:r.length>0?r:void 0,arScale:this.arScale,arPlacement:this.arPlacement,webXROptions:{onExit:()=>{this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"not-presenting"}}))},onError:s=>{this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:s}})),this.showToast(`AR error: ${s.message}`,6e3)}}});if(i.success)i.session&&(this.activeXRSession=i.session),i.mode==="quick-look"?this.showToast("Opening Apple AR Quick Look..."):i.mode==="scene-viewer"?this.showToast("Opening Google Scene Viewer..."):i.mode==="webxr"&&this.showToast("WebXR AR session started.");else{let s=typeof navigator<"u"&&navigator.userAgent||"",o=/Macintosh/i.test(s)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1),c=/Android|iPhone|iPad|iPod/i.test(s);if(o&&!c&&typeof document<"u"&&this.currentModel&&he.arProvider.createUSDZBlob)try{let a=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:he.arProvider.createUSDZBlob(this.currentModel),u=URL.createObjectURL(a),l=document.createElement("a");l.href=u,l.download="three_live_model.usdz",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(u),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.",6e3)}else this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.",6e3);i.error&&this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i.error}}))}return i}catch(i){throw this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(`AR error: ${i.message||String(i)}`,6e3),i}}setupDOM(){let t=this.querySelector("canvas");t||(t=document.createElement("canvas"),t.style.width="100%",t.style.height="100%",t.style.display="block",t.style.touchAction=this.cameraControls?"none":"auto",t.style.outline="none",this.appendChild(t)),this.canvas=t;let r=this.getAttribute("poster");r&&this.updatePoster(r),this.createARButton(),typeof MutationObserver<"u"&&!this.mutationObserver&&(this.mutationObserver=new MutationObserver(()=>{this.updateARButtonVisibility()}),this.mutationObserver.observe(this,{childList:!0}))}initViewer(){if(!this.canvas)return;let t=this.autoRotate,r=this.exposure,i=this.parseOrbitLimit(this.getAttribute("min-camera-orbit")),s=this.parseOrbitLimit(this.getAttribute("max-camera-orbit")),o=this.parseCameraTarget(this.getAttribute("camera-target")),c=this.parseFieldOfView(this.getAttribute("field-of-view"));this.viewer=new de(this,this.canvas,{autoRotate:t,autoRotateDelay:this.autoRotateDelay,autoRotateSpeed:this.parseRotationPerSecond(this.getAttribute("rotation-per-second")),exposure:r,shadowIntensity:this.shadowIntensity,shadowSoftness:this.shadowSoftness,toneMapping:this.toneMapping,environmentImage:this.environmentImage,autoplay:this.autoplay,animationName:this.animationName||void 0,variantName:this.getAttribute("variant-name")||void 0,fieldOfView:c,cameraTarget:o,minCameraOrbit:i,maxCameraOrbit:s,onMeshClick:u=>{this.dispatchEvent(new CustomEvent("meshclick",{bubbles:!0,composed:!0,detail:u}))},onCameraChange:u=>{this.updateHotspots();for(let l of de.getRegisteredPlugins())l.onCameraChange?.(this.viewer,this);this.dispatchEvent(new CustomEvent("camera-change",{bubbles:!0,composed:!0,detail:u}))}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let a=this.getAttribute("camera-orbit");a&&this.applyCameraOrbit(a),this.currentModel&&this.loadModelWithLimits(this.currentModel,this.currentModelLimits)}setupResizeObserver(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>{this.viewer&&(this.viewer.resize(),this.viewer.render(),this.updateHotspots())}),this.resizeObserver.observe(this))}updatePoster(t){if(!(typeof document>"u")){if(!t){this.posterEl&&(this.posterEl.remove(),this.posterEl=null);return}this.posterEl||(this.posterEl=document.createElement("img"),this.posterEl.setAttribute("alt","3D Scene Preview"),this.posterEl.style.position="absolute",this.posterEl.style.inset="0",this.posterEl.style.width="100%",this.posterEl.style.height="100%",this.posterEl.style.objectFit="cover",this.posterEl.style.transition="opacity 0.35s ease-out",this.posterEl.style.pointerEvents="none",this.posterEl.style.zIndex="1",this.appendChild(this.posterEl)),this.posterEl.src=t,this.isModelLoaded||(this.posterEl.style.opacity="1")}}hidePoster(){this.posterEl&&(this.posterEl.style.opacity="0",setTimeout(()=>{this.isModelLoaded&&this.posterEl&&(this.posterEl.remove(),this.posterEl=null)},400))}createARButton(){if(!(typeof document>"u")){if(!this.arButton){let t=document.createElement("button");t.setAttribute("type","button"),t.setAttribute("aria-label","View in Augmented Reality"),t.className="three-live-ar-button",t.setAttribute("part","default-ar-button");let r="http://www.w3.org/2000/svg";if(typeof document.createElementNS=="function"){let s=document.createElementNS(r,"svg");s.setAttribute("width","20"),s.setAttribute("height","20"),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke","currentColor"),s.setAttribute("stroke-width","2"),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.style.marginRight="6px";let o=document.createElementNS(r,"path");o.setAttribute("d","M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z");let c=document.createElementNS(r,"polyline");c.setAttribute("points","3.27 6.96 12 12.01 20.73 6.96");let a=document.createElementNS(r,"line");a.setAttribute("x1","12"),a.setAttribute("y1","22.08"),a.setAttribute("x2","12"),a.setAttribute("y2","12"),s.appendChild(o),s.appendChild(c),s.appendChild(a),t.appendChild(s)}let i=document.createElement("span");i.textContent="View in AR",t.appendChild(i),t.style.cssText="position:absolute;right:16px;bottom:16px;z-index:2;align-items:center;justify-content:center;padding:8px 16px;background-color:rgba(15,23,42,0.85);color:#fff;border:1px solid rgba(255,255,255,0.15);border-radius:9999px;font:600 13px system-ui,-apple-system,sans-serif;cursor:pointer;backdrop-filter:blur(8px);box-shadow:0 4px 12px rgba(0,0,0,0.25);transition:transform .15s ease,background-color .15s ease;display:none",t.addEventListener("mouseenter",()=>{t.style.backgroundColor="rgba(30, 41, 59, 0.95)",t.style.transform="scale(1.04)"}),t.addEventListener("mouseleave",()=>{t.style.backgroundColor="rgba(15, 23, 42, 0.85)",t.style.transform="scale(1)"}),t.addEventListener("click",s=>{s.stopPropagation(),this.activateAR()}),this.arButton=t,this.appendChild(t)}this.updateARButtonVisibility()}}updateARButtonVisibility(){let t=this.hasAttribute("ar")&&!!he.arProvider,r=typeof this.querySelector=="function"?this.querySelector('[slot="ar-button"]'):null;r?(this.arButton&&(this.arButton.style.display="none"),r.__tlARBound||(r.__tlARBound=!0,r.addEventListener("click",i=>{i.stopPropagation(),this.activateAR()})),r.dataset.tlOrigDisplay===void 0&&(r.dataset.tlOrigDisplay=r.style.display==="none"?"":r.style.display),r.style.display=t?r.dataset.tlOrigDisplay||"":"none"):this.arButton&&(this.arButton.style.display=t?"flex":"none")}applyCameraOrbit(t){if(!(!t||!this.viewer))try{let r=JSON.parse(t);this.viewer.setInitialCamera(r.theta,r.phi,r.distance,r.zoom)}catch{let r=this.parseOrbitLimit(t);(r.theta!==void 0||r.phi!==void 0)&&this.viewer.setInitialCamera(r.theta,r.phi,r.distance)}}parseOrbitLimit(t){if(!t)return{};let r=t.trim().split(/\s+/),i={};if(r.length>0&&r[0]!=="auto"){let s=this.parseFieldOfView(r[0]);s!==void 0&&(i.theta=s)}if(r.length>1&&r[1]!=="auto"){let s=this.parseFieldOfView(r[1]);s!==void 0&&(i.phi=s)}if(r.length>2&&r[2]!=="auto"){let s=parseFloat(r[2].replace(/m$/,""));isNaN(s)||(i.distance=s)}return i}applyOrbitLimits(){if(!this.viewer)return;let t=this.parseOrbitLimit(this.getAttribute("min-camera-orbit")),r=this.parseOrbitLimit(this.getAttribute("max-camera-orbit"));this.viewer.setOrbitLimits({minTheta:t.theta,maxTheta:r.theta,minPhi:t.phi,maxPhi:r.phi,minDistance:t.distance,maxDistance:r.distance})}parseCameraTarget(t){if(!t)return;let r=t.trim().split(/\s+/).map(i=>parseFloat(i.replace(/m$/,"")));return r.length>=3&&!r.some(isNaN)?[r[0],r[1],r[2]]:void 0}parseFieldOfView(t){if(!t)return;let r=t.endsWith("rad")?parseFloat(t)*180/Math.PI:parseFloat(t.replace(/deg$/,""));return isNaN(r)?void 0:r}parseRotationPerSecond(t){if(!t)return Math.PI/6;let r=t.trim(),i=parseFloat(r);return isNaN(i)?Math.PI/6:r.endsWith("rad")?i:r.endsWith("%")?i/100*Math.PI*2:i*Math.PI/180}applyCameraTarget(t){let r=this.parseCameraTarget(t);this.viewer&&r&&this.viewer.setTarget(r[0],r[1],r[2])}applyFieldOfView(t){let r=this.parseFieldOfView(t);this.viewer&&r!==void 0&&this.viewer.setFieldOfView(r)}updateHotspot(t){let r=this.querySelector(`[slot="${t.name}"]`);r&&(t.position!==void 0&&r.setAttribute("data-position",t.position),t.normal!==void 0&&r.setAttribute("data-normal",t.normal)),this.updateHotspots()}updateHotspots(){for(let t of de.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}runWithScriptRunner(t){let r=he.scriptRunner;if(!r){let i=new Error('Procedural script execution requires "three-live/full" or ThreeLiveElement.registerScriptRunner().');return this.showToast(i.message),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:i}})),Promise.reject(i)}return this.scriptHandle&&(this.scriptHandle.terminate(),this.scriptHandle=null),this.isModelLoaded=!1,this.viewer?.clearScene?.(),new Promise((i,s)=>{let o=!1;t(r,{onModelReady:a=>{this.loadModelWithLimits(a,Vn).then(()=>{o||(o=!0,i(a))},u=>{let l=u instanceof Error?u.message:String(u);this.showToast(l),o||(o=!0,s(u))})},onUpdateTransforms:a=>this.viewer?.updateMeshTransforms(a),onError:a=>{this.showToast(a.message),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:a}})),o||(o=!0,s(a))},onToast:a=>this.showToast(a)}).then(a=>{a&&(this.scriptHandle=a)},a=>{a instanceof Error&&a.message&&this.showToast(a.message),o||(o=!0,s(a))})})}loadScriptFromSrc(t){return this.runWithScriptRunner((r,i)=>{if(typeof r.executeUrl!="function"){let s=new Error("Registered ScriptRunner does not support executeUrl() for server-generated scripts.");return i.onError?.(s),Promise.reject(s)}return r.executeUrl(t,this.sandbox,i)})}executeScript(t){if(!he.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(Je);return this.showToast(Qe),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:r}})),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(t,this.sandbox,i,{allowClientScripts:!0}))}};he.observedAttributes=["src","ios-src","script-src","sandbox","allow-client-scripts","poster","camera-controls","camera-orbit","camera-target","min-camera-orbit","max-camera-orbit","field-of-view","selected-mesh","ar","ar-modes","ar-scale","ar-placement","exposure","shadow-intensity","shadow-softness","tone-mapping","bloom","bloom-threshold","bloom-radius","outline","outline-selected","outline-color","environment-image","skybox-image","autoplay","animation-name","variant-name","auto-rotate","auto-rotate-delay","rotation-per-second"],he.registerPlugin=de.registerPlugin,he.getRegisteredPlugins=de.getRegisteredPlugins;var Te=he;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",Te);function vn(){if(typeof window>"u"||typeof navigator>"u")return!1;let n=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(n)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))return!1;let t=document.createElement("a");return t.relList!==void 0&&t.relList.supports!==void 0&&t.relList.supports("ar")}function wn(){if(typeof navigator>"u")return!1;let n=navigator.userAgent||"";return/android/i.test(n)}async function An(){if(typeof navigator>"u")return!1;let n=navigator;if(!n.xr||typeof n.xr.isSessionSupported!="function")return!1;try{return await n.xr.isSessionSupported("immersive-ar")?!0:await n.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function dr(){return(await St()).bestMode}async function St(){let[n,e,t]=await Promise.all([An(),Promise.resolve(vn()),Promise.resolve(wn())]),r=[];e&&r.push("quick-look"),n&&r.push("webxr"),t&&r.push("scene-viewer");let i=null;return e?i="quick-look":n?i="webxr":t&&(i="scene-viewer"),{webxr:n,quickLook:e,sceneViewer:t,availableModes:r,bestMode:i}}function hr(n,e={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let t,r=!1;if(typeof n=="string"){if(t=hi(n),!t)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else t=URL.createObjectURL(n),r=!0;let i=[];if(e.allowScale===!1&&i.push("allowsContentScaling=0"),e.canonicalWebPageUrl){let c=Rt(e.canonicalWebPageUrl,!1);c&&i.push(`canonicalWebPageURL=${encodeURIComponent(c)}`)}e.checkoutTitle&&i.push(`checkoutTitle=${encodeURIComponent(e.checkoutTitle)}`),e.checkoutSubtitle&&i.push(`checkoutSubtitle=${encodeURIComponent(e.checkoutSubtitle)}`),e.price&&i.push(`price=${encodeURIComponent(e.price)}`),i.length>0&&(t+=`#${i.join("&")}`);let s=document.createElement("a");s.setAttribute("rel","ar"),s.setAttribute("href",t);let o=document.createElement("img");o.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),o.style.display="none",s.appendChild(o),document.body.appendChild(s),s.click(),setTimeout(()=>{document.body.removeChild(s),r&&URL.revokeObjectURL(t.split("#")[0])},3e3)}function Rt(n,e=!1){if(typeof n!="string")return"";let t=n.replace(/[\x00-\x1f\x7f]+/g,"").trim();if(!t)return"";if(/^[\\/]{2}/.test(t))throw new Error(`[XR-Live Security] Rejected protocol-relative URL in Scene Viewer intent: ${t.slice(0,32)}`);let r=t.toLowerCase();if(r.startsWith("https://")||r.startsWith("http://")||e&&r.startsWith("blob:")||!/^[a-z][a-z0-9+.-]*:/i.test(t))return t;throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Scene Viewer intent: ${t.slice(0,32)}`)}function hi(n){try{return Rt(n,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(n||"").trim().slice(0,32)}`)}}function mi(n,e={}){let t=Rt(n,!0),r=e.mode||"ar_preferred",i=new URLSearchParams({file:t,mode:r,resizable:e.resizable!==!1?"true":"false",enable_vertical_placement:e.enableVerticalPlacement?"true":"false"});return e.title&&i.set("title",e.title),e.link&&i.set("link",Rt(e.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${i.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function di(n,e={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let t=mi(n,e);window.location.href=t}var Pe=null;function fi(n,e){let r=new Float32Array(144),i=new Float32Array(24*6),s=new Float32Array(24*4),o=new Uint16Array(24*6);for(let m=0;m<24;m++){let h=m/24*Math.PI*2,y=Math.cos(h),b=Math.sin(h),d=m*2,g=d+1,T=(m+1)%24*2;r[d*3]=y*.11,r[d*3+1]=.002,r[d*3+2]=b*.11,r[g*3]=y*.145,r[g*3+1]=.002,r[g*3+2]=b*.145,i[d*3+1]=i[g*3+1]=1,o.set([d,T,g,g,T,T+1],m*6)}let c=n.createVertexArray();n.bindVertexArray(c);let a=(m,h,y)=>{let b=n.createBuffer();return n.bindBuffer(34962,b),n.bufferData(34962,m,35044),n.enableVertexAttribArray(h),n.vertexAttribPointer(h,y,5126,!1,0,0),b},u=[a(r,0,3),a(i,1,3),a(s,2,2)],l=n.createBuffer();return u.push(l),n.bindBuffer(34963,l),n.bufferData(34963,o,35044),n.bindVertexArray(null),{name:"__xr_reticle__",nodeIndex:-1,worldSpace:!0,visible:!1,transform:new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),normalMatrix:new Float32Array([1,0,0,0,1,0,0,0,1]),primitives:[{vao:c,indexCount:o.length,indexType:5123,baseColor:e&&e.length>=3?[e[0],e[1],e[2],e[3]??.95]:[.22,.74,.97,.95],metallic:0,roughness:.2,positions:r,indices:o,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:u}]}}function mr(n,e,t,r,i){let s=Math.cos(r),o=Math.sin(r),c=Math.max(.01,i);n.fill(0),n[0]=c*s,n[2]=-c*o,n[5]=c,n[8]=c*o,n[10]=c*s,n[12]=e[0]-c*(s*t[0]+o*t[2]),n[13]=e[1]-c*t[1],n[14]=e[2]-c*(-o*t[0]+s*t[2]),n[15]=1}var xn=class{constructor(e={}){this.s=null;this.placed=!1;this.placedMat=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);this.cleanFn=null;this.opts=e}isSessionActive(){return this.s!==null}hasPlacedModel(){return this.placed}getPlacedMatrix(){return this.placedMat}async start(e,t){if(typeof navigator>"u"||!navigator.xr)throw new Error("WebXR is not supported on this browser.");Pe&&Pe!==this&&Pe.isSessionActive()&&await Pe.stop().catch(()=>{});let r=navigator.xr,i=this.opts,s=t||e?.container,o=String(s?.tagName||"").toLowerCase()==="xr-live",c=e?.bounds,a=Number(c?.radius)||1,u=Array.isArray(c?.center)?c.center:[0,0,0],l=Array.isArray(c?.min)?c.min:[-.5,-.5,-.5],m=typeof navigator<"u"&&navigator.userAgent||"",h=/Android|iPhone|iPad|iPod/i.test(m)&&!/Quest|Oculus|Pico|Vision/i.test(m),y=o?i.arScale==="fixed"?1:h?.55:1:i.arScale==="fixed"?1:a>.45?.3/a:a<.05?.12/Math.max(a,.001):1,b=o?[0,-.25,0]:[u[0]||0,i.arPlacement==="wall"?u[1]:l[1]??0,u[2]||0],d="immersive-ar";try{await r.isSessionSupported("immersive-ar")||(d="immersive-vr")}catch{d="immersive-vr"}let g=s?.querySelector?.('[slot="ar-overlay"]')||null,T=!1,P=null,f=()=>{T&&g?.parentNode&&g.parentNode.removeChild(g),g=null,P=null,T=!1};if(d==="immersive-ar"){if(g)g.addEventListener?.("beforexrselect",E=>E.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let E=document.createElement("div");E.style.cssText="position:fixed;inset:0;pointer-events:none;background:transparent!important;z-index:2147483647;font-family:system-ui,sans-serif;user-select:none";let k=document.createElement("button");k.type="button",k.textContent="\u2715 Exit AR",k.style.cssText="position:absolute;top:max(16px,env(safe-area-inset-top,16px));right:16px;pointer-events:auto;padding:8px 14px;border-radius:99px;border:1px solid rgba(255,255,255,.3);background:rgba(15,23,42,.8);color:#f8fafc;font:600 13px system-ui,sans-serif",k.addEventListener("beforexrselect",G=>G.preventDefault()),k.addEventListener("click",G=>{G.stopPropagation(),this.stop().catch(()=>{})}),P=document.createElement("div"),P.style.cssText="position:absolute;bottom:max(28px,env(safe-area-inset-bottom,28px));left:50%;transform:translateX(-50%);padding:8px 15px;border-radius:99px;border:1px solid rgba(56,189,248,.4);background:rgba(15,23,42,.82);color:#f8fafc;font:500 12.5px system-ui,sans-serif;text-align:center;max-width:88vw",P.textContent="Move phone to detect a surface \u2022 Tap to place",E.appendChild(k),E.appendChild(P),document.body.appendChild(E),g=E,T=!0}}let M=new Set(i.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),p={requiredFeatures:i.requiredFeatures?[...i.requiredFeatures]:[],optionalFeatures:Array.from(M)};g&&(M.add("dom-overlay"),p.optionalFeatures=Array.from(M),p.domOverlay={root:g});for(let E of ce)E.onConfigureXRSessionInit?.(s,p);Array.isArray(p.optionalFeatures)&&p.optionalFeatures.includes("dom-overlay")&&!p.domOverlay?.root&&(p.optionalFeatures=p.optionalFeatures.filter(E=>E!=="dom-overlay"));let S=E=>{let k=String(E?.name||"");return k==="NotAllowedError"||k==="SecurityError"};try{this.s=await r.requestSession(d,p)}catch(E){if(f(),S(E))throw i.onError?.(E),E;try{this.s=await r.requestSession(d,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(k){if(S(k))throw i.onError?.(k),k;try{this.s=await r.requestSession(d)}catch(G){throw i.onError?.(G),G}}}let _=this.s;Pe=this,this.placed=!1;let w=null,A=null,L=null,x=null,v=null,I=[0,-.25,-1.2],R=[0,-.25,-1.2],C=new Float32Array(16),N=new Float32Array(16),F=!1,V=1,U=0,B=!1,D=null,H=null,z=0,O=null,X=()=>{Pe===this&&(Pe=null),O?.(),O=null;try{A?.cancel?.()}catch{}if(A=null,L){let E=e?.meshes;if(Array.isArray(E)){let G=E.indexOf(L);G!==-1&&E.splice(G,1)}let k=e.getGLContext?.()||e?.gl;if(k)for(let G of L.primitives||[]){k.deleteVertexArray?.(G.vao);for(let W of G.buffers||[])k.deleteBuffer?.(W)}L=null}e?.setXRSessionActive?.(!1),f(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=X,_.addEventListener("end",()=>{X(),i.onExit?.()}),_.addEventListener("select",()=>{if(!this.placed){let E=v||I;R=[E[0],E[1],E[2]],mr(this.placedMat,R,b,U,y*V),this.placed=!0,L&&(L.visible=!1),P&&(P.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),i.onPlaced?.(this.placedMat)}});try{let E=e.getGLContext?.()||e?.gl;E&&typeof E.makeXRCompatible=="function"&&await E.makeXRCompatible();let k=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;E&&typeof k=="function"&&typeof _.updateRenderState=="function"&&_.updateRenderState({baseLayer:new k(_,E,{alpha:!0})});try{w=await _.requestReferenceSpace("local")}catch{try{w=await _.requestReferenceSpace("local-floor")}catch{w=await _.requestReferenceSpace("viewer")}}let G=await _.requestReferenceSpace("viewer").catch(()=>w);if(typeof _.requestHitTestSource=="function"&&G&&(A=await _.requestHitTestSource({space:G}).catch(()=>null)),d==="immersive-ar"&&E&&typeof E.createVertexArray=="function"&&Array.isArray(e.meshes)&&(L=fi(E,i.reticleColor),e.meshes.push(L)),typeof window<"u"&&typeof window.addEventListener=="function"){let j=Y=>Math.hypot(Y.touches[1].clientX-Y.touches[0].clientX,Y.touches[1].clientY-Y.touches[0].clientY),re=Y=>Math.atan2(Y.touches[1].clientY-Y.touches[0].clientY,Y.touches[1].clientX-Y.touches[0].clientX),ue=Y=>{this.s&&(Y.touches.length===1&&this.placed?B=!0:Y.touches.length>=2&&(B=!1,D=j(Y),H=re(Y)))},q=Y=>{if(!this.s||Y.touches.length<2)return;let ie=j(Y),$=re(Y);if(D&&D>4&&i.arScale!=="fixed"&&(V=Math.max(.15,Math.min(6,V*(ie/D)))),H!==null){let ne=$-H;ne>Math.PI&&(ne-=Math.PI*2),ne<-Math.PI&&(ne+=Math.PI*2),U-=ne}D=ie,H=$},Z=Y=>{(!Y.touches||Y.touches.length===0)&&(B=!1),(!Y.touches||Y.touches.length<2)&&(D=null,H=null)};window.addEventListener("touchstart",ue,{passive:!0}),window.addEventListener("touchmove",q,{passive:!0}),window.addEventListener("touchend",Z,{passive:!0}),window.addEventListener("touchcancel",Z,{passive:!0}),O=()=>{window.removeEventListener("touchstart",ue),window.removeEventListener("touchmove",q),window.removeEventListener("touchend",Z),window.removeEventListener("touchcancel",Z)}}e.setXRSessionActive?.(!0);let W=(j,re)=>{if(this.s!==_)return;_.requestAnimationFrame(W);let ue=z>0?Math.min(Math.max((j-z)/1e3,0),.1):1/60;z=j,e?.stepXRUpdate?.(ue);let q=re.getViewerPose(w);if(!q)return;let Z=q.views?.[0];if(!F&&Z?.transform){let ee=Z.transform.position,se=Z.transform.matrix,be=ee?.x??(se?se[12]:0),me=ee?.y??(se?se[13]:0),fe=ee?.z??(se?se[14]:0),Se=se?-se[8]:0,Xe=se?-se[10]:-1,Tt=Math.hypot(Se,Xe);Tt>1e-4?(Se/=Tt,Xe/=Tt):(Se=0,Xe=-1),I=[be+Se*1.2,me-.25,fe+Xe*1.2],U=Math.atan2(-Se,-Xe),F=!0}if(A&&typeof re.getHitTestResults=="function"&&(!this.placed||B)){let ee=re.getHitTestResults(A)||[],se=!1;for(let be of ee){let me=be.getPose(w);if(me?.transform?.matrix){let fe=me.transform.matrix,Se=fe[5];if(i.arPlacement==="wall"&&Math.abs(Se)>.35||i.arPlacement==="floor"&&Math.abs(Se)<.65)continue;x||(x=new Float32Array(16)),x.set(fe),v=[fe[12],fe[13],fe[14]],this.placed&&B&&(R=[fe[12],fe[13],fe[14]]),L&&(L.visible=!this.placed||B,L.transform.set(fe)),!this.placed&&P&&(P.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),i.onHit?.(x),se=!0;break}}!se&&L&&(L.visible=!1)}mr(C,this.placed?R:v||I,b,U,y*V),this.placed&&this.placedMat.set(C);let Y=e.xrRigMatrix;Y instanceof Float32Array&&Y.length===16?ae(N,Y,C):N.set(C),e.modelRootMatrix&&e.modelRootMatrix.set(N);for(let ee of ce)ee.onXRFrame?.(e,_,re,w);let ie=e.getGLContext?.()||e?.gl,$=_.renderState?.baseLayer;ie&&$&&$.framebuffer!==void 0&&ie.bindFramebuffer(36160,$.framebuffer);let ne=d==="immersive-ar",te=q.views||[];for(let ee=0;ee<te.length;ee++){let se=te[ee];if(typeof e.renderXRView=="function"){let be;if($&&typeof $.getViewport=="function"){let me=$.getViewport(se);me&&me.width>0&&me.height>0&&(be=[me.x,me.y,me.width,me.height])}else $?.framebufferWidth>0&&$?.framebufferHeight>0&&(be=[0,0,$.framebufferWidth,$.framebufferHeight]);e.renderXRView(se,N,this.placed,be,ne,ee)}}ie&&$&&$.framebuffer&&ie.bindFramebuffer(36160,null)};_.requestAnimationFrame(W)}catch(E){throw typeof _.end=="function"&&await _.end().catch(()=>{}),X(),i.onError?.(E),E}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function Et(n){let e=await St(),t=n.preferredModes||["quick-look","webxr","scene-viewer"],r=null;for(let c of t)if(e.availableModes.includes(c)){r=c;break}if(r||(r=e.bestMode),!r)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let i={...n.quickLookOptions,allowScale:n.arScale==="fixed"?!1:n.quickLookOptions?.allowScale},s={...n.sceneViewerOptions,resizable:n.arScale==="fixed"?!1:n.sceneViewerOptions?.resizable,enableVerticalPlacement:n.arPlacement==="wall"?!0:n.sceneViewerOptions?.enableVerticalPlacement},o={...n.webXROptions,arScale:n.arScale||n.webXROptions?.arScale,arPlacement:n.arPlacement||n.webXROptions?.arPlacement};try{if(r==="quick-look"){let c;if(n.model instanceof Blob&&n.model.type==="model/vnd.usdz+zip")c=n.model;else{if(typeof n.model=="string")return hr(n.model,i),{mode:"quick-look",success:!0};c=ke(n.model)}return hr(c,i),{mode:"quick-look",success:!0}}if(r==="scene-viewer"){let c=n.glbUrl||(typeof n.model=="string"?n.model:null);if(!c)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return di(c,s),{mode:"scene-viewer",success:!0}}if(r==="webxr"){if(!n.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let c=new xn(o);return await c.start(n.view,n.element),{mode:"webxr",success:!0,session:c}}}catch(c){return{mode:r,success:!1,error:c}}return{mode:r,success:!1,error:new Error(`Unhandled AR mode: ${r}`)}}Te.registerAR({activateAR:Et,createUSDZBlob:ke});Te.registerScriptRunner(yn);Ze(Sn);
|