three-live 1.3.0 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +1 -1
  2. package/dist/index.d.ts +37 -0
  3. package/dist/three-author-engine.js +112 -61
  4. package/dist/three-author.cjs +110 -59
  5. package/dist/three-author.d.ts +37 -0
  6. package/dist/three-author.js +109 -58
  7. package/dist/three-convert.cjs +106 -59
  8. package/dist/three-convert.d.ts +37 -0
  9. package/dist/three-convert.js +105 -58
  10. package/dist/three-live-animation.cjs +8 -9
  11. package/dist/three-live-animation.d.ts +37 -0
  12. package/dist/three-live-animation.js +7 -8
  13. package/dist/three-live-animation.min.js +6 -7
  14. package/dist/three-live-cad.cjs +3 -4
  15. package/dist/three-live-cad.d.ts +37 -0
  16. package/dist/three-live-cad.js +2 -3
  17. package/dist/three-live-cad.min.js +3 -4
  18. package/dist/three-live-cli.js +231 -0
  19. package/dist/three-live-element.cjs +17 -20
  20. package/dist/three-live-element.d.ts +37 -0
  21. package/dist/three-live-element.js +16 -19
  22. package/dist/three-live-full.cjs +138 -87
  23. package/dist/three-live-full.js +137 -86
  24. package/dist/three-live-full.min.js +138 -87
  25. package/dist/three-live-studio.cjs +19 -20
  26. package/dist/three-live-studio.d.ts +37 -0
  27. package/dist/three-live-studio.js +18 -19
  28. package/dist/three-live-studio.min.js +18 -19
  29. package/dist/three-live-viewer.cjs +17 -20
  30. package/dist/three-live-viewer.d.ts +37 -0
  31. package/dist/three-live-viewer.js +16 -19
  32. package/dist/three-live-viewer.min.js +17 -20
  33. package/dist/three-live.cjs +115 -64
  34. package/dist/three-live.js +113 -62
  35. package/dist/three-live.min.js +115 -64
  36. package/dist/three-view.cjs +17 -20
  37. package/dist/three-view.d.ts +37 -0
  38. package/dist/three-view.js +16 -19
  39. package/dist/three-xr.cjs +105 -58
  40. package/dist/three-xr.d.ts +37 -0
  41. package/dist/three-xr.js +104 -57
  42. package/package.json +25 -1
@@ -1,4 +1,4 @@
1
- /**
1
+ "use strict";/**
2
2
  * @license
3
3
  * Copyright 2026 Google LLC
4
4
  *
@@ -13,10 +13,9 @@
13
13
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
- */
17
- "use strict";var ThreeLive=(()=>{var Ct=Object.defineProperty;var fr=Object.getOwnPropertyDescriptor;var pr=Object.getOwnPropertyNames;var br=Object.prototype.hasOwnProperty;var yr=(n,e)=>{for(var t in e)Ct(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&&Ct(n,i,{get:()=>e[i],enumerable:!(r=fr(e,i))||r.enumerable});return n};var xr=n=>gr(Ct({},"__esModule",{value:!0}),n);var pi={};yr(pi,{THREE:()=>Pe,ThreeLiveElement:()=>_e,ThreeView:()=>me,activateAR:()=>Tt,createUSDZBlob:()=>Ue,evaluateToneMapping:()=>Un,getARCapabilities:()=>Et,getBestARMode:()=>dr,isQuickLookSupported:()=>wn,isSceneViewerSupported:()=>Rn,isWebXRSupported:()=>Mn,toGLBData:()=>Re});var Ke="__THREE_LIVE_REGISTRY__";function J(){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 ae=J().plugins;function Ze(n){let e=J().plugins;e.some(t=>t.name===n.name)||e.push(n),n.onRegister?.()}function Sn(){return J().plugins}var vr=`#version 300 es
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);}`,We=new WeakMap,An=new Float32Array(20);function Lt(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 Rr(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 En={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=Rr(d);if(!g)continue;d.transform&&(g=Lt(d.transform,g)),e.modelRootMatrix&&(g=Lt(e.modelRootMatrix,g));let[T,P,f,M,p,A]=g,C=[T,f,M,A,P-p,P+p];/floor|table|pedestal|ground|base|plane/i.test(d.name||"")||p<.14&&Math.min(M,A)>.45?c.push(C):o.push(C)}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=Lt(e.modelRootMatrix,h));let y=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[A,C,w,R,,L]of c)f>=L-.08&&Math.abs(d-A)<=w&&Math.abs(g-C)<=R&&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=y);let p=a.find(A=>Math.hypot(d-A[0],g-A[1])<.06&&Math.abs(M-A[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,y,y])}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),A=r/(1+p*2);if(A<.02)continue;let C=1+Math.min(.75,p*.85),w=Math.max(.045,T*1.45*C),R=Math.max(.045,P*1.45*C);An.set([d-w,M,g-R,0,0,d+w,M,g-R,1,0,d+w,M,g+R,1,1,d-w,M,g+R,0,1]),n.bufferSubData(34962,0,An),n.uniform1f(i.uIntensity,A),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 Tn(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,b=f=>({node:f,socket:"value"}),y=t?.interactivity??t?.gltfExtensions?.KHR_interactivity;if(y&&typeof y=="object"){let f=Array.isArray(y.graphs)?y.graphs[y.graph??0]:y;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 A=p.op||(typeof p.declaration=="number"?M[p.declaration]?.op:"");s.push(A?{...p,declaration:u(A)}:{...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 A=(typeof M.mesh=="number"?e[M.mesh]?.primitives?.[0]?.material:0)??0,C=R=>{let L=Array.isArray(R)?R:[R],x=[];for(let I=0;I<L.length;I++){let S=L[I];if(!S||typeof S!="object")continue;let _=S.action||"interpolate",k=typeof S.duration=="number"?S.duration:.35;if(_==="toggleTransform"){let N=S.property==="rotation"||S.property==="scale"?S.property:"translation",V=N==="rotation"?M.rotation||[0,0,0,1]:N==="scale"?M.scale||[1,1,1]:M.translation||[0,0,0],U=`/nodes/${f}/${N}`,B=h(`__toggle_${f}_${I}`,"bool",!1),D=m("variable/get",{configuration:{variable:B}}),H=m("math/not",{values:{a:b(D)}}),z=m("variable/set",{configuration:{variable:B},values:{value:b(H)}}),O=m("pointer/interpolate",{configuration:{pointer:U},values:{value:{value:Array.isArray(S.to)?S.to:V},duration:{value:k}}}),X=m("pointer/interpolate",{configuration:{pointer:U},values:{value:{value:Array.isArray(S.from)?S.from:V},duration:{value:k}}});s[z].flows={out:{node:m("flow/branch",{values:{condition:b(D)},flows:{true:{node:O},false:{node:X}}})}},x.push(z)}else if(_==="interpolate"){let N=S.to??S.value;if(N===void 0)continue;let V={value:{value:N},duration:{value:k}};S.from!==void 0&&(V.from={value:S.from}),x.push(m("pointer/interpolate",{configuration:{pointer:typeof S.pointer=="string"?S.pointer:d(T(S,f),P(T(S,f)),S.property)},values:V}))}else if(_==="setProperty"){if(S.value===void 0)continue;x.push(m("pointer/set",{configuration:{pointer:typeof S.pointer=="string"?S.pointer:d(T(S,f),P(T(S,f)),S.property)},values:{value:{value:S.value}}}))}else if(_==="toggleVisibility"){let N=T(S,f),V=h(`__vis_${N}_${I}`,"bool",!0),U=m("variable/get",{configuration:{variable:V}}),B=m("math/not",{values:{a:b(U)}}),D=m("variable/set",{configuration:{variable:V},values:{value:b(B)}});s[D].flows={out:{node:m("pointer/set",{configuration:{pointer:`/nodes/${N}/extensions/KHR_node_visibility/visible`},values:{value:b(U)}})}},x.push(D)}else if(_==="cycleMaterialColor"&&Array.isArray(S.colors)&&S.colors.length>0){let N=typeof S.duration=="number"?S.duration:.25,V=`/materials/${Math.max(0,A)}/pbrMetallicRoughness/baseColorFactor`,U=h(`__color_idx_${f}_${I}`,"int",0),B=m("variable/get",{configuration:{variable:U}}),D=m("math/add",{values:{a:b(B),b:{value:1}}}),H=m("math/rem",{values:{a:b(D),b:{value:S.colors.length}}}),z=m("variable/set",{configuration:{variable:U},values:{value:b(H)}}),O={};for(let X=0;X<S.colors.length;X++){let E=S.colors[X],F=Array.isArray(E)&&E.length>=3?[E[0],E[1],E[2],E[3]??1]:[1,1,1,1];O[String(X)]={node:N>0?m("pointer/interpolate",{configuration:{pointer:V},values:{value:{value:F},duration:{value:N}}}):m("pointer/set",{configuration:{pointer:V},values:{value:{value:F}}})}}s[z].flows={out:{node:m("flow/switch",{values:{selection:b(B)},flows:O})}},x.push(z)}else if(_==="playAnimation")x.push(m("animation/start",{configuration:{animation:S.animation??S.clip??0}}));else if(_==="stopAnimation")x.push(m("animation/stop"));else if(_==="sendEvent"){let N={};for(let[V,U]of Object.entries(S.values||{}))N[V]={value:U};x.push(m("event/send",{configuration:{event:l(String(S.event??S.id??"custom"))},values:N}))}}if(!x.length)return null;if(x.length===1)return x[0];let v={};return x.forEach((I,S)=>{v[String(S)]={node:I}}),m("flow/sequence",{flows:v})},w=(R,L,x)=>{let v=C(L);v!==null&&m(R,{...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[R,L]of Object.entries(p.onReceive))w("event/receive",L,{event:l(R)})}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 se(){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 ke(n,e,t,r){let[i,s,o]=e,[c,a,u]=r,[l,m,h]=t,b=i-l,y=s-m,d=o-h,g=Math.hypot(b,y,d);g<=1e-5?(b=0,y=0,d=1):(b/=g,y/=g,d/=g);let T=a*d-u*y,P=u*b-c*d,f=c*y-a*b;g=Math.hypot(T,P,f),g<=1e-5?(T=0,P=0,f=0):(T/=g,P/=g,f/=g);let M=y*f-d*P,p=d*T-b*f,A=b*P-y*T;return g=Math.hypot(M,p,A),g<=1e-5?(M=0,p=0,A=0):(M/=g,p/=g,A/=g),n[0]=T,n[1]=M,n[2]=b,n[3]=0,n[4]=P,n[5]=p,n[6]=y,n[7]=0,n[8]=f,n[9]=A,n[10]=d,n[11]=0,n[12]=-(T*i+P*s+f*o),n[13]=-(M*i+p*s+A*o),n[14]=-(b*i+y*s+d*o),n[15]=1,n}function oe(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],b=e[10],y=e[11],d=e[12],g=e[13],T=e[14],P=e[15],f=t[0],M=t[1],p=t[2],A=t[3];return n[0]=f*r+M*c+p*m+A*d,n[1]=f*i+M*a+p*h+A*g,n[2]=f*s+M*u+p*b+A*T,n[3]=f*o+M*l+p*y+A*P,f=t[4],M=t[5],p=t[6],A=t[7],n[4]=f*r+M*c+p*m+A*d,n[5]=f*i+M*a+p*h+A*g,n[6]=f*s+M*u+p*b+A*T,n[7]=f*o+M*l+p*y+A*P,f=t[8],M=t[9],p=t[10],A=t[11],n[8]=f*r+M*c+p*m+A*d,n[9]=f*i+M*a+p*h+A*g,n[10]=f*s+M*u+p*b+A*T,n[11]=f*o+M*l+p*y+A*P,f=t[12],M=t[13],p=t[14],A=t[15],n[12]=f*r+M*c+p*m+A*d,n[13]=f*i+M*a+p*h+A*g,n[14]=f*s+M*u+p*b+A*T,n[15]=f*o+M*l+p*y+A*P,n}function Ce(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,b=i*l,y=s*u,d=s*l,g=o*l,T=c*a,P=c*u,f=c*l,M=r[0],p=r[1],A=r[2];return n[0]=(1-(y+g))*M,n[1]=(h+f)*M,n[2]=(b-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]=(b+P)*A,n[9]=(d-T)*A,n[10]=(1-(m+y))*A,n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n}function ye(n,e,t=0){let r=e[0],i=e[1],s=e[2],o=e[4],c=e[5],a=e[6],u=e[8],l=e[9],m=e[10],h=m*c-a*l,b=-m*o+a*u,y=l*o-c*u,d=r*h+i*b+s*y;return!d||t>0&&(!Number.isFinite(d)||Math.abs(d)<=t)||(d=1/d,n[0]=h*d,n[1]=b*d,n[2]=y*d,n[3]=(-m*i+s*l)*d,n[4]=(m*r-s*u)*d,n[5]=(-l*r+i*u)*d,n[6]=(a*i-s*c)*d,n[7]=(-a*r+s*o)*d,n[8]=(c*r-i*o)*d),n}function _n(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],b=e[11],y=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,A=r*u-s*c,C=i*u-s*a,w=l*d-m*y,R=l*g-h*y,L=l*T-b*y,x=m*g-h*d,v=m*T-b*d,I=h*T-b*g,S=P*I-f*v+M*x+p*L-A*R+C*w;return S?(S=1/S,n[0]=(c*I-a*v+u*x)*S,n[1]=(i*v-r*I-s*x)*S,n[2]=(d*C-g*A+T*p)*S,n[3]=(h*A-m*C-b*p)*S,n[4]=(a*L-o*I-u*R)*S,n[5]=(t*I-i*L+s*R)*S,n[6]=(g*M-y*C-T*f)*S,n[7]=(l*C-h*M+b*f)*S,n[8]=(o*v-c*L+u*w)*S,n[9]=(r*L-t*v-s*w)*S,n[10]=(y*A-d*M+T*P)*S,n[11]=(m*M-l*A-b*P)*S,n[12]=(c*R-o*x-a*w)*S,n[13]=(t*x-r*R+i*w)*S,n[14]=(d*f-y*p-g*P)*S,n[15]=(l*p-m*f+h*P)*S,n):null}function It(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 Cn(n,e,t,r,i,s,o,c,a,u,l,m,h,b,y,d,g=0){let T=u-o,P=l-c,f=m-a,M=h-o,p=b-c,A=y-a,C=i*A-s*p,w=s*M-r*A,R=r*p-i*M,L=T*C+P*w+f*R;if(L>-1e-7&&L<1e-7)return!1;let x=1/L,v=n-o,I=e-c,S=t-a,_=x*(v*C+I*w+S*R);if(_<-g||_>1+g)return!1;let k=I*f-S*P,N=S*T-v*f,V=v*P-I*T,U=x*(r*k+i*N+s*V);if(U<-g||_+U>1+g)return!1;let B=x*(M*k+p*N+A*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*A-f*p,H=f*M-T*A,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(se());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 b=n.nodes[l];if(!b)return;let y=se();if(e&&e[l])y.set(e[l]);else if(b.matrix&&b.matrix.length===16)y.set(b.matrix);else{let g=b.translation||[0,0,0],T=b.rotation||[0,0,0,1],P=b.scale||[1,1,1];Ce(y,T,g,P)}let d=r[l];if(m?oe(d,m,y):d.set(y),Array.isArray(b.children))for(let g of b.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}function nt(n,e,t,r=!0){let i=[],s=null;try{for(let[o,c]of[[35633,e],[35632,t]]){let a=n.createShader(o);if(!a){if(r)throw new Error("Shader allocation failed");return null}if(i.push(a),n.shaderSource(a,c),n.compileShader(a),n.getShaderParameter&&!n.getShaderParameter(a,35713)){if(r)throw new Error(`Shader compile error: ${n.getShaderInfoLog(a)}`);return null}}if(s=n.createProgram(),!s){if(r)throw new Error("Program allocation failed");return null}for(let o of i)n.attachShader(s,o);if(n.linkProgram(s),n.getProgramParameter&&!n.getProgramParameter(s,35714)){let o=r?n.getProgramInfoLog(s):null;if(n.deleteProgram?.(s),s=null,r)throw new Error(`Program link error: ${o}`);return null}return s}finally{for(let o of i)s&&n.detachShader?.(s,o),n.deleteShader?.(o)}}var Sr={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function Pt(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=Sr[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,b=new Float32Array(s*r);for(let y=0;y<s;y++){let d=l+y*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)}b[y*r+g]=P}}return b}function Ln(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 b=0;b+1<n.length;b+=2){let y=n[b],d=n[b+1];n[b]=u*y+l*d+t,n[b+1]=m*y+h*d+r}}var Pn=["neutral","reinhard","none","aces","agx"];function Le(n){let e=String(n??"").trim().toLowerCase();return Pn.includes(e)?e:"neutral"}function Ar(n){return Pn.indexOf(Le(n))}function Er(n){return new TextDecoder().decode(n)}var Nn=J().decoders;function Tr(n,e){Nn.set(n.toLowerCase(),e)}function Fe(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 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),b=t.getUint32(o+4,!0),y=o+8;if(y+h>e.byteLength)throw new Error(`Truncated GLB chunk: required ${y+h} bytes, buffer has ${e.byteLength}`);if(b===1313821514){let d=new Uint8Array(e,y,h),g=Er(d);c=JSON.parse(g,(T,P)=>T==="__proto__"||T==="constructor"||T==="prototype"?void 0:P)}else b===5130562&&(a=e.slice(y,y+h));o=y+h}if(!c)throw new Error("Missing JSON chunk in GLB");let u=c.extensionsRequired||[];if(u.includes("KHR_draco_mesh_compression")&&!Fe("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)&&!Fe("meshopt"))throw new Error(`Model requires ${h}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(u.includes("KHR_texture_basisu")&&!Fe("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 ae)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 Re(n){if(_r(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 Fn=`#version 300 es
16
+ */var ThreeLive=(()=>{var xt=Object.defineProperty,mr=Object.getOwnPropertyDescriptor,dr=Object.getOwnPropertyNames,pr=Object.prototype.hasOwnProperty,fr=(t,e)=>{for(var i in e)xt(t,i,{get:e[i],enumerable:!0})},gr=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of dr(e))!pr.call(t,s)&&s!==i&&xt(t,s,{get:()=>e[s],enumerable:!(r=mr(e,s))||r.enumerable});return t},br=t=>gr(xt({},"__esModule",{value:!0}),t),$t={};fr($t,{THREE:()=>He,ThreeLiveElement:()=>Je,ThreeView:()=>Se,activateAR:()=>ir,createUSDZBlob:()=>Lt,defineModelViewer:()=>sa,evaluateToneMapping:()=>Fr,getARCapabilities:()=>Bt,getBestARMode:()=>aa,isQuickLookSupported:()=>Zi,isSceneViewerSupported:()=>Qi,isWebXRSupported:()=>Ji,toGLBData:()=>We});var et="__THREE_LIVE_REGISTRY__";function he(){let t=typeof globalThis<"u"?globalThis:{};if(!t[et]){let e={plugins:[],decoders:new Map};try{Object.defineProperty(t,et,{value:e,writable:!1,configurable:!1,enumerable:!1})}catch{t[et]=e}}return t[et]}var me=he().plugins;function Ht(t){let e=he().plugins;e.some(i=>i.name===t.name)||e.push(t),t.onRegister?.()}function yr(){return he().plugins}var vr=`#version 300 es
17
+ 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.);}`,xr=`#version 300 es
18
+ 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);}`,Ge=new WeakMap,jt=new Float32Array(20);function Mt(t,e){let[i,r,s,a,o,n]=e;return[t[0]*i+t[4]*r+t[8]*s+t[12],t[1]*i+t[5]*r+t[9]*s+t[13],t[2]*i+t[6]*r+t[10]*s+t[14],Math.abs(t[0])*a+Math.abs(t[4])*o+Math.abs(t[8])*n,Math.abs(t[1])*a+Math.abs(t[5])*o+Math.abs(t[9])*n,Math.abs(t[2])*a+Math.abs(t[6])*o+Math.abs(t[10])*n]}function Mr(t){if(t._lb!==void 0)return t._lb;let e=1e9,i=1e9,r=1e9,s=-1e9,a=-1e9,o=-1e9;for(let n of t.primitives||[]){let l=n.positions;if(l)for(let h=0;h<l.length;h+=3)l[h]<e&&(e=l[h]),l[h+1]<i&&(i=l[h+1]),l[h+2]<r&&(r=l[h+2]),l[h]>s&&(s=l[h]),l[h+1]>a&&(a=l[h+1]),l[h+2]>o&&(o=l[h+2])}return t._lb=e<=s?[(e+s)*.5,(i+a)*.5,(r+o)*.5,(s-e)*.5,(a-i)*.5,(o-r)*.5]:null}function wr(t){let e=Ge.get(t);if(e)return e;let i=(n,l)=>{let h=t.createShader(n);return t.shaderSource(h,l),t.compileShader(h),h},r=t.createProgram();t.attachShader(r,i(35633,vr)),t.attachShader(r,i(35632,xr)),t.linkProgram(r);let s=t.createVertexArray(),a=t.createBuffer(),o=t.createBuffer();return t.bindVertexArray(s),t.bindBuffer(34962,a),t.bufferData(34962,80,35048),t.enableVertexAttribArray(0),t.vertexAttribPointer(0,3,5126,!1,20,0),t.enableVertexAttribArray(1),t.vertexAttribPointer(1,2,5126,!1,20,12),t.bindBuffer(34963,o),t.bufferData(34963,new Uint16Array([0,1,2,0,2,3]),35044),t.bindVertexArray(null),e={prog:r,vao:s,vbo:a,ibo:o,uMVP:t.getUniformLocation(r,"uMVP"),uIntensity:t.getUniformLocation(r,"uShadowIntensity"),uSoftness:t.getUniformLocation(r,"uShadowSoftness")},Ge.set(t,e),e}var Sr={name:"contact-shadow",onContextRestored(t){Ge.delete(t)},onAfterRender(t,e,i){let r=e.shadowIntensity;if(r<=0||!e.bounds)return;let s=wr(t),a=!e.xrSessionActive&&(e.backdropMeshes?.length??0)>0,o=[],n=[];for(let d of e.meshes||[]){if(!d||d.visible===!1||d.isPluginMesh||d.name==="__xr_reticle__"||d.name?.startsWith("__xr_slot_"))continue;let p=Mr(d);if(!p)continue;d.transform&&(p=Mt(d.transform,p)),e.modelRootMatrix&&(p=Mt(e.modelRootMatrix,p));let[A,b,x,u,m,v]=p,S=[A,x,u,v,b-m,b+m];/floor|table|pedestal|ground|base|plane/i.test(d.name||"")||m<.14&&Math.min(u,v)>.45?n.push(S):o.push(S)}let l=[],h=e.bounds.center||[0,0,0],c=Math.max(.05,Number(e.bounds.radius)||.5),f=e.bounds.min,g=f?[h[0],h[1],h[2],c,Math.max(.01,h[1]-f[1]),c]:[h[0],h[1],h[2],c,c,c];e.modelRootMatrix&&(g=Mt(e.modelRootMatrix,g));let w=e.xrSessionActive&&n.length===0&&String(e.container?.tagName||"").toLowerCase()==="xr-live"?(e.modelRootMatrix?e.modelRootMatrix[5]*-.25+e.modelRootMatrix[13]:-.25)+.002:g[1]-g[4]+.002;for(let[d,p,A,b,x]of o){let u=-1/0;for(let[v,S,_,D,,P]of n)x>=P-.08&&Math.abs(d-v)<=_&&Math.abs(p-S)<=D&&P+.002>u&&(u=P+.002);a&&(u=Math.max(u,d>=.04&&d<=.36&&p>=-.34&&p<=-.04&&x>=.01?.036:Math.hypot(d,p)<=.66&&x>=-.06?.003:-.477)),isFinite(u)||(u=w);let m=l.find(v=>Math.hypot(d-v[0],p-v[1])<.06&&Math.abs(u-v[5])<.05);m?(m[2]=Math.max(m[2],A*.78),m[3]=Math.max(m[3],b*.78),m[4]=Math.min(m[4],x)):l.push([d,p,A,b,x,u])}if(l.length===0){let d=Math.max(.1,g[3]*1.5)/1.45;l.push([g[0],g[2],d,d,w,w])}t.useProgram(s.prog),t.uniformMatrix4fv(s.uMVP,!1,i),t.enable(3042),(t.blendFuncSeparate||t.blendFunc).call(t,770,771,1,771),t.depthMask(!1),t.bindVertexArray(s.vao),t.bindBuffer(34962,s.vbo);for(let[d,p,A,b,x,u]of l){let m=Math.max(0,x-u),v=r/(1+m*2);if(v<.02)continue;let S=1+Math.min(.75,m*.85),_=Math.max(.045,A*1.45*S),D=Math.max(.045,b*1.45*S);jt.set([d-_,u,p-D,0,0,d+_,u,p-D,1,0,d+_,u,p+D,1,1,d-_,u,p+D,0,1]),t.bufferSubData(34962,0,jt),t.uniform1f(s.uIntensity,v),t.uniform1f(s.uSoftness,Math.min(1,e.shadowSoftness+Math.min(.45,m*.6))),t.drawElements(4,6,5123,0)}t.bindVertexArray(null),t.depthMask(!0),t.disable(3042)},onDestroy(t){let e=Ge.get(t);e&&(t.deleteVertexArray(e.vao),t.deleteBuffer(e.vbo),t.deleteBuffer(e.ibo),t.deleteProgram(e.prog),Ge.delete(t))}};function Ar(t,e,i){let r=[],s=new Map,a=[],o=[],n=[],l=new Map,h=u=>{let m=s.get(u);return m===void 0&&(m=r.length,r.push({op:u}),s.set(u,m)),m},c=u=>{let m=l.get(u);return m===void 0&&(m=n.length,n.push({id:u}),l.set(u,m)),m},f=(u,m={})=>a.push({declaration:h(u),...m})-1,g=(u,m,v)=>o.push({id:u,type:m,value:v})-1,w=u=>({node:u,socket:"value"}),d=i?.interactivity??i?.gltfExtensions?.KHR_interactivity;if(d&&typeof d=="object"){let u=Array.isArray(d.graphs)?d.graphs[d.graph??0]:d;if(u&&Array.isArray(u.nodes)){let m=Array.isArray(u.declarations)?u.declarations:[];for(let v of m)v?.op&&h(v.op);Array.isArray(u.variables)&&o.push(...u.variables);for(let v of u.events||[])v?.id&&c(v.id);for(let v of u.nodes){if(!v||typeof v!="object")continue;let S=v.op||(typeof v.declaration=="number"?m[v.declaration]?.op:"");a.push(S?{...v,declaration:h(S)}:{...v})}}}let p=(u,m,v="translation")=>v==="baseColorFactor"||v==="metallicFactor"||v==="roughnessFactor"?`/materials/${Math.max(0,m)}/pbrMetallicRoughness/${v}`:v==="emissiveFactor"||v==="alphaCutoff"?`/materials/${Math.max(0,m)}/${v}`:v==="visible"?`/nodes/${u}/extensions/KHR_node_visibility/visible`:`/nodes/${u}/${v}`,A=new Map;t.forEach((u,m)=>{typeof u?.name=="string"&&!A.has(u.name)&&A.set(u.name,m)});let b=(u,m)=>typeof u.target=="string"&&A.has(u.target)?A.get(u.target):typeof u.targetNode=="number"?u.targetNode:m,x=u=>{let m=t[u];return(typeof m?.mesh=="number"?e[m.mesh]?.primitives?.[0]?.material:0)??0};for(let u=0;u<t.length;u++){let m=t[u],v=m?.extras?.interactivity;if(!v||typeof v!="object")continue;let S=(typeof m.mesh=="number"?e[m.mesh]?.primitives?.[0]?.material:0)??0,_=P=>{let N=Array.isArray(P)?P:[P],E=[];for(let L=0;L<N.length;L++){let M=N[L];if(!M||typeof M!="object")continue;let O=M.action||"interpolate",H=typeof M.duration=="number"?M.duration:.35;if(O==="toggleTransform"){let R=M.property==="rotation"||M.property==="scale"?M.property:"translation",C=R==="rotation"?m.rotation||[0,0,0,1]:R==="scale"?m.scale||[1,1,1]:m.translation||[0,0,0],y=`/nodes/${u}/${R}`,T=g(`__toggle_${u}_${L}`,"bool",!1),z=f("variable/get",{configuration:{variable:T}}),G=f("math/not",{values:{a:w(z)}}),B=f("variable/set",{configuration:{variable:T},values:{value:w(G)}}),te=f("pointer/interpolate",{configuration:{pointer:y},values:{value:{value:Array.isArray(M.to)?M.to:C},duration:{value:H}}}),I=f("pointer/interpolate",{configuration:{pointer:y},values:{value:{value:Array.isArray(M.from)?M.from:C},duration:{value:H}}});a[B].flows={out:{node:f("flow/branch",{values:{condition:w(z)},flows:{true:{node:te},false:{node:I}}})}},E.push(B)}else if(O==="interpolate"){let R=M.to??M.value;if(R===void 0)continue;let C={value:{value:R},duration:{value:H}};M.from!==void 0&&(C.from={value:M.from}),E.push(f("pointer/interpolate",{configuration:{pointer:typeof M.pointer=="string"?M.pointer:p(b(M,u),x(b(M,u)),M.property)},values:C}))}else if(O==="setProperty"){if(M.value===void 0)continue;E.push(f("pointer/set",{configuration:{pointer:typeof M.pointer=="string"?M.pointer:p(b(M,u),x(b(M,u)),M.property)},values:{value:{value:M.value}}}))}else if(O==="toggleVisibility"){let R=b(M,u),C=g(`__vis_${R}_${L}`,"bool",!0),y=f("variable/get",{configuration:{variable:C}}),T=f("math/not",{values:{a:w(y)}}),z=f("variable/set",{configuration:{variable:C},values:{value:w(T)}});a[z].flows={out:{node:f("pointer/set",{configuration:{pointer:`/nodes/${R}/extensions/KHR_node_visibility/visible`},values:{value:w(y)}})}},E.push(z)}else if(O==="cycleMaterialColor"&&Array.isArray(M.colors)&&M.colors.length>0){let R=typeof M.duration=="number"?M.duration:.25,C=`/materials/${Math.max(0,S)}/pbrMetallicRoughness/baseColorFactor`,y=g(`__color_idx_${u}_${L}`,"int",0),T=f("variable/get",{configuration:{variable:y}}),z=f("math/add",{values:{a:w(T),b:{value:1}}}),G=f("math/rem",{values:{a:w(z),b:{value:M.colors.length}}}),B=f("variable/set",{configuration:{variable:y},values:{value:w(G)}}),te={};for(let I=0;I<M.colors.length;I++){let W=M.colors[I],Z=Array.isArray(W)&&W.length>=3?[W[0],W[1],W[2],W[3]??1]:[1,1,1,1];te[String(I)]={node:R>0?f("pointer/interpolate",{configuration:{pointer:C},values:{value:{value:Z},duration:{value:R}}}):f("pointer/set",{configuration:{pointer:C},values:{value:{value:Z}}})}}a[B].flows={out:{node:f("flow/switch",{values:{selection:w(T)},flows:te})}},E.push(B)}else if(O==="playAnimation")E.push(f("animation/start",{configuration:{animation:M.animation??M.clip??0}}));else if(O==="stopAnimation")E.push(f("animation/stop"));else if(O==="sendEvent"){let R={};for(let[C,y]of Object.entries(M.values||{}))R[C]={value:y};E.push(f("event/send",{configuration:{event:c(String(M.event??M.id??"custom"))},values:R}))}}if(!E.length)return null;if(E.length===1)return E[0];let F={};return E.forEach((L,M)=>{F[String(M)]={node:L}}),f("flow/sequence",{flows:F})},D=(P,N,E)=>{let F=_(N);F!==null&&f(P,{...E?{configuration:E}:{},flows:{out:{node:F}}})};if(v.onSelect&&D("pointer/onSelect",v.onSelect,{nodeIndex:u}),v.onHoverIn&&D("pointer/onHoverIn",v.onHoverIn,{nodeIndex:u}),v.onHoverOut&&D("pointer/onHoverOut",v.onHoverOut,{nodeIndex:u}),v.onStart&&D("event/onStart",v.onStart),v.onReceive&&typeof v.onReceive=="object")for(let[P,N]of Object.entries(v.onReceive))D("event/receive",N,{event:c(P)})}return a.length?{graphs:[{declarations:r,nodes:a,variables:o,events:n}],graph:0}:null}var Gt='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).',Wt="Security Error: client-side scripts require allow-client-scripts opt-in.";function de(){let t=new Float32Array(16);return t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function wt(t,e,i,r,s){let a=1/Math.tan(e/2);t.fill(0),t[0]=a/i,t[5]=a,t[11]=-1;let o=1/(r-s);return t[10]=(s+r)*o,t[14]=2*s*r*o,t}function tt(t,e,i,r){let[s,a,o]=e,[n,l,h]=r,[c,f,g]=i,w=s-c,d=a-f,p=o-g,A=Math.hypot(w,d,p);A<=1e-5?(w=0,d=0,p=1):(w/=A,d/=A,p/=A);let b=l*p-h*d,x=h*w-n*p,u=n*d-l*w;A=Math.hypot(b,x,u),A<=1e-5?(b=0,x=0,u=0):(b/=A,x/=A,u/=A);let m=d*u-p*x,v=p*b-w*u,S=w*x-d*b;return A=Math.hypot(m,v,S),A<=1e-5?(m=0,v=0,S=0):(m/=A,v/=A,S/=A),t[0]=b,t[1]=m,t[2]=w,t[3]=0,t[4]=x,t[5]=v,t[6]=d,t[7]=0,t[8]=u,t[9]=S,t[10]=p,t[11]=0,t[12]=-(b*s+x*a+u*o),t[13]=-(m*s+v*a+S*o),t[14]=-(w*s+d*a+p*o),t[15]=1,t}function fe(t,e,i){let r=e[0],s=e[1],a=e[2],o=e[3],n=e[4],l=e[5],h=e[6],c=e[7],f=e[8],g=e[9],w=e[10],d=e[11],p=e[12],A=e[13],b=e[14],x=e[15],u=i[0],m=i[1],v=i[2],S=i[3];return t[0]=u*r+m*n+v*f+S*p,t[1]=u*s+m*l+v*g+S*A,t[2]=u*a+m*h+v*w+S*b,t[3]=u*o+m*c+v*d+S*x,u=i[4],m=i[5],v=i[6],S=i[7],t[4]=u*r+m*n+v*f+S*p,t[5]=u*s+m*l+v*g+S*A,t[6]=u*a+m*h+v*w+S*b,t[7]=u*o+m*c+v*d+S*x,u=i[8],m=i[9],v=i[10],S=i[11],t[8]=u*r+m*n+v*f+S*p,t[9]=u*s+m*l+v*g+S*A,t[10]=u*a+m*h+v*w+S*b,t[11]=u*o+m*c+v*d+S*x,u=i[12],m=i[13],v=i[14],S=i[15],t[12]=u*r+m*n+v*f+S*p,t[13]=u*s+m*l+v*g+S*A,t[14]=u*a+m*h+v*w+S*b,t[15]=u*o+m*c+v*d+S*x,t}function St(t,e,i,r){let s=e[0],a=e[1],o=e[2],n=e[3],l=s+s,h=a+a,c=o+o,f=s*l,g=s*h,w=s*c,d=a*h,p=a*c,A=o*c,b=n*l,x=n*h,u=n*c,m=r[0],v=r[1],S=r[2];return t[0]=(1-(d+A))*m,t[1]=(g+u)*m,t[2]=(w-x)*m,t[3]=0,t[4]=(g-u)*v,t[5]=(1-(f+A))*v,t[6]=(p+b)*v,t[7]=0,t[8]=(w+x)*S,t[9]=(p-b)*S,t[10]=(1-(f+d))*S,t[11]=0,t[12]=i[0],t[13]=i[1],t[14]=i[2],t[15]=1,t}function Ne(t,e,i=0){let r=e[0],s=e[1],a=e[2],o=e[4],n=e[5],l=e[6],h=e[8],c=e[9],f=e[10],g=f*n-l*c,w=-f*o+l*h,d=c*o-n*h,p=r*g+s*w+a*d;return!p||i>0&&(!Number.isFinite(p)||Math.abs(p)<=i)||(p=1/p,t[0]=g*p,t[1]=w*p,t[2]=d*p,t[3]=(-f*s+a*c)*p,t[4]=(f*r-a*h)*p,t[5]=(-c*r+s*h)*p,t[6]=(l*s-a*n)*p,t[7]=(-l*r+a*o)*p,t[8]=(n*r-s*o)*p),t}function Rr(t,e){let i=e[0],r=e[1],s=e[2],a=e[3],o=e[4],n=e[5],l=e[6],h=e[7],c=e[8],f=e[9],g=e[10],w=e[11],d=e[12],p=e[13],A=e[14],b=e[15],x=i*n-r*o,u=i*l-s*o,m=i*h-a*o,v=r*l-s*n,S=r*h-a*n,_=s*h-a*l,D=c*p-f*d,P=c*A-g*d,N=c*b-w*d,E=f*A-g*p,F=f*b-w*p,L=g*b-w*A,M=x*L-u*F+m*E+v*N-S*P+_*D;return M?(M=1/M,t[0]=(n*L-l*F+h*E)*M,t[1]=(s*F-r*L-a*E)*M,t[2]=(p*_-A*S+b*v)*M,t[3]=(g*S-f*_-w*v)*M,t[4]=(l*N-o*L-h*P)*M,t[5]=(i*L-s*N+a*P)*M,t[6]=(A*m-d*_-b*u)*M,t[7]=(c*_-g*m+w*u)*M,t[8]=(o*F-n*N+h*D)*M,t[9]=(r*N-i*F-a*D)*M,t[10]=(d*S-p*m+b*x)*M,t[11]=(f*m-c*S-w*x)*M,t[12]=(n*P-o*E-l*D)*M,t[13]=(i*E-r*P+s*D)*M,t[14]=(p*u-d*v-A*x)*M,t[15]=(c*v-f*u+g*x)*M,t):null}function Xt(t,e,i,r,s){let a=s[0]*e+s[4]*i+s[8]*r+s[12],o=s[1]*e+s[5]*i+s[9]*r+s[13],n=s[2]*e+s[6]*i+s[10]*r+s[14],l=s[3]*e+s[7]*i+s[11]*r+s[15],h=l!==0?1/l:1;t[0]=a*h,t[1]=o*h,t[2]=n*h}function Tr(t,e,i,r,s,a,o,n,l,h,c,f,g,w,d,p,A=0){let b=h-o,x=c-n,u=f-l,m=g-o,v=w-n,S=d-l,_=s*S-a*v,D=a*m-r*S,P=r*v-s*m,N=b*_+x*D+u*P;if(N>-1e-7&&N<1e-7)return!1;let E=1/N,F=t-o,L=e-n,M=i-l,O=E*(F*_+L*D+M*P);if(O<-A||O>1+A)return!1;let H=L*u-M*x,R=M*b-F*u,C=F*x-L*b,y=E*(r*H+s*R+a*C);if(y<-A||O+y>1+A)return!1;let T=E*(m*H+v*R+S*C);if(T>1e-4&&T<p.distance){p.distance=T,p.point=[t+r*T,e+s*T,i+a*T];let z=x*S-u*v,G=u*m-b*S,B=b*v-x*m,te=Math.hypot(z,G,B)||1;return p.normal=[z/te,G/te,B/te],!0}return!1}function Cr(t,e){let i=Array.isArray(t?.nodes)?t.nodes.length:0,r=[];for(let c=0;c<i;c++)r.push(de());if(i===0)return r;let s=new Set;for(let c of t.nodes)if(Array.isArray(c.children))for(let f of c.children)s.add(f);let a=new Set,o=128,n=(c,f,g=0)=>{if(g>o||c<0||c>=i||a.has(c))return;a.add(c);let w=t.nodes[c];if(!w)return;let d=de();if(e&&e[c])d.set(e[c]);else if(w.matrix&&w.matrix.length===16)d.set(w.matrix);else{let A=w.translation||[0,0,0],b=w.rotation||[0,0,0,1],x=w.scale||[1,1,1];St(d,b,A,x)}let p=r[c];if(f?fe(p,f,d):p.set(d),Array.isArray(w.children))for(let A of w.children)typeof A=="number"&&n(A,p,g+1)},l=[],h=t.scenes&&t.scenes[t.scene!==void 0?t.scene:0];if(h&&Array.isArray(h.nodes))l.push(...h.nodes);else for(let c=0;c<i;c++)s.has(c)||l.push(c);for(let c of l)n(c,null);for(let c=0;c<i;c++)!s.has(c)&&!l.includes(c)&&n(c,null);return r}var Pr={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function qt(t,e,i,r){if(!i||i.bufferView===void 0)return null;let s=t.bufferViews?.[i.bufferView];if(!s)return null;let a=Number(i.count??0);if(!Number.isInteger(a)||a<=0)return null;let o=i.componentType??5126,n=Pr[o];if(!n)throw new RangeError(`glTF accessor has unsupported componentType ${o}`);let l=n*r,h=s.byteStride&&s.byteStride>0?s.byteStride:l,c=(s.byteOffset||0)+(i.byteOffset||0);if(!Number.isInteger(c)||c<0||h<l||c+(a-1)*h+l>e.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${e.byteLength} bytes)`);if(o===5126&&h===l&&c%4===0)return new Float32Array(e,c,a*r);let f=new DataView(e),g=i.normalized===!0,w=new Float32Array(a*r);for(let d=0;d<a;d++){let p=c+d*h;for(let A=0;A<r;A++){let b=p+A*n,x;switch(o){case 5126:x=f.getFloat32(b,!0);break;case 5120:x=f.getInt8(b),g&&(x=Math.max(x/127,-1));break;case 5121:x=f.getUint8(b),g&&(x/=255);break;case 5122:x=f.getInt16(b,!0),g&&(x=Math.max(x/32767,-1));break;case 5123:x=f.getUint16(b,!0),g&&(x/=65535);break;default:x=f.getUint32(b,!0),g&&(x/=4294967295)}w[d*r+A]=x}}return w}function Er(t,e){let i=Number(e.offset?.[0]??0)||0,r=Number(e.offset?.[1]??0)||0,s=Number(e.scale?.[0]??1),a=Number(e.scale?.[1]??1),o=Number(e.rotation??0)||0,n=Math.cos(o),l=Math.sin(o),h=(Number.isFinite(s)?s:1)*n,c=(Number.isFinite(s)?s:1)*l,f=-(Number.isFinite(a)?a:1)*l,g=(Number.isFinite(a)?a:1)*n;for(let w=0;w+1<t.length;w+=2){let d=t[w],p=t[w+1];t[w]=h*d+c*p+i,t[w+1]=f*d+g*p+r}}function At(t,e,i,r=!0){let s=[],a=null;try{for(let[o,n]of[[35633,e],[35632,i]]){let l=t.createShader(o);if(!l){if(r)throw new Error("Shader allocation failed");return null}if(s.push(l),t.shaderSource(l,n),t.compileShader(l),t.getShaderParameter&&!t.getShaderParameter(l,35713)){if(r)throw new Error(`Shader compile error: ${t.getShaderInfoLog(l)}`);return null}}if(a=t.createProgram(),!a){if(r)throw new Error("Program allocation failed");return null}for(let o of s)t.attachShader(a,o);if(t.linkProgram(a),t.getProgramParameter&&!t.getProgramParameter(a,35714)){let o=r?t.getProgramInfoLog(a):null;if(t.deleteProgram?.(a),a=null,r)throw new Error(`Program link error: ${o}`);return null}return a}finally{for(let o of s)a&&t.detachShader?.(a,o),t.deleteShader?.(o)}}var Kt=["neutral","reinhard","none","aces","agx"];function Ue(t){let e=String(t??"").trim().toLowerCase();return Kt.includes(e)?e:"neutral"}function _r(t){return Kt.indexOf(Ue(t))}function Nr(t){return new TextDecoder().decode(t)}var Yt=he().decoders;function Lr(t,e){Yt.set(t.toLowerCase(),e)}function Be(t){return Yt.get(t.toLowerCase())}function Zt(t){let e=ArrayBuffer.isView(t)?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t,i=new DataView(e);if(e.byteLength<12)throw new Error(`Invalid GLB buffer size: ${e.byteLength} bytes`);let r=i.getUint32(0,!0);if(r!==1179937895){let g=i.getUint8(0);throw g===123||g===32||g===10||g===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 s=i.getUint32(4,!0);if(s!==2)throw new Error(`Unsupported GLB version: ${s}`);let a=i.getUint32(8,!0),o=12,n=null,l=null;for(;o+8<=a&&o+8<=e.byteLength;){let g=i.getUint32(o,!0),w=i.getUint32(o+4,!0),d=o+8;if(d+g>e.byteLength)throw new Error(`Truncated GLB chunk: required ${d+g} bytes, buffer has ${e.byteLength}`);if(w===1313821514){let p=new Uint8Array(e,d,g),A=Nr(p);n=JSON.parse(A,(b,x)=>b==="__proto__"||b==="constructor"||b==="prototype"?void 0:x)}else w===5130562&&(l=e.slice(d,d+g));o=d+g}if(!n)throw new Error("Missing JSON chunk in GLB");let h=n.extensionsRequired||[];if(h.includes("KHR_draco_mesh_compression")&&!Be("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");for(let g of["EXT_meshopt_compression","KHR_meshopt_compression"])if(h.includes(g)&&!Be("meshopt"))throw new Error(`Model requires ${g}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(h.includes("KHR_texture_basisu")&&!Be("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let c=l||new ArrayBuffer(0),f={gltf:n,bin:c,animations:[]};for(let g of me)g.onParseGLB?.(f);return f}function Dr(t){return typeof t=="object"&&t!==null&&"gltf"in t&&typeof t.gltf=="object"&&t.gltf!==null&&"bin"in t&&(t.bin instanceof ArrayBuffer||ArrayBuffer.isView(t.bin))}function We(t){if(Dr(t))return t;if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))return Zt(t);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var Qt=`#version 300 es
20
19
  layout(location=0) in vec3 aPos;
21
20
  layout(location=3) in vec3 aOff;
22
21
  layout(location=1) in vec3 aNormal;
@@ -51,7 +50,7 @@ vec2 scaleUV=uUvTransform.zw;
51
50
  if(scaleUV.x==0.0&&scaleUV.y==0.0)scaleUV=vec2(1.0);
52
51
  vUV=aUV*scaleUV+uUvTransform.xy;
53
52
  gl_Position=uMVP*vec4(aPosition,1.0);
54
- }`,Cr=`#version 300 es
53
+ }`,kr=`#version 300 es
55
54
  precision highp float;
56
55
  in vec3 vNormal,vWorldPos;
57
56
  in vec2 vUV;
@@ -68,7 +67,8 @@ uniform float uNormalScale,uOcclusionStrength;
68
67
  uniform vec2 uViewportSize;
69
68
  uniform vec4 uSectionPlane;
70
69
  uniform int uToneMapping,uNumDirLights,uNumPointLights,uSectionEnabled;
71
- uniform vec3 uDirLightDir[2],uDirLightColor[2],uPointLightPos[2],uPointLightColor[2];
70
+ uniform vec3 uDirLightDir[2],uDirLightColor[2],uPointLightPos[2],uPointLightColor[2],uPointLightSpotDir[2];
71
+ uniform vec2 uPointLightSpotCone[2];
72
72
  out vec4 fragColor;
73
73
 
74
74
  vec2 envBRDF(float r,float n){
@@ -159,6 +159,11 @@ if(mode==4)return agxToneMapping(color);
159
159
  return color;
160
160
  }
161
161
 
162
+ vec3 evalLight(vec3 L,vec3 V,vec3 N,vec3 base,float specExp,float specWeight){
163
+ float NoH=max(dot(N,normalize(L+V)),0.0);
164
+ return base*max(dot(N,L),0.0)*0.75+vec3(pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35);
165
+ }
166
+
162
167
  void main(){
163
168
  if(uSectionEnabled==1&&dot(vWorldPos,uSectionPlane.xyz)>uSectionPlane.w)discard;
164
169
  vec4 base=uBaseColor;
@@ -196,24 +201,16 @@ float specWeight=mix(0.22*gloss,1.0,metallic);
196
201
  vec3 directLight=vec3(0.0);
197
202
  for(int i=0;i<2;i++){
198
203
  if(i>=uNumDirLights)break;
199
- vec3 L=normalize(uDirLightDir[i]);
200
- float NdotL=max(dot(N,L),0.0);
201
- vec3 H=normalize(L+V);
202
- float NoH=max(dot(N,H),0.0);
203
- float spec=pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35;
204
- directLight+=(base.rgb*NdotL*0.75+vec3(spec))*uDirLightColor[i];
204
+ directLight+=evalLight(normalize(uDirLightDir[i]),V,N,base.rgb,specExp,specWeight)*uDirLightColor[i];
205
205
  }
206
206
  for(int i=0;i<2;i++){
207
207
  if(i>=uNumPointLights)break;
208
208
  vec3 toLight=uPointLightPos[i]-vWorldPos;
209
209
  float dist=length(toLight);
210
210
  vec3 L=toLight/max(dist,0.0001);
211
- float atten=1.0/(1.0+0.09*dist+0.032*dist*dist);
212
- float NdotL=max(dot(N,L),0.0);
213
- vec3 H=normalize(L+V);
214
- float NoH=max(dot(N,H),0.0);
215
- float spec=pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35;
216
- directLight+=(base.rgb*NdotL*0.75+vec3(spec))*uPointLightColor[i]*atten;
211
+ float spotAtt=clamp((dot(-L,uPointLightSpotDir[i])-uPointLightSpotCone[i].y)/max(uPointLightSpotCone[i].x-uPointLightSpotCone[i].y,0.0001),0.0,1.0);
212
+ spotAtt*=spotAtt;
213
+ directLight+=evalLight(L,V,N,base.rgb,specExp,specWeight)*uPointLightColor[i]*spotAtt/(1.0+0.09*dist+0.032*dist*dist);
217
214
  }
218
215
 
219
216
  vec3 R=reflect(-V,N);
@@ -244,86 +241,140 @@ color=applyToneMapping(color,uToneMapping);
244
241
  float outAlpha=base.a;
245
242
  /*XRD_O*/
246
243
  fragColor=vec4(color,outAlpha);
247
- }`;function Un(n,e,t=1){e=Le(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,S=I*I;return 15.5*S*I-40.14*S*v+31.96*S-6.868*I*v+.4298*I+.1191*v-.00232},p=M(T),A=M(P),C=M(f),w=1.196879*p-.09802088*A-.09902974*C,R=-.05289685*p+1.15190313*A-.09896118*C,L=-.05297164*p-.09804345*A+1.15107367*C;return[c(Math.pow(Math.max(w,0),2.2)),c(Math.pow(Math.max(R,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 b=1-a,y=1-b*b/(h+b-a),d=y/h;i*=d,s*=d,o*=d;let g=1-1/(u*(h-y)+1);return[c(i+(y-i)*g),c(s+(y-s)*g),c(o+(y-o)*g)]}var Lr=`#version 300 es
244
+ }`;function Fr(t,e,i=1){e=Ue(e);let r=Number.isFinite(i)?Math.max(0,i):1,[s,a,o]=[0,1,2].map(p=>Math.max(0,(Number(t[p])||0)*r)),n=p=>Math.max(0,Math.min(1,p)),l=p=>[p(s),p(a),p(o)];if(e==="none")return l(n);if(e==="reinhard")return l(p=>p/(p+1));if(e==="aces")return l(p=>{let A=p*.6;return n(A*(2.51*A+.03)/(A*(2.43*A+.59)+.14))});if(e==="agx"){let[p,A,b]=[.84247906*s+.0784336*a+.07922375*o,.04232824*s+.87846864*a+.07916613*o,.04237565*s+.0784336*a+.87914297*o].map(x=>{let u=n((Math.log2(Math.max(x,1e-6))+12.47393)/16.5),m=u*u,v=m*m;return 15.5*v*m-40.14*v*u+31.96*v-6.868*m*u+.4298*m+.1191*u-.00232});return[1.196879*p-.09802088*A-.09902974*b,-.05289685*p+1.15190313*A-.09896118*b,-.05297164*p-.09804345*A+1.15107367*b].map(x=>n(Math.pow(Math.max(x,0),2.2)))}let h=Math.min(s,a,o),c=h<.08?h-6.25*h*h:.04;[s,a,o]=l(p=>p-c);let f=Math.max(s,a,o);if(f<.76)return l(n);let g=1-.0576/(f-.52),w=g/f,d=1-1/(.15*(f-g)+1);return l(p=>n(p*w+(g-p*w)*d))}var Ir=`#version 300 es
248
245
  layout(location=0) in vec3 aPosition;
249
246
  uniform mat4 uMVP;
250
- void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,Dr=`#version 300 es
247
+ void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,Or=`#version 300 es
251
248
  precision highp float;
252
249
  uniform vec4 uColorId;
253
250
  out vec4 fragColor;
254
- void main(){fragColor=uColorId;}`;function Ft(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=J().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 Nt(n,e,t,r,i,s,o,c){if(r===void 0||!e.accessors?.[r])return null;let a=Pt(e,t,e.accessors[r],s);if(!a)return null;c&&(a=a.slice(),Ln(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 kt(n){let e=Number(n);return Number.isFinite(e)?Math.max(0,e):1}function Bn(n,e,t){let r=On(),i=Fn,s=r.fs,o=!1;for(let a of ae)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?Ft(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 Nr(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 rt(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 kr(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 kr(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=Fe("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 b=h.length>0?h:(s.meshes||[]).map((v,I)=>({node:v,nodeIdx:-1,meshIdx:I})),y=[];if(Array.isArray(e.lights)&&e.lights.length>0)y.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 S=I.type==="directional"?"directional":I.type==="point"?"point":"ambient";y.push({type:S,color:I.color||[1,1,1],intensity:I.intensity!==void 0?I.intensity:1})}}if(y.length===0&&(y.push({type:"ambient",color:[1,1,1],intensity:.35}),y.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),b.length>t.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${t.maxMeshes}). Found: ${b.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],S=s.images[I.source];if(S){let _=n.createTexture();if(n.bindTexture(3553,_),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 k=s.bufferViews[S.bufferView],N=c.slice(k.byteOffset||0,(k.byteOffset||0)+k.byteLength),V=new Blob([N],{type:S.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(V).then(U=>{n.bindTexture(3553,_),n.texImage2D(3553,0,6408,6408,5121,U),n.generateMipmap(3553),r?.()}).catch(()=>{})}else if(S.uri){let k=Ir(S.uri);if(k){let N=new Image;N.crossOrigin="anonymous",N.referrerPolicy="no-referrer",N.onload=()=>{n.bindTexture(3553,_),n.texImage2D(3553,0,6408,6408,5121,N),n.generateMipmap(3553),r?.()},N.src=k}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",S.uri)}d.push(_)}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<b.length;v++){let I=b[v],S=s.meshes[I.meshIdx],_=I.nodeIdx>=0?m[I.nodeIdx]:se(),k=new Float32Array(9);ye(k,_);let N={name:I.node.name||S.name||`Mesh_${I.meshIdx}`,nodeIndex:I.nodeIdx,transform:_,normalMatrix:k,primitives:[],extras:I.node.extras||S.extras};i.mesh=N;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,re=te=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${te})`),null);if(Y!==5120&&Y!==5121&&Y!==5122&&Y!==5123&&Y!==5126)return re(`componentType ${Y}`);if(!(Number(q.count)>=O))return re(`count ${q.count} < ${O}`);let $=null;try{$=Pt(s,c,{...q,count:O},Z)}catch{return re("out of bounds")}return!$||!$.every(Number.isFinite)?re("non-finite value"):$},E=X(B,3),F=X(D,4),G=X(H,3),W=z?.type==="VEC4"?4:3,j=X(z,W),ne=new Float32Array(O*16),ce=se();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=F?[F[q*4],F[q*4+1],F[q*4+2],F[q*4+3]]:[0,0,0,1],re=G?[G[q*3],G[q*3+1],G[q*3+2]]:[1,1,1];Ce(ce,Y,Z,re),ne.set(ce,q*16)}if(N.instanceMatrices=ne,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];N.instanceColors=q}}}for(let U of S.primitives||[]){if(U.extensions?.KHR_draco_mesh_compression){let $=Fe("draco");$&&$.decodePrimitive(s,U,c)}let B=[],D=n.createVertexArray();i.vao=D,i.buffers=B,n.bindVertexArray(D);let H=Pr(n,N,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 $=te=>{for(let ee=0;ee<3;ee++){let Q=te[12+ee],ie=te[12+ee];for(let be=0;be<3;be++){let he=te[be*4+ee]*z.min[be],de=te[be*4+ee]*z.max[be];Q+=he<de?he:de,ie+=he>de?he:de}Q<g[ee]&&(g[ee]=Q),ie>T[ee]&&(T[ee]=ie)}};if(N.instanceMatrices&&N.instanceMatrices.length>=16){let te=N.instanceMatrices.length>>4,ee=se();for(let Q=0;Q<te;Q++){let ie=N.instanceMatrices.subarray(Q*16,Q*16+16);oe(ee,_,ie),$(ee)}}else $(_)}let X=Nt(n,s,c,U.attributes.POSITION,0,3,B);Nt(n,s,c,U.attributes.NORMAL,1,3,B),Nt(n,s,c,U.attributes.TEXCOORD_0,2,2,B,Nr(s,U));let E=0,F=5123,G=null;if(U.indices!==void 0){let $=s.accessors[U.indices],ee=(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,F=$.componentType===5125?5125||5125:5123||5123;let Q=n.createBuffer();B.push(Q),n.bindBuffer(34963,Q),$.componentType===5125?(G=new Uint32Array(c,ee,$.count),n.bufferData(34963,G,35044)):$.componentType===5121?(G=Uint16Array.from(new Uint8Array(c,ee,$.count)),n.bufferData(34963,G,35044)):(G=ee%2===0?new Uint16Array(c,ee,$.count):new Uint16Array(c.slice(ee,ee+$.count*2)),n.bufferData(34963,G,35044))}else E=z.count;let W={};for(let $ of ae)if($.onBuildPrimitiveVAO){let te=$.onBuildPrimitiveVAO(n,D,U,s,c);te&&(W[$.name]=te)}n.bindVertexArray(null);let j=s.materials&&U.material!==void 0?s.materials[U.material]:null,{program:ne,uniforms:ce}=Bn(n,U,j),q=Hn(j,d),Z=!!(j?.extensions?.KHR_materials_transmission||W.materials?.isTransmissive),Y=U.extensions?.KHR_materials_variants?.mappings,re=Array.isArray(Y)?Y.filter($=>$&&typeof $.material=="number"&&Array.isArray($.variants)).map($=>({material:$.material|0,variants:$.variants.map(te=>Number(te)|0)})):void 0;N.primitives.push({vao:D,instanced:H,indexCount:E,indexType:F,...q,positions:X,indices:G,buffers:B,materialIndex:U.material,defaultMaterialIndex:U.material,variantMappings:re,primitiveDef:U,programCache:new Map([[U.material??-1,{program:ne,uniforms:ce}]]),pluginData:W,customProgram:ne,customUniforms:ce,isTransmissive:Z})}a.push(N)}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],A=T[1]-g[1],C=T[2]-g[2],w=Math.max(Math.hypot(p,A,C)/2,.5),R=[g[0],g[1],g[2]],L=[T[0],T[1],T[2]],x=e.animations;if(!x){for(let v of ae)if(v.onParseGLB?.(e),e.animations){x=e.animations;break}}return x||(x=[]),{meshes:a,bounds:{center:M,radius:w,min:R,max:L},lights:y,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 me=class{constructor(e,t,r){this.supportsInstanceOffsets=!0;this.meshes=[];this.backdropMeshes=[];this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]};this.lights=[];this.modelRootMatrix=se();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=se();this.viewMatrix=se();this.activeViewMatrix=null;this.modelMatrix=se();this.mvpMatrix=se();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:se(),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=kt(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=Le(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 Fe(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,Fn,t.fs),this.pickProg=nt(e,Lr,Dr),this.uRender=Ft(e,this.renderProg,t.uniforms),this.uPick=Ft(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of ae)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 ae)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=kt(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(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(Re(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=Re(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=kt(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=Le(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of ae)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of ae)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 ae)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=se();oe(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],b=r[2]*i+r[6]*s+r[10]*o+r[14],y=r[3]*i+r[7]*s+r[11]*o+r[15];if(y<=1e-4)return{x:0,y:0,z:1,visible:!1};let d=m/y,g=h/y,T=b/y,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,A=(-g*.5+.5)*M,C=d>=-1.1&&d<=1.1&&g>=-1.1&&g<=1.1&&T>=-1&&T<=1;if(C&&t){let[w,R,L]=$e(this),x=[i-w,s-R,o-L];c*x[0]+a*x[1]+u*x[2]>.05&&(C=!1)}return{x:p,y:A,z:T,visible:C}}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=se();oe(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 C=0;C<this.meshes.length;C++){let w=this.meshes[C];if(w.visible===!1||w.isPluginMesh)continue;let R=C+1,L=(R&255)/255,x=(R>>8&255)/255,v=(R>>16&255)/255;i.uniform4f(this.uPick.uColorId,L,x,v,1),oe(this.modelMatrix,this.modelRootMatrix,w.transform);let I=w.instanceMatrices;if(I&&I.length>=16){let S=I.length>>4,_=se();for(let k of w.primitives){i.bindVertexArray(k.vao);for(let N=0;N<S;N++)oe(_,this.modelMatrix,I.subarray(N*16,N*16+16)),oe(this.mvpMatrix,c,_),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),rt(i,k)}}else{oe(this.mvpMatrix,c,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let S of w.primitives)i.bindVertexArray(S.vao),rt(i,S)}}let p=new Uint8Array(4);i.readPixels(u,l,1,1,6408,5121,p),i.bindFramebuffer(36160,null);let A=p[0]+(p[1]<<8)+(p[2]<<16);A>0&&A<=this.meshes.length&&(a=[this.meshes[A-1]])}a.length===0&&(a=this.meshes.filter(p=>p.visible!==!1));let m=null,h=1/0,b=[0,0,0],y=[0,1,0],[d,g,T]=$e(this),P=se();for(let p of a){oe(P,this.modelRootMatrix,p.transform);let A=p.instanceMatrices,C=A&&A.length>=16?A.length>>4:1;for(let w=0;w<C;w++){A&&A.length>=16?oe(this.modelMatrix,P,A.subarray(w*16,w*16+16)):this.modelMatrix.set(P),oe(this.mvpMatrix,c,this.modelMatrix);let R=se();if(!_n(R,this.mvpMatrix))continue;let L=(u+.5)/s*2-1,x=(l+.5)/o*2-1,v=[0,0,0],I=[0,0,0];It(v,L,x,-1,R),It(I,L,x,1,R);let S=I[0]-v[0],_=I[1]-v[1],k=I[2]-v[2],N=Math.hypot(S,_,k)||1,V=S/N,U=_/N,B=k/N,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,F=Math.floor(E?E.length/3:X.length/9);for(let G=0;G<F;G++){let W=E?E[G*3]:G*3,j=E?E[G*3+1]:G*3+1,ne=E?E[G*3+2]:G*3+2;Cn(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[ne*3],X[ne*3+1],X[ne*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,F=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=F-d,ne=G-g,ce=W-T,q=Math.hypot(j,ne,ce);if(q<h){ye(this.normalMatrix,this.modelMatrix);let Z=this.normalMatrix,Y=D.normal[0],re=D.normal[1],$=D.normal[2],te=Z[0]*Y+Z[3]*re+Z[6]*$,ee=Z[1]*Y+Z[4]*re+Z[7]*$,Q=Z[2]*Y+Z[5]*re+Z[8]*$,ie=Math.hypot(te,ee,Q)||1;te/=ie,ee/=ie,Q/=ie,te*j+ee*ne+Q*ce>0&&(te=-te,ee=-ee,Q=-Q),m=p,h=Math.round(q*1e3)/1e3,b=[Math.round(F*1e3)/1e3,Math.round(G*1e3)/1e3,Math.round(W*1e3)/1e3],y=[Math.round(te*1e3)/1e3,Math.round(ee*1e3)/1e3,Math.round(Q*1e3)/1e3]}}}}if(!m)return null;let M={meshIndex:this.meshes.indexOf(m),meshName:m.name,nodeIndex:m.nodeIndex,distance:h,hitPoint:b,normal:y,screenX:e,screenY:t};if(r){for(let p of ae)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;ke(this.viewMatrix,$e(this),r,[0,1,0]),oe(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 ae)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 ae)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 ae)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 ae)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)),A=Math.max(1,f-p),C=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),w=this.customTarget||this.bounds.center,[R,L,x]=$e(this),v=Math.cos(this.currTheta),I=-Math.sin(this.currTheta),S=.032,_=se(),k=se(),N=[R-v*S,L,x-I*S],V=[w[0]-v*S*.25,w[1],w[2]-I*S*.25];et(_,this.fov,p/M,.1,C),ke(k,N,V,[0,1,0]);let U=se(),B=se(),D=[R+v*S,L,x+I*S],H=[w[0]+v*S*.25,w[1],w[2]+I*S*.25];et(U,this.fov,A/M,.1,C),ke(B,D,H,[0,1,0]),this.render({viewMatrix:k,projMatrix:_,eyePos:N,viewport:[0,0,p,M],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:B,projMatrix:U,eyePos:D,viewport:[p,0,A,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=se(),a=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=a,oe(c,e?.projMatrix??this.projMatrix,a);let u=J().xrDepthShader,l=Ar(this.toneMapping),[m,h,b]=e?e.eyePos:$e(this);for(let f of ae)f.onBeforeDrawScene?.(this,t,c,[m,h,b],l);let y=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&y===0)return;let d=e?.eye||"none",g=!1,T=y>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 A=this.selectedMeshName!==""&&p.name===this.selectedMeshName;M<y||p.worldSpace===!0||p.name==="__xr_reticle__"?this.modelMatrix.set(p.transform):oe(this.modelMatrix,this.modelRootMatrix,p.transform),oe(this.mvpMatrix,c,this.modelMatrix),ye(p.normalMatrix,this.modelMatrix);let C=p.extras?.xr?.stereo||p.userData?.xr?.stereo,w=0,R=0,L=1,x=1;C==="sbs"?(L=.5,w=d==="right"?.5:0):C==="ou"&&(x=.5,R=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 S=v.customProgram||this.renderProg,_=v.customUniforms||this.uRender;t.useProgram(S),t.vertexAttrib3f(3,0,0,0),_.uInstanced&&t.uniform1i(_.uInstanced,0),t.uniform1i(_.uToneMapping,l),t.uniform1f(_.uEnvIntensity,this.envIntensity),_.uExposure&&t.uniform1f(_.uExposure,this.exposure),t.uniform3f(_.uCameraPos,m,h,b),t.uniform1f(_.uEmissive,A?1:0),t.uniformMatrix4fv(_.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(_.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(_.uNormalMatrix,!1,p.normalMatrix),_.uUvTransform&&t.uniform4f(_.uUvTransform,w,R,L,x),_.uViewportSize&&t.uniform2f(_.uViewportSize,Math.max(1,s),Math.max(1,o)),u?.bind(t,_,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(_.uEnvironmentMap,4),t.uniform1i(_.uHasEnvironmentMap,1)):t.uniform1i(_.uHasEnvironmentMap,0),this.bindLights(_),_.uSectionEnabled&&t.uniform1i(_.uSectionEnabled,0);for(let N of ae)N.onBeforeDrawPrimitive?.(t,S,v,p,this.worldMatrices||[],this.gltf);t.uniform4fv(_.uBaseColor,v.baseColor),t.uniform1f(_.uMetallic,v.metallic),t.uniform1f(_.uRoughness,v.roughness),_.uClearcoat&&t.uniform2f(_.uClearcoat,v.clearcoat??0,v.clearcoatRoughness??.04),v.texture?(t.activeTexture(33984),t.bindTexture(3553,v.texture),t.uniform1i(_.uBaseColorTexture,0),t.uniform1i(_.uHasTexture,1)):t.uniform1i(_.uHasTexture,0),v.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,v.metallicRoughnessTexture),t.uniform1i(_.uMetallicRoughnessTexture,1),t.uniform1i(_.uHasMetallicRoughnessTexture,1)):t.uniform1i(_.uHasMetallicRoughnessTexture,0),v.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,v.normalTexture),t.uniform1i(_.uNormalTexture,2),t.uniform1i(_.uHasNormalTexture,1),t.uniform1f(_.uNormalScale,v.normalScale)):t.uniform1i(_.uHasNormalTexture,0),v.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,v.occlusionTexture),t.uniform1i(_.uOcclusionTexture,3),t.uniform1i(_.uHasOcclusionTexture,1),t.uniform1f(_.uOcclusionStrength,v.occlusionStrength)):t.uniform1i(_.uHasOcclusionTexture,0),t.bindVertexArray(v.vao);let k=p.instanceMatrices;if(v.instanceCount!==void 0)t.drawElementsInstanced(4,v.indexCount,v.indexType,0,v.instanceCount);else if(k&&k.length>=16&&v.instanced&&_.uInstanced&&_.uViewProj){let N=k.length>>4;t.uniform1i(_.uInstanced,1),t.uniformMatrix4fv(_.uViewProj,!1,c),v.indices?t.drawElementsInstanced(4,v.indexCount,v.indexType,0,N):t.drawArraysInstanced(4,0,v.indexCount,N),t.uniform1i(_.uInstanced,0)}else if(k&&k.length>=16){let N=k.length>>4,V=p.instanceColors,U=se(),B=new Float32Array(9),D=[v.baseColor[0],v.baseColor[1],v.baseColor[2],v.baseColor[3]];for(let H=0;H<N;H++)oe(U,this.modelMatrix,k.subarray(H*16,H*16+16)),oe(this.mvpMatrix,c,U),ye(B,U),t.uniformMatrix4fv(_.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(_.uModel,!1,U),t.uniformMatrix3fv(_.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(_.uBaseColor,D)),rt(t,v)}else rt(t,v)}}};if(P(!1),g){for(let f of ae)f.onBeforeTransmissivePass?.(t,this);P(!0)}for(let f of ae)f.onAfterRender?.(t,this,c,e?.eye??"none",[r,i,s,o],e?.projMatrix??this.projMatrix)}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 ae)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()}};me.registerPlugin=Ze,me.getRegisteredPlugins=Sn;function Fr(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),b=t(n[e+9],0),y=t(n[e+10],1),d=Math.hypot(o,c,a),g=Math.hypot(u,l,m),T=Math.hypot(h,b,y);o*(l*y-b*m)-u*(c*y-b*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,A=o*f,C=c*f,w=a*f,R=u*M,L=l*M,x=m*M,v=h*p,I=b*p,S=y*p,_=A+L+S,k=0,N=0,V=0,U=1;if(_>0){let D=.5/Math.sqrt(_+1);U=.25/D,k=(x-I)*D,N=(v-w)*D,V=(C-R)*D}else if(A>L&&A>S){let D=2*Math.sqrt(Math.max(0,1+A-L-S));D>1e-8&&(U=(x-I)/D,k=.25*D,N=(R+C)/D,V=(v+w)/D)}else if(L>S){let D=2*Math.sqrt(Math.max(0,1+L-A-S));D>1e-8&&(U=(v-w)/D,k=(R+C)/D,N=.25*D,V=(x+I)/D)}else{let D=2*Math.sqrt(Math.max(0,1+S-A-L));D>1e-8&&(U=(C-R)/D,k=(v+w)/D,N=(x+I)/D,V=.25*D)}let B=Math.hypot(k,N,V,U);return B>1e-8&&Number.isFinite(B)?(k/=B,N/=B,V/=B,U/=B):(k=0,N=0,V=0,U=1),{t:[r,i,s],r:[k,N,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=[],b=[];function y(R){let L=m.get(R);if(L!==void 0)return L;L=l.length,m.set(R,L);let x=R,v=x.color?.r??.8,I=x.color?.g??.8,S=x.color?.b??.8,_=x.opacity??1,k={name:x.name||"",pbrMetallicRoughness:{baseColorFactor:[v,I,S,_],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;k.emissiveFactor=[x.emissive.r*V,x.emissive.g*V,x.emissive.b*V]}let N={};return x.clearcoat&&x.clearcoat>0&&(N.KHR_materials_clearcoat={clearcoatFactor:x.clearcoat,clearcoatRoughnessFactor:x.clearcoatRoughness||0}),x.sheen&&x.sheen>0&&(N.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&&(N.KHR_materials_transmission={transmissionFactor:x.transmission}),x.thickness&&x.thickness>0&&(N.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&&(N.KHR_materials_ior={ior:x.ior}),x.dispersion&&x.dispersion>0&&(N.KHR_materials_dispersion={dispersion:x.dispersion}),x.iridescence&&x.iridescence>0&&(N.KHR_materials_iridescence={iridescenceFactor:x.iridescence,iridescenceIor:x.iridescenceIOR??1.3}),Object.keys(N).length>0&&(k.extensions=N),l.push(k),L}function d(R,L){let x=new Uint8Array(R.buffer,R.byteOffset,R.byteLength),v=Fr(x.byteLength),I=new Uint8Array(v);I.set(x),t.push(I);let S=i.length;return i.push({buffer:0,byteOffset:r,byteLength:x.byteLength,target:L}),r+=v,S}function g(R,L,x,v,I,S,_){let k=d(R,x),N=s.length,V={bufferView:k,byteOffset:0,componentType:v,count:I,type:L};return S&&(V.min=S),_&&(V.max=_),s.push(V),N}n.traverse(R=>{(R.isLight||R.color&&R.intensity!==void 0)&&b.push({type:R.type,color:[R.color.r,R.color.g,R.color.b],intensity:R.intensity,position:[R.position.x,R.position.y,R.position.z]})});let T=[];function P(R){let L={name:R.name||""},x=R.position,v=R.quaternion,I=R.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]),R.userData&&Object.keys(R.userData).length>0&&(L.extras=JSON.parse(JSON.stringify(R.userData,(_,k)=>{if(!(_==="__proto__"||_==="prototype"||_==="constructor"))return typeof k=="function"?void 0:k})),R.userData.xr)){let _=Or(R.userData.xr);L.extensions={...L.extensions||{},MOZ_hubs_components:_,ANDROID_xr_scenecore:_},J().xrTraitSerializer?.gltfNode(L,R.userData.xr),a.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(R.geometry){let _=R.geometry,k=_.attributes.position;if(k&&k.count>0){let N=[1/0,1/0,1/0],V=[-1/0,-1/0,-1/0];for(let O=0;O<k.count;O++){let X=k.getX(O),E=k.getY(O),F=k.getZ(O);X<N[0]&&(N[0]=X),X>V[0]&&(V[0]=X),E<N[1]&&(N[1]=E),E>V[1]&&(V[1]=E),F<N[2]&&(N[2]=F),F>V[2]&&(V[2]=F)}let B={attributes:{POSITION:g(k.array,"VEC3",34962,5126,k.count,N,V)}};if(_.attributes.normal&&(B.attributes.NORMAL=g(_.attributes.normal.array,"VEC3",34962,5126,_.attributes.normal.count)),_.attributes.uv&&(B.attributes.TEXCOORD_0=g(_.attributes.uv.array,"VEC2",34962,5126,_.attributes.uv.count)),_.index){let O=_.index.array instanceof Uint32Array;B.indices=g(_.index.array,"SCALAR",34963,O?5125:5123,_.index.count)}R.material&&(B.material=y(R.material));let D=R.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 F=h.indexOf(X);if(F===-1&&h.length<256&&(F=h.length,h.push(X)),F===-1)continue;let G=y(E),W=O.get(G);W||(W=[],O.set(G,W)),W.push(F)}if(O.size>0){let X=[];for(let[E,F]of O.entries())X.push({material:E,variants:F});B.extensions={...B.extensions||{},KHR_materials_variants:{mappings:X}},a.add("KHR_materials_variants")}}let H=R;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),F=new Float32Array(O*4),G=new Float32Array(O*3);for(let j=0;j<O;j++){let{t:ne,r:ce,s:q}=Ur(X,j*16);E[j*3]=ne[0],E[j*3+1]=ne[1],E[j*3+2]=ne[2],F[j*4]=ce[0],F[j*4+1]=ce[1],F[j*4+2]=ce[2],F[j*4+3]=ce[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(F,"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:R.name,...L.extras?{extras:L.extras}:{}}),L.mesh=z}}let S=c.length;if(c.push(L),u.push(R),R.children.length>0){L.children=[];for(let _ of R.children)L.children.push(P(_))}return S}for(let R of n.children)T.push(P(R));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 R=e?.duration??4,L=e?.fps??15,x=Math.max(2,Math.round(R*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})),S=u.map(()=>new Float32Array(x*3)),_=u.map(()=>new Float32Array(x*4)),k=u.map(()=>new Float32Array(x*3));for(let D=0;D<x;D++){let H=D/(x-1)*R;v[D]=H;try{f(H)}catch{}for(let z=0;z<u.length;z++){let O=u[z];S[z][D*3]=O.position.x,S[z][D*3+1]=O.position.y,S[z][D*3+2]=O.position.z,_[z][D*4]=O.quaternion.x,_[z][D*4+1]=O.quaternion.y,_[z][D*4+2]=O.quaternion.z,_[z][D*4+3]=O.quaternion.w,k[z][D*3]=O.scale.x,k[z][D*3+1]=O.scale.y,k[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 N=null,V=()=>(N===null&&(N=g(v,"SCALAR",0,5126,x,[0],[R])),N),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(S[D][E*3]-H.px)>1e-4||Math.abs(S[D][E*3+1]-H.py)>1e-4||Math.abs(S[D][E*3+2]-H.pz)>1e-4)&&(z=!0),(Math.abs(_[D][E*4]-H.qx)>1e-4||Math.abs(_[D][E*4+1]-H.qy)>1e-4||Math.abs(_[D][E*4+2]-H.qz)>1e-4||Math.abs(_[D][E*4+3]-H.qw)>1e-4)&&(O=!0),(Math.abs(k[D][E*3]-H.sx)>1e-4||Math.abs(k[D][E*3+1]-H.sy)>1e-4||Math.abs(k[D][E*3+2]-H.sz)>1e-4)&&(X=!0);if(z){let E=g(S[D],"VEC3",0,5126,x),F=U.length;U.push({input:V(),interpolation:"LINEAR",output:E}),B.push({sampler:F,target:{node:D,path:"translation"}})}if(O){let E=g(_[D],"VEC4",0,5126,x),F=U.length;U.push({input:V(),interpolation:"LINEAR",output:E}),B.push({sampler:F,target:{node:D,path:"rotation"}})}if(X){let E=g(k[D],"VEC3",0,5126,x),F=U.length;U.push({input:V(),interpolation:"LINEAR",output:E}),B.push({sampler:F,target:{node:D,path:"scale"}})}}B.length>0&&M.push({name:"ProceduralLoop",samplers:U,channels:B})}let p=Tn(c,o,n.userData),A={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(R=>({name:R}))}}:{}}}:{}},C=new Uint8Array(r),w=0;for(let R of t)C.set(R,w),w+=R.byteLength;return{gltf:A,bin:C.buffer,lights:b,environmentIntensity:n.environmentIntensity}}function st(n){return new TextEncoder().encode(n)}function ot(n,e){let{gltf:t,bin:r}=Ye(n,e),i=JSON.stringify(t),s=st(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 R=s.getX(w),L=s.getY(w),x=s.getZ(w);c[w*3]=a[0]*R+a[4]*L+a[8]*x+a[12],c[w*3+1]=a[1]*R+a[5]*L+a[9]*x+a[13],c[w*3+2]=a[2]*R+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 R=new Float32Array(9);ye(R,a);for(let L=0;L<o;L++){let x=w.getX(L),v=w.getY(L),I=w.getZ(L),S=R[0]*x+R[3]*v+R[6]*I,_=R[1]*x+R[4]*v+R[7]*I,k=R[2]*x+R[5]*v+R[8]*I,N=Math.hypot(S,_,k)||1;u[L*3]=S/N,u[L*3+1]=_/N,u[L*3+2]=k/N}}let l;if(i.attributes.uv){let w=i.attributes.uv;l=new Float32Array(o*2);for(let R=0;R<o;R++)l[R*2]=w.getX(R),l[R*2+1]=w.getY(R)}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",b=[.8,.8,.8],y=.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&&(b=[w.color.r,w.color.g,w.color.b]),typeof w.roughness=="number"&&(y=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 R=typeof w.opacity=="number"?w.opacity:1,L=typeof w.transmission=="number"?w.transmission:0;if(f=R*(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,A=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 A=="function"){let w=e?.duration??4,R=e?.fps??4,L=Math.max(2,Math.round(w*R)+1),x=[],v=[],I=[],S=[],_=[r.position.x,r.position.y,r.position.z],k=[r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w],N=[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{A(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]),S.push([r.scale.x,r.scale.y,r.scale.z]),(Math.abs(r.position.x-_[0])>1e-4||Math.abs(r.position.y-_[1])>1e-4||Math.abs(r.position.z-_[2])>1e-4||Math.abs(r.quaternion.x-k[0])>1e-4||Math.abs(r.quaternion.y-k[1])>1e-4||Math.abs(r.quaternion.z-k[2])>1e-4||Math.abs(r.quaternion.w-k[3])>1e-4||Math.abs(r.scale.x-N[0])>1e-4)&&(V=!0)}r.position.set(_[0],_[1],_[2]),r.quaternion.set(k[0],k[1],k[2],k[3]),r.scale.set(N[0],N[1],N[2]),V&&(p={times:x,translations:v,rotations:I,scales:S})}let C=r;if(C.isInstancedMesh&&typeof C.count=="number"&&C.count>0&&C.instanceMatrix?.array){let w=Math.min(1e3,Math.floor(C.count)),R=C.instanceMatrix.array,L=C.instanceColor?.array,x=r.name||`Mesh_${t.length}`,v=new Float32Array(16),I=new Float32Array(9);for(let S=0;S<w;S++){let _=R.subarray(S*16,(S+1)*16);oe(v,a,_);let k=new Float32Array(o*3);for(let B=0;B<o;B++){let D=s.getX(B),H=s.getY(B),z=s.getZ(B);k[B*3]=v[0]*D+v[4]*H+v[8]*z+v[12],k[B*3+1]=v[1]*D+v[5]*H+v[9]*z+v[13],k[B*3+2]=v[2]*D+v[6]*H+v[10]*z+v[14]}let N;if(i.attributes.normal){let B=i.attributes.normal;N=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,F=I[2]*H+I[5]*z+I[8]*O,G=Math.hypot(X,E,F)||1;N[D*3]=X/G,N[D*3+1]=E/G,N[D*3+2]=F/G}}let V=b,U=h;L&&L.length>=(S+1)*3&&(V=[b[0]*L[S*3],b[1]*L[S*3+1],b[2]*L[S*3+2]],U=`${h}_inst_${S}`),t.push({name:`${x}_${S}`,positions:k,indices:m,normals:N,uvs:l,materialName:U,color:V,roughness:y,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:b,roughness:y,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=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||[],c=t.bufferViews||[],a=t.materials||[],u=t.meshes||[],l=t.nodes||[];function m(y){let d=o[y];if(!d)throw new Error(`Accessor ${y} 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 y=tt(t);for(let d=0;d<y.length;d++)h.set(d,y[d])}function b(y,d,g,T){let P=u[y];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],A=p.attributes?.POSITION;if(A===void 0)continue;let{acc:C,buffer:w}=m(A),R=new Float32Array(w,0,C.count*3),L=new Float32Array(R.length);for(let E=0;E<C.count;E++){let F=R[E*3],G=R[E*3+1],W=R[E*3+2];L[E*3]=d[0]*F+d[4]*G+d[8]*W+d[12],L[E*3+1]=d[1]*F+d[5]*G+d[9]*W+d[13],L[E*3+2]=d[2]*F+d[6]*G+d[10]*W+d[14]}let x,v=p.attributes?.NORMAL;if(v!==void 0){let{acc:E,buffer:F}=m(v),G=new Float32Array(F,0,E.count*3);x=new Float32Array(G.length);for(let W=0;W<E.count;W++){let j=G[W*3],ne=G[W*3+1],ce=G[W*3+2],q=f[0]*j+f[3]*ne+f[6]*ce,Z=f[1]*j+f[4]*ne+f[7]*ce,Y=f[2]*j+f[5]*ne+f[8]*ce,re=Math.hypot(q,Z,Y)||1;x[W*3]=q/re,x[W*3+1]=Z/re,x[W*3+2]=Y/re}}let I,S=p.attributes?.TEXCOORD_0;if(S!==void 0){let{acc:E,buffer:F}=m(S);I=new Float32Array(F,0,E.count*2)}let _;if(p.indices!==void 0){let{acc:E,buffer:F}=m(p.indices);E.componentType===5125?_=new Uint32Array(F,0,E.count):_=new Uint16Array(F,0,E.count);let G=C.count;for(let W of _)if(W>=G)throw new Error(`SecurityError: Index buffer value (${W}) out of vertex bounds [0, ${G}).`)}else{let E=C.count;_=E>65535?new Uint32Array(E):new Uint16Array(E);for(let F=0;F<E;F++)_[F]=F}let k="DefaultMaterial",N=[.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];k=E.name||`Material_${p.material}`;let F=E.pbrMetallicRoughness||{},G=1;Array.isArray(F.baseColorFactor)&&(N=[F.baseColorFactor[0],F.baseColorFactor[1],F.baseColorFactor[2]],typeof F.baseColorFactor[3]=="number"&&(G=F.baseColorFactor[3])),typeof F.roughnessFactor=="number"&&(V=F.roughnessFactor),typeof F.metallicFactor=="number"&&(U=F.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:_,normals:x,uvs:I,materialName:k,color:N,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 y=0;y<l.length;y++){let d=l[y];if(d.mesh!==void 0&&d.mesh<u.length){let g=h.get(y)||se(),T=d.name||u[d.mesh].name||`Node_${y}`,P=d.extensions?.EXT_mesh_gpu_instancing?.attributes;if(P&&typeof P=="object"){let f=P.TRANSLATION,M=P.ROTATION,p=P.SCALE,A=f!==void 0?(()=>{let{acc:L,buffer:x}=m(f);return new Float32Array(x,0,L.count*3)})():null,C=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,R=Math.min(1e3,A?A.length/3:C?C.length/4:w?w.length/3:0);if(R>0){let L=new Float32Array(16),x=new Float32Array(16);for(let v=0;v<R;v++){let I=A?[A[v*3],A[v*3+1],A[v*3+2]]:[0,0,0],S=C?[C[v*4],C[v*4+1],C[v*4+2],C[v*4+3]]:[0,0,0,1],_=w?[w[v*3],w[v*3+1],w[v*3+2]]:[1,1,1];Ce(L,S,I,_),oe(x,g,L),b(d.mesh,x,`${T}_${v}`,d.extras)}continue}}b(d.mesh,g,T,d.extras)}}else{let y=se();for(let d=0;d<u.length;d++){let g=u[d].name||`Mesh_${d}`;b(d,y,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
255
- endTimeCode = ${K(t)}
251
+ void main(){fragColor=uColorId;}`;function Rt(t,e,i){let r={};for(let s of i)r[s]=t.getUniformLocation(e,s);return r}var Jt=["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","uPointLightSpotDir","uPointLightSpotCone","uEnvIntensity","uExposure","uViewportSize","uSectionPlane","uSectionEnabled"];function ei(){let t=he().xrDepthShader;return{fs:kr.replace("/*XRD_U*/",t?.uniformsGLSL||"").replace("/*XRD_O*/",t?.occlusionGLSL||""),uniforms:t?[...Jt,...t.uniformNames]:Jt}}function Vr(t){if(typeof t!="string")return null;let e=t.trim();if(!e||/[\x00-\x1f\x7f]/.test(e))return null;let i=e.toLowerCase();return i.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(e)?e:null:i.startsWith("https://")||i.startsWith("blob:")?e:i.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(e)||/(^|[\\/])\.\.([\\/]|$)/.test(e)?null:e}function Tt(t,e,i,r,s,a,o,n){if(r===void 0||!e.accessors?.[r])return null;let l=qt(e,i,e.accessors[r],a);if(!l)return null;n&&(l=l.slice(),Er(l,n));let h=t.createBuffer();return o.push(h),t.bindBuffer(34962,h),t.bufferData(34962,l,35044),t.enableVertexAttribArray(s),t.vertexAttribPointer(s,a,5126,!1,0,0),l}function Ct(t){let e=Number(t);return Number.isFinite(e)?Math.max(0,e):1}function ti(t,e,i){let r=ei(),s=Qt,a=r.fs,o=!1;for(let l of me)if(l.onResolveShader){let h=l.onResolveShader(e,i,s,a);h&&(s=h.vs,a=h.fs,o=!0)}let n=o?At(t,s,a):null;return{program:n,uniforms:n?Rt(t,n,r.uniforms):null}}function Ur(t,e,i){let r=e.instanceMatrices;if(!r||r.length<16||typeof t.vertexAttribDivisor!="function"||typeof t.drawElementsInstanced!="function")return!1;let s=r.length>>4,a=e.instanceColors,o=new Float32Array(s*20);for(let l=0;l<s;l++)o.set(r.subarray(l*16,l*16+16),l*20),o[l*20+16]=a?a[l*3]:1,o[l*20+17]=a?a[l*3+1]:1,o[l*20+18]=a?a[l*3+2]:1,o[l*20+19]=1;let n=t.createBuffer();i.push(n),t.bindBuffer(34962,n),t.bufferData(34962,o,35044);for(let l=0;l<5;l++)t.enableVertexAttribArray(8+l),t.vertexAttribPointer(8+l,4,5126,!1,80,l*16),t.vertexAttribDivisor(8+l,1);return!0}function Br(t,e){let i=t.materials?.[e?.material];if(!i)return null;let r=[i.pbrMetallicRoughness?.baseColorTexture,i.pbrMetallicRoughness?.metallicRoughnessTexture,i.normalTexture,i.occlusionTexture,i.emissiveTexture];for(let s of r){let a=s?.extensions?.KHR_texture_transform;if(a&&typeof a=="object")return a}return null}var zr=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),ii=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function it(t,e){e.indices?t.drawElements(4,e.indexCount,e.indexType,0):t.drawArrays(4,0,e.indexCount)}function ri(t,e){let i=t?.pbrMetallicRoughness,r=i?.baseColorFactor,s=t?.extensions?.KHR_materials_clearcoat,a=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:i?.metallicFactor??.1,roughness:i?.roughnessFactor??.5,clearcoat:s?s.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,s?.clearcoatRoughnessFactor??.04),texture:a(i?.baseColorTexture),metallicRoughnessTexture:a(i?.metallicRoughnessTexture),normalTexture:a(t?.normalTexture),normalScale:t?.normalTexture?.scale??1,occlusionTexture:a(t?.occlusionTexture),occlusionStrength:t?.occlusionTexture?.strength??1,isTransmissive:(t?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function si(t,e,i){let r=new Set,s=a=>{a&&!r.has(a)&&(r.add(a),t.deleteTexture(a))};for(let a of e)for(let o of a.primitives){if(o.vao&&t.deleteVertexArray(o.vao),o.buffers)for(let l of o.buffers)t.deleteBuffer(l);s(o.texture),s(o.metallicRoughnessTexture),s(o.normalTexture),s(o.occlusionTexture);let n=new Set;o.customProgram&&n.add(o.customProgram);for(let l of o.programCache?.values()??[])l.program&&n.add(l.program);for(let l of n)t.deleteProgram(l)}if(i)for(let a of i)s(a)}function ai(t,e,i=ii,r){let s={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return $r(t,e,i,r,s)}catch(a){let o=s.mesh&&!s.meshes.includes(s.mesh)?[...s.meshes,s.mesh]:s.meshes;si(t,o,s.gpuTextures),s.vao&&t.deleteVertexArray(s.vao);for(let n of s.buffers)t.deleteBuffer(n);throw a}}function $r(t,e,i,r,s){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:a}=e,o=Be("meshopt");o?.decodeBufferViews&&o.decodeBufferViews(a,e);let n=e.bin,l=[];s.meshes=l;let h=[],c=a.extensions?.KHR_materials_variants;c&&Array.isArray(c.variants)&&c.variants.forEach((L,M)=>{h.push(typeof L?.name=="string"&&L.name?L.name:`Variant_${M}`)});let f=Cr(a),g=[];if(Array.isArray(a.nodes))for(let L=0;L<a.nodes.length;L++){let M=a.nodes[L];M.mesh!==void 0&&a.meshes&&a.meshes[M.mesh]&&g.push({node:M,nodeIdx:L,meshIdx:M.mesh})}let w=g.length>0?g:(a.meshes||[]).map((L,M)=>({node:L,nodeIdx:-1,meshIdx:M})),d=[],p=Array.isArray(e.lights)&&e.lights.length>0?e.lights:Array.isArray(a.asset?.extras?.lights)&&a.asset.extras.lights.length>0?a.asset.extras.lights:null;if(p)for(let L of p)d.push({...L,type:L.type||L.light_type||"point",innerConeAngle:L.innerConeAngle??L.inner_cone_angle,outerConeAngle:L.outerConeAngle??L.outer_cone_angle});else if(a.extensions?.KHR_lights_punctual?.lights){let L=a.extensions.KHR_lights_punctual.lights;for(let M of L){let O=M.type==="directional"?"directional":M.type==="point"?"point":M.type==="spot"?"spot":"ambient";d.push({type:O,color:M.color||[1,1,1],intensity:M.intensity!==void 0?M.intensity:1})}}if(d.length===0&&(d.push({type:"ambient",color:[1,1,1],intensity:.35}),d.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),w.length>i.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${i.maxMeshes}). Found: ${w.length}`);let A=[];if(s.gpuTextures=A,a.textures&&a.images){if(a.textures.length>i.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${i.maxTextures}). Found: ${a.textures.length}`);for(let L=0;L<a.textures.length;L++){let M=a.textures[L],O=a.images[M.source];if(O){let H=t.createTexture();t.bindTexture(3553,H),t.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),t.texParameteri(3553,10242,10497),t.texParameteri(3553,10243,10497),t.texParameteri(3553,10241,9729),t.texParameteri(3553,10240,9729);let R=C=>{t.bindTexture(3553,H),t.texImage2D(3553,0,6408,6408,5121,C),t.generateMipmap(3553),r?.()};if(O.bufferView!==void 0){let C=a.bufferViews[O.bufferView],y=C.byteOffset||0,T=new Blob([n.slice(y,y+C.byteLength)],{type:O.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(T).then(R).catch(()=>{})}else if(O.uri){let C=Vr(O.uri);if(C){let y=new Image;y.crossOrigin="anonymous",y.referrerPolicy="no-referrer",y.onload=()=>R(y),y.src=C}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",O.uri)}A.push(H)}else A.push(null)}}let b=[1/0,1/0,1/0],x=[-1/0,-1/0,-1/0],u=0,m=0;for(let L=0;L<w.length;L++){let M=w[L],O=a.meshes[M.meshIdx],H=M.nodeIdx>=0?f[M.nodeIdx]:de(),R=new Float32Array(9);Ne(R,H);let C={name:M.node.name||O.name||`Mesh_${M.meshIdx}`,nodeIndex:M.nodeIdx,transform:H,normalMatrix:R,primitives:[],extras:M.node.extras||O.extras,...M.node?.visible===!1||M.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{}};s.mesh=C;let y=M.node?.extensions?.EXT_mesh_gpu_instancing;if(y&&y.attributes&&typeof y.attributes=="object"){let T=y.attributes,z=T.TRANSLATION!==void 0?a.accessors?.[T.TRANSLATION]:null,G=T.ROTATION!==void 0?a.accessors?.[T.ROTATION]:null,B=T.SCALE!==void 0?a.accessors?.[T.SCALE]:null,te=T._COLOR_0!==void 0?a.accessors?.[T._COLOR_0]:null,I=Number(z?.count??G?.count??B?.count??0);if(!Number.isFinite(I)||I<0||I>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${I}`);if(I>0){let W=(k,V)=>{if(!k||k.bufferView===void 0||!a.bufferViews?.[k.bufferView])return null;let j=k.componentType??5126,K=J=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${J})`),null);if(j!==5120&&j!==5121&&j!==5122&&j!==5123&&j!==5126)return K(`componentType ${j}`);if(!(Number(k.count)>=I))return K(`count ${k.count} < ${I}`);let Q=null;try{Q=qt(a,n,{...k,count:I},V)}catch{return K("out of bounds")}return!Q||!Q.every(Number.isFinite)?K("non-finite value"):Q},Z=W(z,3),ae=W(G,4),U=W(B,3),ee=te?.type==="VEC4"?4:3,$=W(te,ee),q=new Float32Array(I*16),X=de();for(let k=0;k<I;k++){let V=Z?[Z[k*3],Z[k*3+1],Z[k*3+2]]:[0,0,0],j=ae?[ae[k*4],ae[k*4+1],ae[k*4+2],ae[k*4+3]]:[0,0,0,1],K=U?[U[k*3],U[k*3+1],U[k*3+2]]:[1,1,1];St(X,j,V,K),q.set(X,k*16)}if(C.instanceMatrices=q,$){let k=new Float32Array(I*3);for(let V=0;V<I;V++)k[V*3]=$[V*ee],k[V*3+1]=$[V*ee+1],k[V*3+2]=$[V*ee+2];C.instanceColors=k}}}for(let T of O.primitives||[]){if(T.extensions?.KHR_draco_mesh_compression){let Q=Be("draco");Q&&Q.decodePrimitive(a,T,n)}let z=[],G=t.createVertexArray();s.vao=G,s.buffers=z,t.bindVertexArray(G);let B=Ur(t,C,z),te=a.accessors[T.attributes.POSITION],I=Number(te?.count??0);if(!Number.isFinite(I)||I<0||u+I>i.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${i.maxVertices}).`);if(u+=I,te?.min&&te?.max){let Q=J=>{for(let Y=0;Y<3;Y++){let ue=J[12+Y],se=J[12+Y];for(let ne=0;ne<3;ne++){let oe=J[ne*4+Y]*te.min[ne],le=J[ne*4+Y]*te.max[ne];ue+=oe<le?oe:le,se+=oe>le?oe:le}ue<b[Y]&&(b[Y]=ue),se>x[Y]&&(x[Y]=se)}};if(C.instanceMatrices&&C.instanceMatrices.length>=16){let J=C.instanceMatrices.length>>4,Y=de();for(let ue=0;ue<J;ue++){let se=C.instanceMatrices.subarray(ue*16,ue*16+16);fe(Y,H,se),Q(Y)}}else Q(H)}let W=Tt(t,a,n,T.attributes.POSITION,0,3,z);Tt(t,a,n,T.attributes.NORMAL,1,3,z),Tt(t,a,n,T.attributes.TEXCOORD_0,2,2,z,Br(a,T));let Z=0,ae=5123,U=null;if(T.indices!==void 0){let Q=a.accessors[T.indices],J=(a.bufferViews[Q.bufferView].byteOffset||0)+(Q.byteOffset||0);if(Z=Number(Q.count??0),!Number.isFinite(Z)||Z<0||m+Z>i.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${i.maxIndices}).`);m+=Z,ae=Q.componentType===5125?5125:5123;let Y=t.createBuffer();z.push(Y),t.bindBuffer(34963,Y),Q.componentType===5125?U=new Uint32Array(n,J,Q.count):Q.componentType===5121?U=Uint16Array.from(new Uint8Array(n,J,Q.count)):U=J%2===0?new Uint16Array(n,J,Q.count):new Uint16Array(n.slice(J,J+Q.count*2)),t.bufferData(34963,U,35044)}else Z=te.count;let ee={};for(let Q of me)if(Q.onBuildPrimitiveVAO){let J=Q.onBuildPrimitiveVAO(t,G,T,a,n);J&&(ee[Q.name]=J)}t.bindVertexArray(null);let $=a.materials&&T.material!==void 0?a.materials[T.material]:null,{program:q,uniforms:X}=ti(t,T,$),k=ri($,A),V=!!($?.extensions?.KHR_materials_transmission||ee.materials?.isTransmissive),j=T.extensions?.KHR_materials_variants?.mappings,K=Array.isArray(j)?j.filter(Q=>Q&&typeof Q.material=="number"&&Array.isArray(Q.variants)).map(Q=>({material:Q.material|0,variants:Q.variants.map(J=>Number(J)|0)})):void 0;C.primitives.push({vao:G,instanced:B,indexCount:Z,indexType:ae,...k,positions:W,indices:U,buffers:z,materialIndex:T.material,defaultMaterialIndex:T.material,variantMappings:K,primitiveDef:T,programCache:new Map([[T.material??-1,{program:q,uniforms:X}]]),pluginData:ee,customProgram:q,customUniforms:X,isTransmissive:V})}l.push(C)}isFinite(b[0])||(b=[-1,-1,-1]),isFinite(x[0])||(x=[1,1,1]);let v=[(b[0]+x[0])/2,(b[1]+x[1])/2,(b[2]+x[2])/2],S=x[0]-b[0],_=x[1]-b[1],D=x[2]-b[2],P=Math.max(Math.hypot(S,_,D)/2,.5),N=[b[0],b[1],b[2]],E=[x[0],x[1],x[2]],F=e.animations;if(!F){for(let L of me)if(L.onParseGLB?.(e),e.animations){F=e.animations;break}}return F||(F=[]),{meshes:l,bounds:{center:v,radius:P,min:N,max:E},lights:d,animations:F,worldMatrices:f,gpuTextures:A,availableVariants:h}}function Xe(t){let e=t.customTarget||t.bounds.center,i=t.currDistance*Math.cos(t.currPhi);return[e[0]+i*Math.sin(t.currTheta),e[1]+t.currDistance*Math.sin(t.currPhi),e[2]+i*Math.cos(t.currTheta)]}var Se=class{constructor(t,e,i){this.supportsInstanceOffsets=!0,this.meshes=[],this.backdropMeshes=[],this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]},this.lights=[],this.modelRootMatrix=de(),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=de(),this.viewMatrix=de(),this.activeViewMatrix=null,this.modelMatrix=de(),this.mvpMatrix=de(),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:de(),rawValueToMeters:.001,format:0},this.container=t;let r,s;if(e&&typeof e.getContext=="function"?(r=e,s=i):(s=e,r=s?.canvas),!r){let n=t.querySelector("canvas");n||(n=document.createElement("canvas"),n.style.width="100%",n.style.height="100%",n.style.display="block",n.style.touchAction="none",t.prepend(n)),r=n}this.canvas=r,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!a:a&&(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=Ct(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=Ue(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 o=r.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!o)throw new Error("WebGL2 not supported");this.gl=o,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(t,e){Lr(t,e)}static getDecoder(t){return Be(t)}setupContextLossHandling(){let t=this.canvas;typeof t?.addEventListener=="function"&&(this.boundContextLost=e=>{e.preventDefault?.(),this.contextLost=!0,this.stop()},this.boundContextRestored=()=>this.restoreContext(),t.addEventListener("webglcontextlost",this.boundContextLost),t.addEventListener("webglcontextrestored",this.boundContextRestored))}initGlState(){let t=this.gl,e=ei();this.renderProg=At(t,Qt,e.fs),this.pickProg=At(t,Ir,Or),this.uRender=Rt(t,this.renderProg,e.uniforms),this.uPick=Rt(t,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let t=this.gl;this.contextLost=!1,this.initGlState();for(let e of me)e.onContextRestored?.(t,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 t=this.gl;if(typeof t.createFramebuffer!="function")return;this.pickFbo=t.createFramebuffer(),this.pickTexture=t.createTexture(),this.pickDepth=t.createRenderbuffer();let e=Math.max(1,this.canvas.width),i=Math.max(1,this.canvas.height);this.pickFboWidth=e,this.pickFboHeight=i,t.bindTexture(3553,this.pickTexture),t.texImage2D(3553,0,6408,e,i,0,6408,5121,null),t.texParameteri(3553,10241,9728),t.texParameteri(3553,10240,9728),t.bindRenderbuffer(36161,this.pickDepth),t.renderbufferStorage(36161,33189,e,i),t.bindFramebuffer(36160,this.pickFbo),t.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),t.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),t.bindFramebuffer(36160,null)}resizePickingFbo(t,e){if(!this.pickFbo)return;let i=this.gl,r=Math.max(1,t),s=Math.max(1,e);this.pickFboWidth=r,this.pickFboHeight=s,i.bindTexture(3553,this.pickTexture),i.texImage2D(3553,0,6408,r,s,0,6408,5121,null),i.bindRenderbuffer(36161,this.pickDepth),i.renderbufferStorage(36161,33189,r,s)}loadGLBData(t,e){let{meshes:i,bounds:r,lights:s,animations:a,worldMatrices:o,gpuTextures:n,availableVariants:l}=ai(this.gl,t,e,()=>this.render());if(this.lastGlbData=t,this.lastLimits=e,this.disposeMeshGpuResources(),this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.meshes=i,this.bounds=r,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=s,this.animations=a||[],this.worldMatrices=o||[],this.gpuTextures=n||[],this.availableVariants=l||[],this.gltf=t.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(t.gltf?.nodes))for(let f of t.gltf.nodes)this.initialNodeTransforms.push({t:f.translation?[f.translation[0],f.translation[1],f.translation[2]]:[0,0,0],r:f.rotation?[f.rotation[0],f.rotation[1],f.rotation[2],f.rotation[3]]:[0,0,0,1],s:f.scale?[f.scale[0],f.scale[1],f.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let f of me)f.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:r.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let h=t.exposure??t.gltf?.extras?.exposure??t.gltf?.asset?.extras?.exposure;h!==void 0&&(this.exposure=Ct(h));let c=t.environmentIntensity??t.gltf?.extras?.environmentIntensity??t.gltf?.asset?.extras?.environmentIntensity;c!==void 0&&(this.envIntensity=Math.max(0,Number(c)||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(t){this.loadGLBData(Zt(t))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let t of me)t.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(t){this.loadGLBData(We(t))}setBackdropGLB(t,e){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!t){this.update(0),this.render();return}let i=We(t),{meshes:r}=ai(this.gl,i,ii,()=>this.render());if(e)for(let s of r)s.transform[12]+=e[0],s.transform[13]+=e[1],s.transform[14]+=e[2],Ne(s.normalMatrix,s.transform);this.backdropMeshes=r,this.update(0),this.render()}setClearColor(t,e,i,r=1){this.clearColor=[t,e,i,r]}updateMeshTransforms(t){for(let e=0;e<this.meshes.length;e++){let i=this.meshes[e],r;t instanceof Map?r=t.get(i.name)??t.get(e):Array.isArray(t)?r=t[e]:t&&typeof t=="object"&&(Object.prototype.hasOwnProperty.call(t,i.name)?r=t[i.name]:Object.prototype.hasOwnProperty.call(t,e)&&(r=t[e])),r&&r.length===16&&(i.transform.set(r),Ne(i.normalMatrix,i.transform))}}bindLights(t=this.uRender){let e=this.gl,i=[.28,.28,.28],r=[],s=[],a=[],o=[],n=[],l=[];for(let h of this.lights){let c=h.color||[1,1,1],f=h.intensity!==void 0?h.intensity:1;if(h.type==="ambient")i=[c[0]*f,c[1]*f,c[2]*f];else if(h.type==="directional"&&r.length<6){let g=h.direction||[.5,1,.8];r.push(g[0],g[1],g[2]),s.push(c[0]*f,c[1]*f,c[2]*f)}else if((h.type==="point"||h.type==="spot")&&a.length<6){let g=h.position||[0,0,0];if(a.push(g[0],g[1],g[2]),o.push(c[0]*f,c[1]*f,c[2]*f),h.type==="spot"){let w=h.direction||[0,-1,0],d=Math.max(.01,Math.min(Math.PI/2,h.outerConeAngle??Math.PI/3)),p=Math.max(0,Math.min(d-1e-4,h.innerConeAngle??0));n.push(w[0],w[1],w[2]),l.push(Math.cos(p),Math.cos(d))}else n.push(0,-1,0),l.push(-2,-3)}}r.length===0&&(r.push(.5,1,.8),s.push(1,1,1)),e.uniform3fv(t.uAmbientColor,i),e.uniform1i(t.uNumDirLights,r.length/3),r.length>0&&(e.uniform3fv(t.uDirLightDir,r),e.uniform3fv(t.uDirLightColor,s)),e.uniform1i(t.uNumPointLights,a.length/3),a.length>0&&(e.uniform3fv(t.uPointLightPos,a),e.uniform3fv(t.uPointLightColor,o),t.uPointLightSpotDir&&e.uniform3fv(t.uPointLightSpotDir,n),t.uPointLightSpotCone&&e.uniform2fv(t.uPointLightSpotCone,l)),e.uniform1f(t.uEnvIntensity,this.envIntensity)}setExposure(t){this.exposure=Ct(t)}getExposure(){return this.exposure}setShadow(t,e){this.shadowIntensity=Math.max(0,Math.min(1,Number(t)||0)),e!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(e)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(t){this.toneMapping=Ue(t)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(t){for(let e of me)if(e.setEnvironmentImage){await e.setEnvironmentImage(this,t);return}}async setSkyboxImage(t){for(let e of me)if(e.setSkyboxImage){await e.setSkyboxImage(this,t);return}}setInteractive(t){this.interactive=t}isInteractive(){return this.interactive}getCameraOrbit(){let t=this.currTheta,e=this.currPhi,i=this.currDistance;return{theta:t,phi:e,radius:i,toString(){return`${t.toFixed(4)}rad ${e.toFixed(4)}rad ${i.toFixed(4)}m`}}}getCameraTarget(){let t=this.customTarget||this.bounds.center;return{x:t[0],y:t[1],z:t[2],toString(){return`${t[0].toFixed(4)}m ${t[1].toFixed(4)}m ${t[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let t=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return t.map((e,i)=>{let r=this.meshes.flatMap(h=>h.primitives.filter(c=>c.materialIndex===i||t.length===1&&c.materialIndex===void 0)),s=r[0],a=s?[...s.baseColor]:e.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],o=s?s.metallic:e.pbrMetallicRoughness?.metallicFactor??.1,n=s?s.roughness:e.pbrMetallicRoughness?.roughnessFactor??.5,l={baseColorFactor:a,metallicFactor:o,roughnessFactor:n,setBaseColorFactor:h=>{let c=[h[0],h[1],h[2],h[3]??1];l.baseColorFactor=c,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.baseColorFactor=c);for(let f of r)f.baseColor=c;this.render()},setMetallicFactor:h=>{l.metallicFactor=h,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.metallicFactor=h);for(let c of r)c.metallic=h;this.render()},setRoughnessFactor:h=>{l.roughnessFactor=h,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.roughnessFactor=h);for(let c of r)c.roughness=h;this.render()}};return{name:e.name||`Material_${i}`,pbrMetallicRoughness:l}})}playAnimation(t){if(this.animations.length!==0){if(t){let e=this.animations.find(i=>i.name===t);e&&(this.currentClip=e)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(t=>t.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(t){let e=this.applyVariantMaterial(t);return e&&this.gl&&this.render(),e}applyVariantMaterial(t){let e=t===null||t==="",i=-1;if(e)this.activeVariantName=null;else{if(i=this.availableVariants.indexOf(t),i<0)return!1;this.activeVariantName=t}let r=this.gltf?.materials;if(!Array.isArray(r))return e;for(let s of this.meshes)for(let a of s.primitives){let o=a.defaultMaterialIndex;if(!e&&Array.isArray(a.variantMappings)){for(let l of a.variantMappings)if(Array.isArray(l.variants)&&l.variants.includes(i)){o=l.material;break}}let n=o!==void 0?r[o]:void 0;a.materialIndex=n?o:void 0,Object.assign(a,ri(n,this.gpuTextures)),this.applyPrimitiveProgram(a,a.materialIndex,n??null)}return!0}applyPrimitiveProgram(t,e,i){if(!this.gl||!t.primitiveDef)return;t.programCache??(t.programCache=new Map);let r=e??-1,s=t.programCache.get(r);s||(s=ti(this.gl,{...t.primitiveDef,material:e},i),t.programCache.set(r,s)),t.customProgram=s.program,t.customUniforms=s.uniforms,t.pluginData&&(t.pluginData.materials=t.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(t){this.autoplay=t,t?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(t){this.animationName=t,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(t)}evaluateAnimation(t){for(let e of me)if(e.evaluateAnimation){e.evaluateAnimation(this,t);return}}setTarget(t,e,i){this.customTarget=[t,e,i],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(t){let e=Math.max(10,Math.min(90,t));this.fov=e*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(t){if(this.distanceMode=t,!this.customDistance){let e=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=e,this.targetDistance=e,this.currDistance=e,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(t){t.minTheta!==void 0&&(this.minTheta=t.minTheta*Math.PI/180),t.maxTheta!==void 0&&(this.maxTheta=t.maxTheta*Math.PI/180),t.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,t.minPhi*Math.PI/180)),t.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,t.maxPhi*Math.PI/180)),t.minDistance!==void 0&&(this.minDistanceLimit=t.minDistance),t.maxDistance!==void 0&&(this.maxDistanceLimit=t.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(t){return Math.max(this.minTheta,Math.min(this.maxTheta,t))}clampPhi(t){return Math.max(this.minPhi,Math.min(this.maxPhi,t))}clampDistance(t){let e=this.minDistanceLimit!==null?this.minDistanceLimit:this.bounds?this.bounds.radius*.5:.1,i=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(e,Math.min(i,t))}setCamera(t,e,i,r){t!==void 0&&(this.targetTheta=this.clampTheta(t*Math.PI/180)),e!==void 0&&(this.targetPhi=this.clampPhi(e*Math.PI/180)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(i)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/r))}setInitialCamera(t,e,i,r){if(t!==void 0&&(this.initialTheta=this.clampTheta(t*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),e!==void 0&&(this.initialPhi=this.clampPhi(e*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),i!==void 0&&i>0){let s=this.clampDistance(i);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else if(r!==void 0&&r>0){let s=this.clampDistance(this.bounds.radius*2.5/r);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(t,e){let i=de();fe(i,this.projMatrix,this.viewMatrix);let[r,s,a]=t,o=e?e[0]:0,n=e?e[1]:0,l=e?e[2]:0,h=this.modelRootMatrix;h&&(r=h[0]*t[0]+h[4]*t[1]+h[8]*t[2]+h[12],s=h[1]*t[0]+h[5]*t[1]+h[9]*t[2]+h[13],a=h[2]*t[0]+h[6]*t[1]+h[10]*t[2]+h[14],e&&(o=h[0]*e[0]+h[4]*e[1]+h[8]*e[2],n=h[1]*e[0]+h[5]*e[1]+h[9]*e[2],l=h[2]*e[0]+h[6]*e[1]+h[10]*e[2]));let c=i[0]*r+i[4]*s+i[8]*a+i[12],f=i[1]*r+i[5]*s+i[9]*a+i[13],g=i[2]*r+i[6]*s+i[10]*a+i[14],w=i[3]*r+i[7]*s+i[11]*a+i[15];if(w<=1e-4)return{x:0,y:0,z:1,visible:!1};let d=c/w,p=f/w,A=g/w,b=this.canvas.getBoundingClientRect(),x=b.width||this.canvas.clientWidth||this.canvas.width||300,u=b.height||this.canvas.clientHeight||this.canvas.height||150,m=(d*.5+.5)*x,v=(-p*.5+.5)*u,S=d>=-1.1&&d<=1.1&&p>=-1.1&&p<=1.1&&A>=-1&&A<=1;if(S&&e){let[_,D,P]=Xe(this),N=[r-_,s-D,a-P];o*N[0]+n*N[1]+l*N[2]>.05&&(S=!1)}return{x:m,y:v,z:A,visible:S}}setSelectedMesh(t){this.selectedMeshName=t||""}getSelectedMesh(){return this.selectedMeshName}setupEvents(){let t=this.canvas,e=()=>typeof performance<"u"?performance.now():Date.now();this.boundContextMenu=i=>{i.preventDefault()},t.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=i=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=e(),this.lastPointerX=i.clientX,this.lastPointerY=i.clientY,this.totalDragDist=0,this.activePointers.set(i.pointerId,{x:i.clientX,y:i.clientY}),this.isPanning=i.button===2||i.shiftKey||this.activePointers.size===2,t.setPointerCapture(i.pointerId))},t.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=i=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=e();let r=this.activePointers.get(i.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},s=i.clientX-r.x,a=i.clientY-r.y;if(this.activePointers.set(i.pointerId,{x:i.clientX,y:i.clientY}),this.lastPointerX=i.clientX,this.lastPointerY=i.clientY,this.totalDragDist+=Math.hypot(s,a),this.isPanning||i.button===2||i.shiftKey||this.activePointers.size===2){let o=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],n=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],l=this.customTarget?[...this.customTarget]:[...this.bounds.center],h=this.currDistance/Math.max(t.clientHeight||300,1)*1.5;l[0]+=(-s*o[0]+a*n[0])*h,l[1]+=(-s*o[1]+a*n[1])*h,l[2]+=(-s*o[2]+a*n[2])*h,this.customTarget=l}else this.targetTheta=this.clampTheta(this.targetTheta-s*.008),this.targetPhi=this.clampPhi(this.targetPhi+a*.008)},t.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=i=>{this.lastInteractionTime=e(),this.activePointers.delete(i.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{t.releasePointerCapture(i.pointerId)}catch{}if(this.totalDragDist<5&&i.button===0){let r=t.getBoundingClientRect(),s=Math.floor((i.clientX-r.left)*(t.width/Math.max(r.width,1))),a=Math.floor((i.clientY-r.top)*(t.height/Math.max(r.height,1)));this.performMeshPick(s,a,!0)}},t.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=i=>{if(!this.interactive)return;i.preventDefault(),this.lastInteractionTime=e();let r=Math.exp(i.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},t.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=i=>{let r=i.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),t.tabIndex!==void 0&&t.tabIndex<0&&(t.tabIndex=0),t.getAttribute?.("role")||t.setAttribute?.("role","region"),t.getAttribute?.("aria-label")||t.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=i=>{if(this.interactive){switch(i.key){case"ArrowLeft":this.targetTheta=this.clampTheta(this.targetTheta-.1);break;case"ArrowRight":this.targetTheta=this.clampTheta(this.targetTheta+.1);break;case"ArrowUp":this.targetPhi=this.clampPhi(this.targetPhi+.08);break;case"ArrowDown":this.targetPhi=this.clampPhi(this.targetPhi-.08);break;case"+":case"=":this.targetDistance=this.clampDistance(this.targetDistance*.9);break;case"-":case"_":this.targetDistance=this.clampDistance(this.targetDistance*1.1);break;case"Home":this.resetCamera();break;default:return}this.lastInteractionTime=e(),i.preventDefault()}},t.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let t=(i,r,s)=>{this[s]&&(i.removeEventListener(r,this[s]),this[s]=null)},e=this.canvas;t(e,"webglcontextlost","boundContextLost"),t(e,"webglcontextrestored","boundContextRestored"),t(e,"contextmenu","boundContextMenu"),t(e,"pointerdown","boundPointerDown"),t(e,"pointermove","boundPointerMove"),t(e,"pointerup","boundPointerUp"),t(e,"wheel","boundWheel"),t(e,"keydown","boundKeyDown"),t(this.container,"setCamera","boundSetCamera"),t(this.container,"resetCamera","boundResetCamera")}raycastFromScreenPoint(t,e){let i=this.canvas,r=i.getBoundingClientRect(),s=i.width||300,a=i.height||300,o=r.width>0?Math.floor((t-r.left)*(s/r.width)):Math.floor(t),n=r.height>0?Math.floor((e-r.top)*(a/r.height)):Math.floor(e);return this.performMeshPick(o,n,!1)}performMeshPick(t,e,i=!0){if(this.meshes.length===0)return null;let r=this.gl,s=Math.max(1,this.canvas.width||300),a=Math.max(1,this.canvas.height||300);t=this.mapStereoPickX(t,s);let o=de();fe(o,this.projMatrix,this.viewMatrix);let n=[],l=Math.max(0,Math.min(s-1,t)),h=Math.max(0,Math.min(a-1,a-1-e));if(this.pickFbo&&r&&!this.xrSessionActive){(this.pickFboWidth!==s||this.pickFboHeight!==a)&&this.resizePickingFbo(s,a),r.bindFramebuffer(36160,this.pickFbo),r.viewport(0,0,s,a),r.enable(2929),r.clearColor(0,0,0,0),r.clear(16640),r.useProgram(this.pickProg);for(let v=0;v<this.meshes.length;v++){let S=this.meshes[v];if(S.visible===!1||S.isPluginMesh)continue;let _=v+1,D=(_&255)/255,P=(_>>8&255)/255,N=(_>>16&255)/255;r.uniform4f(this.uPick.uColorId,D,P,N,1),fe(this.modelMatrix,this.modelRootMatrix,S.transform);let E=S.instanceMatrices;if(E&&E.length>=16){let F=E.length>>4,L=de();for(let M of S.primitives){r.bindVertexArray(M.vao);for(let O=0;O<F;O++)fe(L,this.modelMatrix,E.subarray(O*16,O*16+16)),fe(this.mvpMatrix,o,L),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),it(r,M)}}else{fe(this.mvpMatrix,o,this.modelMatrix),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let F of S.primitives)r.bindVertexArray(F.vao),it(r,F)}}let u=new Uint8Array(4);r.readPixels(l,h,1,1,6408,5121,u),r.bindFramebuffer(36160,null);let m=u[0]+(u[1]<<8)+(u[2]<<16);m>0&&m<=this.meshes.length&&(n=[this.meshes[m-1]])}n.length===0&&(n=this.meshes.filter(u=>u.visible!==!1));let c=null,f=1/0,g=[0,0,0],w=[0,1,0],[d,p,A]=Xe(this),b=de();for(let u of n){fe(b,this.modelRootMatrix,u.transform);let m=u.instanceMatrices,v=m&&m.length>=16?m.length>>4:1;for(let S=0;S<v;S++){m&&m.length>=16?fe(this.modelMatrix,b,m.subarray(S*16,S*16+16)):this.modelMatrix.set(b),fe(this.mvpMatrix,o,this.modelMatrix);let _=de();if(!Rr(_,this.mvpMatrix))continue;let D=(l+.5)/s*2-1,P=(h+.5)/a*2-1,N=[0,0,0],E=[0,0,0];Xt(N,D,P,-1,_),Xt(E,D,P,1,_);let F=E[0]-N[0],L=E[1]-N[1],M=E[2]-N[2],O=Math.hypot(F,L,M)||1,H=F/O,R=L/O,C=M/O,y={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((T=>{for(let z of u.primitives){if(!z.positions)continue;let G=z.positions,B=z.indices,te=Math.floor(B?B.length/3:G.length/9);for(let I=0;I<te;I++){let W=B?B[I*3]:I*3,Z=B?B[I*3+1]:I*3+1,ae=B?B[I*3+2]:I*3+2;Tr(N[0],N[1],N[2],H,R,C,G[W*3],G[W*3+1],G[W*3+2],G[Z*3],G[Z*3+1],G[Z*3+2],G[ae*3],G[ae*3+1],G[ae*3+2],y,T)}}})(1e-4),isFinite(y.distance)){let T=y.point[0],z=y.point[1],G=y.point[2],B=this.modelMatrix,te=B[0]*T+B[4]*z+B[8]*G+B[12],I=B[1]*T+B[5]*z+B[9]*G+B[13],W=B[2]*T+B[6]*z+B[10]*G+B[14],Z=te-d,ae=I-p,U=W-A,ee=Math.hypot(Z,ae,U);if(ee<f){Ne(this.normalMatrix,this.modelMatrix);let $=this.normalMatrix,q=y.normal[0],X=y.normal[1],k=y.normal[2],V=$[0]*q+$[3]*X+$[6]*k,j=$[1]*q+$[4]*X+$[7]*k,K=$[2]*q+$[5]*X+$[8]*k,Q=Math.hypot(V,j,K)||1;V/=Q,j/=Q,K/=Q,V*Z+j*ae+K*U>0&&(V=-V,j=-j,K=-K),c=u,f=Math.round(ee*1e3)/1e3,g=[Math.round(te*1e3)/1e3,Math.round(I*1e3)/1e3,Math.round(W*1e3)/1e3],w=[Math.round(V*1e3)/1e3,Math.round(j*1e3)/1e3,Math.round(K*1e3)/1e3]}}}}if(!c)return null;let x={meshIndex:this.meshes.indexOf(c),meshName:c.name,nodeIndex:c.nodeIndex,distance:f,hitPoint:g,normal:w,screenX:t,screenY:e};if(i){for(let u of me)u.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(t,e){if(!this.stereoSBS||this.xrSessionActive||e<2)return t;let i=Math.max(1,Math.floor(e*.5)),r=t>=i,s=r?t-i:t,a=r?Math.max(1,e-i):i,o=(s+.5)/a*2-1;return Math.floor((o*.5+1)*.5*e)}setStereoSBS(t){this.stereoSBS=!!t,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let t=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),e=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);wt(this.projMatrix,this.fov,t,.1,e);let i=this.customTarget||this.bounds.center;tt(this.viewMatrix,Xe(this),i,[0,1,0]),fe(this.mvpMatrix,this.projMatrix,this.viewMatrix),Ne(this.normalMatrix,this.modelMatrix)}resize(){let t=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),e=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.floor(e.width*t)),r=Math.max(1,Math.floor(e.height*t));this.canvas.width!==i||this.canvas.height!==r?(this.canvas.width=i,this.canvas.height=r,this.resizePickingFbo(i,r),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(t){let e=this.xrSessionActive;if(this.xrSessionActive=t,e&&!t){this.xrDepthState.enabled=!1;for(let i of me)i.onXRSessionEnd?.(this);if(this.lastTime=typeof performance<"u"?performance.now():Date.now(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(i){this.reportRenderError(i)}}}reportRenderError(t){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",t))}stepXRUpdate(t){for(let e of me)e.onUpdate?.(this,t)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let t=e=>{if(this.animFrameId===null)return;let i=Math.min(Math.max((e-this.lastTime)/1e3,0),.1);if(this.lastTime=e,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(i),this.render()}catch(r){this.reportRenderError(r)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(t))};this.animFrameId=requestAnimationFrame(t)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(t){this.autoRotate=t}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(t){this.autoRotateSpeed=t}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(t){this.autoRotateDelay=Math.max(0,Number(t)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(t=0){this.turntableRotation=Number(t)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let t=Math.cos(this.turntableRotation),e=Math.sin(this.turntableRotation),i=this.bounds.center[0],r=this.bounds.center[2],s=this.modelRootMatrix;s[0]=t,s[1]=0,s[2]=-e,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=e,s[9]=0,s[10]=t,s[11]=0,s[12]=i-(t*i+e*r),s[13]=0,s[14]=r-(-e*i+t*r),s[15]=1}setVisible(t){this.isVisible=t}update(t){for(let a of me)a.onUpdate?.(this,t);let e=typeof performance<"u"?performance.now():Date.now();if(!this.isPointerDown&&this.autoRotate&&e-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*t,this.updateTurntableMatrix();for(let a of me)a.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 i=Math.round((this.currTheta*180/Math.PI%360+360)%360),r=Math.round(this.currPhi*180/Math.PI),s=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(i-this.lastReportedTheta)>=1||Math.abs(r-this.lastReportedPhi)>=1||Math.abs(s-this.lastReportedZoom)>=.02){this.lastReportedTheta=i,this.lastReportedPhi=r,this.lastReportedZoom=s;let a={theta:i,phi:r,zoom:s,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(a),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:a}))}}renderXRView(t,e,i,r,s=!0,a=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(t);let o=t?.transform?.inverse?.matrix||this.viewMatrix,n=t?.projectionMatrix||this.projMatrix,l=t?.transform?.position,h=l?[l.x,l.y,l.z]:[0,1.6,0];e?this.modelRootMatrix.set(e):i&&e&&this.modelRootMatrix.set(e),this.render({viewMatrix:o,projMatrix:n,eyePos:h,viewport:r,eye:t?.eye||"none",clear:a>0?!1:t?.eye!=="right",isAR:s})}render(t){if(this.contextLost)return;if(!t&&this.stereoSBS){let x=Math.max(2,this.canvas.width||2),u=Math.max(1,this.canvas.height||1),m=Math.max(1,Math.floor(x*.5)),v=Math.max(1,x-m),S=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),_=this.customTarget||this.bounds.center,[D,P,N]=Xe(this),E=Math.cos(this.currTheta),F=-Math.sin(this.currTheta),L=.032,M=de(),O=de(),H=[D-E*L,P,N-F*L],R=[_[0]-E*L*.25,_[1],_[2]-F*L*.25];wt(M,this.fov,m/u,.1,S),tt(O,H,R,[0,1,0]);let C=de(),y=de(),T=[D+E*L,P,N+F*L],z=[_[0]+E*L*.25,_[1],_[2]+F*L*.25];wt(C,this.fov,v/u,.1,S),tt(y,T,z,[0,1,0]),this.render({viewMatrix:O,projMatrix:M,eyePos:H,viewport:[0,0,m,u],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:y,projMatrix:C,eyePos:T,viewport:[m,0,v,u],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,x,u);return}let e=this.gl,i=0,r=0,s=this.canvas.width,a=this.canvas.height;t?.viewport?(i=t.viewport[0],r=t.viewport[1],s=t.viewport[2],a=t.viewport[3],e.viewport(i,r,s,a)):e.viewport(0,0,this.canvas.width,this.canvas.height),e.enable(2929),(!t||t.clear!==!1)&&(t?.isAR?e.clearColor(0,0,0,0):e.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),e.clear(16640));let o=de(),n=t?.viewMatrix??this.viewMatrix;this.activeViewMatrix=n,fe(o,t?.projMatrix??this.projMatrix,n);let l=he().xrDepthShader,h=_r(this.toneMapping),[c,f,g]=t?t.eyePos:Xe(this);for(let x of me)x.onBeforeDrawScene?.(this,e,o,[c,f,g],h);let w=t?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&w===0)return;let d=t?.eye||"none",p=!1,A=w>0?[...this.backdropMeshes,...this.meshes]:this.meshes,b=x=>{for(let u=0;u<A.length;u++){let m=A[u];if(m.visible===!1)continue;let v=this.selectedMeshName!==""&&m.name===this.selectedMeshName;u<w||m.worldSpace===!0||m.name==="__xr_reticle__"?this.modelMatrix.set(m.transform):fe(this.modelMatrix,this.modelRootMatrix,m.transform),fe(this.mvpMatrix,o,this.modelMatrix),Ne(m.normalMatrix,this.modelMatrix);let S=m.extras?.xr?.stereo||m.userData?.xr?.stereo,_=0,D=0,P=1,N=1;S==="sbs"?(P=.5,_=d==="right"?.5:0):S==="ou"&&(N=.5,D=d==="right"?.5:0);for(let E of m.primitives){let F=!!E.isTransmissive;if(!x&&F){p=!0;continue}if(x&&!F)continue;let L=E.customProgram||this.renderProg,M=E.customUniforms||this.uRender;e.useProgram(L),e.vertexAttrib3f(3,0,0,0),M.uInstanced&&e.uniform1i(M.uInstanced,0),e.uniform1i(M.uToneMapping,h),e.uniform1f(M.uEnvIntensity,this.envIntensity),M.uExposure&&e.uniform1f(M.uExposure,this.exposure),e.uniform3f(M.uCameraPos,c,f,g),e.uniform1f(M.uEmissive,v?1:0),e.uniformMatrix4fv(M.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(M.uModel,!1,this.modelMatrix),e.uniformMatrix3fv(M.uNormalMatrix,!1,m.normalMatrix),M.uUvTransform&&e.uniform4f(M.uUvTransform,_,D,P,N),M.uViewportSize&&e.uniform2f(M.uViewportSize,Math.max(1,s),Math.max(1,a)),l?.bind(e,M,this.xrDepthState,n,[i,r,Math.max(1,s),Math.max(1,a)]),this.environmentTexture?(e.activeTexture(33988),e.bindTexture(3553,this.environmentTexture),e.uniform1i(M.uEnvironmentMap,4),e.uniform1i(M.uHasEnvironmentMap,1)):e.uniform1i(M.uHasEnvironmentMap,0),this.bindLights(M),M.uSectionEnabled&&e.uniform1i(M.uSectionEnabled,0);for(let H of me)H.onBeforeDrawPrimitive?.(e,L,E,m,this.worldMatrices||[],this.gltf);e.uniform4fv(M.uBaseColor,E.baseColor),e.uniform1f(M.uMetallic,E.metallic),e.uniform1f(M.uRoughness,E.roughness),M.uClearcoat&&e.uniform2f(M.uClearcoat,E.clearcoat??0,E.clearcoatRoughness??.04),E.texture?(e.activeTexture(33984),e.bindTexture(3553,E.texture),e.uniform1i(M.uBaseColorTexture,0),e.uniform1i(M.uHasTexture,1)):e.uniform1i(M.uHasTexture,0),E.metallicRoughnessTexture?(e.activeTexture(33985),e.bindTexture(3553,E.metallicRoughnessTexture),e.uniform1i(M.uMetallicRoughnessTexture,1),e.uniform1i(M.uHasMetallicRoughnessTexture,1)):e.uniform1i(M.uHasMetallicRoughnessTexture,0),E.normalTexture?(e.activeTexture(33986),e.bindTexture(3553,E.normalTexture),e.uniform1i(M.uNormalTexture,2),e.uniform1i(M.uHasNormalTexture,1),e.uniform1f(M.uNormalScale,E.normalScale)):e.uniform1i(M.uHasNormalTexture,0),E.occlusionTexture?(e.activeTexture(33987),e.bindTexture(3553,E.occlusionTexture),e.uniform1i(M.uOcclusionTexture,3),e.uniform1i(M.uHasOcclusionTexture,1),e.uniform1f(M.uOcclusionStrength,E.occlusionStrength)):e.uniform1i(M.uHasOcclusionTexture,0),e.bindVertexArray(E.vao);let O=m.instanceMatrices;if(E.instanceCount!==void 0)e.drawElementsInstanced(4,E.indexCount,E.indexType,0,E.instanceCount);else if(O&&O.length>=16&&E.instanced&&M.uInstanced&&M.uViewProj){let H=O.length>>4;e.uniform1i(M.uInstanced,1),e.uniformMatrix4fv(M.uViewProj,!1,o),E.indices?e.drawElementsInstanced(4,E.indexCount,E.indexType,0,H):e.drawArraysInstanced(4,0,E.indexCount,H),e.uniform1i(M.uInstanced,0)}else if(O&&O.length>=16){let H=O.length>>4,R=m.instanceColors,C=de(),y=new Float32Array(9),T=[E.baseColor[0],E.baseColor[1],E.baseColor[2],E.baseColor[3]];for(let z=0;z<H;z++)fe(C,this.modelMatrix,O.subarray(z*16,z*16+16)),fe(this.mvpMatrix,o,C),Ne(y,C),e.uniformMatrix4fv(M.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(M.uModel,!1,C),e.uniformMatrix3fv(M.uNormalMatrix,!1,y),R&&(T[0]=E.baseColor[0]*R[z*3],T[1]=E.baseColor[1]*R[z*3+1],T[2]=E.baseColor[2]*R[z*3+2],T[3]=E.baseColor[3],e.uniform4fv(M.uBaseColor,T)),it(e,E)}else it(e,E)}}};if(b(!1),p){for(let x of me)x.onBeforeTransmissivePass?.(e,this);b(!0)}for(let x of me)x.onAfterRender?.(e,this,o,t?.eye??"none",[i,r,s,a],t?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(t,e){si(this.gl,t,e)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let t=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let e of me)e.onDestroy?.(t,this);this.environmentTexture&&(t.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&t.deleteProgram(this.renderProg),this.pickProg&&t.deleteProgram(this.pickProg),this.pickFbo&&t.deleteFramebuffer(this.pickFbo),this.pickTexture&&t.deleteTexture(this.pickTexture),this.pickDepth&&t.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};Se.registerPlugin=Ht,Se.getRegisteredPlugins=yr;function Hr(t){return t+3&-4}var ie=(t,e)=>typeof t=="number"&&Number.isFinite(t)?t:e;function ni(t,e){let i=e,r=1;for(;t.has(i);)i=`${e}_${r++}`;return t.add(i),i}function oi(t,e=0){let[i,r,s,,a,o,n,,l,h,c,,f,g,w]=Array.from({length:15},(y,T)=>ie(t[e+T],T%5===0?1:0)),d=Math.hypot(i,r,s),p=Math.hypot(a,o,n),A=Math.hypot(l,h,c);i*(o*c-h*n)-a*(r*c-h*s)+l*(r*n-o*s)<0&&(d=-d);let b=Math.abs(d)>1e-8?1/d:0,x=Math.abs(p)>1e-8?1/p:0,u=Math.abs(A)>1e-8?1/A:0,m=i*b,v=r*b,S=s*b,_=a*x,D=o*x,P=n*x,N=l*u,E=h*u,F=c*u,L=m+D+F,M=0,O=0,H=0,R=1;if(L>0){let y=.5/Math.sqrt(L+1);R=.25/y,M=(P-E)*y,O=(N-S)*y,H=(v-_)*y}else if(m>D&&m>F){let y=2*Math.sqrt(Math.max(0,1+m-D-F));y>1e-8&&(R=(P-E)/y,M=.25*y,O=(_+v)/y,H=(N+S)/y)}else if(D>F){let y=2*Math.sqrt(Math.max(0,1+D-m-F));y>1e-8&&(R=(N-S)/y,M=(_+v)/y,O=.25*y,H=(P+E)/y)}else{let y=2*Math.sqrt(Math.max(0,1+F-m-D));y>1e-8&&(R=(v-_)/y,M=(N+S)/y,O=(P+E)/y,H=.25*y)}let C=Math.hypot(M,O,H,R);return C>1e-8&&Number.isFinite(C)?(M/=C,O/=C,H/=C,R/=C):(M=0,O=0,H=0,R=1),{t:[f,g,w],r:[M,O,H,R],s:[d,p,A]}}function jr(t){let e={};return t.grab&&(e.interactable={mode:typeof t.grab=="string"?t.grab:"2-hand"},e.movable={scaleInZ:!!t.scale,minScale:typeof t.scale=="object"?t.scale.min??.1:.1,maxScale:typeof t.scale=="object"?t.scale.max??10:10}),t.billboard&&(e.billboard={mode:typeof t.billboard=="string"?t.billboard:"capsule"}),t.follow&&(e.follow={target:typeof t.follow=="object"?t.follow.mode??"head":t.follow}),t.anchor&&(e.anchor={plane:t.anchor}),t.physics&&t.physics!=="none"&&(e.rigidbody={type:t.physics}),e}var Le=(t,e,i,r)=>typeof t=="number"&&Number.isFinite(t)?Math.max(e,Math.min(i,t)):r;function li(t){let e=t?.audioEmitter??t?.spatialAudio??(typeof t?.audio=="object"&&t.audio&&("preset"in t.audio||"distanceModel"in t.audio||"coneInnerAngle"in t.audio||"maxDistance"in t.audio||"volume"in t.audio)?t.audio:typeof t?.audio=="string"&&/^(hum|reactor|wind|beacon|geiger|chimeLoop|machinery|water)$/.test(t.audio)?{preset:t.audio}:void 0);if(!e||typeof e=="object"&&e.enabled===!1)return null;let i=typeof e=="string"?{preset:e}:e,r=typeof i.src=="string"&&!/[\x00-\x20\\%]|^\s*(javascript|data|file|http):/i.test(i.src)?i.src:void 0,s=typeof i.preset=="string"?i.preset:void 0;return!r&&!s?null:{ae:i,src:r,preset:s,volume:Le(i.volume,0,2,.6),loop:typeof i.loop=="boolean"?i.loop:!0,isGlobal:i.type==="global"||i.positional===!1}}function rt(t,e){return hi(t,e)[0]}function hi(t,e){t.updateMatrixWorld(!0);let i=[],r=0,s=[],a=[],o=[],n=[],l=new Set,h=[],c=[],f=new Map,g=[],w=[],d=[],p=new Map,A=[],b=[];function x(R){let C=f.get(R);if(C!==void 0)return C;C=c.length,f.set(R,C);let y=R,T=y.color?.r??1,z=y.color?.g??1,G=y.color?.b??1,B=y.opacity??1,te={baseColorFactor:[T,z,G,B],metallicFactor:y.metalness??0,roughnessFactor:y.roughness??.5},I={},W=V=>{if(!V)return;let j=(typeof V=="string"?V:typeof V.source=="string"?V.source:typeof V.image=="string"?V.image:"").trim();if(!j||/[\x00-\x1f\x7f\\]|\.\./.test(j)||!(/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(j)||!j.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(j)))return;let K=p.get(j);if(K===void 0){let Q=g.length;g.push({uri:j}),w.length===0&&w.push({magFilter:9729,minFilter:9987,wrapS:10497,wrapT:10497}),K=d.length,d.push({sampler:0,source:Q}),p.set(j,K)}return{index:K}},Z=W(y.map);Z&&(te.baseColorTexture=Z);let ae=W(y.roughnessMap||y.metalnessMap);ae&&(te.metallicRoughnessTexture=ae);let U=y.map?.avgColor;Array.isArray(U)&&U.length>=3&&(I.avgColor=[U[0],U[1],U[2]]);let ee=W(y.normalMap),$=W(y.emissiveMap),q=W(y.aoMap),X={name:y.name||"",pbrMetallicRoughness:te,doubleSided:y.side===2||!!y.doubleSided,...ee?{normalTexture:ee}:{},...$?{emissiveTexture:$}:{},...q?{occlusionTexture:q}:{},...Object.keys(I).length>0?{extras:I}:{}};if(y.emissive&&(y.emissive.r>0||y.emissive.g>0||y.emissive.b>0)){let V=y.emissiveIntensity??1;X.emissiveFactor=[y.emissive.r*V,y.emissive.g*V,y.emissive.b*V]}let k={};return y.clearcoat&&y.clearcoat>0&&(k.KHR_materials_clearcoat={clearcoatFactor:y.clearcoat,clearcoatRoughnessFactor:y.clearcoatRoughness||0}),y.sheen&&y.sheen>0&&(k.KHR_materials_sheen={sheenColorFactor:y.sheenColor?[y.sheenColor.r,y.sheenColor.g,y.sheenColor.b]:[1,1,1],sheenRoughnessFactor:y.sheenRoughness||0}),y.transmission&&y.transmission>0&&(k.KHR_materials_transmission={transmissionFactor:y.transmission}),y.thickness&&y.thickness>0&&(k.KHR_materials_volume={thicknessFactor:y.thickness,attenuationDistance:y.attenuationDistance??1/0,attenuationColor:y.attenuationColor?[y.attenuationColor.r,y.attenuationColor.g,y.attenuationColor.b]:[1,1,1]}),y.ior!==void 0&&y.ior!==1.5&&(k.KHR_materials_ior={ior:y.ior}),y.dispersion&&y.dispersion>0&&(k.KHR_materials_dispersion={dispersion:y.dispersion}),y.iridescence&&y.iridescence>0&&(k.KHR_materials_iridescence={iridescenceFactor:y.iridescence,iridescenceIor:y.iridescenceIOR??1.3}),Object.keys(k).length>0&&(X.extensions=k),c.push(X),C}function u(R,C){let y=new Uint8Array(R.buffer,R.byteOffset,R.byteLength),T=Hr(y.byteLength),z=new Uint8Array(T);z.set(y),i.push(z);let G=s.length;return s.push({buffer:0,byteOffset:r,byteLength:y.byteLength,target:C}),r+=T,G}function m(R,C,y,T,z,G,B){let te=u(R,y),I=a.length,W={bufferView:te,byteOffset:0,componentType:T,count:z,type:C};return G&&(W.min=G),B&&(W.max=B),a.push(W),I}t.traverse(R=>{if(R.isLight||R.color&&R.intensity!==void 0){let C=R.matrixWorld?.elements,y=ie(C?C[12]:R.position?.x,0),T=ie(C?C[13]:R.position?.y,0),z=ie(C?C[14]:R.position?.z,0),G=R.target,B=G?.parent?G?.matrixWorld?.elements:void 0,te=ie(B?B[12]:G?.position?.x,0),I=ie(B?B[13]:G?.position?.y,0),W=ie(B?B[14]:G?.position?.z,0),Z=te-y,ae=I-T,U=W-z,ee=Math.hypot(Z,ae,U),$=Math.max(.01,Math.min(Math.PI/2,ie(R.angle,Math.PI/3))),q=Math.max(0,Math.min(1,ie(R.penumbra,0)));b.push({type:R.type,color:[R.color.r,R.color.g,R.color.b],intensity:R.intensity,position:[y,T,z],...R.type==="spot"?{direction:ee>1e-6?[Z/ee,ae/ee,U/ee]:[0,-1,0],outerConeAngle:$,innerConeAngle:Math.max(0,$*(1-q)),range:Math.max(0,ie(R.distance,0))}:R.type==="point"?{range:Math.max(0,ie(R.distance,0))}:{}})}});let v=[],S=new Set([t]),_=[];if(Array.isArray(t.children))for(let R=t.children.length-1;R>=0;R--)_.push({obj:t.children[R],parentKids:v});for(;_.length>0;){let{obj:R,parentKids:C}=_.pop();if(!R||typeof R!="object"||S.has(R))continue;S.add(R),R._bakeAuthorGeometry?.(),he().materializeDeclarativeGeometry?.(R);let y=!!(R.userData&&(R.userData.xr&&typeof R.userData.xr=="object"&&Object.keys(R.userData.xr).length>0||R.userData.interactivity&&typeof R.userData.interactivity=="object"&&Object.keys(R.userData.interactivity).length>0)),T={name:R.name||(y?`Node_${n.length}`:"")},z=ie(R.position?.x,0),G=ie(R.position?.y,0),B=ie(R.position?.z,0),te=ie(R.quaternion?.x,0),I=ie(R.quaternion?.y,0),W=ie(R.quaternion?.z,0),Z=ie(R.quaternion?.w,1),ae=ie(R.scale?.x,1),U=ie(R.scale?.y,1),ee=ie(R.scale?.z,1);if((z||G||B)&&(T.translation=[z,G,B]),(te||I||W||Z!==1)&&(T.rotation=[te,I,W,Z]),(ae!==1||U!==1||ee!==1)&&(T.scale=[ae,U,ee]),R.visible===!1&&(T.extensions={...T.extensions||{},KHR_node_visibility:{visible:!1}},l.add("KHR_node_visibility")),R.userData&&Object.keys(R.userData).length>0&&(T.extras=JSON.parse(JSON.stringify(R.userData,(X,k)=>{if(!(X==="__proto__"||X==="prototype"||X==="constructor"))return typeof k=="function"?void 0:k})),R.userData.xr)){let X=jr(R.userData.xr);T.extensions={...T.extensions||{},MOZ_hubs_components:X,ANDROID_xr_scenecore:X},he().xrTraitSerializer?.gltfNode(T,R.userData.xr),l.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(R.geometry){let X=R.geometry,k=X.attributes.position;if(k&&k.count>0){let V=[1/0,1/0,1/0],j=[-1/0,-1/0,-1/0];for(let se=0;se<k.count;se++){let ne=k.getX(se),oe=k.getY(se),le=k.getZ(se);ne<V[0]&&(V[0]=ne),ne>j[0]&&(j[0]=ne),oe<V[1]&&(V[1]=oe),oe>j[1]&&(j[1]=oe),le<V[2]&&(V[2]=le),le>j[2]&&(j[2]=le)}let K={attributes:{POSITION:m(k.array,"VEC3",34962,5126,k.count,V,j)}};if(X.attributes.normal&&(K.attributes.NORMAL=m(X.attributes.normal.array,"VEC3",34962,5126,X.attributes.normal.count)),X.attributes.uv&&(K.attributes.TEXCOORD_0=m(X.attributes.uv.array,"VEC2",34962,5126,X.attributes.uv.count)),X.index){let se=X.index.array instanceof Uint32Array;K.indices=m(X.index.array,"SCALAR",34963,se?5125:5123,X.index.count)}let Q=Array.isArray(R.material)?R.material[0]:R.material;Q&&(K.material=x(Q));let J=R.userData?.variants;if(J&&typeof J=="object"){let se=new Map;for(let ne of Object.keys(J)){if(!ne||ne==="__proto__"||ne==="constructor"||ne==="prototype")continue;let oe=J[ne];if(!oe||typeof oe!="object")continue;let le=A.indexOf(ne);if(le===-1&&A.length<256&&(le=A.length,A.push(ne)),le===-1)continue;let xe=x(oe),Te=se.get(xe);Te||(Te=[],se.set(xe,Te)),Te.push(le)}if(se.size>0){let ne=[];for(let[oe,le]of se.entries())ne.push({material:oe,variants:le});K.extensions={...K.extensions||{},KHR_materials_variants:{mappings:ne}},l.add("KHR_materials_variants")}}let Y=R;if(Y.isInstancedMesh&&typeof Y.count=="number"&&Y.count>0&&Y.instanceMatrix?.array){let se=Math.min(1e4,Math.floor(Y.count)),ne=Y.instanceMatrix.array,oe=new Float32Array(se*3),le=new Float32Array(se*4),xe=new Float32Array(se*3);for(let pe=0;pe<se;pe++){let{t:_e,r:je,s:zt}=oi(ne,pe*16);oe[pe*3]=_e[0],oe[pe*3+1]=_e[1],oe[pe*3+2]=_e[2],le[pe*4]=je[0],le[pe*4+1]=je[1],le[pe*4+2]=je[2],le[pe*4+3]=je[3],xe[pe*3]=zt[0],xe[pe*3+1]=zt[1],xe[pe*3+2]=zt[2]}let Te={TRANSLATION:m(oe,"VEC3",0,5126,se),ROTATION:m(le,"VEC4",0,5126,se),SCALE:m(xe,"VEC3",0,5126,se)};if(Y.instanceColor?.array&&Y.instanceColor.array.length>=se*3){let pe=new Float32Array(Y.instanceColor.array.subarray(0,se*3));Te._COLOR_0=m(pe,"VEC3",0,5126,se)}T.extensions={...T.extensions||{},EXT_mesh_gpu_instancing:{attributes:Te}},l.add("EXT_mesh_gpu_instancing")}let ue=o.length;o.push({primitives:[K],name:R.name,...T.extras?{extras:T.extras}:{}}),T.mesh=ue}}let $=n.length;n.push(T),h.push(R),C.push($);let q=R.children;if(Array.isArray(q)&&q.length>0){let X=[];T.children=X;for(let k=q.length-1;k>=0;k--)_.push({obj:q[k],parentKids:X})}}for(let R=0;R<n.length;R++){let C=n[R];C.children&&C.children.length===0?delete C.children:C.children&&C.children.length>0&&(C.extras?.xr?.lod||C.extensions?.ANDROID_xr_scenecore?.lod||h[R]?.isLOD)&&(C.extensions={...C.extensions||{},MSFT_lod:{ids:[...C.children]}},l.add("MSFT_lod"))}let D=e?.animateCallback||e?.animateFn||(typeof t.userData?.animate=="function"?t.userData.animate:typeof t.__animateFn=="function"?t.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0),P=[];if(typeof D=="function"&&h.length>0){let R=e?.duration??4,C=e?.fps??15,y=Math.max(2,Math.round(R*C)+1),T=new Float32Array(y),z=h.map(U=>[ie(U.position?.x,0),ie(U.position?.y,0),ie(U.position?.z,0),ie(U.quaternion?.x,0),ie(U.quaternion?.y,0),ie(U.quaternion?.z,0),ie(U.quaternion?.w,1),ie(U.scale?.x,1),ie(U.scale?.y,1),ie(U.scale?.z,1)]),G=h.map(()=>new Float32Array(y*3)),B=h.map(()=>new Float32Array(y*4)),te=h.map(()=>new Float32Array(y*3));for(let U=0;U<y;U++){let ee=U/(y-1)*R;T[U]=ee;try{D(ee)}catch{}for(let $=0;$<h.length;$++){let q=h[$];G[$][U*3]=ie(q.position?.x,0),G[$][U*3+1]=ie(q.position?.y,0),G[$][U*3+2]=ie(q.position?.z,0);let X=ie(q.quaternion?.x,0),k=ie(q.quaternion?.y,0),V=ie(q.quaternion?.z,0),j=ie(q.quaternion?.w,1),K=Math.hypot(X,k,V,j)||1;if(X/=K,k/=K,V/=K,j/=K,U>0){let Q=(U-1)*4,J=B[$];J[Q]*X+J[Q+1]*k+J[Q+2]*V+J[Q+3]*j<0&&(X=-X,k=-k,V=-V,j=-j)}B[$][U*4]=X,B[$][U*4+1]=k,B[$][U*4+2]=V,B[$][U*4+3]=j,te[$][U*3]=ie(q.scale?.x,1),te[$][U*3+1]=ie(q.scale?.y,1),te[$][U*3+2]=ie(q.scale?.z,1)}}for(let U=0;U<h.length;U++){let ee=h[U],$=z[U];ee.position?.set($[0],$[1],$[2]),ee.quaternion?.set($[3],$[4],$[5],$[6]),ee.scale?.set($[7],$[8],$[9])}t.updateMatrixWorld(!0);let I=null,W=()=>(I===null&&(I=m(T,"SCALAR",0,5126,y,[0],[R])),I),Z=[],ae=[];for(let U=0;U<h.length;U++){let ee=z[U],$=(X,k,V)=>X.some((j,K)=>Math.abs(j-ee[V+K%k])>1e-4),q=(X,k,V,j)=>{X&&ae.push({sampler:Z.push({input:W(),interpolation:"LINEAR",output:m(k,V,0,5126,y)})-1,target:{node:U,path:j}})};q($(G[U],3,0),G[U],"VEC3","translation"),q($(B[U],4,3),B[U],"VEC4","rotation"),q($(te[U],3,7),te[U],"VEC3","scale")}ae.length>0&&P.push({name:"ProceduralLoop",samplers:Z,channels:ae})}let N=Ar(n,o,t.userData),E=[],F=[],L=[];for(let R=0;R<n.length;R++){let C=n[R],y=li(C.extras?.xr);if(!y)continue;let{ae:T,src:z,preset:G,volume:B,loop:te,isGlobal:I}=y,W=C.name||`Node_${R}`,Z=F.length;F.push({name:`${W}_source`,gain:B,loop:te,autoPlay:typeof T.autoplay=="boolean"?T.autoplay:!0,...z!==void 0?{audio:E.push({uri:z})-1}:{},...G?{extras:{preset:G,pitch:Le(T.pitch,.25,4,1)}}:{}});let ae=L.length,U=Le(T.refDistance,.05,100,1),ee=Le(T.coneInnerAngle,0,360,360),$=Le(T.coneOuterAngle,ee,360,360);L.push({name:`${W}_emitter`,type:I?"global":"positional",gain:B,sources:[Z],...I?{}:{positional:{distanceModel:T.distanceModel==="linear"||T.distanceModel==="exponential"?T.distanceModel:"inverse",refDistance:U,maxDistance:Le(T.maxDistance,U,500,Math.max(U,25)),rolloffFactor:Le(T.rolloffFactor,0,10,1),coneInnerAngle:+(ee*Math.PI/180).toFixed(6),coneOuterAngle:+($*Math.PI/180).toFixed(6),coneOuterGain:Le(T.coneOuterGain,0,1,0)}}}),C.extensions={...C.extensions||{},KHR_audio_emitter:{emitter:ae}},l.add("KHR_audio_emitter")}let M={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:t.environmentIntensity}},scenes:[{nodes:v}],scene:0,nodes:n,meshes:o,materials:c,...g.length>0?{images:g}:{},...w.length>0?{samplers:w}:{},...d.length>0?{textures:d}:{},accessors:a,bufferViews:s,buffers:[{byteLength:r}],...P.length>0?{animations:P}:{},...N||l.size>0?{extensionsUsed:[...N?["KHR_interactivity"]:[],...l]}:{},...N||A.length>0||L.length>0?{extensions:{...N?{KHR_interactivity:N}:{},...A.length>0?{KHR_materials_variants:{variants:A.map(R=>({name:R}))}}:{},...L.length>0?{KHR_audio_emitter:{...E.length>0?{audio:E}:{},sources:F,emitters:L}}:{}}}:{}},O=new Uint8Array(r),H=0;for(let R of i)O.set(R,H),H+=R.byteLength;return[{gltf:M,bin:O.buffer,lights:b,environmentIntensity:t.environmentIntensity},h]}function Pt(t){return new TextEncoder().encode(t)}function Et(t,e){let{gltf:i,bin:r}=rt(t,e),s=JSON.stringify(i),a=Pt(s),o=(4-a.byteLength%4)%4,n=a.byteLength+o,l=20+n+8+r.byteLength,h=new Uint8Array(l),c=new DataView(h.buffer);c.setUint32(0,1179937895,!0),c.setUint32(4,2,!0),c.setUint32(8,l,!0),c.setUint32(12,n,!0),c.setUint32(16,1313821514,!0),h.set(a,20);for(let g=0;g<o;g++)h[20+a.byteLength+g]=32;let f=20+n;return c.setUint32(f,r.byteLength,!0),c.setUint32(f+4,5130562,!0),h.set(new Uint8Array(r),f+8),h}function Gr(t,e){let[i,r]=hi(t,e);return ui(i,r)}function ui(t,e){let i=[],r=t.gltf,s=he().decoders.get("meshopt");s&&typeof s.decodeBufferViews=="function"&&s.decodeBufferViews(r,t);let a=t.bin,o=a instanceof ArrayBuffer?a:a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),n=r.accessors||[],l=r.bufferViews||[],h=r.materials||[],c=r.meshes||[],f=r.nodes||[],g=r.textures||[],w=r.images||[],d=r.samplers||[],p=new Set,A=h.map((S,_)=>ni(p,st(S?.name,`Material_${_}`))),b=new Map;function x(S){let _=/^data:image\/(png|jpe?g)(?:;[^,]*)?;base64,([A-Za-z0-9+/=\s]+)$/i.exec(S);if(!_)return null;let D=_[2].replace(/\s+/g,""),P=D.endsWith("==")?2:D.endsWith("=")?1:0,N=new Uint8Array((D.length*3>>2)-P),E=L=>{let M=D.charCodeAt(L);return M>96?M-71:M>64?M-65:M>47?M+4:M===43?62:M===47?63:0},F=0;for(let L=0;L<D.length;L+=4){let M=E(L)<<18|E(L+1)<<12|E(L+2)<<6|E(L+3);N[F++]=M>>16&255,F<N.length&&(N[F++]=M>>8&255),F<N.length&&(N[F++]=M&255)}return N}function u(S,_,D){let P=S?.index;if(typeof P!="number")return;let N=g[P],E=N?.source;if(typeof E!="number"||!w[E])return;let F=b.get(E);if(F===void 0){F=null;let O=w[E],H=null;if(typeof O.bufferView=="number"){let R=l[O.bufferView],C=R?.byteOffset||0,y=R?.byteLength||0;R&&y>0&&C>=0&&C+y<=o.byteLength&&(H=new Uint8Array(o,C,y))}else typeof O.uri=="string"&&(H=x(O.uri));if(H&&H.byteLength>0){let R=H[0]===255&&H[1]===216&&H[2]===255||!(H[0]===137&&H[1]===80)&&/jpe?g/i.test(O.mimeType||O.uri||"");F={file:`texture_${E}.${R?"jpg":"png"}`,data:H}}b.set(E,F)}if(!F)return;let L=typeof N.sampler=="number"?d[N.sampler]:void 0,M=O=>O===33071?"clamp":O===33648?"mirror":"repeat";return{file:F.file,data:F.data,wrapS:M(L?.wrapS),wrapT:M(L?.wrapT),..._?{scale:_}:{},...D?{bias:D}:{}}}function m(S){let _=n[S];if(!_)throw new Error(`Accessor ${S} not found`);let D=l[_.bufferView||0],P=(D.byteOffset||0)+(_.byteOffset||0),N=D.byteLength||0;return{acc:_,buffer:o.slice(P,P+N)}}function v(S,_,D,P){let N=[],E=c[S];if(!E)return N;let F=E.primitives||[];for(let L=0;L<F.length;L++){let M=F[L],O=M.attributes?.POSITION;if(O===void 0)continue;let{acc:H,buffer:R}=m(O),C=new Float32Array(R,0,H.count*3),y,T=M.attributes?.NORMAL;if(T!==void 0){let{acc:k,buffer:V}=m(T),j=new Float32Array(V,0,k.count*3);y=new Float32Array(j.length);for(let K=0;K<k.count;K++){let Q=j[K*3],J=j[K*3+1],Y=j[K*3+2],ue=Math.hypot(Q,J,Y)||1;y[K*3]=Q/ue,y[K*3+1]=J/ue,y[K*3+2]=Y/ue}}let z,G=M.attributes?.TEXCOORD_0;if(G!==void 0){let{acc:k,buffer:V}=m(G);z=new Float32Array(V,0,k.count*2)}let B;if(M.indices!==void 0){let{acc:k,buffer:V}=m(M.indices);B=k.componentType===5125?new Uint32Array(V,0,k.count):new Uint16Array(V,0,k.count);let j=H.count;for(let K of B)if(K>=j)throw new Error(`SecurityError: Index buffer value (${K}) out of vertex bounds [0, ${j}).`)}else{let k=H.count;B=k>65535?new Uint32Array(k):new Uint16Array(k);for(let V=0;V<k;V++)B[V]=V}let te="DefaultMaterial",I=[1,1,1],W=.5,Z=0,ae=0,U=0,ee=1.5,$=1,q=[0,0,0],X;if(M.material!==void 0&&h[M.material]){let k=h[M.material];te=A[M.material]||`Material_${M.material}`;let V=k.pbrMetallicRoughness||{},j=(_e,je)=>Array.isArray(_e)&&_e.length>=3?[_e[0],_e[1],_e[2]]:je;I=j(V.baseColorFactor,[1,1,1]);let K=Array.isArray(V.baseColorFactor)&&typeof V.baseColorFactor[3]=="number"?V.baseColorFactor[3]:1,Q=I[0]!==1||I[1]!==1||I[2]!==1||K!==1,J=u(V.baseColorTexture,Q?[I[0],I[1],I[2],K]:void 0),Y=k.extras?.avgColor;!J&&Array.isArray(Y)&&Y.length>=3&&(I=[I[0]*Y[0],I[1]*Y[1],I[2]*Y[2]]),typeof V.roughnessFactor=="number"&&(W=V.roughnessFactor),typeof V.metallicFactor=="number"&&(Z=V.metallicFactor);let ue=typeof V.roughnessFactor=="number"?V.roughnessFactor:1,se=typeof V.metallicFactor=="number"?V.metallicFactor:1,ne=u(V.metallicRoughnessTexture,ue!==1||se!==1?[1,ue,se,1]:void 0);q=j(k.emissiveFactor,[0,0,0]);let oe=(q[0]>0||q[1]>0||q[2]>0)&&(q[0]!==1||q[1]!==1||q[2]!==1)?[q[0],q[1],q[2],1]:void 0,le=u(k.emissiveTexture,oe),xe=u(k.normalTexture,[2,2,2,1],[-1,-1,-1,0]),Te=u(k.occlusionTexture);(J||ne||xe||le||Te)&&(X=[J,ne,xe,le,Te]);let pe=k.extensions||{};pe.KHR_materials_clearcoat&&(ae=pe.KHR_materials_clearcoat.clearcoatFactor??0,U=pe.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),typeof pe.KHR_materials_ior?.ior=="number"&&(ee=pe.KHR_materials_ior.ior),$=K*(1-(pe.KHR_materials_transmission?.transmissionFactor??0))}N.push({name:F.length>1?`${_}_p${L}`:_,positions:C,indices:B,normals:y,uvs:z,materialName:te,color:I,roughness:W,metallic:Z,clearcoat:ae,clearcoatRoughness:U,ior:ee,opacity:$,emissiveColor:q,...X?{textures:X}:{},xrTraits:D||E.extras?.xr,...P?{invisible:!0}:{}})}return N}if(f.length>0){let S=new Float32Array(0),_=new Uint16Array(0),D=(C,y)=>{if(C===void 0)return null;let{acc:T,buffer:z}=m(C);return new Float32Array(z,0,T.count*y)},P=(C,y)=>Array.isArray(C)&&C.length>=3?[ie(C[0],y),ie(C[1],y),ie(C[2],y)]:[y,y,y],N=(C,y,T)=>C&&C.length>=(y+1)*3?[C[y*3],C[y*3+1],C[y*3+2]]:T,E=(C,y,T)=>C&&C.length>=(y+1)*4?[C[y*4],C[y*4+1],C[y*4+2],C[y*4+3]]:T,F=new Map,L=r.animations?.[0];if(L&&Array.isArray(L.channels)&&Array.isArray(L.samplers))for(let C of L.channels){let y=L.samplers[C?.sampler],T=C?.target?.node,z=C?.target?.path;if(!y||typeof T!="number"||y.input===void 0)continue;let G=F.get(T);G||(G={input:y.input},F.set(T,G)),z==="translation"?G.t=y.output:z==="rotation"?G.r=y.output:z==="scale"&&(G.s=y.output)}let M=r.scenes?.[r.scene??0]?.nodes??[];if(!Array.isArray(M)||M.length===0){let C=new Set;for(let y of f)if(Array.isArray(y?.children))for(let T of y.children)C.add(T);M=[];for(let y=0;y<f.length;y++)C.has(y)||M.push(y);M.length===0&&(M=[0])}let O=new Set,H=[],R=(C,y)=>{if(Array.isArray(C))for(let T=C.length-1;T>=0;T--)H.push({idx:C[T],out:y})};for(R(M,i);H.length>0;){let{idx:C,out:y}=H.pop();if(typeof C!="number"||C<0||C>=f.length||O.has(C))continue;O.add(C);let T=f[C];if(!T)continue;let z=[0,0,0],G=[0,0,0,1],B=[1,1,1];if(Array.isArray(T.matrix)&&T.matrix.length===16){let $=oi(T.matrix);z=$.t,G=$.r,B=$.s}else z=P(T.translation,0),Array.isArray(T.rotation)&&T.rotation.length>=4&&(G=[ie(T.rotation[0],0),ie(T.rotation[1],0),ie(T.rotation[2],0),ie(T.rotation[3],1)]),B=P(T.scale,1);let te,I=F.get(C);if(I){let $=D(I.input,1);if($&&$.length>0){let q=D(I.t,3),X=D(I.r,4),k=D(I.s,3),V=Array.from($),j=[],K=[],Q=[];for(let J=0;J<$.length;J++)j.push(N(q,J,z)),K.push(E(X,J,G)),Q.push(N(k,J,B));te={times:V,translations:j,rotations:K,scales:Q}}}let W=Array.isArray(T.children)?T.children:[],Z=typeof T.mesh=="number"&&T.mesh>=0&&T.mesh<c.length,ae=e?.[C]?.userData?.xr??T.extras?.xr;if(!Z&&W.length===0&&(T.camera!==void 0||T.extensions?.KHR_lights_punctual||!T.name&&!T.extras&&!ae&&!te))continue;let U=($,q,X)=>({name:$,positions:S,indices:_,isXform:!0,xrTraits:ae,timeSamples:te,translation:z,rotation:G,scale:B,children:q,...X?{invisible:!0}:{}}),ee=T.visible===!1||T.extensions?.KHR_node_visibility?.visible===!1||e?.[C]?.visible===!1;if(Z){let $=T.name||c[T.mesh]?.name||`Mesh_${C}`,q=v(T.mesh,$,ae,ee),X=T.extensions?.EXT_mesh_gpu_instancing?.attributes;if(X&&typeof X=="object"&&q.length>0){let k=D(X.TRANSLATION,3),V=D(X.ROTATION,4),j=D(X.SCALE,3),K=D(X._COLOR_0,3),Q=Math.min(1e3,k?k.length/3:V?V.length/4:j?j.length/3:0);if(Q>0){let J=[];for(let Y=0;Y<Q;Y++){let ue=N(k,Y,[0,0,0]),se=E(V,Y,[0,0,0,1]),ne=N(j,Y,[1,1,1]);for(let oe of q){let le=oe.color||[.8,.8,.8],xe=K&&K.length>=(Y+1)*3;J.push({...oe,name:`${oe.name}_${Y}`,materialName:xe?`${oe.materialName}_inst_${Y}`:oe.materialName,color:xe?[le[0]*K[Y*3],le[1]*K[Y*3+1],le[2]*K[Y*3+2]]:oe.color,translation:ue,rotation:se,scale:ne})}}R(W,J),y.push(U($,J,ee));continue}}if(q.length===1)q[0].translation=z,q[0].rotation=G,q[0].scale=B,q[0].timeSamples=te,W.length>0&&(q[0].children=[],R(W,q[0].children)),y.push(q[0]);else{let k=[...q];R(W,k),y.push(U($,k,ee))}}else{let $=[];R(W,$),y.push(U(T.name||`Group_${C}`,$,ee))}}}else for(let S=0;S<c.length;S++){let _=c[S].name||`Mesh_${S}`;i.push(...v(S,_,c[S].extras?.xr))}return i}function st(t,e){if(!t||typeof t!="string")return e;let i=t.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(i)&&(i="_"+i),i||e}function at(t){return String(t??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function ge(t){if(!Number.isFinite(t)||Math.abs(t)<1e-7)return"0";let e=Number(t.toFixed(5)).toString();return e.indexOf(".")===-1?`${e}.0`:e}var Ce=(t,e,i)=>`(${ge(t)}, ${ge(e)}, ${ge(i)})`,nt=(t,e,i,r)=>`(${ge(t)}, ${ge(e)}, ${ge(i)}, ${ge(r)})`;function ci(t){let e=t.length/3,i=new Array(e);for(let r=0;r<e;r++)i[r]=Ce(t[r*3],t[r*3+1],t[r*3+2]);return i.join(", ")}function Wr(t,e){let i=new Array(e);for(let r=0;r<e;r++)i[r]=`(${ge(t[r*2])}, ${ge(1-t[r*2+1])})`;return i.join(", ")}function Xr(t){return Array.from(t).join(", ")}function qr(t){let e=new Map,i=0,r=null,s=[...t];for(;s.length>0;){let d=s.pop();if(!d.isXform&&d.positions&&d.positions.length>0){let p=st(d.materialName,"DefaultMaterial");e.has(p)||e.set(p,{color:d.color||[1,1,1],roughness:d.roughness??.5,metallic:d.metallic??0,clearcoat:d.clearcoat??0,clearcoatRoughness:d.clearcoatRoughness??0,ior:d.ior??1.5,opacity:d.opacity??1,emissiveColor:d.emissiveColor||[0,0,0],textures:d.textures})}if(d.timeSamples&&d.timeSamples.times.length>0){let p=d.timeSamples.times[d.timeSamples.times.length-1];p>i&&(i=p)}if(d.xrTraits?.anchor&&!r&&(r=d.xrTraits.anchor==="vertical"||d.xrTraits.anchor==="wall"?"vertical":"horizontal"),d.children)for(let p=d.children.length-1;p>=0;p--)s.push(d.children[p])}let a="";i>0&&(a=`startTimeCode = 0
252
+ endTimeCode = ${ge(i)}
256
253
  timeCodesPerSecond = 1.0
257
- `);let s="";r&&(s=`uniform token preliminary:anchoring:type = "plane"
254
+ `);let o="";r&&(o=`uniform token preliminary:anchoring:type = "plane"
258
255
  uniform token preliminary:planeAnchoring:alignment = "${r}"
259
- `);let o=`#usda 1.0
256
+ `);let n=`#usda 1.0
260
257
  (
261
258
  defaultPrim = "Root"
262
259
  metersPerUnit = 1.0
263
260
  upAxis = "Y"
264
- ${i})
261
+ ${a})
265
262
 
266
263
  def Xform "Root" (
267
264
  kind = "component"
268
265
  )
269
266
  {
270
- ${s}def Scope "Materials"
267
+ ${o}def Scope "Materials"
268
+ {
269
+ `;for(let[d,p]of e.entries()){let[A,b,x]=p.color,[u,m,v]=p.emissiveColor,S=`/Root/Materials/${d}`,[_,D,P,N,E]=p.textures||[],F=(R,C)=>`.connect = <${S}/${R}.outputs:${C}>`,L=_?`color3f inputs:diffuseColor${F("DiffuseTexture","rgb")}`:`color3f inputs:diffuseColor = ${Ce(A,b,x)}`,M=D?`float inputs:metallic${F("MetallicRoughnessTexture","b")}
270
+ float inputs:roughness${F("MetallicRoughnessTexture","g")}`:`float inputs:metallic = ${ge(p.metallic)}
271
+ float inputs:roughness = ${ge(p.roughness)}`,O="";p.clearcoat>0&&(O+=`float inputs:clearcoat = ${ge(p.clearcoat)}
272
+ `,O+=`float inputs:clearcoatRoughness = ${ge(p.clearcoatRoughness)}
273
+ `),p.ior!==1.5&&(O+=`float inputs:ior = ${ge(p.ior)}
274
+ `),p.opacity<1&&(O+=`float inputs:opacity = ${ge(p.opacity)}
275
+ `),N?O+=`color3f inputs:emissiveColor${F("EmissiveTexture","rgb")}
276
+ `:(u>0||m>0||v>0)&&(O+=`color3f inputs:emissiveColor = ${Ce(u,m,v)}
277
+ `),P&&(O+=`normal3f inputs:normal${F("NormalTexture","rgb")}
278
+ `),E&&(O+=`float inputs:occlusion${F("OcclusionTexture","r")}
279
+ `);let H="";if(_||D||P||N||E){H+=`def Shader "PrimvarReader"
280
+ {
281
+ uniform token info:id = "UsdPrimvarReader_float2"
282
+ string inputs:varname = "st"
283
+ float2 outputs:result
284
+ }
285
+ `;let R=(C,y,T,z)=>{if(!y)return;let G=y.scale?`float4 inputs:scale = ${nt(y.scale[0],y.scale[1],y.scale[2],y.scale[3])}
286
+ `:"",B=y.bias?`float4 inputs:bias = ${nt(y.bias[0],y.bias[1],y.bias[2],y.bias[3])}
287
+ `:"";H+=`def Shader "${C}"
271
288
  {
272
- `;for(let[a,u]of e.entries()){let[l,m,h]=u.color,[b,y,d]=u.emissiveColor,g="";u.clearcoat>0&&(g+=`float inputs:clearcoat = ${K(u.clearcoat)}
273
- `,g+=`float inputs:clearcoatRoughness = ${K(u.clearcoatRoughness)}
274
- `),u.ior!==1.5&&(g+=`float inputs:ior = ${K(u.ior)}
275
- `),u.opacity<1&&(g+=`float inputs:opacity = ${K(u.opacity)}
276
- `),(b>0||y>0||d>0)&&(g+=`color3f inputs:emissiveColor = (${K(b)}, ${K(y)}, ${K(d)})
277
- `),o+=`def Material "${a}"
289
+ uniform token info:id = "UsdUVTexture"
290
+ asset inputs:file = @${at(y.file)}@
291
+ float2 inputs:st${F("PrimvarReader","result")}
292
+ token inputs:sourceColorSpace = "${T}"
293
+ token inputs:wrapS = "${y.wrapS||"repeat"}"
294
+ token inputs:wrapT = "${y.wrapT||"repeat"}"
295
+ ${G}${B}${z}}
296
+ `};R("DiffuseTexture",_,"sRGB",`float3 outputs:rgb
297
+ `),R("MetallicRoughnessTexture",D,"raw",`float outputs:g
298
+ float outputs:b
299
+ `),R("NormalTexture",P,"raw",`float3 outputs:rgb
300
+ `),R("EmissiveTexture",N,"sRGB",`float3 outputs:rgb
301
+ `),R("OcclusionTexture",E,"raw",`float outputs:r
302
+ `)}n+=`def Material "${d}"
278
303
  {
279
304
  def Shader "PBRShader"
280
305
  {
281
306
  uniform token info:id = "UsdPreviewSurface"
282
- color3f inputs:diffuseColor = (${K(l)}, ${K(m)}, ${K(h)})
283
- float inputs:metallic = ${K(u.metallic)}
284
- float inputs:roughness = ${K(u.roughness)}
285
- ${g}token outputs:surface
286
- }
287
- token outputs:surface.connect = </Root/Materials/${a}/PBRShader.outputs:surface>
307
+ ${L}
308
+ ${M}
309
+ ${O}token outputs:surface
288
310
  }
289
- `}o+=`}
311
+ token outputs:surface${F("PBRShader","surface")}
312
+ ${H}}
313
+ `}n+=`}
290
314
  def Scope "Meshes"
291
315
  {
292
- `;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,b=1/0,y=-1/0,d=-1/0,g=-1/0;for(let C=0;C<l;C++){let w=u.positions[C*3],R=u.positions[C*3+1],L=u.positions[C*3+2];w<m&&(m=w),w>y&&(y=w),R<h&&(h=R),R>d&&(d=R),L<b&&(b=L),L>g&&(g=L)}isFinite(m)||(m=h=b=-1,y=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,A="";if(p){let C=[];p.physics&&p.physics!=="none"&&C.push('prepend apiSchemas = ["PhysicsBodyAPI", "PhysicsCollisionAPI"]');let w=J().xrTraitSerializer?.usdLines(p,Xn)??[];if(!w.length)for(let R of["grab","billboard","follow","anchor","physics"]){let L=R==="follow"&&typeof p.follow=="object"?p.follow.mode??"head":p[R];L!==void 0&&w.push(`string ${R} = "${Xn(L)}"`)}w.length>0&&C.push(`customData = {
316
+ `;let l=(d,p,A)=>{let b=[];p&&b.push('"MaterialBindingAPI"');let x=!!(d?.rigidBody&&d.rigidBody!=="none"&&(typeof d.rigidBody!="object"||d.rigidBody.enabled!==!1)),u=!!(d?.physics&&d.physics!=="none"||x);u&&b.push(...x?['"PhysicsBodyAPI"','"PhysicsRigidBodyAPI"','"PhysicsCollisionAPI"','"PhysicsMassAPI"']:['"PhysicsBodyAPI"','"PhysicsCollisionAPI"']);let m=[];if(b.length>0&&m.push(`prepend apiSchemas = [${b.join(", ")}]`),d){let P=he().xrTraitSerializer?.usdLines(d,at)??[];if(!P.length)for(let N of["grab","billboard","follow","anchor","physics"]){let E=N==="follow"&&typeof d.follow=="object"?d.follow.mode??"head":d[N];E!==void 0&&P.push(`string ${N} = "${at(E)}"`)}P.length>0&&m.push(`customData = {
293
317
  dictionary xr = {
294
- ${w.join(`
318
+ ${P.join(`
295
319
  `)}
296
320
  }
297
- }`),C.length>0&&(A=` (
298
- ${C.join(`
321
+ }`)}let v=m.length>0?` (
322
+ ${m.join(`
299
323
  `)}
300
- )`)}if(o+=`def Mesh "${f}"${A}
301
- {
302
- `,p?.physics&&p.physics!=="none"){let C=p.physics==="static"?"true":"false";o+=`bool physics:rigidBodyEnabled = true
303
- bool physics:kinematicEnabled = ${C}
324
+ )`:"",S=A?`uniform token visibility = "invisible"
325
+ `:"";if(u){let P=d?.rigidBody??d?.physics,N=P?.body??P?.mode??P;S+=`bool physics:rigidBodyEnabled = true
326
+ bool physics:kinematicEnabled = ${N==="static"||N==="kinematic"}
304
327
  bool physics:collisionEnabled = true
305
- `}if(u.timeSamples&&u.timeSamples.times.length>0){let C=u.timeSamples,w=C.times.map((x,v)=>{let I=C.translations?.[v]||[0,0,0];return`${K(x)}: (${K(I[0])}, ${K(I[1])}, ${K(I[2])})`}).join(", "),R=C.times.map((x,v)=>{let I=C.rotations?.[v]||[0,0,0,1];return`${K(x)}: (${K(I[3])}, ${K(I[0])}, ${K(I[1])}, ${K(I[2])})`}).join(", "),L=C.times.map((x,v)=>{let I=C.scales?.[v]||[1,1,1];return`${K(x)}: (${K(I[0])}, ${K(I[1])}, ${K(I[2])})`}).join(", ");o+=`double3 xformOp:translate.timeSamples = { ${w} }
306
- quatf xformOp:orient.timeSamples = { ${R} }
307
- double3 xformOp:scale.timeSamples = { ${L} }
328
+ `,P?.mass>0&&Number.isFinite(P.mass)&&(S+=`float physics:mass = ${ge(P.mass)}
329
+ `)}let _=li(d),D=_?`def SpatialAudio "AudioEmitter"
330
+ {
331
+ ${_.src?`asset inputs:file = @${at(_.src)}@
332
+ `:""}uniform token inputs:auralMode = "${_.isGlobal?"nonSpatial":"spatial"}"
333
+ uniform token inputs:playbackMode = "${_.loop?"loopFromStart":"onceFromStart"}"
334
+ double gain = ${ge(_.volume)}
335
+ }
336
+ `:"";return{header:v,body:S,tail:D}},h=d=>{if(d.timeSamples&&d.timeSamples.times.length>0){let m=d.timeSamples,v=(P,N,E)=>m.times.map((F,L)=>`${ge(F)}: ${E(P?.[L]||N)}`).join(", "),S=v(m.translations,[0,0,0],P=>Ce(P[0],P[1],P[2])),_=v(m.rotations,[0,0,0,1],P=>{let N=Math.hypot(P[0],P[1],P[2],P[3])||1;return nt(P[3]/N,P[0]/N,P[1]/N,P[2]/N)}),D=v(m.scales,[1,1,1],P=>Ce(P[0],P[1],P[2]));return`double3 xformOp:translate.timeSamples = { ${S} }
337
+ quatf xformOp:orient.timeSamples = { ${_} }
338
+ double3 xformOp:scale.timeSamples = { ${D} }
308
339
  uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:orient", "xformOp:scale"]
309
- `}o+=`float3[] extent = [(${K(m)}, ${K(h)}, ${K(b)}), (${K(y)}, ${K(d)}, ${K(g)})]
310
- int[] faceVertexCounts = [${M}]
311
- int[] faceVertexIndices = [${zr(u.indices)}]
312
- point3f[] points = [${Wn(u.positions)}]
313
- `,u.normals&&u.normals.length===u.positions.length&&(o+=`normal3f[] normals = [${Wn(u.normals)}] (
340
+ `}let p=[],A="",b=d.translation;b&&(Math.abs(b[0])>1e-7||Math.abs(b[1])>1e-7||Math.abs(b[2])>1e-7)&&(A+=`double3 xformOp:translate = ${Ce(b[0],b[1],b[2])}
341
+ `,p.push('"xformOp:translate"'));let x=d.rotation;if(x){let m=Math.hypot(x[0],x[1],x[2],x[3])||1,v=x[0]/m,S=x[1]/m,_=x[2]/m,D=x[3]/m;(1-Math.abs(D)>1e-7||Math.hypot(v,S,_)>1e-7)&&(A+=`quatf xformOp:orient = ${nt(D,v,S,_)}
342
+ `,p.push('"xformOp:orient"'))}let u=d.scale;return u&&(Math.abs(u[0]-1)>1e-7||Math.abs(u[1]-1)>1e-7||Math.abs(u[2]-1)>1e-7)&&(A+=`float3 xformOp:scale = ${Ce(u[0],u[1],u[2])}
343
+ `,p.push('"xformOp:scale"')),p.length>0&&(A+=`uniform token[] xformOpOrder = [${p.join(", ")}]
344
+ `),A},c=d=>{let p=d.positions.length/3,A=1/0,b=1/0,x=1/0,u=-1/0,m=-1/0,v=-1/0;for(let N=0;N<p;N++){let E=d.positions[N*3],F=d.positions[N*3+1],L=d.positions[N*3+2];E<A&&(A=E),E>u&&(u=E),F<b&&(b=F),F>m&&(m=F),L<x&&(x=L),L>v&&(v=L)}isFinite(A)||(A=b=x=-1,u=m=v=1);let S=Math.floor(d.indices.length/3),_=st(d.materialName,"DefaultMaterial"),D=S>0?S===1?"3":"3, ".repeat(S-1)+"3":"",P=`float3[] extent = [${Ce(A,b,x)}, ${Ce(u,m,v)}]
345
+ int[] faceVertexCounts = [${D}]
346
+ int[] faceVertexIndices = [${Xr(d.indices)}]
347
+ point3f[] points = [${ci(d.positions)}]
348
+ `;return d.normals&&d.normals.length===d.positions.length&&(P+=`normal3f[] normals = [${ci(d.normals)}] (
314
349
  interpolation = "vertex"
315
350
  )
316
- `),u.uvs&&u.uvs.length===l*2&&(o+=`texCoord2f[] primvars:st = [${Vr(u.uvs,l)}] (
351
+ `),d.uvs&&d.uvs.length===p*2&&(P+=`texCoord2f[] primvars:st = [${Wr(d.uvs,p)}] (
317
352
  interpolation = "vertex"
318
353
  )
319
- `),o+=`rel material:binding = </Root/Materials/${P}>
320
- }
321
- `}return o+=`}
354
+ `),P+=`rel material:binding = </Root/Materials/${_}>
355
+ `,P},f=new Set,g=[];for(let d=t.length-1;d>=0;d--)g.push({node:t[d],siblings:f});let w=0;for(;g.length>0;){let d=g.pop();if(d.close){n+=`}
356
+ `;continue}let{node:p,siblings:A}=d,b=!!(p.isXform||p.positions.length===0),x=ni(A,st(p.name,b?`Group_${w}`:`Mesh_${w}`));w++;let u=p.children||[];if(b){let m=l(p.xrTraits,!1,p.invisible);n+=`def Xform "${x}"${m.header}
357
+ {
358
+ ${m.body}${h(p)}${m.tail}`,g.push({close:!0});let v=new Set;for(let S=u.length-1;S>=0;S--)g.push({node:u[S],siblings:v})}else if(u.length>0){let m=l(p.xrTraits,!1,p.invisible),v=`${x}_mesh`;n+=`def Xform "${x}"${m.header}
359
+ {
360
+ ${m.body}${h(p)}${m.tail}`,n+=`def Mesh "${v}" (
361
+ prepend apiSchemas = ["MaterialBindingAPI"]
362
+ )
363
+ {
364
+ ${c(p)}}
365
+ `,g.push({close:!0});let S=new Set([v]);for(let _=u.length-1;_>=0;_--)g.push({node:u[_],siblings:S})}else{let m=l(p.xrTraits,!0,p.invisible);n+=`def Mesh "${x}"${m.header}
366
+ {
367
+ ${m.body}${h(p)}${c(p)}${m.tail}}
368
+ `}}return n+=`}
322
369
  }
323
- `,o}function Yn(n,e){if(n&&typeof n.traverse=="function"){let i=Br(n,e);return Ot(i)}let t=Re(n),r=$n(t);return Ot(r)}var it=null;function qn(n){if(!it){it=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;it[t]=r}}let e=4294967295;for(let t=0;t<n.length;t++)e=it[(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=st(l.filename),h=qn(l.data),b=l.data.length,y=30+m.length,d=t+y,g=0,T=d%64;T!==0&&(g=64-T);let P=new Uint8Array(y+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,b,!0),f.setUint32(22,b,!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:b,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=st(e);return Bt([{filename:"model.usda",data:t}])}function at(n){let e=Re(n),t=$n(e),r=Ot(t),i=st(r);return Bt([{filename:"model.usda",data:i}])}function ct(n){return n&&typeof n.toUSDZ=="function"?n.toUSDZ():n&&typeof n.traverse=="function"?qe(n):at(n)}function Ue(n){let e=ct(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}},ue=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)}lerp(e,t){return this.lerpVectors(this,e,t)}lerpVectors(e,t,r){return this.x=e.x+(t.x-e.x)*r,this.y=e.y+(t.y-e.y)*r,this.z=e.z+(t.z-e.z)*r,this}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}},ht=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}},mt=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.set(e.x*i,e.y*i,e.z*i,Math.cos(r))}normalize(){let e=Math.hypot(this._x,this._y,this._z,this._w);return e===0?this.set(0,0,0,1):this.set(this._x/e,this._y/e,this._z/e,this._w/e)}setFromUnitVectors(e,t){let r=e.dot(t)+1;return r<1e-6?(Math.abs(e.x)>Math.abs(e.z)?this.set(-e.y,e.x,0,0):this.set(0,-e.z,e.y,0)).normalize():this.set(e.y*t.z-e.z*t.y,e.z*t.x-e.x*t.z,e.x*t.y-e.y*t.x,r).normalize()}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}},Oe=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 Ce(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 oe(this.elements,e.elements,t.elements),this}lookAt(e,t,r){return ke(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 ue(0,0,0),r=new ue(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)},pe=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 pe{constructor(e,t){super(e instanceof Float32Array?e:new Float32Array(e),t)}},$t=class extends pe{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},Yt=class extends pe{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 pe)this.index=e;else if(Array.isArray(e)){let t=0;for(let r of e)r>t&&(t=r);this.index=new pe(new(t>65535?Uint32Array:Uint16Array)(e),1)}else e&&e.buffer&&(this.index=new pe(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 ue,s=new ue,o=new ue,c=new ue,a=new ue;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],b=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(b),e.getY(b),e.getZ(b)),c.subVectors(o,s),a.subVectors(i,s),c.cross(a).normalize();for(let y of[m,h,b])r[y*3]+=c.x,r[y*3+1]+=c.y,r[y*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],b=Math.hypot(l,m,h)||1;r[u*3]=l/b,r[u*3+1]=m/b,r[u*3+2]=h/b}return this.setAttribute("normal",new pe(r,3)),this}setFromBuffers(e,t,r,i){this.setAttribute("position",new pe(e,3)),this.setAttribute("normal",new pe(t,3)),this.setAttribute("uv",new pe(r,2)),this.setIndex(i)}computeBoundingBox(){let e=this.attributes.position,t=new ue(1/0,1/0,1/0),r=new ue(-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(){}},dt=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=[],l=[];for(let m=0;m<6;m++){let h=m*4;u.push(0,0,1,0,1,1,0,1),l.push(h,h+1,h+2,h,h+2,h+3)}this.setFromBuffers(c,a,u,l)}},qt=class extends ge{constructor(e=1,t=1,r=1,i=1){super(),r=Math.max(1,Math.floor(r)),i=Math.max(1,Math.floor(i));let s=[],o=[],c=[],a=[];for(let u=0;u<=i;u++){let l=u/i;for(let m=0;m<=r;m++){let h=m/r;if(s.push((h-.5)*e,(.5-l)*t,0),o.push(0,0,1),c.push(h,1-l),u>0&&m>0){let b=(r+1)*u+m-1,y=b-(r+1);a.push(y,b,y+1,b,b+1,y+1)}}}this.setFromBuffers(s,o,c,a)}},ft=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=[];for(let a=0;a<=r;a++){let u=a/r;for(let l=0;l<=t;l++){let m=l/t,h=m*Math.PI*2,b=u*Math.PI,y=-Math.cos(h)*Math.sin(b),d=Math.cos(b),g=Math.sin(h)*Math.sin(b);if(i.push(e*y,e*d,e*g),s.push(y,d,g),o.push(m,1-u),a>0&&l>0){let T=(t+1)*a+l,P=T-(t+1),f=P-1,M=T-1;a!==1&&c.push(P,f,T),a!==r&&c.push(f,M,T)}}}this.setFromBuffers(i,s,o,c)}},De=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,b=l===0?u:-u;for(let y=0;y<=i;y++){let d=y/i,g=d*Math.PI*2,T=Math.sin(g),P=Math.cos(g);s.push(h*T,b,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,b=l+i+2,y=l+1;a.push(m,h,y,h,b,y)}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 b=h/i*Math.PI*2,y=Math.sin(b),d=Math.cos(b);s.push(e*y,u,e*d),o.push(0,1,0),c.push(d*.5+.5,y*.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 b=h/i*Math.PI*2,y=Math.sin(b),d=Math.cos(b);s.push(t*y,-u,t*d),o.push(0,-1,0),c.push(d*.5+.5,1-(y*.5+.5))}for(let h=0;h<i;h++)a.push(l,m+h+1,m+h)}this.setFromBuffers(s,o,c,a)}},jt=class extends De{constructor(e=1,t=1,r=16){super(0,e,t,r)}},Kt=class extends ge{constructor(e=1,t=.4,r=12,i=48,s=Math.PI*2){super(),r=Math.max(3,Math.floor(r)),i=Math.max(3,Math.floor(i));let o=[],c=[],a=[],u=[];for(let l=0;l<=r;l++){let m=l/r*Math.PI*2,h=Math.cos(m),b=Math.sin(m);for(let y=0;y<=i;y++){let d=y/i*s,g=Math.cos(d),T=Math.sin(d);if(o.push((e+t*h)*g,(e+t*h)*T,t*b),c.push(h*g,h*T,b),a.push(y/i,l/r),l>0&&y>0){let P=(i+1)*l+y-1,f=P-(i+1);u.push(P,f,P+1,f,f+1,P+1)}}}this.setFromBuffers(o,c,a,u)}},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 ue,h=new ue,b=new ue,y=new ue,d=new ue;function g(f,M){let p=Math.cos(M),A=Math.sin(M),C=o/s*M,w=e*(2+Math.cos(C))*.5;f.set(w*p,w*A,e*Math.sin(C)*.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),b.subVectors(h,m).normalize(),y.addVectors(m,h).normalize(),d.crossVectors(b,y).normalize(),y.crossVectors(d,b).normalize();for(let A=0;A<=i;++A){let C=A*3,w=T[C],R=T[C+1],L=T[C+2],x=w*y.x+R*d.x,v=w*y.y+R*d.y,I=w*y.z+R*d.z;c.push(m.x+x,m.y+v,m.z+I);let S=Math.hypot(x,v,I)||1;a.push(x/S,v/S,I/S),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 A=1;A<=i;A++){let C=M+(A-1),w=p+(A-1),R=p+A,L=M+A;l.push(C,w,L,w,R,L)}}this.setFromBuffers(c,a,u,l)}},pt=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 pt(e);return t?.(r),r}};function fe(n,e){return n!==void 0?Number(n):e}function Vt(n,e){return n!==void 0?!!n:e}var Ae=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=fe(e.emissiveIntensity,1),this.roughness=fe(e.roughness,.5),this.metalness=fe(e.metalness,.1),this.opacity=fe(e.opacity,1),this.transparent=Vt(e.transparent,!1),this.wireframe=Vt(e.wireframe,!1),this.side=fe(e.side,2),this.doubleSided=Vt(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 ve(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 ve(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(){}},Be=class extends Ae{},Qt=class extends Ae{},en=class extends Ae{},tn=class extends Ae{},nn=class extends Ae{},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 ue,this.rotation=new ht,this.quaternion=new mt,this.scale=new ue(1,1,1),this.matrix=new Oe,this.matrixWorld=new Oe,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 ue(e,t,r);this.updateMatrixWorld(!0);let s=new Oe;s.lookAt(this.position,i,new ue(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],b=o[2],y=o[6],d=o[10],g=c+m+d;if(g>0){let T=.5/Math.sqrt(g+1);this.quaternion.set((y-h)*T,(u-b)*T,(l-a)*T,.25/T)}}},rn=class extends we{},Ve=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 dt(.5,.5,.5)):new ge,this.material=i instanceof Ae?i:i?(xe("unsupported material","MeshStandardMaterial"),new Be({color:13421772})):new Be}};function tr(n){let e=J().materializeDeclarativeGeometry;typeof e=="function"&&e(n)}var bt=1e4,yt=class extends Ve{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>bt)throw new RangeError(`SecurityError: InstancedMesh count (${String(i)}) exceeds MAX_INSTANCES_PER_MESH (${bt})`);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 pe(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 pe(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(){}},ze=class extends we{constructor(e=16777215,t=1){super(),this.color=new ve(e),this.intensity=Number(t),this.type="directional"}},gt=class extends ze{constructor(e,t){super(e,t),this.type="ambient"}},sn=class extends ze{constructor(t,r){super(t,r);this.target=new we;this.type="directional"}},xt=class extends ze{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}},vt=class extends we{},on=class extends vt{constructor(t=45,r=1,i=.1,s=1e3){super();this.target=new ue(0,0,0);this.fov=Number(t),this.aspect=Number(r),this.near=Number(i),this.far=Number(s)}},wt=class extends we{constructor(){super(...arguments);this.background=null;this.environmentIntensity=1}toCanvas3D(){return Se.validate(this),Ye(this)}toGLB(){return Se.validate(this),ot(this)}toUSDZ(){return Se.validate(this),qe(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let t=new Map,r=0;return this.traverse(i=>{if(i instanceof Ve){let s=new Float32Array(i.matrixWorld.elements);t.set(r,s),i.name&&t.set(i.name,s),r++}}),t}},nr=Ye,rr=ot,Gr=qe;var Se=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 Ve||a.geometry?.attributes?.position?.count){if(i++,i>1e3&&o("MESHES",1e3,i),a instanceof yt){let l=c("instance",a.count);(l<0||l>bt)&&o("INSTANCES",bt,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 b=Math.min(m,h.length);for(let y=0;y<b;y++){let d=h[y];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){Se.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 globalThis<"u"&&typeof globalThis.__three_live_sim_time_ms__=="number"?globalThis.__three_live_sim_time_ms__: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 ut=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:ut},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>ut,construct:()=>ut}),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 Ie(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(!Ie(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(!Ie(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=J().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)&&Ie(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(!Ie(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=J().sandboxIframeSrc;if(n)return n;let e=ir();if(!e||!Ie(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(!Ie(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!!J().allowClientScripts}function Kr(n){if(!Ie(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(A){a({type:"ERROR",nonce:r,message:String(A)})}let l=typeof t.importScripts=="function"?t.importScripts.bind(t):null,m=s,h=null;try{let A=i;if(typeof t.trustedTypes<"u"&&t.trustedTypes&&typeof t.trustedTypes.createPolicy=="function")try{let C={createScriptURL:function(R){if(R!==i&&(!s||R!==s))throw new TypeError("Disallowed worker importScripts URL");return R}};o&&(C.createScript=function(R){return String(R)});let w=t.trustedTypes.createPolicy("three-live#worker-boot",C);A=w.createScriptURL(i),s&&(m=w.createScriptURL(s)),o&&typeof w.createScript=="function"&&(h=w.createScript.bind(w))}catch{}l(A)}catch(A){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: '+(A&&A.message||A));return}let b=t.THREE;if(!b||typeof b.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 A=t.__THREE_LIVE_REGISTRY__;for(let C=0;C<e.length;C++)if(typeof e[C]=="function")try{e[C](b,A)}catch{}}for(let A=0;A<c.length;A++){let C=c[A],w=t;for(;w&&w!==Object.prototype;){if(w!==t)try{delete w[C]}catch{}try{Object.defineProperty(w,C,{value:void 0,writable:!1,configurable:!1,enumerable:!1})}catch{}try{w=Object.getPrototypeOf(w)}catch{break}}}let y=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:y,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(A,C){if(A.type==="3D_MODEL_READY"){if(T)return;T=!0}A.nonce=r,C&&C.length?a(A,C):a(A)}let f=function(A,C){if(!A||g.indexOf(A.type)===-1)throw new Error("Sandboxed scripts may only post Three-Live scene messages ("+g.join(", ")+").");P(A,C)},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(A){let C=A&&A.data;if(!(!C||C.nonce!==r)&&!(C.type!=="EXECUTE"&&C.type!=="EXECUTE_URL")&&!p){p=!0;try{let w=new b.Scene,R=new b.PerspectiveCamera(60,1,.1,1e3),L=new b.WebGLRenderer({isSandboxed:!0});if(C.type==="EXECUTE_URL"){if(!s||C.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=b,t.scene=w,t.camera=R,t.renderer=L,v(x),typeof t.__THREE_LIVE_SCENE__=="function"){let I=t.__THREE_LIVE_SCENE__(b,w,R,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) {
370
+ `,n}var ot=null;function _t(t){if(!ot){ot=new Uint32Array(256);for(let i=0;i<256;i++){let r=i;for(let s=0;s<8;s++)r=r&1?3988292384^r>>>1:r>>>1;ot[i]=r}}let e=4294967295;for(let i=0;i<t.length;i++)e=ot[(e^t[i])&255]^e>>>8;return(e^4294967295)>>>0}function Kr(t){let e=[],i=0,r=[];for(let c of t){let f=Pt(c.filename),g=_t(c.data),w=c.data.length,d=30+f.length,p=(i+d)%64,A=p!==0?64-p:0;A>0&&A<4&&(A+=64);let b=new Uint8Array(d+A),x=new DataView(b.buffer);x.setUint32(0,67324752,!0),x.setUint16(4,20,!0),x.setUint32(14,g,!0),x.setUint32(18,w,!0),x.setUint32(22,w,!0),x.setUint16(26,f.length,!0),x.setUint16(28,A,!0),b.set(f,30),A>=4&&(x.setUint16(d,6534,!0),x.setUint16(d+2,A-4,!0)),e.push({offset:i,size:w,crc:g,filenameBytes:f,entry:c}),r.push(b,c.data),i+=b.length+c.data.length}let s=i;for(let c of e){let f=new Uint8Array(46+c.filenameBytes.length),g=new DataView(f.buffer);g.setUint32(0,33639248,!0),g.setUint16(4,20,!0),g.setUint16(6,20,!0),g.setUint32(16,c.crc,!0),g.setUint32(20,c.size,!0),g.setUint32(24,c.size,!0),g.setUint16(28,c.filenameBytes.length,!0),g.setUint32(42,c.offset,!0),f.set(c.filenameBytes,46),r.push(f),i+=f.length}let a=i-s,o=new Uint8Array(22),n=new DataView(o.buffer);n.setUint32(0,101010256,!0),n.setUint16(8,e.length,!0),n.setUint16(10,e.length,!0),n.setUint32(12,a,!0),n.setUint32(16,s,!0),r.push(o),i+=22;let l=new Uint8Array(i),h=0;for(let c of r)l.set(c,h),h+=c.length;return l}function mi(t){let e=[{filename:"model.usda",data:Pt(qr(t))}],i=new Set(["model.usda"]),r=[...t];for(;r.length>0;){let s=r.pop();for(let a of s.textures||[])a?.file&&a.data?.byteLength&&!i.has(a.file)&&(i.add(a.file),e.push({filename:a.file,data:a.data}));if(s.children)for(let a=s.children.length-1;a>=0;a--)r.push(s.children[a])}return Kr(e)}function Nt(t){return mi(Gr(t))}function di(t){return mi(ui(We(t)))}function pi(t){return t&&typeof t.toUSDZ=="function"?t.toUSDZ():di(t)}function Lt(t){let e=pi(t);return new Blob([e],{type:"model/vnd.usdz+zip"})}var Pe=class rr{constructor(e=0,i=0){this.x=Number(e),this.y=Number(i)}set(e,i){return this.x=Number(e),this.y=Number(i),this}clone(){return new rr(this.x,this.y)}copy(e){return this.set(e.x,e.y)}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}divideScalar(e){return this.multiplyScalar(e?1/e:0)}setScalar(e){return this.set(e,e)}},re=class sr{constructor(e=0,i=0,r=0){this.x=Number(e),this.y=Number(i),this.z=Number(r)}set(e,i,r){return this.x=Number(e),this.y=Number(i),this.z=Number(r),this}clone(){return new sr(this.x,this.y,this.z)}copy(e){return this.set(e.x,e.y,e.z)}add(e){return this.addVectors(this,e)}addVectors(e,i){return this.set(e.x+i.x,e.y+i.y,e.z+i.z)}sub(e){return this.subVectors(this,e)}subVectors(e,i){return this.set(e.x-i.x,e.y-i.y,e.z-i.z)}multiplyScalar(e){return this.set(this.x*e,this.y*e,this.z*e)}divideScalar(e){return this.multiplyScalar(e?1/e:0)}setScalar(e){return this.set(e,e,e)}addScaledVector(e,i){return this.set(this.x+e.x*i,this.y+e.y*i,this.z+e.z*i)}length(){return Math.hypot(this.x,this.y,this.z)}normalize(){let e=this.length();return e>1e-5?this.multiplyScalar(1/e):this}cross(e){return this.crossVectors(this,e)}crossVectors(e,i){let r=e.x,s=e.y,a=e.z,o=i.x,n=i.y,l=i.z;return this.set(s*l-a*n,a*o-r*l,r*n-s*o)}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)}lerp(e,i){return this.lerpVectors(this,e,i)}lerpVectors(e,i,r){return this.x=e.x+(i.x-e.x)*r,this.y=e.y+(i.y-e.y)*r,this.z=e.z+(i.z-e.z)*r,this}applyMatrix4(e){let i=this.x,r=this.y,s=this.z,a=e.elements,o=1/(a[3]*i+a[7]*r+a[11]*s+a[15]);return this.x=(a[0]*i+a[4]*r+a[8]*s+a[12])*o,this.y=(a[1]*i+a[5]*r+a[9]*s+a[13])*o,this.z=(a[2]*i+a[6]*r+a[10]*s+a[14])*o,this}},Yr=class{constructor(t=0,e=0,i=0,r=1){this.x=Number(t),this.y=Number(e),this.z=Number(i),this.w=Number(r)}set(t,e,i,r){return this.x=Number(t),this.y=Number(e),this.z=Number(i),this.w=Number(r),this}},fi=class ar{constructor(e=0,i=0,r=0,s="XYZ"){this._onChangeCallback=null,this._x=Number(e),this._y=Number(i),this._z=Number(r),this.order=s}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,i,r,s=this.order){return this._x=Number(e),this._y=Number(i),this._z=Number(r),this.order=s,this._onChangeCallback?.(),this}copy(e){return this.set(e.x,e.y,e.z,e.order)}clone(){return new ar(this._x,this._y,this._z,this.order)}_onChange(e){return this._onChangeCallback=e,this}},Dt=class nr{constructor(e=0,i=0,r=0,s=1){this._onChangeCallback=null,this._x=Number(e),this._y=Number(i),this._z=Number(r),this._w=Number(s)}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,i,r,s){return this._x=Number(e),this._y=Number(i),this._z=Number(r),this._w=Number(s),this._onChangeCallback?.(),this}copy(e){return this.set(e.x,e.y,e.z,e.w)}clone(){return new nr(this._x,this._y,this._z,this._w)}identity(){return this.set(0,0,0,1)}setFromEuler(e,i=!0){let r=e.x,s=e.y,a=e.z,o=Math.cos(r/2),n=Math.cos(s/2),l=Math.cos(a/2),h=Math.sin(r/2),c=Math.sin(s/2),f=Math.sin(a/2);return this._x=h*n*l+o*c*f,this._y=o*c*l-h*n*f,this._z=o*n*f+h*c*l,this._w=o*n*l-h*c*f,i&&this._onChangeCallback?.(),this}setFromAxisAngle(e,i){let r=i/2,s=Math.sin(r);return this.set(e.x*s,e.y*s,e.z*s,Math.cos(r))}normalize(){let e=Math.hypot(this._x,this._y,this._z,this._w);return e===0?this.set(0,0,0,1):this.set(this._x/e,this._y/e,this._z/e,this._w/e)}setFromUnitVectors(e,i){let r=e.dot(i)+1;return r<1e-6?(Math.abs(e.x)>Math.abs(e.z)?this.set(-e.y,e.x,0,0):this.set(0,-e.z,e.y,0)).normalize():this.set(e.y*i.z-e.z*i.y,e.z*i.x-e.x*i.z,e.x*i.y-e.y*i.x,r).normalize()}multiply(e){return this.multiplyQuaternions(this,e)}multiplyQuaternions(e,i){let r=e.x,s=e.y,a=e.z,o=e.w,n=i.x,l=i.y,h=i.z,c=i.w;return this._x=r*c+o*n+s*h-a*l,this._y=s*c+o*l+a*n-r*h,this._z=a*c+o*h+r*l-s*n,this._w=o*c-r*n-s*l-a*h,this._onChangeCallback?.(),this}_onChange(e){return this._onChangeCallback=e,this}},qe=class or{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 or;return e.copy(this),e}compose(e,i,r){return St(this.elements,[i.x,i.y,i.z,i.w],[e.x,e.y,e.z],[r.x,r.y,r.z]),this}multiply(e){return this.multiplyMatrices(this,e)}multiplyMatrices(e,i){return fe(this.elements,e.elements,i.elements),this}lookAt(e,i,r){return tt(this.elements,[e.x,e.y,e.z],[i.x,i.y,i.z],[r.x,r.y,r.z]),this}makeRotationFromQuaternion(e){let i=new re(0,0,0),r=new re(1,1,1);return this.compose(i,e,r)}makeTranslation(e,i,r){return this.identity(),this.elements[12]=Number(e),this.elements[13]=Number(i),this.elements[14]=Number(r),this}makeScale(e,i,r){return this.identity(),this.elements[0]=Number(e),this.elements[5]=Number(i),this.elements[10]=Number(r),this}},Zr=class{constructor(){this.elements=new Float32Array([1,0,0,0,1,0,0,0,1])}identity(){let t=this.elements;return t.fill(0),t[0]=1,t[4]=1,t[8]=1,this}getNormalMatrix(t){return Ne(this.elements,t.elements),this}},we=t=>t<=.04045?t/12.92:((t+.055)/1.055)**2.4,lt=t=>t<=.0031308?t*12.92:1.055*t**(1/2.4)-.055,gi={black:0,white:16777215,red:16711680,green:32768,lime:65280,blue:255,yellow:16776960,cyan:65535,aqua:65535,magenta:16711935,fuchsia:16711935,gray:8421504,grey:8421504,silver:12632256,orange:16753920,purple:8388736,pink:16761035,gold:16766720},De=class lr{constructor(e,i,r){this.r=1,this.g=1,this.b=1,e!==void 0&&(i!==void 0&&r!==void 0?this.setRGB(e,i,r):this.set(e))}set(e){return typeof e=="number"?this.setHex(e):typeof e=="string"?this.setStyle(e):(e&&typeof e=="object"&&"r"in e&&(this.r=Number(e.r),this.g=Number(e.g),this.b=Number(e.b)),this)}setStyle(e){let i=e.trim().toLowerCase();if(i[0]==="#"){let r=i.slice(1);r.length===3||r.length===4?r=r[0]+r[0]+r[1]+r[1]+r[2]+r[2]:r.length===8&&(r=r.slice(0,6));let s=parseInt(r,16);r.length===6&&!Number.isNaN(s)&&this.setHex(s)}else if(i in gi)this.setHex(gi[i]);else if(i.startsWith("hsl")){let r=/^hsla?\(([^)]+)\)$/.exec(i)?.[1].trim().split(/[\s,/]+/);r&&r.length>=3&&this.setHSL((parseFloat(r[0])||0)/360,(parseFloat(r[1])||0)/100,(parseFloat(r[2])||0)/100)}else{let r=/^rgba?\(([^)]+)\)$/.exec(i)?.[1].trim().split(/[\s,/]+/);if(r&&r.length>=3){let s=a=>we(Math.max(0,Math.min(1,(parseFloat(a)||0)/(a.endsWith("%")?100:255))));this.setRGB(s(r[0]),s(r[1]),s(r[2]))}}return this}setHSL(e,i,r){if(e=((Number(e)||0)%1+1)%1,i=Math.max(0,Math.min(1,Number(i)||0)),r=Math.max(0,Math.min(1,Number(r)||0)),i===0){let n=we(r);return this.setRGB(n,n,n)}let s=r<=.5?r*(1+i):r+i-r*i,a=2*r-s,o=n=>(n<0&&(n+=1),n>1&&(n-=1),n<1/6?a+(s-a)*6*n:n<1/2?s:n<2/3?a+(s-a)*6*(2/3-n):a);return this.setRGB(we(o(e+1/3)),we(o(e)),we(o(e-1/3)))}lerp(e,i){return this.lerpColors(this,e,i)}lerpColors(e,i,r){let s=Number(r)||0;return this.setRGB(e.r+(i.r-e.r)*s,e.g+(i.g-e.g)*s,e.b+(i.b-e.b)*s)}multiplyScalar(e){let i=Number(e)||0;return this.setRGB(this.r*i,this.g*i,this.b*i)}setScalar(e){let i=Number(e)||0;return this.setRGB(i,i,i)}setHex(e){let i=Math.floor(e);return this.setRGB(we((i>>16&255)/255),we((i>>8&255)/255),we((i&255)/255))}setRGB(e,i,r){return this.r=Number(e),this.g=Number(i),this.b=Number(r),this}convertSRGBToLinear(){return this.setRGB(we(this.r),we(this.g),we(this.b))}convertLinearToSRGB(){return this.setRGB(lt(this.r),lt(this.g),lt(this.b))}getHex(){let e=i=>Math.round(lt(Math.max(0,Math.min(1,i)))*255);return e(this.r)<<16|e(this.g)<<8|e(this.b)}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}copy(e){return this.setRGB(e.r,e.g,e.b)}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}clone(){return new lr(this.r,this.g,this.b)}},Qr={degToRad:t=>t*Math.PI/180,radToDeg:t=>t*180/Math.PI,clamp:(t,e,i)=>Math.max(e,Math.min(i,t)),lerp:(t,e,i)=>t+(e-t)*i,generateUUID:()=>Math.random().toString(36).substring(2,15),randFloat:(t,e)=>t+Math.random()*(e-t)},ve=class hr{constructor(e,i){if(this.needsUpdate=!1,typeof i!="number"||!Number.isInteger(i)||i<1||i>16)throw new Error(`SecurityError: BufferAttribute itemSize must be an integer in [1, 16]. Received: ${String(i)}`);Array.isArray(e)?this.array=new Float32Array(e):this.array=e,this.itemSize=i;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/i)}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,i){return this.array[e*this.itemSize]=i,this.needsUpdate=!0,this}setY(e,i){return this.array[e*this.itemSize+1]=i,this.needsUpdate=!0,this}setZ(e,i){return this.array[e*this.itemSize+2]=i,this.needsUpdate=!0,this}setXYZ(e,i,r,s){let a=e*this.itemSize;return this.array[a]=i,this.array[a+1]=r,this.array[a+2]=s,this.needsUpdate=!0,this}setUsage(e){return this}clone(){let e=this.array?.constructor||Float32Array;return new hr(new e(this.array),this.itemSize)}},Jr=class extends ve{constructor(t,e){super(t instanceof Float32Array||Array.isArray(t)?t:new Float32Array(t),e)}},es=class extends ve{constructor(t,e){super(t instanceof Uint16Array?t:new Uint16Array(t),e)}},ts=class extends ve{constructor(t,e){super(t instanceof Uint32Array?t:new Uint32Array(t),e)}},be=class ur{constructor(){this.name="",this.attributes={},this.index=null,this.boundingBox=null}setAttribute(e,i){return this.attributes[e]=i,this}getAttribute(e){return this.attributes[e]}setIndex(e){if(e instanceof ve)this.index=e;else if(Array.isArray(e)){let i=0;for(let r of e)r>i&&(i=r);this.index=new ve(new(i>65535?Uint32Array:Uint16Array)(e),1)}else e&&e.buffer&&(this.index=new ve(e,1));return this}computeVertexNormals(){let e=this.attributes.position;if(!e)return this;let i=!1;if(typeof i=="function"){let l=i(e.array,this.index?.array);return this.setAttribute("normal",new ve(l,3)),this}let r=e.count,s=e.array,a=new Float32Array(r*3),o=this.index?.array,n=o?o.length:r;for(let l=0;l<n;l+=3){let h=(o?o[l]:l)*3,c=(o?o[l+1]:l+1)*3,f=(o?o[l+2]:l+2)*3,g=s[c],w=s[c+1],d=s[c+2],p=s[f]-g,A=s[f+1]-w,b=s[f+2]-d,x=s[h]-g,u=s[h+1]-w,m=s[h+2]-d,v=A*m-b*u,S=b*x-p*m,_=p*u-A*x;a[h]+=v,a[h+1]+=S,a[h+2]+=_,a[c]+=v,a[c+1]+=S,a[c+2]+=_,a[f]+=v,a[f+1]+=S,a[f+2]+=_}for(let l=0;l<r*3;l+=3){let h=a[l],c=a[l+1],f=a[l+2],g=Math.hypot(h,c,f)||1;a[l]=h/g,a[l+1]=c/g,a[l+2]=f/g}return this.setAttribute("normal",new ve(a,3)),this}setFromBuffers(e,i,r,s){this.setAttribute("position",new ve(e,3)),this.setAttribute("normal",new ve(i,3)),this.setAttribute("uv",new ve(r,2)),this.setIndex(s)}setFromPoints(e){let i=[];if(Array.isArray(e))for(let r of e)i.push(Number(r?.x)||0,Number(r?.y)||0,Number(r?.z)||0);return this.setAttribute("position",new ve(i,3))}computeBoundingBox(){let e=this.attributes.position,i=new re(1/0,1/0,1/0),r=new re(-1/0,-1/0,-1/0);if(e&&e.count>0)for(let s=0;s<e.count;s++){let a=e.getX(s),o=e.getY(s),n=e.getZ(s);a<i.x&&(i.x=a),o<i.y&&(i.y=o),n<i.z&&(i.z=n),a>r.x&&(r.x=a),o>r.y&&(r.y=o),n>r.z&&(r.z=n)}else i.set(0,0,0),r.set(0,0,0);return this.boundingBox={min:i,max:r},this.boundingBox}center(){let e=this.computeBoundingBox();return this.translate(-(e.min.x+e.max.x)*.5,-(e.min.y+e.max.y)*.5,-(e.min.z+e.max.z)*.5)}_xform(e,i){let r=this.attributes.position;if(r){let s=r.array;for(let a=0;a<s.length;a+=3)e(s,a);r.needsUpdate=!0,i&&this.computeVertexNormals(),this.computeBoundingBox()}return this}translate(e=0,i=0,r=0){return this._xform((s,a)=>{s[a]+=e,s[a+1]+=i,s[a+2]+=r})}scale(e=1,i=1,r=1){return this._xform((s,a)=>{s[a]*=e,s[a+1]*=i,s[a+2]*=r},!0)}_rot(e,i,r){let s=Math.cos(r),a=Math.sin(r);for(let o of[this.attributes.position,this.attributes.normal]){if(!o)continue;let n=o.array;for(let l=0;l<n.length;l+=3){let h=n[l+e],c=n[l+i];n[l+e]=h*s-c*a,n[l+i]=h*a+c*s}o.needsUpdate=!0}return this}rotateX(e){return this._rot(1,2,e)}rotateY(e){return this._rot(2,0,e)}rotateZ(e){return this._rot(0,1,e)}applyMatrix4(e){let i=this.attributes.position;if(i&&e?.elements){let r=new re;for(let s=0;s<i.count;s++)r.set(i.getX(s),i.getY(s),i.getZ(s)).applyMatrix4(e),i.setXYZ(s,r.x,r.y,r.z);this.computeVertexNormals()}return this}clone(){let e=new ur;e.name=this.name;for(let i of Object.keys(this.attributes))e.attributes[i]=this.attributes[i].clone();return this.index&&(e.index=this.index.clone()),e}dispose(){}},bi=class extends be{constructor(t=1,e=1,i=1){super();let r=t/2,s=e/2,a=i/2,o=[-r,-s,a,r,-s,a,r,s,a,-r,s,a,r,-s,-a,-r,-s,-a,-r,s,-a,r,s,-a,-r,s,a,r,s,a,r,s,-a,-r,s,-a,-r,-s,-a,r,-s,-a,r,-s,a,-r,-s,a,r,-s,a,r,-s,-a,r,s,-a,r,s,a,-r,-s,-a,-r,-s,a,-r,s,a,-r,s,-a],n=[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],l=[],h=[];for(let c=0;c<6;c++){let f=c*4;l.push(0,0,1,0,1,1,0,1),h.push(f,f+1,f+2,f,f+2,f+3)}this.setFromBuffers(o,n,l,h)}},is=class extends be{constructor(t=1,e=1,i=1,r=1){super(),i=Math.max(1,Math.floor(i)),r=Math.max(1,Math.floor(r));let s=[],a=[],o=[],n=[];for(let l=0;l<=r;l++){let h=l/r;for(let c=0;c<=i;c++){let f=c/i;if(s.push((f-.5)*t,(.5-h)*e,0),a.push(0,0,1),o.push(f,1-h),l>0&&c>0){let g=(i+1)*l+c-1,w=g-(i+1);n.push(w,g,w+1,g,g+1,w+1)}}}this.setFromBuffers(s,a,o,n)}},rs=class extends be{constructor(t=1,e=16,i=12,r=0,s=Math.PI*2,a=0,o=Math.PI){super(),e=Math.max(3,Math.floor(e)),i=Math.max(2,Math.floor(i));let n=[],l=[],h=[],c=[],f=Math.min(a+o,Math.PI);for(let g=0;g<=i;g++){let w=g/i,d=a+w*o;for(let p=0;p<=e;p++){let A=p/e,b=r+A*s,x=-Math.cos(b)*Math.sin(d),u=Math.cos(d),m=Math.sin(b)*Math.sin(d);if(n.push(t*x,t*u,t*m),l.push(x,u,m),h.push(A,1-w),g>0&&p>0){let v=(e+1)*g+p,S=v-(e+1),_=S-1,D=v-1;(g!==1||a>0)&&c.push(S,_,v),(g!==i||f<Math.PI)&&c.push(_,D,v)}}}this.setFromBuffers(n,l,h,c)}},yi=class extends be{constructor(t=1,e=1,i=1,r=16,s=1,a=!1,o=0,n=Math.PI*2){super(),r=Math.max(3,Math.floor(r)),s=Math.max(1,Math.floor(Number(s)||1));let l=[],h=[],c=[],f=[],g=i/2,w=(e-t)/(i||1),d=r+1;for(let A=0;A<=s;A++){let b=A/s,x=b*(e-t)+t,u=g-b*i;for(let m=0;m<=r;m++){let v=m/r,S=o+v*n,_=Math.sin(S),D=Math.cos(S),P=Math.hypot(_,w,D)||1;if(l.push(x*_,u,x*D),h.push(_/P,w/P,D/P),c.push(v,1-b),A<s&&m<r){let N=A*d+m,E=N+d;f.push(N,E,N+1,E,E+1,N+1)}}}let p=(A,b)=>{if(a||A<=0)return;let x=b*g,u=l.length/3;l.push(0,x,0),h.push(0,b,0),c.push(.5,.5);let m=u+1;for(let v=0;v<=r;v++){let S=o+v/r*n,_=Math.sin(S),D=Math.cos(S);l.push(A*_,x,A*D),h.push(0,b,0),c.push(D*.5+.5,.5+b*_*.5),v<r&&f.push(u,m+v+(b>0?0:1),m+v+(b>0?1:0))}};p(t,1),p(e,-1),this.setFromBuffers(l,h,c,f)}},ss=class extends yi{constructor(t=1,e=1,i=16,r=1,s=!1,a=0,o=Math.PI*2){super(0,t,e,i,r,s,a,o)}},as=class extends be{constructor(t=1,e=.4,i=12,r=48,s=Math.PI*2){super(),i=Math.max(3,Math.floor(i)),r=Math.max(3,Math.floor(r));let a=[],o=[],n=[],l=[];for(let h=0;h<=i;h++){let c=h/i*Math.PI*2,f=Math.cos(c),g=Math.sin(c);for(let w=0;w<=r;w++){let d=w/r*s,p=Math.cos(d),A=Math.sin(d);if(a.push((t+e*f)*p,(t+e*f)*A,e*g),o.push(f*p,f*A,g),n.push(w/r,h/i),h>0&&w>0){let b=(r+1)*h+w-1,x=b-(r+1);l.push(b,x,b+1,x,x+1,b+1)}}}this.setFromBuffers(a,o,n,l)}};function vi(t,e,i,r,s){let a=Math.max(2,Math.min(256,Math.floor(Number(e)||64))),o=Math.max(3,Math.min(64,Math.floor(Number(i)||8))),n=Number(r)||.1,l=[],h=[],c=[],f=[],g=[],w=new re,d=new re,p=new re;for(let b=0;b<=a;b++){let x=new re;s(b/a,x),g.push(x)}let A=o+1;for(let b=0;b<=a;b++){let x=b/a,u=g[b];w.subVectors(g[Math.min(a,b+1)],g[Math.max(0,b-1)]).normalize(),b===0&&d.set(Math.abs(w.y)>.9?1:0,Math.abs(w.y)>.9?0:1,0),p.crossVectors(w,d).normalize(),d.crossVectors(p,w).normalize();for(let m=0;m<=o;m++){let v=m/o*Math.PI*2,S=-Math.cos(v),_=Math.sin(v),D=S*d.x+_*p.x,P=S*d.y+_*p.y,N=S*d.z+_*p.z;if(l.push(u.x+n*D,u.y+n*P,u.z+n*N),h.push(D,P,N),c.push(x,m/o),b>0&&m>0){let E=A*(b-1)+m-1,F=E+A;f.push(E,F,E+1,F,F+1,E+1)}}}t.setFromBuffers(l,h,c,f)}var ns=class extends be{constructor(t=1,e=.4,i=64,r=8,s=2,a=3){super(),i=Math.floor(i),r=Math.floor(r),vi(this,i,r,e,(o,n)=>{let l=o*s*Math.PI*2,h=a/s*l,c=t*(2+Math.cos(h))*.5;n.set(c*Math.cos(l),c*Math.sin(l),t*Math.sin(h)*.5)})}},ze=class{getPoint(t,e=new re){return e}getPointAt(t,e=new re){return this.getPoint(t,e)}getTangent(t,e=new re){return e.subVectors(this.getPoint(Math.min(1,t+.001)),this.getPoint(Math.max(0,t-.001))).normalize()}getPoints(t=5){let e=Math.max(1,Math.min(512,Math.floor(Number(t)||5))),i=[];for(let r=0;r<=e;r++)i.push(this.getPoint(r/e));return i}getSpacedPoints(t=5){return this.getPoints(t)}},os=class extends ze{constructor(t=new re,e=new re){super(),this.v1=t,this.v2=e}getPoint(t,e=new re){return e.lerpVectors(this.v1,this.v2,t)}},ls=class extends ze{constructor(t=new re,e=new re,i=new re){super(),this.v0=t,this.v1=e,this.v2=i}getPoint(t,e=new re){return e.lerpVectors(this.v0,this.v1,t).lerp(new re().lerpVectors(this.v1,this.v2,t),t)}},hs=class extends ze{constructor(t=new re,e=new re,i=new re,r=new re){super(),this.v0=t,this.v1=e,this.v2=i,this.v3=r}getPoint(t,e=new re){let i=new re().lerpVectors(this.v0,this.v1,t),r=new re().lerpVectors(this.v1,this.v2,t),s=new re().lerpVectors(this.v2,this.v3,t);return e.lerpVectors(i.lerp(r,t),r.lerp(s,t),t)}},us=class extends ze{constructor(t=[],e=!1){super(),this.points=Array.isArray(t)?t:[],this.closed=!!e}getPoint(t,e=new re){let i=this.points,r=i.length;if(!r)return e.set(0,0,0);if(r===1)return e.copy(i[0]);let s=(this.closed?r:r-1)*Math.max(0,Math.min(1,Number(t)||0)),a=Math.floor(s),o=s-a;!this.closed&&a>=r-1&&(a=r-2,o=1);let n=p=>i[this.closed?(p%r+r)%r:Math.max(0,Math.min(r-1,p))],l=n(a-1),h=n(a),c=n(a+1),f=n(a+2),g=o*o,w=g*o,d=(p,A,b,x)=>.5*(2*A+(b-p)*o+(2*p-5*A+4*b-x)*g+(3*A-p-3*b+x)*w);return e.set(d(l.x,h.x,c.x,f.x),d(l.y,h.y,c.y,f.y),d(l.z,h.z,c.z,f.z))}},xi=class extends be{constructor(t=[new Pe(0,-.5),new Pe(.5,0),new Pe(0,.5)],e=12,i=0,r=Math.PI*2){super();let s=Array.isArray(t)&&t.length>=2?t:[new Pe(.2,0),new Pe(.2,.5)],a=Math.max(3,Math.min(128,Math.floor(Number(e)||12))),o=[],n=[],l=[],h=[],c=s.length;for(let f=0;f<=a;f++){let g=f/a,w=i+g*r,d=Math.sin(w),p=Math.cos(w),A=f*c;for(let b=0;b<c;b++){let x=s[b],u=Number(x?.x)||0,m=Number(x?.y)||0;o.push(u*d,m,u*p);let v=s[Math.max(0,b-1)],S=s[Math.min(c-1,b+1)],_=(Number(S?.x)||0)-(Number(v?.x)||0),D=(Number(S?.y)||0)-(Number(v?.y)||0),P=Math.hypot(D,_)||1;if(n.push(D/P*d,-_/P,D/P*p),l.push(g,b/(c-1)),f<a&&b<c-1){let N=A+b,E=N+c;h.push(N,E,N+1,E,E+1,N+1)}}}this.setFromBuffers(o,n,l,h)}},cs=class extends be{constructor(t,e=64,i=1,r=8,s=!1){super(),vi(this,e,r,i,(a,o)=>{let n=t?.getPointAt??t?.getPoint;if(typeof n=="function"){let l=n.call(t,a,o);l&&l!==o&&o.copy(l)}else o.set(0,a,0)})}},ht="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",kt=class{constructor(t=""){this.isTexture=!0,this.wrapS=10497,this.wrapT=10497,this.repeat=new Pe(1,1),this.offset=new Pe(0,0),this.image=null,this.width=0,this.height=0,this.source=t,t&&typeof t=="object"&&(this.image=t)}dispose(){}},ms=class extends kt{constructor(t=null,e=1,i=1,r=1023,s=1009,a,o=1001,n=1001,l=1003,h=1003,c=1,f=""){super(""),this.isDataTexture=!0,this.avgColor=[1,1,1,1],this.flipY=!1,this.generateMipmaps=!1,this.unpackAlignment=1,this._sig=0;let g=Number(e),w=Number(i),d=t&&typeof t.length=="number"?t:null;this.width=g,this.height=w,this.image={data:d,width:g,height:w},this.format=Number(r)||1023,this.type=Number(s)||1009,this.wrapS=Number(o)||1001,this.wrapT=Number(n)||1001,this.magFilter=Number(l)||1003,this.minFilter=Number(h)||1003,this.colorSpace=f||"",this._bake()}get needsUpdate(){return!1}set needsUpdate(t){t&&this._bake()}_bake(){let t=this.image,e=t?.data,i=Number(t?.width??this.width),r=Number(t?.height??this.height);if(!e||!e.length||!(i>0&&r>0)||i>2048||r>2048){this.source="";return}let s=Math.max(1,i|0),a=Math.max(1,r|0),o=s*a,n=this.format,l=n===1021||n===1024||n===1028||e.length===o?1:n===1025||n===1030||e.length===o*2?2:n===1022||e.length===o*3?3:4,h=this.type===1015||this.type===1016||e instanceof Float32Array||e instanceof Float64Array,c=Math.min(s,48),f=Math.min(a,48),g=(this.flipY?257:1)^this.colorSpace.length^e.length,w=Math.max(1,e.length>>6|0);for(let F=0;F<e.length;F+=w)g=Math.imul(g^(e[F]*256|0),16777619)|0;if(g===this._sig&&this.source)return;this._sig=g;let d=f*(1+c*4),p=new Uint8Array(68+d),A=new DataView(p.buffer);A.setUint32(0,2303741511),A.setUint32(4,218765834),A.setUint32(8,13),A.setUint32(12,1229472850),A.setUint32(16,c),A.setUint32(20,f),p[24]=8,p[25]=6,A.setUint32(29,_t(p.subarray(12,29))),A.setUint32(33,d+11),A.setUint32(37,1229209940),p[41]=120,p[42]=1,p[43]=1,A.setUint16(44,d,!0),A.setUint16(46,~d&65535,!0);let b=48,x=1,u=0,m=0,v=0,S=0,_=0,D=F=>{if(!Number.isFinite(F))return 0;let L=h&&F<=1?F*255:F;return L>0?L<255?L+.5|0:255:0};for(let F=0;F<f;F++){let L=F*a/f|0,M=this.flipY?a-1-L:L;p[b++]=0,u+=x;for(let O=0;O<c;O++){let H=(M*s+(O*s/c|0))*l,R=n===1021?255:D(e[H]??0),C=l>=3||n===1030?D(e[H+1]??0):R,y=l>=3?D(e[H+2]??0):n===1030?0:R,T=l===4?D(e[H+3]??255):n===1021?D(e[H]??255):n===1025?D(e[H+1]??255):255;p[b++]=R,x+=R,u+=x,p[b++]=C,x+=C,u+=x,p[b++]=y,x+=y,u+=x,p[b++]=T,x+=T,u+=x,m+=R,v+=C,S+=y,_+=T}x%=65521,u%=65521}A.setUint32(b,(u<<16|x)>>>0),A.setUint32(b+4,_t(p.subarray(37,b+4))),A.setUint32(b+12,1229278788),A.setUint32(b+16,2923585666);let P=c*f*255,N=this.colorSpace==="srgb-linear";this.avgColor=[N?m/P:we(m/P),N?v/P:we(v/P),N?S/P:we(S/P),_/P];let E=["data:image/png;base64,"];for(let F=0;F<p.length;F+=3){let L=p[F]<<16|(p[F+1]??0)<<8|(p[F+2]??0);E.push(ht[L>>18&63]+ht[L>>12&63]+(F+1<p.length?ht[L>>6&63]:"=")+(F+2<p.length?ht[L&63]:"="))}this.source=E.join("")}},ds=class{load(t,e){let i=new kt(t);return e?.(i),i}};function Me(t,e){return t!==void 0?Number(t):e}function Ft(t,e){return t!==void 0?!!t:e}var Re=class{constructor(t={}){this.name=t.name||"",this.color=new De(t.color??16777215),this.emissive=new De(t.emissive??0),this.emissiveIntensity=Me(t.emissiveIntensity,1),this.roughness=Me(t.roughness,.5),this.metalness=Me(t.metalness,0),this.opacity=Me(t.opacity,1),this.transparent=Ft(t.transparent,!1),this.wireframe=Ft(t.wireframe,!1),this.side=Me(t.side,2),this.doubleSided=Ft(t.doubleSided,!0),this.map=t.map||null;for(let e of["normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap"])t[e]&&(this[e]=t[e]);this.clearcoat=Me(t.clearcoat,0),this.clearcoatRoughness=Me(t.clearcoatRoughness,0),this.sheen=Me(t.sheen,0),this.sheenColor=new De(t.sheenColor??0),this.sheenRoughness=Me(t.sheenRoughness,0),this.transmission=Me(t.transmission,0),this.thickness=Me(t.thickness,0),this.attenuationColor=new De(t.attenuationColor??16777215),this.attenuationDistance=Me(t.attenuationDistance,1/0),this.ior=Me(t.ior,1.5),this.dispersion=Me(t.dispersion,0),this.iridescence=Me(t.iridescence,0),this.iridescenceIOR=Me(t.iridescenceIOR,1.3)}dispose(){}},ut=class extends Re{},ps=class extends Re{},fs=class extends Re{},gs=class extends Re{},bs=class extends Re{},ke=class cr{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 re,this.rotation=new fi,this.quaternion=new Dt,this.scale=new re(1,1,1),this.matrix=new qe,this.matrixWorld=new qe,this.rotation._onChange(()=>{this.quaternion.setFromEuler(this.rotation,!1)}),this.quaternion._onChange(()=>{let e=this.quaternion,i=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)))),s=Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z));this.rotation.set(i,r,s)})}add(...e){for(let i of e)i&&i instanceof cr&&(i.parent&&i.parent.remove(i),i.parent=this,this.children.push(i));return this}remove(...e){for(let i of e){let r=this.children.indexOf(i);r!==-1&&(i.parent=null,this.children.splice(r,1))}return this}traverse(e){let i=new Set,r=[this];for(;r.length>0;){let s=r.pop();if(!s||typeof s!="object"||i.has(s))continue;i.add(s),e(s);let a=s.children;if(Array.isArray(a))for(let o=a.length-1;o>=0;o--)r.push(a[o])}}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale)}updateMatrixWorld(e=!1){this.traverse(i=>{Mi(i),(i.matrixAutoUpdate||e)&&i.updateMatrix?.(),i.parent&&i.parent.matrixWorld?i.matrixWorld?.multiplyMatrices(i.parent.matrixWorld,i.matrix):i.matrix&&i.matrixWorld?.copy(i.matrix)})}lookAt(e,i,r){let s=typeof e=="object"?e:new re(e,i,r);this.target instanceof re?this.target.copy(s):this.target?.position instanceof re&&this.target.position.copy(s),this.updateMatrixWorld(!0);let a=new qe;a.lookAt(this.position,s,new re(0,1,0));let o=a.elements,n=o[0],l=o[4],h=o[8],c=o[1],f=o[5],g=o[9],w=o[2],d=o[6],p=o[10],A=n+f+p;if(A>0){let b=.5/Math.sqrt(A+1);this.quaternion.set((d-g)*b,(h-w)*b,(c-l)*b,.25/b)}}translateOnAxis(e,i){let r=e.clone().applyMatrix4(new qe().makeRotationFromQuaternion(this.quaternion)).multiplyScalar(i);return this.position.add(r),this}translateX(e){return this.translateOnAxis(new re(1,0,0),e)}translateY(e){return this.translateOnAxis(new re(0,1,0),e)}translateZ(e){return this.translateOnAxis(new re(0,0,1),e)}rotateX(e){return this.rotation.x+=e,this}rotateY(e){return this.rotation.y+=e,this}rotateZ(e){return this.rotation.z+=e,this}_chain(){let e=[];for(let i=this;i&&e.length<64;i=i.parent)e.push(i);return e}_syncWorld(){let e=this._chain();for(let i=e.length-1;i>=0;i--){let r=e[i];r.updateMatrix?.(),r.parent?.matrixWorld?r.matrixWorld.multiplyMatrices(r.parent.matrixWorld,r.matrix):r.matrixWorld?.copy(r.matrix)}return this.matrixWorld.elements}getWorldPosition(e=new re){let i=this._syncWorld();return e.set(i[12],i[13],i[14])}getWorldScale(e=new re){let i=this._syncWorld();return e.set(Math.hypot(i[0],i[1],i[2]),Math.hypot(i[4],i[5],i[6]),Math.hypot(i[8],i[9],i[10]))}getWorldDirection(e=new re){let i=this._syncWorld();return e.set(i[8],i[9],i[10]).normalize()}getWorldQuaternion(e=new Dt){let i=this._chain();e.set(0,0,0,1);for(let r=i.length-1;r>=0;r--)e.multiply(i[r].quaternion);return e}clone(e=!0){let i=this instanceof Qe?new this.constructor(this._sourceGeo||this.geometry,this.material):this instanceof Ie?new Ie(this.geometry,this.material):new this.constructor;i.name=this.name,i.position.copy(this.position),i.quaternion.copy(this.quaternion),i.scale.copy(this.scale),i.visible=this.visible,i.castShadow=this.castShadow,i.receiveShadow=this.receiveShadow;try{i.userData=JSON.parse(JSON.stringify(this.userData||{}))}catch{i.userData={...this.userData||{}}}if(e)for(let r of this.children)i.add(r.clone(!0));return i}},ys=class extends ke{},Ie=class extends ke{constructor(t,e){super(),this.isMesh=!0;let i=Array.isArray(e)?e[0]:e;this.geometry=t instanceof be?t:t?($e("unsupported geometry","BoxGeometry"),new bi(.5,.5,.5)):new be,this.material=i instanceof Re?i:i?($e("unsupported material","MeshStandardMaterial"),new ut({color:13421772})):new ut}};function Mi(t){typeof t?._bakeAuthorGeometry=="function"&&t._bakeAuthorGeometry();let e=he().materializeDeclarativeGeometry;typeof e=="function"&&e(t)}var ct=1e4,wi=class extends Ie{constructor(t,e,i=1){super(t,e),this.instanceColor=null,this.isInstancedMesh=!0;let r=Number(i);if(!Number.isFinite(r)||r<0||r>ct)throw new RangeError(`SecurityError: InstancedMesh count (${String(i)}) exceeds MAX_INSTANCES_PER_MESH (${ct})`);this.count=Math.floor(r);let s=new Float32Array(this.count*16);for(let a=0;a<this.count;a++){let o=a*16;s[o]=1,s[o+5]=1,s[o+10]=1,s[o+15]=1}this.instanceMatrix=new ve(s,16)}setMatrixAt(t,e){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!e||!e.elements)return;let r=this.instanceMatrix.array,s=i*16;if(!(s+16>r.length))for(let a=0;a<16;a++){let o=Number(e.elements[a]);r[s+a]=Number.isFinite(o)?o:a%5===0?1:0}}getMatrixAt(t,e){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!e||!e.elements)return;let r=this.instanceMatrix.array,s=i*16;if(!(s+16>r.length))for(let a=0;a<16;a++)e.elements[a]=r[s+a]}setColorAt(t,e){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!e)return;if(!this.instanceColor||this.instanceColor.array.length<this.count*3){let a=new Float32Array(this.count*3);a.fill(1),this.instanceColor=new ve(a,3)}let r=this.instanceColor.array,s=i*3;r[s]=Number.isFinite(e.r)?e.r:1,r[s+1]=Number.isFinite(e.g)?e.g:1,r[s+2]=Number.isFinite(e.b)?e.b:1}getColorAt(t,e){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!e)return;if(!this.instanceColor||this.instanceColor.array.length<(i+1)*3){e.setRGB(1,1,1);return}let r=this.instanceColor.array,s=i*3;e.setRGB(r[s],r[s+1],r[s+2])}dispose(){}},mt=class extends ke{constructor(t=16777215,e=1){super(),this.color=new De(t),this.intensity=Number(e),this.type="directional"}},Si=class extends mt{constructor(t,e){super(t,e),this.type="ambient"}},vs=class extends mt{constructor(t,e){super(t,e),this.target=new ke,this.type="directional"}},Ai=class extends mt{constructor(t,e,i=0,r=2){super(t,e),this.type="point",this.distance=i,this.decay=r}},Ri=class extends ke{},xs=class extends Ri{constructor(t=45,e=1,i=.1,r=1e3){super(),this.target=new re(0,0,0),this.fov=Number(t),this.aspect=Number(e),this.near=Number(i),this.far=Number(r)}},Ti=class extends ke{constructor(){super(...arguments),this.background=null,this.environmentIntensity=1}toCanvas3D(){return Oe.validate(this),rt(this)}toGLB(){return Oe.validate(this),Et(this)}toUSDZ(){return Oe.validate(this),Nt(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let t=new Map,e=0;return this.traverse(i=>{if(i instanceof Ie){let r=new Float32Array(i.matrixWorld.elements);t.set(e,r),i.name&&t.set(i.name,r),e++}}),t}},Ci=rt,Pi=Et,Ms=Nt,Oe=class{static validate(t){let e=0,i=0,r=0,s=new Set,a=(n,l,h)=>{throw new Error(`SecurityError: Scene exceeds SECURITY_3D_MAX_${n} (${l}). Found: ${h}`)},o=(n,l)=>{if(!Number.isFinite(l))throw new Error(`SecurityError: Scene reports a non-finite ${n} count (${String(l)}), which cannot be bounds-checked.`);return l};t.traverse(n=>{if(Mi(n),n instanceof Ie||n.geometry?.attributes?.position?.count){if(r++,r>1e3&&a("MESHES",1e3,r),n instanceof wi){let h=o("instance",n.count);(h<0||h>ct)&&a("INSTANCES",ct,h)}let l=n.geometry;if(l){let h=0;if(l.attributes.position&&(h=o("vertex",l.attributes.position.count),e+=h,e>1e5&&a("VERTICES",1e5,e)),l.index){let c=o("index",l.index.count);i+=c,i>3e5&&a("INDICES",3e5,i);let f=l.index.array;if(f&&h>0){let g=Math.min(c,f.length);for(let w=0;w<g;w++){let d=f[w];if(!Number.isFinite(d)||d<0||d>=h)throw new Error(`SecurityError: Index buffer value (${String(d)}) out of vertex bounds [0, ${h}).`)}}}}if(n.material){let h=n.material;for(let c of["map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap"])h[c]&&s.add(h[c])}}}),s.size>16&&a("TEXTURES",16,s.size);for(let n of s){let l=n,h=l.image,c=Number(h?.width??l.width??0)||0,f=Number(h?.height??l.height??0)||0;(!Number.isFinite(c)||!Number.isFinite(f)||c>2048||f>2048)&&a("TEXTURE_DIMENSION",2048,Math.max(c,f))}}},ws=class{constructor(t={}){this.shadowMap={enabled:!1,type:0},this.capabilities={isWebGL2:!0,maxTextures:16},this.boundViewer=null,this.hasInitialModelRendered=!1,this.domElement=t.canvas||(typeof document<"u"?document.createElement("canvas"):{}),t.viewer&&(this.boundViewer=t.viewer),t.container?.threeLiveViewer&&(this.boundViewer=t.container.threeLiveViewer),t.canvas?.parentElement?.threeLiveViewer&&(this.boundViewer=t.canvas.parentElement.threeLiveViewer);let e=typeof WorkerGlobalScope<"u"&&typeof self<"u"&&self instanceof WorkerGlobalScope;this.isSandboxed=t.isSandboxed||e,this.containerId=t.containerId||""}setSize(t,e){return this}setPixelRatio(t){return this}setClearColor(t,e=1){let i=new De(t);return this.boundViewer&&typeof this.boundViewer.setClearColor=="function"&&this.boundViewer.setClearColor(i.r,i.g,i.b,e),this}clear(){return this}dispose(){}render(t,e){if(this.isSandboxed){Oe.validate(t);let r=(s,a)=>{typeof self<"u"&&typeof self.postMessage=="function"&&(a&&a.length?self.postMessage(s,a):self.postMessage(s))};if(this.hasInitialModelRendered){let s=t.getMeshTransforms(),a={};for(let[o,n]of s.entries())a[o]=Array.from(n);r({type:"3D_UPDATE_TRANSFORMS",containerId:this.containerId,transforms:a})}else{this.hasInitialModelRendered=!0;let s=Ci(t),a=Pi(t),o=(s.lights||[]).map(n=>({type:n.type,color:n.color,intensity:n.intensity,position:n.position}));r({type:"3D_MODEL_READY",containerId:this.containerId,glbBuffer:a.buffer,dynamicLights:o,camera:e?{fov:e.fov||60,position:[e.position.x,e.position.y,e.position.z]}:void 0},[a.buffer])}return}let i=this.boundViewer;!i&&this.domElement?.parentElement&&this.domElement.parentElement.threeLiveViewer&&(i=this.domElement.parentElement.threeLiveViewer,this.boundViewer=i),!i&&typeof window<"u"&&(i=window.__three_live_active_viewer__,this.boundViewer=i),i&&typeof i.loadModel=="function"&&(i._hasThreeLiveModelLoaded?typeof i.updateMeshTransforms=="function"&&i.updateMeshTransforms(t.getMeshTransforms()):(i.loadModel(t.toCanvas3D()),i._hasThreeLiveModelLoaded=!0))}};function Ei(){return typeof globalThis<"u"&&typeof globalThis.__three_live_sim_time_ms__=="number"?globalThis.__three_live_sim_time_ms__:typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Ss=class{constructor(t=!0){this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1,this.autoStart=t,t&&this.start()}start(){this.startTime=Ei(),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 t=0;if(this.autoStart&&!this.running&&this.start(),this.running){let e=Ei();t=(e-this.oldTime)/1e3,this.oldTime=e,this.elapsedTime+=t}return t}};function As(){}var dt=new Proxy(As,{get:(t,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:dt},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>dt,construct:()=>dt}),_i=(()=>{try{if(typeof document>"u")return null;let t=document.currentScript;return t?.src?t.src:t?.textContent&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(new Blob([t.textContent],{type:"text/javascript"})):null}catch{return null}})();function pt(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function Ke(t,e){if(!t||typeof t!="string")return!1;let i=t.trim();if(!i)return!1;try{let r=new URL(i,pt());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 Ni,Ye;function Rs(t){if(!Ke(t))throw new Error(`SecurityError: Refusing to create TrustedScriptURL for disallowed URL "${t}".`);let e=globalThis.trustedTypes;if(!e||typeof e.createPolicy!="function")return t;if(Ye===void 0||Ni!==e){Ni=e;try{Ye=e.createPolicy("three-live#worker",{createScriptURL:i=>{if(!Ke(i))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${i}".`);return i}})}catch{Ye=null}}return Ye?Ye.createScriptURL(t):t}function Li(){let t=he().sandboxEngineSrc;if(t)return t;if(_i)return _i;try{if(typeof document>"u")return null;let e=pt(),i=Array.from(document.querySelectorAll("script[src]"));for(let r of i){let s=r.src;if(!s)continue;let a=new URL(s,e).pathname;if(/(?:^|\/)(?:three|xr)-live[^/]*\.js$/.test(a)&&Ke(s,{requireSameOrigin:!0}))return s}}catch{}return null}function It(t,e){if(!Ke(t))throw new Error(`SecurityError: Refusing to load ${e} from disallowed URL "${t}". Only http:, https:, and blob: URLs are permitted.`);return new URL(t,pt()).href}function Ts(){let t=Li();if(!t)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.");return It(t,"sandbox engine")}function Cs(){let t=he().sandboxIframeSrc;if(t)return t;let e=Li();if(!e||!Ke(e))return null;let i=new URL(e,pt());return i.protocol==="blob:"?null:new URL("three-live-sandbox.html",i).href}function Ps(){let t=Cs();if(!t)throw new Error("Three-Live could not locate three-live-sandbox.html for iframe sandbox execution. Set ThreeLiveElement.sandboxIframeSrc (or ThreeLiveElement.sandboxEngineSrc) explicitly.");return It(t,"sandbox iframe")}function Es(){return!!he().allowClientScripts}function _s(t){return It(t,"procedural scene script")}var Ns=["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 Ls(t,e){let i=self,r=t.nonce,s=t.engineSrc,a=t.allowedScriptUrl,o=t.allowClientScripts,n=t.revoked,l=i.postMessage.bind(i);function h(u){l({type:"ERROR",nonce:r,message:String(u)})}let c=typeof i.importScripts=="function"?i.importScripts.bind(i):null,f=a,g=null;try{let u=s;if(typeof i.trustedTypes<"u"&&i.trustedTypes&&typeof i.trustedTypes.createPolicy=="function")try{let m={createScriptURL:function(S){if(S!==s&&(!a||S!==a))throw new TypeError("Disallowed worker importScripts URL");return S}};o&&(m.createScript=function(S){return String(S)});let v=i.trustedTypes.createPolicy("three-live#worker-boot",m);u=v.createScriptURL(s),a&&(f=v.createScriptURL(a)),o&&typeof v.createScript=="function"&&(g=v.createScript.bind(v))}catch{}c(u)}catch(u){h('Sandbox failed to load the Three-Live engine from "'+s+'". It must be a same-origin (or CORS-enabled) IIFE bundle such as three-live.min.js. Underlying error: '+(u&&u.message||u));return}let w=i.THREE;if(!w||typeof w.Scene!="function"){h('Sandbox loaded "'+s+'" 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 u=i.__THREE_LIVE_REGISTRY__;for(let m=0;m<e.length;m++)if(typeof e[m]=="function")try{e[m](w,u)}catch{}}function d(u,m,v){let S=i;for(;S&&S!==Object.prototype;){if(!v&&S!==i)try{delete S[u]}catch{}if(!v||S===i||Object.prototype.hasOwnProperty.call(S,u))try{Object.defineProperty(S,u,v?{value:m,writable:!1,configurable:!1}:{value:m,writable:!1,configurable:!1,enumerable:!1})}catch{}try{S=Object.getPrototypeOf(S)}catch{break}}}for(let u=0;u<n.length;u++)d(n[u],void 0);d("performance",Object.freeze({now:function(){return Date.now()}}));let p=["3D_MODEL_READY","3D_UPDATE_TRANSFORMS"],A=!1;function b(u,m){if(u.type==="3D_MODEL_READY"){if(A)return;A=!0}u.nonce=r,m&&m.length?l(u,m):l(u)}d("postMessage",function(u,m){if(!u||p.indexOf(u.type)===-1)throw new Error("Sandboxed scripts may only post Three-Live scene messages ("+p.join(", ")+").");b(u,m)},!0);let x=!1;i.onmessage=function(u){let m=u&&u.data;if(!(!m||m.nonce!==r)&&!(m.type!=="EXECUTE"&&m.type!=="EXECUTE_URL")&&!x){x=!0;try{let v=new w.Scene,S=new w.PerspectiveCamera(60,1,.1,1e3),_=new w.WebGLRenderer({isSandboxed:!0});if(m.type==="EXECUTE_URL"){if(!a||m.scriptUrl!==a||typeof c!="function"){h("SecurityError: Refusing to execute unapproved script URL inside sandbox worker.");return}let D=f||a,P=c;if(c=null,f=null,i.THREE=w,i.scene=v,i.camera=S,i.renderer=_,P(D),typeof i.__THREE_LIVE_SCENE__=="function"){let N=i.__THREE_LIVE_SCENE__(w,v,S,_);N&&typeof N.toGLB=="function"&&(v=N)}else i.scene&&typeof i.scene.toGLB=="function"&&(v=i.scene)}else{if(!o){h("SecurityError: Client-modified script compilation (Use Case 1) is disabled in this sandbox worker.");return}let D=g?(0,eval)(g(`(function (THREE, scene, camera, renderer) {
324
371
  return (function () {
325
- `+C.script+`
372
+ `+m.script+`
373
+ ;
374
+ return typeof scene === "object" && scene ? scene : undefined;
326
375
  })();
327
376
  })`)):new Function("THREE","scene","camera","renderer",`return (function () {
328
- `+C.script+`
329
- })();`);h=null;let v=x(b,w,R,L);v&&typeof v.toGLB=="function"&&(w=v)}if(!T){b.SceneQuotaValidator&&b.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=(J().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 Te=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,Te++;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=()=>{},b=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),Te=Math.max(0,Te-1),typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("message",b),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",b),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 y=document.body||document.documentElement;if(!y||typeof y.appendChild!="function"){h();let d=new Error("SecurityError: Cannot mount sandbox iframe because document.body is unavailable.");throw r.onError?.(d),d}return y.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(Te>=32)return r(`SecurityError: ${Te} 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 b=h instanceof Error?h.message:String(h);return r(b,"Security Error: sandbox engine URL is not configured.")}if(e==="iframe"){let h;try{h=qr()}catch(b){let y=b instanceof Error?b.message:String(b);return r(y,"Security Error: sandbox iframe URL is not configured.")}try{return Promise.resolve(ri(n,i,h,t))}catch(b){return Promise.reject(b)}}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"}),b=URL.createObjectURL(h);try{let y=Wr(b);c=new Worker(y)}finally{URL.revokeObjectURL(b)}}catch(h){let b=h instanceof Error?h.message:String(h);return r(`Failed to initialize Web Worker for sandboxed execution (CSP may block blob workers): ${b}`,"Security Error: Failed to start Worker sandbox.")}Te++;let a=!1,u={modelDispatched:!1},l,m=()=>{a||(a=!0,l!==void 0&&clearTimeout(l),Te=Math.max(0,Te-1),c.terminate())};return l=setTimeout(()=>{a||(m(),or(t))},3e3),c.onmessage=h=>{let b=cr(h.data,s);b&&ur(b,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)}},Rt=new Set;function xe(n,e){let t=`[three-live] ${n} is unsupported; degraded to ${e}.`;Rt.has(t)||(Rt.add(t),typeof console<"u"&&typeof console.warn=="function"&&console.warn(t))}function ii(){return Array.from(Rt)}function si(){Rt.clear()}var Mt=class extends Be{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=Mt,He=class extends ft{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 He{constructor(e=1,t=0){super(e,t,"IcosahedronGeometry")}},ln=class extends He{constructor(e=1,t=0){super(e,t,"OctahedronGeometry")}},hn=class extends He{constructor(e=1,t=0){super(e,t,"DodecahedronGeometry")}},mn=class extends He{constructor(e=1,t=0){super(e,t,"TetrahedronGeometry")}},dn=class extends De{constructor(e=1,t=1,r=4,i=8){xe("CapsuleGeometry","CylinderGeometry"),super(e,e,t+e*2,i)}},fn=class extends De{constructor(e=.5,t=1,r=16){xe("RingGeometry","CylinderGeometry"),super(t,t,.01,Math.max(8,r))}},pn=class extends De{constructor(e=1,t=16){xe("CircleGeometry","CylinderGeometry"),super(e,e,.01,Math.max(8,t))}},bn=class extends xt{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}},St=class extends gt{constructor(e,t,r){xe("HemisphereLight","AmbientLight"),super(e,r),this.groundColor=new ve(t??4473924)}},ai=St,lr={Vector2:Ht,Vector3:ue,Vector4:Gt,Euler:ht,Quaternion:mt,Matrix4:Oe,Matrix3:Xt,Color:ve,MathUtils:Hr,BufferAttribute:pe,Float32BufferAttribute:Wt,Uint16BufferAttribute:$t,Uint32BufferAttribute:Yt,BufferGeometry:ge,BoxGeometry:dt,PlaneGeometry:qt,SphereGeometry:ft,CylinderGeometry:De,ConeGeometry:jt,TorusGeometry:Kt,TorusKnotGeometry:Zt,IcosahedronGeometry:un,OctahedronGeometry:ln,DodecahedronGeometry:hn,TetrahedronGeometry:mn,CapsuleGeometry:dn,RingGeometry:fn,CircleGeometry:pn,Texture:pt,TextureLoader:Jt,Material:Ae,MeshStandardMaterial:Be,MeshBasicMaterial:Qt,MeshLambertMaterial:en,MeshPhongMaterial:tn,MeshPhysicalMaterial:nn,ShaderMaterial:Mt,RawShaderMaterial:oi,Object3D:we,Group:rn,Mesh:Ve,InstancedMesh:yt,Light:ze,AmbientLight:gt,DirectionalLight:sn,PointLight:xt,SpotLight:bn,HemisphereLight:St,RectAreaLight:ai,Camera:vt,PerspectiveCamera:on,Scene:wt,WebGLRenderer:an,Clock:cn,SceneQuotaValidator:Se,exportSceneToCanvas3D:nr,exportSceneToGLB:rr,exportSceneToUSDZ:Gr,generateUSDZ:ct,glbToUSDZ:at,sceneToCanvas3D:Ye,sceneToGLB:ot,sceneToUSDZ:qe,authorScriptRunner:yn,getAuthorWarnings:ii,clearAuthorWarnings:si};Object.freeze(Se);Object.freeze(Se.prototype);Object.freeze(wt.prototype);Object.freeze(lr);var Pe=new Proxy(lr,{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("__")&&xe(`THREE.${e}`,"no-op proxy"),ut)},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")}}),lt=J();lt.threeNamespace=Pe;if(lt.workerExtensionInstallers)for(let n of lt.workerExtensionInstallers)n(Pe,lt);var zt={name:"three_author",THREE:Pe};var Me=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;typeof Me.THREE>"u"&&(Me.THREE=Pe);typeof Me.requestAnimationFrame!="function"&&(Me.requestAnimationFrame=n=>(typeof n=="function"&&typeof Me.__three_live_raf_cb__!="function"&&(Me.__three_live_raf_cb__=n),Me.__three_live_in_step__||xe("requestAnimationFrame","single-frame static evaluation"),0));typeof Me.cancelAnimationFrame!="function"&&(Me.cancelAnimationFrame=()=>{});if(typeof window<"u"){let n=window;n.ThreeLive=n.ThreeLive||{},n.ThreeLive.THREE=Pe,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 xn=(n,e,t)=>({x:n,y:e,z:t,toString:()=>`${n}m ${e}m ${t}m`}),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 le=class le 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 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){me.registerDecoder(t,r)}static getDecoder(t){return me.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.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 me.getRegisteredPlugins())i.onElementConnected?.(this)}disconnectedCallback(){for(let t of me.getRegisteredPlugins())t.onElementDisconnected?.(this);this.scriptHandle?.terminate(),this.scriptHandle=null,this.mutationObserver?.disconnect(),this.mutationObserver=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.activeXRSession?.stop?.().catch?.(()=>{}),this.activeXRSession=null,this.toastTimer&&clearTimeout(this.toastTimer),this.toastTimer=null,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(Le(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 me.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 Le(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():[]}fireEvent(t,r){this.dispatchEvent(new CustomEvent(t,{bubbles:!0,composed:!0,detail:r}))}setSlotVisible(t,r){let i=typeof this.querySelector=="function"?this.querySelector(`[slot="${t}"]`):null;i&&(i.hidden=!r,i.style&&(i.style.display=r?"":"none"))}emitError(t,r="script"){this.setSlotVisible("error",!0),this.fireEvent("error",{error:t}),this.fireEvent("three-error",{error:t,message:t?.message||String(t),stage:r})}selectVariant(t){if(!this.viewer)return!1;let r=this.viewer.selectVariant(t);return r&&this.fireEvent("variant-applied",{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():xn(0,0,0)}getFieldOfView(){return this.viewer?this.viewer.getFieldOfView():45}jumpCameraToGoal(){this.viewer?.jumpCameraToGoal()}toDataURL(t,r){return this.viewer?.render?.(),this.canvas?this.canvas.toDataURL(t,r):""}toBlob(t){return 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){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:xn(s,o,c),normal:xn(a,u,l)}}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=Re(i);this.viewer.loadGLBData(s,r),this.currentModel=s,this.currentModelLimits=r,this.isModelLoaded=!0,this.hidePoster(),this.setSlotVisible("error",!1),this.updateHotspots();let o=this.getAttribute("selected-mesh");o&&this.viewer.setSelectedMesh(o);let c=this.getAttribute("variant-name");c&&this.selectVariant(c),this.fireEvent("load",{model:s}),this.fireEvent("three-load",{model:s,source:typeof t=="string"?"src":"model"})}catch(i){throw this.emitError(i,"load"),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);let s=()=>{i&&(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)")};typeof requestAnimationFrame<"u"?requestAnimationFrame(s):s(),this.toastTimer=setTimeout(()=>{i&&(i.style.opacity="0",i.style.transform="translateX(-50%) translateY(10px)"),this.toastTimer=null},r)}async activateAR(){this.activeXRSession?.isSessionActive?.()&&(await this.activeXRSession.stop().catch(()=>{}),this.activeXRSession=null);let t=(s,o=s.message)=>{throw this.fireEvent("ar-status",{status:"failed",error:s}),this.showToast(o,6e3),s};this.currentModel||t(new Error("No 3D model is loaded in <three-live>.")),le.arProvider||t(new Error("AR module not bundled. Use the default 'three-live' bundle or call ThreeLiveElement.registerAR()."));let r=this.getAttribute("ios-src"),i=(this.getAttribute("ar-modes")||"").split(/\s+/).filter(Boolean);try{this.fireEvent("ar-status",{status:"session-started"});let s=await le.arProvider.activateAR({model:r||this.currentModel,glbUrl:typeof this.currentModel=="string"?this.currentModel:void 0,view:this.viewer||void 0,element:this,preferredModes:i.length>0?i:void 0,arScale:this.arScale,arPlacement:this.arPlacement,webXROptions:{onExit:()=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"not-presenting"})},onError:o=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"failed",error:o}),this.showToast(`AR error: ${o.message}`,6e3)}}});if(s.success){s.session&&(this.activeXRSession=s.session);let o=s.mode==="quick-look"?"Opening Apple AR Quick Look...":s.mode==="scene-viewer"?"Opening Google Scene Viewer...":s.mode==="webxr"?"WebXR AR session started.":"";o&&this.showToast(o)}else{let o=typeof navigator<"u"&&navigator.userAgent||"",c=/Macintosh/i.test(o)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1),a=/Android|iPhone|iPad|iPod/i.test(o),u=s.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.";if(c&&!a&&typeof document<"u"&&this.currentModel&&le.arProvider.createUSDZBlob)try{let l=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:le.arProvider.createUSDZBlob(this.currentModel),m=URL.createObjectURL(l),h=document.createElement("a");h.href=m,h.download="three_live_model.usdz",document.body.appendChild(h),h.click(),document.body.removeChild(h),setTimeout(()=>URL.revokeObjectURL(m),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(u,6e3)}else this.showToast(u,6e3);s.error&&this.fireEvent("ar-status",{status:"failed",error:s.error})}return s}catch(s){return this.activeXRSession=null,t(s,`AR error: ${s.message||String(s)}`)}}setupDOM(){let t=this.querySelector("canvas");t||(t=document.createElement("canvas"),t.style.cssText=`width:100%;height:100%;display:block;touch-action:${this.cameraControls?"none":"auto"};outline:none`,this.appendChild(t)),this.canvas=t,typeof t.addEventListener=="function"&&!t.__tlCtxBound&&(t.__tlCtxBound=!0,t.addEventListener("webglcontextlost",i=>this.fireEvent("three-context-lost",{originalEvent:i})),t.addEventListener("webglcontextrestored",i=>this.fireEvent("three-context-restored",{originalEvent:i}))),this.setSlotVisible("error",!1),this.isModelLoaded||this.setSlotVisible("poster",!0);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 me(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.fireEvent("meshclick",u)},onCameraChange:u=>{this.updateHotspots();for(let l of me.getRegisteredPlugins())l.onCameraChange?.(this.viewer,this);this.fireEvent("camera-change",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.cssText="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity .35s ease-out;pointer-events:none;z-index:1",this.appendChild(this.posterEl)),this.posterEl.src=t,this.isModelLoaded||(this.posterEl.style.opacity="1")}}hidePoster(){this.setSlotVisible("poster",!1),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");for(let[c,a]of[["width","20"],["height","20"],["viewBox","0 0 24 24"],["fill","none"],["stroke","currentColor"],["stroke-width","2"],["stroke-linecap","round"],["stroke-linejoin","round"]])s.setAttribute(c,a);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 16zM3.27 6.96 12 12.01l8.73-5.05M12 22.08V12"),s.appendChild(o),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=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,i,s]=t.trim().split(/\s+/),o=s&&s!=="auto"?parseFloat(s):NaN;return{theta:r&&r!=="auto"?this.parseFieldOfView(r):void 0,phi:i&&i!=="auto"?this.parseFieldOfView(i):void 0,distance:isNaN(o)?void 0:o}}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(parseFloat);return r.length>=3&&!r.some(isNaN)?[r[0],r[1],r[2]]:void 0}parseFieldOfView(t){if(!t)return;let r=parseFloat(t);return isNaN(r)?void 0:t.endsWith("rad")?r*180/Math.PI: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 me.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}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.emitError(i,"script"),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.emitError(a,"script"),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(!le.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(Je);return this.showToast(Qe),this.emitError(r,"security"),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=me.registerPlugin,le.getRegisteredPlugins=me.getRegisteredPlugins;var _e=le;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",_e);function wn(){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 Rn(){if(typeof navigator>"u")return!1;let n=navigator.userAgent||"";return/android/i.test(n)}async function Mn(){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 Et()).bestMode}async function Et(){let[n,e,t]=await Promise.all([Mn(),Promise.resolve(wn()),Promise.resolve(Rn())]),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=At(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 At(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 At(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=At(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",At(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 Ne=null;function fi(n,e){let r=new Float32Array(144),i=new Float32Array(144),s=new Float32Array(96),o=new Uint16Array(144);for(let m=0;m<24;m++){let h=m/24*Math.PI*2,b=Math.cos(h),y=Math.sin(h),d=m*2,g=d+1,T=(m+1)%24*2;r[d*3]=b*.11,r[d*3+1]=.002,r[d*3+2]=y*.11,r[g*3]=b*.145,r[g*3+1]=.002,r[g*3+2]=y*.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,b)=>{let y=n.createBuffer();return n.bindBuffer(34962,y),n.bufferData(34962,m,35044),n.enableVertexAttribArray(h),n.vertexAttribPointer(h,b,5126,!1,0,0),y},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 vn=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.");Ne&&Ne!==this&&Ne.isSessionActive()&&await Ne.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),b=o?i.arScale==="fixed"?1:h?.55:1:i.arScale==="fixed"?1:a>.45?.3/a:a<.05?.12/Math.max(a,.001):1,y=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 F=document.createElement("button");F.type="button",F.textContent="\u2715 Exit AR",F.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",F.addEventListener("beforexrselect",G=>G.preventDefault()),F.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(F),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 ae)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 A=E=>{let F=String(E?.name||"");return F==="NotAllowedError"||F==="SecurityError"};try{this.s=await r.requestSession(d,p)}catch(E){if(f(),A(E))throw i.onError?.(E),E;try{this.s=await r.requestSession(d,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(F){if(A(F))throw i.onError?.(F),F;try{this.s=await r.requestSession(d)}catch(G){throw i.onError?.(G),G}}}let C=this.s;Ne=this,this.placed=!1;let w=null,R=null,L=null,x=null,v=null,I=[0,-.25,-1.2],S=[0,-.25,-1.2],_=new Float32Array(16),k=new Float32Array(16),N=!1,V=1,U=0,B=!1,D=null,H=null,z=0,O=null,X=()=>{Ne===this&&(Ne=null),O?.(),O=null;try{R?.cancel?.()}catch{}if(R=null,L){let E=e?.meshes;if(Array.isArray(E)){let G=E.indexOf(L);G!==-1&&E.splice(G,1)}let F=e.getGLContext?.()||e?.gl;if(F)for(let G of L.primitives||[]){F.deleteVertexArray?.(G.vao);for(let W of G.buffers||[])F.deleteBuffer?.(W)}L=null}e?.setXRSessionActive?.(!1),f(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=X,C.addEventListener("end",()=>{X(),i.onExit?.()}),C.addEventListener("select",()=>{if(!this.placed){let E=v||I;S=[E[0],E[1],E[2]],mr(this.placedMat,S,y,U,b*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 F=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;E&&typeof F=="function"&&typeof C.updateRenderState=="function"&&C.updateRenderState({baseLayer:new F(C,E,{alpha:!0})});try{w=await C.requestReferenceSpace("local")}catch{try{w=await C.requestReferenceSpace("local-floor")}catch{w=await C.requestReferenceSpace("viewer")}}let G=await C.requestReferenceSpace("viewer").catch(()=>w);if(typeof C.requestHitTestSource=="function"&&G&&(R=await C.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),ne=Y=>Math.atan2(Y.touches[1].clientY-Y.touches[0].clientY,Y.touches[1].clientX-Y.touches[0].clientX),ce=Y=>{this.s&&(Y.touches.length===1&&this.placed?B=!0:Y.touches.length>=2&&(B=!1,D=j(Y),H=ne(Y)))},q=Y=>{if(!this.s||Y.touches.length<2)return;let re=j(Y),$=ne(Y);if(D&&D>4&&i.arScale!=="fixed"&&(V=Math.max(.15,Math.min(6,V*(re/D)))),H!==null){let te=$-H;te>Math.PI&&(te-=Math.PI*2),te<-Math.PI&&(te+=Math.PI*2),U-=te}D=re,H=$},Z=Y=>{(!Y.touches||Y.touches.length===0)&&(B=!1),(!Y.touches||Y.touches.length<2)&&(D=null,H=null)};window.addEventListener("touchstart",ce,{passive:!0}),window.addEventListener("touchmove",q,{passive:!0}),window.addEventListener("touchend",Z,{passive:!0}),window.addEventListener("touchcancel",Z,{passive:!0}),O=()=>{window.removeEventListener("touchstart",ce),window.removeEventListener("touchmove",q),window.removeEventListener("touchend",Z),window.removeEventListener("touchcancel",Z)}}e.setXRSessionActive?.(!0);let W=(j,ne)=>{if(this.s!==C)return;C.requestAnimationFrame(W);let ce=z>0?Math.min(Math.max((j-z)/1e3,0),.1):1/60;z=j,e?.stepXRUpdate?.(ce);let q=ne.getViewerPose(w);if(!q)return;let Z=q.views?.[0];if(!N&&Z?.transform){let Q=Z.transform.position,ie=Z.transform.matrix,be=Q?.x??(ie?ie[12]:0),he=Q?.y??(ie?ie[13]:0),de=Q?.z??(ie?ie[14]:0),Ee=ie?-ie[8]:0,Xe=ie?-ie[10]:-1,_t=Math.hypot(Ee,Xe);_t>1e-4?(Ee/=_t,Xe/=_t):(Ee=0,Xe=-1),I=[be+Ee*1.2,he-.25,de+Xe*1.2],U=Math.atan2(-Ee,-Xe),N=!0}if(R&&typeof ne.getHitTestResults=="function"&&(!this.placed||B)){let Q=ne.getHitTestResults(R)||[],ie=!1;for(let be of Q){let he=be.getPose(w);if(he?.transform?.matrix){let de=he.transform.matrix,Ee=de[5];if(i.arPlacement==="wall"&&Math.abs(Ee)>.35||i.arPlacement==="floor"&&Math.abs(Ee)<.65)continue;x||(x=new Float32Array(16)),x.set(de),v=[de[12],de[13],de[14]],this.placed&&B&&(S=[de[12],de[13],de[14]]),L&&(L.visible=!this.placed||B,L.transform.set(de)),!this.placed&&P&&(P.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),i.onHit?.(x),ie=!0;break}}!ie&&L&&(L.visible=!1)}mr(_,this.placed?S:v||I,y,U,b*V),this.placed&&this.placedMat.set(_);let Y=e.xrRigMatrix;Y instanceof Float32Array&&Y.length===16?oe(k,Y,_):k.set(_),e.modelRootMatrix&&e.modelRootMatrix.set(k);for(let Q of ae)Q.onXRFrame?.(e,C,ne,w);let re=e.getGLContext?.()||e?.gl,$=C.renderState?.baseLayer;re&&$&&$.framebuffer!==void 0&&re.bindFramebuffer(36160,$.framebuffer);let te=d==="immersive-ar",ee=q.views||[];for(let Q=0;Q<ee.length;Q++){let ie=ee[Q];if(typeof e.renderXRView=="function"){let be;if($&&typeof $.getViewport=="function"){let he=$.getViewport(ie);he&&he.width>0&&he.height>0&&(be=[he.x,he.y,he.width,he.height])}else $?.framebufferWidth>0&&$?.framebufferHeight>0&&(be=[0,0,$.framebufferWidth,$.framebufferHeight]);e.renderXRView(ie,k,this.placed,be,te,Q)}}re&&$&&$.framebuffer&&re.bindFramebuffer(36160,null)};C.requestAnimationFrame(W)}catch(E){throw typeof C.end=="function"&&await C.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 Tt(n){let e=await Et(),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=Ue(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 vn(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}`)}}_e.registerAR({activateAR:Tt,createUSDZBlob:Ue});_e.registerScriptRunner(yn);Ze(En);return xr(pi);})();
377
+ `+m.script+`
378
+ ;
379
+ return typeof scene === "object" && scene ? scene : undefined;
380
+ })();`);g=null;let P=D(w,v,S,_);P&&typeof P.toGLB=="function"&&(v=P)}if(!A){w.SceneQuotaValidator&&w.SceneQuotaValidator.validate(v);let D=v.toGLB(),P=D instanceof ArrayBuffer?D:D.buffer.slice(D.byteOffset,D.byteOffset+D.byteLength);b({type:"3D_MODEL_READY",glbBuffer:P},[P])}l({type:"DONE",nonce:r})}catch(v){h(v&&v.message||v)}}},l({type:"READY",nonce:r})}function Di(t,e,i){let r=i?.allowedScriptUrl??null,s=i?.allowClientScripts??r===null,a={nonce:e,engineSrc:t,allowedScriptUrl:r,allowClientScripts:s,revoked:Ns},o=(he().workerExtensionInstallers??[]).map(n=>`(${n.toString()})`).join(",");return`'use strict';(${Ls.toString()})(${JSON.stringify(a)},[${o}]);`}function ki(t){t.onError?.(new Error("SecurityError: Sandboxed script exceeded SECURITY_3D_SANDBOX_TIMEOUT_MS (3000 ms) and was terminated.")),t.onToast?.("Security Error: script timed out and was stopped.")}var Fe=0;function Fi(){try{let t=new Uint32Array(4);return globalThis.crypto?.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(8,"0")).join("")}catch{return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}}function Ds(t){try{return new TextEncoder().encode(t).length}catch{return t.length}}var ks=1024,Fs=256;function Ii(t){if(!Array.isArray(t)&&!(t instanceof Float32Array)||t.length!==16)return!1;for(let e=0;e<16;e++){let i=t[e];if(typeof i!="number"||!Number.isFinite(i))return!1}return!0}function Oi(t,e){if(!t||typeof t!="object")return null;let i=t;if(i.nonce!==e)return null;switch(i.type){case"READY":return{type:"READY"};case"DONE":return{type:"DONE"};case"ERROR":return{type:"ERROR",message:(typeof i.message=="string"?i.message:String(i.message??"Unknown worker error")).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").slice(0,ks)};case"3D_UPDATE_TRANSFORMS":{let r=i.transforms;if(Array.isArray(r)){if(r.length>1e3)return null;for(let s of r)if(!Ii(s))return null;return{type:"3D_UPDATE_TRANSFORMS",transforms:r}}if(r&&typeof r=="object"){let s=Object.keys(r);if(s.length>1e3)return null;let a=Object.create(null),o=r;for(let n of s){if(n.length>Fs||n==="__proto__"||n==="constructor"||n==="prototype")return null;let l=o[n];if(!Ii(l))return null;a[n]=l}return{type:"3D_UPDATE_TRANSFORMS",transforms:a}}return null}case"3D_MODEL_READY":{let r=i.glbBuffer;return!(r instanceof ArrayBuffer)||r.byteLength>16777216?null:{type:"3D_MODEL_READY",payload:r}}default:return null}}function Is(t){let e=Ds(t);if(e>1048576)throw new Error(`SecurityError: Script length (${e} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function Vi(t,e,i,r){switch(t.type){case"READY":return;case"3D_UPDATE_TRANSFORMS":e.onUpdateTransforms?.(t.transforms);return;case"3D_MODEL_READY":if(r.modelDispatched)return;r.modelDispatched=!0,e.onModelReady(t.payload);return;case"DONE":i();return;case"ERROR":i(),e.onError?.(new Error(`Worker script error: ${t.message}`));return;default:return t}}function Os(t,e,i,r){let s=Fi(),a=Di(e,s,t.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:t.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=i,Fe++;let n=!1,l=!1,h={modelDispatched:!1},c,f=()=>{if(n||l)return;let p=o.contentWindow;!p||typeof p.postMessage!="function"||(l=!0,p.postMessage(t.kind==="url"?{type:"SANDBOX_RUN",nonce:s,workerSource:a,scriptUrl:t.scriptUrl}:{type:"SANDBOX_RUN",nonce:s,workerSource:a,script:t.script},"*"))},g=()=>{},w=p=>{if(n||!o.contentWindow||p.source!==o.contentWindow)return;let A=p.data;if(A&&typeof A=="object"&&A.type==="IFRAME_READY"){f();return}let b=Oi(A,s);b&&Vi(b,r,g,h)};g=()=>{n||(n=!0,c!==void 0&&clearTimeout(c),Fe=Math.max(0,Fe-1),typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("message",w),typeof o.remove=="function"?o.remove():o.parentNode&&o.parentNode.removeChild(o))},c=setTimeout(()=>{n||(g(),ki(r))},3e3),typeof globalThis.addEventListener=="function"&&globalThis.addEventListener("message",w),o.onload=()=>{f()},o.onerror=()=>{g(),r.onError?.(new Error(`Sandbox iframe failed to load "${i}". Verify that three-live-sandbox.html is served at that URL.`))};let d=document.body||document.documentElement;if(!d||typeof d.appendChild!="function"){g();let p=new Error("SecurityError: Cannot mount sandbox iframe because document.body is unavailable.");throw r.onError?.(p),p}return d.appendChild(o),{terminate:g}}function Ui(t,e,i,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(Fe>=32)return r(`SecurityError: ${Fe} 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 s;try{s=Ts()}catch(g){let w=g instanceof Error?g.message:String(g);return r(w,"Security Error: sandbox engine URL is not configured.")}if(e==="iframe"){let g;try{g=Ps()}catch(w){let d=w instanceof Error?w.message:String(w);return r(d,"Security Error: sandbox iframe URL is not configured.")}try{return Promise.resolve(Os(t,s,g,i))}catch(w){return Promise.reject(w)}}let a=Fi(),o=Di(s,a,t.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:t.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),n;try{let g=new Blob([o],{type:"application/javascript"}),w=URL.createObjectURL(g);try{let d=Rs(w);n=new Worker(d)}finally{URL.revokeObjectURL(w)}}catch(g){let w=g instanceof Error?g.message:String(g);return r(`Failed to initialize Web Worker for sandboxed execution (CSP may block blob workers): ${w}`,"Security Error: Failed to start Worker sandbox.")}Fe++;let l=!1,h={modelDispatched:!1},c,f=()=>{l||(l=!0,c!==void 0&&clearTimeout(c),Fe=Math.max(0,Fe-1),n.terminate())};return c=setTimeout(()=>{l||(f(),ki(i))},3e3),n.onmessage=g=>{let w=Oi(g.data,a);w&&Vi(w,i,f,h)},n.onerror=g=>{f(),i.onError?.(new Error(`Worker execution error: ${g.message}`))},t.kind==="url"?n.postMessage({type:"EXECUTE_URL",scriptUrl:t.scriptUrl,nonce:a}):n.postMessage({type:"EXECUTE",script:t.script,nonce:a}),Promise.resolve({terminate:f})}function Bi(t,e){return t==="none"||t==="unsafe-host-realm"?e(`SecurityError: sandbox="${t}" is prohibited. Sandboxing is mandatory for live compilation and cannot be bypassed. Use sandbox="worker" (default) or sandbox="iframe".`,`Security Error: sandbox="${t}" is not permitted.`):t!=="worker"&&t!=="iframe"?e(`SecurityError: Unsupported sandbox mode "${t}". Live compilation requires sandbox="worker" or sandbox="iframe".`,"Security Error: unsupported sandbox mode."):null}var zi=t=>(e,i)=>{let r=new Error(e);return t.onError?.(r),i&&t.onToast?.(i),Promise.reject(r)},$i={execute(t,e,i,r){let s=zi(i),a=Bi(e,s);if(a)return a;try{Is(t)}catch(o){let n=o instanceof Error?o.message:String(o);return s(n,"Security Error: script exceeds the size limit.")}return r?.allowClientScripts??Es()?Ui({kind:"script",script:t},e,i,s):s(Gt,Wt)},executeUrl(t,e,i){let r=zi(i),s=Bi(e,r);if(s)return s;let a;try{a=_s(t)}catch(o){let n=o instanceof Error?o.message:String(o);return r(n,"Security Error: disallowed scene script URL.")}return Ui({kind:"url",scriptUrl:a},e,i,r)}},ft=new Set;function $e(t,e){let i=`[three-live] ${t} is unsupported; degraded to ${e}.`;ft.has(i)||(ft.add(i),typeof console<"u"&&typeof console.warn=="function"&&console.warn(i))}function Vs(){return Array.from(ft)}function Us(){ft.clear()}var Hi=class extends ut{constructor(t={}){$e("ShaderMaterial","MeshStandardMaterial");let e=t.uniforms||{},i=e.color?.value??e.uColor?.value??e.diffuse?.value??t.color;super({color:i!==void 0?i:8421504,opacity:e.opacity?.value??t.opacity??1,transparent:!!t.transparent,wireframe:!!t.wireframe,side:t.side}),this.uniforms=e}},Bs=Hi,Ze=class extends be{constructor(t=[],e=[],i=1,r=0){super();let s=Number(i)||1,a=Math.max(0,Math.min(7,Math.floor(Number(r)||0))),o=a+1,n=[],l=[],h=[],c=[],f=new re,g=new re,w=new re,d=(b,x)=>x.set(t[b*3]||0,t[b*3+1]||0,t[b*3+2]||0),p=(b,x)=>{let u=b.clone().normalize();n.push(u.x*s,u.y*s,u.z*s),l.push(x.x,x.y,x.z),h.push(Math.atan2(u.z,-u.x)/(2*Math.PI)+.5,1-Math.acos(Math.max(-1,Math.min(1,u.y)))/Math.PI)},A=(b,x,u)=>{let m=n.length/3,v=a===0?new re().subVectors(u,x).cross(new re().subVectors(b,x)).normalize():null;p(b,v||b.clone().normalize()),p(x,v||x.clone().normalize()),p(u,v||u.clone().normalize()),c.push(m,m+1,m+2)};for(let b=0;b<e.length;b+=3){d(e[b],f),d(e[b+1],g),d(e[b+2],w);let x=[];for(let u=0;u<=o;u++){x[u]=[];let m=f.clone().lerp(w,u/o),v=g.clone().lerp(w,u/o),S=o-u;for(let _=0;_<=S;_++)x[u][_]=S===0?m.clone():m.clone().lerp(v,_/S)}for(let u=0;u<o;u++)for(let m=0;m<2*(o-u)-1;m++){let v=m>>1;(m&1)===0?A(x[u][v+1],x[u+1][v],x[u][v]):A(x[u][v+1],x[u+1][v+1],x[u+1][v])}}this.setFromBuffers(n,l,h,c)}},zs=class extends Ze{constructor(t=1,e=0){super([1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],t,e)}},gt=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],ji=[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],$s=class extends Ze{constructor(t=1,e=0){super(gt,ji,t,e)}},ce=(1+Math.sqrt(5))/2,Hs=class extends Ze{constructor(t=1,e=0){super([-1,ce,0,1,ce,0,-1,-ce,0,1,-ce,0,0,-1,ce,0,1,ce,0,-1,-ce,0,1,-ce,ce,0,-1,ce,0,1,-ce,0,-1,-ce,0,1],[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],t,e)}},Ae=1/ce,js=class extends Ze{constructor(t=1,e=0){super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-Ae,-ce,0,-Ae,ce,0,Ae,-ce,0,Ae,ce,-Ae,-ce,0,-Ae,ce,0,Ae,-ce,0,Ae,ce,0,-ce,0,-Ae,ce,0,-Ae,-ce,0,Ae,ce,0,Ae],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],t,e)}},Gs=class extends xi{constructor(t=1,e=1,i=4,r=8){let s=Math.max(1e-4,Number(t)||1),a=Math.max(0,Number.isFinite(Number(e))?Number(e):1)*.5,o=Math.max(2,Math.min(64,Math.floor(Number(i)||4))),n=[];for(let l=-1;l<=1;l+=2)for(let h=0;h<=o;h++){if(l>0&&h===0&&a===0)continue;let c=(l<0?h/o-1:h/o)*(Math.PI/2);n.push(new Pe(Math.max(0,Math.cos(c)*s),l*a+Math.sin(c)*s))}super(n,Math.max(4,Math.min(128,Math.floor(Number(r)||8))))}},Gi=class extends be{constructor(t=.5,e=1,i=32,r=1,s=0,a=Math.PI*2){super();let o=Math.max(1e-4,Number(e)||1),n=Number(t),l=Number.isFinite(n)?Math.max(0,n):o*.5,h=Math.max(o,l),c=Math.min(h*.999,Math.min(o,l)),f=Math.max(3,Math.min(256,Math.floor(Number(i)||32))),g=Math.max(1,Math.min(64,Math.floor(Number(r)||1))),w=Number.isFinite(Number(s))?Number(s):0,d=Number.isFinite(Number(a))?Number(a):Math.PI*2,p=[],A=[],b=[],x=[];for(let u=0;u<=g;u++){let m=c+u/g*(h-c);for(let v=0;v<=f;v++){let S=w+v/f*d,_=Math.cos(S),D=Math.sin(S);if(p.push(m*_,m*D,0),A.push(0,0,1),b.push(m/h*_*.5+.5,m/h*D*.5+.5),u<g&&v<f){let P=u*(f+1)+v,N=P+f+1;m>1e-6&&x.push(P,N,P+1),x.push(N,N+1,P+1)}}}this.setFromBuffers(p,A,b,x)}},Ws=class extends Gi{constructor(t=1,e=32,i=0,r=Math.PI*2){super(0,t,e,1,i,r)}},Wi=class extends Re{constructor(t={}){super({roughness:.35,metalness:.1,side:2,...t});let e=Number(t.size);this.size=Number.isFinite(e)?Math.max(.002,Math.min(2,e)):.05,this.sizeAttenuation=t.sizeAttenuation!==!1,t.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.35)}},Ot=class extends Re{constructor(t={}){super({roughness:.4,metalness:.1,side:2,...t});let e=Number(t.linewidth);this.linewidth=Number.isFinite(e)?Math.max(.5,Math.min(20,e)):1,t.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.3)}},Xs=class extends Ot{constructor(t={}){super(t),this.dashSize=Number(t.dashSize)||3,this.gapSize=Number(t.gapSize)||1,this.scale=Number(t.scale)||1}};function Xi(t,e){let i=t?.attributes?.position;if(!i?.array||i.count<3)return new Float32Array(0);let r=i.array,s=t?.index?.array,a=Math.min(8192,Math.floor((s?s.length:i.count)/3)),o=g=>`${Math.round((r[g*3]||0)*1e4)},${Math.round((r[g*3+1]||0)*1e4)},${Math.round((r[g*3+2]||0)*1e4)}`,n=e===void 0,l=n?1:Math.cos(e*Math.PI/180),h={},c=[],f=(g,w)=>c.push(r[g*3]||0,r[g*3+1]||0,r[g*3+2]||0,r[w*3]||0,r[w*3+1]||0,r[w*3+2]||0);for(let g=0;g<a;g++){let w=s?s[g*3]:g*3,d=s?s[g*3+1]:g*3+1,p=s?s[g*3+2]:g*3+2,A=r[w*3]||0,b=r[w*3+1]||0,x=r[w*3+2]||0,u=(r[d*3]||0)-A,m=(r[d*3+1]||0)-b,v=(r[d*3+2]||0)-x,S=(r[p*3]||0)-A,_=(r[p*3+1]||0)-b,D=(r[p*3+2]||0)-x,P=m*D-v*_,N=v*S-u*D,E=u*_-m*S,F=Math.hypot(P,N,E);if(!n&&F<1e-8)continue;F>0&&(P/=F,N/=F,E/=F);let L=[w,d,p];for(let M=0;M<3;M++){let O=L[M],H=L[(M+1)%3],R=o(O),C=o(H);if(R===C)continue;let y=R<C?`${R}|${C}`:`${C}|${R}`,T=h[y];T?T.m||(T.m=1,T.nx*P+T.ny*N+T.nz*E<=l&&f(O,H)):(h[y]={va:O,vb:H,nx:P,ny:N,nz:E,m:n?1:0},n&&f(O,H))}}if(!n){let g=Object.keys(h);for(let w=0;w<g.length;w++){let d=h[g[w]];d&&!d.m&&f(d.va,d.vb)}}return new Float32Array(c)}var qs=class extends be{constructor(t){super(),this.setAttribute("position",new ve(Xi(t),3)),this.__isSegmentPairs=!0}},Ks=class extends be{constructor(t,e=1){super();let i=Number.isFinite(Number(e))?Number(e):1;this.setAttribute("position",new ve(Xi(t,i),3)),this.__isSegmentPairs=!0}};function Ys(t,e,i=1){let r=new be;r.__baked=!0;let s=t?.attributes?.position;if(!s?.array||s.count<2)return r;let a=s.array,o=t.index?.array,n=t.__isSegmentPairs?"segments":e,l=o?o.length:s.count,h=Math.min(4096,Math.max(0,n==="segments"?Math.floor(l/2):n==="loop"&&l>=3?l:l-1));if(h===0)return r;t.computeBoundingBox();let c=t.boundingBox,f=c&&c.max.distanceTo(c.min)||1,g=Math.max(.0015,Math.min(.025,f*.003))*(.5+.5*Math.max(.5,Math.min(6,Number(i)||1))),w=[],d=[],p=[],A=[];for(let b=0;b<h;b++){let x=n==="segments"?b*2:b,u=n==="segments"?b*2+1:(b+1)%l,m=o?o[x]:x,v=o?o[u]:u,S=a[m*3]||0,_=a[m*3+1]||0,D=a[m*3+2]||0,P=(a[v*3]||0)-S,N=(a[v*3+1]||0)-_,E=(a[v*3+2]||0)-D,F=Math.hypot(P,N,E);if(F<1e-6)continue;let L=P/F,M=N/F,O=E/F,H=(Math.abs(M)<.9?Math.hypot(O,L):Math.hypot(O,M))||1,R=Math.abs(M)<.9?O/H:0,C=Math.abs(M)<.9?0:-O/H,y=Math.abs(M)<.9?-L/H:M/H,T=M*y-O*C,z=O*R-L*y,G=L*C-M*R,B=w.length/3,te=[[R,C,y],[T,z,G],[-R,-C,-y],[-T,-z,-G]];for(let I=0;I<2;I++){let W=S+I*P,Z=_+I*N,ae=D+I*E;for(let U=0;U<4;U++){let ee=te[U];w.push(W+ee[0]*g,Z+ee[1]*g,ae+ee[2]*g),d.push(ee[0],ee[1],ee[2]),p.push(U/4,I)}}for(let I=0;I<4;I++){let W=(I+1)%4;A.push(B+I,B+W,B+4+W,B+I,B+4+W,B+4+I)}}return w.length>0&&r.setFromBuffers(w,d,p,A),r}function Zs(t,e=.05){let i=new be;i.__baked=!0;let r=t?.attributes?.position;if(!r?.array||r.count<1)return i;let s=r.array,a=r.count,o=Math.min(a,5e3),n=Math.max(.003,Math.min(.25,(Number(e)||.05)*.6)),l=[],h=[],c=[],f=[];for(let g=0;g<o;g++){let w=a<=5e3?g:Math.floor(g*a/o),d=s[w*3]||0,p=s[w*3+1]||0,A=s[w*3+2]||0,b=g*6;for(let x=0;x<6;x++){let u=gt[x*3],m=gt[x*3+1],v=gt[x*3+2];l.push(d+u*n,p+m*n,A+v*n),h.push(u,m,v),c.push(.5,.5)}for(let x=0;x<24;x++)f.push(b+ji[x])}return i.setFromBuffers(l,h,c,f),i}var Qe=class extends Ie{constructor(t,e,i="strip"){let r=e&&typeof e=="object"?e:{},s=e instanceof Re?e:i==="points"?new Wi(r):new Ot(r),a=t instanceof be?t:new be;super(a,s),this.isLine=!0,this._lineMode=i,this._sourceGeo=a}computeLineDistances(){return this}_bakeAuthorGeometry(){this.geometry&&!this.geometry.__baked&&(this._sourceGeo=this.geometry);let t=this._lineMode==="points";if(t){let e=this._sourceGeo?.attributes?.color;if(e?.array&&e.count>0&&this.material?.color.r===1&&this.material.color.g===1&&this.material.color.b===1){let i=e.array,r=Math.min(e.count,64),s=0,a=0,o=0;for(let n=0;n<r;n++)s+=i[n*3]||0,a+=i[n*3+1]||0,o+=i[n*3+2]||0;this.material.color.setRGB(s/r,a/r,o/r)}}!this.geometry?.__baked&&this._sourceGeo?.attributes?.position?.count>=(t?1:2)&&(this.geometry=t?Zs(this._sourceGeo,this.material?.size??.05):Ys(this._sourceGeo,this._lineMode,this.material?.linewidth??1))}},Qs=class extends Qe{constructor(t,e){super(t,e,"loop"),this.isLineLoop=!0}},Js=class extends Qe{constructor(t,e){super(t,e,"segments"),this.isLineSegments=!0}},ea=class extends Qe{constructor(t,e){super(t,e,"points"),this.isPoints=!0}},ta=class extends Ai{constructor(t,e,i=0,r=Math.PI/3,s=0,a=2){super(t,e,i,a),this.target=new ke,this.type="spot";let o=Number(r);this.angle=Number.isFinite(o)?Math.max(.01,Math.min(Math.PI/2,o)):Math.PI/3;let n=Number(s);this.penumbra=Number.isFinite(n)?Math.max(0,Math.min(1,n)):0}},qi=class extends Si{constructor(t,e,i){$e("HemisphereLight","AmbientLight"),super(t,i),this.groundColor=new De(e??4473924)}},ia=qi,Ki={Vector2:Pe,Vector3:re,Vector4:Yr,Euler:fi,Quaternion:Dt,Matrix4:qe,Matrix3:Zr,Color:De,MathUtils:Qr,BufferAttribute:ve,Float32BufferAttribute:Jr,Uint16BufferAttribute:es,Uint32BufferAttribute:ts,BufferGeometry:be,BoxGeometry:bi,PlaneGeometry:is,SphereGeometry:rs,CylinderGeometry:yi,ConeGeometry:ss,TorusGeometry:as,TorusKnotGeometry:ns,Curve:ze,Curve3:ze,LineCurve3:os,QuadraticBezierCurve3:ls,CubicBezierCurve3:hs,CatmullRomCurve3:us,LatheGeometry:xi,TubeGeometry:cs,PolyhedronGeometry:Ze,IcosahedronGeometry:Hs,OctahedronGeometry:$s,DodecahedronGeometry:js,TetrahedronGeometry:zs,CapsuleGeometry:Gs,RingGeometry:Gi,CircleGeometry:Ws,WireframeGeometry:qs,EdgesGeometry:Ks,FrontSide:0,BackSide:1,DoubleSide:2,NoBlending:0,NormalBlending:1,AdditiveBlending:2,MultiplyBlending:4,RepeatWrapping:1e3,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002,NearestFilter:1003,NearestMipmapNearestFilter:1004,NearestMipmapLinearFilter:1005,LinearFilter:1006,LinearMipmapNearestFilter:1007,LinearMipmapLinearFilter:1008,UnsignedByteType:1009,ByteType:1010,ShortType:1011,UnsignedShortType:1012,IntType:1013,UnsignedIntType:1014,FloatType:1015,HalfFloatType:1016,AlphaFormat:1021,RGBFormat:1022,RGBAFormat:1023,LuminanceFormat:1024,LuminanceAlphaFormat:1025,RedFormat:1028,RGFormat:1030,NoColorSpace:"",SRGBColorSpace:"srgb",LinearSRGBColorSpace:"srgb-linear",StaticDrawUsage:35044,DynamicDrawUsage:35048,ACESFilmicToneMapping:4,PCFSoftShadowMap:2,Texture:kt,DataTexture:ms,TextureLoader:ds,Material:Re,MeshStandardMaterial:ut,MeshBasicMaterial:ps,MeshLambertMaterial:fs,MeshPhongMaterial:gs,MeshPhysicalMaterial:bs,PointsMaterial:Wi,LineBasicMaterial:Ot,LineDashedMaterial:Xs,ShaderMaterial:Hi,RawShaderMaterial:Bs,Object3D:ke,Group:ys,Mesh:Ie,InstancedMesh:wi,Line:Qe,LineLoop:Qs,LineSegments:Js,Points:ea,Light:mt,AmbientLight:Si,DirectionalLight:vs,PointLight:Ai,SpotLight:ta,HemisphereLight:qi,RectAreaLight:ia,Camera:Ri,PerspectiveCamera:xs,Scene:Ti,WebGLRenderer:ws,Clock:Ss,SceneQuotaValidator:Oe,exportSceneToCanvas3D:Ci,exportSceneToGLB:Pi,exportSceneToUSDZ:Ms,generateUSDZ:pi,glbToUSDZ:di,sceneToCanvas3D:rt,sceneToGLB:Et,sceneToUSDZ:Nt,authorScriptRunner:$i,getAuthorWarnings:Vs,clearAuthorWarnings:Us};Object.freeze(Oe),Object.freeze(Oe.prototype),Object.freeze(Ti.prototype),Object.freeze(Ki);var He=new Proxy(Ki,{get:(t,e)=>{if(e in t)return t[e];let i=he().authorNamespace;return i&&typeof e=="string"&&e in i?i[e]:(typeof e=="string"&&e!=="then"&&e!=="toJSON"&&!e.startsWith("__")&&$e(`THREE.${e}`,"no-op proxy"),dt)},has:(t,e)=>{if(e in t)return!0;let i=he().authorNamespace;return!!(i&&typeof e=="string"&&e in i)},set:(t,e)=>{throw new TypeError(`Cannot assign to read only property '${String(e)}' of #<THREE>`)},defineProperty:(t,e)=>{throw new TypeError(`Cannot define property '${String(e)}', object is not extensible`)},deleteProperty:(t,e)=>{throw new TypeError(`Cannot delete property '${String(e)}' of #<THREE>`)},setPrototypeOf:()=>{throw new TypeError("#<THREE> is not extensible")}}),bt=he();if(bt.threeNamespace=He,bt.workerExtensionInstallers)for(let t of bt.workerExtensionInstallers)t(He,bt);var Vt={name:"three_author",THREE:He},Ee=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;if(typeof Ee.THREE>"u"&&(Ee.THREE=He),typeof Ee.requestAnimationFrame!="function"&&(Ee.requestAnimationFrame=t=>(typeof t=="function"&&typeof Ee.__three_live_raf_cb__!="function"&&(Ee.__three_live_raf_cb__=t),Ee.__three_live_in_step__||$e("requestAnimationFrame","single-frame static evaluation"),0)),typeof Ee.cancelAnimationFrame!="function"&&(Ee.cancelAnimationFrame=()=>{}),typeof window<"u"){let t=window;t.ThreeLive=t.ThreeLive||{},t.ThreeLive.THREE=He,t.ThreeLivePlugins=t.ThreeLivePlugins||{},t.ThreeLivePlugins.threeAuthor=Vt,t.ThreeLivePlugins.three_author=Vt,t.ThreeLivePlugins["three-author"]=Vt}function Yi(t,e){let i=t?.trim(),r=i?Number(i):NaN;return Number.isFinite(r)?r:e}var Ut=(t,e,i)=>({x:t,y:e,z:i,toString:()=>`${t}m ${e}m ${i}m`}),ra=typeof HTMLElement<"u"?HTMLElement:class{};typeof CustomEvent>"u"&&typeof Event<"u"&&(globalThis.CustomEvent=class extends Event{constructor(t,e){super(t,e),this.detail=e?.detail??null}});var yt=class ye extends ra{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.loadController=null,this.resizeObserver=null,this.mutationObserver=null}static get arProvider(){return he().arProvider}static set arProvider(e){he().arProvider=e}static get scriptRunner(){return he().scriptRunner}static set scriptRunner(e){he().scriptRunner=e}static get sandboxEngineSrc(){return he().sandboxEngineSrc??null}static set sandboxEngineSrc(e){he().sandboxEngineSrc=e}static get sandboxIframeSrc(){return he().sandboxIframeSrc??null}static set sandboxIframeSrc(e){he().sandboxIframeSrc=e}static get allowClientScripts(){return!!he().allowClientScripts}static set allowClientScripts(e){he().allowClientScripts=e}static registerScriptRunner(e){ye.scriptRunner=e}static defineModelViewer(e="model-viewer"){if(typeof customElements>"u")return!1;let i=customElements.get(e);if(i!=null)return i===ye||i.prototype instanceof ye;class r extends ye{}return customElements.define(e,r),!0}static registerDecoder(e,i){Se.registerDecoder(e,i)}static getDecoder(e){return Se.getDecoder(e)}static registerAR(e){typeof e=="function"?ye.arProvider={activateAR:e}:ye.arProvider=e,typeof document<"u"&&document.querySelectorAll("three-live").forEach(i=>{i instanceof ye&&i.updateARButtonVisibility()})}static isARSupported(){return!!ye.arProvider}getLoadedModel(){return this.currentModel}beginLoad(){let e=this.loadController,i=this.scriptHandle,r=new AbortController;return this.loadController=r,this.scriptHandle=null,e?.abort(),i?.terminate(),r}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 e=this.getAttribute("src"),i=this.getAttribute("script-src");if(e)this.loadModel(e).catch(()=>{});else if(i)this.loadScriptFromSrc(i).catch(()=>{});else{let r=this.querySelector('script[type="text/three"], script[type="text/three-live"]');r&&r.textContent&&this.executeScript(r.textContent).catch(()=>{})}for(let r of Se.getRegisteredPlugins())r.onElementConnected?.(this)}disconnectedCallback(){for(let e of Se.getRegisteredPlugins())e.onElementDisconnected?.(this);this.beginLoad().abort(),this.mutationObserver?.disconnect(),this.mutationObserver=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.activeXRSession?.stop?.().catch?.(()=>{}),this.activeXRSession=null,this.toastTimer&&clearTimeout(this.toastTimer),this.toastTimer=null,this.viewer?.destroy(),this.viewer=null,this.isModelLoaded=!1}attributeChangedCallback(e,i,r){if(i!==r){switch(e){case"src":r&&this.loadModel(r).catch(()=>{});break;case"camera-target":this.applyCameraTarget(r);break;case"min-camera-orbit":case"max-camera-orbit":this.applyOrbitLimits();break;case"field-of-view":this.applyFieldOfView(r);break;case"script-src":r&&this.loadScriptFromSrc(r).catch(()=>{});break;case"sandbox":case"allow-client-scripts":case"ios-src":break;case"poster":this.updatePoster(r);break;case"camera-orbit":this.applyCameraOrbit(r);break;case"selected-mesh":this.viewer&&r!==null&&this.viewer.setSelectedMesh(r);break;case"exposure":if(this.viewer&&r!==null){let s=parseFloat(r);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(Ue(r));break;case"environment-image":this.viewer&&this.viewer.setEnvironmentImage(r).catch(()=>{});break;case"skybox-image":this.viewer&&this.viewer.setSkyboxImage?.(r)?.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(r!==null&&r!=="false");break;case"animation-name":this.viewer&&r!==null&&this.viewer.setAnimationName(r);break;case"variant-name":this.viewer&&this.selectVariant(r);break;case"auto-rotate":this.viewer&&this.viewer.setAutoRotate(r!==null&&r!=="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(r));break;case"ar":this.updateARButtonVisibility();break}for(let s of Se.getRegisteredPlugins())s.onAttributeChanged?.(this,e,i,r)}}getAttr(e){return this.getAttribute(e)}setAttr(e,i){i!==null?this.setAttribute(e,String(i)):this.removeAttribute(e)}getBoolAttr(e){return this.hasAttribute(e)&&this.getAttr(e)!=="false"}setBoolAttr(e,i){this.setAttr(e,i?"":null)}getFloatAttr(e,i){let r=this.getAttr(e);return r!==null?parseFloat(r):i}get src(){return this.getAttr("src")}set src(e){this.setAttr("src",e)}get cameraControls(){return this.getBoolAttr("camera-controls")}set cameraControls(e){this.setBoolAttr("camera-controls",e)}get cameraOrbit(){return this.getAttr("camera-orbit")}set cameraOrbit(e){this.setAttr("camera-orbit",e)}get cameraTarget(){return this.getAttr("camera-target")}set cameraTarget(e){this.setAttr("camera-target",e)}get minCameraOrbit(){return this.getAttr("min-camera-orbit")}set minCameraOrbit(e){this.setAttr("min-camera-orbit",e)}get maxCameraOrbit(){return this.getAttr("max-camera-orbit")}set maxCameraOrbit(e){this.setAttr("max-camera-orbit",e)}get fieldOfView(){return this.getAttr("field-of-view")}set fieldOfView(e){this.setAttr("field-of-view",e)}get iosSrc(){return this.getAttr("ios-src")}set iosSrc(e){this.setAttr("ios-src",e)}get scriptSrc(){return this.getAttr("script-src")}set scriptSrc(e){this.setAttr("script-src",e)}get sandbox(){return this.getAttr("sandbox")||(he().sandboxIframeSrc?"iframe":"worker")}set sandbox(e){this.setAttr("sandbox",e)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||ye.allowClientScripts}set allowClientScripts(e){this.setBoolAttr("allow-client-scripts",e)}get poster(){return this.getAttr("poster")}set poster(e){this.setAttr("poster",e)}get selectedMesh(){return this.getAttr("selected-mesh")}set selectedMesh(e){this.setAttr("selected-mesh",e)}get exposure(){return this.getFloatAttr("exposure",1)}set exposure(e){this.setAttr("exposure",e)}get autoRotate(){return this.getBoolAttr("auto-rotate")}set autoRotate(e){this.setBoolAttr("auto-rotate",e)}get autoRotateDelay(){return this.getFloatAttr("auto-rotate-delay",3e3)}set autoRotateDelay(e){this.setAttr("auto-rotate-delay",e)}get rotationPerSecond(){return this.getAttr("rotation-per-second")||"30deg"}set rotationPerSecond(e){this.setAttr("rotation-per-second",e)}get turntableRotation(){return this.viewer?this.viewer.turntableRotation:0}get ar(){return this.hasAttribute("ar")}set ar(e){this.setBoolAttr("ar",e)}get arScale(){return this.getAttr("ar-scale")||"auto"}set arScale(e){this.setAttr("ar-scale",e)}get arPlacement(){return this.getAttr("ar-placement")||"floor"}set arPlacement(e){this.setAttr("ar-placement",e)}get canActivateAR(){return ye.isARSupported()}get shadowIntensity(){return this.getFloatAttr("shadow-intensity",0)}set shadowIntensity(e){this.setAttr("shadow-intensity",e)}get shadowSoftness(){return this.getFloatAttr("shadow-softness",.5)}set shadowSoftness(e){this.setAttr("shadow-softness",e)}get toneMapping(){return Ue(this.getAttr("tone-mapping"))}set toneMapping(e){this.setAttr("tone-mapping",e)}get bloom(){return this.getFloatAttr("bloom",0)}set bloom(e){this.setAttr("bloom",e)}get bloomThreshold(){return Yi(this.getAttr("bloom-threshold"),.62)}set bloomThreshold(e){this.setAttr("bloom-threshold",e)}get bloomRadius(){return Yi(this.getAttr("bloom-radius"),.75)}set bloomRadius(e){this.setAttr("bloom-radius",e)}get outlineSelected(){return this.getBoolAttr("outline-selected")}set outlineSelected(e){this.setBoolAttr("outline-selected",e)}get outlineColor(){return this.getAttr("outline-color")||"#38bdf8"}set outlineColor(e){this.setAttr("outline-color",e)}get environmentImage(){return this.getAttr("environment-image")}set environmentImage(e){this.setAttr("environment-image",e)}get skyboxImage(){return this.getAttr("skybox-image")}set skyboxImage(e){this.setAttr("skybox-image",e)}get autoplay(){return this.getBoolAttr("autoplay")}set autoplay(e){this.setBoolAttr("autoplay",e)}get animationName(){return this.getAttr("animation-name")}set animationName(e){this.setAttr("animation-name",e)}get availableAnimations(){return this.viewer?this.viewer.getAvailableAnimations():[]}get variantName(){return this.viewer?this.viewer.getVariantName():this.getAttr("variant-name")}set variantName(e){this.setAttr("variant-name",e)}get availableVariants(){return this.viewer?this.viewer.getAvailableVariants():[]}fireEvent(e,i){this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:i}))}setSlotVisible(e,i){let r=typeof this.querySelector=="function"?this.querySelector(`[slot="${e}"]`):null;r&&(r.hidden=!i,r.style&&(r.style.display=i?"":"none"))}emitError(e,i="script"){this.setSlotVisible("error",!0),this.fireEvent("error",{error:e}),this.fireEvent("three-error",{error:e,message:e?.message||String(e),stage:i})}selectVariant(e){if(!this.viewer)return!1;let i=this.viewer.selectVariant(e);return i&&this.fireEvent("variant-applied",{variantName:this.viewer.getVariantName()}),i}get model(){let e=this.viewer?this.viewer.getModelMaterials():[];return{materials:e,getMaterialByName(i){return e.find(r=>r.name===i)??null}}}play(){this.viewer&&this.viewer.playAnimation(this.animationName||void 0)}pause(){this.viewer&&this.viewer.pauseAnimation()}resetCamera(){this.viewer?.resetCamera()}resetTurntableRotation(e=0){this.viewer?.resetTurntableRotation(e)}setCamera(e,i,r,s){this.viewer&&this.viewer.setCamera(e,i,r,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():Ut(0,0,0)}getFieldOfView(){return this.viewer?this.viewer.getFieldOfView():45}jumpCameraToGoal(){this.viewer?.jumpCameraToGoal()}toDataURL(e,i){return this.viewer?.render?.(),this.canvas?this.canvas.toDataURL(e,i):""}toBlob(e){return this.viewer?.render?.(),new Promise((i,r)=>{if(!this.canvas||typeof this.canvas.toBlob!="function"){r(new Error("Canvas toBlob is not supported in this environment."));return}this.canvas.toBlob(s=>{s?i(s):r(new Error("Failed to capture canvas blob."))},e?.mimeType,e?.qualityArgument)})}positionAndNormalFromPoint(e,i){let r=this.viewer?.raycastFromScreenPoint(e,i);if(!r)return null;let[s,a,o]=r.hitPoint||r.point,[n,l,h]=r.normal;return{position:Ut(s,a,o),normal:Ut(n,l,h)}}loadModel(e){return this.loadModelWithLimits(e)}async loadModelWithLimits(e,i,r=this.beginLoad()){if(r.signal.throwIfAborted(),!this.viewer){this.currentModel=e,this.currentModelLimits=i;return}try{let s;if(typeof e=="string"){let l=await fetch(e,{signal:r.signal});if(!l.ok)throw new Error(`Failed to load "${e}": HTTP ${l.status}`);s=await l.arrayBuffer()}else s=e;r.signal.throwIfAborted();let a=We(s);this.viewer.loadGLBData(a,i),this.currentModel=a,this.currentModelLimits=i,this.isModelLoaded=!0,this.hidePoster(),this.setSlotVisible("error",!1),this.updateHotspots();let o=this.getAttr("selected-mesh");o&&this.viewer.setSelectedMesh(o);let n=this.getAttr("variant-name");n&&this.selectVariant(n),this.fireEvent("load",{model:a}),this.fireEvent("three-load",{model:a,source:typeof e=="string"?"src":"model"})}catch(s){throw r.signal.aborted||this.emitError(s,"load"),s}}showToast(e,i=4500){if(typeof document>"u")return;let r=this.querySelector(".three-live-toast");r||(r=document.createElement("div"),r.className="three-live-toast",r.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(r)),r.textContent=e,this.toastTimer&&clearTimeout(this.toastTimer);let s=()=>{r&&(r.style.opacity="1",r.style.transform="translateX(-50%) translateY(0)")};typeof requestAnimationFrame<"u"?requestAnimationFrame(s):s(),this.toastTimer=setTimeout(()=>{r&&(r.style.opacity="0",r.style.transform="translateX(-50%) translateY(10px)"),this.toastTimer=null},i)}async activateAR(){this.activeXRSession?.isSessionActive?.()&&(await this.activeXRSession.stop().catch(()=>{}),this.activeXRSession=null);let e=(s,a=s.message)=>{throw this.fireEvent("ar-status",{status:"failed",error:s}),this.showToast(a,6e3),s};this.currentModel||e(new Error("No 3D model is loaded in <three-live>.")),ye.arProvider||e(new Error("AR module not bundled. Use the default 'three-live' bundle or call ThreeLiveElement.registerAR()."));let i=this.getAttr("ios-src"),r=(this.getAttr("ar-modes")||"").split(/\s+/).filter(Boolean);try{this.fireEvent("ar-status",{status:"session-started"});let s=await ye.arProvider.activateAR({model:i||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.fireEvent("ar-status",{status:"not-presenting"})},onError:a=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"failed",error:a}),this.showToast(`AR error: ${a.message}`,6e3)}}});if(s.success){s.session&&(this.activeXRSession=s.session);let a=s.mode==="quick-look"?"Opening Apple AR Quick Look...":s.mode==="scene-viewer"?"Opening Google Scene Viewer...":s.mode==="webxr"?"WebXR AR session started.":"";a&&this.showToast(a)}else{let a=s.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.";if(this.isDesktopMac()&&typeof document<"u"&&this.currentModel&&ye.arProvider.createUSDZBlob)try{let o=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:ye.arProvider.createUSDZBlob(this.currentModel),n=URL.createObjectURL(o),l=document.createElement("a");l.href=n,l.download="three_live_model.usdz",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(n),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(a,6e3)}else this.showToast(a,6e3);s.error&&this.fireEvent("ar-status",{status:"failed",error:s.error})}return s}catch(s){return this.activeXRSession=null,e(s,`AR error: ${s.message||String(s)}`)}}setupDOM(){let e=this.querySelector("canvas");e||(e=document.createElement("canvas"),e.style.cssText=`width:100%;height:100%;display:block;touch-action:${this.cameraControls?"none":"auto"};outline:none`,this.appendChild(e)),this.canvas=e,typeof e.addEventListener=="function"&&!e.__tlCtxBound&&(e.__tlCtxBound=!0,e.addEventListener("webglcontextlost",r=>this.fireEvent("three-context-lost",{originalEvent:r})),e.addEventListener("webglcontextrestored",r=>this.fireEvent("three-context-restored",{originalEvent:r}))),this.setSlotVisible("error",!1),this.isModelLoaded||this.setSlotVisible("poster",!0);let i=this.getAttr("poster");i&&this.updatePoster(i),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 e=this.autoRotate,i=this.exposure,r=this.parseOrbitLimit(this.getAttr("min-camera-orbit")),s=this.parseOrbitLimit(this.getAttr("max-camera-orbit")),a=this.parseCameraTarget(this.getAttr("camera-target")),o=this.parseFieldOfView(this.getAttr("field-of-view"));this.viewer=new Se(this,this.canvas,{autoRotate:e,autoRotateDelay:this.autoRotateDelay,autoRotateSpeed:this.parseRotationPerSecond(this.getAttr("rotation-per-second")),exposure:i,shadowIntensity:this.shadowIntensity,shadowSoftness:this.shadowSoftness,toneMapping:this.toneMapping,environmentImage:this.environmentImage,autoplay:this.autoplay,animationName:this.animationName||void 0,variantName:this.getAttr("variant-name")||void 0,fieldOfView:o,cameraTarget:a,minCameraOrbit:r,maxCameraOrbit:s,onMeshClick:l=>{this.fireEvent("meshclick",l)},onCameraChange:l=>{this.updateHotspots();for(let h of Se.getRegisteredPlugins())h.onCameraChange?.(this.viewer,this);this.fireEvent("camera-change",l)}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let n=this.getAttr("camera-orbit");n&&this.applyCameraOrbit(n),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(e){if(!(typeof document>"u")){if(!e){this.posterEl&&(this.posterEl.remove(),this.posterEl=null);return}this.posterEl||(this.posterEl=document.createElement("img"),this.posterEl.alt="3D Scene Preview",this.posterEl.style.cssText="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity .35s ease-out;pointer-events:none;z-index:1",this.appendChild(this.posterEl)),this.posterEl.src=e,this.isModelLoaded||(this.posterEl.style.opacity="1")}}hidePoster(){this.setSlotVisible("poster",!1),this.posterEl&&(this.posterEl.style.opacity="0",setTimeout(()=>{this.isModelLoaded&&this.posterEl&&(this.posterEl.remove(),this.posterEl=null)},400))}isDesktopMac(){let e=typeof navigator<"u"&&navigator.userAgent||"";return/Macintosh/i.test(e)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1)&&!/Android|iPhone|iPad|iPod/i.test(e)}syncARButtonLabel(e){let i=this.isDesktopMac(),r=i?"Quick Look (.usdz)":"View in AR",s=i?"Download .usdz preview for macOS Quick Look (live camera AR requires iOS or Android)":"View in Augmented Reality";typeof e.setAttribute=="function"&&(e.setAttribute("aria-label",s),e.setAttribute("title",s));let a=e._labelSpan||(typeof e.querySelector=="function"?e.querySelector("span"):null);a&&(a.textContent=r)}createARButton(){if(!(typeof document>"u")){if(!this.arButton){let e=document.createElement("button");e.type="button",e.className="three-live-ar-button",e.setAttribute("part","default-ar-button");let i="http://www.w3.org/2000/svg";if(typeof document.createElementNS=="function"){let s=document.createElementNS(i,"svg");for(let[o,n]of[["width","20"],["height","20"],["viewBox","0 0 24 24"],["fill","none"],["stroke","currentColor"],["stroke-width","2"],["stroke-linecap","round"],["stroke-linejoin","round"]])s.setAttribute(o,n);s.style.marginRight="6px";let a=document.createElementNS(i,"path");a.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 16zM3.27 6.96 12 12.01l8.73-5.05M12 22.08V12"),s.appendChild(a),e.appendChild(s)}let r=document.createElement("span");e._labelSpan=r,e.appendChild(r),this.syncARButtonLabel(e),e.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",e.addEventListener("mouseenter",()=>{e.style.backgroundColor="rgba(30, 41, 59, 0.95)",e.style.transform="scale(1.04)"}),e.addEventListener("mouseleave",()=>{e.style.backgroundColor="rgba(15, 23, 42, 0.85)",e.style.transform="scale(1)"}),e.addEventListener("click",s=>{s.stopPropagation(),this.activateAR()}),this.arButton=e,this.appendChild(e)}this.updateARButtonVisibility()}}updateARButtonVisibility(){let e=this.hasAttribute("ar")&&!!ye.arProvider,i=typeof this.querySelector=="function"?this.querySelector('[slot="ar-button"]'):null;i?(this.arButton&&(this.arButton.style.display="none"),i.__tlARBound||(i.__tlARBound=!0,i.addEventListener("click",r=>{r.stopPropagation(),this.activateAR()})),i.dataset.tlOrigDisplay===void 0&&(i.dataset.tlOrigDisplay=i.style.display==="none"?"":i.style.display),i.style.display=e?i.dataset.tlOrigDisplay||"":"none"):this.arButton&&(this.syncARButtonLabel(this.arButton),this.arButton.style.display=e?"flex":"none")}applyCameraOrbit(e){if(!(!e||!this.viewer))try{let i=JSON.parse(e);this.viewer.setInitialCamera(i.theta,i.phi,i.distance,i.zoom)}catch{let i=this.parseOrbitLimit(e);(i.theta!==void 0||i.phi!==void 0)&&this.viewer.setInitialCamera(i.theta,i.phi,i.distance)}}parseOrbitLimit(e){if(!e)return{};let[i,r,s]=e.trim().split(/\s+/),a=s&&s!=="auto"?parseFloat(s):NaN;return{theta:i&&i!=="auto"?this.parseFieldOfView(i):void 0,phi:r&&r!=="auto"?this.parseFieldOfView(r):void 0,distance:isNaN(a)?void 0:a}}applyOrbitLimits(){if(!this.viewer)return;let e=this.parseOrbitLimit(this.getAttr("min-camera-orbit")),i=this.parseOrbitLimit(this.getAttr("max-camera-orbit"));this.viewer.setOrbitLimits({minTheta:e.theta,maxTheta:i.theta,minPhi:e.phi,maxPhi:i.phi,minDistance:e.distance,maxDistance:i.distance})}parseCameraTarget(e){if(!e)return;let i=e.trim().split(/\s+/).map(parseFloat);return i.length>=3&&!i.some(isNaN)?[i[0],i[1],i[2]]:void 0}parseFieldOfView(e){if(!e)return;let i=parseFloat(e);return isNaN(i)?void 0:e.endsWith("rad")?i*180/Math.PI:i}parseRotationPerSecond(e){if(!e)return Math.PI/6;let i=e.trim(),r=parseFloat(i);return isNaN(r)?Math.PI/6:i.endsWith("rad")?r:i.endsWith("%")?r/100*Math.PI*2:r*Math.PI/180}applyCameraTarget(e){let i=this.parseCameraTarget(e);this.viewer&&i&&this.viewer.setTarget(i[0],i[1],i[2])}applyFieldOfView(e){let i=this.parseFieldOfView(e);this.viewer&&i!==void 0&&this.viewer.setFieldOfView(i)}updateHotspot(e){let i=this.querySelector(`[slot="${e.name}"]`);i&&(e.position!==void 0&&i.setAttribute("data-position",e.position),e.normal!==void 0&&i.setAttribute("data-normal",e.normal)),this.updateHotspots()}updateHotspots(){for(let e of Se.getRegisteredPlugins())if(e.updateHotspotsForElement){e.updateHotspotsForElement(this,this.viewer);return}}runWithScriptRunner(e){let i=ye.scriptRunner;if(!i){let a=new Error('Script execution requires "three-live/full" or registerScriptRunner().');return this.showToast(a.message),this.emitError(a,"script"),Promise.reject(a)}let r=this.beginLoad(),s=()=>!r.signal.aborted;return new Promise((a,o)=>{let n=()=>o(r.signal.reason);if(r.signal.addEventListener("abort",n,{once:!0}),!s()){n();return}let l={onModelReady:h=>{this.loadModelWithLimits(h,zr,r).then(()=>a(h),o)},onUpdateTransforms:h=>{s()&&this.viewer?.updateMeshTransforms(h)},onError:h=>{s()&&(this.showToast(h.message),this.emitError(h,"script"),o(h))},onToast:h=>{s()&&this.showToast(h)}};e(i,l).then(h=>{s()?this.scriptHandle=h||null:h?.terminate()},h=>{s()&&l.onError?.(h)})})}loadScriptFromSrc(e){return this.runWithScriptRunner((i,r)=>{if(typeof i.executeUrl!="function"){let s=new Error("Registered ScriptRunner does not support executeUrl() for server-generated scripts.");return r.onError?.(s),Promise.reject(s)}return i.executeUrl(e,this.sandbox,r)})}executeScript(e){if(!ye.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let i=new Error(Gt);return this.showToast(Wt),this.emitError(i,"security"),Promise.reject(i)}return this.runWithScriptRunner((i,r)=>i.execute(e,this.sandbox,r,{allowClientScripts:!0}))}};yt.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"],yt.registerPlugin=Se.registerPlugin,yt.getRegisteredPlugins=Se.getRegisteredPlugins;var Je=yt;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",Je);function sa(t="model-viewer"){return Je.defineModelViewer(t)}function Zi(){if(typeof window>"u"||typeof navigator>"u")return!1;let t=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(t)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))return!1;let e=document.createElement("a");return e.relList!==void 0&&e.relList.supports!==void 0&&e.relList.supports("ar")}function Qi(){if(typeof navigator>"u")return!1;let t=navigator.userAgent||"";return/android/i.test(t)}async function Ji(){if(typeof navigator>"u")return!1;let t=navigator;if(!t.xr||typeof t.xr.isSessionSupported!="function")return!1;try{return await t.xr.isSessionSupported("immersive-ar")?!0:await t.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function aa(){return(await Bt()).bestMode}async function Bt(){let[t,e,i]=await Promise.all([Ji(),Promise.resolve(Zi()),Promise.resolve(Qi())]),r=[];e&&r.push("quick-look"),t&&r.push("webxr"),i&&r.push("scene-viewer");let s=null;return e?s="quick-look":t?s="webxr":i&&(s="scene-viewer"),{webxr:t,quickLook:e,sceneViewer:i,availableModes:r,bestMode:s}}function er(t,e={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let i,r=!1;if(typeof t=="string"){if(i=na(t),!i)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else i=URL.createObjectURL(t),r=!0;let s=[];if(e.allowScale===!1&&s.push("allowsContentScaling=0"),e.canonicalWebPageUrl){let n=vt(e.canonicalWebPageUrl,!1);n&&s.push(`canonicalWebPageURL=${encodeURIComponent(n)}`)}e.checkoutTitle&&s.push(`checkoutTitle=${encodeURIComponent(e.checkoutTitle)}`),e.checkoutSubtitle&&s.push(`checkoutSubtitle=${encodeURIComponent(e.checkoutSubtitle)}`),e.price&&s.push(`price=${encodeURIComponent(e.price)}`),s.length>0&&(i+=`#${s.join("&")}`);let a=document.createElement("a");a.setAttribute("rel","ar"),a.setAttribute("href",i);let o=document.createElement("img");o.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),o.style.display="none",a.appendChild(o),document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),r&&URL.revokeObjectURL(i.split("#")[0])},3e3)}function vt(t,e=!1){if(typeof t!="string")return"";let i=t.replace(/[\x00-\x1f\x7f]+/g,"").trim();if(!i)return"";if(/^[\\/]{2}/.test(i))throw new Error(`[XR-Live Security] Rejected protocol-relative URL in Scene Viewer intent: ${i.slice(0,32)}`);let r=i.toLowerCase();if(r.startsWith("https://")||r.startsWith("http://")||e&&r.startsWith("blob:")||!/^[a-z][a-z0-9+.-]*:/i.test(i))return i;throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Scene Viewer intent: ${i.slice(0,32)}`)}function na(t){try{return vt(t,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(t||"").trim().slice(0,32)}`)}}function oa(t,e={}){let i=vt(t,!0),r=e.mode||"ar_preferred",s=new URLSearchParams({file:i,mode:r,resizable:e.resizable!==!1?"true":"false",enable_vertical_placement:e.enableVerticalPlacement?"true":"false"});return e.title&&s.set("title",e.title),e.link&&s.set("link",vt(e.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${s.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function la(t,e={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let i=oa(t,e);window.location.href=i}var Ve=null;function ha(t,e){let i=new Float32Array(144),r=new Float32Array(144),s=new Float32Array(96),a=new Uint16Array(144);for(let c=0;c<24;c++){let f=c/24*Math.PI*2,g=Math.cos(f),w=Math.sin(f),d=c*2,p=d+1,A=(c+1)%24*2;i[d*3]=g*.11,i[d*3+1]=.002,i[d*3+2]=w*.11,i[p*3]=g*.145,i[p*3+1]=.002,i[p*3+2]=w*.145,r[d*3+1]=r[p*3+1]=1,a.set([d,A,p,p,A,A+1],c*6)}let o=t.createVertexArray();t.bindVertexArray(o);let n=(c,f,g)=>{let w=t.createBuffer();return t.bindBuffer(34962,w),t.bufferData(34962,c,35044),t.enableVertexAttribArray(f),t.vertexAttribPointer(f,g,5126,!1,0,0),w},l=[n(i,0,3),n(r,1,3),n(s,2,2)],h=t.createBuffer();return l.push(h),t.bindBuffer(34963,h),t.bufferData(34963,a,35044),t.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:o,indexCount:a.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:i,indices:a,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:l}]}}function tr(t,e,i,r,s){let a=Math.cos(r),o=Math.sin(r),n=Math.max(.01,s);t.fill(0),t[0]=n*a,t[2]=-n*o,t[5]=n,t[8]=n*o,t[10]=n*a,t[12]=e[0]-n*(a*i[0]+o*i[2]),t[13]=e[1]-n*i[1],t[14]=e[2]-n*(-o*i[0]+a*i[2]),t[15]=1}var ua=class{constructor(t={}){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=t}isSessionActive(){return this.s!==null}hasPlacedModel(){return this.placed}getPlacedMatrix(){return this.placedMat}async start(t,e){if(typeof navigator>"u"||!navigator.xr)throw new Error("WebXR is not supported on this browser.");Ve&&Ve!==this&&Ve.isSessionActive()&&await Ve.stop().catch(()=>{});let i=navigator.xr,r=this.opts,s=e||t?.container,a=String(s?.tagName||"").toLowerCase()==="xr-live",o=t?.bounds,n=Number(o?.radius)||1,l=Array.isArray(o?.center)?o.center:[0,0,0],h=Array.isArray(o?.min)?o.min:[-.5,-.5,-.5],c=typeof navigator<"u"&&navigator.userAgent||"",f=/Android|iPhone|iPad|iPod/i.test(c)&&!/Quest|Oculus|Pico|Vision/i.test(c),g=a?r.arScale==="fixed"?1:f?.55:1:r.arScale==="fixed"?1:n>.45?.3/n:n<.05?.12/Math.max(n,.001):1,w=a?[0,-.25,0]:[l[0]||0,r.arPlacement==="wall"?l[1]:h[1]??0,l[2]||0],d="immersive-ar";try{await i.isSessionSupported("immersive-ar")||(d="immersive-vr")}catch{d="immersive-vr"}let p=s?.querySelector?.('[slot="ar-overlay"]')||null,A=!1,b=null,x=()=>{A&&p?.parentNode&&p.parentNode.removeChild(p),p=null,b=null,A=!1};if(d==="immersive-ar"){if(p)p.addEventListener?.("beforexrselect",I=>I.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let I=document.createElement("div");I.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 W=document.createElement("button");W.type="button",W.textContent="\u2715 Exit AR",W.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",W.addEventListener("beforexrselect",Z=>Z.preventDefault()),W.addEventListener("click",Z=>{Z.stopPropagation(),this.stop().catch(()=>{})}),b=document.createElement("div"),b.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",b.textContent="Move phone to detect a surface \u2022 Tap to place",I.appendChild(W),I.appendChild(b),document.body.appendChild(I),p=I,A=!0}}let u=new Set(r.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),m={requiredFeatures:r.requiredFeatures?[...r.requiredFeatures]:[],optionalFeatures:Array.from(u)};p&&(u.add("dom-overlay"),m.optionalFeatures=Array.from(u),m.domOverlay={root:p});for(let I of me)I.onConfigureXRSessionInit?.(s,m);Array.isArray(m.optionalFeatures)&&m.optionalFeatures.includes("dom-overlay")&&!m.domOverlay?.root&&(m.optionalFeatures=m.optionalFeatures.filter(I=>I!=="dom-overlay"));let v=I=>{let W=String(I?.name||"");return W==="NotAllowedError"||W==="SecurityError"};try{this.s=await i.requestSession(d,m)}catch(I){if(x(),v(I))throw r.onError?.(I),I;try{this.s=await i.requestSession(d,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(W){if(v(W))throw r.onError?.(W),W;try{this.s=await i.requestSession(d)}catch(Z){throw r.onError?.(Z),Z}}}let S=this.s;Ve=this,this.placed=!1;let _=null,D=null,P=null,N=null,E=null,F=[0,-.25,-1.2],L=[0,-.25,-1.2],M=new Float32Array(16),O=new Float32Array(16),H=!1,R=1,C=0,y=!1,T=null,z=null,G=0,B=null,te=()=>{Ve===this&&(Ve=null),B?.(),B=null;try{D?.cancel?.()}catch{}if(D=null,P){let I=t?.meshes;if(Array.isArray(I)){let Z=I.indexOf(P);Z!==-1&&I.splice(Z,1)}let W=t.getGLContext?.()||t?.gl;if(W)for(let Z of P.primitives||[]){W.deleteVertexArray?.(Z.vao);for(let ae of Z.buffers||[])W.deleteBuffer?.(ae)}P=null}t?.setXRSessionActive?.(!1),x(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=te,S.addEventListener("end",()=>{te(),r.onExit?.()}),S.addEventListener("select",()=>{if(!this.placed){let I=E||F;L=[I[0],I[1],I[2]],tr(this.placedMat,L,w,C,g*R),this.placed=!0,P&&(P.visible=!1),b&&(b.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),r.onPlaced?.(this.placedMat)}});try{let I=t.getGLContext?.()||t?.gl;I&&typeof I.makeXRCompatible=="function"&&await I.makeXRCompatible();let W=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;I&&typeof W=="function"&&typeof S.updateRenderState=="function"&&S.updateRenderState({baseLayer:new W(S,I,{alpha:!0})});try{_=await S.requestReferenceSpace("local")}catch{try{_=await S.requestReferenceSpace("local-floor")}catch{_=await S.requestReferenceSpace("viewer")}}let Z=await S.requestReferenceSpace("viewer").catch(()=>_);if(typeof S.requestHitTestSource=="function"&&Z&&(D=await S.requestHitTestSource({space:Z}).catch(()=>null)),d==="immersive-ar"&&I&&typeof I.createVertexArray=="function"&&Array.isArray(t.meshes)&&(P=ha(I,r.reticleColor),t.meshes.push(P)),typeof window<"u"&&typeof window.addEventListener=="function"){let U=k=>Math.hypot(k.touches[1].clientX-k.touches[0].clientX,k.touches[1].clientY-k.touches[0].clientY),ee=k=>Math.atan2(k.touches[1].clientY-k.touches[0].clientY,k.touches[1].clientX-k.touches[0].clientX),$=k=>{this.s&&(k.touches.length===1&&this.placed?y=!0:k.touches.length>=2&&(y=!1,T=U(k),z=ee(k)))},q=k=>{if(!this.s||k.touches.length<2)return;let V=U(k),j=ee(k);if(T&&T>4&&r.arScale!=="fixed"&&(R=Math.max(.15,Math.min(6,R*(V/T)))),z!==null){let K=j-z;K>Math.PI&&(K-=Math.PI*2),K<-Math.PI&&(K+=Math.PI*2),C-=K}T=V,z=j},X=k=>{(!k.touches||k.touches.length===0)&&(y=!1),(!k.touches||k.touches.length<2)&&(T=null,z=null)};window.addEventListener("touchstart",$,{passive:!0}),window.addEventListener("touchmove",q,{passive:!0}),window.addEventListener("touchend",X,{passive:!0}),window.addEventListener("touchcancel",X,{passive:!0}),B=()=>{window.removeEventListener("touchstart",$),window.removeEventListener("touchmove",q),window.removeEventListener("touchend",X),window.removeEventListener("touchcancel",X)}}t.setXRSessionActive?.(!0);let ae=(U,ee)=>{if(this.s!==S)return;S.requestAnimationFrame(ae);let $=G>0?Math.min(Math.max((U-G)/1e3,0),.1):1/60;G=U,t?.stepXRUpdate?.($);let q=ee.getViewerPose(_);if(!q)return;let X=q.views?.[0];if(!H&&X?.transform){let J=X.transform.position,Y=X.transform.matrix,ue=J?.x??(Y?Y[12]:0),se=J?.y??(Y?Y[13]:0),ne=J?.z??(Y?Y[14]:0),oe=Y?-Y[8]:0,le=Y?-Y[10]:-1,xe=Math.hypot(oe,le);xe>1e-4?(oe/=xe,le/=xe):(oe=0,le=-1),F=[ue+oe*1.2,se-.25,ne+le*1.2],C=Math.atan2(-oe,-le),H=!0}if(D&&typeof ee.getHitTestResults=="function"&&(!this.placed||y)){let J=ee.getHitTestResults(D)||[],Y=!1;for(let ue of J){let se=ue.getPose(_);if(se?.transform?.matrix){let ne=se.transform.matrix,oe=ne[5];if(r.arPlacement==="wall"&&Math.abs(oe)>.35||r.arPlacement==="floor"&&Math.abs(oe)<.65)continue;N||(N=new Float32Array(16)),N.set(ne),E=[ne[12],ne[13],ne[14]],this.placed&&y&&(L=[ne[12],ne[13],ne[14]]),P&&(P.visible=!this.placed||y,P.transform.set(ne)),!this.placed&&b&&(b.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),r.onHit?.(N),Y=!0;break}}!Y&&P&&(P.visible=!1)}tr(M,this.placed?L:E||F,w,C,g*R),this.placed&&this.placedMat.set(M);let k=t.xrRigMatrix;k instanceof Float32Array&&k.length===16?fe(O,k,M):O.set(M),t.modelRootMatrix&&t.modelRootMatrix.set(O);for(let J of me)J.onXRFrame?.(t,S,ee,_);let V=t.getGLContext?.()||t?.gl,j=S.renderState?.baseLayer;V&&j&&j.framebuffer!==void 0&&V.bindFramebuffer(36160,j.framebuffer);let K=d==="immersive-ar",Q=q.views||[];for(let J=0;J<Q.length;J++){let Y=Q[J];if(typeof t.renderXRView=="function"){let ue;if(j&&typeof j.getViewport=="function"){let se=j.getViewport(Y);se&&se.width>0&&se.height>0&&(ue=[se.x,se.y,se.width,se.height])}else j?.framebufferWidth>0&&j?.framebufferHeight>0&&(ue=[0,0,j.framebufferWidth,j.framebufferHeight]);t.renderXRView(Y,O,this.placed,ue,K,J)}}V&&j&&j.framebuffer&&V.bindFramebuffer(36160,null)};S.requestAnimationFrame(ae)}catch(I){throw typeof S.end=="function"&&await S.end().catch(()=>{}),te(),r.onError?.(I),I}}async stop(){let t=this.s;if(t)try{await t.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function ir(t){let e=await Bt(),i=t.preferredModes||["quick-look","webxr","scene-viewer"],r=null;for(let n of i)if(e.availableModes.includes(n)){r=n;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 s={...t.quickLookOptions,allowScale:t.arScale==="fixed"?!1:t.quickLookOptions?.allowScale},a={...t.sceneViewerOptions,resizable:t.arScale==="fixed"?!1:t.sceneViewerOptions?.resizable,enableVerticalPlacement:t.arPlacement==="wall"?!0:t.sceneViewerOptions?.enableVerticalPlacement},o={...t.webXROptions,arScale:t.arScale||t.webXROptions?.arScale,arPlacement:t.arPlacement||t.webXROptions?.arPlacement};try{if(r==="quick-look"){let n;if(t.model instanceof Blob&&t.model.type==="model/vnd.usdz+zip")n=t.model;else{if(typeof t.model=="string")return er(t.model,s),{mode:"quick-look",success:!0};n=Lt(t.model)}return er(n,s),{mode:"quick-look",success:!0}}if(r==="scene-viewer"){let n=t.glbUrl||(typeof t.model=="string"?t.model:null);if(!n)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return la(n,a),{mode:"scene-viewer",success:!0}}if(r==="webxr"){if(!t.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let n=new ua(o);return await n.start(t.view,t.element),{mode:"webxr",success:!0,session:n}}}catch(n){return{mode:r,success:!1,error:n}}return{mode:r,success:!1,error:new Error(`Unhandled AR mode: ${r}`)}}return Je.registerAR({activateAR:ir,createUSDZBlob:Lt}),Je.registerScriptRunner($i),Ht(Sr),br($t)})();