three-live 1.2.4 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/index.d.ts +58 -0
- package/dist/three-author-engine.js +89 -63
- package/dist/three-author.cjs +88 -62
- package/dist/three-author.d.ts +58 -0
- package/dist/three-author.js +87 -61
- package/dist/three-convert.cjs +81 -59
- package/dist/three-convert.d.ts +58 -0
- package/dist/three-convert.js +80 -58
- package/dist/three-live-animation.cjs +8 -9
- package/dist/three-live-animation.d.ts +58 -0
- package/dist/three-live-animation.js +7 -8
- package/dist/three-live-animation.min.js +6 -7
- package/dist/three-live-cad.cjs +3 -4
- package/dist/three-live-cad.d.ts +58 -0
- package/dist/three-live-cad.js +2 -3
- package/dist/three-live-cad.min.js +3 -4
- package/dist/three-live-cli.js +231 -0
- package/dist/three-live-element.cjs +20 -21
- package/dist/three-live-element.d.ts +58 -0
- package/dist/three-live-element.js +19 -20
- package/dist/three-live-full.cjs +113 -87
- package/dist/three-live-full.js +110 -84
- package/dist/three-live-full.min.js +113 -87
- package/dist/three-live-studio.cjs +19 -20
- package/dist/three-live-studio.d.ts +58 -0
- package/dist/three-live-studio.js +18 -19
- package/dist/three-live-studio.min.js +18 -19
- package/dist/three-live-viewer.cjs +20 -21
- package/dist/three-live-viewer.d.ts +58 -0
- package/dist/three-live-viewer.js +19 -20
- package/dist/three-live-viewer.min.js +20 -21
- package/dist/three-live.cjs +90 -64
- package/dist/three-live.js +89 -63
- package/dist/three-live.min.js +89 -63
- package/dist/three-view.cjs +18 -19
- package/dist/three-view.d.ts +58 -0
- package/dist/three-view.js +19 -20
- package/dist/three-xr.cjs +81 -59
- package/dist/three-xr.d.ts +58 -0
- package/dist/three-xr.js +80 -58
- package/package.json +7 -1
package/dist/three-live.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
"use strict";/**
|
|
2
2
|
* @license
|
|
3
3
|
* Copyright 2026 Google LLC
|
|
4
4
|
*
|
|
@@ -13,11 +13,11 @@
|
|
|
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 _t=Object.defineProperty;var fr=Object.getOwnPropertyDescriptor;var pr=Object.getOwnPropertyNames;var br=Object.prototype.hasOwnProperty;var yr=(n,e)=>{for(var t in e)_t(n,t,{get:e[t],enumerable:!0})},gr=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of pr(e))!br.call(n,i)&&i!==t&&_t(n,i,{get:()=>e[i],enumerable:!(r=fr(e,i))||r.enumerable});return n};var vr=n=>gr(_t({},"__esModule",{value:!0}),n);var pi={};yr(pi,{THREE:()=>Pe,ThreeLiveElement:()=>_e,ThreeView:()=>de,activateAR:()=>Et,createUSDZBlob:()=>Ue,evaluateToneMapping:()=>Un,getARCapabilities:()=>Mt,getBestARMode:()=>dr,isQuickLookSupported:()=>xn,isSceneViewerSupported:()=>wn,isWebXRSupported:()=>An,toGLBData:()=>Ae});var Ke="__THREE_LIVE_REGISTRY__";function Q(){let n=typeof globalThis<"u"?globalThis:{};if(!n[Ke]){let e={plugins:[],decoders:new Map};try{Object.defineProperty(n,Ke,{value:e,writable:!1,configurable:!1,enumerable:!1})}catch{n[Ke]=e}}return n[Ke]}var ce=Q().plugins;function Ze(n){let e=Q().plugins;e.some(t=>t.name===n.name)||e.push(n),n.onRegister?.()}function Rn(){return Q().plugins}var xr=`#version 300 es
|
|
16
|
+
*/var ThreeLive=(()=>{var be=Object.defineProperty,dr=Object.getOwnPropertyDescriptor,pr=Object.getOwnPropertyNames,fr=Object.prototype.hasOwnProperty,gr=(e,t)=>{for(var i in t)be(e,i,{get:t[i],enumerable:!0})},br=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of pr(t))!fr.call(e,s)&&s!==i&&be(e,s,{get:()=>t[s],enumerable:!(r=dr(t,s))||r.enumerable});return e},yr=e=>br(be({},"__esModule",{value:!0}),e),$e={};gr($e,{THREE:()=>Ht,ThreeLiveElement:()=>pe,ThreeView:()=>Mt,activateAR:()=>rr,createUSDZBlob:()=>Le,evaluateToneMapping:()=>Ir,getARCapabilities:()=>Ve,getBestARMode:()=>aa,isQuickLookSupported:()=>Ji,isSceneViewerSupported:()=>Qi,isWebXRSupported:()=>tr,toGLBData:()=>zt});var Zt="__THREE_LIVE_REGISTRY__";function ot(){let e=typeof globalThis<"u"?globalThis:{};if(!e[Zt]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(e,Zt,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{e[Zt]=t}}return e[Zt]}var ct=ot().plugins;function He(e){let t=ot().plugins;t.some(i=>i.name===e.name)||t.push(e),e.onRegister?.()}function vr(){return ot().plugins}var xr=`#version 300 es
|
|
18
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.);}`,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,Sn=new Float32Array(20);function Ct(n,e){let[t,r,i,s,o,c]=e;return[n[0]*t+n[4]*r+n[8]*i+n[12],n[1]*t+n[5]*r+n[9]*i+n[13],n[2]*t+n[6]*r+n[10]*i+n[14],Math.abs(n[0])*s+Math.abs(n[4])*o+Math.abs(n[8])*c,Math.abs(n[1])*s+Math.abs(n[5])*o+Math.abs(n[9])*c,Math.abs(n[2])*s+Math.abs(n[6])*o+Math.abs(n[10])*c]}function Ar(n){if(n._lb!==void 0)return n._lb;let e=1e9,t=1e9,r=1e9,i=-1e9,s=-1e9,o=-1e9;for(let c of n.primitives||[]){let a=c.positions;if(a)for(let u=0;u<a.length;u+=3)a[u]<e&&(e=a[u]),a[u+1]<t&&(t=a[u+1]),a[u+2]<r&&(r=a[u+2]),a[u]>i&&(i=a[u]),a[u+1]>s&&(s=a[u+1]),a[u+2]>o&&(o=a[u+2])}return n._lb=e<=i?[(e+i)*.5,(t+s)*.5,(r+o)*.5,(i-e)*.5,(s-t)*.5,(o-r)*.5]:null}function Rr(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,xr)),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 Mn={name:"contact-shadow",onContextRestored(n){We.delete(n)},onAfterRender(n,e,t){let r=e.shadowIntensity;if(r<=0||!e.bounds)return;let i=Rr(n),s=!e.xrSessionActive&&(e.backdropMeshes?.length??0)>0,o=[],c=[];for(let d of e.meshes||[]){if(!d||d.visible===!1||d.isPluginMesh||d.name==="__xr_reticle__"||d.name?.startsWith("__xr_slot_"))continue;let g=Ar(d);if(!g)continue;d.transform&&(g=Ct(d.transform,g)),e.modelRootMatrix&&(g=Ct(e.modelRootMatrix,g));let[T,P,f,R,p,M]=g,_=[T,f,R,M,P-p,P+p];/floor|table|pedestal|ground|base|plane/i.test(d.name||"")||p<.14&&Math.min(R,M)>.45?c.push(_):o.push(_)}let a=[],u=e.bounds.center||[0,0,0],l=Math.max(.05,Number(e.bounds.radius)||.5),m=e.bounds.min,h=m?[u[0],u[1],u[2],l,Math.max(.01,u[1]-m[1]),l]:[u[0],u[1],u[2],l,l,l];e.modelRootMatrix&&(h=Ct(e.modelRootMatrix,h));let b=e.xrSessionActive&&c.length===0&&String(e.container?.tagName||"").toLowerCase()==="xr-live"?(e.modelRootMatrix?e.modelRootMatrix[5]*-.25+e.modelRootMatrix[13]:-.25)+.002:h[1]-h[4]+.002;for(let[d,g,T,P,f]of o){let R=-1/0;for(let[M,_,w,A,,L]of c)f>=L-.08&&Math.abs(d-M)<=w&&Math.abs(g-_)<=A&&L+.002>R&&(R=L+.002);s&&(R=Math.max(R,d>=.04&&d<=.36&&g>=-.34&&g<=-.04&&f>=.01?.036:Math.hypot(d,g)<=.66&&f>=-.06?.003:-.477)),isFinite(R)||(R=b);let p=a.find(M=>Math.hypot(d-M[0],g-M[1])<.06&&Math.abs(R-M[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,R])}if(a.length===0){let d=Math.max(.1,h[3]*1.5)/1.45;a.push([h[0],h[2],d,d,b,b])}n.useProgram(i.prog),n.uniformMatrix4fv(i.uMVP,!1,t),n.enable(3042),(n.blendFuncSeparate||n.blendFunc).call(n,770,771,1,771),n.depthMask(!1),n.bindVertexArray(i.vao),n.bindBuffer(34962,i.vbo);for(let[d,g,T,P,f,R]of a){let p=Math.max(0,f-R),M=r/(1+p*2);if(M<.02)continue;let _=1+Math.min(.75,p*.85),w=Math.max(.045,T*1.45*_),A=Math.max(.045,P*1.45*_);Sn.set([d-w,R,g-A,0,0,d+w,R,g-A,1,0,d+w,R,g+A,1,1,d-w,R,g+A,0,1]),n.bufferSubData(34962,0,Sn),n.uniform1f(i.uIntensity,M),n.uniform1f(i.uSoftness,Math.min(1,e.shadowSoftness+Math.min(.45,p*.6))),n.drawElements(4,6,5123,0)}n.bindVertexArray(null),n.depthMask(!0),n.disable(3042)},onDestroy(n){let e=We.get(n);e&&(n.deleteVertexArray(e.vao),n.deleteBuffer(e.vbo),n.deleteBuffer(e.ibo),n.deleteProgram(e.prog),We.delete(n))}};function En(n,e,t){let r=[],i=new Map,s=[],o=[],c=[],a=new Map,u=f=>{let R=i.get(f);return R===void 0&&(R=r.length,r.push({op:f}),i.set(f,R)),R},l=f=>{let R=a.get(f);return R===void 0&&(R=c.length,c.push({id:f}),a.set(f,R)),R},m=(f,R={})=>s.push({declaration:u(f),...R})-1,h=(f,R,p)=>o.push({id:f,type:R,value:p})-1,y=f=>({node:f,socket:"value"}),b=t?.interactivity??t?.gltfExtensions?.KHR_interactivity;if(b&&typeof b=="object"){let f=Array.isArray(b.graphs)?b.graphs[b.graph??0]:b;if(f&&Array.isArray(f.nodes)){let R=Array.isArray(f.declarations)?f.declarations:[];for(let p of R)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 M=p.op||(typeof p.declaration=="number"?R[p.declaration]?.op:"");s.push(M?{...p,declaration:u(M)}:{...p})}}}let d=(f,R,p="translation")=>p==="baseColorFactor"||p==="metallicFactor"||p==="roughnessFactor"?`/materials/${Math.max(0,R)}/pbrMetallicRoughness/${p}`:p==="emissiveFactor"||p==="alphaCutoff"?`/materials/${Math.max(0,R)}/${p}`:p==="visible"?`/nodes/${f}/extensions/KHR_node_visibility/visible`:`/nodes/${f}/${p}`,g=new Map;n.forEach((f,R)=>{typeof f?.name=="string"&&!g.has(f.name)&&g.set(f.name,R)});let T=(f,R)=>typeof f.target=="string"&&g.has(f.target)?g.get(f.target):typeof f.targetNode=="number"?f.targetNode:R,P=f=>{let R=n[f];return(typeof R?.mesh=="number"?e[R.mesh]?.primitives?.[0]?.material:0)??0};for(let f=0;f<n.length;f++){let R=n[f],p=R?.extras?.interactivity;if(!p||typeof p!="object")continue;let M=(typeof R.mesh=="number"?e[R.mesh]?.primitives?.[0]?.material:0)??0,_=A=>{let L=Array.isArray(A)?A:[A],v=[];for(let I=0;I<L.length;I++){let S=L[I];if(!S||typeof S!="object")continue;let C=S.action||"interpolate",F=typeof S.duration=="number"?S.duration:.35;if(C==="toggleTransform"){let N=S.property==="rotation"||S.property==="scale"?S.property:"translation",V=N==="rotation"?R.rotation||[0,0,0,1]:N==="scale"?R.scale||[1,1,1]:R.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:y(D)}}),z=m("variable/set",{configuration:{variable:B},values:{value:y(H)}}),O=m("pointer/interpolate",{configuration:{pointer:U},values:{value:{value:Array.isArray(S.to)?S.to:V},duration:{value:F}}}),X=m("pointer/interpolate",{configuration:{pointer:U},values:{value:{value:Array.isArray(S.from)?S.from:V},duration:{value:F}}});s[z].flows={out:{node:m("flow/branch",{values:{condition:y(D)},flows:{true:{node:O},false:{node:X}}})}},v.push(z)}else if(C==="interpolate"){let N=S.to??S.value;if(N===void 0)continue;let V={value:{value:N},duration:{value:F}};S.from!==void 0&&(V.from={value:S.from}),v.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(C==="setProperty"){if(S.value===void 0)continue;v.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(C==="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:y(U)}}),D=m("variable/set",{configuration:{variable:V},values:{value:y(B)}});s[D].flows={out:{node:m("pointer/set",{configuration:{pointer:`/nodes/${N}/extensions/KHR_node_visibility/visible`},values:{value:y(U)}})}},v.push(D)}else if(C==="cycleMaterialColor"&&Array.isArray(S.colors)&&S.colors.length>0){let N=typeof S.duration=="number"?S.duration:.25,V=`/materials/${Math.max(0,M)}/pbrMetallicRoughness/baseColorFactor`,U=h(`__color_idx_${f}_${I}`,"int",0),B=m("variable/get",{configuration:{variable:U}}),D=m("math/add",{values:{a:y(B),b:{value:1}}}),H=m("math/rem",{values:{a:y(D),b:{value:S.colors.length}}}),z=m("variable/set",{configuration:{variable:U},values:{value:y(H)}}),O={};for(let X=0;X<S.colors.length;X++){let E=S.colors[X],k=Array.isArray(E)&&E.length>=3?[E[0],E[1],E[2],E[3]??1]:[1,1,1,1];O[String(X)]={node:N>0?m("pointer/interpolate",{configuration:{pointer:V},values:{value:{value:k},duration:{value:N}}}):m("pointer/set",{configuration:{pointer:V},values:{value:{value:k}}})}}s[z].flows={out:{node:m("flow/switch",{values:{selection:y(B)},flows:O})}},v.push(z)}else if(C==="playAnimation")v.push(m("animation/start",{configuration:{animation:S.animation??S.clip??0}}));else if(C==="stopAnimation")v.push(m("animation/stop"));else if(C==="sendEvent"){let N={};for(let[V,U]of Object.entries(S.values||{}))N[V]={value:U};v.push(m("event/send",{configuration:{event:l(String(S.event??S.id??"custom"))},values:N}))}}if(!v.length)return null;if(v.length===1)return v[0];let x={};return v.forEach((I,S)=>{x[String(S)]={node:I}}),m("flow/sequence",{flows:x})},w=(A,L,v)=>{let x=_(L);x!==null&&m(A,{...v?{configuration:v}:{},flows:{out:{node:x}}})};if(p.onSelect&&w("pointer/onSelect",p.onSelect,{nodeIndex:f}),p.onHoverIn&&w("pointer/onHoverIn",p.onHoverIn,{nodeIndex:f}),p.onHoverOut&&w("pointer/onHoverOut",p.onHoverOut,{nodeIndex:f}),p.onStart&&w("event/onStart",p.onStart),p.onReceive&&typeof p.onReceive=="object")for(let[A,L]of Object.entries(p.onReceive))w("event/receive",L,{event:l(A)})}return s.length?{graphs:[{declarations:r,nodes:s,variables:o,events:c}],graph:0}:null}var Je='SecurityError: Client-modified script compilation (Use Case 1) is disabled by default to satisfy strict CSP and Trusted Types requirements. Use script-src="..." or loadScriptFromSrc(url) for server-generated scripts (Use Case 2), or explicitly opt in via ThreeLiveElement.allowClientScripts = true (or the allow-client-scripts attribute).',Qe="Security Error: client-side scripts require allow-client-scripts opt-in.";function oe(){let n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n}function et(n,e,t,r,i){let s=1/Math.tan(e/2);n.fill(0),n[0]=s/t,n[5]=s,n[11]=-1;let o=1/(r-i);return n[10]=(i+r)*o,n[14]=2*i*r*o,n}function Fe(n,e,t,r){let[i,s,o]=e,[c,a,u]=r,[l,m,h]=t,y=i-l,b=s-m,d=o-h,g=Math.hypot(y,b,d);g<=1e-5?(y=0,b=0,d=1):(y/=g,b/=g,d/=g);let T=a*d-u*b,P=u*y-c*d,f=c*b-a*y;g=Math.hypot(T,P,f),g<=1e-5?(T=0,P=0,f=0):(T/=g,P/=g,f/=g);let R=b*f-d*P,p=d*T-y*f,M=y*P-b*T;return g=Math.hypot(R,p,M),g<=1e-5?(R=0,p=0,M=0):(R/=g,p/=g,M/=g),n[0]=T,n[1]=R,n[2]=y,n[3]=0,n[4]=P,n[5]=p,n[6]=b,n[7]=0,n[8]=f,n[9]=M,n[10]=d,n[11]=0,n[12]=-(T*i+P*s+f*o),n[13]=-(R*i+p*s+M*o),n[14]=-(y*i+b*s+d*o),n[15]=1,n}function ae(n,e,t){let r=e[0],i=e[1],s=e[2],o=e[3],c=e[4],a=e[5],u=e[6],l=e[7],m=e[8],h=e[9],y=e[10],b=e[11],d=e[12],g=e[13],T=e[14],P=e[15],f=t[0],R=t[1],p=t[2],M=t[3];return n[0]=f*r+R*c+p*m+M*d,n[1]=f*i+R*a+p*h+M*g,n[2]=f*s+R*u+p*y+M*T,n[3]=f*o+R*l+p*b+M*P,f=t[4],R=t[5],p=t[6],M=t[7],n[4]=f*r+R*c+p*m+M*d,n[5]=f*i+R*a+p*h+M*g,n[6]=f*s+R*u+p*y+M*T,n[7]=f*o+R*l+p*b+M*P,f=t[8],R=t[9],p=t[10],M=t[11],n[8]=f*r+R*c+p*m+M*d,n[9]=f*i+R*a+p*h+M*g,n[10]=f*s+R*u+p*y+M*T,n[11]=f*o+R*l+p*b+M*P,f=t[12],R=t[13],p=t[14],M=t[15],n[12]=f*r+R*c+p*m+M*d,n[13]=f*i+R*a+p*h+M*g,n[14]=f*s+R*u+p*y+M*T,n[15]=f*o+R*l+p*b+M*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,y=i*l,b=s*u,d=s*l,g=o*l,T=c*a,P=c*u,f=c*l,R=r[0],p=r[1],M=r[2];return n[0]=(1-(b+g))*R,n[1]=(h+f)*R,n[2]=(y-P)*R,n[3]=0,n[4]=(h-f)*p,n[5]=(1-(m+g))*p,n[6]=(d+T)*p,n[7]=0,n[8]=(y+P)*M,n[9]=(d-T)*M,n[10]=(1-(m+b))*M,n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n}function ye(n,e){let t=e[0],r=e[1],i=e[2],s=e[4],o=e[5],c=e[6],a=e[8],u=e[9],l=e[10],m=l*o-c*u,h=-l*s+c*a,y=u*s-o*a,b=t*m+r*h+i*y;return b&&(b=1/b,n[0]=m*b,n[1]=h*b,n[2]=y*b,n[3]=(-l*r+i*u)*b,n[4]=(l*t-i*a)*b,n[5]=(-u*t+r*a)*b,n[6]=(c*r-i*o)*b,n[7]=(-c*t+i*s)*b,n[8]=(o*t-r*s)*b),n}function Tn(n,e){let t=e[0],r=e[1],i=e[2],s=e[3],o=e[4],c=e[5],a=e[6],u=e[7],l=e[8],m=e[9],h=e[10],y=e[11],b=e[12],d=e[13],g=e[14],T=e[15],P=t*c-r*o,f=t*a-i*o,R=t*u-s*o,p=r*a-i*c,M=r*u-s*c,_=i*u-s*a,w=l*d-m*b,A=l*g-h*b,L=l*T-y*b,v=m*g-h*d,x=m*T-y*d,I=h*T-y*g,S=P*I-f*x+R*v+p*L-M*A+_*w;return S?(S=1/S,n[0]=(c*I-a*x+u*v)*S,n[1]=(i*x-r*I-s*v)*S,n[2]=(d*_-g*M+T*p)*S,n[3]=(h*M-m*_-y*p)*S,n[4]=(a*L-o*I-u*A)*S,n[5]=(t*I-i*L+s*A)*S,n[6]=(g*R-b*_-T*f)*S,n[7]=(l*_-h*R+y*f)*S,n[8]=(o*x-c*L+u*w)*S,n[9]=(r*L-t*x-s*w)*S,n[10]=(b*M-d*R+T*P)*S,n[11]=(m*R-l*M-y*P)*S,n[12]=(c*A-o*v-a*w)*S,n[13]=(t*v-r*A+i*w)*S,n[14]=(d*f-b*p-g*P)*S,n[15]=(l*p-m*f+h*P)*S,n):null}function Dt(n,e,t,r,i){let s=i[0]*e+i[4]*t+i[8]*r+i[12],o=i[1]*e+i[5]*t+i[9]*r+i[13],c=i[2]*e+i[6]*t+i[10]*r+i[14],a=i[3]*e+i[7]*t+i[11]*r+i[15],u=a!==0?1/a:1;n[0]=s*u,n[1]=o*u,n[2]=c*u}function _n(n,e,t,r,i,s,o,c,a,u,l,m,h,y,b,d,g=0){let T=u-o,P=l-c,f=m-a,R=h-o,p=y-c,M=b-a,_=i*M-s*p,w=s*R-r*M,A=r*p-i*R,L=T*_+P*w+f*A;if(L>-1e-7&&L<1e-7)return!1;let v=1/L,x=n-o,I=e-c,S=t-a,C=v*(x*_+I*w+S*A);if(C<-g||C>1+g)return!1;let F=I*f-S*P,N=S*T-x*f,V=x*P-I*T,U=v*(r*F+i*N+s*V);if(U<-g||C+U>1+g)return!1;let B=v*(R*F+p*N+M*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*M-f*p,H=f*R-T*M,z=T*p-P*R,O=Math.hypot(D,H,z)||1;return d.normal=[D/O,H/O,z/O],!0}return!1}function tt(n,e){let t=Array.isArray(n?.nodes)?n.nodes.length:0,r=[];for(let l=0;l<t;l++)r.push(oe());if(t===0)return r;let i=new Set;for(let l of n.nodes)if(Array.isArray(l.children))for(let m of l.children)i.add(m);let s=new Set,o=128,c=(l,m,h=0)=>{if(h>o||l<0||l>=t||s.has(l))return;s.add(l);let y=n.nodes[l];if(!y)return;let b=oe();if(e&&e[l])b.set(e[l]);else if(y.matrix&&y.matrix.length===16)b.set(y.matrix);else{let g=y.translation||[0,0,0],T=y.rotation||[0,0,0,1],P=y.scale||[1,1,1];Ce(b,T,g,P)}let d=r[l];if(m?ae(d,m,b):d.set(b),Array.isArray(y.children))for(let g of y.children)typeof g=="number"&&c(g,d,h+1)},a=[],u=n.scenes&&n.scenes[n.scene!==void 0?n.scene:0];if(u&&Array.isArray(u.nodes))a.push(...u.nodes);else for(let l=0;l<t;l++)i.has(l)||a.push(l);for(let l of a)c(l,null);for(let l=0;l<t;l++)!i.has(l)&&!a.includes(l)&&c(l,null);return r}var Sr={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function It(n,e,t,r){if(!t||t.bufferView===void 0)return null;let i=n.bufferViews?.[t.bufferView];if(!i)return null;let s=Number(t.count??0);if(!Number.isInteger(s)||s<=0)return null;let o=t.componentType??5126,c=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,y=new Float32Array(s*r);for(let b=0;b<s;b++){let d=l+b*u;for(let g=0;g<r;g++){let T=d+g*c,P;switch(o){case 5126:P=m.getFloat32(T,!0);break;case 5120:P=m.getInt8(T),h&&(P=Math.max(P/127,-1));break;case 5121:P=m.getUint8(T),h&&(P/=255);break;case 5122:P=m.getInt16(T,!0),h&&(P=Math.max(P/32767,-1));break;case 5123:P=m.getUint16(T,!0),h&&(P/=65535);break;default:P=m.getUint32(T,!0),h&&(P/=4294967295)}y[b*r+g]=P}}return y}function Cn(n,e){let t=Number(e.offset?.[0]??0)||0,r=Number(e.offset?.[1]??0)||0,i=Number(e.scale?.[0]??1),s=Number(e.scale?.[1]??1),o=Number(e.rotation??0)||0,c=Math.cos(o),a=Math.sin(o),u=(Number.isFinite(i)?i:1)*c,l=(Number.isFinite(i)?i:1)*a,m=-(Number.isFinite(s)?s:1)*a,h=(Number.isFinite(s)?s:1)*c;for(let y=0;y+1<n.length;y+=2){let b=n[y],d=n[y+1];n[y]=u*b+l*d+t,n[y+1]=m*b+h*d+r}}var Pn=["neutral","reinhard","none","aces","agx"];function Le(n){let e=String(n??"").trim().toLowerCase();return Pn.includes(e)?e:"neutral"}function Mr(n){return Pn.indexOf(Le(n))}function Er(n){return new TextDecoder().decode(n)}var Nn=Q().decoders;function Tr(n,e){Nn.set(n.toLowerCase(),e)}function ke(n){return Nn.get(n.toLowerCase())}function Fn(n){let e=ArrayBuffer.isView(n)?n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength):n,t=new DataView(e);if(e.byteLength<12)throw new Error(`Invalid GLB buffer size: ${e.byteLength} bytes`);let r=t.getUint32(0,!0);if(r!==1179937895){let h=t.getUint8(0);throw h===123||h===32||h===10||h===13?new Error("[three-live] Multi-file JSON .gltf is not supported for performance reasons. Please pack your asset into a single binary .glb file."):new Error(`Invalid GLB magic: 0x${r.toString(16)}`)}let i=t.getUint32(4,!0);if(i!==2)throw new Error(`Unsupported GLB version: ${i}`);let s=t.getUint32(8,!0),o=12,c=null,a=null;for(;o+8<=s&&o+8<=e.byteLength;){let h=t.getUint32(o,!0),y=t.getUint32(o+4,!0),b=o+8;if(b+h>e.byteLength)throw new Error(`Truncated GLB chunk: required ${b+h} bytes, buffer has ${e.byteLength}`);if(y===1313821514){let d=new Uint8Array(e,b,h),g=Er(d);c=JSON.parse(g,(T,P)=>T==="__proto__"||T==="constructor"||T==="prototype"?void 0:P)}else y===5130562&&(a=e.slice(b,b+h));o=b+h}if(!c)throw new Error("Missing JSON chunk in GLB");let u=c.extensionsRequired||[];if(u.includes("KHR_draco_mesh_compression")&&!ke("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)&&!ke("meshopt"))throw new Error(`Model requires ${h}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(u.includes("KHR_texture_basisu")&&!ke("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let l=a||new ArrayBuffer(0),m={gltf:c,bin:l,animations:[]};for(let h of ce)h.onParseGLB?.(m);return m}function _r(n){return typeof n=="object"&&n!==null&&"gltf"in n&&typeof n.gltf=="object"&&n.gltf!==null&&"bin"in n&&(n.bin instanceof ArrayBuffer||ArrayBuffer.isView(n.bin))}function Ae(n){if(_r(n))return n;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return Fn(n);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var kn=`#version 300 es
|
|
20
|
-
layout(location=0) in vec3
|
|
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);}`,Gt=new WeakMap,Ge=new Float32Array(20);function ye(e,t){let[i,r,s,a,o,n]=t;return[e[0]*i+e[4]*r+e[8]*s+e[12],e[1]*i+e[5]*r+e[9]*s+e[13],e[2]*i+e[6]*r+e[10]*s+e[14],Math.abs(e[0])*a+Math.abs(e[4])*o+Math.abs(e[8])*n,Math.abs(e[1])*a+Math.abs(e[5])*o+Math.abs(e[9])*n,Math.abs(e[2])*a+Math.abs(e[6])*o+Math.abs(e[10])*n]}function Mr(e){if(e._lb!==void 0)return e._lb;let t=1e9,i=1e9,r=1e9,s=-1e9,a=-1e9,o=-1e9;for(let n of e.primitives||[]){let h=n.positions;if(h)for(let l=0;l<h.length;l+=3)h[l]<t&&(t=h[l]),h[l+1]<i&&(i=h[l+1]),h[l+2]<r&&(r=h[l+2]),h[l]>s&&(s=h[l]),h[l+1]>a&&(a=h[l+1]),h[l+2]>o&&(o=h[l+2])}return e._lb=t<=s?[(t+s)*.5,(i+a)*.5,(r+o)*.5,(s-t)*.5,(a-i)*.5,(o-r)*.5]:null}function Sr(e){let t=Gt.get(e);if(t)return t;let i=(n,h)=>{let l=e.createShader(n);return e.shaderSource(l,h),e.compileShader(l),l},r=e.createProgram();e.attachShader(r,i(35633,xr)),e.attachShader(r,i(35632,wr)),e.linkProgram(r);let s=e.createVertexArray(),a=e.createBuffer(),o=e.createBuffer();return e.bindVertexArray(s),e.bindBuffer(34962,a),e.bufferData(34962,80,35048),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,3,5126,!1,20,0),e.enableVertexAttribArray(1),e.vertexAttribPointer(1,2,5126,!1,20,12),e.bindBuffer(34963,o),e.bufferData(34963,new Uint16Array([0,1,2,0,2,3]),35044),e.bindVertexArray(null),t={prog:r,vao:s,vbo:a,ibo:o,uMVP:e.getUniformLocation(r,"uMVP"),uIntensity:e.getUniformLocation(r,"uShadowIntensity"),uSoftness:e.getUniformLocation(r,"uShadowSoftness")},Gt.set(e,t),t}var Ar={name:"contact-shadow",onContextRestored(e){Gt.delete(e)},onAfterRender(e,t,i){let r=t.shadowIntensity;if(r<=0||!t.bounds)return;let s=Sr(e),a=!t.xrSessionActive&&(t.backdropMeshes?.length??0)>0,o=[],n=[];for(let u of t.meshes||[]){if(!u||u.visible===!1||u.isPluginMesh||u.name==="__xr_reticle__"||u.name?.startsWith("__xr_slot_"))continue;let d=Mr(u);if(!d)continue;u.transform&&(d=ye(u.transform,d)),t.modelRootMatrix&&(d=ye(t.modelRootMatrix,d));let[M,w,v,m,p,x]=d,S=[M,v,m,x,w-p,w+p];/floor|table|pedestal|ground|base|plane/i.test(u.name||"")||p<.14&&Math.min(m,x)>.45?n.push(S):o.push(S)}let h=[],l=t.bounds.center||[0,0,0],c=Math.max(.05,Number(t.bounds.radius)||.5),f=t.bounds.min,g=f?[l[0],l[1],l[2],c,Math.max(.01,l[1]-f[1]),c]:[l[0],l[1],l[2],c,c,c];t.modelRootMatrix&&(g=ye(t.modelRootMatrix,g));let b=t.xrSessionActive&&n.length===0&&String(t.container?.tagName||"").toLowerCase()==="xr-live"?(t.modelRootMatrix?t.modelRootMatrix[5]*-.25+t.modelRootMatrix[13]:-.25)+.002:g[1]-g[4]+.002;for(let[u,d,M,w,v]of o){let m=-1/0;for(let[x,S,N,F,,E]of n)v>=E-.08&&Math.abs(u-x)<=N&&Math.abs(d-S)<=F&&E+.002>m&&(m=E+.002);a&&(m=Math.max(m,u>=.04&&u<=.36&&d>=-.34&&d<=-.04&&v>=.01?.036:Math.hypot(u,d)<=.66&&v>=-.06?.003:-.477)),isFinite(m)||(m=b);let p=h.find(x=>Math.hypot(u-x[0],d-x[1])<.06&&Math.abs(m-x[5])<.05);p?(p[2]=Math.max(p[2],M*.78),p[3]=Math.max(p[3],w*.78),p[4]=Math.min(p[4],v)):h.push([u,d,M,w,v,m])}if(h.length===0){let u=Math.max(.1,g[3]*1.5)/1.45;h.push([g[0],g[2],u,u,b,b])}e.useProgram(s.prog),e.uniformMatrix4fv(s.uMVP,!1,i),e.enable(3042),(e.blendFuncSeparate||e.blendFunc).call(e,770,771,1,771),e.depthMask(!1),e.bindVertexArray(s.vao),e.bindBuffer(34962,s.vbo);for(let[u,d,M,w,v,m]of h){let p=Math.max(0,v-m),x=r/(1+p*2);if(x<.02)continue;let S=1+Math.min(.75,p*.85),N=Math.max(.045,M*1.45*S),F=Math.max(.045,w*1.45*S);Ge.set([u-N,m,d-F,0,0,u+N,m,d-F,1,0,u+N,m,d+F,1,1,u-N,m,d+F,0,1]),e.bufferSubData(34962,0,Ge),e.uniform1f(s.uIntensity,x),e.uniform1f(s.uSoftness,Math.min(1,t.shadowSoftness+Math.min(.45,p*.6))),e.drawElements(4,6,5123,0)}e.bindVertexArray(null),e.depthMask(!0),e.disable(3042)},onDestroy(e){let t=Gt.get(e);t&&(e.deleteVertexArray(t.vao),e.deleteBuffer(t.vbo),e.deleteBuffer(t.ibo),e.deleteProgram(t.prog),Gt.delete(e))}};function Tr(e,t,i){let r=[],s=new Map,a=[],o=[],n=[],h=new Map,l=m=>{let p=s.get(m);return p===void 0&&(p=r.length,r.push({op:m}),s.set(m,p)),p},c=m=>{let p=h.get(m);return p===void 0&&(p=n.length,n.push({id:m}),h.set(m,p)),p},f=(m,p={})=>a.push({declaration:l(m),...p})-1,g=(m,p,x)=>o.push({id:m,type:p,value:x})-1,b=m=>({node:m,socket:"value"}),u=i?.interactivity??i?.gltfExtensions?.KHR_interactivity;if(u&&typeof u=="object"){let m=Array.isArray(u.graphs)?u.graphs[u.graph??0]:u;if(m&&Array.isArray(m.nodes)){let p=Array.isArray(m.declarations)?m.declarations:[];for(let x of p)x?.op&&l(x.op);Array.isArray(m.variables)&&o.push(...m.variables);for(let x of m.events||[])x?.id&&c(x.id);for(let x of m.nodes){if(!x||typeof x!="object")continue;let S=x.op||(typeof x.declaration=="number"?p[x.declaration]?.op:"");a.push(S?{...x,declaration:l(S)}:{...x})}}}let d=(m,p,x="translation")=>x==="baseColorFactor"||x==="metallicFactor"||x==="roughnessFactor"?`/materials/${Math.max(0,p)}/pbrMetallicRoughness/${x}`:x==="emissiveFactor"||x==="alphaCutoff"?`/materials/${Math.max(0,p)}/${x}`:x==="visible"?`/nodes/${m}/extensions/KHR_node_visibility/visible`:`/nodes/${m}/${x}`,M=new Map;e.forEach((m,p)=>{typeof m?.name=="string"&&!M.has(m.name)&&M.set(m.name,p)});let w=(m,p)=>typeof m.target=="string"&&M.has(m.target)?M.get(m.target):typeof m.targetNode=="number"?m.targetNode:p,v=m=>{let p=e[m];return(typeof p?.mesh=="number"?t[p.mesh]?.primitives?.[0]?.material:0)??0};for(let m=0;m<e.length;m++){let p=e[m],x=p?.extras?.interactivity;if(!x||typeof x!="object")continue;let S=(typeof p.mesh=="number"?t[p.mesh]?.primitives?.[0]?.material:0)??0,N=E=>{let L=Array.isArray(E)?E:[E],C=[];for(let R=0;R<L.length;R++){let y=L[R];if(!y||typeof y!="object")continue;let U=y.action||"interpolate",j=typeof y.duration=="number"?y.duration:.35;if(U==="toggleTransform"){let T=y.property==="rotation"||y.property==="scale"?y.property:"translation",k=T==="rotation"?p.rotation||[0,0,0,1]:T==="scale"?p.scale||[1,1,1]:p.translation||[0,0,0],A=`/nodes/${m}/${T}`,P=g(`__toggle_${m}_${R}`,"bool",!1),G=f("variable/get",{configuration:{variable:P}}),q=f("math/not",{values:{a:b(G)}}),$=f("variable/set",{configuration:{variable:P},values:{value:b(q)}}),Y=f("pointer/interpolate",{configuration:{pointer:A},values:{value:{value:Array.isArray(y.to)?y.to:k},duration:{value:j}}}),_=f("pointer/interpolate",{configuration:{pointer:A},values:{value:{value:Array.isArray(y.from)?y.from:k},duration:{value:j}}});a[$].flows={out:{node:f("flow/branch",{values:{condition:b(G)},flows:{true:{node:Y},false:{node:_}}})}},C.push($)}else if(U==="interpolate"){let T=y.to??y.value;if(T===void 0)continue;let k={value:{value:T},duration:{value:j}};y.from!==void 0&&(k.from={value:y.from}),C.push(f("pointer/interpolate",{configuration:{pointer:typeof y.pointer=="string"?y.pointer:d(w(y,m),v(w(y,m)),y.property)},values:k}))}else if(U==="setProperty"){if(y.value===void 0)continue;C.push(f("pointer/set",{configuration:{pointer:typeof y.pointer=="string"?y.pointer:d(w(y,m),v(w(y,m)),y.property)},values:{value:{value:y.value}}}))}else if(U==="toggleVisibility"){let T=w(y,m),k=g(`__vis_${T}_${R}`,"bool",!0),A=f("variable/get",{configuration:{variable:k}}),P=f("math/not",{values:{a:b(A)}}),G=f("variable/set",{configuration:{variable:k},values:{value:b(P)}});a[G].flows={out:{node:f("pointer/set",{configuration:{pointer:`/nodes/${T}/extensions/KHR_node_visibility/visible`},values:{value:b(A)}})}},C.push(G)}else if(U==="cycleMaterialColor"&&Array.isArray(y.colors)&&y.colors.length>0){let T=typeof y.duration=="number"?y.duration:.25,k=`/materials/${Math.max(0,S)}/pbrMetallicRoughness/baseColorFactor`,A=g(`__color_idx_${m}_${R}`,"int",0),P=f("variable/get",{configuration:{variable:A}}),G=f("math/add",{values:{a:b(P),b:{value:1}}}),q=f("math/rem",{values:{a:b(G),b:{value:y.colors.length}}}),$=f("variable/set",{configuration:{variable:A},values:{value:b(q)}}),Y={};for(let _=0;_<y.colors.length;_++){let z=y.colors[_],V=Array.isArray(z)&&z.length>=3?[z[0],z[1],z[2],z[3]??1]:[1,1,1,1];Y[String(_)]={node:T>0?f("pointer/interpolate",{configuration:{pointer:k},values:{value:{value:V},duration:{value:T}}}):f("pointer/set",{configuration:{pointer:k},values:{value:{value:V}}})}}a[$].flows={out:{node:f("flow/switch",{values:{selection:b(P)},flows:Y})}},C.push($)}else if(U==="playAnimation")C.push(f("animation/start",{configuration:{animation:y.animation??y.clip??0}}));else if(U==="stopAnimation")C.push(f("animation/stop"));else if(U==="sendEvent"){let T={};for(let[k,A]of Object.entries(y.values||{}))T[k]={value:A};C.push(f("event/send",{configuration:{event:c(String(y.event??y.id??"custom"))},values:T}))}}if(!C.length)return null;if(C.length===1)return C[0];let D={};return C.forEach((R,y)=>{D[String(y)]={node:R}}),f("flow/sequence",{flows:D})},F=(E,L,C)=>{let D=N(L);D!==null&&f(E,{...C?{configuration:C}:{},flows:{out:{node:D}}})};if(x.onSelect&&F("pointer/onSelect",x.onSelect,{nodeIndex:m}),x.onHoverIn&&F("pointer/onHoverIn",x.onHoverIn,{nodeIndex:m}),x.onHoverOut&&F("pointer/onHoverOut",x.onHoverOut,{nodeIndex:m}),x.onStart&&F("event/onStart",x.onStart),x.onReceive&&typeof x.onReceive=="object")for(let[E,L]of Object.entries(x.onReceive))F("event/receive",L,{event:c(E)})}return a.length?{graphs:[{declarations:r,nodes:a,variables:o,events:n}],graph:0}:null}var We='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).',je="Security Error: client-side scripts require allow-client-scripts opt-in.";function mt(){let e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function ve(e,t,i,r,s){let a=1/Math.tan(t/2);e.fill(0),e[0]=a/i,e[5]=a,e[11]=-1;let o=1/(r-s);return e[10]=(s+r)*o,e[14]=2*s*r*o,e}function Jt(e,t,i,r){let[s,a,o]=t,[n,h,l]=r,[c,f,g]=i,b=s-c,u=a-f,d=o-g,M=Math.hypot(b,u,d);M<=1e-5?(b=0,u=0,d=1):(b/=M,u/=M,d/=M);let w=h*d-l*u,v=l*b-n*d,m=n*u-h*b;M=Math.hypot(w,v,m),M<=1e-5?(w=0,v=0,m=0):(w/=M,v/=M,m/=M);let p=u*m-d*v,x=d*w-b*m,S=b*v-u*w;return M=Math.hypot(p,x,S),M<=1e-5?(p=0,x=0,S=0):(p/=M,x/=M,S/=M),e[0]=w,e[1]=p,e[2]=b,e[3]=0,e[4]=v,e[5]=x,e[6]=u,e[7]=0,e[8]=m,e[9]=S,e[10]=d,e[11]=0,e[12]=-(w*s+v*a+m*o),e[13]=-(p*s+x*a+S*o),e[14]=-(b*s+u*a+d*o),e[15]=1,e}function dt(e,t,i){let r=t[0],s=t[1],a=t[2],o=t[3],n=t[4],h=t[5],l=t[6],c=t[7],f=t[8],g=t[9],b=t[10],u=t[11],d=t[12],M=t[13],w=t[14],v=t[15],m=i[0],p=i[1],x=i[2],S=i[3];return e[0]=m*r+p*n+x*f+S*d,e[1]=m*s+p*h+x*g+S*M,e[2]=m*a+p*l+x*b+S*w,e[3]=m*o+p*c+x*u+S*v,m=i[4],p=i[5],x=i[6],S=i[7],e[4]=m*r+p*n+x*f+S*d,e[5]=m*s+p*h+x*g+S*M,e[6]=m*a+p*l+x*b+S*w,e[7]=m*o+p*c+x*u+S*v,m=i[8],p=i[9],x=i[10],S=i[11],e[8]=m*r+p*n+x*f+S*d,e[9]=m*s+p*h+x*g+S*M,e[10]=m*a+p*l+x*b+S*w,e[11]=m*o+p*c+x*u+S*v,m=i[12],p=i[13],x=i[14],S=i[15],e[12]=m*r+p*n+x*f+S*d,e[13]=m*s+p*h+x*g+S*M,e[14]=m*a+p*l+x*b+S*w,e[15]=m*o+p*c+x*u+S*v,e}function xe(e,t,i,r){let s=t[0],a=t[1],o=t[2],n=t[3],h=s+s,l=a+a,c=o+o,f=s*h,g=s*l,b=s*c,u=a*l,d=a*c,M=o*c,w=n*h,v=n*l,m=n*c,p=r[0],x=r[1],S=r[2];return e[0]=(1-(u+M))*p,e[1]=(g+m)*p,e[2]=(b-v)*p,e[3]=0,e[4]=(g-m)*x,e[5]=(1-(f+M))*x,e[6]=(d+w)*x,e[7]=0,e[8]=(b+v)*S,e[9]=(d-w)*S,e[10]=(1-(f+u))*S,e[11]=0,e[12]=i[0],e[13]=i[1],e[14]=i[2],e[15]=1,e}function Et(e,t,i=0){let r=t[0],s=t[1],a=t[2],o=t[4],n=t[5],h=t[6],l=t[8],c=t[9],f=t[10],g=f*n-h*c,b=-f*o+h*l,u=c*o-n*l,d=r*g+s*b+a*u;return!d||i>0&&(!Number.isFinite(d)||Math.abs(d)<=i)||(d=1/d,e[0]=g*d,e[1]=b*d,e[2]=u*d,e[3]=(-f*s+a*c)*d,e[4]=(f*r-a*l)*d,e[5]=(-c*r+s*l)*d,e[6]=(h*s-a*n)*d,e[7]=(-h*r+a*o)*d,e[8]=(n*r-s*o)*d),e}function Rr(e,t){let i=t[0],r=t[1],s=t[2],a=t[3],o=t[4],n=t[5],h=t[6],l=t[7],c=t[8],f=t[9],g=t[10],b=t[11],u=t[12],d=t[13],M=t[14],w=t[15],v=i*n-r*o,m=i*h-s*o,p=i*l-a*o,x=r*h-s*n,S=r*l-a*n,N=s*l-a*h,F=c*d-f*u,E=c*M-g*u,L=c*w-b*u,C=f*M-g*d,D=f*w-b*d,R=g*w-b*M,y=v*R-m*D+p*C+x*L-S*E+N*F;return y?(y=1/y,e[0]=(n*R-h*D+l*C)*y,e[1]=(s*D-r*R-a*C)*y,e[2]=(d*N-M*S+w*x)*y,e[3]=(g*S-f*N-b*x)*y,e[4]=(h*L-o*R-l*E)*y,e[5]=(i*R-s*L+a*E)*y,e[6]=(M*p-u*N-w*m)*y,e[7]=(c*N-g*p+b*m)*y,e[8]=(o*D-n*L+l*F)*y,e[9]=(r*L-i*D-a*F)*y,e[10]=(u*S-d*p+w*v)*y,e[11]=(f*p-c*S-b*v)*y,e[12]=(n*E-o*C-h*F)*y,e[13]=(i*C-r*E+s*F)*y,e[14]=(d*m-u*x-M*v)*y,e[15]=(c*x-f*m+g*v)*y,e):null}function Xe(e,t,i,r,s){let a=s[0]*t+s[4]*i+s[8]*r+s[12],o=s[1]*t+s[5]*i+s[9]*r+s[13],n=s[2]*t+s[6]*i+s[10]*r+s[14],h=s[3]*t+s[7]*i+s[11]*r+s[15],l=h!==0?1/h:1;e[0]=a*l,e[1]=o*l,e[2]=n*l}function Cr(e,t,i,r,s,a,o,n,h,l,c,f,g,b,u,d,M=0){let w=l-o,v=c-n,m=f-h,p=g-o,x=b-n,S=u-h,N=s*S-a*x,F=a*p-r*S,E=r*x-s*p,L=w*N+v*F+m*E;if(L>-1e-7&&L<1e-7)return!1;let C=1/L,D=e-o,R=t-n,y=i-h,U=C*(D*N+R*F+y*E);if(U<-M||U>1+M)return!1;let j=R*m-y*v,T=y*w-D*m,k=D*v-R*w,A=C*(r*j+s*T+a*k);if(A<-M||U+A>1+M)return!1;let P=C*(p*j+x*T+S*k);if(P>1e-4&&P<d.distance){d.distance=P,d.point=[e+r*P,t+s*P,i+a*P];let G=v*S-m*x,q=m*p-w*S,$=w*x-v*p,Y=Math.hypot(G,q,$)||1;return d.normal=[G/Y,q/Y,$/Y],!0}return!1}function Pr(e,t){let i=Array.isArray(e?.nodes)?e.nodes.length:0,r=[];for(let c=0;c<i;c++)r.push(mt());if(i===0)return r;let s=new Set;for(let c of e.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 b=e.nodes[c];if(!b)return;let u=mt();if(t&&t[c])u.set(t[c]);else if(b.matrix&&b.matrix.length===16)u.set(b.matrix);else{let M=b.translation||[0,0,0],w=b.rotation||[0,0,0,1],v=b.scale||[1,1,1];xe(u,w,M,v)}let d=r[c];if(f?dt(d,f,u):d.set(u),Array.isArray(b.children))for(let M of b.children)typeof M=="number"&&n(M,d,g+1)},h=[],l=e.scenes&&e.scenes[e.scene!==void 0?e.scene:0];if(l&&Array.isArray(l.nodes))h.push(...l.nodes);else for(let c=0;c<i;c++)s.has(c)||h.push(c);for(let c of h)n(c,null);for(let c=0;c<i;c++)!s.has(c)&&!h.includes(c)&&n(c,null);return r}var Er={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function qe(e,t,i,r){if(!i||i.bufferView===void 0)return null;let s=e.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=Er[o];if(!n)throw new RangeError(`glTF accessor has unsupported componentType ${o}`);let h=n*r,l=s.byteStride&&s.byteStride>0?s.byteStride:h,c=(s.byteOffset||0)+(i.byteOffset||0);if(!Number.isInteger(c)||c<0||l<h||c+(a-1)*l+h>t.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${t.byteLength} bytes)`);if(o===5126&&l===h&&c%4===0)return new Float32Array(t,c,a*r);let f=new DataView(t),g=i.normalized===!0,b=new Float32Array(a*r);for(let u=0;u<a;u++){let d=c+u*l;for(let M=0;M<r;M++){let w=d+M*n,v;switch(o){case 5126:v=f.getFloat32(w,!0);break;case 5120:v=f.getInt8(w),g&&(v=Math.max(v/127,-1));break;case 5121:v=f.getUint8(w),g&&(v/=255);break;case 5122:v=f.getInt16(w,!0),g&&(v=Math.max(v/32767,-1));break;case 5123:v=f.getUint16(w,!0),g&&(v/=65535);break;default:v=f.getUint32(w,!0),g&&(v/=4294967295)}b[u*r+M]=v}}return b}function _r(e,t){let i=Number(t.offset?.[0]??0)||0,r=Number(t.offset?.[1]??0)||0,s=Number(t.scale?.[0]??1),a=Number(t.scale?.[1]??1),o=Number(t.rotation??0)||0,n=Math.cos(o),h=Math.sin(o),l=(Number.isFinite(s)?s:1)*n,c=(Number.isFinite(s)?s:1)*h,f=-(Number.isFinite(a)?a:1)*h,g=(Number.isFinite(a)?a:1)*n;for(let b=0;b+1<e.length;b+=2){let u=e[b],d=e[b+1];e[b]=l*u+c*d+i,e[b+1]=f*u+g*d+r}}function we(e,t,i,r=!0){let s=[],a=null;try{for(let[o,n]of[[35633,t],[35632,i]]){let h=e.createShader(o);if(!h){if(r)throw new Error("Shader allocation failed");return null}if(s.push(h),e.shaderSource(h,n),e.compileShader(h),e.getShaderParameter&&!e.getShaderParameter(h,35713)){if(r)throw new Error(`Shader compile error: ${e.getShaderInfoLog(h)}`);return null}}if(a=e.createProgram(),!a){if(r)throw new Error("Program allocation failed");return null}for(let o of s)e.attachShader(a,o);if(e.linkProgram(a),e.getProgramParameter&&!e.getProgramParameter(a,35714)){let o=r?e.getProgramInfoLog(a):null;if(e.deleteProgram?.(a),a=null,r)throw new Error(`Program link error: ${o}`);return null}return a}finally{for(let o of s)a&&e.detachShader?.(a,o),e.deleteShader?.(o)}}var Ke=["neutral","reinhard","none","aces","agx"];function Ut(e){let t=String(e??"").trim().toLowerCase();return Ke.includes(t)?t:"neutral"}function Nr(e){return Ke.indexOf(Ut(e))}function Lr(e){return new TextDecoder().decode(e)}var Ye=ot().decoders;function Dr(e,t){Ye.set(e.toLowerCase(),t)}function Vt(e){return Ye.get(e.toLowerCase())}function Ze(e){let t=ArrayBuffer.isView(e)?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):e,i=new DataView(t);if(t.byteLength<12)throw new Error(`Invalid GLB buffer size: ${t.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,h=null;for(;o+8<=a&&o+8<=t.byteLength;){let g=i.getUint32(o,!0),b=i.getUint32(o+4,!0),u=o+8;if(u+g>t.byteLength)throw new Error(`Truncated GLB chunk: required ${u+g} bytes, buffer has ${t.byteLength}`);if(b===1313821514){let d=new Uint8Array(t,u,g),M=Lr(d);n=JSON.parse(M,(w,v)=>w==="__proto__"||w==="constructor"||w==="prototype"?void 0:v)}else b===5130562&&(h=t.slice(u,u+g));o=u+g}if(!n)throw new Error("Missing JSON chunk in GLB");let l=n.extensionsRequired||[];if(l.includes("KHR_draco_mesh_compression")&&!Vt("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(l.includes(g)&&!Vt("meshopt"))throw new Error(`Model requires ${g}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(l.includes("KHR_texture_basisu")&&!Vt("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let c=h||new ArrayBuffer(0),f={gltf:n,bin:c,animations:[]};for(let g of ct)g.onParseGLB?.(f);return f}function kr(e){return typeof e=="object"&&e!==null&&"gltf"in e&&typeof e.gltf=="object"&&e.gltf!==null&&"bin"in e&&(e.bin instanceof ArrayBuffer||ArrayBuffer.isView(e.bin))}function zt(e){if(kr(e))return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Ze(e);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var Je=`#version 300 es
|
|
19
|
+
layout(location=0) in vec3 aPos;
|
|
20
|
+
layout(location=3) in vec3 aOff;
|
|
21
21
|
layout(location=1) in vec3 aNormal;
|
|
22
22
|
layout(location=2) in vec2 aUV;
|
|
23
23
|
uniform mat4 uMVP,uModel;
|
|
@@ -40,6 +40,7 @@ mat3 xrNormalMatrix(){return uInstanced==1?transpose(inverse(mat3(xrModel()))):u
|
|
|
40
40
|
out vec3 vNormal,vWorldPos;
|
|
41
41
|
out vec2 vUV;
|
|
42
42
|
void main(){
|
|
43
|
+
vec3 aPosition=aPos+aOff;
|
|
43
44
|
vInstTint=uInstanced==1?aInstColor:vec4(1.0);
|
|
44
45
|
vec3 rawN=uNormalMatrix*aNormal;
|
|
45
46
|
vNormal=length(rawN)>1e-5?normalize(rawN):vec3(0.0);
|
|
@@ -49,7 +50,7 @@ vec2 scaleUV=uUvTransform.zw;
|
|
|
49
50
|
if(scaleUV.x==0.0&&scaleUV.y==0.0)scaleUV=vec2(1.0);
|
|
50
51
|
vUV=aUV*scaleUV+uUvTransform.xy;
|
|
51
52
|
gl_Position=uMVP*vec4(aPosition,1.0);
|
|
52
|
-
}`,
|
|
53
|
+
}`,Fr=`#version 300 es
|
|
53
54
|
precision highp float;
|
|
54
55
|
in vec3 vNormal,vWorldPos;
|
|
55
56
|
in vec2 vUV;
|
|
@@ -66,7 +67,8 @@ uniform float uNormalScale,uOcclusionStrength;
|
|
|
66
67
|
uniform vec2 uViewportSize;
|
|
67
68
|
uniform vec4 uSectionPlane;
|
|
68
69
|
uniform int uToneMapping,uNumDirLights,uNumPointLights,uSectionEnabled;
|
|
69
|
-
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];
|
|
70
72
|
out vec4 fragColor;
|
|
71
73
|
|
|
72
74
|
vec2 envBRDF(float r,float n){
|
|
@@ -157,6 +159,11 @@ if(mode==4)return agxToneMapping(color);
|
|
|
157
159
|
return color;
|
|
158
160
|
}
|
|
159
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
|
+
|
|
160
167
|
void main(){
|
|
161
168
|
if(uSectionEnabled==1&&dot(vWorldPos,uSectionPlane.xyz)>uSectionPlane.w)discard;
|
|
162
169
|
vec4 base=uBaseColor;
|
|
@@ -194,24 +201,16 @@ float specWeight=mix(0.22*gloss,1.0,metallic);
|
|
|
194
201
|
vec3 directLight=vec3(0.0);
|
|
195
202
|
for(int i=0;i<2;i++){
|
|
196
203
|
if(i>=uNumDirLights)break;
|
|
197
|
-
|
|
198
|
-
float NdotL=max(dot(N,L),0.0);
|
|
199
|
-
vec3 H=normalize(L+V);
|
|
200
|
-
float NoH=max(dot(N,H),0.0);
|
|
201
|
-
float spec=pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35;
|
|
202
|
-
directLight+=(base.rgb*NdotL*0.75+vec3(spec))*uDirLightColor[i];
|
|
204
|
+
directLight+=evalLight(normalize(uDirLightDir[i]),V,N,base.rgb,specExp,specWeight)*uDirLightColor[i];
|
|
203
205
|
}
|
|
204
206
|
for(int i=0;i<2;i++){
|
|
205
207
|
if(i>=uNumPointLights)break;
|
|
206
208
|
vec3 toLight=uPointLightPos[i]-vWorldPos;
|
|
207
209
|
float dist=length(toLight);
|
|
208
210
|
vec3 L=toLight/max(dist,0.0001);
|
|
209
|
-
float
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
float NoH=max(dot(N,H),0.0);
|
|
213
|
-
float spec=pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35;
|
|
214
|
-
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);
|
|
215
214
|
}
|
|
216
215
|
|
|
217
216
|
vec3 R=reflect(-V,N);
|
|
@@ -242,86 +241,113 @@ color=applyToneMapping(color,uToneMapping);
|
|
|
242
241
|
float outAlpha=base.a;
|
|
243
242
|
/*XRD_O*/
|
|
244
243
|
fragColor=vec4(color,outAlpha);
|
|
245
|
-
}`;function
|
|
244
|
+
}`;function Ir(e,t,i=1){t=Ut(t);let r=Number.isFinite(i)?Math.max(0,i):1,[s,a,o]=[0,1,2].map(d=>Math.max(0,(Number(e[d])||0)*r)),n=d=>Math.max(0,Math.min(1,d)),h=d=>[d(s),d(a),d(o)];if(t==="none")return h(n);if(t==="reinhard")return h(d=>d/(d+1));if(t==="aces")return h(d=>{let M=d*.6;return n(M*(2.51*M+.03)/(M*(2.43*M+.59)+.14))});if(t==="agx"){let[d,M,w]=[.84247906*s+.0784336*a+.07922375*o,.04232824*s+.87846864*a+.07916613*o,.04237565*s+.0784336*a+.87914297*o].map(v=>{let m=n((Math.log2(Math.max(v,1e-6))+12.47393)/16.5),p=m*m,x=p*p;return 15.5*x*p-40.14*x*m+31.96*x-6.868*p*m+.4298*p+.1191*m-.00232});return[1.196879*d-.09802088*M-.09902974*w,-.05289685*d+1.15190313*M-.09896118*w,-.05297164*d-.09804345*M+1.15107367*w].map(v=>n(Math.pow(Math.max(v,0),2.2)))}let l=Math.min(s,a,o),c=l<.08?l-6.25*l*l:.04;[s,a,o]=h(d=>d-c);let f=Math.max(s,a,o);if(f<.76)return h(n);let g=1-.0576/(f-.52),b=g/f,u=1-1/(.15*(f-g)+1);return h(d=>n(d*b+(g-d*b)*u))}var Or=`#version 300 es
|
|
246
245
|
layout(location=0) in vec3 aPosition;
|
|
247
246
|
uniform mat4 uMVP;
|
|
248
|
-
void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,
|
|
247
|
+
void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,Ur=`#version 300 es
|
|
249
248
|
precision highp float;
|
|
250
249
|
uniform vec4 uColorId;
|
|
251
250
|
out vec4 fragColor;
|
|
252
|
-
void main(){fragColor=uColorId;}`;function Ln(n,e,t){let r=n.createShader(e);if(n.shaderSource(r,t),n.compileShader(r),!n.getShaderParameter(r,35713)){let i=n.getShaderInfoLog(r);throw n.deleteShader(r),new Error(`Shader compile error: ${i}`)}return r}function Ft(n,e,t){let r=Ln(n,35633,e),i=Ln(n,35632,t),s=n.createProgram();if(n.attachShader(s,r),n.attachShader(s,i),n.linkProgram(s),!n.getProgramParameter(s,35714)){let o=n.getProgramInfoLog(s);throw n.deleteProgram(s),new Error(`Program link error: ${o}`)}return s}function kt(n,e,t){let r={};for(let i of t)r[i]=n.getUniformLocation(e,i);return r}var Dn=["uMVP","uModel","uInstanced","uViewProj","uNormalMatrix","uUvTransform","uBaseColor","uMetallic","uRoughness","uClearcoat","uEmissive","uCameraPos","uBaseColorTexture","uHasTexture","uMetallicRoughnessTexture","uHasMetallicRoughnessTexture","uNormalTexture","uHasNormalTexture","uNormalScale","uOcclusionTexture","uHasOcclusionTexture","uOcclusionStrength","uToneMapping","uEnvironmentMap","uHasEnvironmentMap","uAmbientColor","uNumDirLights","uDirLightDir","uDirLightColor","uNumPointLights","uPointLightPos","uPointLightColor","uEnvIntensity","uExposure","uViewportSize","uSectionPlane","uSectionEnabled"];function On(){let n=Q().xrDepthShader;return{fs:Cr.replace("/*XRD_U*/",n?.uniformsGLSL||"").replace("/*XRD_O*/",n?.occlusionGLSL||""),uniforms:n?[...Dn,...n.uniformNames]:Dn}}function Ir(n){if(typeof n!="string")return null;let e=n.trim();if(!e||/[\x00-\x1f\x7f]/.test(e))return null;let t=e.toLowerCase();return t.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(e)?e:null:t.startsWith("https://")||t.startsWith("blob:")?e:t.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(e)||/(^|[\\/])\.\.([\\/]|$)/.test(e)?null:e}function Pt(n,e,t,r,i,s,o,c){if(r===void 0||!e.accessors?.[r])return null;let a=It(e,t,e.accessors[r],s);if(!a)return null;c&&(a=a.slice(),Cn(a,c));let u=n.createBuffer();return o.push(u),n.bindBuffer(34962,u),n.bufferData(34962,a,35044),n.enableVertexAttribArray(i),n.vertexAttribPointer(i,s,5126,!1,0,0),a}function Nt(n){let e=Number(n);return Number.isFinite(e)?Math.max(0,e):1}function Bn(n,e,t){let r=On(),i=kn,s=r.fs,o=!1;for(let a of ce)if(a.onResolveShader){let u=a.onResolveShader(e,t,i,s);u&&(i=u.vs,s=u.fs,o=!0)}let c=o?Ft(n,i,s):null;return{program:c,uniforms:c?kt(n,c,r.uniforms):null}}function Pr(n,e,t){let r=e.instanceMatrices;if(!r||r.length<16||typeof n.vertexAttribDivisor!="function"||typeof n.drawElementsInstanced!="function")return!1;let i=r.length>>4,s=e.instanceColors,o=new Float32Array(i*20);for(let a=0;a<i;a++)o.set(r.subarray(a*16,a*16+16),a*20),o[a*20+16]=s?s[a*3]:1,o[a*20+17]=s?s[a*3+1]:1,o[a*20+18]=s?s[a*3+2]:1,o[a*20+19]=1;let c=n.createBuffer();t.push(c),n.bindBuffer(34962,c),n.bufferData(34962,o,35044);for(let a=0;a<5;a++)n.enableVertexAttribArray(8+a),n.vertexAttribPointer(8+a,4,5126,!1,80,a*16),n.vertexAttribDivisor(8+a,1);return!0}function 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 nt(n,e){e.indices?n.drawElements(4,e.indexCount,e.indexType,0):n.drawArrays(4,0,e.indexCount)}function Hn(n,e){let t=n?.pbrMetallicRoughness,r=t?.baseColorFactor,i=n?.extensions?.KHR_materials_clearcoat,s=o=>o!==void 0&&e[o.index]?e[o.index]:null;return{baseColor:r?[r[0],r[1],r[2],r[3]??1]:[.8,.8,.8,1],metallic:t?.metallicFactor??.1,roughness:t?.roughnessFactor??.5,clearcoat:i?i.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,i?.clearcoatRoughnessFactor??.04),texture:s(t?.baseColorTexture),metallicRoughnessTexture:s(t?.metallicRoughnessTexture),normalTexture:s(n?.normalTexture),normalScale:n?.normalTexture?.scale??1,occlusionTexture:s(n?.occlusionTexture),occlusionStrength:n?.occlusionTexture?.strength??1,isTransmissive:(n?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function Gn(n,e,t){let r=new Set,i=s=>{s&&!r.has(s)&&(r.add(s),n.deleteTexture(s))};for(let s of e)for(let o of s.primitives){if(o.vao&&n.deleteVertexArray(o.vao),o.buffers)for(let a of o.buffers)n.deleteBuffer(a);i(o.texture),i(o.metallicRoughnessTexture),i(o.normalTexture),i(o.occlusionTexture);let c=new Set;o.customProgram&&c.add(o.customProgram);for(let a of o.programCache?.values()??[])a.program&&c.add(a.program);for(let a of c)n.deleteProgram(a)}if(t)for(let s of t)i(s)}function In(n,e,t=zn,r){let i={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return Fr(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 Fr(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=ke("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((x,I)=>{u.push(typeof x?.name=="string"&&x.name?x.name:`Variant_${I}`)});let m=tt(s),h=[];if(Array.isArray(s.nodes))for(let x=0;x<s.nodes.length;x++){let I=s.nodes[x];I.mesh!==void 0&&s.meshes&&s.meshes[I.mesh]&&h.push({node:I,nodeIdx:x,meshIdx:I.mesh})}let y=h.length>0?h:(s.meshes||[]).map((x,I)=>({node:x,nodeIdx:-1,meshIdx:I})),b=[];if(Array.isArray(e.lights)&&e.lights.length>0)b.push(...e.lights);else if(s.extensions?.KHR_lights_punctual?.lights){let x=s.extensions.KHR_lights_punctual.lights;for(let I of x){let S=I.type==="directional"?"directional":I.type==="point"?"point":"ambient";b.push({type:S,color:I.color||[1,1,1],intensity:I.intensity!==void 0?I.intensity:1})}}if(b.length===0&&(b.push({type:"ambient",color:[1,1,1],intensity:.35}),b.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),y.length>t.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${t.maxMeshes}). Found: ${y.length}`);let d=[];if(i.gpuTextures=d,s.textures&&s.images){if(s.textures.length>t.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${t.maxTextures}). Found: ${s.textures.length}`);for(let x=0;x<s.textures.length;x++){let I=s.textures[x],S=s.images[I.source];if(S){let C=n.createTexture();if(n.bindTexture(3553,C),n.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),n.texParameteri(3553,10242,10497),n.texParameteri(3553,10243,10497),n.texParameteri(3553,10241,9729),n.texParameteri(3553,10240,9729),S.bufferView!==void 0){let F=s.bufferViews[S.bufferView],N=c.slice(F.byteOffset||0,(F.byteOffset||0)+F.byteLength),V=new Blob([N],{type:S.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(V).then(U=>{n.bindTexture(3553,C),n.texImage2D(3553,0,6408,6408,5121,U),n.generateMipmap(3553),r?.()}).catch(()=>{})}else if(S.uri){let F=Ir(S.uri);if(F){let N=new Image;N.crossOrigin="anonymous",N.referrerPolicy="no-referrer",N.onload=()=>{n.bindTexture(3553,C),n.texImage2D(3553,0,6408,6408,5121,N),n.generateMipmap(3553),r?.()},N.src=F}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",S.uri)}d.push(C)}else d.push(null)}}let g=[1/0,1/0,1/0],T=[-1/0,-1/0,-1/0],P=0,f=0;for(let x=0;x<y.length;x++){let I=y[x],S=s.meshes[I.meshIdx],C=I.nodeIdx>=0?m[I.nodeIdx]:oe(),F=new Float32Array(9);ye(F,C);let N={name:I.node.name||S.name||`Mesh_${I.meshIdx}`,nodeIndex:I.nodeIdx,transform:C,normalMatrix:F,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,ie=ne=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${ne})`),null);if(Y!==5120&&Y!==5121&&Y!==5122&&Y!==5123&&Y!==5126)return ie(`componentType ${Y}`);if(!(Number(q.count)>=O))return ie(`count ${q.count} < ${O}`);let $=null;try{$=It(s,c,{...q,count:O},Z)}catch{return ie("out of bounds")}return!$||!$.every(Number.isFinite)?ie("non-finite value"):$},E=X(B,3),k=X(D,4),G=X(H,3),W=z?.type==="VEC4"?4:3,j=X(z,W),re=new Float32Array(O*16),ue=oe();for(let q=0;q<O;q++){let Z=E?[E[q*3],E[q*3+1],E[q*3+2]]:[0,0,0],Y=k?[k[q*4],k[q*4+1],k[q*4+2],k[q*4+3]]:[0,0,0,1],ie=G?[G[q*3],G[q*3+1],G[q*3+2]]:[1,1,1];Ce(ue,Y,Z,ie),re.set(ue,q*16)}if(N.instanceMatrices=re,j){let q=new Float32Array(O*3);for(let Z=0;Z<O;Z++)q[Z*3]=j[Z*W],q[Z*3+1]=j[Z*W+1],q[Z*3+2]=j[Z*W+2];N.instanceColors=q}}}for(let U of S.primitives||[]){if(U.extensions?.KHR_draco_mesh_compression){let $=ke("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 $=ne=>{for(let te=0;te<3;te++){let ee=ne[12+te],se=ne[12+te];for(let be=0;be<3;be++){let me=ne[be*4+te]*z.min[be],fe=ne[be*4+te]*z.max[be];ee+=me<fe?me:fe,se+=me>fe?me:fe}ee<g[te]&&(g[te]=ee),se>T[te]&&(T[te]=se)}};if(N.instanceMatrices&&N.instanceMatrices.length>=16){let ne=N.instanceMatrices.length>>4,te=oe();for(let ee=0;ee<ne;ee++){let se=N.instanceMatrices.subarray(ee*16,ee*16+16);ae(te,C,se),$(te)}}else $(C)}let X=Pt(n,s,c,U.attributes.POSITION,0,3,B);Pt(n,s,c,U.attributes.NORMAL,1,3,B),Pt(n,s,c,U.attributes.TEXCOORD_0,2,2,B,Nr(s,U));let E=0,k=5123,G=null;if(U.indices!==void 0){let $=s.accessors[U.indices],te=(s.bufferViews[$.bufferView].byteOffset||0)+($.byteOffset||0);if(E=Number($.count??0),!Number.isFinite(E)||E<0||f+E>t.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${t.maxIndices}).`);f+=E,k=$.componentType===5125?5125||5125:5123||5123;let ee=n.createBuffer();B.push(ee),n.bindBuffer(34963,ee),$.componentType===5125?(G=new Uint32Array(c,te,$.count),n.bufferData(34963,G,35044)):$.componentType===5121?(G=Uint16Array.from(new Uint8Array(c,te,$.count)),n.bufferData(34963,G,35044)):(G=te%2===0?new Uint16Array(c,te,$.count):new Uint16Array(c.slice(te,te+$.count*2)),n.bufferData(34963,G,35044))}else E=z.count;let W={};for(let $ of ce)if($.onBuildPrimitiveVAO){let ne=$.onBuildPrimitiveVAO(n,D,U,s,c);ne&&(W[$.name]=ne)}n.bindVertexArray(null);let j=s.materials&&U.material!==void 0?s.materials[U.material]:null,{program:re,uniforms:ue}=Bn(n,U,j),q=Hn(j,d),Z=!!(j?.extensions?.KHR_materials_transmission||W.materials?.isTransmissive),Y=U.extensions?.KHR_materials_variants?.mappings,ie=Array.isArray(Y)?Y.filter($=>$&&typeof $.material=="number"&&Array.isArray($.variants)).map($=>({material:$.material|0,variants:$.variants.map(ne=>Number(ne)|0)})):void 0;N.primitives.push({vao:D,instanced:H,indexCount:E,indexType:k,...q,positions:X,indices:G,buffers:B,materialIndex:U.material,defaultMaterialIndex:U.material,variantMappings:ie,primitiveDef:U,programCache:new Map([[U.material??-1,{program:re,uniforms:ue}]]),pluginData:W,customProgram:re,customUniforms:ue,isTransmissive:Z})}a.push(N)}isFinite(g[0])||(g=[-1,-1,-1]),isFinite(T[0])||(T=[1,1,1]);let R=[(g[0]+T[0])/2,(g[1]+T[1])/2,(g[2]+T[2])/2],p=T[0]-g[0],M=T[1]-g[1],_=T[2]-g[2],w=Math.max(Math.hypot(p,M,_)/2,.5),A=[g[0],g[1],g[2]],L=[T[0],T[1],T[2]],v=e.animations;if(!v){for(let x of ce)if(x.onParseGLB?.(e),e.animations){v=e.animations;break}}return v||(v=[]),{meshes:a,bounds:{center:R,radius:w,min:A,max:L},lights:b,animations:v,worldMatrices:m,gpuTextures:d,availableVariants:u}}function $e(n){let e=n.customTarget||n.bounds.center,t=n.currDistance*Math.cos(n.currPhi);return[e[0]+t*Math.sin(n.currTheta),e[1]+n.currDistance*Math.sin(n.currPhi),e[2]+t*Math.cos(n.currTheta)]}var de=class{constructor(e,t,r){this.meshes=[];this.backdropMeshes=[];this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]};this.lights=[];this.modelRootMatrix=oe();this.clearColor=[0,0,0,0];this.envIntensity=1;this.exposure=1;this.shadowIntensity=0;this.shadowSoftness=.5;this.toneMapping="neutral";this.environmentTexture=null;this.animations=[];this.currentClip=null;this.animationTime=0;this.isPlayingAnimation=!1;this.autoplay=!1;this.animationName="";this.gpuTextures=[];this.availableVariants=[];this.activeVariantName=null;this.gltf=null;this.worldMatrices=[];this.initialNodeTransforms=[];this.projMatrix=oe();this.viewMatrix=oe();this.activeViewMatrix=null;this.modelMatrix=oe();this.mvpMatrix=oe();this.normalMatrix=new Float32Array(9);this.initialTheta=.6;this.initialPhi=.35;this.initialDistance=null;this.customDistance=!1;this.distanceMode="auto";this.initialCustomTarget=null;this.customTarget=null;this.fov=Math.PI/4;this.minTheta=-1/0;this.maxTheta=1/0;this.minPhi=-Math.PI*.48;this.maxPhi=Math.PI*.48;this.minDistanceLimit=null;this.maxDistanceLimit=null;this.activePointers=new Map;this.isPanning=!1;this.targetTheta=.6;this.currTheta=.6;this.targetPhi=.35;this.currPhi=.35;this.targetDistance=3;this.currDistance=3;this.autoRotate=!1;this.autoRotateSpeed=Math.PI/6;this.autoRotateDelay=3e3;this.lastInteractionTime=-1/0;this.turntableRotation=0;this.isPointerDown=!1;this.interactive=!0;this.skyboxTexture=null;this.lastPointerX=0;this.lastPointerY=0;this.totalDragDist=0;this.selectedMeshName="";this.pickFbo=null;this.pickTexture=null;this.pickDepth=null;this.pickFboWidth=0;this.pickFboHeight=0;this.animFrameId=null;this.isVisible=!0;this.xrSessionActive=!1;this.lastTime=0;this.lastReportedTheta=-999;this.lastReportedPhi=-999;this.lastReportedZoom=-999;this.boundPointerDown=null;this.boundPointerMove=null;this.boundPointerUp=null;this.boundWheel=null;this.boundKeyDown=null;this.boundContextMenu=null;this.boundSetCamera=null;this.boundResetCamera=null;this.contextLost=!1;this.lastGlbData=null;this.boundContextLost=null;this.boundContextRestored=null;this.stereoSBS=!1;this.renderErrorReported=!1;this.xrDepthState={enabled:!1,texture:null,uvTransform:oe(),rawValueToMeters:.001,format:0};this.container=e;let i,s;if(t&&typeof t.getContext=="function"?(i=t,s=r):(s=t,i=s?.canvas),!i){let a=e.querySelector("canvas");a||(a=document.createElement("canvas"),a.style.width="100%",a.style.height="100%",a.style.display="block",a.style.touchAction="none",e.prepend(a)),i=a}this.canvas=i,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let o=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!o:o&&(this.autoRotate=!1),this.opts.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=this.opts.autoRotateSpeed),this.opts.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(this.opts.autoRotateDelay)||0)),this.opts.exposure!==void 0&&(this.exposure=Nt(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 ke(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=Ft(e,kn,t.fs),this.pickProg=Ft(e,Lr,Dr),this.uRender=kt(e,this.renderProg,t.uniforms),this.uPick=kt(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of ce)t.onContextRestored?.(e,this);this.meshes=[],this.gpuTextures=[],this.environmentTexture=null,this.lastGlbData&&this.loadGLBData(this.lastGlbData,this.lastLimits),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}setupPickingFbo(){let e=this.gl;if(typeof e.createFramebuffer!="function")return;this.pickFbo=e.createFramebuffer(),this.pickTexture=e.createTexture(),this.pickDepth=e.createRenderbuffer();let t=Math.max(1,this.canvas.width),r=Math.max(1,this.canvas.height);this.pickFboWidth=t,this.pickFboHeight=r,e.bindTexture(3553,this.pickTexture),e.texImage2D(3553,0,6408,t,r,0,6408,5121,null),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728),e.bindRenderbuffer(36161,this.pickDepth),e.renderbufferStorage(36161,33189,t,r),e.bindFramebuffer(36160,this.pickFbo),e.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),e.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),e.bindFramebuffer(36160,null)}resizePickingFbo(e,t){if(!this.pickFbo)return;let r=this.gl,i=Math.max(1,e),s=Math.max(1,t);this.pickFboWidth=i,this.pickFboHeight=s,r.bindTexture(3553,this.pickTexture),r.texImage2D(3553,0,6408,i,s,0,6408,5121,null),r.bindRenderbuffer(36161,this.pickDepth),r.renderbufferStorage(36161,33189,i,s)}loadGLBData(e,t){this.lastGlbData=e,this.lastLimits=t;let{meshes:r,bounds:i,lights:s,animations:o,worldMatrices:c,gpuTextures:a,availableVariants:u}=In(this.gl,e,t,()=>this.render());if(this.disposeMeshGpuResources(),this.meshes=r,this.bounds=i,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=s,this.animations=o||[],this.worldMatrices=c||[],this.gpuTextures=a||[],this.availableVariants=u||[],this.gltf=e.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let h of e.gltf.nodes)this.initialNodeTransforms.push({t:h.translation?[h.translation[0],h.translation[1],h.translation[2]]:[0,0,0],r:h.rotation?[h.rotation[0],h.rotation[1],h.rotation[2],h.rotation[3]]:[0,0,0,1],s:h.scale?[h.scale[0],h.scale[1],h.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let h of ce)h.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:i.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let l=e.exposure??e.gltf?.extras?.exposure??e.gltf?.asset?.extras?.exposure;l!==void 0&&(this.exposure=Nt(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(Fn(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(Ae(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=Ae(e),{meshes:i}=In(this.gl,r,zn,()=>this.render());if(t)for(let s of i)s.transform[12]+=t[0],s.transform[13]+=t[1],s.transform[14]+=t[2],ye(s.normalMatrix,s.transform);this.backdropMeshes=i,this.update(0),this.render()}setClearColor(e,t,r,i=1){this.clearColor=[e,t,r,i]}updateMeshTransforms(e){for(let t=0;t<this.meshes.length;t++){let r=this.meshes[t],i;e instanceof Map?i=e.get(r.name)??e.get(t):Array.isArray(e)?i=e[t]:e&&typeof e=="object"&&(Object.prototype.hasOwnProperty.call(e,r.name)?i=e[r.name]:Object.prototype.hasOwnProperty.call(e,t)&&(i=e[t])),i&&i.length===16&&(r.transform.set(i),ye(r.normalMatrix,r.transform))}}bindLights(e=this.uRender){let t=this.gl,r=[.28,.28,.28],i=[],s=[],o=[],c=[];for(let a of this.lights){let u=a.color||[1,1,1],l=a.intensity!==void 0?a.intensity:1;if(a.type==="ambient")r=[u[0]*l,u[1]*l,u[2]*l];else if(a.type==="directional"&&i.length<6){let m=a.direction||[.5,1,.8];i.push(m[0],m[1],m[2]),s.push(u[0]*l,u[1]*l,u[2]*l)}else if(a.type==="point"&&o.length<6){let m=a.position||[0,0,0];o.push(m[0],m[1],m[2]),c.push(u[0]*l,u[1]*l,u[2]*l)}}i.length===0&&(i.push(.5,1,.8),s.push(1,1,1)),t.uniform3fv(e.uAmbientColor,r),t.uniform1i(e.uNumDirLights,i.length/3),i.length>0&&(t.uniform3fv(e.uDirLightDir,i),t.uniform3fv(e.uDirLightColor,s)),t.uniform1i(e.uNumPointLights,o.length/3),o.length>0&&(t.uniform3fv(e.uPointLightPos,o),t.uniform3fv(e.uPointLightColor,c)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=Nt(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 ce)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of ce)if(t.setSkyboxImage){await t.setSkyboxImage(this,e);return}}setInteractive(e){this.interactive=e}isInteractive(){return this.interactive}getCameraOrbit(){let e=this.currTheta,t=this.currPhi,r=this.currDistance;return{theta:e,phi:t,radius:r,toString(){return`${e.toFixed(4)}rad ${t.toFixed(4)}rad ${r.toFixed(4)}m`}}}getCameraTarget(){let e=this.customTarget||this.bounds.center;return{x:e[0],y:e[1],z:e[2],toString(){return`${e[0].toFixed(4)}m ${e[1].toFixed(4)}m ${e[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let e=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return e.map((t,r)=>{let i=this.meshes.flatMap(l=>l.primitives.filter(m=>m.materialIndex===r||e.length===1&&m.materialIndex===void 0)),s=i[0],o=s?[...s.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],c=s?s.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,a=s?s.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,u={baseColorFactor:o,metallicFactor:c,roughnessFactor:a,setBaseColorFactor:l=>{let m=[l[0],l[1],l[2],l[3]??1];u.baseColorFactor=m,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=m);for(let h of i)h.baseColor=m;this.render()},setMetallicFactor:l=>{u.metallicFactor=l,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=l);for(let m of i)m.metallic=l;this.render()},setRoughnessFactor:l=>{u.roughnessFactor=l,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=l);for(let m of i)m.roughness=l;this.render()}};return{name:t.name||`Material_${r}`,pbrMetallicRoughness:u}})}playAnimation(e){if(this.animations.length!==0){if(e){let t=this.animations.find(r=>r.name===e);t&&(this.currentClip=t)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(e=>e.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(e){let t=this.applyVariantMaterial(e);return t&&this.gl&&this.render(),t}applyVariantMaterial(e){let t=e===null||e==="",r=-1;if(t)this.activeVariantName=null;else{if(r=this.availableVariants.indexOf(e),r<0)return!1;this.activeVariantName=e}let i=this.gltf?.materials;if(!Array.isArray(i))return t;for(let s of this.meshes)for(let o of s.primitives){let c=o.defaultMaterialIndex;if(!t&&Array.isArray(o.variantMappings)){for(let u of o.variantMappings)if(Array.isArray(u.variants)&&u.variants.includes(r)){c=u.material;break}}let a=c!==void 0?i[c]:void 0;o.materialIndex=a?c:void 0,Object.assign(o,Hn(a,this.gpuTextures)),this.applyPrimitiveProgram(o,o.materialIndex,a??null)}return!0}applyPrimitiveProgram(e,t,r){if(!this.gl||!e.primitiveDef)return;e.programCache??(e.programCache=new Map);let i=t??-1,s=e.programCache.get(i);s||(s=Bn(this.gl,{...e.primitiveDef,material:t},r),e.programCache.set(i,s)),e.customProgram=s.program,e.customUniforms=s.uniforms,e.pluginData&&(e.pluginData.materials=e.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(e){this.autoplay=e,e?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(e){this.animationName=e,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(e)}evaluateAnimation(e){for(let t of ce)if(t.evaluateAnimation){t.evaluateAnimation(this,e);return}}setTarget(e,t,r){this.customTarget=[e,t,r],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(e){let t=Math.max(10,Math.min(90,e));this.fov=t*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(e){if(this.distanceMode=e,!this.customDistance){let t=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=t,this.targetDistance=t,this.currDistance=t,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(e){e.minTheta!==void 0&&(this.minTheta=e.minTheta*Math.PI/180),e.maxTheta!==void 0&&(this.maxTheta=e.maxTheta*Math.PI/180),e.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,e.minPhi*Math.PI/180)),e.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,e.maxPhi*Math.PI/180)),e.minDistance!==void 0&&(this.minDistanceLimit=e.minDistance),e.maxDistance!==void 0&&(this.maxDistanceLimit=e.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){return{minTheta:isFinite(this.minTheta)?this.minTheta*180/Math.PI:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*180/Math.PI:void 0,minPhi:this.minPhi*180/Math.PI,maxPhi:this.maxPhi*180/Math.PI,minDistance:this.minDistanceLimit!==null?this.minDistanceLimit:void 0,maxDistance:this.maxDistanceLimit!==null?this.maxDistanceLimit:void 0}}clampTheta(e){return Math.max(this.minTheta,Math.min(this.maxTheta,e))}clampPhi(e){return Math.max(this.minPhi,Math.min(this.maxPhi,e))}clampDistance(e){let t=this.minDistanceLimit!==null?this.minDistanceLimit:this.bounds?this.bounds.radius*.5:.1,r=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(t,Math.min(r,e))}setCamera(e,t,r,i){e!==void 0&&(this.targetTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.targetPhi=this.clampPhi(t*Math.PI/180)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(r)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/i))}setInitialCamera(e,t,r,i){if(e!==void 0&&(this.initialTheta=this.clampTheta(e*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),t!==void 0&&(this.initialPhi=this.clampPhi(t*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),r!==void 0&&r>0){let s=this.clampDistance(r);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else if(i!==void 0&&i>0){let s=this.clampDistance(this.bounds.radius*2.5/i);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else{this.customDistance=!1;let s=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=s,this.targetDistance=s,this.currDistance=s}this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.initialDistance!==null?this.targetDistance=this.clampDistance(this.initialDistance):this.targetDistance=this.clampDistance(this.bounds.radius*2.5),this.initialCustomTarget?this.customTarget=[...this.initialCustomTarget]:this.customTarget=null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(e,t){let r=oe();ae(r,this.projMatrix,this.viewMatrix);let[i,s,o]=e,c=t?t[0]:0,a=t?t[1]:0,u=t?t[2]:0,l=this.modelRootMatrix;l&&(i=l[0]*e[0]+l[4]*e[1]+l[8]*e[2]+l[12],s=l[1]*e[0]+l[5]*e[1]+l[9]*e[2]+l[13],o=l[2]*e[0]+l[6]*e[1]+l[10]*e[2]+l[14],t&&(c=l[0]*t[0]+l[4]*t[1]+l[8]*t[2],a=l[1]*t[0]+l[5]*t[1]+l[9]*t[2],u=l[2]*t[0]+l[6]*t[1]+l[10]*t[2]));let m=r[0]*i+r[4]*s+r[8]*o+r[12],h=r[1]*i+r[5]*s+r[9]*o+r[13],y=r[2]*i+r[6]*s+r[10]*o+r[14],b=r[3]*i+r[7]*s+r[11]*o+r[15];if(b<=1e-4)return{x:0,y:0,z:1,visible:!1};let d=m/b,g=h/b,T=y/b,P=this.canvas.getBoundingClientRect(),f=P.width||this.canvas.clientWidth||this.canvas.width||300,R=P.height||this.canvas.clientHeight||this.canvas.height||150,p=(d*.5+.5)*f,M=(-g*.5+.5)*R,_=d>=-1.1&&d<=1.1&&g>=-1.1&&g<=1.1&&T>=-1&&T<=1;if(_&&t){let[w,A,L]=$e(this),v=[i-w,s-A,o-L];c*v[0]+a*v[1]+u*v[2]>.05&&(_=!1)}return{x:p,y:M,z:T,visible:_}}setSelectedMesh(e){this.selectedMeshName=e||""}getSelectedMesh(){return this.selectedMeshName}setupEvents(){let e=this.canvas;this.boundContextMenu=t=>{t.preventDefault()},e.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=t=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.lastPointerX=t.clientX,this.lastPointerY=t.clientY,this.totalDragDist=0,this.activePointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.isPanning=t.button===2||t.shiftKey||this.activePointers.size===2,e.setPointerCapture(t.pointerId))},e.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=t=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=this.activePointers.get(t.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},i=t.clientX-r.x,s=t.clientY-r.y;if(this.activePointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.lastPointerX=t.clientX,this.lastPointerY=t.clientY,this.totalDragDist+=Math.hypot(i,s),this.isPanning||t.button===2||t.shiftKey||this.activePointers.size===2){let o=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],c=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],a=this.customTarget?[...this.customTarget]:[...this.bounds.center],u=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;a[0]+=(-i*o[0]+s*c[0])*u,a[1]+=(-i*o[1]+s*c[1])*u,a[2]+=(-i*o[2]+s*c[2])*u,this.customTarget=a}else this.targetTheta=this.clampTheta(this.targetTheta-i*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=t=>{this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.activePointers.delete(t.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(t.pointerId)}catch{}if(this.totalDragDist<5&&t.button===0){let r=e.getBoundingClientRect(),i=Math.floor((t.clientX-r.left)*(e.width/Math.max(r.width,1))),s=Math.floor((t.clientY-r.top)*(e.height/Math.max(r.height,1)));this.performMeshPick(i,s,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=t=>{if(!this.interactive)return;t.preventDefault(),this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=Math.exp(t.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=t=>{let r=t.detail||{};r.reset?this.resetCamera():this.setCamera(r.theta,r.phi,r.distance,r.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),e.tabIndex!==void 0&&e.tabIndex<0&&(e.tabIndex=0),e.getAttribute?.("role")||e.setAttribute?.("role","region"),e.getAttribute?.("aria-label")||e.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=t=>{if(!this.interactive)return;let r=typeof performance<"u"?performance.now():Date.now();switch(t.key){case"ArrowLeft":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta-.1),t.preventDefault();break;case"ArrowRight":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta+.1),t.preventDefault();break;case"ArrowUp":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi+.08),t.preventDefault();break;case"ArrowDown":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi-.08),t.preventDefault();break;case"+":case"=":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*.9),t.preventDefault();break}case"-":case"_":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*1.1),t.preventDefault();break}case"Home":this.lastInteractionTime=r,this.resetCamera(),t.preventDefault();break}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=this.canvas;this.boundContextLost&&(e.removeEventListener("webglcontextlost",this.boundContextLost),this.boundContextLost=null),this.boundContextRestored&&(e.removeEventListener("webglcontextrestored",this.boundContextRestored),this.boundContextRestored=null),this.boundContextMenu&&(e.removeEventListener("contextmenu",this.boundContextMenu),this.boundContextMenu=null),this.boundPointerDown&&(e.removeEventListener("pointerdown",this.boundPointerDown),this.boundPointerDown=null),this.boundPointerMove&&(e.removeEventListener("pointermove",this.boundPointerMove),this.boundPointerMove=null),this.boundPointerUp&&(e.removeEventListener("pointerup",this.boundPointerUp),this.boundPointerUp=null),this.boundWheel&&(e.removeEventListener("wheel",this.boundWheel),this.boundWheel=null),this.boundKeyDown&&(e.removeEventListener("keydown",this.boundKeyDown),this.boundKeyDown=null),this.boundSetCamera&&(this.container.removeEventListener("setCamera",this.boundSetCamera),this.boundSetCamera=null),this.boundResetCamera&&(this.container.removeEventListener("resetCamera",this.boundResetCamera),this.boundResetCamera=null)}raycastFromScreenPoint(e,t){let r=this.canvas,i=r.getBoundingClientRect(),s=r.width||300,o=r.height||300,c=i.width>0?Math.floor((e-i.left)*(s/i.width)):Math.floor(e),a=i.height>0?Math.floor((t-i.top)*(o/i.height)):Math.floor(t);return this.performMeshPick(c,a,!1)}performMeshPick(e,t,r=!0){if(this.meshes.length===0)return null;let i=this.gl,s=Math.max(1,this.canvas.width||300),o=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,s);let c=oe();ae(c,this.projMatrix,this.viewMatrix);let a=[],u=Math.max(0,Math.min(s-1,e)),l=Math.max(0,Math.min(o-1,o-1-t));if(this.pickFbo&&i&&!this.xrSessionActive){(this.pickFboWidth!==s||this.pickFboHeight!==o)&&this.resizePickingFbo(s,o),i.bindFramebuffer(36160,this.pickFbo),i.viewport(0,0,s,o),i.enable(2929),i.clearColor(0,0,0,0),i.clear(16384|256),i.useProgram(this.pickProg);for(let _=0;_<this.meshes.length;_++){let w=this.meshes[_];if(w.visible===!1||w.isPluginMesh)continue;let A=_+1,L=(A&255)/255,v=(A>>8&255)/255,x=(A>>16&255)/255;i.uniform4f(this.uPick.uColorId,L,v,x,1),ae(this.modelMatrix,this.modelRootMatrix,w.transform);let I=w.instanceMatrices;if(I&&I.length>=16){let S=I.length>>4,C=oe();for(let F of w.primitives){i.bindVertexArray(F.vao);for(let N=0;N<S;N++)ae(C,this.modelMatrix,I.subarray(N*16,N*16+16)),ae(this.mvpMatrix,c,C),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),nt(i,F)}}else{ae(this.mvpMatrix,c,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let S of w.primitives)i.bindVertexArray(S.vao),nt(i,S)}}let p=new Uint8Array(4);i.readPixels(u,l,1,1,6408,5121,p),i.bindFramebuffer(36160,null);let M=p[0]+(p[1]<<8)+(p[2]<<16);M>0&&M<=this.meshes.length&&(a=[this.meshes[M-1]])}a.length===0&&(a=this.meshes.filter(p=>p.visible!==!1));let m=null,h=1/0,y=[0,0,0],b=[0,1,0],[d,g,T]=$e(this),P=oe();for(let p of a){ae(P,this.modelRootMatrix,p.transform);let M=p.instanceMatrices,_=M&&M.length>=16?M.length>>4:1;for(let w=0;w<_;w++){M&&M.length>=16?ae(this.modelMatrix,P,M.subarray(w*16,w*16+16)):this.modelMatrix.set(P),ae(this.mvpMatrix,c,this.modelMatrix);let A=oe();if(!Tn(A,this.mvpMatrix))continue;let L=(u+.5)/s*2-1,v=(l+.5)/o*2-1,x=[0,0,0],I=[0,0,0];Dt(x,L,v,-1,A),Dt(I,L,v,1,A);let S=I[0]-x[0],C=I[1]-x[1],F=I[2]-x[2],N=Math.hypot(S,C,F)||1,V=S/N,U=C/N,B=F/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,k=Math.floor(E?E.length/3:X.length/9);for(let G=0;G<k;G++){let W=E?E[G*3]:G*3,j=E?E[G*3+1]:G*3+1,re=E?E[G*3+2]:G*3+2;_n(x[0],x[1],x[2],V,U,B,X[W*3],X[W*3+1],X[W*3+2],X[j*3],X[j*3+1],X[j*3+2],X[re*3],X[re*3+1],X[re*3+2],D,z)}}})(1e-4),isFinite(D.distance)){let z=D.point[0],O=D.point[1],X=D.point[2],E=this.modelMatrix,k=E[0]*z+E[4]*O+E[8]*X+E[12],G=E[1]*z+E[5]*O+E[9]*X+E[13],W=E[2]*z+E[6]*O+E[10]*X+E[14],j=k-d,re=G-g,ue=W-T,q=Math.hypot(j,re,ue);if(q<h){ye(this.normalMatrix,this.modelMatrix);let Z=this.normalMatrix,Y=D.normal[0],ie=D.normal[1],$=D.normal[2],ne=Z[0]*Y+Z[3]*ie+Z[6]*$,te=Z[1]*Y+Z[4]*ie+Z[7]*$,ee=Z[2]*Y+Z[5]*ie+Z[8]*$,se=Math.hypot(ne,te,ee)||1;ne/=se,te/=se,ee/=se,ne*j+te*re+ee*ue>0&&(ne=-ne,te=-te,ee=-ee),m=p,h=Math.round(q*1e3)/1e3,y=[Math.round(k*1e3)/1e3,Math.round(G*1e3)/1e3,Math.round(W*1e3)/1e3],b=[Math.round(ne*1e3)/1e3,Math.round(te*1e3)/1e3,Math.round(ee*1e3)/1e3]}}}}if(!m)return null;let R={meshIndex:this.meshes.indexOf(m),meshName:m.name,nodeIndex:m.nodeIndex,distance:h,hitPoint:y,normal:b,screenX:e,screenY:t};if(r){for(let p of ce)p.onMeshSelect?.(this,R);this.opts.onMeshClick&&this.opts.onMeshClick(R),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:R}))}return R}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let r=Math.max(1,Math.floor(t*.5)),i=e>=r,s=i?e-r:e,o=i?Math.max(1,t-r):r,c=(s+.5)/o*2-1;return Math.floor((c*.5+1)*.5*t)}setStereoSBS(e){this.stereoSBS=!!e,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let e=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),t=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);et(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center;Fe(this.viewMatrix,$e(this),r,[0,1,0]),ae(this.mvpMatrix,this.projMatrix,this.viewMatrix),ye(this.normalMatrix,this.modelMatrix)}resize(){let e=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),t=this.canvas.getBoundingClientRect(),r=Math.max(1,Math.floor(t.width*e)),i=Math.max(1,Math.floor(t.height*e));this.canvas.width!==r||this.canvas.height!==i?(this.canvas.width=r,this.canvas.height=i,this.resizePickingFbo(r,i),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(e){let t=this.xrSessionActive;if(this.xrSessionActive=e,t&&!e){this.xrDepthState.enabled=!1;for(let r of ce)r.onXRSessionEnd?.(this);if(this.lastTime=typeof performance<"u"?performance.now():Date.now(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(r){this.reportRenderError(r)}}}reportRenderError(e){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",e))}stepXRUpdate(e){for(let t of ce)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let e=t=>{if(this.animFrameId===null)return;let r=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(r),this.render()}catch(i){this.reportRenderError(i)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(e))};this.animFrameId=requestAnimationFrame(e)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(e){this.autoRotate=e}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(e){this.autoRotateSpeed=e}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(e){this.autoRotateDelay=Math.max(0,Number(e)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(e=0){this.turntableRotation=Number(e)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let e=Math.cos(this.turntableRotation),t=Math.sin(this.turntableRotation),r=this.bounds.center[0],i=this.bounds.center[2],s=this.modelRootMatrix;s[0]=e,s[1]=0,s[2]=-t,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=t,s[9]=0,s[10]=e,s[11]=0,s[12]=r-(e*r+t*i),s[13]=0,s[14]=i-(-t*r+e*i),s[15]=1}setVisible(e){this.isVisible=e}update(e){for(let o of ce)o.onUpdate?.(this,e);let t=typeof performance<"u"?performance.now():Date.now();if(!this.isPointerDown&&this.autoRotate&&t-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*e,this.updateTurntableMatrix();for(let o of ce)o.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let r=Math.round((this.currTheta*180/Math.PI%360+360)%360),i=Math.round(this.currPhi*180/Math.PI),s=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(r-this.lastReportedTheta)>=1||Math.abs(i-this.lastReportedPhi)>=1||Math.abs(s-this.lastReportedZoom)>=.02){this.lastReportedTheta=r,this.lastReportedPhi=i,this.lastReportedZoom=s;let o={theta:r,phi:i,zoom:s,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(o),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:o}))}}renderXRView(e,t,r,i,s=!0,o=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let c=e?.transform?.inverse?.matrix||this.viewMatrix,a=e?.projectionMatrix||this.projMatrix,u=e?.transform?.position,l=u?[u.x,u.y,u.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):r&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:c,projMatrix:a,eyePos:l,viewport:i,eye:e?.eye||"none",clear:o>0?!1:e?.eye!=="right",isAR:s})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let f=Math.max(2,this.canvas.width||2),R=Math.max(1,this.canvas.height||1),p=Math.max(1,Math.floor(f*.5)),M=Math.max(1,f-p),_=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),w=this.customTarget||this.bounds.center,[A,L,v]=$e(this),x=Math.cos(this.currTheta),I=-Math.sin(this.currTheta),S=.032,C=oe(),F=oe(),N=[A-x*S,L,v-I*S],V=[w[0]-x*S*.25,w[1],w[2]-I*S*.25];et(C,this.fov,p/R,.1,_),Fe(F,N,V,[0,1,0]);let U=oe(),B=oe(),D=[A+x*S,L,v+I*S],H=[w[0]+x*S*.25,w[1],w[2]+I*S*.25];et(U,this.fov,M/R,.1,_),Fe(B,D,H,[0,1,0]),this.render({viewMatrix:F,projMatrix:C,eyePos:N,viewport:[0,0,p,R],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:B,projMatrix:U,eyePos:D,viewport:[p,0,M,R],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,f,R);return}let t=this.gl,r=0,i=0,s=this.canvas.width,o=this.canvas.height;e?.viewport?(r=e.viewport[0],i=e.viewport[1],s=e.viewport[2],o=e.viewport[3],t.viewport(r,i,s,o)):t.viewport(0,0,this.canvas.width,this.canvas.height),t.enable(2929),(!e||e.clear!==!1)&&(e?.isAR?t.clearColor(0,0,0,0):t.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),t.clear(16384|256));let c=oe(),a=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=a,ae(c,e?.projMatrix??this.projMatrix,a);let u=Q().xrDepthShader,l=Mr(this.toneMapping),[m,h,y]=e?e.eyePos:$e(this);for(let f of ce)f.onBeforeDrawScene?.(this,t,c,[m,h,y],l);let b=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&b===0)return;let d=e?.eye||"none",g=!1,T=b>0?[...this.backdropMeshes,...this.meshes]:this.meshes,P=f=>{for(let R=0;R<T.length;R++){let p=T[R];if(p.visible===!1)continue;let M=this.selectedMeshName!==""&&p.name===this.selectedMeshName;R<b||p.worldSpace===!0||p.name==="__xr_reticle__"?this.modelMatrix.set(p.transform):ae(this.modelMatrix,this.modelRootMatrix,p.transform),ae(this.mvpMatrix,c,this.modelMatrix),ye(p.normalMatrix,this.modelMatrix);let _=p.extras?.xr?.stereo||p.userData?.xr?.stereo,w=0,A=0,L=1,v=1;_==="sbs"?(L=.5,w=d==="right"?.5:0):_==="ou"&&(v=.5,A=d==="right"?.5:0);for(let x of p.primitives){let I=!!x.isTransmissive;if(!f&&I){g=!0;continue}if(f&&!I)continue;let S=x.customProgram||this.renderProg,C=x.customUniforms||this.uRender;t.useProgram(S),t.uniform1i(C.uToneMapping,l),t.uniform1f(C.uEnvIntensity,this.envIntensity),C.uExposure&&t.uniform1f(C.uExposure,this.exposure),t.uniform3f(C.uCameraPos,m,h,y),t.uniform1f(C.uEmissive,M?1:0),t.uniformMatrix4fv(C.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(C.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(C.uNormalMatrix,!1,p.normalMatrix),C.uUvTransform&&t.uniform4f(C.uUvTransform,w,A,L,v),C.uViewportSize&&t.uniform2f(C.uViewportSize,Math.max(1,s),Math.max(1,o)),u?.bind(t,C,this.xrDepthState,a,[r,i,Math.max(1,s),Math.max(1,o)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(C.uEnvironmentMap,4),t.uniform1i(C.uHasEnvironmentMap,1)):t.uniform1i(C.uHasEnvironmentMap,0),this.bindLights(C),C.uSectionEnabled&&t.uniform1i(C.uSectionEnabled,0);for(let N of ce)N.onBeforeDrawPrimitive?.(t,S,x,p,this.worldMatrices||[],this.gltf);t.uniform4fv(C.uBaseColor,x.baseColor),t.uniform1f(C.uMetallic,x.metallic),t.uniform1f(C.uRoughness,x.roughness),C.uClearcoat&&t.uniform2f(C.uClearcoat,x.clearcoat??0,x.clearcoatRoughness??.04),x.texture?(t.activeTexture(33984),t.bindTexture(3553,x.texture),t.uniform1i(C.uBaseColorTexture,0),t.uniform1i(C.uHasTexture,1)):t.uniform1i(C.uHasTexture,0),x.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,x.metallicRoughnessTexture),t.uniform1i(C.uMetallicRoughnessTexture,1),t.uniform1i(C.uHasMetallicRoughnessTexture,1)):t.uniform1i(C.uHasMetallicRoughnessTexture,0),x.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,x.normalTexture),t.uniform1i(C.uNormalTexture,2),t.uniform1i(C.uHasNormalTexture,1),t.uniform1f(C.uNormalScale,x.normalScale)):t.uniform1i(C.uHasNormalTexture,0),x.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,x.occlusionTexture),t.uniform1i(C.uOcclusionTexture,3),t.uniform1i(C.uHasOcclusionTexture,1),t.uniform1f(C.uOcclusionStrength,x.occlusionStrength)):t.uniform1i(C.uHasOcclusionTexture,0),t.bindVertexArray(x.vao);let F=p.instanceMatrices;if(F&&F.length>=16&&x.instanced&&C.uInstanced&&C.uViewProj){let N=F.length>>4;t.uniform1i(C.uInstanced,1),t.uniformMatrix4fv(C.uViewProj,!1,c),x.indices?t.drawElementsInstanced(4,x.indexCount,x.indexType,0,N):t.drawArraysInstanced(4,0,x.indexCount,N),t.uniform1i(C.uInstanced,0)}else if(F&&F.length>=16){let N=F.length>>4,V=p.instanceColors,U=oe(),B=new Float32Array(9),D=[x.baseColor[0],x.baseColor[1],x.baseColor[2],x.baseColor[3]];for(let H=0;H<N;H++)ae(U,this.modelMatrix,F.subarray(H*16,H*16+16)),ae(this.mvpMatrix,c,U),ye(B,U),t.uniformMatrix4fv(C.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(C.uModel,!1,U),t.uniformMatrix3fv(C.uNormalMatrix,!1,B),V&&(D[0]=x.baseColor[0]*V[H*3],D[1]=x.baseColor[1]*V[H*3+1],D[2]=x.baseColor[2]*V[H*3+2],D[3]=x.baseColor[3],t.uniform4fv(C.uBaseColor,D)),nt(t,x)}else nt(t,x)}}};if(P(!1),g){for(let f of ce)f.onBeforeTransmissivePass?.(t,this);P(!0)}for(let f of ce)f.onAfterRender?.(t,this,c)}disposeMeshListGpuResources(e,t){Gn(this.gl,e,t)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let e=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let t of ce)t.onDestroy?.(e,this);this.environmentTexture&&(e.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&e.deleteProgram(this.renderProg),this.pickProg&&e.deleteProgram(this.pickProg),this.pickFbo&&e.deleteFramebuffer(this.pickFbo),this.pickTexture&&e.deleteTexture(this.pickTexture),this.pickDepth&&e.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};de.registerPlugin=Ze,de.getRegisteredPlugins=Rn;function kr(n){return n+3&-4}function Ur(n,e=0){let t=(D,H)=>typeof D=="number"&&Number.isFinite(D)?D:H,r=t(n[e+12],0),i=t(n[e+13],0),s=t(n[e+14],0),o=t(n[e+0],1),c=t(n[e+1],0),a=t(n[e+2],0),u=t(n[e+4],0),l=t(n[e+5],1),m=t(n[e+6],0),h=t(n[e+8],0),y=t(n[e+9],0),b=t(n[e+10],1),d=Math.hypot(o,c,a),g=Math.hypot(u,l,m),T=Math.hypot(h,y,b);o*(l*b-y*m)-u*(c*b-y*a)+h*(c*m-l*a)<0&&(d=-d);let f=Math.abs(d)>1e-8?1/d:0,R=Math.abs(g)>1e-8?1/g:0,p=Math.abs(T)>1e-8?1/T:0,M=o*f,_=c*f,w=a*f,A=u*R,L=l*R,v=m*R,x=h*p,I=y*p,S=b*p,C=M+L+S,F=0,N=0,V=0,U=1;if(C>0){let D=.5/Math.sqrt(C+1);U=.25/D,F=(v-I)*D,N=(x-w)*D,V=(_-A)*D}else if(M>L&&M>S){let D=2*Math.sqrt(Math.max(0,1+M-L-S));D>1e-8&&(U=(v-I)/D,F=.25*D,N=(A+_)/D,V=(x+w)/D)}else if(L>S){let D=2*Math.sqrt(Math.max(0,1+L-M-S));D>1e-8&&(U=(x-w)/D,F=(A+_)/D,N=.25*D,V=(v+I)/D)}else{let D=2*Math.sqrt(Math.max(0,1+S-M-L));D>1e-8&&(U=(_-A)/D,F=(x+w)/D,N=(v+I)/D,V=.25*D)}let B=Math.hypot(F,N,V,U);return B>1e-8&&Number.isFinite(B)?(F/=B,N/=B,V/=B,U/=B):(F=0,N=0,V=0,U=1),{t:[r,i,s],r:[F,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=[],y=[];function b(A){let L=m.get(A);if(L!==void 0)return L;L=l.length,m.set(A,L);let v=A,x=v.color?.r??.8,I=v.color?.g??.8,S=v.color?.b??.8,C=v.opacity??1,F={name:v.name||"",pbrMetallicRoughness:{baseColorFactor:[x,I,S,C],metallicFactor:v.metalness??.1,roughnessFactor:v.roughness??.5},doubleSided:v.side===2||!!v.doubleSided};if(v.emissive&&(v.emissive.r>0||v.emissive.g>0||v.emissive.b>0)){let V=v.emissiveIntensity??1;F.emissiveFactor=[v.emissive.r*V,v.emissive.g*V,v.emissive.b*V]}let N={};return v.clearcoat&&v.clearcoat>0&&(N.KHR_materials_clearcoat={clearcoatFactor:v.clearcoat,clearcoatRoughnessFactor:v.clearcoatRoughness||0}),v.sheen&&v.sheen>0&&(N.KHR_materials_sheen={sheenColorFactor:v.sheenColor?[v.sheenColor.r,v.sheenColor.g,v.sheenColor.b]:[1,1,1],sheenRoughnessFactor:v.sheenRoughness||0}),v.transmission&&v.transmission>0&&(N.KHR_materials_transmission={transmissionFactor:v.transmission}),v.thickness&&v.thickness>0&&(N.KHR_materials_volume={thicknessFactor:v.thickness,attenuationDistance:v.attenuationDistance??1/0,attenuationColor:v.attenuationColor?[v.attenuationColor.r,v.attenuationColor.g,v.attenuationColor.b]:[1,1,1]}),v.ior!==void 0&&v.ior!==1.5&&(N.KHR_materials_ior={ior:v.ior}),v.dispersion&&v.dispersion>0&&(N.KHR_materials_dispersion={dispersion:v.dispersion}),v.iridescence&&v.iridescence>0&&(N.KHR_materials_iridescence={iridescenceFactor:v.iridescence,iridescenceIor:v.iridescenceIOR??1.3}),Object.keys(N).length>0&&(F.extensions=N),l.push(F),L}function d(A,L){let v=new Uint8Array(A.buffer,A.byteOffset,A.byteLength),x=kr(v.byteLength),I=new Uint8Array(x);I.set(v),t.push(I);let S=i.length;return i.push({buffer:0,byteOffset:r,byteLength:v.byteLength,target:L}),r+=x,S}function g(A,L,v,x,I,S,C){let F=d(A,v),N=s.length,V={bufferView:F,byteOffset:0,componentType:x,count:I,type:L};return S&&(V.min=S),C&&(V.max=C),s.push(V),N}n.traverse(A=>{(A.isLight||A.color&&A.intensity!==void 0)&&y.push({type:A.type,color:[A.color.r,A.color.g,A.color.b],intensity:A.intensity,position:[A.position.x,A.position.y,A.position.z]})});let T=[];function P(A){let L={name:A.name||""},v=A.position,x=A.quaternion,I=A.scale;if((v.x||v.y||v.z)&&(L.translation=[v.x,v.y,v.z]),(x.x||x.y||x.z||x.w!==1)&&(L.rotation=[x.x,x.y,x.z,x.w]),(I.x!==1||I.y!==1||I.z!==1)&&(L.scale=[I.x,I.y,I.z]),A.userData&&Object.keys(A.userData).length>0&&(L.extras=JSON.parse(JSON.stringify(A.userData,(C,F)=>{if(!(C==="__proto__"||C==="prototype"||C==="constructor"))return typeof F=="function"?void 0:F})),A.userData.xr)){let C=Or(A.userData.xr);L.extensions={...L.extensions||{},MOZ_hubs_components:C,ANDROID_xr_scenecore:C},Q().xrTraitSerializer?.gltfNode(L,A.userData.xr),a.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(A.geometry){let C=A.geometry,F=C.attributes.position;if(F&&F.count>0){let N=[1/0,1/0,1/0],V=[-1/0,-1/0,-1/0];for(let O=0;O<F.count;O++){let X=F.getX(O),E=F.getY(O),k=F.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),k<N[2]&&(N[2]=k),k>V[2]&&(V[2]=k)}let B={attributes:{POSITION:g(F.array,"VEC3",34962,5126,F.count,N,V)}};if(C.attributes.normal&&(B.attributes.NORMAL=g(C.attributes.normal.array,"VEC3",34962,5126,C.attributes.normal.count)),C.attributes.uv&&(B.attributes.TEXCOORD_0=g(C.attributes.uv.array,"VEC2",34962,5126,C.attributes.uv.count)),C.index){let O=C.index.array instanceof Uint32Array;B.indices=g(C.index.array,"SCALAR",34963,O?5125:5123,C.index.count)}A.material&&(B.material=b(A.material));let D=A.userData?.variants;if(D&&typeof D=="object"){let O=new Map;for(let X of Object.keys(D)){if(!X||X==="__proto__"||X==="constructor"||X==="prototype")continue;let E=D[X];if(!E||typeof E!="object")continue;let k=h.indexOf(X);if(k===-1&&h.length<256&&(k=h.length,h.push(X)),k===-1)continue;let G=b(E),W=O.get(G);W||(W=[],O.set(G,W)),W.push(k)}if(O.size>0){let X=[];for(let[E,k]of O.entries())X.push({material:E,variants:k});B.extensions={...B.extensions||{},KHR_materials_variants:{mappings:X}},a.add("KHR_materials_variants")}}let H=A;if(H.isInstancedMesh&&typeof H.count=="number"&&H.count>0&&H.instanceMatrix?.array){let O=Math.min(1e4,Math.floor(H.count)),X=H.instanceMatrix.array,E=new Float32Array(O*3),k=new Float32Array(O*4),G=new Float32Array(O*3);for(let j=0;j<O;j++){let{t:re,r:ue,s:q}=Ur(X,j*16);E[j*3]=re[0],E[j*3+1]=re[1],E[j*3+2]=re[2],k[j*4]=ue[0],k[j*4+1]=ue[1],k[j*4+2]=ue[2],k[j*4+3]=ue[3],G[j*3]=q[0],G[j*3+1]=q[1],G[j*3+2]=q[2]}let W={TRANSLATION:g(E,"VEC3",0,5126,O),ROTATION:g(k,"VEC4",0,5126,O),SCALE:g(G,"VEC3",0,5126,O)};if(H.instanceColor?.array&&H.instanceColor.array.length>=O*3){let j=new Float32Array(H.instanceColor.array.subarray(0,O*3));W._COLOR_0=g(j,"VEC3",0,5126,O)}L.extensions={...L.extensions||{},EXT_mesh_gpu_instancing:{attributes:W}},a.add("EXT_mesh_gpu_instancing")}let z=o.length;o.push({primitives:[B],name:A.name,...L.extras?{extras:L.extras}:{}}),L.mesh=z}}let S=c.length;if(c.push(L),u.push(A),A.children.length>0){L.children=[];for(let C of A.children)L.children.push(P(C))}return S}for(let A of n.children)T.push(P(A));let f=e?.animateCallback||e?.animateFn||(typeof n.userData?.animate=="function"?n.userData.animate:typeof n.__animateFn=="function"?n.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0),R=[];if(typeof f=="function"&&u.length>0){let A=e?.duration??4,L=e?.fps??15,v=Math.max(2,Math.round(A*L)+1),x=new Float32Array(v),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(v*3)),C=u.map(()=>new Float32Array(v*4)),F=u.map(()=>new Float32Array(v*3));for(let D=0;D<v;D++){let H=D/(v-1)*A;x[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,C[z][D*4]=O.quaternion.x,C[z][D*4+1]=O.quaternion.y,C[z][D*4+2]=O.quaternion.z,C[z][D*4+3]=O.quaternion.w,F[z][D*3]=O.scale.x,F[z][D*3+1]=O.scale.y,F[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(x,"SCALAR",0,5126,v,[0],[A])),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<v;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(C[D][E*4]-H.qx)>1e-4||Math.abs(C[D][E*4+1]-H.qy)>1e-4||Math.abs(C[D][E*4+2]-H.qz)>1e-4||Math.abs(C[D][E*4+3]-H.qw)>1e-4)&&(O=!0),(Math.abs(F[D][E*3]-H.sx)>1e-4||Math.abs(F[D][E*3+1]-H.sy)>1e-4||Math.abs(F[D][E*3+2]-H.sz)>1e-4)&&(X=!0);if(z){let E=g(S[D],"VEC3",0,5126,v),k=U.length;U.push({input:V(),interpolation:"LINEAR",output:E}),B.push({sampler:k,target:{node:D,path:"translation"}})}if(O){let E=g(C[D],"VEC4",0,5126,v),k=U.length;U.push({input:V(),interpolation:"LINEAR",output:E}),B.push({sampler:k,target:{node:D,path:"rotation"}})}if(X){let E=g(F[D],"VEC3",0,5126,v),k=U.length;U.push({input:V(),interpolation:"LINEAR",output:E}),B.push({sampler:k,target:{node:D,path:"scale"}})}}B.length>0&&R.push({name:"ProceduralLoop",samplers:U,channels:B})}let p=En(c,o,n.userData),M={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}],...R.length>0?{animations:R}:{},...p||a.size>0?{extensionsUsed:[...p?["KHR_interactivity"]:[],...a]}:{},...p||h.length>0?{extensions:{...p?{KHR_interactivity:p}:{},...h.length>0?{KHR_materials_variants:{variants:h.map(A=>({name:A}))}}:{}}}:{}},_=new Uint8Array(r),w=0;for(let A of t)_.set(A,w),w+=A.byteLength;return{gltf:M,bin:_.buffer,lights:y,environmentIntensity:n.environmentIntensity}}function it(n){return new TextEncoder().encode(n)}function st(n,e){let{gltf:t,bin:r}=Ye(n,e),i=JSON.stringify(t),s=it(i),o=(4-s.byteLength%4)%4,c=s.byteLength+o,a=20+c+8+r.byteLength,u=new Uint8Array(a),l=new DataView(u.buffer);l.setUint32(0,1179937895,!0),l.setUint32(4,2,!0),l.setUint32(8,a,!0),l.setUint32(12,c,!0),l.setUint32(16,1313821514,!0),u.set(s,20);for(let h=0;h<o;h++)u[20+s.byteLength+h]=32;let m=20+c;return l.setUint32(m,r.byteLength,!0),l.setUint32(m+4,5130562,!0),u.set(new Uint8Array(r),m+8),u}function Br(n,e){n.updateMatrixWorld(!0);let t=[];return n.traverse(r=>{if(r.geometry){let i=r.geometry,s=i.attributes.position;if(!s||s.count===0)return;let o=s.count,c=new Float32Array(o*3),a=r.matrixWorld.elements;for(let w=0;w<o;w++){let A=s.getX(w),L=s.getY(w),v=s.getZ(w);c[w*3]=a[0]*A+a[4]*L+a[8]*v+a[12],c[w*3+1]=a[1]*A+a[5]*L+a[9]*v+a[13],c[w*3+2]=a[2]*A+a[6]*L+a[10]*v+a[14]}let u;if(i.attributes.normal){let w=i.attributes.normal;u=new Float32Array(o*3);let A=new Float32Array(9);ye(A,a);for(let L=0;L<o;L++){let v=w.getX(L),x=w.getY(L),I=w.getZ(L),S=A[0]*v+A[3]*x+A[6]*I,C=A[1]*v+A[4]*x+A[7]*I,F=A[2]*v+A[5]*x+A[8]*I,N=Math.hypot(S,C,F)||1;u[L*3]=S/N,u[L*3+1]=C/N,u[L*3+2]=F/N}}let l;if(i.attributes.uv){let w=i.attributes.uv;l=new Float32Array(o*2);for(let A=0;A<o;A++)l[A*2]=w.getX(A),l[A*2+1]=w.getY(A)}let m;if(i.index)m=i.index.array;else{m=o>65535?new Uint32Array(o):new Uint16Array(o);for(let w=0;w<o;w++)m[w]=w}let h="DefaultMaterial",y=[.8,.8,.8],b=.5,d=.1,g=0,T=0,P=1.5,f=1,R=[0,0,0];if(r.material){let w=r.material;h=w.name||`Material_${t.length}`,w.color&&(y=[w.color.r,w.color.g,w.color.b]),typeof w.roughness=="number"&&(b=w.roughness),typeof w.metalness=="number"&&(d=w.metalness),typeof w.clearcoat=="number"&&(g=w.clearcoat),typeof w.clearcoatRoughness=="number"&&(T=w.clearcoatRoughness),typeof w.ior=="number"&&(P=w.ior);let A=typeof w.opacity=="number"?w.opacity:1,L=typeof w.transmission=="number"?w.transmission:0;if(f=A*(1-L),w.emissive&&(w.emissive.r>0||w.emissive.g>0||w.emissive.b>0)){let v=w.emissiveIntensity??1;R=[w.emissive.r*v,w.emissive.g*v,w.emissive.b*v]}}let p,M=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 M=="function"){let w=e?.duration??4,A=e?.fps??4,L=Math.max(2,Math.round(w*A)+1),v=[],x=[],I=[],S=[],C=[r.position.x,r.position.y,r.position.z],F=[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;v.push(B);try{M(B)}catch{}x.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-C[0])>1e-4||Math.abs(r.position.y-C[1])>1e-4||Math.abs(r.position.z-C[2])>1e-4||Math.abs(r.quaternion.x-F[0])>1e-4||Math.abs(r.quaternion.y-F[1])>1e-4||Math.abs(r.quaternion.z-F[2])>1e-4||Math.abs(r.quaternion.w-F[3])>1e-4||Math.abs(r.scale.x-N[0])>1e-4)&&(V=!0)}r.position.set(C[0],C[1],C[2]),r.quaternion.set(F[0],F[1],F[2],F[3]),r.scale.set(N[0],N[1],N[2]),V&&(p={times:v,translations:x,rotations:I,scales:S})}let _=r;if(_.isInstancedMesh&&typeof _.count=="number"&&_.count>0&&_.instanceMatrix?.array){let w=Math.min(1e3,Math.floor(_.count)),A=_.instanceMatrix.array,L=_.instanceColor?.array,v=r.name||`Mesh_${t.length}`,x=new Float32Array(16),I=new Float32Array(9);for(let S=0;S<w;S++){let C=A.subarray(S*16,(S+1)*16);ae(x,a,C);let F=new Float32Array(o*3);for(let B=0;B<o;B++){let D=s.getX(B),H=s.getY(B),z=s.getZ(B);F[B*3]=x[0]*D+x[4]*H+x[8]*z+x[12],F[B*3+1]=x[1]*D+x[5]*H+x[9]*z+x[13],F[B*3+2]=x[2]*D+x[6]*H+x[10]*z+x[14]}let N;if(i.attributes.normal){let B=i.attributes.normal;N=new Float32Array(o*3),ye(I,x);for(let D=0;D<o;D++){let H=B.getX(D),z=B.getY(D),O=B.getZ(D),X=I[0]*H+I[3]*z+I[6]*O,E=I[1]*H+I[4]*z+I[7]*O,k=I[2]*H+I[5]*z+I[8]*O,G=Math.hypot(X,E,k)||1;N[D*3]=X/G,N[D*3+1]=E/G,N[D*3+2]=k/G}}let V=y,U=h;L&&L.length>=(S+1)*3&&(V=[y[0]*L[S*3],y[1]*L[S*3+1],y[2]*L[S*3+2]],U=`${h}_inst_${S}`),t.push({name:`${v}_${S}`,positions:F,indices:m,normals:N,uvs:l,materialName:U,color:V,roughness:b,metallic:d,clearcoat:g,clearcoatRoughness:T,ior:P,opacity:f,emissiveColor:R,xrTraits:r.userData?.xr})}return}t.push({name:r.name||`Mesh_${t.length}`,positions:c,indices:m,normals:u,uvs:l,materialName:h,color:y,roughness:b,metallic:d,clearcoat:g,clearcoatRoughness:T,ior:P,opacity:f,emissiveColor:R,xrTraits:r.userData?.xr,timeSamples:p})}}),t}function $n(n){let e=[],t=n.gltf,r=Q().decoders.get("meshopt");r&&typeof r.decodeBufferViews=="function"&&r.decodeBufferViews(t,n);let i=n.bin,s=i instanceof ArrayBuffer?i:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),o=t.accessors||[],c=t.bufferViews||[],a=t.materials||[],u=t.meshes||[],l=t.nodes||[];function m(b){let d=o[b];if(!d)throw new Error(`Accessor ${b} not found`);let g=c[d.bufferView||0],T=(g.byteOffset||0)+(d.byteOffset||0),P=g.byteLength||0,f=s.slice(T,T+P);return{acc:d,buffer:f}}let h=new Map;if(l.length>0){let b=tt(t);for(let d=0;d<b.length;d++)h.set(d,b[d])}function y(b,d,g,T){let P=u[b];if(!P)return;let f=new Float32Array(9);ye(f,d);for(let R=0;R<(P.primitives||[]).length;R++){let p=P.primitives[R],M=p.attributes?.POSITION;if(M===void 0)continue;let{acc:_,buffer:w}=m(M),A=new Float32Array(w,0,_.count*3),L=new Float32Array(A.length);for(let E=0;E<_.count;E++){let k=A[E*3],G=A[E*3+1],W=A[E*3+2];L[E*3]=d[0]*k+d[4]*G+d[8]*W+d[12],L[E*3+1]=d[1]*k+d[5]*G+d[9]*W+d[13],L[E*3+2]=d[2]*k+d[6]*G+d[10]*W+d[14]}let v,x=p.attributes?.NORMAL;if(x!==void 0){let{acc:E,buffer:k}=m(x),G=new Float32Array(k,0,E.count*3);v=new Float32Array(G.length);for(let W=0;W<E.count;W++){let j=G[W*3],re=G[W*3+1],ue=G[W*3+2],q=f[0]*j+f[3]*re+f[6]*ue,Z=f[1]*j+f[4]*re+f[7]*ue,Y=f[2]*j+f[5]*re+f[8]*ue,ie=Math.hypot(q,Z,Y)||1;v[W*3]=q/ie,v[W*3+1]=Z/ie,v[W*3+2]=Y/ie}}let I,S=p.attributes?.TEXCOORD_0;if(S!==void 0){let{acc:E,buffer:k}=m(S);I=new Float32Array(k,0,E.count*2)}let C;if(p.indices!==void 0){let{acc:E,buffer:k}=m(p.indices);E.componentType===5125?C=new Uint32Array(k,0,E.count):C=new Uint16Array(k,0,E.count);let G=_.count;for(let W of C)if(W>=G)throw new Error(`SecurityError: Index buffer value (${W}) out of vertex bounds [0, ${G}).`)}else{let E=_.count;C=E>65535?new Uint32Array(E):new Uint16Array(E);for(let k=0;k<E;k++)C[k]=k}let F="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];F=E.name||`Material_${p.material}`;let k=E.pbrMetallicRoughness||{},G=1;Array.isArray(k.baseColorFactor)&&(N=[k.baseColorFactor[0],k.baseColorFactor[1],k.baseColorFactor[2]],typeof k.baseColorFactor[3]=="number"&&(G=k.baseColorFactor[3])),typeof k.roughnessFactor=="number"&&(V=k.roughnessFactor),typeof k.metallicFactor=="number"&&(U=k.metallicFactor),Array.isArray(E.emissiveFactor)&&E.emissiveFactor.length>=3&&(O=[E.emissiveFactor[0],E.emissiveFactor[1],E.emissiveFactor[2]]);let W=E.extensions||{};W.KHR_materials_clearcoat&&(B=W.KHR_materials_clearcoat.clearcoatFactor??0,D=W.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),W.KHR_materials_ior&&typeof W.KHR_materials_ior.ior=="number"&&(H=W.KHR_materials_ior.ior);let j=W.KHR_materials_transmission?.transmissionFactor??0;z=G*(1-j)}let X=(P.primitives||[]).length>1?`${g}_p${R}`:g;e.push({name:X,positions:L,indices:C,normals:v,uvs:I,materialName:F,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 b=0;b<l.length;b++){let d=l[b];if(d.mesh!==void 0&&d.mesh<u.length){let g=h.get(b)||oe(),T=d.name||u[d.mesh].name||`Node_${b}`,P=d.extensions?.EXT_mesh_gpu_instancing?.attributes;if(P&&typeof P=="object"){let f=P.TRANSLATION,R=P.ROTATION,p=P.SCALE,M=f!==void 0?(()=>{let{acc:L,buffer:v}=m(f);return new Float32Array(v,0,L.count*3)})():null,_=R!==void 0?(()=>{let{acc:L,buffer:v}=m(R);return new Float32Array(v,0,L.count*4)})():null,w=p!==void 0?(()=>{let{acc:L,buffer:v}=m(p);return new Float32Array(v,0,L.count*3)})():null,A=Math.min(1e3,M?M.length/3:_?_.length/4:w?w.length/3:0);if(A>0){let L=new Float32Array(16),v=new Float32Array(16);for(let x=0;x<A;x++){let I=M?[M[x*3],M[x*3+1],M[x*3+2]]:[0,0,0],S=_?[_[x*4],_[x*4+1],_[x*4+2],_[x*4+3]]:[0,0,0,1],C=w?[w[x*3],w[x*3+1],w[x*3+2]]:[1,1,1];Ce(L,S,I,C),ae(v,g,L),y(d.mesh,v,`${T}_${x}`,d.extras)}continue}}y(d.mesh,g,T,d.extras)}}else{let b=oe();for(let d=0;d<u.length;d++){let g=u[d].name||`Mesh_${d}`;y(d,b,g,u[d].extras)}}return e}function Ut(n,e){if(!n||typeof n!="string")return e;let t=n.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(t)&&(t="_"+t),t||e}function Xn(n){return String(n??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function K(n){if(!Number.isFinite(n)||Math.abs(n)<1e-7)return"0";let e=Number(n.toFixed(5)).toString();return e.indexOf(".")===-1?`${e}.0`:e}function Wn(n){let e=n.length/3,t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${K(n[r*3])}, ${K(n[r*3+1])}, ${K(n[r*3+2])})`;return t.join(", ")}function Vr(n,e){let t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${K(n[r*2])}, ${K(1-n[r*2+1])})`;return t.join(", ")}function zr(n){return Array.from(n).join(", ")}function Ot(n){let e=new Map;for(let a of n){let u=Ut(a.materialName,"DefaultMaterial");e.has(u)||e.set(u,{color:a.color||[.8,.8,.8],roughness:a.roughness??.5,metallic:a.metallic??0,clearcoat:a.clearcoat??0,clearcoatRoughness:a.clearcoatRoughness??0,ior:a.ior??1.5,opacity:a.opacity??1,emissiveColor:a.emissiveColor||[0,0,0]})}let t=0,r=null;for(let a of n){if(a.timeSamples&&a.timeSamples.times.length>0){let u=a.timeSamples.times[a.timeSamples.times.length-1];u>t&&(t=u)}a.xrTraits?.anchor&&!r&&(r=a.xrTraits.anchor==="vertical"||a.xrTraits.anchor==="wall"?"vertical":"horizontal")}let i="";t>0&&(i=`startTimeCode = 0
|
|
253
|
-
endTimeCode = ${
|
|
251
|
+
void main(){fragColor=uColorId;}`;function Me(e,t,i){let r={};for(let s of i)r[s]=e.getUniformLocation(t,s);return r}var Qe=["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 ti(){let e=ot().xrDepthShader;return{fs:Fr.replace("/*XRD_U*/",e?.uniformsGLSL||"").replace("/*XRD_O*/",e?.occlusionGLSL||""),uniforms:e?[...Qe,...e.uniformNames]:Qe}}function Vr(e){if(typeof e!="string")return null;let t=e.trim();if(!t||/[\x00-\x1f\x7f]/.test(t))return null;let i=t.toLowerCase();return i.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(t)?t:null:i.startsWith("https://")||i.startsWith("blob:")?t:i.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(t)||/(^|[\\/])\.\.([\\/]|$)/.test(t)?null:t}function Se(e,t,i,r,s,a,o,n){if(r===void 0||!t.accessors?.[r])return null;let h=qe(t,i,t.accessors[r],a);if(!h)return null;n&&(h=h.slice(),_r(h,n));let l=e.createBuffer();return o.push(l),e.bindBuffer(34962,l),e.bufferData(34962,h,35044),e.enableVertexAttribArray(s),e.vertexAttribPointer(s,a,5126,!1,0,0),h}function Ae(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,t):1}function ei(e,t,i){let r=ti(),s=Je,a=r.fs,o=!1;for(let h of ct)if(h.onResolveShader){let l=h.onResolveShader(t,i,s,a);l&&(s=l.vs,a=l.fs,o=!0)}let n=o?we(e,s,a):null;return{program:n,uniforms:n?Me(e,n,r.uniforms):null}}function zr(e,t,i){let r=t.instanceMatrices;if(!r||r.length<16||typeof e.vertexAttribDivisor!="function"||typeof e.drawElementsInstanced!="function")return!1;let s=r.length>>4,a=t.instanceColors,o=new Float32Array(s*20);for(let h=0;h<s;h++)o.set(r.subarray(h*16,h*16+16),h*20),o[h*20+16]=a?a[h*3]:1,o[h*20+17]=a?a[h*3+1]:1,o[h*20+18]=a?a[h*3+2]:1,o[h*20+19]=1;let n=e.createBuffer();i.push(n),e.bindBuffer(34962,n),e.bufferData(34962,o,35044);for(let h=0;h<5;h++)e.enableVertexAttribArray(8+h),e.vertexAttribPointer(8+h,4,5126,!1,80,h*16),e.vertexAttribDivisor(8+h,1);return!0}function Br(e,t){let i=e.materials?.[t?.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 $r=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 Qt(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}function ri(e,t){let i=e?.pbrMetallicRoughness,r=i?.baseColorFactor,s=e?.extensions?.KHR_materials_clearcoat,a=o=>o!==void 0&&t[o.index]?t[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(e?.normalTexture),normalScale:e?.normalTexture?.scale??1,occlusionTexture:a(e?.occlusionTexture),occlusionStrength:e?.occlusionTexture?.strength??1,isTransmissive:(e?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function si(e,t,i){let r=new Set,s=a=>{a&&!r.has(a)&&(r.add(a),e.deleteTexture(a))};for(let a of t)for(let o of a.primitives){if(o.vao&&e.deleteVertexArray(o.vao),o.buffers)for(let h of o.buffers)e.deleteBuffer(h);s(o.texture),s(o.metallicRoughnessTexture),s(o.normalTexture),s(o.occlusionTexture);let n=new Set;o.customProgram&&n.add(o.customProgram);for(let h of o.programCache?.values()??[])h.program&&n.add(h.program);for(let h of n)e.deleteProgram(h)}if(i)for(let a of i)s(a)}function ai(e,t,i=ii,r){let s={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return Hr(e,t,i,r,s)}catch(a){let o=s.mesh&&!s.meshes.includes(s.mesh)?[...s.meshes,s.mesh]:s.meshes;si(e,o,s.gpuTextures),s.vao&&e.deleteVertexArray(s.vao);for(let n of s.buffers)e.deleteBuffer(n);throw a}}function Hr(e,t,i,r,s){if(!t||!t.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:a}=t,o=Vt("meshopt");o?.decodeBufferViews&&o.decodeBufferViews(a,t);let n=t.bin,h=[];s.meshes=h;let l=[],c=a.extensions?.KHR_materials_variants;c&&Array.isArray(c.variants)&&c.variants.forEach((R,y)=>{l.push(typeof R?.name=="string"&&R.name?R.name:`Variant_${y}`)});let f=Pr(a),g=[];if(Array.isArray(a.nodes))for(let R=0;R<a.nodes.length;R++){let y=a.nodes[R];y.mesh!==void 0&&a.meshes&&a.meshes[y.mesh]&&g.push({node:y,nodeIdx:R,meshIdx:y.mesh})}let b=g.length>0?g:(a.meshes||[]).map((R,y)=>({node:R,nodeIdx:-1,meshIdx:y})),u=[],d=Array.isArray(t.lights)&&t.lights.length>0?t.lights:Array.isArray(a.asset?.extras?.lights)&&a.asset.extras.lights.length>0?a.asset.extras.lights:null;if(d)for(let R of d)u.push({...R,type:R.type||R.light_type||"point",innerConeAngle:R.innerConeAngle??R.inner_cone_angle,outerConeAngle:R.outerConeAngle??R.outer_cone_angle});else if(a.extensions?.KHR_lights_punctual?.lights){let R=a.extensions.KHR_lights_punctual.lights;for(let y of R){let U=y.type==="directional"?"directional":y.type==="point"?"point":y.type==="spot"?"spot":"ambient";u.push({type:U,color:y.color||[1,1,1],intensity:y.intensity!==void 0?y.intensity:1})}}if(u.length===0&&(u.push({type:"ambient",color:[1,1,1],intensity:.35}),u.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),b.length>i.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${i.maxMeshes}). Found: ${b.length}`);let M=[];if(s.gpuTextures=M,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 R=0;R<a.textures.length;R++){let y=a.textures[R],U=a.images[y.source];if(U){let j=e.createTexture();e.bindTexture(3553,j),e.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),e.texParameteri(3553,10242,10497),e.texParameteri(3553,10243,10497),e.texParameteri(3553,10241,9729),e.texParameteri(3553,10240,9729);let T=k=>{e.bindTexture(3553,j),e.texImage2D(3553,0,6408,6408,5121,k),e.generateMipmap(3553),r?.()};if(U.bufferView!==void 0){let k=a.bufferViews[U.bufferView],A=k.byteOffset||0,P=new Blob([n.slice(A,A+k.byteLength)],{type:U.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(P).then(T).catch(()=>{})}else if(U.uri){let k=Vr(U.uri);if(k){let A=new Image;A.crossOrigin="anonymous",A.referrerPolicy="no-referrer",A.onload=()=>T(A),A.src=k}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",U.uri)}M.push(j)}else M.push(null)}}let w=[1/0,1/0,1/0],v=[-1/0,-1/0,-1/0],m=0,p=0;for(let R=0;R<b.length;R++){let y=b[R],U=a.meshes[y.meshIdx],j=y.nodeIdx>=0?f[y.nodeIdx]:mt(),T=new Float32Array(9);Et(T,j);let k={name:y.node.name||U.name||`Mesh_${y.meshIdx}`,nodeIndex:y.nodeIdx,transform:j,normalMatrix:T,primitives:[],extras:y.node.extras||U.extras,...y.node?.visible===!1||y.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{}};s.mesh=k;let A=y.node?.extensions?.EXT_mesh_gpu_instancing;if(A&&A.attributes&&typeof A.attributes=="object"){let P=A.attributes,G=P.TRANSLATION!==void 0?a.accessors?.[P.TRANSLATION]:null,q=P.ROTATION!==void 0?a.accessors?.[P.ROTATION]:null,$=P.SCALE!==void 0?a.accessors?.[P.SCALE]:null,Y=P._COLOR_0!==void 0?a.accessors?.[P._COLOR_0]:null,_=Number(G?.count??q?.count??$?.count??0);if(!Number.isFinite(_)||_<0||_>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${_}`);if(_>0){let z=(I,tt)=>{if(!I||I.bufferView===void 0||!a.bufferViews?.[I.bufferView])return null;let Z=I.componentType??5126,at=it=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${it})`),null);if(Z!==5120&&Z!==5121&&Z!==5122&&Z!==5123&&Z!==5126)return at(`componentType ${Z}`);if(!(Number(I.count)>=_))return at(`count ${I.count} < ${_}`);let J=null;try{J=qe(a,n,{...I,count:_},tt)}catch{return at("out of bounds")}return!J||!J.every(Number.isFinite)?at("non-finite value"):J},V=z(G,3),W=z(q,4),O=z($,3),H=Y?.type==="VEC4"?4:3,B=z(Y,H),K=new Float32Array(_*16),X=mt();for(let I=0;I<_;I++){let tt=V?[V[I*3],V[I*3+1],V[I*3+2]]:[0,0,0],Z=W?[W[I*4],W[I*4+1],W[I*4+2],W[I*4+3]]:[0,0,0,1],at=O?[O[I*3],O[I*3+1],O[I*3+2]]:[1,1,1];xe(X,Z,tt,at),K.set(X,I*16)}if(k.instanceMatrices=K,B){let I=new Float32Array(_*3);for(let tt=0;tt<_;tt++)I[tt*3]=B[tt*H],I[tt*3+1]=B[tt*H+1],I[tt*3+2]=B[tt*H+2];k.instanceColors=I}}}for(let P of U.primitives||[]){if(P.extensions?.KHR_draco_mesh_compression){let J=Vt("draco");J&&J.decodePrimitive(a,P,n)}let G=[],q=e.createVertexArray();s.vao=q,s.buffers=G,e.bindVertexArray(q);let $=zr(e,k,G),Y=a.accessors[P.attributes.POSITION],_=Number(Y?.count??0);if(!Number.isFinite(_)||_<0||m+_>i.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${i.maxVertices}).`);if(m+=_,Y?.min&&Y?.max){let J=it=>{for(let rt=0;rt<3;rt++){let gt=it[12+rt],st=it[12+rt];for(let nt=0;nt<3;nt++){let lt=it[nt*4+rt]*Y.min[nt],ht=it[nt*4+rt]*Y.max[nt];gt+=lt<ht?lt:ht,st+=lt>ht?lt:ht}gt<w[rt]&&(w[rt]=gt),st>v[rt]&&(v[rt]=st)}};if(k.instanceMatrices&&k.instanceMatrices.length>=16){let it=k.instanceMatrices.length>>4,rt=mt();for(let gt=0;gt<it;gt++){let st=k.instanceMatrices.subarray(gt*16,gt*16+16);dt(rt,j,st),J(rt)}}else J(j)}let z=Se(e,a,n,P.attributes.POSITION,0,3,G);Se(e,a,n,P.attributes.NORMAL,1,3,G),Se(e,a,n,P.attributes.TEXCOORD_0,2,2,G,Br(a,P));let V=0,W=5123,O=null;if(P.indices!==void 0){let J=a.accessors[P.indices],it=(a.bufferViews[J.bufferView].byteOffset||0)+(J.byteOffset||0);if(V=Number(J.count??0),!Number.isFinite(V)||V<0||p+V>i.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${i.maxIndices}).`);p+=V,W=J.componentType===5125?5125:5123;let rt=e.createBuffer();G.push(rt),e.bindBuffer(34963,rt),J.componentType===5125?O=new Uint32Array(n,it,J.count):J.componentType===5121?O=Uint16Array.from(new Uint8Array(n,it,J.count)):O=it%2===0?new Uint16Array(n,it,J.count):new Uint16Array(n.slice(it,it+J.count*2)),e.bufferData(34963,O,35044)}else V=Y.count;let H={};for(let J of ct)if(J.onBuildPrimitiveVAO){let it=J.onBuildPrimitiveVAO(e,q,P,a,n);it&&(H[J.name]=it)}e.bindVertexArray(null);let B=a.materials&&P.material!==void 0?a.materials[P.material]:null,{program:K,uniforms:X}=ei(e,P,B),I=ri(B,M),tt=!!(B?.extensions?.KHR_materials_transmission||H.materials?.isTransmissive),Z=P.extensions?.KHR_materials_variants?.mappings,at=Array.isArray(Z)?Z.filter(J=>J&&typeof J.material=="number"&&Array.isArray(J.variants)).map(J=>({material:J.material|0,variants:J.variants.map(it=>Number(it)|0)})):void 0;k.primitives.push({vao:q,instanced:$,indexCount:V,indexType:W,...I,positions:z,indices:O,buffers:G,materialIndex:P.material,defaultMaterialIndex:P.material,variantMappings:at,primitiveDef:P,programCache:new Map([[P.material??-1,{program:K,uniforms:X}]]),pluginData:H,customProgram:K,customUniforms:X,isTransmissive:tt})}h.push(k)}isFinite(w[0])||(w=[-1,-1,-1]),isFinite(v[0])||(v=[1,1,1]);let x=[(w[0]+v[0])/2,(w[1]+v[1])/2,(w[2]+v[2])/2],S=v[0]-w[0],N=v[1]-w[1],F=v[2]-w[2],E=Math.max(Math.hypot(S,N,F)/2,.5),L=[w[0],w[1],w[2]],C=[v[0],v[1],v[2]],D=t.animations;if(!D){for(let R of ct)if(R.onParseGLB?.(t),t.animations){D=t.animations;break}}return D||(D=[]),{meshes:h,bounds:{center:x,radius:E,min:L,max:C},lights:u,animations:D,worldMatrices:f,gpuTextures:M,availableVariants:l}}function Wt(e){let t=e.customTarget||e.bounds.center,i=e.currDistance*Math.cos(e.currPhi);return[t[0]+i*Math.sin(e.currTheta),t[1]+e.currDistance*Math.sin(e.currPhi),t[2]+i*Math.cos(e.currTheta)]}var Mt=class{constructor(e,t,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=mt(),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=mt(),this.viewMatrix=mt(),this.activeViewMatrix=null,this.modelMatrix=mt(),this.mvpMatrix=mt(),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:mt(),rawValueToMeters:.001,format:0},this.container=e;let r,s;if(t&&typeof t.getContext=="function"?(r=t,s=i):(s=t,r=s?.canvas),!r){let n=e.querySelector("canvas");n||(n=document.createElement("canvas"),n.style.width="100%",n.style.height="100%",n.style.display="block",n.style.touchAction="none",e.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=Ae(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=Ut(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(e,t){Dr(e,t)}static getDecoder(e){return Vt(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=ti();this.renderProg=we(e,Je,t.fs),this.pickProg=we(e,Or,Ur),this.uRender=Me(e,this.renderProg,t.uniforms),this.uPick=Me(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of ct)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),i=Math.max(1,this.canvas.height);this.pickFboWidth=t,this.pickFboHeight=i,e.bindTexture(3553,this.pickTexture),e.texImage2D(3553,0,6408,t,i,0,6408,5121,null),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728),e.bindRenderbuffer(36161,this.pickDepth),e.renderbufferStorage(36161,33189,t,i),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 i=this.gl,r=Math.max(1,e),s=Math.max(1,t);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(e,t){let{meshes:i,bounds:r,lights:s,animations:a,worldMatrices:o,gpuTextures:n,availableVariants:h}=ai(this.gl,e,t,()=>this.render());if(this.lastGlbData=e,this.lastLimits=t,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=h||[],this.gltf=e.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let f of e.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 ct)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 l=e.exposure??e.gltf?.extras?.exposure??e.gltf?.asset?.extras?.exposure;l!==void 0&&(this.exposure=Ae(l));let c=e.environmentIntensity??e.gltf?.extras?.environmentIntensity??e.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(e){this.loadGLBData(Ze(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let e of ct)e.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(zt(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let i=zt(e),{meshes:r}=ai(this.gl,i,ii,()=>this.render());if(t)for(let s of r)s.transform[12]+=t[0],s.transform[13]+=t[1],s.transform[14]+=t[2],Et(s.normalMatrix,s.transform);this.backdropMeshes=r,this.update(0),this.render()}setClearColor(e,t,i,r=1){this.clearColor=[e,t,i,r]}updateMeshTransforms(e){for(let t=0;t<this.meshes.length;t++){let i=this.meshes[t],r;e instanceof Map?r=e.get(i.name)??e.get(t):Array.isArray(e)?r=e[t]:e&&typeof e=="object"&&(Object.prototype.hasOwnProperty.call(e,i.name)?r=e[i.name]:Object.prototype.hasOwnProperty.call(e,t)&&(r=e[t])),r&&r.length===16&&(i.transform.set(r),Et(i.normalMatrix,i.transform))}}bindLights(e=this.uRender){let t=this.gl,i=[.28,.28,.28],r=[],s=[],a=[],o=[],n=[],h=[];for(let l of this.lights){let c=l.color||[1,1,1],f=l.intensity!==void 0?l.intensity:1;if(l.type==="ambient")i=[c[0]*f,c[1]*f,c[2]*f];else if(l.type==="directional"&&r.length<6){let g=l.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((l.type==="point"||l.type==="spot")&&a.length<6){let g=l.position||[0,0,0];if(a.push(g[0],g[1],g[2]),o.push(c[0]*f,c[1]*f,c[2]*f),l.type==="spot"){let b=l.direction||[0,-1,0],u=Math.max(.01,Math.min(Math.PI/2,l.outerConeAngle??Math.PI/3)),d=Math.max(0,Math.min(u-1e-4,l.innerConeAngle??0));n.push(b[0],b[1],b[2]),h.push(Math.cos(d),Math.cos(u))}else n.push(0,-1,0),h.push(-2,-3)}}r.length===0&&(r.push(.5,1,.8),s.push(1,1,1)),t.uniform3fv(e.uAmbientColor,i),t.uniform1i(e.uNumDirLights,r.length/3),r.length>0&&(t.uniform3fv(e.uDirLightDir,r),t.uniform3fv(e.uDirLightColor,s)),t.uniform1i(e.uNumPointLights,a.length/3),a.length>0&&(t.uniform3fv(e.uPointLightPos,a),t.uniform3fv(e.uPointLightColor,o),e.uPointLightSpotDir&&t.uniform3fv(e.uPointLightSpotDir,n),e.uPointLightSpotCone&&t.uniform2fv(e.uPointLightSpotCone,h)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=Ae(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=Ut(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of ct)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of ct)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,i=this.currDistance;return{theta:e,phi:t,radius:i,toString(){return`${e.toFixed(4)}rad ${t.toFixed(4)}rad ${i.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,i)=>{let r=this.meshes.flatMap(l=>l.primitives.filter(c=>c.materialIndex===i||e.length===1&&c.materialIndex===void 0)),s=r[0],a=s?[...s.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],o=s?s.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,n=s?s.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,h={baseColorFactor:a,metallicFactor:o,roughnessFactor:n,setBaseColorFactor:l=>{let c=[l[0],l[1],l[2],l[3]??1];h.baseColorFactor=c,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=c);for(let f of r)f.baseColor=c;this.render()},setMetallicFactor:l=>{h.metallicFactor=l,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=l);for(let c of r)c.metallic=l;this.render()},setRoughnessFactor:l=>{h.roughnessFactor=l,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=l);for(let c of r)c.roughness=l;this.render()}};return{name:t.name||`Material_${i}`,pbrMetallicRoughness:h}})}playAnimation(e){if(this.animations.length!==0){if(e){let t=this.animations.find(i=>i.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==="",i=-1;if(t)this.activeVariantName=null;else{if(i=this.availableVariants.indexOf(e),i<0)return!1;this.activeVariantName=e}let r=this.gltf?.materials;if(!Array.isArray(r))return t;for(let s of this.meshes)for(let a of s.primitives){let o=a.defaultMaterialIndex;if(!t&&Array.isArray(a.variantMappings)){for(let h of a.variantMappings)if(Array.isArray(h.variants)&&h.variants.includes(i)){o=h.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(e,t,i){if(!this.gl||!e.primitiveDef)return;e.programCache??(e.programCache=new Map);let r=t??-1,s=e.programCache.get(r);s||(s=ei(this.gl,{...e.primitiveDef,material:t},i),e.programCache.set(r,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 ct)if(t.evaluateAnimation){t.evaluateAnimation(this,e);return}}setTarget(e,t,i){this.customTarget=[e,t,i],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,i=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(t,Math.min(i,e))}setCamera(e,t,i,r){e!==void 0&&(this.targetTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.targetPhi=this.clampPhi(t*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(e,t,i,r){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),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(e,t){let i=mt();dt(i,this.projMatrix,this.viewMatrix);let[r,s,a]=e,o=t?t[0]:0,n=t?t[1]:0,h=t?t[2]:0,l=this.modelRootMatrix;l&&(r=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],a=l[2]*e[0]+l[6]*e[1]+l[10]*e[2]+l[14],t&&(o=l[0]*t[0]+l[4]*t[1]+l[8]*t[2],n=l[1]*t[0]+l[5]*t[1]+l[9]*t[2],h=l[2]*t[0]+l[6]*t[1]+l[10]*t[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],b=i[3]*r+i[7]*s+i[11]*a+i[15];if(b<=1e-4)return{x:0,y:0,z:1,visible:!1};let u=c/b,d=f/b,M=g/b,w=this.canvas.getBoundingClientRect(),v=w.width||this.canvas.clientWidth||this.canvas.width||300,m=w.height||this.canvas.clientHeight||this.canvas.height||150,p=(u*.5+.5)*v,x=(-d*.5+.5)*m,S=u>=-1.1&&u<=1.1&&d>=-1.1&&d<=1.1&&M>=-1&&M<=1;if(S&&t){let[N,F,E]=Wt(this),L=[r-N,s-F,a-E];o*L[0]+n*L[1]+h*L[2]>.05&&(S=!1)}return{x:p,y:x,z:M,visible:S}}setSelectedMesh(e){this.selectedMeshName=e||""}getSelectedMesh(){return this.selectedMeshName}setupEvents(){let e=this.canvas,t=()=>typeof performance<"u"?performance.now():Date.now();this.boundContextMenu=i=>{i.preventDefault()},e.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=i=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=t(),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,e.setPointerCapture(i.pointerId))},e.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=i=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=t();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]],h=this.customTarget?[...this.customTarget]:[...this.bounds.center],l=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;h[0]+=(-s*o[0]+a*n[0])*l,h[1]+=(-s*o[1]+a*n[1])*l,h[2]+=(-s*o[2]+a*n[2])*l,this.customTarget=h}else this.targetTheta=this.clampTheta(this.targetTheta-s*.008),this.targetPhi=this.clampPhi(this.targetPhi+a*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=i=>{this.lastInteractionTime=t(),this.activePointers.delete(i.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(i.pointerId)}catch{}if(this.totalDragDist<5&&i.button===0){let r=e.getBoundingClientRect(),s=Math.floor((i.clientX-r.left)*(e.width/Math.max(r.width,1))),a=Math.floor((i.clientY-r.top)*(e.height/Math.max(r.height,1)));this.performMeshPick(s,a,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=i=>{if(!this.interactive)return;i.preventDefault(),this.lastInteractionTime=t();let r=Math.exp(i.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},e.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),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=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=t(),i.preventDefault()}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=(i,r,s)=>{this[s]&&(i.removeEventListener(r,this[s]),this[s]=null)},t=this.canvas;e(t,"webglcontextlost","boundContextLost"),e(t,"webglcontextrestored","boundContextRestored"),e(t,"contextmenu","boundContextMenu"),e(t,"pointerdown","boundPointerDown"),e(t,"pointermove","boundPointerMove"),e(t,"pointerup","boundPointerUp"),e(t,"wheel","boundWheel"),e(t,"keydown","boundKeyDown"),e(this.container,"setCamera","boundSetCamera"),e(this.container,"resetCamera","boundResetCamera")}raycastFromScreenPoint(e,t){let i=this.canvas,r=i.getBoundingClientRect(),s=i.width||300,a=i.height||300,o=r.width>0?Math.floor((e-r.left)*(s/r.width)):Math.floor(e),n=r.height>0?Math.floor((t-r.top)*(a/r.height)):Math.floor(t);return this.performMeshPick(o,n,!1)}performMeshPick(e,t,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);e=this.mapStereoPickX(e,s);let o=mt();dt(o,this.projMatrix,this.viewMatrix);let n=[],h=Math.max(0,Math.min(s-1,e)),l=Math.max(0,Math.min(a-1,a-1-t));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 x=0;x<this.meshes.length;x++){let S=this.meshes[x];if(S.visible===!1||S.isPluginMesh)continue;let N=x+1,F=(N&255)/255,E=(N>>8&255)/255,L=(N>>16&255)/255;r.uniform4f(this.uPick.uColorId,F,E,L,1),dt(this.modelMatrix,this.modelRootMatrix,S.transform);let C=S.instanceMatrices;if(C&&C.length>=16){let D=C.length>>4,R=mt();for(let y of S.primitives){r.bindVertexArray(y.vao);for(let U=0;U<D;U++)dt(R,this.modelMatrix,C.subarray(U*16,U*16+16)),dt(this.mvpMatrix,o,R),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),Qt(r,y)}}else{dt(this.mvpMatrix,o,this.modelMatrix),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let D of S.primitives)r.bindVertexArray(D.vao),Qt(r,D)}}let m=new Uint8Array(4);r.readPixels(h,l,1,1,6408,5121,m),r.bindFramebuffer(36160,null);let p=m[0]+(m[1]<<8)+(m[2]<<16);p>0&&p<=this.meshes.length&&(n=[this.meshes[p-1]])}n.length===0&&(n=this.meshes.filter(m=>m.visible!==!1));let c=null,f=1/0,g=[0,0,0],b=[0,1,0],[u,d,M]=Wt(this),w=mt();for(let m of n){dt(w,this.modelRootMatrix,m.transform);let p=m.instanceMatrices,x=p&&p.length>=16?p.length>>4:1;for(let S=0;S<x;S++){p&&p.length>=16?dt(this.modelMatrix,w,p.subarray(S*16,S*16+16)):this.modelMatrix.set(w),dt(this.mvpMatrix,o,this.modelMatrix);let N=mt();if(!Rr(N,this.mvpMatrix))continue;let F=(h+.5)/s*2-1,E=(l+.5)/a*2-1,L=[0,0,0],C=[0,0,0];Xe(L,F,E,-1,N),Xe(C,F,E,1,N);let D=C[0]-L[0],R=C[1]-L[1],y=C[2]-L[2],U=Math.hypot(D,R,y)||1,j=D/U,T=R/U,k=y/U,A={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((P=>{for(let G of m.primitives){if(!G.positions)continue;let q=G.positions,$=G.indices,Y=Math.floor($?$.length/3:q.length/9);for(let _=0;_<Y;_++){let z=$?$[_*3]:_*3,V=$?$[_*3+1]:_*3+1,W=$?$[_*3+2]:_*3+2;Cr(L[0],L[1],L[2],j,T,k,q[z*3],q[z*3+1],q[z*3+2],q[V*3],q[V*3+1],q[V*3+2],q[W*3],q[W*3+1],q[W*3+2],A,P)}}})(1e-4),isFinite(A.distance)){let P=A.point[0],G=A.point[1],q=A.point[2],$=this.modelMatrix,Y=$[0]*P+$[4]*G+$[8]*q+$[12],_=$[1]*P+$[5]*G+$[9]*q+$[13],z=$[2]*P+$[6]*G+$[10]*q+$[14],V=Y-u,W=_-d,O=z-M,H=Math.hypot(V,W,O);if(H<f){Et(this.normalMatrix,this.modelMatrix);let B=this.normalMatrix,K=A.normal[0],X=A.normal[1],I=A.normal[2],tt=B[0]*K+B[3]*X+B[6]*I,Z=B[1]*K+B[4]*X+B[7]*I,at=B[2]*K+B[5]*X+B[8]*I,J=Math.hypot(tt,Z,at)||1;tt/=J,Z/=J,at/=J,tt*V+Z*W+at*O>0&&(tt=-tt,Z=-Z,at=-at),c=m,f=Math.round(H*1e3)/1e3,g=[Math.round(Y*1e3)/1e3,Math.round(_*1e3)/1e3,Math.round(z*1e3)/1e3],b=[Math.round(tt*1e3)/1e3,Math.round(Z*1e3)/1e3,Math.round(at*1e3)/1e3]}}}}if(!c)return null;let v={meshIndex:this.meshes.indexOf(c),meshName:c.name,nodeIndex:c.nodeIndex,distance:f,hitPoint:g,normal:b,screenX:e,screenY:t};if(i){for(let m of ct)m.onMeshSelect?.(this,v);this.opts.onMeshClick&&this.opts.onMeshClick(v),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:v}))}return v}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let i=Math.max(1,Math.floor(t*.5)),r=e>=i,s=r?e-i:e,a=r?Math.max(1,t-i):i,o=(s+.5)/a*2-1;return Math.floor((o*.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);ve(this.projMatrix,this.fov,e,.1,t);let i=this.customTarget||this.bounds.center;Jt(this.viewMatrix,Wt(this),i,[0,1,0]),dt(this.mvpMatrix,this.projMatrix,this.viewMatrix),Et(this.normalMatrix,this.modelMatrix)}resize(){let e=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),t=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.floor(t.width*e)),r=Math.max(1,Math.floor(t.height*e));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(e){let t=this.xrSessionActive;if(this.xrSessionActive=e,t&&!e){this.xrDepthState.enabled=!1;for(let i of ct)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(e){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",e))}stepXRUpdate(e){for(let t of ct)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 i=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(i),this.render()}catch(r){this.reportRenderError(r)}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),i=this.bounds.center[0],r=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]=i-(e*i+t*r),s[13]=0,s[14]=r-(-t*i+e*r),s[15]=1}setVisible(e){this.isVisible=e}update(e){for(let a of ct)a.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 a of ct)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(e,t,i,r,s=!0,a=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let o=e?.transform?.inverse?.matrix||this.viewMatrix,n=e?.projectionMatrix||this.projMatrix,h=e?.transform?.position,l=h?[h.x,h.y,h.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):i&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:o,projMatrix:n,eyePos:l,viewport:r,eye:e?.eye||"none",clear:a>0?!1:e?.eye!=="right",isAR:s})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let v=Math.max(2,this.canvas.width||2),m=Math.max(1,this.canvas.height||1),p=Math.max(1,Math.floor(v*.5)),x=Math.max(1,v-p),S=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),N=this.customTarget||this.bounds.center,[F,E,L]=Wt(this),C=Math.cos(this.currTheta),D=-Math.sin(this.currTheta),R=.032,y=mt(),U=mt(),j=[F-C*R,E,L-D*R],T=[N[0]-C*R*.25,N[1],N[2]-D*R*.25];ve(y,this.fov,p/m,.1,S),Jt(U,j,T,[0,1,0]);let k=mt(),A=mt(),P=[F+C*R,E,L+D*R],G=[N[0]+C*R*.25,N[1],N[2]+D*R*.25];ve(k,this.fov,x/m,.1,S),Jt(A,P,G,[0,1,0]),this.render({viewMatrix:U,projMatrix:y,eyePos:j,viewport:[0,0,p,m],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:A,projMatrix:k,eyePos:P,viewport:[p,0,x,m],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,v,m);return}let t=this.gl,i=0,r=0,s=this.canvas.width,a=this.canvas.height;e?.viewport?(i=e.viewport[0],r=e.viewport[1],s=e.viewport[2],a=e.viewport[3],t.viewport(i,r,s,a)):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(16640));let o=mt(),n=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=n,dt(o,e?.projMatrix??this.projMatrix,n);let h=ot().xrDepthShader,l=Nr(this.toneMapping),[c,f,g]=e?e.eyePos:Wt(this);for(let v of ct)v.onBeforeDrawScene?.(this,t,o,[c,f,g],l);let b=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&b===0)return;let u=e?.eye||"none",d=!1,M=b>0?[...this.backdropMeshes,...this.meshes]:this.meshes,w=v=>{for(let m=0;m<M.length;m++){let p=M[m];if(p.visible===!1)continue;let x=this.selectedMeshName!==""&&p.name===this.selectedMeshName;m<b||p.worldSpace===!0||p.name==="__xr_reticle__"?this.modelMatrix.set(p.transform):dt(this.modelMatrix,this.modelRootMatrix,p.transform),dt(this.mvpMatrix,o,this.modelMatrix),Et(p.normalMatrix,this.modelMatrix);let S=p.extras?.xr?.stereo||p.userData?.xr?.stereo,N=0,F=0,E=1,L=1;S==="sbs"?(E=.5,N=u==="right"?.5:0):S==="ou"&&(L=.5,F=u==="right"?.5:0);for(let C of p.primitives){let D=!!C.isTransmissive;if(!v&&D){d=!0;continue}if(v&&!D)continue;let R=C.customProgram||this.renderProg,y=C.customUniforms||this.uRender;t.useProgram(R),t.vertexAttrib3f(3,0,0,0),y.uInstanced&&t.uniform1i(y.uInstanced,0),t.uniform1i(y.uToneMapping,l),t.uniform1f(y.uEnvIntensity,this.envIntensity),y.uExposure&&t.uniform1f(y.uExposure,this.exposure),t.uniform3f(y.uCameraPos,c,f,g),t.uniform1f(y.uEmissive,x?1:0),t.uniformMatrix4fv(y.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(y.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(y.uNormalMatrix,!1,p.normalMatrix),y.uUvTransform&&t.uniform4f(y.uUvTransform,N,F,E,L),y.uViewportSize&&t.uniform2f(y.uViewportSize,Math.max(1,s),Math.max(1,a)),h?.bind(t,y,this.xrDepthState,n,[i,r,Math.max(1,s),Math.max(1,a)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(y.uEnvironmentMap,4),t.uniform1i(y.uHasEnvironmentMap,1)):t.uniform1i(y.uHasEnvironmentMap,0),this.bindLights(y),y.uSectionEnabled&&t.uniform1i(y.uSectionEnabled,0);for(let j of ct)j.onBeforeDrawPrimitive?.(t,R,C,p,this.worldMatrices||[],this.gltf);t.uniform4fv(y.uBaseColor,C.baseColor),t.uniform1f(y.uMetallic,C.metallic),t.uniform1f(y.uRoughness,C.roughness),y.uClearcoat&&t.uniform2f(y.uClearcoat,C.clearcoat??0,C.clearcoatRoughness??.04),C.texture?(t.activeTexture(33984),t.bindTexture(3553,C.texture),t.uniform1i(y.uBaseColorTexture,0),t.uniform1i(y.uHasTexture,1)):t.uniform1i(y.uHasTexture,0),C.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,C.metallicRoughnessTexture),t.uniform1i(y.uMetallicRoughnessTexture,1),t.uniform1i(y.uHasMetallicRoughnessTexture,1)):t.uniform1i(y.uHasMetallicRoughnessTexture,0),C.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,C.normalTexture),t.uniform1i(y.uNormalTexture,2),t.uniform1i(y.uHasNormalTexture,1),t.uniform1f(y.uNormalScale,C.normalScale)):t.uniform1i(y.uHasNormalTexture,0),C.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,C.occlusionTexture),t.uniform1i(y.uOcclusionTexture,3),t.uniform1i(y.uHasOcclusionTexture,1),t.uniform1f(y.uOcclusionStrength,C.occlusionStrength)):t.uniform1i(y.uHasOcclusionTexture,0),t.bindVertexArray(C.vao);let U=p.instanceMatrices;if(C.instanceCount!==void 0)t.drawElementsInstanced(4,C.indexCount,C.indexType,0,C.instanceCount);else if(U&&U.length>=16&&C.instanced&&y.uInstanced&&y.uViewProj){let j=U.length>>4;t.uniform1i(y.uInstanced,1),t.uniformMatrix4fv(y.uViewProj,!1,o),C.indices?t.drawElementsInstanced(4,C.indexCount,C.indexType,0,j):t.drawArraysInstanced(4,0,C.indexCount,j),t.uniform1i(y.uInstanced,0)}else if(U&&U.length>=16){let j=U.length>>4,T=p.instanceColors,k=mt(),A=new Float32Array(9),P=[C.baseColor[0],C.baseColor[1],C.baseColor[2],C.baseColor[3]];for(let G=0;G<j;G++)dt(k,this.modelMatrix,U.subarray(G*16,G*16+16)),dt(this.mvpMatrix,o,k),Et(A,k),t.uniformMatrix4fv(y.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(y.uModel,!1,k),t.uniformMatrix3fv(y.uNormalMatrix,!1,A),T&&(P[0]=C.baseColor[0]*T[G*3],P[1]=C.baseColor[1]*T[G*3+1],P[2]=C.baseColor[2]*T[G*3+2],P[3]=C.baseColor[3],t.uniform4fv(y.uBaseColor,P)),Qt(t,C)}else Qt(t,C)}}};if(w(!1),d){for(let v of ct)v.onBeforeTransmissivePass?.(t,this);w(!0)}for(let v of ct)v.onAfterRender?.(t,this,o,e?.eye??"none",[i,r,s,a],e?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(e,t){si(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 ct)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()}};Mt.registerPlugin=He,Mt.getRegisteredPlugins=vr;function Gr(e){return e+3&-4}var et=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t;function ni(e,t){let i=t,r=1;for(;e.has(i);)i=`${t}_${r++}`;return e.add(i),i}function oi(e,t=0){let[i,r,s,,a,o,n,,h,l,c,,f,g,b]=Array.from({length:15},(A,P)=>et(e[t+P],P%5===0?1:0)),u=Math.hypot(i,r,s),d=Math.hypot(a,o,n),M=Math.hypot(h,l,c);i*(o*c-l*n)-a*(r*c-l*s)+h*(r*n-o*s)<0&&(u=-u);let w=Math.abs(u)>1e-8?1/u:0,v=Math.abs(d)>1e-8?1/d:0,m=Math.abs(M)>1e-8?1/M:0,p=i*w,x=r*w,S=s*w,N=a*v,F=o*v,E=n*v,L=h*m,C=l*m,D=c*m,R=p+F+D,y=0,U=0,j=0,T=1;if(R>0){let A=.5/Math.sqrt(R+1);T=.25/A,y=(E-C)*A,U=(L-S)*A,j=(x-N)*A}else if(p>F&&p>D){let A=2*Math.sqrt(Math.max(0,1+p-F-D));A>1e-8&&(T=(E-C)/A,y=.25*A,U=(N+x)/A,j=(L+S)/A)}else if(F>D){let A=2*Math.sqrt(Math.max(0,1+F-p-D));A>1e-8&&(T=(L-S)/A,y=(N+x)/A,U=.25*A,j=(E+C)/A)}else{let A=2*Math.sqrt(Math.max(0,1+D-p-F));A>1e-8&&(T=(x-N)/A,y=(L+S)/A,U=(E+C)/A,j=.25*A)}let k=Math.hypot(y,U,j,T);return k>1e-8&&Number.isFinite(k)?(y/=k,U/=k,j/=k,T/=k):(y=0,U=0,j=0,T=1),{t:[f,g,b],r:[y,U,j,T],s:[u,d,M]}}function Wr(e){let t={};return e.grab&&(t.interactable={mode:typeof e.grab=="string"?e.grab:"2-hand"},t.movable={scaleInZ:!!e.scale,minScale:typeof e.scale=="object"?e.scale.min??.1:.1,maxScale:typeof e.scale=="object"?e.scale.max??10:10}),e.billboard&&(t.billboard={mode:typeof e.billboard=="string"?e.billboard:"capsule"}),e.follow&&(t.follow={target:typeof e.follow=="object"?e.follow.mode??"head":e.follow}),e.anchor&&(t.anchor={plane:e.anchor}),e.physics&&e.physics!=="none"&&(t.rigidbody={type:e.physics}),t}var _t=(e,t,i,r)=>typeof e=="number"&&Number.isFinite(e)?Math.max(t,Math.min(i,e)):r;function li(e){let t=e?.audioEmitter??e?.spatialAudio??(typeof e?.audio=="object"&&e.audio&&("preset"in e.audio||"distanceModel"in e.audio||"coneInnerAngle"in e.audio||"maxDistance"in e.audio||"volume"in e.audio)?e.audio:typeof e?.audio=="string"&&/^(hum|reactor|wind|beacon|geiger|chimeLoop|machinery|water)$/.test(e.audio)?{preset:e.audio}:void 0);if(!t||typeof t=="object"&&t.enabled===!1)return null;let i=typeof t=="string"?{preset:t}:t,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:_t(i.volume,0,2,.6),loop:typeof i.loop=="boolean"?i.loop:!0,isGlobal:i.type==="global"||i.positional===!1}}function te(e,t){return hi(e,t)[0]}function hi(e,t){e.updateMatrixWorld(!0);let i=[],r=0,s=[],a=[],o=[],n=[],h=new Set,l=[],c=[],f=new Map,g=[],b=[],u=[],d=new Map,M=[],w=[];function v(T){let k=f.get(T);if(k!==void 0)return k;k=c.length,f.set(T,k);let A=T,P=A.color?.r??.8,G=A.color?.g??.8,q=A.color?.b??.8,$=A.opacity??1,Y={baseColorFactor:[P,G,q,$],metallicFactor:A.metalness??0,roughnessFactor:A.roughness??.5},_={};if(A.map){let W="";typeof A.map=="string"?W=A.map:typeof A.map.source=="string"?W=A.map.source:typeof A.map.image=="string"&&(W=A.map.image);let O=W.trim(),H=O&&!/[\x00-\x1f\x7f\\]|\.\./.test(O)&&(/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(O)||!O.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(O))?O:null;if(H){let K=d.get(H);if(K===void 0){let X=g.length;g.push({uri:H}),b.length===0&&b.push({magFilter:9729,minFilter:9987,wrapS:10497,wrapT:10497}),K=u.length,u.push({sampler:0,source:X}),d.set(H,K)}Y.baseColorTexture={index:K}}let B=A.map.avgColor;Array.isArray(B)&&B.length>=3&&(_.avgColor=[B[0],B[1],B[2]])}let z={name:A.name||"",pbrMetallicRoughness:Y,doubleSided:A.side===2||!!A.doubleSided,...Object.keys(_).length>0?{extras:_}:{}};if(A.emissive&&(A.emissive.r>0||A.emissive.g>0||A.emissive.b>0)){let W=A.emissiveIntensity??1;z.emissiveFactor=[A.emissive.r*W,A.emissive.g*W,A.emissive.b*W]}let V={};return A.clearcoat&&A.clearcoat>0&&(V.KHR_materials_clearcoat={clearcoatFactor:A.clearcoat,clearcoatRoughnessFactor:A.clearcoatRoughness||0}),A.sheen&&A.sheen>0&&(V.KHR_materials_sheen={sheenColorFactor:A.sheenColor?[A.sheenColor.r,A.sheenColor.g,A.sheenColor.b]:[1,1,1],sheenRoughnessFactor:A.sheenRoughness||0}),A.transmission&&A.transmission>0&&(V.KHR_materials_transmission={transmissionFactor:A.transmission}),A.thickness&&A.thickness>0&&(V.KHR_materials_volume={thicknessFactor:A.thickness,attenuationDistance:A.attenuationDistance??1/0,attenuationColor:A.attenuationColor?[A.attenuationColor.r,A.attenuationColor.g,A.attenuationColor.b]:[1,1,1]}),A.ior!==void 0&&A.ior!==1.5&&(V.KHR_materials_ior={ior:A.ior}),A.dispersion&&A.dispersion>0&&(V.KHR_materials_dispersion={dispersion:A.dispersion}),A.iridescence&&A.iridescence>0&&(V.KHR_materials_iridescence={iridescenceFactor:A.iridescence,iridescenceIor:A.iridescenceIOR??1.3}),Object.keys(V).length>0&&(z.extensions=V),c.push(z),k}function m(T,k){let A=new Uint8Array(T.buffer,T.byteOffset,T.byteLength),P=Gr(A.byteLength),G=new Uint8Array(P);G.set(A),i.push(G);let q=s.length;return s.push({buffer:0,byteOffset:r,byteLength:A.byteLength,target:k}),r+=P,q}function p(T,k,A,P,G,q,$){let Y=m(T,A),_=a.length,z={bufferView:Y,byteOffset:0,componentType:P,count:G,type:k};return q&&(z.min=q),$&&(z.max=$),a.push(z),_}e.traverse(T=>{if(T.isLight||T.color&&T.intensity!==void 0){let k=T.matrixWorld?.elements,A=et(k?k[12]:T.position?.x,0),P=et(k?k[13]:T.position?.y,0),G=et(k?k[14]:T.position?.z,0),q=T.target,$=q?.parent?q?.matrixWorld?.elements:void 0,Y=et($?$[12]:q?.position?.x,0),_=et($?$[13]:q?.position?.y,0),z=et($?$[14]:q?.position?.z,0),V=Y-A,W=_-P,O=z-G,H=Math.hypot(V,W,O),B=Math.max(.01,Math.min(Math.PI/2,et(T.angle,Math.PI/3))),K=Math.max(0,Math.min(1,et(T.penumbra,0)));w.push({type:T.type,color:[T.color.r,T.color.g,T.color.b],intensity:T.intensity,position:[A,P,G],...T.type==="spot"?{direction:H>1e-6?[V/H,W/H,O/H]:[0,-1,0],outerConeAngle:B,innerConeAngle:Math.max(0,B*(1-K)),range:Math.max(0,et(T.distance,0))}:T.type==="point"?{range:Math.max(0,et(T.distance,0))}:{}})}});let x=[],S=new Set([e]),N=[];if(Array.isArray(e.children))for(let T=e.children.length-1;T>=0;T--)N.push({obj:e.children[T],parentKids:x});for(;N.length>0;){let{obj:T,parentKids:k}=N.pop();if(!T||typeof T!="object"||S.has(T))continue;S.add(T),T._bakeAuthorGeometry?.(),ot().materializeDeclarativeGeometry?.(T);let A=!!(T.userData&&(T.userData.xr&&typeof T.userData.xr=="object"&&Object.keys(T.userData.xr).length>0||T.userData.interactivity&&typeof T.userData.interactivity=="object"&&Object.keys(T.userData.interactivity).length>0)),P={name:T.name||(A?`Node_${n.length}`:"")},G=et(T.position?.x,0),q=et(T.position?.y,0),$=et(T.position?.z,0),Y=et(T.quaternion?.x,0),_=et(T.quaternion?.y,0),z=et(T.quaternion?.z,0),V=et(T.quaternion?.w,1),W=et(T.scale?.x,1),O=et(T.scale?.y,1),H=et(T.scale?.z,1);if((G||q||$)&&(P.translation=[G,q,$]),(Y||_||z||V!==1)&&(P.rotation=[Y,_,z,V]),(W!==1||O!==1||H!==1)&&(P.scale=[W,O,H]),T.visible===!1&&(P.extensions={...P.extensions||{},KHR_node_visibility:{visible:!1}},h.add("KHR_node_visibility")),T.userData&&Object.keys(T.userData).length>0&&(P.extras=JSON.parse(JSON.stringify(T.userData,(X,I)=>{if(!(X==="__proto__"||X==="prototype"||X==="constructor"))return typeof I=="function"?void 0:I})),T.userData.xr)){let X=Wr(T.userData.xr);P.extensions={...P.extensions||{},MOZ_hubs_components:X,ANDROID_xr_scenecore:X},ot().xrTraitSerializer?.gltfNode(P,T.userData.xr),h.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(T.geometry){let X=T.geometry,I=X.attributes.position;if(I&&I.count>0){let tt=[1/0,1/0,1/0],Z=[-1/0,-1/0,-1/0];for(let st=0;st<I.count;st++){let nt=I.getX(st),lt=I.getY(st),ht=I.getZ(st);nt<tt[0]&&(tt[0]=nt),nt>Z[0]&&(Z[0]=nt),lt<tt[1]&&(tt[1]=lt),lt>Z[1]&&(Z[1]=lt),ht<tt[2]&&(tt[2]=ht),ht>Z[2]&&(Z[2]=ht)}let at={attributes:{POSITION:p(I.array,"VEC3",34962,5126,I.count,tt,Z)}};if(X.attributes.normal&&(at.attributes.NORMAL=p(X.attributes.normal.array,"VEC3",34962,5126,X.attributes.normal.count)),X.attributes.uv&&(at.attributes.TEXCOORD_0=p(X.attributes.uv.array,"VEC2",34962,5126,X.attributes.uv.count)),X.index){let st=X.index.array instanceof Uint32Array;at.indices=p(X.index.array,"SCALAR",34963,st?5125:5123,X.index.count)}let J=Array.isArray(T.material)?T.material[0]:T.material;J&&(at.material=v(J));let it=T.userData?.variants;if(it&&typeof it=="object"){let st=new Map;for(let nt of Object.keys(it)){if(!nt||nt==="__proto__"||nt==="constructor"||nt==="prototype")continue;let lt=it[nt];if(!lt||typeof lt!="object")continue;let ht=M.indexOf(nt);if(ht===-1&&M.length<256&&(ht=M.length,M.push(nt)),ht===-1)continue;let At=v(lt),Ot=st.get(At);Ot||(Ot=[],st.set(At,Ot)),Ot.push(ht)}if(st.size>0){let nt=[];for(let[lt,ht]of st.entries())nt.push({material:lt,variants:ht});at.extensions={...at.extensions||{},KHR_materials_variants:{mappings:nt}},h.add("KHR_materials_variants")}}let rt=T;if(rt.isInstancedMesh&&typeof rt.count=="number"&&rt.count>0&&rt.instanceMatrix?.array){let st=Math.min(1e4,Math.floor(rt.count)),nt=rt.instanceMatrix.array,lt=new Float32Array(st*3),ht=new Float32Array(st*4),At=new Float32Array(st*3);for(let vt=0;vt<st;vt++){let{t:ze,r:ge,s:Be}=oi(nt,vt*16);lt[vt*3]=ze[0],lt[vt*3+1]=ze[1],lt[vt*3+2]=ze[2],ht[vt*4]=ge[0],ht[vt*4+1]=ge[1],ht[vt*4+2]=ge[2],ht[vt*4+3]=ge[3],At[vt*3]=Be[0],At[vt*3+1]=Be[1],At[vt*3+2]=Be[2]}let Ot={TRANSLATION:p(lt,"VEC3",0,5126,st),ROTATION:p(ht,"VEC4",0,5126,st),SCALE:p(At,"VEC3",0,5126,st)};if(rt.instanceColor?.array&&rt.instanceColor.array.length>=st*3){let vt=new Float32Array(rt.instanceColor.array.subarray(0,st*3));Ot._COLOR_0=p(vt,"VEC3",0,5126,st)}P.extensions={...P.extensions||{},EXT_mesh_gpu_instancing:{attributes:Ot}},h.add("EXT_mesh_gpu_instancing")}let gt=o.length;o.push({primitives:[at],name:T.name,...P.extras?{extras:P.extras}:{}}),P.mesh=gt}}let B=n.length;n.push(P),l.push(T),k.push(B);let K=T.children;if(Array.isArray(K)&&K.length>0){let X=[];P.children=X;for(let I=K.length-1;I>=0;I--)N.push({obj:K[I],parentKids:X})}}for(let T=0;T<n.length;T++){let k=n[T];k.children&&k.children.length===0?delete k.children:k.children&&k.children.length>0&&(k.extras?.xr?.lod||k.extensions?.ANDROID_xr_scenecore?.lod||l[T]?.isLOD)&&(k.extensions={...k.extensions||{},MSFT_lod:{ids:[...k.children]}},h.add("MSFT_lod"))}let F=t?.animateCallback||t?.animateFn||(typeof e.userData?.animate=="function"?e.userData.animate:typeof e.__animateFn=="function"?e.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0),E=[];if(typeof F=="function"&&l.length>0){let T=t?.duration??4,k=t?.fps??15,A=Math.max(2,Math.round(T*k)+1),P=new Float32Array(A),G=l.map(O=>[et(O.position?.x,0),et(O.position?.y,0),et(O.position?.z,0),et(O.quaternion?.x,0),et(O.quaternion?.y,0),et(O.quaternion?.z,0),et(O.quaternion?.w,1),et(O.scale?.x,1),et(O.scale?.y,1),et(O.scale?.z,1)]),q=l.map(()=>new Float32Array(A*3)),$=l.map(()=>new Float32Array(A*4)),Y=l.map(()=>new Float32Array(A*3));for(let O=0;O<A;O++){let H=O/(A-1)*T;P[O]=H;try{F(H)}catch{}for(let B=0;B<l.length;B++){let K=l[B];q[B][O*3]=et(K.position?.x,0),q[B][O*3+1]=et(K.position?.y,0),q[B][O*3+2]=et(K.position?.z,0);let X=et(K.quaternion?.x,0),I=et(K.quaternion?.y,0),tt=et(K.quaternion?.z,0),Z=et(K.quaternion?.w,1),at=Math.hypot(X,I,tt,Z)||1;if(X/=at,I/=at,tt/=at,Z/=at,O>0){let J=(O-1)*4,it=$[B];it[J]*X+it[J+1]*I+it[J+2]*tt+it[J+3]*Z<0&&(X=-X,I=-I,tt=-tt,Z=-Z)}$[B][O*4]=X,$[B][O*4+1]=I,$[B][O*4+2]=tt,$[B][O*4+3]=Z,Y[B][O*3]=et(K.scale?.x,1),Y[B][O*3+1]=et(K.scale?.y,1),Y[B][O*3+2]=et(K.scale?.z,1)}}for(let O=0;O<l.length;O++){let H=l[O],B=G[O];H.position?.set(B[0],B[1],B[2]),H.quaternion?.set(B[3],B[4],B[5],B[6]),H.scale?.set(B[7],B[8],B[9])}e.updateMatrixWorld(!0);let _=null,z=()=>(_===null&&(_=p(P,"SCALAR",0,5126,A,[0],[T])),_),V=[],W=[];for(let O=0;O<l.length;O++){let H=G[O],B=(X,I,tt)=>X.some((Z,at)=>Math.abs(Z-H[tt+at%I])>1e-4),K=(X,I,tt,Z)=>{X&&W.push({sampler:V.push({input:z(),interpolation:"LINEAR",output:p(I,tt,0,5126,A)})-1,target:{node:O,path:Z}})};K(B(q[O],3,0),q[O],"VEC3","translation"),K(B($[O],4,3),$[O],"VEC4","rotation"),K(B(Y[O],3,7),Y[O],"VEC3","scale")}W.length>0&&E.push({name:"ProceduralLoop",samplers:V,channels:W})}let L=Tr(n,o,e.userData),C=[],D=[],R=[];for(let T=0;T<n.length;T++){let k=n[T],A=li(k.extras?.xr);if(!A)continue;let{ae:P,src:G,preset:q,volume:$,loop:Y,isGlobal:_}=A,z=k.name||`Node_${T}`,V=D.length;D.push({name:`${z}_source`,gain:$,loop:Y,autoPlay:typeof P.autoplay=="boolean"?P.autoplay:!0,...G!==void 0?{audio:C.push({uri:G})-1}:{},...q?{extras:{preset:q,pitch:_t(P.pitch,.25,4,1)}}:{}});let W=R.length,O=_t(P.refDistance,.05,100,1),H=_t(P.coneInnerAngle,0,360,360),B=_t(P.coneOuterAngle,H,360,360);R.push({name:`${z}_emitter`,type:_?"global":"positional",gain:$,sources:[V],..._?{}:{positional:{distanceModel:P.distanceModel==="linear"||P.distanceModel==="exponential"?P.distanceModel:"inverse",refDistance:O,maxDistance:_t(P.maxDistance,O,500,Math.max(O,25)),rolloffFactor:_t(P.rolloffFactor,0,10,1),coneInnerAngle:+(H*Math.PI/180).toFixed(6),coneOuterAngle:+(B*Math.PI/180).toFixed(6),coneOuterGain:_t(P.coneOuterGain,0,1,0)}}}),k.extensions={...k.extensions||{},KHR_audio_emitter:{emitter:W}},h.add("KHR_audio_emitter")}let y={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:e.environmentIntensity}},scenes:[{nodes:x}],scene:0,nodes:n,meshes:o,materials:c,...g.length>0?{images:g}:{},...b.length>0?{samplers:b}:{},...u.length>0?{textures:u}:{},accessors:a,bufferViews:s,buffers:[{byteLength:r}],...E.length>0?{animations:E}:{},...L||h.size>0?{extensionsUsed:[...L?["KHR_interactivity"]:[],...h]}:{},...L||M.length>0||R.length>0?{extensions:{...L?{KHR_interactivity:L}:{},...M.length>0?{KHR_materials_variants:{variants:M.map(T=>({name:T}))}}:{},...R.length>0?{KHR_audio_emitter:{...C.length>0?{audio:C}:{},sources:D,emitters:R}}:{}}}:{}},U=new Uint8Array(r),j=0;for(let T of i)U.set(T,j),j+=T.byteLength;return[{gltf:y,bin:U.buffer,lights:w,environmentIntensity:e.environmentIntensity},l]}function Te(e){return new TextEncoder().encode(e)}function Re(e,t){let{gltf:i,bin:r}=te(e,t),s=JSON.stringify(i),a=Te(s),o=(4-a.byteLength%4)%4,n=a.byteLength+o,h=20+n+8+r.byteLength,l=new Uint8Array(h),c=new DataView(l.buffer);c.setUint32(0,1179937895,!0),c.setUint32(4,2,!0),c.setUint32(8,h,!0),c.setUint32(12,n,!0),c.setUint32(16,1313821514,!0),l.set(a,20);for(let g=0;g<o;g++)l[20+a.byteLength+g]=32;let f=20+n;return c.setUint32(f,r.byteLength,!0),c.setUint32(f+4,5130562,!0),l.set(new Uint8Array(r),f+8),l}function jr(e,t){let[i,r]=hi(e,t);return Ce(i,r)}function Ce(e,t){let i=[],r=e.gltf,s=ot().decoders.get("meshopt");s&&typeof s.decodeBufferViews=="function"&&s.decodeBufferViews(r,e);let a=e.bin,o=a instanceof ArrayBuffer?a:a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),n=r.accessors||[],h=r.bufferViews||[],l=r.materials||[],c=r.meshes||[],f=r.nodes||[],g=new Set,b=l.map((M,w)=>ni(g,ee(M?.name,`Material_${w}`)));function u(M){let w=n[M];if(!w)throw new Error(`Accessor ${M} not found`);let v=h[w.bufferView||0],m=(v.byteOffset||0)+(w.byteOffset||0),p=v.byteLength||0;return{acc:w,buffer:o.slice(m,m+p)}}function d(M,w,v,m){let p=[],x=c[M];if(!x)return p;let S=x.primitives||[];for(let N=0;N<S.length;N++){let F=S[N],E=F.attributes?.POSITION;if(E===void 0)continue;let{acc:L,buffer:C}=u(E),D=new Float32Array(C,0,L.count*3),R,y=F.attributes?.NORMAL;if(y!==void 0){let{acc:V,buffer:W}=u(y),O=new Float32Array(W,0,V.count*3);R=new Float32Array(O.length);for(let H=0;H<V.count;H++){let B=O[H*3],K=O[H*3+1],X=O[H*3+2],I=Math.hypot(B,K,X)||1;R[H*3]=B/I,R[H*3+1]=K/I,R[H*3+2]=X/I}}let U,j=F.attributes?.TEXCOORD_0;if(j!==void 0){let{acc:V,buffer:W}=u(j);U=new Float32Array(W,0,V.count*2)}let T;if(F.indices!==void 0){let{acc:V,buffer:W}=u(F.indices);T=V.componentType===5125?new Uint32Array(W,0,V.count):new Uint16Array(W,0,V.count);let O=L.count;for(let H of T)if(H>=O)throw new Error(`SecurityError: Index buffer value (${H}) out of vertex bounds [0, ${O}).`)}else{let V=L.count;T=V>65535?new Uint32Array(V):new Uint16Array(V);for(let W=0;W<V;W++)T[W]=W}let k="DefaultMaterial",A=[.8,.8,.8],P=.5,G=0,q=0,$=0,Y=1.5,_=1,z=[0,0,0];if(F.material!==void 0&&l[F.material]){let V=l[F.material];k=b[F.material]||`Material_${F.material}`;let W=V.pbrMetallicRoughness||{},O=(X,I)=>Array.isArray(X)&&X.length>=3?[X[0],X[1],X[2]]:I;A=O(W.baseColorFactor,[1,1,1]);let H=V.extras?.avgColor;Array.isArray(H)&&H.length>=3&&(A=[A[0]*H[0],A[1]*H[1],A[2]*H[2]]);let B=Array.isArray(W.baseColorFactor)&&typeof W.baseColorFactor[3]=="number"?W.baseColorFactor[3]:1;typeof W.roughnessFactor=="number"&&(P=W.roughnessFactor),typeof W.metallicFactor=="number"&&(G=W.metallicFactor),z=O(V.emissiveFactor,[0,0,0]);let K=V.extensions||{};K.KHR_materials_clearcoat&&(q=K.KHR_materials_clearcoat.clearcoatFactor??0,$=K.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),typeof K.KHR_materials_ior?.ior=="number"&&(Y=K.KHR_materials_ior.ior),_=B*(1-(K.KHR_materials_transmission?.transmissionFactor??0))}p.push({name:S.length>1?`${w}_p${N}`:w,positions:D,indices:T,normals:R,uvs:U,materialName:k,color:A,roughness:P,metallic:G,clearcoat:q,clearcoatRoughness:$,ior:Y,opacity:_,emissiveColor:z,xrTraits:v||x.extras?.xr,...m?{invisible:!0}:{}})}return p}if(f.length>0){let M=new Float32Array(0),w=new Uint16Array(0),v=(D,R)=>{if(D===void 0)return null;let{acc:y,buffer:U}=u(D);return new Float32Array(U,0,y.count*R)},m=(D,R)=>Array.isArray(D)&&D.length>=3?[et(D[0],R),et(D[1],R),et(D[2],R)]:[R,R,R],p=(D,R,y)=>D&&D.length>=(R+1)*3?[D[R*3],D[R*3+1],D[R*3+2]]:y,x=(D,R,y)=>D&&D.length>=(R+1)*4?[D[R*4],D[R*4+1],D[R*4+2],D[R*4+3]]:y,S=new Map,N=r.animations?.[0];if(N&&Array.isArray(N.channels)&&Array.isArray(N.samplers))for(let D of N.channels){let R=N.samplers[D?.sampler],y=D?.target?.node,U=D?.target?.path;if(!R||typeof y!="number"||R.input===void 0)continue;let j=S.get(y);j||(j={input:R.input},S.set(y,j)),U==="translation"?j.t=R.output:U==="rotation"?j.r=R.output:U==="scale"&&(j.s=R.output)}let F=r.scenes?.[r.scene??0]?.nodes??[];if(!Array.isArray(F)||F.length===0){let D=new Set;for(let R of f)if(Array.isArray(R?.children))for(let y of R.children)D.add(y);F=[];for(let R=0;R<f.length;R++)D.has(R)||F.push(R);F.length===0&&(F=[0])}let E=new Set,L=[],C=(D,R)=>{if(Array.isArray(D))for(let y=D.length-1;y>=0;y--)L.push({idx:D[y],out:R})};for(C(F,i);L.length>0;){let{idx:D,out:R}=L.pop();if(typeof D!="number"||D<0||D>=f.length||E.has(D))continue;E.add(D);let y=f[D];if(!y)continue;let U=[0,0,0],j=[0,0,0,1],T=[1,1,1];if(Array.isArray(y.matrix)&&y.matrix.length===16){let _=oi(y.matrix);U=_.t,j=_.r,T=_.s}else U=m(y.translation,0),Array.isArray(y.rotation)&&y.rotation.length>=4&&(j=[et(y.rotation[0],0),et(y.rotation[1],0),et(y.rotation[2],0),et(y.rotation[3],1)]),T=m(y.scale,1);let k,A=S.get(D);if(A){let _=v(A.input,1);if(_&&_.length>0){let z=v(A.t,3),V=v(A.r,4),W=v(A.s,3),O=Array.from(_),H=[],B=[],K=[];for(let X=0;X<_.length;X++)H.push(p(z,X,U)),B.push(x(V,X,j)),K.push(p(W,X,T));k={times:O,translations:H,rotations:B,scales:K}}}let P=Array.isArray(y.children)?y.children:[],G=typeof y.mesh=="number"&&y.mesh>=0&&y.mesh<c.length,q=t?.[D]?.userData?.xr??y.extras?.xr;if(!G&&P.length===0&&(y.camera!==void 0||y.extensions?.KHR_lights_punctual||!y.name&&!y.extras&&!q&&!k))continue;let $=(_,z,V)=>({name:_,positions:M,indices:w,isXform:!0,xrTraits:q,timeSamples:k,translation:U,rotation:j,scale:T,children:z,...V?{invisible:!0}:{}}),Y=y.visible===!1||y.extensions?.KHR_node_visibility?.visible===!1||t?.[D]?.visible===!1;if(G){let _=y.name||c[y.mesh]?.name||`Mesh_${D}`,z=d(y.mesh,_,q,Y),V=y.extensions?.EXT_mesh_gpu_instancing?.attributes;if(V&&typeof V=="object"&&z.length>0){let W=v(V.TRANSLATION,3),O=v(V.ROTATION,4),H=v(V.SCALE,3),B=v(V._COLOR_0,3),K=Math.min(1e3,W?W.length/3:O?O.length/4:H?H.length/3:0);if(K>0){let X=[];for(let I=0;I<K;I++){let tt=p(W,I,[0,0,0]),Z=x(O,I,[0,0,0,1]),at=p(H,I,[1,1,1]);for(let J of z){let it=J.color||[.8,.8,.8],rt=B&&B.length>=(I+1)*3;X.push({...J,name:`${J.name}_${I}`,materialName:rt?`${J.materialName}_inst_${I}`:J.materialName,color:rt?[it[0]*B[I*3],it[1]*B[I*3+1],it[2]*B[I*3+2]]:J.color,translation:tt,rotation:Z,scale:at})}}C(P,X),R.push($(_,X,Y));continue}}if(z.length===1)z[0].translation=U,z[0].rotation=j,z[0].scale=T,z[0].timeSamples=k,P.length>0&&(z[0].children=[],C(P,z[0].children)),R.push(z[0]);else{let W=[...z];C(P,W),R.push($(_,W,Y))}}else{let _=[];C(P,_),R.push($(y.name||`Group_${D}`,_,Y))}}}else for(let M=0;M<c.length;M++){let w=c[M].name||`Mesh_${M}`;i.push(...d(M,w,c[M].extras?.xr))}return i}function ee(e,t){if(!e||typeof e!="string")return t;let i=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(i)&&(i="_"+i),i||t}function Pe(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function pt(e){if(!Number.isFinite(e)||Math.abs(e)<1e-7)return"0";let t=Number(e.toFixed(5)).toString();return t.indexOf(".")===-1?`${t}.0`:t}var Rt=(e,t,i)=>`(${pt(e)}, ${pt(t)}, ${pt(i)})`,ui=(e,t,i,r)=>`(${pt(e)}, ${pt(t)}, ${pt(i)}, ${pt(r)})`;function ci(e){let t=e.length/3,i=new Array(t);for(let r=0;r<t;r++)i[r]=Rt(e[r*3],e[r*3+1],e[r*3+2]);return i.join(", ")}function Xr(e,t){let i=new Array(t);for(let r=0;r<t;r++)i[r]=`(${pt(e[r*2])}, ${pt(1-e[r*2+1])})`;return i.join(", ")}function qr(e){return Array.from(e).join(", ")}function Ee(e){let t=new Map,i=0,r=null,s=[...e];for(;s.length>0;){let u=s.pop();if(!u.isXform&&u.positions&&u.positions.length>0){let d=ee(u.materialName,"DefaultMaterial");t.has(d)||t.set(d,{color:u.color||[.8,.8,.8],roughness:u.roughness??.5,metallic:u.metallic??0,clearcoat:u.clearcoat??0,clearcoatRoughness:u.clearcoatRoughness??0,ior:u.ior??1.5,opacity:u.opacity??1,emissiveColor:u.emissiveColor||[0,0,0]})}if(u.timeSamples&&u.timeSamples.times.length>0){let d=u.timeSamples.times[u.timeSamples.times.length-1];d>i&&(i=d)}if(u.xrTraits?.anchor&&!r&&(r=u.xrTraits.anchor==="vertical"||u.xrTraits.anchor==="wall"?"vertical":"horizontal"),u.children)for(let d=u.children.length-1;d>=0;d--)s.push(u.children[d])}let a="";i>0&&(a=`startTimeCode = 0
|
|
252
|
+
endTimeCode = ${pt(i)}
|
|
254
253
|
timeCodesPerSecond = 1.0
|
|
255
|
-
`);let
|
|
254
|
+
`);let o="";r&&(o=`uniform token preliminary:anchoring:type = "plane"
|
|
256
255
|
uniform token preliminary:planeAnchoring:alignment = "${r}"
|
|
257
|
-
`);let
|
|
256
|
+
`);let n=`#usda 1.0
|
|
258
257
|
(
|
|
259
258
|
defaultPrim = "Root"
|
|
260
259
|
metersPerUnit = 1.0
|
|
261
260
|
upAxis = "Y"
|
|
262
|
-
${
|
|
261
|
+
${a})
|
|
263
262
|
|
|
264
263
|
def Xform "Root" (
|
|
265
264
|
kind = "component"
|
|
266
265
|
)
|
|
267
266
|
{
|
|
268
|
-
${
|
|
267
|
+
${o}def Scope "Materials"
|
|
269
268
|
{
|
|
270
|
-
`;for(let[
|
|
271
|
-
`,
|
|
272
|
-
`),
|
|
273
|
-
`),
|
|
274
|
-
`),(
|
|
275
|
-
`),
|
|
269
|
+
`;for(let[u,d]of t.entries()){let[M,w,v]=d.color,[m,p,x]=d.emissiveColor,S="";d.clearcoat>0&&(S+=`float inputs:clearcoat = ${pt(d.clearcoat)}
|
|
270
|
+
`,S+=`float inputs:clearcoatRoughness = ${pt(d.clearcoatRoughness)}
|
|
271
|
+
`),d.ior!==1.5&&(S+=`float inputs:ior = ${pt(d.ior)}
|
|
272
|
+
`),d.opacity<1&&(S+=`float inputs:opacity = ${pt(d.opacity)}
|
|
273
|
+
`),(m>0||p>0||x>0)&&(S+=`color3f inputs:emissiveColor = ${Rt(m,p,x)}
|
|
274
|
+
`),n+=`def Material "${u}"
|
|
276
275
|
{
|
|
277
276
|
def Shader "PBRShader"
|
|
278
277
|
{
|
|
279
278
|
uniform token info:id = "UsdPreviewSurface"
|
|
280
|
-
color3f inputs:diffuseColor =
|
|
281
|
-
float inputs:metallic = ${
|
|
282
|
-
float inputs:roughness = ${
|
|
283
|
-
${
|
|
279
|
+
color3f inputs:diffuseColor = ${Rt(M,w,v)}
|
|
280
|
+
float inputs:metallic = ${pt(d.metallic)}
|
|
281
|
+
float inputs:roughness = ${pt(d.roughness)}
|
|
282
|
+
${S}token outputs:surface
|
|
284
283
|
}
|
|
285
|
-
token outputs:surface.connect = </Root/Materials/${
|
|
284
|
+
token outputs:surface.connect = </Root/Materials/${u}/PBRShader.outputs:surface>
|
|
286
285
|
}
|
|
287
|
-
`}
|
|
286
|
+
`}n+=`}
|
|
288
287
|
def Scope "Meshes"
|
|
289
288
|
{
|
|
290
|
-
`;let
|
|
289
|
+
`;let h=(u,d,M)=>{let w=[];d&&w.push('"MaterialBindingAPI"');let v=!!(u?.rigidBody&&u.rigidBody!=="none"&&(typeof u.rigidBody!="object"||u.rigidBody.enabled!==!1)),m=!!(u?.physics&&u.physics!=="none"||v);m&&w.push(...v?['"PhysicsBodyAPI"','"PhysicsRigidBodyAPI"','"PhysicsCollisionAPI"','"PhysicsMassAPI"']:['"PhysicsBodyAPI"','"PhysicsCollisionAPI"']);let p=[];if(w.length>0&&p.push(`prepend apiSchemas = [${w.join(", ")}]`),u){let E=ot().xrTraitSerializer?.usdLines(u,Pe)??[];if(!E.length)for(let L of["grab","billboard","follow","anchor","physics"]){let C=L==="follow"&&typeof u.follow=="object"?u.follow.mode??"head":u[L];C!==void 0&&E.push(`string ${L} = "${Pe(C)}"`)}E.length>0&&p.push(`customData = {
|
|
291
290
|
dictionary xr = {
|
|
292
|
-
${
|
|
291
|
+
${E.join(`
|
|
293
292
|
`)}
|
|
294
293
|
}
|
|
295
|
-
}`)
|
|
296
|
-
${
|
|
294
|
+
}`)}let x=p.length>0?` (
|
|
295
|
+
${p.join(`
|
|
297
296
|
`)}
|
|
298
|
-
)
|
|
299
|
-
{
|
|
300
|
-
|
|
301
|
-
bool physics:kinematicEnabled = ${_}
|
|
297
|
+
)`:"",S=M?`uniform token visibility = "invisible"
|
|
298
|
+
`:"";if(m){let E=u?.rigidBody??u?.physics,L=E?.body??E?.mode??E;S+=`bool physics:rigidBodyEnabled = true
|
|
299
|
+
bool physics:kinematicEnabled = ${L==="static"||L==="kinematic"}
|
|
302
300
|
bool physics:collisionEnabled = true
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
301
|
+
`,E?.mass>0&&Number.isFinite(E.mass)&&(S+=`float physics:mass = ${pt(E.mass)}
|
|
302
|
+
`)}let N=li(u),F=N?`def SpatialAudio "AudioEmitter"
|
|
303
|
+
{
|
|
304
|
+
${N.src?`asset inputs:file = @${Pe(N.src)}@
|
|
305
|
+
`:""}uniform token inputs:auralMode = "${N.isGlobal?"nonSpatial":"spatial"}"
|
|
306
|
+
uniform token inputs:playbackMode = "${N.loop?"loopFromStart":"onceFromStart"}"
|
|
307
|
+
double gain = ${pt(N.volume)}
|
|
308
|
+
}
|
|
309
|
+
`:"";return{header:x,body:S,tail:F}},l=u=>{if(u.timeSamples&&u.timeSamples.times.length>0){let p=u.timeSamples,x=(E,L,C)=>p.times.map((D,R)=>`${pt(D)}: ${C(E?.[R]||L)}`).join(", "),S=x(p.translations,[0,0,0],E=>Rt(E[0],E[1],E[2])),N=x(p.rotations,[0,0,0,1],E=>{let L=Math.hypot(E[0],E[1],E[2],E[3])||1;return ui(E[3]/L,E[0]/L,E[1]/L,E[2]/L)}),F=x(p.scales,[1,1,1],E=>Rt(E[0],E[1],E[2]));return`double3 xformOp:translate.timeSamples = { ${S} }
|
|
310
|
+
quatf xformOp:orient.timeSamples = { ${N} }
|
|
311
|
+
double3 xformOp:scale.timeSamples = { ${F} }
|
|
306
312
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:orient", "xformOp:scale"]
|
|
307
|
-
`}
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
313
|
+
`}let d=[],M="",w=u.translation;w&&(Math.abs(w[0])>1e-7||Math.abs(w[1])>1e-7||Math.abs(w[2])>1e-7)&&(M+=`double3 xformOp:translate = ${Rt(w[0],w[1],w[2])}
|
|
314
|
+
`,d.push('"xformOp:translate"'));let v=u.rotation;if(v){let p=Math.hypot(v[0],v[1],v[2],v[3])||1,x=v[0]/p,S=v[1]/p,N=v[2]/p,F=v[3]/p;(1-Math.abs(F)>1e-7||Math.hypot(x,S,N)>1e-7)&&(M+=`quatf xformOp:orient = ${ui(F,x,S,N)}
|
|
315
|
+
`,d.push('"xformOp:orient"'))}let m=u.scale;return m&&(Math.abs(m[0]-1)>1e-7||Math.abs(m[1]-1)>1e-7||Math.abs(m[2]-1)>1e-7)&&(M+=`float3 xformOp:scale = ${Rt(m[0],m[1],m[2])}
|
|
316
|
+
`,d.push('"xformOp:scale"')),d.length>0&&(M+=`uniform token[] xformOpOrder = [${d.join(", ")}]
|
|
317
|
+
`),M},c=u=>{let d=u.positions.length/3,M=1/0,w=1/0,v=1/0,m=-1/0,p=-1/0,x=-1/0;for(let L=0;L<d;L++){let C=u.positions[L*3],D=u.positions[L*3+1],R=u.positions[L*3+2];C<M&&(M=C),C>m&&(m=C),D<w&&(w=D),D>p&&(p=D),R<v&&(v=R),R>x&&(x=R)}isFinite(M)||(M=w=v=-1,m=p=x=1);let S=Math.floor(u.indices.length/3),N=ee(u.materialName,"DefaultMaterial"),F=S>0?S===1?"3":"3, ".repeat(S-1)+"3":"",E=`float3[] extent = [${Rt(M,w,v)}, ${Rt(m,p,x)}]
|
|
318
|
+
int[] faceVertexCounts = [${F}]
|
|
319
|
+
int[] faceVertexIndices = [${qr(u.indices)}]
|
|
320
|
+
point3f[] points = [${ci(u.positions)}]
|
|
321
|
+
`;return u.normals&&u.normals.length===u.positions.length&&(E+=`normal3f[] normals = [${ci(u.normals)}] (
|
|
312
322
|
interpolation = "vertex"
|
|
313
323
|
)
|
|
314
|
-
`),u.uvs&&u.uvs.length===
|
|
324
|
+
`),u.uvs&&u.uvs.length===d*2&&(E+=`texCoord2f[] primvars:st = [${Xr(u.uvs,d)}] (
|
|
315
325
|
interpolation = "vertex"
|
|
316
326
|
)
|
|
317
|
-
`),
|
|
318
|
-
}
|
|
319
|
-
`
|
|
327
|
+
`),E+=`rel material:binding = </Root/Materials/${N}>
|
|
328
|
+
`,E},f=new Set,g=[];for(let u=e.length-1;u>=0;u--)g.push({node:e[u],siblings:f});let b=0;for(;g.length>0;){let u=g.pop();if(u.close){n+=`}
|
|
329
|
+
`;continue}let{node:d,siblings:M}=u,w=!!(d.isXform||d.positions.length===0),v=ni(M,ee(d.name,w?`Group_${b}`:`Mesh_${b}`));b++;let m=d.children||[];if(w){let p=h(d.xrTraits,!1,d.invisible);n+=`def Xform "${v}"${p.header}
|
|
330
|
+
{
|
|
331
|
+
${p.body}${l(d)}${p.tail}`,g.push({close:!0});let x=new Set;for(let S=m.length-1;S>=0;S--)g.push({node:m[S],siblings:x})}else if(m.length>0){let p=h(d.xrTraits,!1,d.invisible),x=`${v}_mesh`;n+=`def Xform "${v}"${p.header}
|
|
332
|
+
{
|
|
333
|
+
${p.body}${l(d)}${p.tail}`,n+=`def Mesh "${x}" (
|
|
334
|
+
prepend apiSchemas = ["MaterialBindingAPI"]
|
|
335
|
+
)
|
|
336
|
+
{
|
|
337
|
+
${c(d)}}
|
|
338
|
+
`,g.push({close:!0});let S=new Set([x]);for(let N=m.length-1;N>=0;N--)g.push({node:m[N],siblings:S})}else{let p=h(d.xrTraits,!0,d.invisible);n+=`def Mesh "${v}"${p.header}
|
|
339
|
+
{
|
|
340
|
+
${p.body}${l(d)}${c(d)}${p.tail}}
|
|
341
|
+
`}}return n+=`}
|
|
320
342
|
}
|
|
321
|
-
`,o}function Yn(n,e){if(n&&typeof n.traverse=="function"){let i=Br(n,e);return Ot(i)}let t=Ae(n),r=$n(t);return Ot(r)}var rt=null;function qn(n){if(!rt){rt=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let i=0;i<8;i++)r=r&1?3988292384^r>>>1:r>>>1;rt[t]=r}}let e=4294967295;for(let t=0;t<n.length;t++)e=rt[(e^n[t])&255]^e>>>8;return(e^4294967295)>>>0}function Bt(n){let e=[],t=0,r=[];for(let l of n){let m=it(l.filename),h=qn(l.data),y=l.data.length,b=30+m.length,d=t+b,g=0,T=d%64;T!==0&&(g=64-T);let P=new Uint8Array(b+g),f=new DataView(P.buffer);f.setUint32(0,67324752,!0),f.setUint16(4,20,!0),f.setUint16(6,0,!0),f.setUint16(8,0,!0),f.setUint16(10,0,!0),f.setUint16(12,0,!0),f.setUint32(14,h,!0),f.setUint32(18,y,!0),f.setUint32(22,y,!0),f.setUint16(26,m.length,!0),f.setUint16(28,g,!0),P.set(m,30),g>0&&P.fill(0,30+m.length),e.push({offset:t,size:y,crc:h,filenameBytes:m,entry:l}),r.push(P),r.push(l.data),t+=P.length+l.data.length}let i=t;for(let l of e){let m=new Uint8Array(46+l.filenameBytes.length),h=new DataView(m.buffer);h.setUint32(0,33639248,!0),h.setUint16(4,20,!0),h.setUint16(6,20,!0),h.setUint16(8,0,!0),h.setUint16(10,0,!0),h.setUint16(12,0,!0),h.setUint16(14,0,!0),h.setUint32(16,l.crc,!0),h.setUint32(20,l.size,!0),h.setUint32(24,l.size,!0),h.setUint16(28,l.filenameBytes.length,!0),h.setUint16(30,0,!0),h.setUint16(32,0,!0),h.setUint16(34,0,!0),h.setUint16(36,0,!0),h.setUint32(38,0,!0),h.setUint32(42,l.offset,!0),m.set(l.filenameBytes,46),r.push(m),t+=m.length}let s=t-i,o=new Uint8Array(22),c=new DataView(o.buffer);c.setUint32(0,101010256,!0),c.setUint16(4,0,!0),c.setUint16(6,0,!0),c.setUint16(8,e.length,!0),c.setUint16(10,e.length,!0),c.setUint32(12,s,!0),c.setUint32(16,i,!0),c.setUint16(20,0,!0),r.push(o),t+=22;let a=new Uint8Array(t),u=0;for(let l of r)a.set(l,u),u+=l.length;return a}function qe(n){let e=Yn(n),t=it(e);return Bt([{filename:"model.usda",data:t}])}function ot(n){let e=Ae(n),t=$n(e),r=Ot(t),i=it(r);return Bt([{filename:"model.usda",data:i}])}function at(n){return n&&typeof n.toUSDZ=="function"?n.toUSDZ():n&&typeof n.traverse=="function"?qe(n):ot(n)}function Ue(n){let e=at(n);return new Blob([e],{type:"model/vnd.usdz+zip"})}var Ht=class n{constructor(e=0,t=0){this.x=Number(e),this.y=Number(t)}set(e,t){return this.x=Number(e),this.y=Number(t),this}clone(){return new n(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}sub(e){return this.x-=e.x,this.y-=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}},le=class n{constructor(e=0,t=0,r=0){this.x=Number(e),this.y=Number(t),this.z=Number(r)}set(e,t,r){return this.x=Number(e),this.y=Number(t),this.z=Number(r),this}clone(){return new n(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}length(){return Math.hypot(this.x,this.y,this.z)}normalize(){let e=this.length();return e>1e-5&&(this.x/=e,this.y/=e,this.z/=e),this}cross(e){let t=this.y*e.z-this.z*e.y,r=this.z*e.x-this.x*e.z,i=this.x*e.y-this.y*e.x;return this.x=t,this.y=r,this.z=i,this}crossVectors(e,t){let r=e.x,i=e.y,s=e.z,o=t.x,c=t.y,a=t.z;return this.x=i*a-s*c,this.y=s*o-r*a,this.z=r*c-i*o,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y,this.z-e.z)}applyMatrix4(e){let t=this.x,r=this.y,i=this.z,s=e.elements,o=1/(s[3]*t+s[7]*r+s[11]*i+s[15]);return this.x=(s[0]*t+s[4]*r+s[8]*i+s[12])*o,this.y=(s[1]*t+s[5]*r+s[9]*i+s[13])*o,this.z=(s[2]*t+s[6]*r+s[10]*i+s[14])*o,this}},Gt=class{constructor(e=0,t=0,r=0,i=1){this.x=Number(e),this.y=Number(t),this.z=Number(r),this.w=Number(i)}set(e,t,r,i){return this.x=Number(e),this.y=Number(t),this.z=Number(r),this.w=Number(i),this}},lt=class n{constructor(e=0,t=0,r=0,i="XYZ"){this._onChangeCallback=null;this._x=Number(e),this._y=Number(t),this._z=Number(r),this.order=i}get x(){return this._x}set x(e){this._x=Number(e),this._onChangeCallback?.()}get y(){return this._y}set y(e){this._y=Number(e),this._onChangeCallback?.()}get z(){return this._z}set z(e){this._z=Number(e),this._onChangeCallback?.()}set(e,t,r,i=this.order){return this._x=Number(e),this._y=Number(t),this._z=Number(r),this.order=i,this._onChangeCallback?.(),this}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this.order=e.order,this._onChangeCallback?.(),this}clone(){return new n(this._x,this._y,this._z,this.order)}_onChange(e){return this._onChangeCallback=e,this}},ht=class n{constructor(e=0,t=0,r=0,i=1){this._onChangeCallback=null;this._x=Number(e),this._y=Number(t),this._z=Number(r),this._w=Number(i)}get x(){return this._x}set x(e){this._x=Number(e),this._onChangeCallback?.()}get y(){return this._y}set y(e){this._y=Number(e),this._onChangeCallback?.()}get z(){return this._z}set z(e){this._z=Number(e),this._onChangeCallback?.()}get w(){return this._w}set w(e){this._w=Number(e),this._onChangeCallback?.()}set(e,t,r,i){return this._x=Number(e),this._y=Number(t),this._z=Number(r),this._w=Number(i),this._onChangeCallback?.(),this}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback?.(),this}clone(){return new n(this._x,this._y,this._z,this._w)}setFromEuler(e,t=!0){let r=e.x,i=e.y,s=e.z,o=Math.cos(r/2),c=Math.cos(i/2),a=Math.cos(s/2),u=Math.sin(r/2),l=Math.sin(i/2),m=Math.sin(s/2);return this._x=u*c*a+o*l*m,this._y=o*l*a-u*c*m,this._z=o*c*m+u*l*a,this._w=o*c*a-u*l*m,t&&this._onChangeCallback?.(),this}setFromAxisAngle(e,t){let r=t/2,i=Math.sin(r);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(r),this._onChangeCallback?.(),this}multiply(e){return this.multiplyQuaternions(this,e)}multiplyQuaternions(e,t){let r=e.x,i=e.y,s=e.z,o=e.w,c=t.x,a=t.y,u=t.z,l=t.w;return this._x=r*l+o*c+i*u-s*a,this._y=i*l+o*a+s*c-r*u,this._z=s*l+o*u+r*a-i*c,this._w=o*l-r*c-i*a-s*u,this._onChangeCallback?.(),this}_onChange(e){return this._onChangeCallback=e,this}},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 ae(this.elements,e.elements,t.elements),this}lookAt(e,t,r){return Fe(this.elements,[e.x,e.y,e.z],[t.x,t.y,t.z],[r.x,r.y,r.z]),this}makeRotationFromQuaternion(e){let t=new le(0,0,0),r=new le(1,1,1);return this.compose(t,e,r)}makeTranslation(e,t,r){return this.identity(),this.elements[12]=Number(e),this.elements[13]=Number(t),this.elements[14]=Number(r),this}makeScale(e,t,r){return this.identity(),this.elements[0]=Number(e),this.elements[5]=Number(t),this.elements[10]=Number(r),this}},Xt=class{constructor(){this.elements=new Float32Array([1,0,0,0,1,0,0,0,1])}identity(){let e=this.elements;return e.fill(0),e[0]=1,e[4]=1,e[8]=1,this}getNormalMatrix(e){return ye(this.elements,e.elements),this}},xe=class n{constructor(e,t,r){this.r=1;this.g=1;this.b=1;e!==void 0&&(t!==void 0&&r!==void 0?this.setRGB(e,t,r):this.set(e))}set(e){if(typeof e=="number")this.setHex(e);else if(typeof e=="string")if(e.startsWith("#")){let t=parseInt(e.slice(1),16);this.setHex(t)}else e==="red"?this.setRGB(1,0,0):e==="green"?this.setRGB(0,1,0):e==="blue"?this.setRGB(0,0,1):e==="white"?this.setRGB(1,1,1):e==="black"&&this.setRGB(0,0,0);else e&&typeof e=="object"&&"r"in e&&(this.r=Number(e.r),this.g=Number(e.g),this.b=Number(e.b));return this}setHex(e){let t=Math.floor(e);return this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(t&255)/255,this}setRGB(e,t,r){return this.r=Number(e),this.g=Number(t),this.b=Number(r),this}getHex(){return Math.round(Math.max(0,Math.min(1,this.r))*255)<<16|Math.round(Math.max(0,Math.min(1,this.g))*255)<<8|Math.round(Math.max(0,Math.min(1,this.b))*255)}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}clone(){return new n(this.r,this.g,this.b)}},Hr={degToRad:n=>n*Math.PI/180,radToDeg:n=>n*180/Math.PI,clamp:(n,e,t)=>Math.max(e,Math.min(t,n)),lerp:(n,e,t)=>n+(e-n)*t,generateUUID:()=>Math.random().toString(36).substring(2,15),randFloat:(n,e)=>n+Math.random()*(e-n)},J=class{constructor(e,t){this.needsUpdate=!1;if(typeof t!="number"||!Number.isInteger(t)||t<1||t>16)throw new Error(`SecurityError: BufferAttribute itemSize must be an integer in [1, 16]. Received: ${String(t)}`);Array.isArray(e)?this.array=new Float32Array(e):this.array=e,this.itemSize=t;let r=this.array?this.array.length:0;if(!Number.isFinite(r)||r<0)throw new Error(`SecurityError: BufferAttribute array has a non-finite length: ${String(r)}`);this.count=Math.floor(r/t)}getX(e){return this.array[e*this.itemSize]}getY(e){return this.array[e*this.itemSize+1]}getZ(e){return this.array[e*this.itemSize+2]}setX(e,t){return this.array[e*this.itemSize]=t,this.needsUpdate=!0,this}setY(e,t){return this.array[e*this.itemSize+1]=t,this.needsUpdate=!0,this}setZ(e,t){return this.array[e*this.itemSize+2]=t,this.needsUpdate=!0,this}setXYZ(e,t,r,i){let s=e*this.itemSize;return this.array[s]=t,this.array[s+1]=r,this.array[s+2]=i,this.needsUpdate=!0,this}},Wt=class extends J{constructor(e,t){super(e instanceof Float32Array?e:new Float32Array(e),t)}},$t=class extends J{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},Yt=class extends J{constructor(e,t){super(e instanceof Uint32Array?e:new Uint32Array(e),t)}},ge=class{constructor(){this.name="";this.attributes={};this.index=null;this.boundingBox=null}setAttribute(e,t){return this.attributes[e]=t,this}getAttribute(e){return this.attributes[e]}setIndex(e){if(e instanceof J)this.index=e;else if(Array.isArray(e)){let t=e.length,r=0;for(let s=0;s<t;s++)e[s]>r&&(r=e[s]);let i=r>65535?new Uint32Array(t):new Uint16Array(t);for(let s=0;s<t;s++)i[s]=e[s];this.index=new J(i,1)}else e&&e.buffer&&(this.index=new J(e,1));return this}computeVertexNormals(){let e=this.attributes.position;if(!e)return this;let t=e.count,r=new Float32Array(t*3),i=new le,s=new le,o=new le,c=new le,a=new le;if(this.index){let u=this.index.array;for(let l=0;l<u.length;l+=3){let m=u[l],h=u[l+1],y=u[l+2];i.set(e.getX(m),e.getY(m),e.getZ(m)),s.set(e.getX(h),e.getY(h),e.getZ(h)),o.set(e.getX(y),e.getY(y),e.getZ(y)),c.subVectors(o,s),a.subVectors(i,s),c.cross(a).normalize();for(let b of[m,h,y])r[b*3]+=c.x,r[b*3+1]+=c.y,r[b*3+2]+=c.z}}else for(let u=0;u<t;u+=3){i.set(e.getX(u),e.getY(u),e.getZ(u)),s.set(e.getX(u+1),e.getY(u+1),e.getZ(u+1)),o.set(e.getX(u+2),e.getY(u+2),e.getZ(u+2)),c.subVectors(o,s),a.subVectors(i,s),c.cross(a).normalize();for(let l=0;l<3;l++)r[(u+l)*3]=c.x,r[(u+l)*3+1]=c.y,r[(u+l)*3+2]=c.z}for(let u=0;u<t;u++){let l=r[u*3],m=r[u*3+1],h=r[u*3+2],y=Math.hypot(l,m,h)||1;r[u*3]=l/y,r[u*3+1]=m/y,r[u*3+2]=h/y}return this.setAttribute("normal",new J(r,3)),this}setFromBuffers(e,t,r,i){this.setAttribute("position",new J(e instanceof Float32Array?e:new Float32Array(e),3)),this.setAttribute("normal",new J(t instanceof Float32Array?t:new Float32Array(t),3)),this.setAttribute("uv",new J(r instanceof Float32Array?r:new Float32Array(r),2)),this.setIndex(i)}computeBoundingBox(){let e=this.attributes.position,t=new le(1/0,1/0,1/0),r=new le(-1/0,-1/0,-1/0);if(e&&e.count>0)for(let i=0;i<e.count;i++){let s=e.getX(i),o=e.getY(i),c=e.getZ(i);s<t.x&&(t.x=s),o<t.y&&(t.y=o),c<t.z&&(t.z=c),s>r.x&&(r.x=s),o>r.y&&(r.y=o),c>r.z&&(r.z=c)}else t.set(0,0,0),r.set(0,0,0);return this.boundingBox={min:t,max:r},this.boundingBox}center(){let e=this.computeBoundingBox(),t=(e.min.x+e.max.x)*.5,r=(e.min.y+e.max.y)*.5,i=(e.min.z+e.max.z)*.5,s=this.attributes.position;if(s&&s.count>0){for(let o=0;o<s.count;o++)s.setXYZ(o,s.getX(o)-t,s.getY(o)-r,s.getZ(o)-i);this.computeBoundingBox()}return this}dispose(){}},mt=class extends ge{constructor(e=1,t=1,r=1){super();let i=e/2,s=t/2,o=r/2,c=[-i,-s,o,i,-s,o,i,s,o,-i,s,o,i,-s,-o,-i,-s,-o,-i,s,-o,i,s,-o,-i,s,o,i,s,o,i,s,-o,-i,s,-o,-i,-s,-o,i,-s,-o,i,-s,o,-i,-s,o,i,-s,o,i,-s,-o,i,s,-o,i,s,o,-i,-s,-o,-i,-s,o,-i,s,o,-i,s,-o],a=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0],u=[0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1],l=[];for(let m=0;m<6;m++){let h=m*4;l.push(h,h+1,h+2,h,h+2,h+3)}this.setAttribute("position",new J(new Float32Array(c),3)),this.setAttribute("normal",new J(new Float32Array(a),3)),this.setAttribute("uv",new J(new Float32Array(u),2)),this.setIndex(l)}},qt=class extends ge{constructor(e=1,t=1){super();let r=e/2,i=t/2,s=[-r,i,0,r,i,0,-r,-i,0,r,-i,0],o=[0,0,1,0,0,1,0,0,1,0,0,1],c=[0,1,1,1,0,0,1,0],a=[0,2,1,2,3,1];this.setAttribute("position",new J(new Float32Array(s),3)),this.setAttribute("normal",new J(new Float32Array(o),3)),this.setAttribute("uv",new J(new Float32Array(c),2)),this.setIndex(a)}},dt=class extends ge{constructor(e=1,t=16,r=12){super(),t=Math.max(3,Math.floor(t)),r=Math.max(2,Math.floor(r));let i=[],s=[],o=[],c=[],a=[];for(let u=0;u<=r;u++){let l=[],m=u/r;for(let h=0;h<=t;h++){let y=h/t,b=y*Math.PI*2,d=m*Math.PI,g=-e*Math.cos(b)*Math.sin(d),T=e*Math.cos(d),P=e*Math.sin(b)*Math.sin(d);i.push(g,T,P);let f=Math.hypot(g,T,P)||1;s.push(g/f,T/f,P/f),o.push(y,1-m),l.push(i.length/3-1)}a.push(l)}for(let u=0;u<r;u++)for(let l=0;l<t;l++){let m=a[u][l+1],h=a[u][l],y=a[u+1][l],b=a[u+1][l+1];u!==0&&c.push(m,h,b),u!==r-1&&c.push(h,y,b)}this.setAttribute("position",new J(new Float32Array(i),3)),this.setAttribute("normal",new J(new Float32Array(s),3)),this.setAttribute("uv",new J(new Float32Array(o),2)),this.setIndex(c)}},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,y=l===0?u:-u;for(let b=0;b<=i;b++){let d=b/i,g=d*Math.PI*2,T=Math.sin(g),P=Math.cos(g);s.push(h*T,y,h*P),o.push(T,0,P),c.push(d,1-m)}}for(let l=0;l<i;l++){let m=l,h=l+i+1,y=l+i+2,b=l+1;a.push(m,h,b,h,y,b)}if(e>0){let l=s.length/3;s.push(0,u,0),o.push(0,1,0),c.push(.5,.5);let m=s.length/3;for(let h=0;h<=i;h++){let y=h/i*Math.PI*2,b=Math.sin(y),d=Math.cos(y);s.push(e*b,u,e*d),o.push(0,1,0),c.push(d*.5+.5,b*.5+.5)}for(let h=0;h<i;h++)a.push(l,m+h,m+h+1)}if(t>0){let l=s.length/3;s.push(0,-u,0),o.push(0,-1,0),c.push(.5,.5);let m=s.length/3;for(let h=0;h<=i;h++){let y=h/i*Math.PI*2,b=Math.sin(y),d=Math.cos(y);s.push(t*b,-u,t*d),o.push(0,-1,0),c.push(d*.5+.5,1-(b*.5+.5))}for(let h=0;h<i;h++)a.push(l,m+h+1,m+h)}this.setAttribute("position",new J(new Float32Array(s),3)),this.setAttribute("normal",new J(new Float32Array(o),3)),this.setAttribute("uv",new J(new Float32Array(c),2)),this.setIndex(a)}},jt=class extends 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=32){super(),r=Math.max(3,Math.floor(r)),i=Math.max(3,Math.floor(i));let s=[],o=[],c=[],a=[];for(let u=0;u<=r;u++){let l=u/r*Math.PI*2;for(let m=0;m<=i;m++){let h=m/i*Math.PI*2,y=(e+t*Math.cos(l))*Math.cos(h),b=(e+t*Math.cos(l))*Math.sin(h),d=t*Math.sin(l);s.push(y,b,d);let g=e*Math.cos(h),T=e*Math.sin(h),P=y-g,f=b-T,R=d,p=Math.hypot(P,f,R)||1;o.push(P/p,f/p,R/p),c.push(m/i,u/r)}}for(let u=1;u<=r;u++)for(let l=1;l<=i;l++){let m=(i+1)*u+l-1,h=(i+1)*(u-1)+l-1,y=(i+1)*(u-1)+l,b=(i+1)*u+l;a.push(m,h,b,h,y,b)}this.setAttribute("position",new J(new Float32Array(s),3)),this.setAttribute("normal",new J(new Float32Array(o),3)),this.setAttribute("uv",new J(new Float32Array(c),2)),this.setIndex(a)}},Zt=class extends ge{constructor(e=1,t=.4,r=64,i=8,s=2,o=3){super(),r=Math.floor(r),i=Math.floor(i);let c=[],a=[],u=[],l=[],m=new le,h=new le,y=new le,b=new le,d=new le;function g(f,R){let p=Math.cos(R),M=Math.sin(R),_=o/s*R,w=e*(2+Math.cos(_))*.5;f.set(w*p,w*M,e*Math.sin(_)*.5)}let T=[];for(let f=0;f<=i;++f){let R=f/i*Math.PI*2;T.push(-t*Math.cos(R),t*Math.sin(R),f/i)}for(let f=0;f<=r;++f){let R=f/r,p=R*s*Math.PI*2;g(m,p),g(h,p+.01),y.subVectors(h,m).normalize(),b.addVectors(m,h).normalize(),d.crossVectors(y,b).normalize(),b.crossVectors(d,y).normalize();for(let M=0;M<=i;++M){let _=M*3,w=T[_],A=T[_+1],L=T[_+2],v=w*b.x+A*d.x,x=w*b.y+A*d.y,I=w*b.z+A*d.z;c.push(m.x+v,m.y+x,m.z+I);let S=Math.hypot(v,x,I)||1;a.push(v/S,x/S,I/S),u.push(R,L)}}let P=i+1;for(let f=1;f<=r;f++){let R=P*(f-1),p=R+P;for(let M=1;M<=i;M++){let _=R+(M-1),w=p+(M-1),A=p+M,L=R+M;l.push(_,w,L,w,A,L)}}this.setAttribute("position",new J(new Float32Array(c),3)),this.setAttribute("normal",new J(new Float32Array(a),3)),this.setAttribute("uv",new J(new Float32Array(u),2)),this.setIndex(l)}},ft=class{constructor(e=""){this.isTexture=!0;this.wrapS=10497;this.wrapT=10497;this.image=null;this.width=0;this.height=0;this.source=e,e&&typeof e=="object"&&(this.image=e)}dispose(){}},Jt=class{load(e,t){let r=new ft(e);return t?.(r),r}};function pe(n,e){return n!==void 0?Number(n):e}function Vt(n,e){return n!==void 0?!!n:e}var Me=class{constructor(e={}){this.name=e.name||"",this.color=new xe(e.color!==void 0?e.color:16777215),this.emissive=new xe(e.emissive!==void 0?e.emissive:0),this.emissiveIntensity=pe(e.emissiveIntensity,1),this.roughness=pe(e.roughness,.5),this.metalness=pe(e.metalness,.1),this.opacity=pe(e.opacity,1),this.transparent=Vt(e.transparent,!1),this.wireframe=Vt(e.wireframe,!1),this.side=pe(e.side,2),this.doubleSided=Vt(e.doubleSided,!0),this.map=e.map||null,this.clearcoat=pe(e.clearcoat,0),this.clearcoatRoughness=pe(e.clearcoatRoughness,0),this.sheen=pe(e.sheen,0),this.sheenColor=new xe(e.sheenColor!==void 0?e.sheenColor:0),this.sheenRoughness=pe(e.sheenRoughness,0),this.transmission=pe(e.transmission,0),this.thickness=pe(e.thickness,0),this.attenuationColor=new xe(e.attenuationColor!==void 0?e.attenuationColor:16777215),this.attenuationDistance=pe(e.attenuationDistance,1/0),this.ior=pe(e.ior,1.5),this.dispersion=pe(e.dispersion,0),this.iridescence=pe(e.iridescence,0),this.iridescenceIOR=pe(e.iridescenceIOR,1.3)}dispose(){}},Be=class extends Me{},Qt=class extends Me{},en=class extends Me{},tn=class extends Me{},nn=class extends Me{},we=class n{constructor(){this.name="";this.matrixAutoUpdate=!0;this.visible=!0;this.castShadow=!1;this.receiveShadow=!1;this.parent=null;this.children=[];this.userData={};this.position=new le,this.rotation=new lt,this.quaternion=new ht,this.scale=new le(1,1,1),this.matrix=new 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 le(e,t,r);this.updateMatrixWorld(!0);let s=new Oe;s.lookAt(this.position,i,new le(0,1,0));let o=s.elements,c=o[0],a=o[4],u=o[8],l=o[1],m=o[5],h=o[9],y=o[2],b=o[6],d=o[10],g=c+m+d;if(g>0){let T=.5/Math.sqrt(g+1);this.quaternion.set((b-h)*T,(u-y)*T,(l-a)*T,.25/T)}}},rn=class extends we{},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?(ve("unsupported geometry","BoxGeometry"),new mt(.5,.5,.5)):new ge,this.material=i instanceof Me?i:i?(ve("unsupported material","MeshStandardMaterial"),new Be({color:13421772})):new Be}};function tr(n){let e=Q().materializeDeclarativeGeometry;typeof e=="function"&&e(n)}var pt=1e4,bt=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>pt)throw new RangeError(`SecurityError: InstancedMesh count (${String(i)}) exceeds MAX_INSTANCES_PER_MESH (${pt})`);this.count=Math.floor(s);let o=new Float32Array(this.count*16);for(let c=0;c<this.count;c++){let a=c*16;o[a]=1,o[a+5]=1,o[a+10]=1,o[a+15]=1}this.instanceMatrix=new J(o,16)}setMatrixAt(t,r){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!r||!r.elements)return;let s=this.instanceMatrix.array,o=i*16;if(!(o+16>s.length))for(let c=0;c<16;c++){let a=Number(r.elements[c]);s[o+c]=Number.isFinite(a)?a:c%5===0?1:0}}getMatrixAt(t,r){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!r||!r.elements)return;let s=this.instanceMatrix.array,o=i*16;if(!(o+16>s.length))for(let c=0;c<16;c++)r.elements[c]=s[o+c]}setColorAt(t,r){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!r)return;if(!this.instanceColor||this.instanceColor.array.length<this.count*3){let c=new Float32Array(this.count*3);c.fill(1),this.instanceColor=new J(c,3)}let s=this.instanceColor.array,o=i*3;s[o]=Number.isFinite(r.r)?r.r:1,s[o+1]=Number.isFinite(r.g)?r.g:1,s[o+2]=Number.isFinite(r.b)?r.b:1}getColorAt(t,r){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!r)return;if(!this.instanceColor||this.instanceColor.array.length<(i+1)*3){r.setRGB(1,1,1);return}let s=this.instanceColor.array,o=i*3;r.setRGB(s[o],s[o+1],s[o+2])}dispose(){}},ze=class extends we{constructor(e=16777215,t=1){super(),this.color=new xe(e),this.intensity=Number(t),this.type="directional"}},yt=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"}},gt=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 le(0,0,0);this.fov=Number(t),this.aspect=Number(r),this.near=Number(i),this.far=Number(s)}},xt=class extends we{constructor(){super(...arguments);this.background=null;this.environmentIntensity=1}toCanvas3D(){return Se.validate(this),Ye(this)}toGLB(){return Se.validate(this),st(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=st,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 bt){let l=c("instance",a.count);(l<0||l>pt)&&o("INSTANCES",pt,l)}let u=a.geometry;if(u){let l=0;if(u.attributes.position&&(l=c("vertex",u.attributes.position.count),t+=l,t>1e5&&o("VERTICES",1e5,t)),u.index){let m=c("index",u.index.count);r+=m,r>3e5&&o("INDICES",3e5,r);let h=u.index.array;if(h&&l>0){let y=Math.min(m,h.length);for(let b=0;b<y;b++){let d=h[b];if(!Number.isFinite(d)||d<0||d>=l)throw new Error(`SecurityError: Index buffer value (${String(d)}) out of vertex bounds [0, ${l}).`)}}}}if(a.material){let l=a.material;l.map&&s.add(l.map),l.normalMap&&s.add(l.normalMap),l.roughnessMap&&s.add(l.roughnessMap)}}}),s.size>16&&o("TEXTURES",16,s.size);for(let a of s){let u=a,l=u.image,m=Number(l?.width??u.width??0)||0,h=Number(l?.height??u.height??0)||0;(!Number.isFinite(m)||!Number.isFinite(h)||m>2048||h>2048)&&o("TEXTURE_DIMENSION",2048,Math.max(m,h))}}},an=class{constructor(e={}){this.shadowMap={enabled:!1,type:0};this.capabilities={isWebGL2:!0,maxTextures:16};this.boundViewer=null;this.isSandboxed=!1;this.containerId="";this.hasInitialModelRendered=!1;this.domElement=e.canvas||(typeof document<"u"?document.createElement("canvas"):{}),e.viewer&&(this.boundViewer=e.viewer),e.container?.threeLiveViewer&&(this.boundViewer=e.container.threeLiveViewer),e.canvas?.parentElement?.threeLiveViewer&&(this.boundViewer=e.canvas.parentElement.threeLiveViewer);let t=typeof WorkerGlobalScope<"u"&&typeof self<"u"&&self instanceof WorkerGlobalScope;this.isSandboxed=e.isSandboxed||t,this.containerId=e.containerId||""}setSize(e,t){return this}setPixelRatio(e){return this}setClearColor(e,t=1){let r=new xe(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 ct=new Proxy(Xr,{get:(n,e)=>{if(e==="isProxy")return!0;if(!(e==="constructor"||e==="__proto__"||e==="prototype"))return e==="domElement"?typeof document<"u"?document.createElement("canvas"):{}:e==="shadowMap"?{enabled:!1,type:0}:e==="capabilities"?{isWebGL2:!0,maxTextures:16}:e===Symbol.toPrimitive?()=>0:ct},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>ct,construct:()=>ct}),Kn=(()=>{try{if(typeof document>"u")return null;let n=document.currentScript;return n?.src?n.src:n?.textContent&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(new Blob([n.textContent],{type:"text/javascript"})):null}catch{return null}})();function Ge(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function 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=Q().sandboxEngineSrc;if(n)return n;if(Kn)return Kn;try{if(typeof document>"u")return null;let e=Ge(),t=Array.from(document.querySelectorAll("script[src]"));for(let r of t){let i=r.src;if(!i)continue;let s=new URL(i,e).pathname;if(/(?:^|\/)(?:three|xr)-live[^/]*\.js$/.test(s)&&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=Q().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!!Q().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(M){a({type:"ERROR",nonce:r,message:String(M)})}let l=typeof t.importScripts=="function"?t.importScripts.bind(t):null,m=s,h=null;try{let M=i;if(typeof t.trustedTypes<"u"&&t.trustedTypes&&typeof t.trustedTypes.createPolicy=="function")try{let _={createScriptURL:function(A){if(A!==i&&(!s||A!==s))throw new TypeError("Disallowed worker importScripts URL");return A}};o&&(_.createScript=function(A){return String(A)});let w=t.trustedTypes.createPolicy("three-live#worker-boot",_);M=w.createScriptURL(i),s&&(m=w.createScriptURL(s)),o&&typeof w.createScript=="function"&&(h=w.createScript.bind(w))}catch{}l(M)}catch(M){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: '+(M&&M.message||M));return}let y=t.THREE;if(!y||typeof y.Scene!="function"){u('Sandbox loaded "'+i+'" but it did not install a THREE namespace. Point sandboxEngineSrc at an IIFE build (three-live.min.js), not an ES module build.');return}if(Array.isArray(e)){let M=t.__THREE_LIVE_REGISTRY__;for(let _=0;_<e.length;_++)if(typeof e[_]=="function")try{e[_](y,M)}catch{}}for(let M=0;M<c.length;M++){let _=c[M],w=t;for(;w&&w!==Object.prototype;){if(w!==t)try{delete w[_]}catch{}try{Object.defineProperty(w,_,{value:void 0,writable:!1,configurable:!1,enumerable:!1})}catch{}try{w=Object.getPrototypeOf(w)}catch{break}}}let b=Object.freeze({now:function(){return Date.now()}}),d=t;for(;d&&d!==Object.prototype;){if(d!==t)try{delete d.performance}catch{}try{Object.defineProperty(d,"performance",{value:b,writable:!1,configurable:!1,enumerable:!1})}catch{}try{d=Object.getPrototypeOf(d)}catch{break}}let g=["3D_MODEL_READY","3D_UPDATE_TRANSFORMS"],T=!1;function P(M,_){if(M.type==="3D_MODEL_READY"){if(T)return;T=!0}M.nonce=r,_&&_.length?a(M,_):a(M)}let f=function(M,_){if(!M||g.indexOf(M.type)===-1)throw new Error("Sandboxed scripts may only post Three-Live scene messages ("+g.join(", ")+").");P(M,_)},R=t;for(;R&&R!==Object.prototype;){if(R===t||Object.prototype.hasOwnProperty.call(R,"postMessage"))try{Object.defineProperty(R,"postMessage",{value:f,writable:!1,configurable:!1})}catch{}try{R=Object.getPrototypeOf(R)}catch{break}}let p=!1;t.onmessage=function(M){let _=M&&M.data;if(!(!_||_.nonce!==r)&&!(_.type!=="EXECUTE"&&_.type!=="EXECUTE_URL")&&!p){p=!0;try{let w=new y.Scene,A=new y.PerspectiveCamera(60,1,.1,1e3),L=new y.WebGLRenderer({isSandboxed:!0});if(_.type==="EXECUTE_URL"){if(!s||_.scriptUrl!==s||typeof l!="function"){u("SecurityError: Refusing to execute unapproved script URL inside sandbox worker.");return}let v=m||s,x=l;if(l=null,m=null,t.THREE=y,t.scene=w,t.camera=A,t.renderer=L,x(v),typeof t.__THREE_LIVE_SCENE__=="function"){let I=t.__THREE_LIVE_SCENE__(y,w,A,L);I&&typeof I.toGLB=="function"&&(w=I)}else t.scene&&typeof t.scene.toGLB=="function"&&(w=t.scene)}else{if(!o){u("SecurityError: Client-modified script compilation (Use Case 1) is disabled in this sandbox worker.");return}let v=h?(0,eval)(h(`(function (THREE, scene, camera, renderer) {
|
|
343
|
+
`,n}function Kr(e,t){if(e&&typeof e.traverse=="function"){let s=jr(e,t);return Ee(s)}let i=zt(e),r=Ce(i);return Ee(r)}var ie=null;function _e(e){if(!ie){ie=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;ie[i]=r}}let t=4294967295;for(let i=0;i<e.length;i++)t=ie[(t^e[i])&255]^t>>>8;return(t^4294967295)>>>0}function Yr(e){let t=[],i=0,r=[];for(let c of e){let f=Te(c.filename),g=_e(c.data),b=c.data.length,u=30+f.length,d=(i+u)%64,M=d!==0?64-d:0,w=new Uint8Array(u+M),v=new DataView(w.buffer);v.setUint32(0,67324752,!0),v.setUint16(4,20,!0),v.setUint32(14,g,!0),v.setUint32(18,b,!0),v.setUint32(22,b,!0),v.setUint16(26,f.length,!0),v.setUint16(28,M,!0),w.set(f,30),t.push({offset:i,size:b,crc:g,filenameBytes:f,entry:c}),r.push(w,c.data),i+=w.length+c.data.length}let s=i;for(let c of t){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,t.length,!0),n.setUint16(10,t.length,!0),n.setUint32(12,a,!0),n.setUint32(16,s,!0),r.push(o),i+=22;let h=new Uint8Array(i),l=0;for(let c of r)h.set(c,l),l+=c.length;return h}var mi=e=>Yr([{filename:"model.usda",data:Te(e)}]);function Ne(e){return mi(Kr(e))}function di(e){return mi(Ee(Ce(zt(e))))}function pi(e){return e&&typeof e.toUSDZ=="function"?e.toUSDZ():di(e)}function Le(e){let t=pi(e);return new Blob([t],{type:"model/vnd.usdz+zip"})}var Ct=class sr{constructor(t=0,i=0){this.x=Number(t),this.y=Number(i)}set(t,i){return this.x=Number(t),this.y=Number(i),this}clone(){return new sr(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}sub(t){return this.x-=t.x,this.y-=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divideScalar(t){return this.multiplyScalar(t?1/t:0)}setScalar(t){return this.set(t,t)}},Q=class ar{constructor(t=0,i=0,r=0){this.x=Number(t),this.y=Number(i),this.z=Number(r)}set(t,i,r){return this.x=Number(t),this.y=Number(i),this.z=Number(r),this}clone(){return new ar(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addVectors(t,i){return this.x=t.x+i.x,this.y=t.y+i.y,this.z=t.z+i.z,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subVectors(t,i){return this.x=t.x-i.x,this.y=t.y-i.y,this.z=t.z-i.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}divideScalar(t){return this.multiplyScalar(t?1/t:0)}setScalar(t){return this.set(t,t,t)}addScaledVector(t,i){return this.x+=t.x*i,this.y+=t.y*i,this.z+=t.z*i,this}length(){return Math.hypot(this.x,this.y,this.z)}normalize(){let t=this.length();return t>1e-5&&(this.x/=t,this.y/=t,this.z/=t),this}cross(t){let i=this.y*t.z-this.z*t.y,r=this.z*t.x-this.x*t.z,s=this.x*t.y-this.y*t.x;return this.x=i,this.y=r,this.z=s,this}crossVectors(t,i){let r=t.x,s=t.y,a=t.z,o=i.x,n=i.y,h=i.z;return this.x=s*h-a*n,this.y=a*o-r*h,this.z=r*n-s*o,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}distanceTo(t){return Math.hypot(this.x-t.x,this.y-t.y,this.z-t.z)}lerp(t,i){return this.lerpVectors(this,t,i)}lerpVectors(t,i,r){return this.x=t.x+(i.x-t.x)*r,this.y=t.y+(i.y-t.y)*r,this.z=t.z+(i.z-t.z)*r,this}applyMatrix4(t){let i=this.x,r=this.y,s=this.z,a=t.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}},Zr=class{constructor(e=0,t=0,i=0,r=1){this.x=Number(e),this.y=Number(t),this.z=Number(i),this.w=Number(r)}set(e,t,i,r){return this.x=Number(e),this.y=Number(t),this.z=Number(i),this.w=Number(r),this}},fi=class nr{constructor(t=0,i=0,r=0,s="XYZ"){this._onChangeCallback=null,this._x=Number(t),this._y=Number(i),this._z=Number(r),this.order=s}get x(){return this._x}set x(t){this._x=Number(t),this._onChangeCallback?.()}get y(){return this._y}set y(t){this._y=Number(t),this._onChangeCallback?.()}get z(){return this._z}set z(t){this._z=Number(t),this._onChangeCallback?.()}set(t,i,r,s=this.order){return this._x=Number(t),this._y=Number(i),this._z=Number(r),this.order=s,this._onChangeCallback?.(),this}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this.order=t.order,this._onChangeCallback?.(),this}clone(){return new nr(this._x,this._y,this._z,this.order)}_onChange(t){return this._onChangeCallback=t,this}},gi=class or{constructor(t=0,i=0,r=0,s=1){this._onChangeCallback=null,this._x=Number(t),this._y=Number(i),this._z=Number(r),this._w=Number(s)}get x(){return this._x}set x(t){this._x=Number(t),this._onChangeCallback?.()}get y(){return this._y}set y(t){this._y=Number(t),this._onChangeCallback?.()}get z(){return this._z}set z(t){this._z=Number(t),this._onChangeCallback?.()}get w(){return this._w}set w(t){this._w=Number(t),this._onChangeCallback?.()}set(t,i,r,s){return this._x=Number(t),this._y=Number(i),this._z=Number(r),this._w=Number(s),this._onChangeCallback?.(),this}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback?.(),this}clone(){return new or(this._x,this._y,this._z,this._w)}setFromEuler(t,i=!0){let r=t.x,s=t.y,a=t.z,o=Math.cos(r/2),n=Math.cos(s/2),h=Math.cos(a/2),l=Math.sin(r/2),c=Math.sin(s/2),f=Math.sin(a/2);return this._x=l*n*h+o*c*f,this._y=o*c*h-l*n*f,this._z=o*n*f+l*c*h,this._w=o*n*h-l*c*f,i&&this._onChangeCallback?.(),this}setFromAxisAngle(t,i){let r=i/2,s=Math.sin(r);return this.set(t.x*s,t.y*s,t.z*s,Math.cos(r))}normalize(){let t=Math.hypot(this._x,this._y,this._z,this._w);return t===0?this.set(0,0,0,1):this.set(this._x/t,this._y/t,this._z/t,this._w/t)}setFromUnitVectors(t,i){let r=t.dot(i)+1;return r<1e-6?(Math.abs(t.x)>Math.abs(t.z)?this.set(-t.y,t.x,0,0):this.set(0,-t.z,t.y,0)).normalize():this.set(t.y*i.z-t.z*i.y,t.z*i.x-t.x*i.z,t.x*i.y-t.y*i.x,r).normalize()}multiply(t){return this.multiplyQuaternions(this,t)}multiplyQuaternions(t,i){let r=t.x,s=t.y,a=t.z,o=t.w,n=i.x,h=i.y,l=i.z,c=i.w;return this._x=r*c+o*n+s*l-a*h,this._y=s*c+o*h+a*n-r*l,this._z=a*c+o*l+r*h-s*n,this._w=o*c-r*n-s*h-a*l,this._onChangeCallback?.(),this}_onChange(t){return this._onChangeCallback=t,this}},jt=class lr{constructor(){this.elements=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}identity(){let t=this.elements;return t.fill(0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,this}copy(t){return this.elements.set(t.elements),this}clone(){let t=new lr;return t.copy(this),t}compose(t,i,r){return xe(this.elements,[i.x,i.y,i.z,i.w],[t.x,t.y,t.z],[r.x,r.y,r.z]),this}multiply(t){return this.multiplyMatrices(this,t)}multiplyMatrices(t,i){return dt(this.elements,t.elements,i.elements),this}lookAt(t,i,r){return Jt(this.elements,[t.x,t.y,t.z],[i.x,i.y,i.z],[r.x,r.y,r.z]),this}makeRotationFromQuaternion(t){let i=new Q(0,0,0),r=new Q(1,1,1);return this.compose(i,t,r)}makeTranslation(t,i,r){return this.identity(),this.elements[12]=Number(t),this.elements[13]=Number(i),this.elements[14]=Number(r),this}makeScale(t,i,r){return this.identity(),this.elements[0]=Number(t),this.elements[5]=Number(i),this.elements[10]=Number(r),this}},Jr=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 Et(this.elements,e.elements),this}},wt=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,re=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,bi={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},Nt=class hr{constructor(t,i,r){this.r=1,this.g=1,this.b=1,t!==void 0&&(i!==void 0&&r!==void 0?this.setRGB(t,i,r):this.set(t))}set(t){return typeof t=="number"?this.setHex(t):typeof t=="string"?this.setStyle(t):(t&&typeof t=="object"&&"r"in t&&(this.r=Number(t.r),this.g=Number(t.g),this.b=Number(t.b)),this)}setStyle(t){let i=t.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 bi)this.setHex(bi[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=>wt(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(t,i,r){if(t=((Number(t)||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=wt(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(wt(o(t+1/3)),wt(o(t)),wt(o(t-1/3)))}lerp(t,i){let r=Number(i)||0;return this.r+=(t.r-this.r)*r,this.g+=(t.g-this.g)*r,this.b+=(t.b-this.b)*r,this}lerpColors(t,i,r){let s=Number(r)||0;return this.r=t.r+(i.r-t.r)*s,this.g=t.g+(i.g-t.g)*s,this.b=t.b+(i.b-t.b)*s,this}multiplyScalar(t){let i=Number(t)||0;return this.r*=i,this.g*=i,this.b*=i,this}setScalar(t){let i=Number(t)||0;return this.setRGB(i,i,i)}setHex(t){let i=Math.floor(t);return this.r=wt((i>>16&255)/255),this.g=wt((i>>8&255)/255),this.b=wt((i&255)/255),this}setRGB(t,i,r){return this.r=Number(t),this.g=Number(i),this.b=Number(r),this}convertSRGBToLinear(){return this.r=wt(this.r),this.g=wt(this.g),this.b=wt(this.b),this}convertLinearToSRGB(){return this.r=re(this.r),this.g=re(this.g),this.b=re(this.b),this}getHex(){let t=i=>Math.round(re(Math.max(0,Math.min(1,i)))*255);return t(this.r)<<16|t(this.g)<<8|t(this.b)}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b}clone(){return new hr(this.r,this.g,this.b)}},Qr={degToRad:e=>e*Math.PI/180,radToDeg:e=>e*180/Math.PI,clamp:(e,t,i)=>Math.max(t,Math.min(i,e)),lerp:(e,t,i)=>e+(t-e)*i,generateUUID:()=>Math.random().toString(36).substring(2,15),randFloat:(e,t)=>e+Math.random()*(t-e)},bt=class ur{constructor(t,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(t)?this.array=new Float32Array(t):this.array=t,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(t){return this.array[t*this.itemSize]}getY(t){return this.array[t*this.itemSize+1]}getZ(t){return this.array[t*this.itemSize+2]}setX(t,i){return this.array[t*this.itemSize]=i,this.needsUpdate=!0,this}setY(t,i){return this.array[t*this.itemSize+1]=i,this.needsUpdate=!0,this}setZ(t,i){return this.array[t*this.itemSize+2]=i,this.needsUpdate=!0,this}setXYZ(t,i,r,s){let a=t*this.itemSize;return this.array[a]=i,this.array[a+1]=r,this.array[a+2]=s,this.needsUpdate=!0,this}setUsage(t){return this}clone(){let t=this.array?.constructor||Float32Array;return new ur(new t(this.array),this.itemSize)}},ts=class extends bt{constructor(e,t){super(e instanceof Float32Array?e:new Float32Array(e),t)}},es=class extends bt{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},is=class extends bt{constructor(e,t){super(e instanceof Uint32Array?e:new Uint32Array(e),t)}},ft=class cr{constructor(){this.name="",this.attributes={},this.index=null,this.boundingBox=null}setAttribute(t,i){return this.attributes[t]=i,this}getAttribute(t){return this.attributes[t]}setIndex(t){if(t instanceof bt)this.index=t;else if(Array.isArray(t)){let i=0;for(let r of t)r>i&&(i=r);this.index=new bt(new(i>65535?Uint32Array:Uint16Array)(t),1)}else t&&t.buffer&&(this.index=new bt(t,1));return this}computeVertexNormals(){let t=this.attributes.position;if(!t)return this;let i=t.count,r=new Float32Array(i*3),s=new Q,a=new Q,o=new Q,n=new Q,h=new Q,l=this.index?.array,c=l?l.length:i;for(let f=0;f<c;f+=3){let g=l?l[f]:f,b=l?l[f+1]:f+1,u=l?l[f+2]:f+2;s.set(t.getX(g),t.getY(g),t.getZ(g)),a.set(t.getX(b),t.getY(b),t.getZ(b)),o.set(t.getX(u),t.getY(u),t.getZ(u)),n.subVectors(o,a),h.subVectors(s,a),n.cross(h).normalize();for(let d of[g,b,u])r[d*3]+=n.x,r[d*3+1]+=n.y,r[d*3+2]+=n.z}for(let f=0;f<i;f++){let g=r[f*3],b=r[f*3+1],u=r[f*3+2],d=Math.hypot(g,b,u)||1;r[f*3]=g/d,r[f*3+1]=b/d,r[f*3+2]=u/d}return this.setAttribute("normal",new bt(r,3)),this}setFromBuffers(t,i,r,s){this.setAttribute("position",new bt(t,3)),this.setAttribute("normal",new bt(i,3)),this.setAttribute("uv",new bt(r,2)),this.setIndex(s)}setFromPoints(t){let i=[];if(Array.isArray(t))for(let r of t)i.push(Number(r?.x)||0,Number(r?.y)||0,Number(r?.z)||0);return this.setAttribute("position",new bt(i,3))}computeBoundingBox(){let t=this.attributes.position,i=new Q(1/0,1/0,1/0),r=new Q(-1/0,-1/0,-1/0);if(t&&t.count>0)for(let s=0;s<t.count;s++){let a=t.getX(s),o=t.getY(s),n=t.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 t=this.computeBoundingBox();return this.translate(-(t.min.x+t.max.x)*.5,-(t.min.y+t.max.y)*.5,-(t.min.z+t.max.z)*.5)}_xform(t,i){let r=this.attributes.position;if(r){let s=r.array;for(let a=0;a<s.length;a+=3)t(s,a);r.needsUpdate=!0,i&&this.computeVertexNormals(),this.computeBoundingBox()}return this}translate(t=0,i=0,r=0){return this._xform((s,a)=>{s[a]+=t,s[a+1]+=i,s[a+2]+=r})}scale(t=1,i=1,r=1){return this._xform((s,a)=>{s[a]*=t,s[a+1]*=i,s[a+2]*=r},!0)}_rot(t,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 h=0;h<n.length;h+=3){let l=n[h+t],c=n[h+i];n[h+t]=l*s-c*a,n[h+i]=l*a+c*s}o.needsUpdate=!0}return this}rotateX(t){return this._rot(1,2,t)}rotateY(t){return this._rot(2,0,t)}rotateZ(t){return this._rot(0,1,t)}applyMatrix4(t){let i=this.attributes.position;if(i&&t?.elements){let r=new Q;for(let s=0;s<i.count;s++)r.set(i.getX(s),i.getY(s),i.getZ(s)).applyMatrix4(t),i.setXYZ(s,r.x,r.y,r.z);this.computeVertexNormals()}return this}clone(){let t=new cr;t.name=this.name;for(let i of Object.keys(this.attributes))t.attributes[i]=this.attributes[i].clone();return this.index&&(t.index=this.index.clone()),t}dispose(){}},yi=class extends ft{constructor(e=1,t=1,i=1){super();let r=e/2,s=t/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],h=[],l=[];for(let c=0;c<6;c++){let f=c*4;h.push(0,0,1,0,1,1,0,1),l.push(f,f+1,f+2,f,f+2,f+3)}this.setFromBuffers(o,n,h,l)}},rs=class extends ft{constructor(e=1,t=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 h=0;h<=r;h++){let l=h/r;for(let c=0;c<=i;c++){let f=c/i;if(s.push((f-.5)*e,(.5-l)*t,0),a.push(0,0,1),o.push(f,1-l),h>0&&c>0){let g=(i+1)*h+c-1,b=g-(i+1);n.push(b,g,b+1,g,g+1,b+1)}}}this.setFromBuffers(s,a,o,n)}},ss=class extends ft{constructor(e=1,t=16,i=12){super(),t=Math.max(3,Math.floor(t)),i=Math.max(2,Math.floor(i));let r=[],s=[],a=[],o=[];for(let n=0;n<=i;n++){let h=n/i;for(let l=0;l<=t;l++){let c=l/t,f=c*Math.PI*2,g=h*Math.PI,b=-Math.cos(f)*Math.sin(g),u=Math.cos(g),d=Math.sin(f)*Math.sin(g);if(r.push(e*b,e*u,e*d),s.push(b,u,d),a.push(c,1-h),n>0&&l>0){let M=(t+1)*n+l,w=M-(t+1),v=w-1,m=M-1;n!==1&&o.push(w,v,M),n!==i&&o.push(v,m,M)}}}this.setFromBuffers(r,s,a,o)}},vi=class extends ft{constructor(e=1,t=1,i=1,r=16){super(),r=Math.max(3,Math.floor(r));let s=[],a=[],o=[],n=[],h=i/2;for(let c=0;c<=1;c++){let f=c,g=c===0?e:t,b=c===0?h:-h;for(let u=0;u<=r;u++){let d=u/r,M=d*Math.PI*2,w=Math.sin(M),v=Math.cos(M);s.push(g*w,b,g*v),a.push(w,0,v),o.push(d,1-f)}}for(let c=0;c<r;c++){let f=c,g=c+r+1,b=c+r+2,u=c+1;n.push(f,g,u,g,b,u)}let l=(c,f)=>{if(c<=0)return;let g=f*h,b=s.length/3;s.push(0,g,0),a.push(0,f,0),o.push(.5,.5);let u=s.length/3;for(let d=0;d<=r;d++){let M=d/r*Math.PI*2,w=Math.sin(M),v=Math.cos(M);s.push(c*w,g,c*v),a.push(0,f,0),o.push(v*.5+.5,.5+f*w*.5)}for(let d=0;d<r;d++)n.push(b,u+d+(f>0?0:1),u+d+(f>0?1:0))};l(e,1),l(t,-1),this.setFromBuffers(s,a,o,n)}},as=class extends vi{constructor(e=1,t=1,i=16){super(0,e,t,i)}},ns=class extends ft{constructor(e=1,t=.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=[],h=[];for(let l=0;l<=i;l++){let c=l/i*Math.PI*2,f=Math.cos(c),g=Math.sin(c);for(let b=0;b<=r;b++){let u=b/r*s,d=Math.cos(u),M=Math.sin(u);if(a.push((e+t*f)*d,(e+t*f)*M,t*g),o.push(f*d,f*M,g),n.push(b/r,l/i),l>0&&b>0){let w=(r+1)*l+b-1,v=w-(r+1);h.push(w,v,w+1,v,v+1,w+1)}}}this.setFromBuffers(a,o,n,h)}};function xi(e,t,i,r,s){let a=Math.max(2,Math.min(256,Math.floor(Number(t)||64))),o=Math.max(3,Math.min(64,Math.floor(Number(i)||8))),n=Number(r)||.1,h=[],l=[],c=[],f=[],g=new Q,b=new Q,u=new Q,d=new Q,M=new Q;for(let v=0;v<=a;v++){let m=v/a;s(Math.max(0,m-.001),g),s(Math.min(1,m+.001),b),u.subVectors(b,g).normalize(),v===0&&d.set(Math.abs(u.y)>.9?1:0,Math.abs(u.y)>.9?0:1,0),M.crossVectors(u,d).normalize(),d.crossVectors(M,u).normalize(),s(m,g);for(let p=0;p<=o;p++){let x=p/o*Math.PI*2,S=-n*Math.cos(x),N=n*Math.sin(x),F=S*d.x+N*M.x,E=S*d.y+N*M.y,L=S*d.z+N*M.z;h.push(g.x+F,g.y+E,g.z+L);let C=Math.hypot(F,E,L)||1;l.push(F/C,E/C,L/C),c.push(m,p/o)}}let w=o+1;for(let v=1;v<=a;v++){let m=w*(v-1),p=m+w;for(let x=1;x<=o;x++){let S=m+x-1,N=p+x-1;f.push(S,N,m+x,N,p+x,m+x)}}e.setFromBuffers(h,l,c,f)}var os=class extends ft{constructor(e=1,t=.4,i=64,r=8,s=2,a=3){super(),i=Math.floor(i),r=Math.floor(r),xi(this,i,r,t,(o,n)=>{let h=o*s*Math.PI*2,l=a/s*h,c=e*(2+Math.cos(l))*.5;n.set(c*Math.cos(h),c*Math.sin(h),e*Math.sin(l)*.5)})}},Bt=class{getPoint(e,t=new Q){return t}getPointAt(e,t=new Q){return this.getPoint(e,t)}getTangent(e,t=new Q){return t.subVectors(this.getPoint(Math.min(1,e+.001)),this.getPoint(Math.max(0,e-.001))).normalize()}getPoints(e=5){let t=Math.max(1,Math.min(512,Math.floor(Number(e)||5))),i=[];for(let r=0;r<=t;r++)i.push(this.getPoint(r/t));return i}getSpacedPoints(e=5){return this.getPoints(e)}},ls=class extends Bt{constructor(e=new Q,t=new Q){super(),this.v1=e,this.v2=t}getPoint(e,t=new Q){return t.lerpVectors(this.v1,this.v2,e)}},hs=class extends Bt{constructor(e=new Q,t=new Q,i=new Q){super(),this.v0=e,this.v1=t,this.v2=i}getPoint(e,t=new Q){return t.lerpVectors(this.v0,this.v1,e).lerp(new Q().lerpVectors(this.v1,this.v2,e),e)}},us=class extends Bt{constructor(e=new Q,t=new Q,i=new Q,r=new Q){super(),this.v0=e,this.v1=t,this.v2=i,this.v3=r}getPoint(e,t=new Q){let i=new Q().lerpVectors(this.v0,this.v1,e),r=new Q().lerpVectors(this.v1,this.v2,e),s=new Q().lerpVectors(this.v2,this.v3,e);return t.lerpVectors(i.lerp(r,e),r.lerp(s,e),e)}},cs=class extends Bt{constructor(e=[],t=!1){super(),this.points=Array.isArray(e)?e:[],this.closed=!!t}getPoint(e,t=new Q){let i=this.points,r=i.length;if(!r)return t.set(0,0,0);if(r===1)return t.copy(i[0]);let s=(this.closed?r:r-1)*Math.max(0,Math.min(1,Number(e)||0)),a=Math.floor(s),o=s-a;!this.closed&&a>=r-1&&(a=r-2,o=1);let n=d=>i[this.closed?(d%r+r)%r:Math.max(0,Math.min(r-1,d))],h=n(a-1),l=n(a),c=n(a+1),f=n(a+2),g=o*o,b=g*o,u=(d,M,w,v)=>.5*(2*M+(w-d)*o+(2*d-5*M+4*w-v)*g+(3*M-d-3*w+v)*b);return t.set(u(h.x,l.x,c.x,f.x),u(h.y,l.y,c.y,f.y),u(h.z,l.z,c.z,f.z))}},wi=class extends ft{constructor(e=[new Ct(0,-.5),new Ct(.5,0),new Ct(0,.5)],t=12,i=0,r=Math.PI*2){super();let s=Array.isArray(e)&&e.length>=2?e:[new Ct(.2,0),new Ct(.2,.5)],a=Math.max(3,Math.min(128,Math.floor(Number(t)||12))),o=[],n=[],h=[],l=[],c=s.length;for(let f=0;f<=a;f++){let g=f/a,b=i+g*r,u=Math.sin(b),d=Math.cos(b);for(let M=0;M<c;M++){let w=s[M],v=Number(w?.x)||0,m=Number(w?.y)||0;o.push(v*u,m,v*d);let p=s[Math.max(0,M-1)],x=s[Math.min(c-1,M+1)],S=(Number(x?.x)||0)-(Number(p?.x)||0),N=(Number(x?.y)||0)-(Number(p?.y)||0),F=Math.hypot(N,S)||1;n.push(N/F*u,-S/F,N/F*d),h.push(g,M/(c-1))}}for(let f=0;f<a;f++){let g=f*c;for(let b=0;b<c-1;b++){let u=g+b,d=g+c+b;l.push(u,d,u+1,d,d+1,u+1)}}this.setFromBuffers(o,n,h,l)}},ms=class extends ft{constructor(e,t=64,i=1,r=8,s=!1){super(),xi(this,t,r,i,(a,o)=>{let n=e?.getPointAt??e?.getPoint;if(typeof n=="function"){let h=n.call(e,a,o);h&&h!==o&&o.copy(h)}else o.set(0,a,0)})}},se="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",De=class{constructor(e=""){this.isTexture=!0,this.wrapS=10497,this.wrapT=10497,this.repeat=new Ct(1,1),this.offset=new Ct(0,0),this.image=null,this.width=0,this.height=0,this.source=e,e&&typeof e=="object"&&(this.image=e)}dispose(){}},ds=class extends De{constructor(e=null,t=1,i=1,r=1023,s=1009,a,o=1001,n=1001,h=1003,l=1003,c=1,f=""){super(""),this.isDataTexture=!0,this.avgColor=[1,1,1,1],this.flipY=!1,this.generateMipmaps=!1,this.unpackAlignment=1;let g=Number(t),b=Number(i),u=e&&typeof e.length=="number"?e:null;this.width=g,this.height=b,this.image={data:u,width:g,height:b},this.format=Number(r)||1023,this.type=Number(s)||1009,this.wrapS=Number(o)||1001,this.wrapT=Number(n)||1001,this.magFilter=Number(h)||1003,this.minFilter=Number(l)||1003,this.colorSpace=f||"",this._bake()}get needsUpdate(){return!1}set needsUpdate(e){e&&this._bake()}_bake(){let e=this.image,t=e?.data,i=Number(e?.width??this.width),r=Number(e?.height??this.height);if(!t||!t.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,h=n===1021||n===1024||n===1028||t.length===o?1:n===1025||n===1030||t.length===o*2?2:n===1022||t.length===o*3?3:4,l=this.type===1015||this.type===1016||t instanceof Float32Array||t instanceof Float64Array,c=Math.min(s,96),f=Math.min(a,96),g=f*(1+c*4),b=new Uint8Array(68+g),u=new DataView(b.buffer);u.setUint32(0,2303741511),u.setUint32(4,218765834),u.setUint32(8,13),u.setUint32(12,1229472850),u.setUint32(16,c),u.setUint32(20,f),b[24]=8,b[25]=6,u.setUint32(29,_e(b.subarray(12,29))),u.setUint32(33,g+11),u.setUint32(37,1229209940),b[41]=120,b[42]=1,b[43]=1,u.setUint16(44,g,!0),u.setUint16(46,~g&65535,!0);let d=48,M=1,w=0,v=0,m=0,p=0,x=0,S=L=>{if(!Number.isFinite(L))return 0;let C=l&&L<=1?L*255:L;return C>0?C<255?C+.5|0:255:0};for(let L=0;L<f;L++){let C=L*a/f|0,D=this.flipY?a-1-C:C;b[d++]=0,w+=M;for(let R=0;R<c;R++){let y=(D*s+(R*s/c|0))*h,U=n===1021?255:S(t[y]??0),j=h>=3||n===1030?S(t[y+1]??0):U,T=h>=3?S(t[y+2]??0):n===1030?0:U,k=h===4?S(t[y+3]??255):n===1021?S(t[y]??255):n===1025?S(t[y+1]??255):255;b[d++]=U,M+=U,w+=M,b[d++]=j,M+=j,w+=M,b[d++]=T,M+=T,w+=M,b[d++]=k,M+=k,w+=M,v+=U,m+=j,p+=T,x+=k}M%=65521,w%=65521}u.setUint32(d,(w<<16|M)>>>0),u.setUint32(d+4,_e(b.subarray(37,d+4))),u.setUint32(d+12,1229278788),u.setUint32(d+16,2923585666);let N=c*f*255,F=this.colorSpace==="srgb-linear";this.avgColor=[F?v/N:wt(v/N),F?m/N:wt(m/N),F?p/N:wt(p/N),x/N];let E=["data:image/png;base64,"];for(let L=0;L<b.length;L+=3){let C=b[L]<<16|(b[L+1]??0)<<8|(b[L+2]??0);E.push(se[C>>18&63]+se[C>>12&63]+(L+1<b.length?se[C>>6&63]:"=")+(L+2<b.length?se[C&63]:"="))}this.source=E.join("")}},ps=class{load(e,t){let i=new De(e);return t?.(i),i}};function yt(e,t){return e!==void 0?Number(e):t}function ke(e,t){return e!==void 0?!!e:t}var Tt=class{constructor(e={}){this.name=e.name||"",this.color=new Nt(e.color!==void 0?e.color:16777215),this.emissive=new Nt(e.emissive!==void 0?e.emissive:0),this.emissiveIntensity=yt(e.emissiveIntensity,1),this.roughness=yt(e.roughness,.5),this.metalness=yt(e.metalness,0),this.opacity=yt(e.opacity,1),this.transparent=ke(e.transparent,!1),this.wireframe=ke(e.wireframe,!1),this.side=yt(e.side,2),this.doubleSided=ke(e.doubleSided,!0),this.map=e.map||null,this.clearcoat=yt(e.clearcoat,0),this.clearcoatRoughness=yt(e.clearcoatRoughness,0),this.sheen=yt(e.sheen,0),this.sheenColor=new Nt(e.sheenColor!==void 0?e.sheenColor:0),this.sheenRoughness=yt(e.sheenRoughness,0),this.transmission=yt(e.transmission,0),this.thickness=yt(e.thickness,0),this.attenuationColor=new Nt(e.attenuationColor!==void 0?e.attenuationColor:16777215),this.attenuationDistance=yt(e.attenuationDistance,1/0),this.ior=yt(e.ior,1.5),this.dispersion=yt(e.dispersion,0),this.iridescence=yt(e.iridescence,0),this.iridescenceIOR=yt(e.iridescenceIOR,1.3)}dispose(){}},ae=class extends Tt{},fs=class extends Tt{},gs=class extends Tt{},bs=class extends Tt{},ys=class extends Tt{},Lt=class mr{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 Q,this.rotation=new fi,this.quaternion=new gi,this.scale=new Q(1,1,1),this.matrix=new jt,this.matrixWorld=new jt,this.rotation._onChange(()=>{this.quaternion.setFromEuler(this.rotation,!1)}),this.quaternion._onChange(()=>{let t=this.quaternion,i=Math.atan2(2*(t.w*t.x+t.y*t.z),1-2*(t.x*t.x+t.y*t.y)),r=Math.asin(Math.max(-1,Math.min(1,2*(t.w*t.y-t.z*t.x)))),s=Math.atan2(2*(t.w*t.z+t.x*t.y),1-2*(t.y*t.y+t.z*t.z));this.rotation.set(i,r,s)})}add(...t){for(let i of t)i&&i instanceof mr&&(i.parent&&i.parent.remove(i),i.parent=this,this.children.push(i));return this}remove(...t){for(let i of t){let r=this.children.indexOf(i);r!==-1&&(i.parent=null,this.children.splice(r,1))}return this}traverse(t){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),t(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(t=!1){this.traverse(i=>{Mi(i),(i.matrixAutoUpdate||t)&&i.updateMatrix?.(),i.parent&&i.parent.matrixWorld?i.matrixWorld?.multiplyMatrices(i.parent.matrixWorld,i.matrix):i.matrix&&i.matrixWorld?.copy(i.matrix)})}lookAt(t,i,r){let s=typeof t=="object"?t:new Q(t,i,r);this.target instanceof Q?this.target.copy(s):this.target?.position instanceof Q&&this.target.position.copy(s),this.updateMatrixWorld(!0);let a=new jt;a.lookAt(this.position,s,new Q(0,1,0));let o=a.elements,n=o[0],h=o[4],l=o[8],c=o[1],f=o[5],g=o[9],b=o[2],u=o[6],d=o[10],M=n+f+d;if(M>0){let w=.5/Math.sqrt(M+1);this.quaternion.set((u-g)*w,(l-b)*w,(c-h)*w,.25/w)}}translateOnAxis(t,i){let r=t.clone().applyMatrix4(new jt().makeRotationFromQuaternion(this.quaternion)).multiplyScalar(i);return this.position.add(r),this}translateX(t){return this.translateOnAxis(new Q(1,0,0),t)}translateY(t){return this.translateOnAxis(new Q(0,1,0),t)}translateZ(t){return this.translateOnAxis(new Q(0,0,1),t)}rotateX(t){return this.rotation.x+=t,this}rotateY(t){return this.rotation.y+=t,this}rotateZ(t){return this.rotation.z+=t,this}clone(t=!0){let i=this instanceof Yt?new this.constructor(this._sourceGeo||this.geometry,this.material):this instanceof kt?new kt(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(t)for(let r of this.children)i.add(r.clone(!0));return i}},vs=class extends Lt{},kt=class extends Lt{constructor(e,t){super(),this.isMesh=!0;let i=Array.isArray(t)?t[0]:t;this.geometry=e instanceof ft?e:e?($t("unsupported geometry","BoxGeometry"),new yi(.5,.5,.5)):new ft,this.material=i instanceof Tt?i:i?($t("unsupported material","MeshStandardMaterial"),new ae({color:13421772})):new ae}};function Mi(e){typeof e?._bakeAuthorGeometry=="function"&&e._bakeAuthorGeometry();let t=ot().materializeDeclarativeGeometry;typeof t=="function"&&t(e)}var ne=1e4,Si=class extends kt{constructor(e,t,i=1){super(e,t),this.instanceColor=null,this.isInstancedMesh=!0;let r=Number(i);if(!Number.isFinite(r)||r<0||r>ne)throw new RangeError(`SecurityError: InstancedMesh count (${String(i)}) exceeds MAX_INSTANCES_PER_MESH (${ne})`);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 bt(s,16)}setMatrixAt(e,t){let i=Math.floor(Number(e));if(!Number.isFinite(i)||i<0||i>=this.count||!t||!t.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(t.elements[a]);r[s+a]=Number.isFinite(o)?o:a%5===0?1:0}}getMatrixAt(e,t){let i=Math.floor(Number(e));if(!Number.isFinite(i)||i<0||i>=this.count||!t||!t.elements)return;let r=this.instanceMatrix.array,s=i*16;if(!(s+16>r.length))for(let a=0;a<16;a++)t.elements[a]=r[s+a]}setColorAt(e,t){let i=Math.floor(Number(e));if(!Number.isFinite(i)||i<0||i>=this.count||!t)return;if(!this.instanceColor||this.instanceColor.array.length<this.count*3){let a=new Float32Array(this.count*3);a.fill(1),this.instanceColor=new bt(a,3)}let r=this.instanceColor.array,s=i*3;r[s]=Number.isFinite(t.r)?t.r:1,r[s+1]=Number.isFinite(t.g)?t.g:1,r[s+2]=Number.isFinite(t.b)?t.b:1}getColorAt(e,t){let i=Math.floor(Number(e));if(!Number.isFinite(i)||i<0||i>=this.count||!t)return;if(!this.instanceColor||this.instanceColor.array.length<(i+1)*3){t.setRGB(1,1,1);return}let r=this.instanceColor.array,s=i*3;t.setRGB(r[s],r[s+1],r[s+2])}dispose(){}},oe=class extends Lt{constructor(e=16777215,t=1){super(),this.color=new Nt(e),this.intensity=Number(t),this.type="directional"}},Ai=class extends oe{constructor(e,t){super(e,t),this.type="ambient"}},xs=class extends oe{constructor(e,t){super(e,t),this.target=new Lt,this.type="directional"}},Ti=class extends oe{constructor(e,t,i=0,r=2){super(e,t),this.type="point",this.distance=i,this.decay=r}},Ri=class extends Lt{},ws=class extends Ri{constructor(e=45,t=1,i=.1,r=1e3){super(),this.target=new Q(0,0,0),this.fov=Number(e),this.aspect=Number(t),this.near=Number(i),this.far=Number(r)}},Ci=class extends Lt{constructor(){super(...arguments),this.background=null,this.environmentIntensity=1}toCanvas3D(){return Ft.validate(this),te(this)}toGLB(){return Ft.validate(this),Re(this)}toUSDZ(){return Ft.validate(this),Ne(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let e=new Map,t=0;return this.traverse(i=>{if(i instanceof kt){let r=new Float32Array(i.matrixWorld.elements);e.set(t,r),i.name&&e.set(i.name,r),t++}}),e}},Pi=te,Ei=Re,Ms=Ne,Ft=class{static validate(e){let t=0,i=0,r=0,s=new Set,a=(n,h,l)=>{throw new Error(`SecurityError: Scene exceeds SECURITY_3D_MAX_${n} (${h}). Found: ${l}`)},o=(n,h)=>{if(!Number.isFinite(h))throw new Error(`SecurityError: Scene reports a non-finite ${n} count (${String(h)}), which cannot be bounds-checked.`);return h};e.traverse(n=>{if(Mi(n),n instanceof kt||n.geometry?.attributes?.position?.count){if(r++,r>1e3&&a("MESHES",1e3,r),n instanceof Si){let l=o("instance",n.count);(l<0||l>ne)&&a("INSTANCES",ne,l)}let h=n.geometry;if(h){let l=0;if(h.attributes.position&&(l=o("vertex",h.attributes.position.count),t+=l,t>1e5&&a("VERTICES",1e5,t)),h.index){let c=o("index",h.index.count);i+=c,i>3e5&&a("INDICES",3e5,i);let f=h.index.array;if(f&&l>0){let g=Math.min(c,f.length);for(let b=0;b<g;b++){let u=f[b];if(!Number.isFinite(u)||u<0||u>=l)throw new Error(`SecurityError: Index buffer value (${String(u)}) out of vertex bounds [0, ${l}).`)}}}}if(n.material){let l=n.material;l.map&&s.add(l.map),l.normalMap&&s.add(l.normalMap),l.roughnessMap&&s.add(l.roughnessMap)}}}),s.size>16&&a("TEXTURES",16,s.size);for(let n of s){let h=n,l=h.image,c=Number(l?.width??h.width??0)||0,f=Number(l?.height??h.height??0)||0;(!Number.isFinite(c)||!Number.isFinite(f)||c>2048||f>2048)&&a("TEXTURE_DIMENSION",2048,Math.max(c,f))}}},Ss=class{constructor(e={}){this.shadowMap={enabled:!1,type:0},this.capabilities={isWebGL2:!0,maxTextures:16},this.boundViewer=null,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 i=new Nt(e);return this.boundViewer&&typeof this.boundViewer.setClearColor=="function"&&this.boundViewer.setClearColor(i.r,i.g,i.b,t),this}clear(){return this}dispose(){}render(e,t){if(this.isSandboxed){Ft.validate(e);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=e.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=Pi(e),a=Ei(e),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:t?{fov:t.fov||60,position:[t.position.x,t.position.y,t.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(e.getMeshTransforms()):(i.loadModel(e.toCanvas3D()),i._hasThreeLiveModelLoaded=!0))}};function _i(){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 As=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=_i(),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=_i();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function Ts(){}var le=new Proxy(Ts,{get:(e,t)=>{if(t==="isProxy")return!0;if(!(t==="constructor"||t==="__proto__"||t==="prototype"))return t==="domElement"?typeof document<"u"?document.createElement("canvas"):{}:t==="shadowMap"?{enabled:!1,type:0}:t==="capabilities"?{isWebGL2:!0,maxTextures:16}:t===Symbol.toPrimitive?()=>0:le},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>le,construct:()=>le}),Ni=(()=>{try{if(typeof document>"u")return null;let e=document.currentScript;return e?.src?e.src:e?.textContent&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(new Blob([e.textContent],{type:"text/javascript"})):null}catch{return null}})();function he(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function Xt(e,t){if(!e||typeof e!="string")return!1;let i=e.trim();if(!i)return!1;try{let r=new URL(i,he());return!(r.protocol!=="https:"&&r.protocol!=="http:"&&r.protocol!=="blob:"||t?.requireSameOrigin&&r.protocol!=="blob:"&&typeof location<"u"&&location.origin&&location.origin!=="null"&&r.origin!==location.origin)}catch{return!1}}var Li,qt;function Rs(e){if(!Xt(e))throw new Error(`SecurityError: Refusing to create TrustedScriptURL for disallowed URL "${e}".`);let t=globalThis.trustedTypes;if(!t||typeof t.createPolicy!="function")return e;if(qt===void 0||Li!==t){Li=t;try{qt=t.createPolicy("three-live#worker",{createScriptURL:i=>{if(!Xt(i))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${i}".`);return i}})}catch{qt=null}}return qt?qt.createScriptURL(e):e}function Di(){let e=ot().sandboxEngineSrc;if(e)return e;if(Ni)return Ni;try{if(typeof document>"u")return null;let t=he(),i=Array.from(document.querySelectorAll("script[src]"));for(let r of i){let s=r.src;if(!s)continue;let a=new URL(s,t).pathname;if(/(?:^|\/)(?:three|xr)-live[^/]*\.js$/.test(a)&&Xt(s,{requireSameOrigin:!0}))return s}}catch{}return null}function Fe(e,t){if(!Xt(e))throw new Error(`SecurityError: Refusing to load ${t} from disallowed URL "${e}". Only http:, https:, and blob: URLs are permitted.`);return new URL(e,he()).href}function Cs(){let e=Di();if(!e)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 Fe(e,"sandbox engine")}function Ps(){let e=ot().sandboxIframeSrc;if(e)return e;let t=Di();if(!t||!Xt(t))return null;let i=new URL(t,he());return i.protocol==="blob:"?null:new URL("three-live-sandbox.html",i).href}function Es(){let e=Ps();if(!e)throw new Error("Three-Live could not locate three-live-sandbox.html for iframe sandbox execution. Set ThreeLiveElement.sandboxIframeSrc (or ThreeLiveElement.sandboxEngineSrc) explicitly.");return Fe(e,"sandbox iframe")}function _s(){return!!ot().allowClientScripts}function Ns(e){return Fe(e,"procedural scene script")}var Ls=["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 Ds(e,t){let i=self,r=e.nonce,s=e.engineSrc,a=e.allowedScriptUrl,o=e.allowClientScripts,n=e.revoked,h=i.postMessage.bind(i);function l(m){h({type:"ERROR",nonce:r,message:String(m)})}let c=typeof i.importScripts=="function"?i.importScripts.bind(i):null,f=a,g=null;try{let m=s;if(typeof i.trustedTypes<"u"&&i.trustedTypes&&typeof i.trustedTypes.createPolicy=="function")try{let p={createScriptURL:function(S){if(S!==s&&(!a||S!==a))throw new TypeError("Disallowed worker importScripts URL");return S}};o&&(p.createScript=function(S){return String(S)});let x=i.trustedTypes.createPolicy("three-live#worker-boot",p);m=x.createScriptURL(s),a&&(f=x.createScriptURL(a)),o&&typeof x.createScript=="function"&&(g=x.createScript.bind(x))}catch{}c(m)}catch(m){l('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: '+(m&&m.message||m));return}let b=i.THREE;if(!b||typeof b.Scene!="function"){l('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(t)){let m=i.__THREE_LIVE_REGISTRY__;for(let p=0;p<t.length;p++)if(typeof t[p]=="function")try{t[p](b,m)}catch{}}function u(m,p,x){let S=i;for(;S&&S!==Object.prototype;){if(!x&&S!==i)try{delete S[m]}catch{}if(!x||S===i||Object.prototype.hasOwnProperty.call(S,m))try{Object.defineProperty(S,m,x?{value:p,writable:!1,configurable:!1}:{value:p,writable:!1,configurable:!1,enumerable:!1})}catch{}try{S=Object.getPrototypeOf(S)}catch{break}}}for(let m=0;m<n.length;m++)u(n[m],void 0);u("performance",Object.freeze({now:function(){return Date.now()}}));let d=["3D_MODEL_READY","3D_UPDATE_TRANSFORMS"],M=!1;function w(m,p){if(m.type==="3D_MODEL_READY"){if(M)return;M=!0}m.nonce=r,p&&p.length?h(m,p):h(m)}u("postMessage",function(m,p){if(!m||d.indexOf(m.type)===-1)throw new Error("Sandboxed scripts may only post Three-Live scene messages ("+d.join(", ")+").");w(m,p)},!0);let v=!1;i.onmessage=function(m){let p=m&&m.data;if(!(!p||p.nonce!==r)&&!(p.type!=="EXECUTE"&&p.type!=="EXECUTE_URL")&&!v){v=!0;try{let x=new b.Scene,S=new b.PerspectiveCamera(60,1,.1,1e3),N=new b.WebGLRenderer({isSandboxed:!0});if(p.type==="EXECUTE_URL"){if(!a||p.scriptUrl!==a||typeof c!="function"){l("SecurityError: Refusing to execute unapproved script URL inside sandbox worker.");return}let F=f||a,E=c;if(c=null,f=null,i.THREE=b,i.scene=x,i.camera=S,i.renderer=N,E(F),typeof i.__THREE_LIVE_SCENE__=="function"){let L=i.__THREE_LIVE_SCENE__(b,x,S,N);L&&typeof L.toGLB=="function"&&(x=L)}else i.scene&&typeof i.scene.toGLB=="function"&&(x=i.scene)}else{if(!o){l("SecurityError: Client-modified script compilation (Use Case 1) is disabled in this sandbox worker.");return}let F=g?(0,eval)(g(`(function (THREE, scene, camera, renderer) {
|
|
322
344
|
return (function () {
|
|
323
|
-
`+
|
|
345
|
+
`+p.script+`
|
|
346
|
+
;
|
|
347
|
+
return typeof scene === "object" && scene ? scene : undefined;
|
|
324
348
|
})();
|
|
325
349
|
})`)):new Function("THREE","scene","camera","renderer",`return (function () {
|
|
326
|
-
`+
|
|
327
|
-
})();`);h=null;let x=v(y,w,A,L);x&&typeof x.toGLB=="function"&&(w=x)}if(!T){y.SceneQuotaValidator&&y.SceneQuotaValidator.validate(w);let v=w.toGLB(),x=v instanceof ArrayBuffer?v:v.buffer.slice(v.byteOffset,v.byteOffset+v.byteLength);P({type:"3D_MODEL_READY",glbBuffer:x},[x])}a({type:"DONE",nonce:r})}catch(w){u(w&&w.message||w)}}},a({type:"READY",nonce:r})}function sr(n,e,t){let r=t?.allowedScriptUrl??null,i=t?.allowClientScripts??r===null,s={nonce:e,engineSrc:n,allowedScriptUrl:r,allowClientScripts:i,revoked:Zr},o=(Q().workerExtensionInstallers??[]).map(c=>`(${c.toString()})`).join(",");return`'use strict';(${Jr.toString()})(${JSON.stringify(s)},[${o}]);`}function or(n){n.onError?.(new Error("SecurityError: Sandboxed script exceeded SECURITY_3D_SANDBOX_TIMEOUT_MS (3000 ms) and was terminated.")),n.onToast?.("Security Error: script timed out and was stopped.")}var 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=()=>{},y=d=>{if(c||!o.contentWindow||d.source!==o.contentWindow)return;let g=d.data;if(g&&typeof g=="object"&&g.type==="IFRAME_READY"){m();return}let T=cr(g,i);T&&ur(T,r,h,u)};h=()=>{c||(c=!0,l!==void 0&&clearTimeout(l),Te=Math.max(0,Te-1),typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("message",y),typeof o.remove=="function"?o.remove():o.parentNode&&o.parentNode.removeChild(o))},l=setTimeout(()=>{c||(h(),or(r))},3e3),typeof globalThis.addEventListener=="function"&&globalThis.addEventListener("message",y),o.onload=()=>{m()},o.onerror=()=>{h(),r.onError?.(new Error(`Sandbox iframe failed to load "${t}". Verify that three-live-sandbox.html is served at that URL.`))};let b=document.body||document.documentElement;if(!b||typeof b.appendChild!="function"){h();let d=new Error("SecurityError: Cannot mount sandbox iframe because document.body is unavailable.");throw r.onError?.(d),d}return b.appendChild(o),{terminate:h}}function Qn(n,e,t,r){if(e==="worker"&&typeof Worker>"u")return r("Sandboxed procedural execution requires Web Workers, but Workers are unavailable in this environment. For host security, Three-Live prohibits unsandboxed in-process evaluation.","Security Error: Web Workers unavailable. Script execution aborted.");if(e==="iframe"&&(typeof document>"u"||typeof document.createElement!="function"))return r("Sandboxed iframe execution requires a DOM environment with document.createElement. Refusing to evaluate in the host realm.","Security Error: DOM unavailable for iframe sandbox.");if(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 y=h instanceof Error?h.message:String(h);return r(y,"Security Error: sandbox engine URL is not configured.")}if(e==="iframe"){let h;try{h=qr()}catch(y){let b=y instanceof Error?y.message:String(y);return r(b,"Security Error: sandbox iframe URL is not configured.")}try{return Promise.resolve(ri(n,i,h,t))}catch(y){return Promise.reject(y)}}let s=ar(),o=sr(i,s,n.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:n.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),c;try{let h=new Blob([o],{type:"application/javascript"}),y=URL.createObjectURL(h);try{let b=Wr(y);c=new Worker(b)}finally{URL.revokeObjectURL(y)}}catch(h){let y=h instanceof Error?h.message:String(h);return r(`Failed to initialize Web Worker for sandboxed execution (CSP may block blob workers): ${y}`,"Security Error: Failed to start Worker sandbox.")}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 y=cr(h.data,s);y&&ur(y,t,m,u)},c.onerror=h=>{m(),t.onError?.(new Error(`Worker execution error: ${h.message}`))},n.kind==="url"?c.postMessage({type:"EXECUTE_URL",scriptUrl:n.scriptUrl,nonce:s}):c.postMessage({type:"EXECUTE",script:n.script,nonce:s}),Promise.resolve({terminate:m})}function er(n,e){return n==="none"||n==="unsafe-host-realm"?e(`SecurityError: sandbox="${n}" is prohibited. Sandboxing is mandatory for live compilation and cannot be bypassed. Use sandbox="worker" (default) or sandbox="iframe".`,`Security Error: sandbox="${n}" is not permitted.`):n!=="worker"&&n!=="iframe"?e(`SecurityError: Unsupported sandbox mode "${n}". Live compilation requires sandbox="worker" or sandbox="iframe".`,"Security Error: unsupported sandbox mode."):null}var yn={execute(n,e,t,r){let i=(c,a)=>{let u=new Error(c);return t.onError?.(u),a&&t.onToast?.(a),Promise.reject(u)},s=er(e,i);if(s)return s;try{ni(n)}catch(c){let a=c instanceof Error?c.message:String(c);return i(a,"Security Error: script exceeds the size limit.")}return r?.allowClientScripts??jr()?Qn({kind:"script",script:n},e,t,i):i(Je,Qe)},executeUrl(n,e,t){let r=(o,c)=>{let a=new Error(o);return t.onError?.(a),c&&t.onToast?.(c),Promise.reject(a)},i=er(e,r);if(i)return i;let s;try{s=Kr(n)}catch(o){let c=o instanceof Error?o.message:String(o);return r(c,"Security Error: disallowed scene script URL.")}return Qn({kind:"url",scriptUrl:s},e,t,r)}},wt=new Set;function ve(n,e){let t=`[three-live] ${n} is unsupported; degraded to ${e}.`;wt.has(t)||(wt.add(t),typeof console<"u"&&typeof console.warn=="function"&&console.warn(t))}function ii(){return Array.from(wt)}function si(){wt.clear()}var At=class extends Be{constructor(e={}){ve("ShaderMaterial","MeshStandardMaterial");let t=e.uniforms||{},r=t.color?.value??t.uColor?.value??t.diffuse?.value??e.color;super({color:r!==void 0?r:8421504,opacity:t.opacity?.value??e.opacity??1,transparent:!!e.transparent,wireframe:!!e.wireframe,side:e.side}),this.uniforms=t}},oi=At,He=class extends dt{constructor(e=1,t=0,r="PolyhedronGeometry"){ve(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){ve("CapsuleGeometry","CylinderGeometry"),super(e,e,t+e*2,i)}},fn=class extends De{constructor(e=.5,t=1,r=16){ve("RingGeometry","CylinderGeometry"),super(t,t,.01,Math.max(8,r))}},pn=class extends De{constructor(e=1,t=16){ve("CircleGeometry","CylinderGeometry"),super(e,e,.01,Math.max(8,t))}},bn=class extends gt{constructor(t,r,i=0,s=Math.PI/3,o=0,c=2){ve("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}},Rt=class extends yt{constructor(e,t,r){ve("HemisphereLight","AmbientLight"),super(e,r),this.groundColor=new xe(t??4473924)}},ai=Rt,lr={Vector2:Ht,Vector3:le,Vector4:Gt,Euler:lt,Quaternion:ht,Matrix4:Oe,Matrix3:Xt,Color:xe,MathUtils:Hr,BufferAttribute:J,Float32BufferAttribute:Wt,Uint16BufferAttribute:$t,Uint32BufferAttribute:Yt,BufferGeometry:ge,BoxGeometry:mt,PlaneGeometry:qt,SphereGeometry:dt,CylinderGeometry:De,ConeGeometry:jt,TorusGeometry:Kt,TorusKnotGeometry:Zt,IcosahedronGeometry:un,OctahedronGeometry:ln,DodecahedronGeometry:hn,TetrahedronGeometry:mn,CapsuleGeometry:dn,RingGeometry:fn,CircleGeometry:pn,Texture:ft,TextureLoader:Jt,Material:Me,MeshStandardMaterial:Be,MeshBasicMaterial:Qt,MeshLambertMaterial:en,MeshPhongMaterial:tn,MeshPhysicalMaterial:nn,ShaderMaterial:At,RawShaderMaterial:oi,Object3D:we,Group:rn,Mesh:Ve,InstancedMesh:bt,Light:ze,AmbientLight:yt,DirectionalLight:sn,PointLight:gt,SpotLight:bn,HemisphereLight:Rt,RectAreaLight:ai,Camera:vt,PerspectiveCamera:on,Scene:xt,WebGLRenderer:an,Clock:cn,SceneQuotaValidator:Se,exportSceneToCanvas3D:nr,exportSceneToGLB:rr,exportSceneToUSDZ:Gr,generateUSDZ:at,glbToUSDZ:ot,sceneToCanvas3D:Ye,sceneToGLB:st,sceneToUSDZ:qe,authorScriptRunner:yn,getAuthorWarnings:ii,clearAuthorWarnings:si};Object.freeze(Se);Object.freeze(Se.prototype);Object.freeze(xt.prototype);Object.freeze(lr);var Pe=new Proxy(lr,{get:(n,e)=>{if(e in n)return n[e];let t=Q().authorNamespace;return t&&typeof e=="string"&&e in t?t[e]:(typeof e=="string"&&e!=="then"&&e!=="toJSON"&&!e.startsWith("__")&&ve(`THREE.${e}`,"no-op proxy"),ct)},has:(n,e)=>{if(e in n)return!0;let t=Q().authorNamespace;return!!(t&&typeof e=="string"&&e in t)},set:(n,e)=>{throw new TypeError(`Cannot assign to read only property '${String(e)}' of #<THREE>`)},defineProperty:(n,e)=>{throw new TypeError(`Cannot define property '${String(e)}', object is not extensible`)},deleteProperty:(n,e)=>{throw new TypeError(`Cannot delete property '${String(e)}' of #<THREE>`)},setPrototypeOf:()=>{throw new TypeError("#<THREE> is not extensible")}}),ut=Q();ut.threeNamespace=Pe;if(ut.workerExtensionInstallers)for(let n of ut.workerExtensionInstallers)n(Pe,ut);var zt={name:"three_author",THREE:Pe};var Re=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;typeof Re.THREE>"u"&&(Re.THREE=Pe);typeof Re.requestAnimationFrame!="function"&&(Re.requestAnimationFrame=n=>(typeof n=="function"&&typeof Re.__three_live_raf_cb__!="function"&&(Re.__three_live_raf_cb__=n),Re.__three_live_in_step__||ve("requestAnimationFrame","single-frame static evaluation"),0));typeof Re.cancelAnimationFrame!="function"&&(Re.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 li=typeof HTMLElement<"u"?HTMLElement:class{};typeof CustomEvent>"u"&&typeof Event<"u"&&(globalThis.CustomEvent=class extends Event{constructor(n,e){super(n,e),this.detail=e?.detail??null}});var he=class he extends li{constructor(){super(...arguments);this.viewer=null;this.canvas=null;this.posterEl=null;this.arButton=null;this.currentModel=null;this.activeXRSession=null;this.toastTimer=null;this.currentModelLimits=void 0;this.isModelLoaded=!1;this.scriptHandle=null;this.resizeObserver=null;this.mutationObserver=null}static get arProvider(){return Q().arProvider}static set arProvider(t){Q().arProvider=t}static get scriptRunner(){return Q().scriptRunner}static set scriptRunner(t){Q().scriptRunner=t}static get sandboxEngineSrc(){return Q().sandboxEngineSrc??null}static set sandboxEngineSrc(t){Q().sandboxEngineSrc=t}static get sandboxIframeSrc(){return Q().sandboxIframeSrc??null}static set sandboxIframeSrc(t){Q().sandboxIframeSrc=t}static get allowClientScripts(){return!!Q().allowClientScripts}static set allowClientScripts(t){Q().allowClientScripts=t}static registerScriptRunner(t){he.scriptRunner=t}static registerDecoder(t,r){de.registerDecoder(t,r)}static getDecoder(t){return de.getDecoder(t)}static registerAR(t){typeof t=="function"?he.arProvider={activateAR:t}:he.arProvider=t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(i=>{i instanceof he&&i.updateARButtonVisibility()})}static isARSupported(){return!!he.arProvider}getLoadedModel(){return this.currentModel}connectedCallback(){if(typeof document>"u")return;(!this.style.display||this.style.display==="inline")&&(this.style.display="block"),getComputedStyle(this).position==="static"&&(this.style.position="relative"),this.style.overflow="hidden",this.setupDOM(),this.initViewer(),this.setupResizeObserver();let t=this.getAttribute("src"),r=this.getAttribute("script-src");if(t)this.loadModel(t).catch(()=>{});else if(r)this.loadScriptFromSrc(r).catch(()=>{});else{let i=this.querySelector('script[type="text/three"], script[type="text/three-live"]');i&&i.textContent&&this.executeScript(i.textContent).catch(()=>{})}for(let i of de.getRegisteredPlugins())i.onElementConnected?.(this)}disconnectedCallback(){for(let t of de.getRegisteredPlugins())t.onElementDisconnected?.(this);this.scriptHandle&&(this.scriptHandle.terminate(),this.scriptHandle=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.activeXRSession&&(this.activeXRSession.stop?.().catch?.(()=>{}),this.activeXRSession=null),this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=null),this.viewer&&(this.viewer.destroy(),this.viewer=null),this.isModelLoaded=!1}attributeChangedCallback(t,r,i){if(r!==i){switch(t){case"src":i&&this.loadModel(i).catch(()=>{});break;case"camera-target":this.applyCameraTarget(i);break;case"min-camera-orbit":case"max-camera-orbit":this.applyOrbitLimits();break;case"field-of-view":this.applyFieldOfView(i);break;case"script-src":i&&this.loadScriptFromSrc(i).catch(()=>{});break;case"sandbox":case"allow-client-scripts":case"ios-src":break;case"poster":this.updatePoster(i);break;case"camera-orbit":this.applyCameraOrbit(i);break;case"selected-mesh":this.viewer&&i!==null&&this.viewer.setSelectedMesh(i);break;case"exposure":if(this.viewer&&i!==null){let s=parseFloat(i);isNaN(s)||this.viewer.setExposure(s)}break;case"shadow-intensity":case"shadow-softness":this.viewer&&this.viewer.setShadow(this.shadowIntensity,this.shadowSoftness);break;case"tone-mapping":this.viewer?.setToneMapping(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 de.getRegisteredPlugins())s.onAttributeChanged?.(this,t,r,i)}}getAttr(t){return this.getAttribute(t)}setAttr(t,r){r!==null?this.setAttribute(t,r):this.removeAttribute(t)}getBoolAttr(t){return this.hasAttribute(t)&&this.getAttribute(t)!=="false"}setBoolAttr(t,r){r?this.setAttribute(t,""):this.removeAttribute(t)}getFloatAttr(t,r){let i=this.getAttribute(t);return i!==null?parseFloat(i):r}get src(){return this.getAttr("src")}set src(t){this.setAttr("src",t)}get cameraControls(){return this.getBoolAttr("camera-controls")}set cameraControls(t){this.setBoolAttr("camera-controls",t)}get cameraOrbit(){return this.getAttr("camera-orbit")}set cameraOrbit(t){this.setAttr("camera-orbit",t)}get cameraTarget(){return this.getAttr("camera-target")}set cameraTarget(t){this.setAttr("camera-target",t)}get minCameraOrbit(){return this.getAttr("min-camera-orbit")}set minCameraOrbit(t){this.setAttr("min-camera-orbit",t)}get maxCameraOrbit(){return this.getAttr("max-camera-orbit")}set maxCameraOrbit(t){this.setAttr("max-camera-orbit",t)}get fieldOfView(){return this.getAttr("field-of-view")}set fieldOfView(t){this.setAttr("field-of-view",t)}get iosSrc(){return this.getAttr("ios-src")}set iosSrc(t){this.setAttr("ios-src",t)}get scriptSrc(){return this.getAttr("script-src")}set scriptSrc(t){this.setAttr("script-src",t)}get sandbox(){return this.getAttribute("sandbox")||(Q().sandboxIframeSrc?"iframe":"worker")}set sandbox(t){this.setAttribute("sandbox",t)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||he.allowClientScripts}set allowClientScripts(t){this.setBoolAttr("allow-client-scripts",t)}get poster(){return this.getAttr("poster")}set poster(t){this.setAttr("poster",t)}get selectedMesh(){return this.getAttr("selected-mesh")}set selectedMesh(t){this.setAttr("selected-mesh",t)}get exposure(){return this.getFloatAttr("exposure",1)}set exposure(t){this.setAttribute("exposure",String(t))}get autoRotate(){return this.getBoolAttr("auto-rotate")}set autoRotate(t){this.setBoolAttr("auto-rotate",t)}get autoRotateDelay(){return this.getFloatAttr("auto-rotate-delay",3e3)}set autoRotateDelay(t){this.setAttribute("auto-rotate-delay",String(t))}get rotationPerSecond(){return this.getAttr("rotation-per-second")||"30deg"}set rotationPerSecond(t){this.setAttr("rotation-per-second",t)}get turntableRotation(){return this.viewer?this.viewer.turntableRotation:0}get ar(){return this.hasAttribute("ar")}set ar(t){this.setBoolAttr("ar",t)}get arScale(){return this.getAttribute("ar-scale")||"auto"}set arScale(t){this.setAttribute("ar-scale",t)}get arPlacement(){return this.getAttribute("ar-placement")||"floor"}set arPlacement(t){this.setAttribute("ar-placement",t)}get canActivateAR(){return he.isARSupported()}get shadowIntensity(){return this.getFloatAttr("shadow-intensity",0)}set shadowIntensity(t){this.setAttribute("shadow-intensity",String(t))}get shadowSoftness(){return this.getFloatAttr("shadow-softness",.5)}set shadowSoftness(t){this.setAttribute("shadow-softness",String(t))}get toneMapping(){return 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():[]}selectVariant(t){if(!this.viewer)return!1;let r=this.viewer.selectVariant(t);return r&&this.dispatchEvent(new CustomEvent("variant-applied",{bubbles:!0,composed:!0,detail:{variantName:this.viewer.getVariantName()}})),r}get model(){let t=this.viewer?this.viewer.getModelMaterials():[];return{materials:t,getMaterialByName(r){return t.find(i=>i.name===r)??null}}}play(){this.viewer&&this.viewer.playAnimation(this.animationName||void 0)}pause(){this.viewer&&this.viewer.pauseAnimation()}resetCamera(){this.viewer?.resetCamera()}resetTurntableRotation(t=0){this.viewer?.resetTurntableRotation(t)}setCamera(t,r,i,s){this.viewer&&this.viewer.setCamera(t,r,i,s)}getCameraOrbit(){return this.viewer?this.viewer.getCameraOrbit():{theta:0,phi:0,radius:3,toString(){return"0rad 0rad 3m"}}}getCameraTarget(){return this.viewer?this.viewer.getCameraTarget():{x:0,y:0,z:0,toString(){return"0m 0m 0m"}}}getFieldOfView(){return this.viewer?this.viewer.getFieldOfView():45}jumpCameraToGoal(){this.viewer?.jumpCameraToGoal()}toDataURL(t,r){return this.viewer&&this.viewer.render?.(),this.canvas?this.canvas.toDataURL(t,r):""}toBlob(t){return this.viewer&&this.viewer.render?.(),new Promise((r,i)=>{if(!this.canvas||typeof this.canvas.toBlob!="function"){i(new Error("Canvas toBlob is not supported in this environment."));return}this.canvas.toBlob(s=>{s?r(s):i(new Error("Failed to capture canvas blob."))},t?.mimeType,t?.qualityArgument)})}positionAndNormalFromPoint(t,r){if(!this.viewer)return null;let i=this.viewer.raycastFromScreenPoint(t,r);if(!i)return null;let[s,o,c]=i.hitPoint||i.point,[a,u,l]=i.normal;return{position:{x:s,y:o,z:c,toString(){return`${s}m ${o}m ${c}m`}},normal:{x:a,y:u,z:l,toString(){return`${a}m ${u}m ${l}m`}}}}async loadModel(t){return this.loadModelWithLimits(t)}async loadModelWithLimits(t,r){if(!this.viewer){this.currentModel=t,this.currentModelLimits=r;return}try{let i;if(typeof t=="string"){this.isModelLoaded=!1,this.viewer?.clearScene?.();let a=await fetch(t);if(!a.ok)throw new Error(`Failed to load 3D model from "${t}": HTTP ${a.status}`);i=await a.arrayBuffer()}else i=t;let s=Ae(i);this.viewer.loadGLBData(s,r),this.currentModel=s,this.currentModelLimits=r,this.isModelLoaded=!0,this.hidePoster(),this.updateHotspots();let o=this.getAttribute("selected-mesh");o&&this.viewer.setSelectedMesh(o);let c=this.getAttribute("variant-name");c&&this.selectVariant(c),this.dispatchEvent(new CustomEvent("load",{bubbles:!0,composed:!0,detail:{model:s}}))}catch(i){throw this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:i}})),i}}showToast(t,r=4500){if(typeof document>"u")return;let i=this.querySelector(".three-live-toast");i||(i=document.createElement("div"),i.className="three-live-toast",i.style.cssText="position:absolute;bottom:70px;left:50%;transform:translateX(-50%) translateY(10px);z-index:10;padding:10px 16px;background-color:rgba(15,23,42,0.94);color:#f8fafc;border:1px solid rgba(56,189,248,0.45);border-radius:14px;font:500 13px/1.35 system-ui,-apple-system,sans-serif;box-shadow:0 10px 25px rgba(0,0,0,0.45);backdrop-filter:blur(12px);pointer-events:none;opacity:0;transition:opacity .25s ease,transform .25s ease;max-width:88%;text-align:center;white-space:normal;word-break:break-word",this.appendChild(i)),i.textContent=t,this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=null),typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{i&&(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)")}):(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)"),this.toastTimer=setTimeout(()=>{i&&(i.style.opacity="0",i.style.transform="translateX(-50%) translateY(10px)"),this.toastTimer=null},r)}async activateAR(){if(this.activeXRSession&&typeof this.activeXRSession.isSessionActive=="function"&&this.activeXRSession.isSessionActive()&&(await this.activeXRSession.stop().catch(()=>{}),this.activeXRSession=null),!this.currentModel){let i=new Error("No 3D model is loaded in <three-live>.");throw this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(i.message,6e3),i}if(!he.arProvider){let i=new Error("AR module not bundled. Use the default 'three-live' bundle or call ThreeLiveElement.registerAR().");throw this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(i.message,6e3),i}let t=this.getAttribute("ios-src"),r=(this.getAttribute("ar-modes")||"").split(/\s+/).filter(Boolean);try{this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"session-started"}}));let i=await he.arProvider.activateAR({model:t||this.currentModel,glbUrl:typeof this.currentModel=="string"?this.currentModel:void 0,view:this.viewer||void 0,element:this,preferredModes:r.length>0?r:void 0,arScale:this.arScale,arPlacement:this.arPlacement,webXROptions:{onExit:()=>{this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"not-presenting"}}))},onError:s=>{this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:s}})),this.showToast(`AR error: ${s.message}`,6e3)}}});if(i.success)i.session&&(this.activeXRSession=i.session),i.mode==="quick-look"?this.showToast("Opening Apple AR Quick Look..."):i.mode==="scene-viewer"?this.showToast("Opening Google Scene Viewer..."):i.mode==="webxr"&&this.showToast("WebXR AR session started.");else{let s=typeof navigator<"u"&&navigator.userAgent||"",o=/Macintosh/i.test(s)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1),c=/Android|iPhone|iPad|iPod/i.test(s);if(o&&!c&&typeof document<"u"&&this.currentModel&&he.arProvider.createUSDZBlob)try{let a=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:he.arProvider.createUSDZBlob(this.currentModel),u=URL.createObjectURL(a),l=document.createElement("a");l.href=u,l.download="three_live_model.usdz",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(u),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.",6e3)}else this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.",6e3);i.error&&this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i.error}}))}return i}catch(i){throw this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(`AR error: ${i.message||String(i)}`,6e3),i}}setupDOM(){let t=this.querySelector("canvas");t||(t=document.createElement("canvas"),t.style.width="100%",t.style.height="100%",t.style.display="block",t.style.touchAction=this.cameraControls?"none":"auto",t.style.outline="none",this.appendChild(t)),this.canvas=t;let r=this.getAttribute("poster");r&&this.updatePoster(r),this.createARButton(),typeof MutationObserver<"u"&&!this.mutationObserver&&(this.mutationObserver=new MutationObserver(()=>{this.updateARButtonVisibility()}),this.mutationObserver.observe(this,{childList:!0}))}initViewer(){if(!this.canvas)return;let t=this.autoRotate,r=this.exposure,i=this.parseOrbitLimit(this.getAttribute("min-camera-orbit")),s=this.parseOrbitLimit(this.getAttribute("max-camera-orbit")),o=this.parseCameraTarget(this.getAttribute("camera-target")),c=this.parseFieldOfView(this.getAttribute("field-of-view"));this.viewer=new de(this,this.canvas,{autoRotate:t,autoRotateDelay:this.autoRotateDelay,autoRotateSpeed:this.parseRotationPerSecond(this.getAttribute("rotation-per-second")),exposure:r,shadowIntensity:this.shadowIntensity,shadowSoftness:this.shadowSoftness,toneMapping:this.toneMapping,environmentImage:this.environmentImage,autoplay:this.autoplay,animationName:this.animationName||void 0,variantName:this.getAttribute("variant-name")||void 0,fieldOfView:c,cameraTarget:o,minCameraOrbit:i,maxCameraOrbit:s,onMeshClick:u=>{this.dispatchEvent(new CustomEvent("meshclick",{bubbles:!0,composed:!0,detail:u}))},onCameraChange:u=>{this.updateHotspots();for(let l of de.getRegisteredPlugins())l.onCameraChange?.(this.viewer,this);this.dispatchEvent(new CustomEvent("camera-change",{bubbles:!0,composed:!0,detail:u}))}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let a=this.getAttribute("camera-orbit");a&&this.applyCameraOrbit(a),this.currentModel&&this.loadModelWithLimits(this.currentModel,this.currentModelLimits)}setupResizeObserver(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>{this.viewer&&(this.viewer.resize(),this.viewer.render(),this.updateHotspots())}),this.resizeObserver.observe(this))}updatePoster(t){if(!(typeof document>"u")){if(!t){this.posterEl&&(this.posterEl.remove(),this.posterEl=null);return}this.posterEl||(this.posterEl=document.createElement("img"),this.posterEl.setAttribute("alt","3D Scene Preview"),this.posterEl.style.position="absolute",this.posterEl.style.inset="0",this.posterEl.style.width="100%",this.posterEl.style.height="100%",this.posterEl.style.objectFit="cover",this.posterEl.style.transition="opacity 0.35s ease-out",this.posterEl.style.pointerEvents="none",this.posterEl.style.zIndex="1",this.appendChild(this.posterEl)),this.posterEl.src=t,this.isModelLoaded||(this.posterEl.style.opacity="1")}}hidePoster(){this.posterEl&&(this.posterEl.style.opacity="0",setTimeout(()=>{this.isModelLoaded&&this.posterEl&&(this.posterEl.remove(),this.posterEl=null)},400))}createARButton(){if(!(typeof document>"u")){if(!this.arButton){let t=document.createElement("button");t.setAttribute("type","button"),t.setAttribute("aria-label","View in Augmented Reality"),t.className="three-live-ar-button",t.setAttribute("part","default-ar-button");let r="http://www.w3.org/2000/svg";if(typeof document.createElementNS=="function"){let s=document.createElementNS(r,"svg");s.setAttribute("width","20"),s.setAttribute("height","20"),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke","currentColor"),s.setAttribute("stroke-width","2"),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.style.marginRight="6px";let o=document.createElementNS(r,"path");o.setAttribute("d","M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z");let c=document.createElementNS(r,"polyline");c.setAttribute("points","3.27 6.96 12 12.01 20.73 6.96");let a=document.createElementNS(r,"line");a.setAttribute("x1","12"),a.setAttribute("y1","22.08"),a.setAttribute("x2","12"),a.setAttribute("y2","12"),s.appendChild(o),s.appendChild(c),s.appendChild(a),t.appendChild(s)}let i=document.createElement("span");i.textContent="View in AR",t.appendChild(i),t.style.cssText="position:absolute;right:16px;bottom:16px;z-index:2;align-items:center;justify-content:center;padding:8px 16px;background-color:rgba(15,23,42,0.85);color:#fff;border:1px solid rgba(255,255,255,0.15);border-radius:9999px;font:600 13px system-ui,-apple-system,sans-serif;cursor:pointer;backdrop-filter:blur(8px);box-shadow:0 4px 12px rgba(0,0,0,0.25);transition:transform .15s ease,background-color .15s ease;display:none",t.addEventListener("mouseenter",()=>{t.style.backgroundColor="rgba(30, 41, 59, 0.95)",t.style.transform="scale(1.04)"}),t.addEventListener("mouseleave",()=>{t.style.backgroundColor="rgba(15, 23, 42, 0.85)",t.style.transform="scale(1)"}),t.addEventListener("click",s=>{s.stopPropagation(),this.activateAR()}),this.arButton=t,this.appendChild(t)}this.updateARButtonVisibility()}}updateARButtonVisibility(){let t=this.hasAttribute("ar")&&!!he.arProvider,r=typeof this.querySelector=="function"?this.querySelector('[slot="ar-button"]'):null;r?(this.arButton&&(this.arButton.style.display="none"),r.__tlARBound||(r.__tlARBound=!0,r.addEventListener("click",i=>{i.stopPropagation(),this.activateAR()})),r.dataset.tlOrigDisplay===void 0&&(r.dataset.tlOrigDisplay=r.style.display==="none"?"":r.style.display),r.style.display=t?r.dataset.tlOrigDisplay||"":"none"):this.arButton&&(this.arButton.style.display=t?"flex":"none")}applyCameraOrbit(t){if(!(!t||!this.viewer))try{let r=JSON.parse(t);this.viewer.setInitialCamera(r.theta,r.phi,r.distance,r.zoom)}catch{let r=this.parseOrbitLimit(t);(r.theta!==void 0||r.phi!==void 0)&&this.viewer.setInitialCamera(r.theta,r.phi,r.distance)}}parseOrbitLimit(t){if(!t)return{};let r=t.trim().split(/\s+/),i={};if(r.length>0&&r[0]!=="auto"){let s=this.parseFieldOfView(r[0]);s!==void 0&&(i.theta=s)}if(r.length>1&&r[1]!=="auto"){let s=this.parseFieldOfView(r[1]);s!==void 0&&(i.phi=s)}if(r.length>2&&r[2]!=="auto"){let s=parseFloat(r[2].replace(/m$/,""));isNaN(s)||(i.distance=s)}return i}applyOrbitLimits(){if(!this.viewer)return;let t=this.parseOrbitLimit(this.getAttribute("min-camera-orbit")),r=this.parseOrbitLimit(this.getAttribute("max-camera-orbit"));this.viewer.setOrbitLimits({minTheta:t.theta,maxTheta:r.theta,minPhi:t.phi,maxPhi:r.phi,minDistance:t.distance,maxDistance:r.distance})}parseCameraTarget(t){if(!t)return;let r=t.trim().split(/\s+/).map(i=>parseFloat(i.replace(/m$/,"")));return r.length>=3&&!r.some(isNaN)?[r[0],r[1],r[2]]:void 0}parseFieldOfView(t){if(!t)return;let r=t.endsWith("rad")?parseFloat(t)*180/Math.PI:parseFloat(t.replace(/deg$/,""));return isNaN(r)?void 0:r}parseRotationPerSecond(t){if(!t)return Math.PI/6;let r=t.trim(),i=parseFloat(r);return isNaN(i)?Math.PI/6:r.endsWith("rad")?i:r.endsWith("%")?i/100*Math.PI*2:i*Math.PI/180}applyCameraTarget(t){let r=this.parseCameraTarget(t);this.viewer&&r&&this.viewer.setTarget(r[0],r[1],r[2])}applyFieldOfView(t){let r=this.parseFieldOfView(t);this.viewer&&r!==void 0&&this.viewer.setFieldOfView(r)}updateHotspot(t){let r=this.querySelector(`[slot="${t.name}"]`);r&&(t.position!==void 0&&r.setAttribute("data-position",t.position),t.normal!==void 0&&r.setAttribute("data-normal",t.normal)),this.updateHotspots()}updateHotspots(){for(let t of de.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}runWithScriptRunner(t){let r=he.scriptRunner;if(!r){let i=new Error('Procedural script execution requires "three-live/full" or ThreeLiveElement.registerScriptRunner().');return this.showToast(i.message),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:i}})),Promise.reject(i)}return this.scriptHandle&&(this.scriptHandle.terminate(),this.scriptHandle=null),this.isModelLoaded=!1,this.viewer?.clearScene?.(),new Promise((i,s)=>{let o=!1;t(r,{onModelReady:a=>{this.loadModelWithLimits(a,Vn).then(()=>{o||(o=!0,i(a))},u=>{let l=u instanceof Error?u.message:String(u);this.showToast(l),o||(o=!0,s(u))})},onUpdateTransforms:a=>this.viewer?.updateMeshTransforms(a),onError:a=>{this.showToast(a.message),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:a}})),o||(o=!0,s(a))},onToast:a=>this.showToast(a)}).then(a=>{a&&(this.scriptHandle=a)},a=>{a instanceof Error&&a.message&&this.showToast(a.message),o||(o=!0,s(a))})})}loadScriptFromSrc(t){return this.runWithScriptRunner((r,i)=>{if(typeof r.executeUrl!="function"){let s=new Error("Registered ScriptRunner does not support executeUrl() for server-generated scripts.");return i.onError?.(s),Promise.reject(s)}return r.executeUrl(t,this.sandbox,i)})}executeScript(t){if(!he.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(Je);return this.showToast(Qe),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:r}})),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(t,this.sandbox,i,{allowClientScripts:!0}))}};he.observedAttributes=["src","ios-src","script-src","sandbox","allow-client-scripts","poster","camera-controls","camera-orbit","camera-target","min-camera-orbit","max-camera-orbit","field-of-view","selected-mesh","ar","ar-modes","ar-scale","ar-placement","exposure","shadow-intensity","shadow-softness","tone-mapping","bloom","bloom-threshold","bloom-radius","outline","outline-selected","outline-color","environment-image","skybox-image","autoplay","animation-name","variant-name","auto-rotate","auto-rotate-delay","rotation-per-second"],he.registerPlugin=de.registerPlugin,he.getRegisteredPlugins=de.getRegisteredPlugins;var _e=he;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",_e);function xn(){if(typeof window>"u"||typeof navigator>"u")return!1;let n=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(n)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))return!1;let t=document.createElement("a");return t.relList!==void 0&&t.relList.supports!==void 0&&t.relList.supports("ar")}function wn(){if(typeof navigator>"u")return!1;let n=navigator.userAgent||"";return/android/i.test(n)}async function An(){if(typeof navigator>"u")return!1;let n=navigator;if(!n.xr||typeof n.xr.isSessionSupported!="function")return!1;try{return await n.xr.isSessionSupported("immersive-ar")?!0:await n.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function dr(){return(await Mt()).bestMode}async function Mt(){let[n,e,t]=await Promise.all([An(),Promise.resolve(xn()),Promise.resolve(wn())]),r=[];e&&r.push("quick-look"),n&&r.push("webxr"),t&&r.push("scene-viewer");let i=null;return e?i="quick-look":n?i="webxr":t&&(i="scene-viewer"),{webxr:n,quickLook:e,sceneViewer:t,availableModes:r,bestMode:i}}function hr(n,e={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let t,r=!1;if(typeof n=="string"){if(t=hi(n),!t)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else t=URL.createObjectURL(n),r=!0;let i=[];if(e.allowScale===!1&&i.push("allowsContentScaling=0"),e.canonicalWebPageUrl){let c=St(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 St(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 St(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=St(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",St(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,y=Math.cos(h),b=Math.sin(h),d=m*2,g=d+1,T=(m+1)%24*2;r[d*3]=y*.11,r[d*3+1]=.002,r[d*3+2]=b*.11,r[g*3]=y*.145,r[g*3+1]=.002,r[g*3+2]=b*.145,i[d*3+1]=i[g*3+1]=1,o.set([d,T,g,g,T,T+1],m*6)}let c=n.createVertexArray();n.bindVertexArray(c);let a=(m,h,y)=>{let b=n.createBuffer();return n.bindBuffer(34962,b),n.bufferData(34962,m,35044),n.enableVertexAttribArray(h),n.vertexAttribPointer(h,y,5126,!1,0,0),b},u=[a(r,0,3),a(i,1,3),a(s,2,2)],l=n.createBuffer();return u.push(l),n.bindBuffer(34963,l),n.bufferData(34963,o,35044),n.bindVertexArray(null),{name:"__xr_reticle__",nodeIndex:-1,worldSpace:!0,visible:!1,transform:new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),normalMatrix:new Float32Array([1,0,0,0,1,0,0,0,1]),primitives:[{vao:c,indexCount:o.length,indexType:5123,baseColor:e&&e.length>=3?[e[0],e[1],e[2],e[3]??.95]:[.22,.74,.97,.95],metallic:0,roughness:.2,positions:r,indices:o,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:u}]}}function mr(n,e,t,r,i){let s=Math.cos(r),o=Math.sin(r),c=Math.max(.01,i);n.fill(0),n[0]=c*s,n[2]=-c*o,n[5]=c,n[8]=c*o,n[10]=c*s,n[12]=e[0]-c*(s*t[0]+o*t[2]),n[13]=e[1]-c*t[1],n[14]=e[2]-c*(-o*t[0]+s*t[2]),n[15]=1}var 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),y=o?i.arScale==="fixed"?1:h?.55:1:i.arScale==="fixed"?1:a>.45?.3/a:a<.05?.12/Math.max(a,.001):1,b=o?[0,-.25,0]:[u[0]||0,i.arPlacement==="wall"?u[1]:l[1]??0,u[2]||0],d="immersive-ar";try{await r.isSessionSupported("immersive-ar")||(d="immersive-vr")}catch{d="immersive-vr"}let g=s?.querySelector?.('[slot="ar-overlay"]')||null,T=!1,P=null,f=()=>{T&&g?.parentNode&&g.parentNode.removeChild(g),g=null,P=null,T=!1};if(d==="immersive-ar"){if(g)g.addEventListener?.("beforexrselect",E=>E.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let E=document.createElement("div");E.style.cssText="position:fixed;inset:0;pointer-events:none;background:transparent!important;z-index:2147483647;font-family:system-ui,sans-serif;user-select:none";let k=document.createElement("button");k.type="button",k.textContent="\u2715 Exit AR",k.style.cssText="position:absolute;top:max(16px,env(safe-area-inset-top,16px));right:16px;pointer-events:auto;padding:8px 14px;border-radius:99px;border:1px solid rgba(255,255,255,.3);background:rgba(15,23,42,.8);color:#f8fafc;font:600 13px system-ui,sans-serif",k.addEventListener("beforexrselect",G=>G.preventDefault()),k.addEventListener("click",G=>{G.stopPropagation(),this.stop().catch(()=>{})}),P=document.createElement("div"),P.style.cssText="position:absolute;bottom:max(28px,env(safe-area-inset-bottom,28px));left:50%;transform:translateX(-50%);padding:8px 15px;border-radius:99px;border:1px solid rgba(56,189,248,.4);background:rgba(15,23,42,.82);color:#f8fafc;font:500 12.5px system-ui,sans-serif;text-align:center;max-width:88vw",P.textContent="Move phone to detect a surface \u2022 Tap to place",E.appendChild(k),E.appendChild(P),document.body.appendChild(E),g=E,T=!0}}let R=new Set(i.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),p={requiredFeatures:i.requiredFeatures?[...i.requiredFeatures]:[],optionalFeatures:Array.from(R)};g&&(R.add("dom-overlay"),p.optionalFeatures=Array.from(R),p.domOverlay={root:g});for(let E of ce)E.onConfigureXRSessionInit?.(s,p);Array.isArray(p.optionalFeatures)&&p.optionalFeatures.includes("dom-overlay")&&!p.domOverlay?.root&&(p.optionalFeatures=p.optionalFeatures.filter(E=>E!=="dom-overlay"));let M=E=>{let k=String(E?.name||"");return k==="NotAllowedError"||k==="SecurityError"};try{this.s=await r.requestSession(d,p)}catch(E){if(f(),M(E))throw i.onError?.(E),E;try{this.s=await r.requestSession(d,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(k){if(M(k))throw i.onError?.(k),k;try{this.s=await r.requestSession(d)}catch(G){throw i.onError?.(G),G}}}let _=this.s;Ne=this,this.placed=!1;let w=null,A=null,L=null,v=null,x=null,I=[0,-.25,-1.2],S=[0,-.25,-1.2],C=new Float32Array(16),F=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{A?.cancel?.()}catch{}if(A=null,L){let E=e?.meshes;if(Array.isArray(E)){let G=E.indexOf(L);G!==-1&&E.splice(G,1)}let k=e.getGLContext?.()||e?.gl;if(k)for(let G of L.primitives||[]){k.deleteVertexArray?.(G.vao);for(let W of G.buffers||[])k.deleteBuffer?.(W)}L=null}e?.setXRSessionActive?.(!1),f(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=X,_.addEventListener("end",()=>{X(),i.onExit?.()}),_.addEventListener("select",()=>{if(!this.placed){let E=x||I;S=[E[0],E[1],E[2]],mr(this.placedMat,S,b,U,y*V),this.placed=!0,L&&(L.visible=!1),P&&(P.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),i.onPlaced?.(this.placedMat)}});try{let E=e.getGLContext?.()||e?.gl;E&&typeof E.makeXRCompatible=="function"&&await E.makeXRCompatible();let k=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;E&&typeof k=="function"&&typeof _.updateRenderState=="function"&&_.updateRenderState({baseLayer:new k(_,E,{alpha:!0})});try{w=await _.requestReferenceSpace("local")}catch{try{w=await _.requestReferenceSpace("local-floor")}catch{w=await _.requestReferenceSpace("viewer")}}let G=await _.requestReferenceSpace("viewer").catch(()=>w);if(typeof _.requestHitTestSource=="function"&&G&&(A=await _.requestHitTestSource({space:G}).catch(()=>null)),d==="immersive-ar"&&E&&typeof E.createVertexArray=="function"&&Array.isArray(e.meshes)&&(L=fi(E,i.reticleColor),e.meshes.push(L)),typeof window<"u"&&typeof window.addEventListener=="function"){let j=Y=>Math.hypot(Y.touches[1].clientX-Y.touches[0].clientX,Y.touches[1].clientY-Y.touches[0].clientY),re=Y=>Math.atan2(Y.touches[1].clientY-Y.touches[0].clientY,Y.touches[1].clientX-Y.touches[0].clientX),ue=Y=>{this.s&&(Y.touches.length===1&&this.placed?B=!0:Y.touches.length>=2&&(B=!1,D=j(Y),H=re(Y)))},q=Y=>{if(!this.s||Y.touches.length<2)return;let ie=j(Y),$=re(Y);if(D&&D>4&&i.arScale!=="fixed"&&(V=Math.max(.15,Math.min(6,V*(ie/D)))),H!==null){let ne=$-H;ne>Math.PI&&(ne-=Math.PI*2),ne<-Math.PI&&(ne+=Math.PI*2),U-=ne}D=ie,H=$},Z=Y=>{(!Y.touches||Y.touches.length===0)&&(B=!1),(!Y.touches||Y.touches.length<2)&&(D=null,H=null)};window.addEventListener("touchstart",ue,{passive:!0}),window.addEventListener("touchmove",q,{passive:!0}),window.addEventListener("touchend",Z,{passive:!0}),window.addEventListener("touchcancel",Z,{passive:!0}),O=()=>{window.removeEventListener("touchstart",ue),window.removeEventListener("touchmove",q),window.removeEventListener("touchend",Z),window.removeEventListener("touchcancel",Z)}}e.setXRSessionActive?.(!0);let W=(j,re)=>{if(this.s!==_)return;_.requestAnimationFrame(W);let ue=z>0?Math.min(Math.max((j-z)/1e3,0),.1):1/60;z=j,e?.stepXRUpdate?.(ue);let q=re.getViewerPose(w);if(!q)return;let Z=q.views?.[0];if(!N&&Z?.transform){let ee=Z.transform.position,se=Z.transform.matrix,be=ee?.x??(se?se[12]:0),me=ee?.y??(se?se[13]:0),fe=ee?.z??(se?se[14]:0),Ee=se?-se[8]:0,Xe=se?-se[10]:-1,Tt=Math.hypot(Ee,Xe);Tt>1e-4?(Ee/=Tt,Xe/=Tt):(Ee=0,Xe=-1),I=[be+Ee*1.2,me-.25,fe+Xe*1.2],U=Math.atan2(-Ee,-Xe),N=!0}if(A&&typeof re.getHitTestResults=="function"&&(!this.placed||B)){let ee=re.getHitTestResults(A)||[],se=!1;for(let be of ee){let me=be.getPose(w);if(me?.transform?.matrix){let fe=me.transform.matrix,Ee=fe[5];if(i.arPlacement==="wall"&&Math.abs(Ee)>.35||i.arPlacement==="floor"&&Math.abs(Ee)<.65)continue;v||(v=new Float32Array(16)),v.set(fe),x=[fe[12],fe[13],fe[14]],this.placed&&B&&(S=[fe[12],fe[13],fe[14]]),L&&(L.visible=!this.placed||B,L.transform.set(fe)),!this.placed&&P&&(P.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),i.onHit?.(v),se=!0;break}}!se&&L&&(L.visible=!1)}mr(C,this.placed?S:x||I,b,U,y*V),this.placed&&this.placedMat.set(C);let Y=e.xrRigMatrix;Y instanceof Float32Array&&Y.length===16?ae(F,Y,C):F.set(C),e.modelRootMatrix&&e.modelRootMatrix.set(F);for(let ee of ce)ee.onXRFrame?.(e,_,re,w);let ie=e.getGLContext?.()||e?.gl,$=_.renderState?.baseLayer;ie&&$&&$.framebuffer!==void 0&&ie.bindFramebuffer(36160,$.framebuffer);let ne=d==="immersive-ar",te=q.views||[];for(let ee=0;ee<te.length;ee++){let se=te[ee];if(typeof e.renderXRView=="function"){let be;if($&&typeof $.getViewport=="function"){let me=$.getViewport(se);me&&me.width>0&&me.height>0&&(be=[me.x,me.y,me.width,me.height])}else $?.framebufferWidth>0&&$?.framebufferHeight>0&&(be=[0,0,$.framebufferWidth,$.framebufferHeight]);e.renderXRView(se,F,this.placed,be,ne,ee)}}ie&&$&&$.framebuffer&&ie.bindFramebuffer(36160,null)};_.requestAnimationFrame(W)}catch(E){throw typeof _.end=="function"&&await _.end().catch(()=>{}),X(),i.onError?.(E),E}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function Et(n){let e=await Mt(),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:Et,createUSDZBlob:Ue});_e.registerScriptRunner(yn);Ze(Mn);return vr(pi);})();
|
|
350
|
+
`+p.script+`
|
|
351
|
+
;
|
|
352
|
+
return typeof scene === "object" && scene ? scene : undefined;
|
|
353
|
+
})();`);g=null;let E=F(b,x,S,N);E&&typeof E.toGLB=="function"&&(x=E)}if(!M){b.SceneQuotaValidator&&b.SceneQuotaValidator.validate(x);let F=x.toGLB(),E=F instanceof ArrayBuffer?F:F.buffer.slice(F.byteOffset,F.byteOffset+F.byteLength);w({type:"3D_MODEL_READY",glbBuffer:E},[E])}h({type:"DONE",nonce:r})}catch(x){l(x&&x.message||x)}}},h({type:"READY",nonce:r})}function ki(e,t,i){let r=i?.allowedScriptUrl??null,s=i?.allowClientScripts??r===null,a={nonce:t,engineSrc:e,allowedScriptUrl:r,allowClientScripts:s,revoked:Ls},o=(ot().workerExtensionInstallers??[]).map(n=>`(${n.toString()})`).join(",");return`'use strict';(${Ds.toString()})(${JSON.stringify(a)},[${o}]);`}function Fi(e){e.onError?.(new Error("SecurityError: Sandboxed script exceeded SECURITY_3D_SANDBOX_TIMEOUT_MS (3000 ms) and was terminated.")),e.onToast?.("Security Error: script timed out and was stopped.")}var Dt=0;function Ii(){try{let e=new Uint32Array(4);return globalThis.crypto?.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(8,"0")).join("")}catch{return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}}function ks(e){try{return new TextEncoder().encode(e).length}catch{return e.length}}var Fs=1024,Is=256;function Oi(e){if(!Array.isArray(e)&&!(e instanceof Float32Array)||e.length!==16)return!1;for(let t=0;t<16;t++){let i=e[t];if(typeof i!="number"||!Number.isFinite(i))return!1}return!0}function Ui(e,t){if(!e||typeof e!="object")return null;let i=e;if(i.nonce!==t)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,Fs)};case"3D_UPDATE_TRANSFORMS":{let r=i.transforms;if(Array.isArray(r)){if(r.length>1e3)return null;for(let s of r)if(!Oi(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>Is||n==="__proto__"||n==="constructor"||n==="prototype")return null;let h=o[n];if(!Oi(h))return null;a[n]=h}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 Os(e){let t=ks(e);if(t>1048576)throw new Error(`SecurityError: Script length (${t} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function Vi(e,t,i,r){switch(e.type){case"READY":return;case"3D_UPDATE_TRANSFORMS":t.onUpdateTransforms?.(e.transforms);return;case"3D_MODEL_READY":if(r.modelDispatched)return;r.modelDispatched=!0,t.onModelReady(e.payload);return;case"DONE":i();return;case"ERROR":i(),t.onError?.(new Error(`Worker script error: ${e.message}`));return;default:return e}}function Us(e,t,i,r){let s=Ii(),a=ki(t,s,e.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:e.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,Dt++;let n=!1,h=!1,l={modelDispatched:!1},c,f=()=>{if(n||h)return;let d=o.contentWindow;!d||typeof d.postMessage!="function"||(h=!0,d.postMessage(e.kind==="url"?{type:"SANDBOX_RUN",nonce:s,workerSource:a,scriptUrl:e.scriptUrl}:{type:"SANDBOX_RUN",nonce:s,workerSource:a,script:e.script},"*"))},g=()=>{},b=d=>{if(n||!o.contentWindow||d.source!==o.contentWindow)return;let M=d.data;if(M&&typeof M=="object"&&M.type==="IFRAME_READY"){f();return}let w=Ui(M,s);w&&Vi(w,r,g,l)};g=()=>{n||(n=!0,c!==void 0&&clearTimeout(c),Dt=Math.max(0,Dt-1),typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("message",b),typeof o.remove=="function"?o.remove():o.parentNode&&o.parentNode.removeChild(o))},c=setTimeout(()=>{n||(g(),Fi(r))},3e3),typeof globalThis.addEventListener=="function"&&globalThis.addEventListener("message",b),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 u=document.body||document.documentElement;if(!u||typeof u.appendChild!="function"){g();let d=new Error("SecurityError: Cannot mount sandbox iframe because document.body is unavailable.");throw r.onError?.(d),d}return u.appendChild(o),{terminate:g}}function zi(e,t,i,r){if(t==="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(t==="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(Dt>=32)return r(`SecurityError: ${Dt} 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=Cs()}catch(g){let b=g instanceof Error?g.message:String(g);return r(b,"Security Error: sandbox engine URL is not configured.")}if(t==="iframe"){let g;try{g=Es()}catch(b){let u=b instanceof Error?b.message:String(b);return r(u,"Security Error: sandbox iframe URL is not configured.")}try{return Promise.resolve(Us(e,s,g,i))}catch(b){return Promise.reject(b)}}let a=Ii(),o=ki(s,a,e.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:e.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),n;try{let g=new Blob([o],{type:"application/javascript"}),b=URL.createObjectURL(g);try{let u=Rs(b);n=new Worker(u)}finally{URL.revokeObjectURL(b)}}catch(g){let b=g instanceof Error?g.message:String(g);return r(`Failed to initialize Web Worker for sandboxed execution (CSP may block blob workers): ${b}`,"Security Error: Failed to start Worker sandbox.")}Dt++;let h=!1,l={modelDispatched:!1},c,f=()=>{h||(h=!0,c!==void 0&&clearTimeout(c),Dt=Math.max(0,Dt-1),n.terminate())};return c=setTimeout(()=>{h||(f(),Fi(i))},3e3),n.onmessage=g=>{let b=Ui(g.data,a);b&&Vi(b,i,f,l)},n.onerror=g=>{f(),i.onError?.(new Error(`Worker execution error: ${g.message}`))},e.kind==="url"?n.postMessage({type:"EXECUTE_URL",scriptUrl:e.scriptUrl,nonce:a}):n.postMessage({type:"EXECUTE",script:e.script,nonce:a}),Promise.resolve({terminate:f})}function Bi(e,t){return e==="none"||e==="unsafe-host-realm"?t(`SecurityError: sandbox="${e}" is prohibited. Sandboxing is mandatory for live compilation and cannot be bypassed. Use sandbox="worker" (default) or sandbox="iframe".`,`Security Error: sandbox="${e}" is not permitted.`):e!=="worker"&&e!=="iframe"?t(`SecurityError: Unsupported sandbox mode "${e}". Live compilation requires sandbox="worker" or sandbox="iframe".`,"Security Error: unsupported sandbox mode."):null}var $i=e=>(t,i)=>{let r=new Error(t);return e.onError?.(r),i&&e.onToast?.(i),Promise.reject(r)},Hi={execute(e,t,i,r){let s=$i(i),a=Bi(t,s);if(a)return a;try{Os(e)}catch(o){let n=o instanceof Error?o.message:String(o);return s(n,"Security Error: script exceeds the size limit.")}return r?.allowClientScripts??_s()?zi({kind:"script",script:e},t,i,s):s(We,je)},executeUrl(e,t,i){let r=$i(i),s=Bi(t,r);if(s)return s;let a;try{a=Ns(e)}catch(o){let n=o instanceof Error?o.message:String(o);return r(n,"Security Error: disallowed scene script URL.")}return zi({kind:"url",scriptUrl:a},t,i,r)}},ue=new Set;function $t(e,t){let i=`[three-live] ${e} is unsupported; degraded to ${t}.`;ue.has(i)||(ue.add(i),typeof console<"u"&&typeof console.warn=="function"&&console.warn(i))}function Vs(){return Array.from(ue)}function zs(){ue.clear()}var Gi=class extends ae{constructor(e={}){$t("ShaderMaterial","MeshStandardMaterial");let t=e.uniforms||{},i=t.color?.value??t.uColor?.value??t.diffuse?.value??e.color;super({color:i!==void 0?i:8421504,opacity:t.opacity?.value??e.opacity??1,transparent:!!e.transparent,wireframe:!!e.wireframe,side:e.side}),this.uniforms=t}},Bs=Gi,Kt=class extends ft{constructor(e=[],t=[],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=[],h=[],l=[],c=[],f=new Q,g=new Q,b=new Q,u=(w,v)=>v.set(e[w*3]||0,e[w*3+1]||0,e[w*3+2]||0),d=(w,v)=>{let m=w.clone().normalize();n.push(m.x*s,m.y*s,m.z*s),h.push(v.x,v.y,v.z),l.push(Math.atan2(m.z,-m.x)/(2*Math.PI)+.5,1-Math.acos(Math.max(-1,Math.min(1,m.y)))/Math.PI)},M=(w,v,m)=>{let p=n.length/3,x=a===0?new Q().subVectors(m,v).cross(new Q().subVectors(w,v)).normalize():null;d(w,x||w.clone().normalize()),d(v,x||v.clone().normalize()),d(m,x||m.clone().normalize()),c.push(p,p+1,p+2)};for(let w=0;w<t.length;w+=3){u(t[w],f),u(t[w+1],g),u(t[w+2],b);let v=[];for(let m=0;m<=o;m++){v[m]=[];let p=f.clone().lerp(b,m/o),x=g.clone().lerp(b,m/o),S=o-m;for(let N=0;N<=S;N++)v[m][N]=S===0?p.clone():p.clone().lerp(x,N/S)}for(let m=0;m<o;m++)for(let p=0;p<2*(o-m)-1;p++){let x=p>>1;(p&1)===0?M(v[m][x+1],v[m+1][x],v[m][x]):M(v[m][x+1],v[m+1][x+1],v[m+1][x])}}this.setFromBuffers(n,h,l,c)}},$s=class extends Kt{constructor(e=1,t=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],e,t)}},ce=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],Wi=[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],Hs=class extends Kt{constructor(e=1,t=0){super(ce,Wi,e,t)}},ut=(1+Math.sqrt(5))/2,Gs=class extends Kt{constructor(e=1,t=0){super([-1,ut,0,1,ut,0,-1,-ut,0,1,-ut,0,0,-1,ut,0,1,ut,0,-1,-ut,0,1,-ut,ut,0,-1,ut,0,1,-ut,0,-1,-ut,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],e,t)}},St=1/ut,Ws=class extends Kt{constructor(e=1,t=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,-St,-ut,0,-St,ut,0,St,-ut,0,St,ut,-St,-ut,0,-St,ut,0,St,-ut,0,St,ut,0,-ut,0,-St,ut,0,-St,-ut,0,St,ut,0,St],[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],e,t)}},js=class extends wi{constructor(e=1,t=1,i=4,r=8){let s=Math.max(1e-4,Number(e)||1),a=Math.max(0,Number.isFinite(Number(t))?Number(t):1)*.5,o=Math.max(2,Math.min(64,Math.floor(Number(i)||4))),n=[];for(let h=-1;h<=1;h+=2)for(let l=0;l<=o;l++){if(h>0&&l===0&&a===0)continue;let c=(h<0?l/o-1:l/o)*(Math.PI/2);n.push(new Ct(Math.max(0,Math.cos(c)*s),h*a+Math.sin(c)*s))}super(n,Math.max(4,Math.min(128,Math.floor(Number(r)||8))))}},ji=class extends ft{constructor(e=.5,t=1,i=32,r=1,s=0,a=Math.PI*2){super();let o=Math.max(1e-4,Number(t)||1),n=Number(e),h=Number.isFinite(n)?Math.max(0,n):o*.5,l=Math.max(o,h),c=Math.min(l*.999,Math.min(o,h)),f=Math.max(3,Math.min(256,Math.floor(Number(i)||32))),g=Math.max(1,Math.min(64,Math.floor(Number(r)||1))),b=Number.isFinite(Number(s))?Number(s):0,u=Number.isFinite(Number(a))?Number(a):Math.PI*2,d=[],M=[],w=[],v=[];for(let m=0;m<=g;m++){let p=c+m/g*(l-c);for(let x=0;x<=f;x++){let S=b+x/f*u,N=Math.cos(S),F=Math.sin(S);if(d.push(p*N,p*F,0),M.push(0,0,1),w.push(p/l*N*.5+.5,p/l*F*.5+.5),m<g&&x<f){let E=m*(f+1)+x,L=E+f+1;p>1e-6&&v.push(E,L,E+1),v.push(L,L+1,E+1)}}}this.setFromBuffers(d,M,w,v)}},Xs=class extends ji{constructor(e=1,t=32,i=0,r=Math.PI*2){super(0,e,t,1,i,r)}},Xi=class extends Tt{constructor(e={}){super({roughness:.35,metalness:.1,side:2,...e});let t=Number(e.size);this.size=Number.isFinite(t)?Math.max(.002,Math.min(2,t)):.05,this.sizeAttenuation=e.sizeAttenuation!==!1,e.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.35)}},Ie=class extends Tt{constructor(e={}){super({roughness:.4,metalness:.1,side:2,...e});let t=Number(e.linewidth);this.linewidth=Number.isFinite(t)?Math.max(.5,Math.min(20,t)):1,e.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.3)}},qs=class extends Ie{constructor(e={}){super(e),this.dashSize=Number(e.dashSize)||3,this.gapSize=Number(e.gapSize)||1,this.scale=Number(e.scale)||1}};function qi(e,t){let i=e?.attributes?.position;if(!i?.array||i.count<3)return new Float32Array(0);let r=i.array,s=e?.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=t===void 0,h=n?1:Math.cos(t*Math.PI/180),l={},c=[],f=(g,b)=>c.push(r[g*3]||0,r[g*3+1]||0,r[g*3+2]||0,r[b*3]||0,r[b*3+1]||0,r[b*3+2]||0);for(let g=0;g<a;g++){let b=s?s[g*3]:g*3,u=s?s[g*3+1]:g*3+1,d=s?s[g*3+2]:g*3+2,M=r[b*3]||0,w=r[b*3+1]||0,v=r[b*3+2]||0,m=(r[u*3]||0)-M,p=(r[u*3+1]||0)-w,x=(r[u*3+2]||0)-v,S=(r[d*3]||0)-M,N=(r[d*3+1]||0)-w,F=(r[d*3+2]||0)-v,E=p*F-x*N,L=x*S-m*F,C=m*N-p*S,D=Math.hypot(E,L,C);if(!n&&D<1e-8)continue;D>0&&(E/=D,L/=D,C/=D);let R=[b,u,d];for(let y=0;y<3;y++){let U=R[y],j=R[(y+1)%3],T=o(U),k=o(j);if(T===k)continue;let A=T<k?`${T}|${k}`:`${k}|${T}`,P=l[A];P?P.m||(P.m=1,P.nx*E+P.ny*L+P.nz*C<=h&&f(U,j)):(l[A]={va:U,vb:j,nx:E,ny:L,nz:C,m:n?1:0},n&&f(U,j))}}if(!n){let g=Object.keys(l);for(let b=0;b<g.length;b++){let u=l[g[b]];u&&!u.m&&f(u.va,u.vb)}}return new Float32Array(c)}var Ks=class extends ft{constructor(e){super(),this.setAttribute("position",new bt(qi(e),3)),this.__isSegmentPairs=!0}},Ys=class extends ft{constructor(e,t=1){super();let i=Number.isFinite(Number(t))?Number(t):1;this.setAttribute("position",new bt(qi(e,i),3)),this.__isSegmentPairs=!0}};function Zs(e,t,i=1){let r=new ft;r.__baked=!0;let s=e?.attributes?.position;if(!s?.array||s.count<2)return r;let a=s.array,o=e.index?.array,n=e.__isSegmentPairs?"segments":t,h=o?o.length:s.count,l=Math.min(4096,Math.max(0,n==="segments"?Math.floor(h/2):n==="loop"&&h>=3?h:h-1));if(l===0)return r;e.computeBoundingBox();let c=e.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))),b=[],u=[],d=[],M=[];for(let w=0;w<l;w++){let v=n==="segments"?w*2:w,m=n==="segments"?w*2+1:(w+1)%h,p=o?o[v]:v,x=o?o[m]:m,S=a[p*3]||0,N=a[p*3+1]||0,F=a[p*3+2]||0,E=(a[x*3]||0)-S,L=(a[x*3+1]||0)-N,C=(a[x*3+2]||0)-F,D=Math.hypot(E,L,C);if(D<1e-6)continue;let R=E/D,y=L/D,U=C/D,j=(Math.abs(y)<.9?Math.hypot(U,R):Math.hypot(U,y))||1,T=Math.abs(y)<.9?U/j:0,k=Math.abs(y)<.9?0:-U/j,A=Math.abs(y)<.9?-R/j:y/j,P=y*A-U*k,G=U*T-R*A,q=R*k-y*T,$=b.length/3,Y=[[T,k,A],[P,G,q],[-T,-k,-A],[-P,-G,-q]];for(let _=0;_<2;_++){let z=S+_*E,V=N+_*L,W=F+_*C;for(let O=0;O<4;O++){let H=Y[O];b.push(z+H[0]*g,V+H[1]*g,W+H[2]*g),u.push(H[0],H[1],H[2]),d.push(O/4,_)}}for(let _=0;_<4;_++){let z=(_+1)%4;M.push($+_,$+z,$+4+z,$+_,$+4+z,$+4+_)}}return b.length>0&&r.setFromBuffers(b,u,d,M),r}function Js(e,t=.05){let i=new ft;i.__baked=!0;let r=e?.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(t)||.05)*.6)),h=[],l=[],c=[],f=[];for(let g=0;g<o;g++){let b=a<=5e3?g:Math.floor(g*a/o),u=s[b*3]||0,d=s[b*3+1]||0,M=s[b*3+2]||0,w=g*6;for(let v=0;v<6;v++){let m=ce[v*3],p=ce[v*3+1],x=ce[v*3+2];h.push(u+m*n,d+p*n,M+x*n),l.push(m,p,x),c.push(.5,.5)}for(let v=0;v<24;v++)f.push(w+Wi[v])}return i.setFromBuffers(h,l,c,f),i}var Yt=class extends kt{constructor(e,t,i="strip"){let r=t&&typeof t=="object"?t:{},s=t instanceof Tt?t:i==="points"?new Xi(r):new Ie(r),a=e instanceof ft?e:new ft;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 e=this._lineMode==="points";if(e){let t=this._sourceGeo?.attributes?.color;if(t?.array&&t.count>0&&this.material?.color.r===1&&this.material.color.g===1&&this.material.color.b===1){let i=t.array,r=Math.min(t.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>=(e?1:2)&&(this.geometry=e?Js(this._sourceGeo,this.material?.size??.05):Zs(this._sourceGeo,this._lineMode,this.material?.linewidth??1))}},Qs=class extends Yt{constructor(e,t){super(e,t,"loop"),this.isLineLoop=!0}},ta=class extends Yt{constructor(e,t){super(e,t,"segments"),this.isLineSegments=!0}},ea=class extends Yt{constructor(e,t){super(e,t,"points"),this.isPoints=!0}},ia=class extends Ti{constructor(e,t,i=0,r=Math.PI/3,s=0,a=2){super(e,t,i,a),this.target=new Lt,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}},Ki=class extends Ai{constructor(e,t,i){$t("HemisphereLight","AmbientLight"),super(e,i),this.groundColor=new Nt(t??4473924)}},ra=Ki,Yi={Vector2:Ct,Vector3:Q,Vector4:Zr,Euler:fi,Quaternion:gi,Matrix4:jt,Matrix3:Jr,Color:Nt,MathUtils:Qr,BufferAttribute:bt,Float32BufferAttribute:ts,Uint16BufferAttribute:es,Uint32BufferAttribute:is,BufferGeometry:ft,BoxGeometry:yi,PlaneGeometry:rs,SphereGeometry:ss,CylinderGeometry:vi,ConeGeometry:as,TorusGeometry:ns,TorusKnotGeometry:os,Curve:Bt,Curve3:Bt,LineCurve3:ls,QuadraticBezierCurve3:hs,CubicBezierCurve3:us,CatmullRomCurve3:cs,LatheGeometry:wi,TubeGeometry:ms,PolyhedronGeometry:Kt,IcosahedronGeometry:Gs,OctahedronGeometry:Hs,DodecahedronGeometry:Ws,TetrahedronGeometry:$s,CapsuleGeometry:js,RingGeometry:ji,CircleGeometry:Xs,WireframeGeometry:Ks,EdgesGeometry:Ys,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:De,DataTexture:ds,TextureLoader:ps,Material:Tt,MeshStandardMaterial:ae,MeshBasicMaterial:fs,MeshLambertMaterial:gs,MeshPhongMaterial:bs,MeshPhysicalMaterial:ys,PointsMaterial:Xi,LineBasicMaterial:Ie,LineDashedMaterial:qs,ShaderMaterial:Gi,RawShaderMaterial:Bs,Object3D:Lt,Group:vs,Mesh:kt,InstancedMesh:Si,Line:Yt,LineLoop:Qs,LineSegments:ta,Points:ea,Light:oe,AmbientLight:Ai,DirectionalLight:xs,PointLight:Ti,SpotLight:ia,HemisphereLight:Ki,RectAreaLight:ra,Camera:Ri,PerspectiveCamera:ws,Scene:Ci,WebGLRenderer:Ss,Clock:As,SceneQuotaValidator:Ft,exportSceneToCanvas3D:Pi,exportSceneToGLB:Ei,exportSceneToUSDZ:Ms,generateUSDZ:pi,glbToUSDZ:di,sceneToCanvas3D:te,sceneToGLB:Re,sceneToUSDZ:Ne,authorScriptRunner:Hi,getAuthorWarnings:Vs,clearAuthorWarnings:zs};Object.freeze(Ft),Object.freeze(Ft.prototype),Object.freeze(Ci.prototype),Object.freeze(Yi);var Ht=new Proxy(Yi,{get:(e,t)=>{if(t in e)return e[t];let i=ot().authorNamespace;return i&&typeof t=="string"&&t in i?i[t]:(typeof t=="string"&&t!=="then"&&t!=="toJSON"&&!t.startsWith("__")&&$t(`THREE.${t}`,"no-op proxy"),le)},has:(e,t)=>{if(t in e)return!0;let i=ot().authorNamespace;return!!(i&&typeof t=="string"&&t in i)},set:(e,t)=>{throw new TypeError(`Cannot assign to read only property '${String(t)}' of #<THREE>`)},defineProperty:(e,t)=>{throw new TypeError(`Cannot define property '${String(t)}', object is not extensible`)},deleteProperty:(e,t)=>{throw new TypeError(`Cannot delete property '${String(t)}' of #<THREE>`)},setPrototypeOf:()=>{throw new TypeError("#<THREE> is not extensible")}}),me=ot();if(me.threeNamespace=Ht,me.workerExtensionInstallers)for(let e of me.workerExtensionInstallers)e(Ht,me);var Oe={name:"three_author",THREE:Ht},Pt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;if(typeof Pt.THREE>"u"&&(Pt.THREE=Ht),typeof Pt.requestAnimationFrame!="function"&&(Pt.requestAnimationFrame=e=>(typeof e=="function"&&typeof Pt.__three_live_raf_cb__!="function"&&(Pt.__three_live_raf_cb__=e),Pt.__three_live_in_step__||$t("requestAnimationFrame","single-frame static evaluation"),0)),typeof Pt.cancelAnimationFrame!="function"&&(Pt.cancelAnimationFrame=()=>{}),typeof window<"u"){let e=window;e.ThreeLive=e.ThreeLive||{},e.ThreeLive.THREE=Ht,e.ThreeLivePlugins=e.ThreeLivePlugins||{},e.ThreeLivePlugins.threeAuthor=Oe,e.ThreeLivePlugins.three_author=Oe,e.ThreeLivePlugins["three-author"]=Oe}function Zi(e,t){let i=e?.trim(),r=i?Number(i):NaN;return Number.isFinite(r)?r:t}var Ue=(e,t,i)=>({x:e,y:t,z:i,toString:()=>`${e}m ${t}m ${i}m`}),sa=typeof HTMLElement<"u"?HTMLElement:class{};typeof CustomEvent>"u"&&typeof Event<"u"&&(globalThis.CustomEvent=class extends Event{constructor(e,t){super(e,t),this.detail=t?.detail??null}});var de=class xt extends sa{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 ot().arProvider}static set arProvider(t){ot().arProvider=t}static get scriptRunner(){return ot().scriptRunner}static set scriptRunner(t){ot().scriptRunner=t}static get sandboxEngineSrc(){return ot().sandboxEngineSrc??null}static set sandboxEngineSrc(t){ot().sandboxEngineSrc=t}static get sandboxIframeSrc(){return ot().sandboxIframeSrc??null}static set sandboxIframeSrc(t){ot().sandboxIframeSrc=t}static get allowClientScripts(){return!!ot().allowClientScripts}static set allowClientScripts(t){ot().allowClientScripts=t}static registerScriptRunner(t){xt.scriptRunner=t}static registerDecoder(t,i){Mt.registerDecoder(t,i)}static getDecoder(t){return Mt.getDecoder(t)}static registerAR(t){typeof t=="function"?xt.arProvider={activateAR:t}:xt.arProvider=t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(i=>{i instanceof xt&&i.updateARButtonVisibility()})}static isARSupported(){return!!xt.arProvider}getLoadedModel(){return this.currentModel}beginLoad(){let t=this.loadController,i=this.scriptHandle,r=new AbortController;return this.loadController=r,this.scriptHandle=null,t?.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 t=this.getAttribute("src"),i=this.getAttribute("script-src");if(t)this.loadModel(t).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 Mt.getRegisteredPlugins())r.onElementConnected?.(this)}disconnectedCallback(){for(let t of Mt.getRegisteredPlugins())t.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(t,i,r){if(i!==r){switch(t){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(Ut(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 Mt.getRegisteredPlugins())s.onAttributeChanged?.(this,t,i,r)}}getAttr(t){return this.getAttribute(t)}setAttr(t,i){i!==null?this.setAttribute(t,String(i)):this.removeAttribute(t)}getBoolAttr(t){return this.hasAttribute(t)&&this.getAttr(t)!=="false"}setBoolAttr(t,i){this.setAttr(t,i?"":null)}getFloatAttr(t,i){let r=this.getAttr(t);return r!==null?parseFloat(r):i}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.getAttr("sandbox")||(ot().sandboxIframeSrc?"iframe":"worker")}set sandbox(t){this.setAttr("sandbox",t)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||xt.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.setAttr("exposure",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.setAttr("auto-rotate-delay",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.getAttr("ar-scale")||"auto"}set arScale(t){this.setAttr("ar-scale",t)}get arPlacement(){return this.getAttr("ar-placement")||"floor"}set arPlacement(t){this.setAttr("ar-placement",t)}get canActivateAR(){return xt.isARSupported()}get shadowIntensity(){return this.getFloatAttr("shadow-intensity",0)}set shadowIntensity(t){this.setAttr("shadow-intensity",t)}get shadowSoftness(){return this.getFloatAttr("shadow-softness",.5)}set shadowSoftness(t){this.setAttr("shadow-softness",t)}get toneMapping(){return Ut(this.getAttr("tone-mapping"))}set toneMapping(t){this.setAttr("tone-mapping",t)}get bloom(){return this.getFloatAttr("bloom",0)}set bloom(t){this.setAttr("bloom",t)}get bloomThreshold(){return Zi(this.getAttr("bloom-threshold"),.62)}set bloomThreshold(t){this.setAttr("bloom-threshold",t)}get bloomRadius(){return Zi(this.getAttr("bloom-radius"),.75)}set bloomRadius(t){this.setAttr("bloom-radius",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,i){this.dispatchEvent(new CustomEvent(t,{bubbles:!0,composed:!0,detail:i}))}setSlotVisible(t,i){let r=typeof this.querySelector=="function"?this.querySelector(`[slot="${t}"]`):null;r&&(r.hidden=!i,r.style&&(r.style.display=i?"":"none"))}emitError(t,i="script"){this.setSlotVisible("error",!0),this.fireEvent("error",{error:t}),this.fireEvent("three-error",{error:t,message:t?.message||String(t),stage:i})}selectVariant(t){if(!this.viewer)return!1;let i=this.viewer.selectVariant(t);return i&&this.fireEvent("variant-applied",{variantName:this.viewer.getVariantName()}),i}get model(){let t=this.viewer?this.viewer.getModelMaterials():[];return{materials:t,getMaterialByName(i){return t.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(t=0){this.viewer?.resetTurntableRotation(t)}setCamera(t,i,r,s){this.viewer&&this.viewer.setCamera(t,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():Ue(0,0,0)}getFieldOfView(){return this.viewer?this.viewer.getFieldOfView():45}jumpCameraToGoal(){this.viewer?.jumpCameraToGoal()}toDataURL(t,i){return this.viewer?.render?.(),this.canvas?this.canvas.toDataURL(t,i):""}toBlob(t){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."))},t?.mimeType,t?.qualityArgument)})}positionAndNormalFromPoint(t,i){let r=this.viewer?.raycastFromScreenPoint(t,i);if(!r)return null;let[s,a,o]=r.hitPoint||r.point,[n,h,l]=r.normal;return{position:Ue(s,a,o),normal:Ue(n,h,l)}}loadModel(t){return this.loadModelWithLimits(t)}async loadModelWithLimits(t,i,r=this.beginLoad()){if(r.signal.throwIfAborted(),!this.viewer){this.currentModel=t,this.currentModelLimits=i;return}try{let s;if(typeof t=="string"){let h=await fetch(t,{signal:r.signal});if(!h.ok)throw new Error(`Failed to load "${t}": HTTP ${h.status}`);s=await h.arrayBuffer()}else s=t;r.signal.throwIfAborted();let a=zt(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 t=="string"?"src":"model"})}catch(s){throw r.signal.aborted||this.emitError(s,"load"),s}}showToast(t,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=t,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 t=(s,a=s.message)=>{throw this.fireEvent("ar-status",{status:"failed",error:s}),this.showToast(a,6e3),s};this.currentModel||t(new Error("No 3D model is loaded in <three-live>.")),xt.arProvider||t(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 xt.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=typeof navigator<"u"&&navigator.userAgent||"",o=/Macintosh/i.test(a)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1),n=/Android|iPhone|iPad|iPod/i.test(a),h=s.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.";if(o&&!n&&typeof document<"u"&&this.currentModel&&xt.arProvider.createUSDZBlob)try{let l=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:xt.arProvider.createUSDZBlob(this.currentModel),c=URL.createObjectURL(l),f=document.createElement("a");f.href=c,f.download="three_live_model.usdz",document.body.appendChild(f),f.click(),document.body.removeChild(f),setTimeout(()=>URL.revokeObjectURL(c),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(h,6e3)}else this.showToast(h,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",r=>this.fireEvent("three-context-lost",{originalEvent:r})),t.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 t=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 Mt(this,this.canvas,{autoRotate:t,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:h=>{this.fireEvent("meshclick",h)},onCameraChange:h=>{this.updateHotspots();for(let l of Mt.getRegisteredPlugins())l.onCameraChange?.(this.viewer,this);this.fireEvent("camera-change",h)}}),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(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.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.type="button",t.className="three-live-ar-button";for(let[s,a]of[["aria-label","View in Augmented Reality"],["part","default-ar-button"]])t.setAttribute(s,a);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),t.appendChild(s)}let r=document.createElement("span");r.textContent="View in AR",t.appendChild(r),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")&&!!xt.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=t?i.dataset.tlOrigDisplay||"":"none"):this.arButton&&(this.arButton.style.display=t?"flex":"none")}applyCameraOrbit(t){if(!(!t||!this.viewer))try{let i=JSON.parse(t);this.viewer.setInitialCamera(i.theta,i.phi,i.distance,i.zoom)}catch{let i=this.parseOrbitLimit(t);(i.theta!==void 0||i.phi!==void 0)&&this.viewer.setInitialCamera(i.theta,i.phi,i.distance)}}parseOrbitLimit(t){if(!t)return{};let[i,r,s]=t.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 t=this.parseOrbitLimit(this.getAttr("min-camera-orbit")),i=this.parseOrbitLimit(this.getAttr("max-camera-orbit"));this.viewer.setOrbitLimits({minTheta:t.theta,maxTheta:i.theta,minPhi:t.phi,maxPhi:i.phi,minDistance:t.distance,maxDistance:i.distance})}parseCameraTarget(t){if(!t)return;let i=t.trim().split(/\s+/).map(parseFloat);return i.length>=3&&!i.some(isNaN)?[i[0],i[1],i[2]]:void 0}parseFieldOfView(t){if(!t)return;let i=parseFloat(t);return isNaN(i)?void 0:t.endsWith("rad")?i*180/Math.PI:i}parseRotationPerSecond(t){if(!t)return Math.PI/6;let i=t.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(t){let i=this.parseCameraTarget(t);this.viewer&&i&&this.viewer.setTarget(i[0],i[1],i[2])}applyFieldOfView(t){let i=this.parseFieldOfView(t);this.viewer&&i!==void 0&&this.viewer.setFieldOfView(i)}updateHotspot(t){let i=this.querySelector(`[slot="${t.name}"]`);i&&(t.position!==void 0&&i.setAttribute("data-position",t.position),t.normal!==void 0&&i.setAttribute("data-normal",t.normal)),this.updateHotspots()}updateHotspots(){for(let t of Mt.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}runWithScriptRunner(t){let i=xt.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 h={onModelReady:l=>{this.loadModelWithLimits(l,$r,r).then(()=>a(l),o)},onUpdateTransforms:l=>{s()&&this.viewer?.updateMeshTransforms(l)},onError:l=>{s()&&(this.showToast(l.message),this.emitError(l,"script"),o(l))},onToast:l=>{s()&&this.showToast(l)}};t(i,h).then(l=>{s()?this.scriptHandle=l||null:l?.terminate()},l=>{s()&&h.onError?.(l)})})}loadScriptFromSrc(t){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(t,this.sandbox,r)})}executeScript(t){if(!xt.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let i=new Error(We);return this.showToast(je),this.emitError(i,"security"),Promise.reject(i)}return this.runWithScriptRunner((i,r)=>i.execute(t,this.sandbox,r,{allowClientScripts:!0}))}};de.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"],de.registerPlugin=Mt.registerPlugin,de.getRegisteredPlugins=Mt.getRegisteredPlugins;var pe=de;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",pe);function Ji(){if(typeof window>"u"||typeof navigator>"u")return!1;let e=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(e)||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 Qi(){if(typeof navigator>"u")return!1;let e=navigator.userAgent||"";return/android/i.test(e)}async function tr(){if(typeof navigator>"u")return!1;let e=navigator;if(!e.xr||typeof e.xr.isSessionSupported!="function")return!1;try{return await e.xr.isSessionSupported("immersive-ar")?!0:await e.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function aa(){return(await Ve()).bestMode}async function Ve(){let[e,t,i]=await Promise.all([tr(),Promise.resolve(Ji()),Promise.resolve(Qi())]),r=[];t&&r.push("quick-look"),e&&r.push("webxr"),i&&r.push("scene-viewer");let s=null;return t?s="quick-look":e?s="webxr":i&&(s="scene-viewer"),{webxr:e,quickLook:t,sceneViewer:i,availableModes:r,bestMode:s}}function er(e,t={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let i,r=!1;if(typeof e=="string"){if(i=na(e),!i)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else i=URL.createObjectURL(e),r=!0;let s=[];if(t.allowScale===!1&&s.push("allowsContentScaling=0"),t.canonicalWebPageUrl){let n=fe(t.canonicalWebPageUrl,!1);n&&s.push(`canonicalWebPageURL=${encodeURIComponent(n)}`)}t.checkoutTitle&&s.push(`checkoutTitle=${encodeURIComponent(t.checkoutTitle)}`),t.checkoutSubtitle&&s.push(`checkoutSubtitle=${encodeURIComponent(t.checkoutSubtitle)}`),t.price&&s.push(`price=${encodeURIComponent(t.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 fe(e,t=!1){if(typeof e!="string")return"";let i=e.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://")||t&&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(e){try{return fe(e,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(e||"").trim().slice(0,32)}`)}}function oa(e,t={}){let i=fe(e,!0),r=t.mode||"ar_preferred",s=new URLSearchParams({file:i,mode:r,resizable:t.resizable!==!1?"true":"false",enable_vertical_placement:t.enableVerticalPlacement?"true":"false"});return t.title&&s.set("title",t.title),t.link&&s.set("link",fe(t.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(e,t={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let i=oa(e,t);window.location.href=i}var It=null;function ha(e,t){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),b=Math.sin(f),u=c*2,d=u+1,M=(c+1)%24*2;i[u*3]=g*.11,i[u*3+1]=.002,i[u*3+2]=b*.11,i[d*3]=g*.145,i[d*3+1]=.002,i[d*3+2]=b*.145,r[u*3+1]=r[d*3+1]=1,a.set([u,M,d,d,M,M+1],c*6)}let o=e.createVertexArray();e.bindVertexArray(o);let n=(c,f,g)=>{let b=e.createBuffer();return e.bindBuffer(34962,b),e.bufferData(34962,c,35044),e.enableVertexAttribArray(f),e.vertexAttribPointer(f,g,5126,!1,0,0),b},h=[n(i,0,3),n(r,1,3),n(s,2,2)],l=e.createBuffer();return h.push(l),e.bindBuffer(34963,l),e.bufferData(34963,a,35044),e.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:t&&t.length>=3?[t[0],t[1],t[2],t[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:h}]}}function ir(e,t,i,r,s){let a=Math.cos(r),o=Math.sin(r),n=Math.max(.01,s);e.fill(0),e[0]=n*a,e[2]=-n*o,e[5]=n,e[8]=n*o,e[10]=n*a,e[12]=t[0]-n*(a*i[0]+o*i[2]),e[13]=t[1]-n*i[1],e[14]=t[2]-n*(-o*i[0]+a*i[2]),e[15]=1}var ua=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.");It&&It!==this&&It.isSessionActive()&&await It.stop().catch(()=>{});let i=navigator.xr,r=this.opts,s=t||e?.container,a=String(s?.tagName||"").toLowerCase()==="xr-live",o=e?.bounds,n=Number(o?.radius)||1,h=Array.isArray(o?.center)?o.center:[0,0,0],l=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,b=a?[0,-.25,0]:[h[0]||0,r.arPlacement==="wall"?h[1]:l[1]??0,h[2]||0],u="immersive-ar";try{await i.isSessionSupported("immersive-ar")||(u="immersive-vr")}catch{u="immersive-vr"}let d=s?.querySelector?.('[slot="ar-overlay"]')||null,M=!1,w=null,v=()=>{M&&d?.parentNode&&d.parentNode.removeChild(d),d=null,w=null,M=!1};if(u==="immersive-ar"){if(d)d.addEventListener?.("beforexrselect",_=>_.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let _=document.createElement("div");_.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 z=document.createElement("button");z.type="button",z.textContent="\u2715 Exit AR",z.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",z.addEventListener("beforexrselect",V=>V.preventDefault()),z.addEventListener("click",V=>{V.stopPropagation(),this.stop().catch(()=>{})}),w=document.createElement("div"),w.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",w.textContent="Move phone to detect a surface \u2022 Tap to place",_.appendChild(z),_.appendChild(w),document.body.appendChild(_),d=_,M=!0}}let m=new Set(r.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),p={requiredFeatures:r.requiredFeatures?[...r.requiredFeatures]:[],optionalFeatures:Array.from(m)};d&&(m.add("dom-overlay"),p.optionalFeatures=Array.from(m),p.domOverlay={root:d});for(let _ of ct)_.onConfigureXRSessionInit?.(s,p);Array.isArray(p.optionalFeatures)&&p.optionalFeatures.includes("dom-overlay")&&!p.domOverlay?.root&&(p.optionalFeatures=p.optionalFeatures.filter(_=>_!=="dom-overlay"));let x=_=>{let z=String(_?.name||"");return z==="NotAllowedError"||z==="SecurityError"};try{this.s=await i.requestSession(u,p)}catch(_){if(v(),x(_))throw r.onError?.(_),_;try{this.s=await i.requestSession(u,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(z){if(x(z))throw r.onError?.(z),z;try{this.s=await i.requestSession(u)}catch(V){throw r.onError?.(V),V}}}let S=this.s;It=this,this.placed=!1;let N=null,F=null,E=null,L=null,C=null,D=[0,-.25,-1.2],R=[0,-.25,-1.2],y=new Float32Array(16),U=new Float32Array(16),j=!1,T=1,k=0,A=!1,P=null,G=null,q=0,$=null,Y=()=>{It===this&&(It=null),$?.(),$=null;try{F?.cancel?.()}catch{}if(F=null,E){let _=e?.meshes;if(Array.isArray(_)){let V=_.indexOf(E);V!==-1&&_.splice(V,1)}let z=e.getGLContext?.()||e?.gl;if(z)for(let V of E.primitives||[]){z.deleteVertexArray?.(V.vao);for(let W of V.buffers||[])z.deleteBuffer?.(W)}E=null}e?.setXRSessionActive?.(!1),v(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=Y,S.addEventListener("end",()=>{Y(),r.onExit?.()}),S.addEventListener("select",()=>{if(!this.placed){let _=C||D;R=[_[0],_[1],_[2]],ir(this.placedMat,R,b,k,g*T),this.placed=!0,E&&(E.visible=!1),w&&(w.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),r.onPlaced?.(this.placedMat)}});try{let _=e.getGLContext?.()||e?.gl;_&&typeof _.makeXRCompatible=="function"&&await _.makeXRCompatible();let z=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;_&&typeof z=="function"&&typeof S.updateRenderState=="function"&&S.updateRenderState({baseLayer:new z(S,_,{alpha:!0})});try{N=await S.requestReferenceSpace("local")}catch{try{N=await S.requestReferenceSpace("local-floor")}catch{N=await S.requestReferenceSpace("viewer")}}let V=await S.requestReferenceSpace("viewer").catch(()=>N);if(typeof S.requestHitTestSource=="function"&&V&&(F=await S.requestHitTestSource({space:V}).catch(()=>null)),u==="immersive-ar"&&_&&typeof _.createVertexArray=="function"&&Array.isArray(e.meshes)&&(E=ha(_,r.reticleColor),e.meshes.push(E)),typeof window<"u"&&typeof window.addEventListener=="function"){let O=I=>Math.hypot(I.touches[1].clientX-I.touches[0].clientX,I.touches[1].clientY-I.touches[0].clientY),H=I=>Math.atan2(I.touches[1].clientY-I.touches[0].clientY,I.touches[1].clientX-I.touches[0].clientX),B=I=>{this.s&&(I.touches.length===1&&this.placed?A=!0:I.touches.length>=2&&(A=!1,P=O(I),G=H(I)))},K=I=>{if(!this.s||I.touches.length<2)return;let tt=O(I),Z=H(I);if(P&&P>4&&r.arScale!=="fixed"&&(T=Math.max(.15,Math.min(6,T*(tt/P)))),G!==null){let at=Z-G;at>Math.PI&&(at-=Math.PI*2),at<-Math.PI&&(at+=Math.PI*2),k-=at}P=tt,G=Z},X=I=>{(!I.touches||I.touches.length===0)&&(A=!1),(!I.touches||I.touches.length<2)&&(P=null,G=null)};window.addEventListener("touchstart",B,{passive:!0}),window.addEventListener("touchmove",K,{passive:!0}),window.addEventListener("touchend",X,{passive:!0}),window.addEventListener("touchcancel",X,{passive:!0}),$=()=>{window.removeEventListener("touchstart",B),window.removeEventListener("touchmove",K),window.removeEventListener("touchend",X),window.removeEventListener("touchcancel",X)}}e.setXRSessionActive?.(!0);let W=(O,H)=>{if(this.s!==S)return;S.requestAnimationFrame(W);let B=q>0?Math.min(Math.max((O-q)/1e3,0),.1):1/60;q=O,e?.stepXRUpdate?.(B);let K=H.getViewerPose(N);if(!K)return;let X=K.views?.[0];if(!j&&X?.transform){let it=X.transform.position,rt=X.transform.matrix,gt=it?.x??(rt?rt[12]:0),st=it?.y??(rt?rt[13]:0),nt=it?.z??(rt?rt[14]:0),lt=rt?-rt[8]:0,ht=rt?-rt[10]:-1,At=Math.hypot(lt,ht);At>1e-4?(lt/=At,ht/=At):(lt=0,ht=-1),D=[gt+lt*1.2,st-.25,nt+ht*1.2],k=Math.atan2(-lt,-ht),j=!0}if(F&&typeof H.getHitTestResults=="function"&&(!this.placed||A)){let it=H.getHitTestResults(F)||[],rt=!1;for(let gt of it){let st=gt.getPose(N);if(st?.transform?.matrix){let nt=st.transform.matrix,lt=nt[5];if(r.arPlacement==="wall"&&Math.abs(lt)>.35||r.arPlacement==="floor"&&Math.abs(lt)<.65)continue;L||(L=new Float32Array(16)),L.set(nt),C=[nt[12],nt[13],nt[14]],this.placed&&A&&(R=[nt[12],nt[13],nt[14]]),E&&(E.visible=!this.placed||A,E.transform.set(nt)),!this.placed&&w&&(w.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),r.onHit?.(L),rt=!0;break}}!rt&&E&&(E.visible=!1)}ir(y,this.placed?R:C||D,b,k,g*T),this.placed&&this.placedMat.set(y);let I=e.xrRigMatrix;I instanceof Float32Array&&I.length===16?dt(U,I,y):U.set(y),e.modelRootMatrix&&e.modelRootMatrix.set(U);for(let it of ct)it.onXRFrame?.(e,S,H,N);let tt=e.getGLContext?.()||e?.gl,Z=S.renderState?.baseLayer;tt&&Z&&Z.framebuffer!==void 0&&tt.bindFramebuffer(36160,Z.framebuffer);let at=u==="immersive-ar",J=K.views||[];for(let it=0;it<J.length;it++){let rt=J[it];if(typeof e.renderXRView=="function"){let gt;if(Z&&typeof Z.getViewport=="function"){let st=Z.getViewport(rt);st&&st.width>0&&st.height>0&&(gt=[st.x,st.y,st.width,st.height])}else Z?.framebufferWidth>0&&Z?.framebufferHeight>0&&(gt=[0,0,Z.framebufferWidth,Z.framebufferHeight]);e.renderXRView(rt,U,this.placed,gt,at,it)}}tt&&Z&&Z.framebuffer&&tt.bindFramebuffer(36160,null)};S.requestAnimationFrame(W)}catch(_){throw typeof S.end=="function"&&await S.end().catch(()=>{}),Y(),r.onError?.(_),_}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function rr(e){let t=await Ve(),i=e.preferredModes||["quick-look","webxr","scene-viewer"],r=null;for(let n of i)if(t.availableModes.includes(n)){r=n;break}if(r||(r=t.bestMode),!r)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let s={...e.quickLookOptions,allowScale:e.arScale==="fixed"?!1:e.quickLookOptions?.allowScale},a={...e.sceneViewerOptions,resizable:e.arScale==="fixed"?!1:e.sceneViewerOptions?.resizable,enableVerticalPlacement:e.arPlacement==="wall"?!0:e.sceneViewerOptions?.enableVerticalPlacement},o={...e.webXROptions,arScale:e.arScale||e.webXROptions?.arScale,arPlacement:e.arPlacement||e.webXROptions?.arPlacement};try{if(r==="quick-look"){let n;if(e.model instanceof Blob&&e.model.type==="model/vnd.usdz+zip")n=e.model;else{if(typeof e.model=="string")return er(e.model,s),{mode:"quick-look",success:!0};n=Le(e.model)}return er(n,s),{mode:"quick-look",success:!0}}if(r==="scene-viewer"){let n=e.glbUrl||(typeof e.model=="string"?e.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(!e.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let n=new ua(o);return await n.start(e.view,e.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 pe.registerAR({activateAR:rr,createUSDZBlob:Le}),pe.registerScriptRunner(Hi),He(Ar),yr($e)})();
|