three-live 1.1.0 → 1.2.0

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.
@@ -14,7 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
- "use strict";var ThreeLiveViewer=(()=>{var ge=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var $e=Object.getOwnPropertyNames;var qe=Object.prototype.hasOwnProperty;var Ke=(n,t)=>{for(var e in t)ge(n,e,{get:t[e],enumerable:!0})},Ze=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of $e(t))!qe.call(n,i)&&i!==e&&ge(n,i,{get:()=>t[i],enumerable:!(r=je(t,i))||r.enumerable});return n};var Je=n=>Ze(ge({},"__esModule",{value:!0}),n);var at={};Ke(at,{ThreeLiveElement:()=>de,ThreeView:()=>G,toGLBData:()=>oe});var ve="__THREE_LIVE_REGISTRY__";function U(){let n=typeof globalThis<"u"?globalThis:{};if(!n[ve]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(n,ve,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{n[ve]=t}}return n[ve]}var O=U().plugins;function we(n){let t=U().plugins;t.some(e=>e.name===n.name)||t.push(n)}function Re(){return U().plugins}function V(){let n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n}function Ee(n,t,e,r,i){let s=1/Math.tan(t/2);n.fill(0),n[0]=s/e,n[5]=s,n[11]=-1;let u=1/(r-i);return n[10]=(i+r)*u,n[14]=2*i*r*u,n}function Ae(n,t,e,r){let[i,s,u]=t,[c,o,l]=r,[a,h,m]=e,b=i-a,p=s-h,y=u-m,g=Math.hypot(b,p,y);g<=1e-5?(b=0,p=0,y=1):(b/=g,p/=g,y/=g);let M=o*y-l*p,w=l*b-c*y,R=c*p-o*b;g=Math.hypot(M,w,R),g<=1e-5?(M=0,w=0,R=0):(M/=g,w/=g,R/=g);let T=p*R-y*w,v=y*M-b*R,x=b*w-p*M;return g=Math.hypot(T,v,x),g<=1e-5?(T=0,v=0,x=0):(T/=g,v/=g,x/=g),n[0]=M,n[1]=T,n[2]=b,n[3]=0,n[4]=w,n[5]=v,n[6]=p,n[7]=0,n[8]=R,n[9]=x,n[10]=y,n[11]=0,n[12]=-(M*i+w*s+R*u),n[13]=-(T*i+v*s+x*u),n[14]=-(b*i+p*s+y*u),n[15]=1,n}function Y(n,t,e){let r=t[0],i=t[1],s=t[2],u=t[3],c=t[4],o=t[5],l=t[6],a=t[7],h=t[8],m=t[9],b=t[10],p=t[11],y=t[12],g=t[13],M=t[14],w=t[15],R=e[0],T=e[1],v=e[2],x=e[3];return n[0]=R*r+T*c+v*h+x*y,n[1]=R*i+T*o+v*m+x*g,n[2]=R*s+T*l+v*b+x*M,n[3]=R*u+T*a+v*p+x*w,R=e[4],T=e[5],v=e[6],x=e[7],n[4]=R*r+T*c+v*h+x*y,n[5]=R*i+T*o+v*m+x*g,n[6]=R*s+T*l+v*b+x*M,n[7]=R*u+T*a+v*p+x*w,R=e[8],T=e[9],v=e[10],x=e[11],n[8]=R*r+T*c+v*h+x*y,n[9]=R*i+T*o+v*m+x*g,n[10]=R*s+T*l+v*b+x*M,n[11]=R*u+T*a+v*p+x*w,R=e[12],T=e[13],v=e[14],x=e[15],n[12]=R*r+T*c+v*h+x*y,n[13]=R*i+T*o+v*m+x*g,n[14]=R*s+T*l+v*b+x*M,n[15]=R*u+T*a+v*p+x*w,n}function Pe(n,t,e,r){let i=t[0],s=t[1],u=t[2],c=t[3],o=i+i,l=s+s,a=u+u,h=i*o,m=i*l,b=i*a,p=s*l,y=s*a,g=u*a,M=c*o,w=c*l,R=c*a,T=r[0],v=r[1],x=r[2];return n[0]=(1-(p+g))*T,n[1]=(m+R)*T,n[2]=(b-w)*T,n[3]=0,n[4]=(m-R)*v,n[5]=(1-(h+g))*v,n[6]=(y+M)*v,n[7]=0,n[8]=(b+w)*x,n[9]=(y-M)*x,n[10]=(1-(h+p))*x,n[11]=0,n[12]=e[0],n[13]=e[1],n[14]=e[2],n[15]=1,n}function se(n,t){let e=t[0],r=t[1],i=t[2],s=t[4],u=t[5],c=t[6],o=t[8],l=t[9],a=t[10],h=a*u-c*l,m=-a*s+c*o,b=l*s-u*o,p=e*h+r*m+i*b;return p&&(p=1/p,n[0]=h*p,n[1]=(-a*r+i*l)*p,n[2]=(c*r-i*u)*p,n[3]=m*p,n[4]=(a*e-i*o)*p,n[5]=(-c*e+i*s)*p,n[6]=b*p,n[7]=(-l*e+r*o)*p,n[8]=(u*e-r*s)*p),n}function De(n,t){let e=t[0],r=t[1],i=t[2],s=t[3],u=t[4],c=t[5],o=t[6],l=t[7],a=t[8],h=t[9],m=t[10],b=t[11],p=t[12],y=t[13],g=t[14],M=t[15],w=e*c-r*u,R=e*o-i*u,T=e*l-s*u,v=r*o-i*c,x=r*l-s*c,S=i*l-s*o,A=a*y-h*p,f=a*g-m*p,P=a*M-b*p,D=h*g-m*y,d=h*M-b*y,C=m*M-b*g,E=w*C-R*d+T*D+v*P-x*f+S*A;return E?(E=1/E,n[0]=(c*C-o*d+l*D)*E,n[1]=(i*d-r*C-s*D)*E,n[2]=(y*S-g*x+M*v)*E,n[3]=(m*x-h*S-b*v)*E,n[4]=(o*P-u*C-l*f)*E,n[5]=(e*C-i*P+s*f)*E,n[6]=(g*T-p*S-M*R)*E,n[7]=(a*S-m*T+b*R)*E,n[8]=(u*d-c*P+l*A)*E,n[9]=(r*P-e*d-s*A)*E,n[10]=(p*x-y*T+M*w)*E,n[11]=(h*T-a*x-b*w)*E,n[12]=(c*f-u*D-o*A)*E,n[13]=(e*D-r*f+i*A)*E,n[14]=(y*R-p*v-g*w)*E,n[15]=(a*v-h*R+m*w)*E,n):null}function xe(n,t,e,r,i){let s=i[0]*t+i[4]*e+i[8]*r+i[12],u=i[1]*t+i[5]*e+i[9]*r+i[13],c=i[2]*t+i[6]*e+i[10]*r+i[14],o=i[3]*t+i[7]*e+i[11]*r+i[15],l=o!==0?1/o:1;n[0]=s*l,n[1]=u*l,n[2]=c*l}function Ce(n,t,e,r,i,s,u,c,o,l,a,h,m,b,p,y,g=0){let M=l-u,w=a-c,R=h-o,T=m-u,v=b-c,x=p-o,S=i*x-s*v,A=s*T-r*x,f=r*v-i*T,P=M*S+w*A+R*f;if(P>-1e-7&&P<1e-7)return!1;let D=1/P,d=n-u,C=t-c,E=e-o,X=D*(d*S+C*A+E*f);if(X<-g||X>1+g)return!1;let ee=C*R-E*w,j=E*M-d*R,_=d*w-C*M,ue=D*(r*ee+i*j+s*_);if(ue<-g||X+ue>1+g)return!1;let k=D*(T*ee+v*j+x*_);if(k>1e-4&&k<y.distance){y.distance=k,y.point=[n+r*k,t+i*k,e+s*k];let W=w*x-R*v,I=R*T-M*x,L=M*v-w*T,B=Math.hypot(W,I,L)||1;return y.normal=[W/B,I/B,L/B],!0}return!1}function Se(n,t){let e=Array.isArray(n?.nodes)?n.nodes.length:0,r=[];for(let a=0;a<e;a++)r.push(V());if(e===0)return r;let i=new Set;for(let a of n.nodes)if(Array.isArray(a.children))for(let h of a.children)i.add(h);let s=new Set,u=128,c=(a,h,m=0)=>{if(m>u||a<0||a>=e||s.has(a))return;s.add(a);let b=n.nodes[a];if(!b)return;let p=V();if(t&&t[a])p.set(t[a]);else if(b.matrix&&b.matrix.length===16)p.set(b.matrix);else{let g=b.translation||[0,0,0],M=b.rotation||[0,0,0,1],w=b.scale||[1,1,1];Pe(p,M,g,w)}let y=r[a];if(h?Y(y,h,p):y.set(p),Array.isArray(b.children))for(let g of b.children)typeof g=="number"&&c(g,y,m+1)},o=[],l=n.scenes&&n.scenes[n.scene!==void 0?n.scene:0];if(l&&Array.isArray(l.nodes))o.push(...l.nodes);else for(let a=0;a<e;a++)i.has(a)||o.push(a);for(let a of o)c(a,null);for(let a=0;a<e;a++)!i.has(a)&&!o.includes(a)&&c(a,null);return r}function Qe(n){return new TextDecoder().decode(n)}var Ie=U().decoders;function et(n,t){Ie.set(n.toLowerCase(),t)}function me(n){return Ie.get(n.toLowerCase())}function Be(n){let t=ArrayBuffer.isView(n)?n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength):n,e=new DataView(t);if(t.byteLength<12)throw new Error(`Invalid GLB buffer size: ${t.byteLength} bytes`);let r=e.getUint32(0,!0);if(r!==1179937895){let m=e.getUint8(0);throw m===123||m===32||m===10||m===13?new Error("[three-live] Multi-file JSON .gltf is not supported for performance reasons. Please pack your asset into a single binary .glb file."):new Error(`Invalid GLB magic: 0x${r.toString(16)}`)}let i=e.getUint32(4,!0);if(i!==2)throw new Error(`Unsupported GLB version: ${i}`);let s=e.getUint32(8,!0),u=12,c=null,o=null;for(;u+8<=s&&u+8<=t.byteLength;){let m=e.getUint32(u,!0),b=e.getUint32(u+4,!0),p=u+8;if(p+m>t.byteLength)throw new Error(`Truncated GLB chunk: required ${p+m} bytes, buffer has ${t.byteLength}`);if(b===1313821514){let y=new Uint8Array(t,p,m),g=Qe(y);c=JSON.parse(g,(M,w)=>M==="__proto__"||M==="constructor"||M==="prototype"?void 0:w)}else b===5130562&&(o=t.slice(p,p+m));u=p+m}if(!c)throw new Error("Missing JSON chunk in GLB");let l=c.extensionsRequired||[];if(l.includes("KHR_draco_mesh_compression")&&!me("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");if(l.includes("EXT_meshopt_compression")&&!me("meshopt"))throw new Error("Model requires EXT_meshopt_compression. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).");if(l.includes("KHR_texture_basisu")&&!me("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let a=o||new ArrayBuffer(0),h={gltf:c,bin:a,animations:[]};for(let m of O)m.onParseGLB?.(h);return h}function tt(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 oe(n){if(tt(n))return n;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return Be(n);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var ke=`#version 300 es
17
+ "use strict";var ThreeLiveViewer=(()=>{var ye=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var Ke=Object.prototype.hasOwnProperty;var Ze=(n,t)=>{for(var e in t)ye(n,e,{get:t[e],enumerable:!0})},Je=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of qe(t))!Ke.call(n,i)&&i!==e&&ye(n,i,{get:()=>t[i],enumerable:!(r=$e(t,i))||r.enumerable});return n};var Qe=n=>Je(ye({},"__esModule",{value:!0}),n);var ut={};Ze(ut,{ThreeLiveElement:()=>de,ThreeView:()=>X,toGLBData:()=>oe});var ve="__THREE_LIVE_REGISTRY__";function _(){let n=typeof globalThis<"u"?globalThis:{};if(!n[ve]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(n,ve,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{n[ve]=t}}return n[ve]}var H=_().plugins;function Ae(n){let t=_().plugins;t.some(e=>e.name===n.name)||t.push(n)}function Ee(){return _().plugins}function W(){let n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n}function ge(n,t,e,r,i){let s=1/Math.tan(t/2);n.fill(0),n[0]=s/e,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 xe(n,t,e,r){let[i,s,o]=t,[l,u,c]=r,[a,h,p]=e,b=i-a,f=s-h,y=o-p,T=Math.hypot(b,f,y);T<=1e-5?(b=0,f=0,y=1):(b/=T,f/=T,y/=T);let w=u*y-c*f,P=c*b-l*y,R=l*f-u*b;T=Math.hypot(w,P,R),T<=1e-5?(w=0,P=0,R=0):(w/=T,P/=T,R/=T);let v=f*R-y*P,d=y*w-b*R,m=b*P-f*w;return T=Math.hypot(v,d,m),T<=1e-5?(v=0,d=0,m=0):(v/=T,d/=T,m/=T),n[0]=w,n[1]=v,n[2]=b,n[3]=0,n[4]=P,n[5]=d,n[6]=f,n[7]=0,n[8]=R,n[9]=m,n[10]=y,n[11]=0,n[12]=-(w*i+P*s+R*o),n[13]=-(v*i+d*s+m*o),n[14]=-(b*i+f*s+y*o),n[15]=1,n}function $(n,t,e){let r=t[0],i=t[1],s=t[2],o=t[3],l=t[4],u=t[5],c=t[6],a=t[7],h=t[8],p=t[9],b=t[10],f=t[11],y=t[12],T=t[13],w=t[14],P=t[15],R=e[0],v=e[1],d=e[2],m=e[3];return n[0]=R*r+v*l+d*h+m*y,n[1]=R*i+v*u+d*p+m*T,n[2]=R*s+v*c+d*b+m*w,n[3]=R*o+v*a+d*f+m*P,R=e[4],v=e[5],d=e[6],m=e[7],n[4]=R*r+v*l+d*h+m*y,n[5]=R*i+v*u+d*p+m*T,n[6]=R*s+v*c+d*b+m*w,n[7]=R*o+v*a+d*f+m*P,R=e[8],v=e[9],d=e[10],m=e[11],n[8]=R*r+v*l+d*h+m*y,n[9]=R*i+v*u+d*p+m*T,n[10]=R*s+v*c+d*b+m*w,n[11]=R*o+v*a+d*f+m*P,R=e[12],v=e[13],d=e[14],m=e[15],n[12]=R*r+v*l+d*h+m*y,n[13]=R*i+v*u+d*p+m*T,n[14]=R*s+v*c+d*b+m*w,n[15]=R*o+v*a+d*f+m*P,n}function Pe(n,t,e,r){let i=t[0],s=t[1],o=t[2],l=t[3],u=i+i,c=s+s,a=o+o,h=i*u,p=i*c,b=i*a,f=s*c,y=s*a,T=o*a,w=l*u,P=l*c,R=l*a,v=r[0],d=r[1],m=r[2];return n[0]=(1-(f+T))*v,n[1]=(p+R)*v,n[2]=(b-P)*v,n[3]=0,n[4]=(p-R)*d,n[5]=(1-(h+T))*d,n[6]=(y+w)*d,n[7]=0,n[8]=(b+P)*m,n[9]=(y-w)*m,n[10]=(1-(h+f))*m,n[11]=0,n[12]=e[0],n[13]=e[1],n[14]=e[2],n[15]=1,n}function ne(n,t){let e=t[0],r=t[1],i=t[2],s=t[4],o=t[5],l=t[6],u=t[8],c=t[9],a=t[10],h=a*o-l*c,p=-a*s+l*u,b=c*s-o*u,f=e*h+r*p+i*b;return f&&(f=1/f,n[0]=h*f,n[1]=(-a*r+i*c)*f,n[2]=(l*r-i*o)*f,n[3]=p*f,n[4]=(a*e-i*u)*f,n[5]=(-l*e+i*s)*f,n[6]=b*f,n[7]=(-c*e+r*u)*f,n[8]=(o*e-r*s)*f),n}function Se(n,t){let e=t[0],r=t[1],i=t[2],s=t[3],o=t[4],l=t[5],u=t[6],c=t[7],a=t[8],h=t[9],p=t[10],b=t[11],f=t[12],y=t[13],T=t[14],w=t[15],P=e*l-r*o,R=e*u-i*o,v=e*c-s*o,d=r*u-i*l,m=r*c-s*l,L=i*c-s*u,E=a*y-h*f,g=a*T-p*f,S=a*w-b*f,D=h*T-p*y,C=h*w-b*y,x=p*w-b*T,M=P*x-R*C+v*D+d*S-m*g+L*E;return M?(M=1/M,n[0]=(l*x-u*C+c*D)*M,n[1]=(i*C-r*x-s*D)*M,n[2]=(y*L-T*m+w*d)*M,n[3]=(p*m-h*L-b*d)*M,n[4]=(u*S-o*x-c*g)*M,n[5]=(e*x-i*S+s*g)*M,n[6]=(T*v-f*L-w*R)*M,n[7]=(a*L-p*v+b*R)*M,n[8]=(o*C-l*S+c*E)*M,n[9]=(r*S-e*C-s*E)*M,n[10]=(f*m-y*v+w*P)*M,n[11]=(h*v-a*m-b*P)*M,n[12]=(l*g-o*D-u*E)*M,n[13]=(e*D-r*g+i*E)*M,n[14]=(y*R-f*d-T*P)*M,n[15]=(a*d-h*R+p*P)*M,n):null}function Te(n,t,e,r,i){let s=i[0]*t+i[4]*e+i[8]*r+i[12],o=i[1]*t+i[5]*e+i[9]*r+i[13],l=i[2]*t+i[6]*e+i[10]*r+i[14],u=i[3]*t+i[7]*e+i[11]*r+i[15],c=u!==0?1/u:1;n[0]=s*c,n[1]=o*c,n[2]=l*c}function De(n,t,e,r,i,s,o,l,u,c,a,h,p,b,f,y,T=0){let w=c-o,P=a-l,R=h-u,v=p-o,d=b-l,m=f-u,L=i*m-s*d,E=s*v-r*m,g=r*d-i*v,S=w*L+P*E+R*g;if(S>-1e-7&&S<1e-7)return!1;let D=1/S,C=n-o,x=t-l,M=e-u,k=D*(C*L+x*E+M*g);if(k<-T||k>1+T)return!1;let A=x*R-M*P,z=M*w-C*R,G=C*P-x*w,re=D*(r*A+i*z+s*G);if(re<-T||k+re>1+T)return!1;let N=D*(v*A+d*z+m*G);if(N>1e-4&&N<y.distance){y.distance=N,y.point=[n+r*N,t+i*N,e+s*N];let j=P*m-R*d,B=R*v-w*m,F=w*d-P*v,U=Math.hypot(j,B,F)||1;return y.normal=[j/U,B/U,F/U],!0}return!1}function Ce(n,t){let e=Array.isArray(n?.nodes)?n.nodes.length:0,r=[];for(let a=0;a<e;a++)r.push(W());if(e===0)return r;let i=new Set;for(let a of n.nodes)if(Array.isArray(a.children))for(let h of a.children)i.add(h);let s=new Set,o=128,l=(a,h,p=0)=>{if(p>o||a<0||a>=e||s.has(a))return;s.add(a);let b=n.nodes[a];if(!b)return;let f=W();if(t&&t[a])f.set(t[a]);else if(b.matrix&&b.matrix.length===16)f.set(b.matrix);else{let T=b.translation||[0,0,0],w=b.rotation||[0,0,0,1],P=b.scale||[1,1,1];Pe(f,w,T,P)}let y=r[a];if(h?$(y,h,f):y.set(f),Array.isArray(b.children))for(let T of b.children)typeof T=="number"&&l(T,y,p+1)},u=[],c=n.scenes&&n.scenes[n.scene!==void 0?n.scene:0];if(c&&Array.isArray(c.nodes))u.push(...c.nodes);else for(let a=0;a<e;a++)i.has(a)||u.push(a);for(let a of u)l(a,null);for(let a=0;a<e;a++)!i.has(a)&&!u.includes(a)&&l(a,null);return r}function et(n){return new TextDecoder().decode(n)}var Be=_().decoders;function tt(n,t){Be.set(n.toLowerCase(),t)}function me(n){return Be.get(n.toLowerCase())}function ke(n){let t=ArrayBuffer.isView(n)?n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength):n,e=new DataView(t);if(t.byteLength<12)throw new Error(`Invalid GLB buffer size: ${t.byteLength} bytes`);let r=e.getUint32(0,!0);if(r!==1179937895){let p=e.getUint8(0);throw p===123||p===32||p===10||p===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=e.getUint32(4,!0);if(i!==2)throw new Error(`Unsupported GLB version: ${i}`);let s=e.getUint32(8,!0),o=12,l=null,u=null;for(;o+8<=s&&o+8<=t.byteLength;){let p=e.getUint32(o,!0),b=e.getUint32(o+4,!0),f=o+8;if(f+p>t.byteLength)throw new Error(`Truncated GLB chunk: required ${f+p} bytes, buffer has ${t.byteLength}`);if(b===1313821514){let y=new Uint8Array(t,f,p),T=et(y);l=JSON.parse(T,(w,P)=>w==="__proto__"||w==="constructor"||w==="prototype"?void 0:P)}else b===5130562&&(u=t.slice(f,f+p));o=f+p}if(!l)throw new Error("Missing JSON chunk in GLB");let c=l.extensionsRequired||[];if(c.includes("KHR_draco_mesh_compression")&&!me("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");if(c.includes("EXT_meshopt_compression")&&!me("meshopt"))throw new Error("Model requires EXT_meshopt_compression. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).");if(c.includes("KHR_texture_basisu")&&!me("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let a=u||new ArrayBuffer(0),h={gltf:l,bin:a,animations:[]};for(let p of H)p.onParseGLB?.(h);return h}function it(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 oe(n){if(it(n))return n;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return ke(n);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var Ne=`#version 300 es
18
18
  layout(location=0) in vec3 aPosition;
19
19
  layout(location=1) in vec3 aNormal;
20
20
  layout(location=2) in vec2 aUV;
@@ -32,7 +32,7 @@ vec2 scaleUV=uUvTransform.zw;
32
32
  if(scaleUV.x==0.0&&scaleUV.y==0.0)scaleUV=vec2(1.0);
33
33
  vUV=aUV*scaleUV+uUvTransform.xy;
34
34
  gl_Position=uMVP*vec4(aPosition,1.0);
35
- }`,Ne=`#version 300 es
35
+ }`,rt=`#version 300 es
36
36
  precision highp float;
37
37
  in vec3 vNormal,vWorldPos;
38
38
  in vec2 vUV;
@@ -40,12 +40,13 @@ uniform vec4 uBaseColor;
40
40
  uniform float uMetallic,uRoughness,uEmissive,uEnvIntensity;
41
41
  uniform vec2 uClearcoat;
42
42
  uniform vec3 uCameraPos,uAmbientColor;
43
- uniform sampler2D uBaseColorTexture,uMetallicRoughnessTexture,uNormalTexture,uOcclusionTexture,uEnvironmentMap,uXrDepthTex;
44
- uniform int uHasTexture,uHasMetallicRoughnessTexture,uHasNormalTexture,uHasOcclusionTexture,uHasEnvironmentMap,uXrDepthEnabled,uXrDepthFormat;
45
- uniform float uNormalScale,uOcclusionStrength,uXrRawValueToMeters;
46
- uniform mat4 uXrDepthUVTransform;
43
+ uniform sampler2D uBaseColorTexture,uMetallicRoughnessTexture,uNormalTexture,uOcclusionTexture,uEnvironmentMap;
44
+ uniform int uHasTexture,uHasMetallicRoughnessTexture,uHasNormalTexture,uHasOcclusionTexture,uHasEnvironmentMap;
45
+ uniform float uNormalScale,uOcclusionStrength;
46
+ /*XRD_U*/
47
47
  uniform vec2 uViewportSize;
48
- uniform int uToneMapping,uNumDirLights,uNumPointLights;
48
+ uniform vec4 uSectionPlane;
49
+ uniform int uToneMapping,uNumDirLights,uNumPointLights,uSectionEnabled;
49
50
  uniform vec3 uDirLightDir[2],uDirLightColor[2],uPointLightPos[2],uPointLightColor[2];
50
51
  out vec4 fragColor;
51
52
 
@@ -114,6 +115,7 @@ return color;
114
115
  }
115
116
 
116
117
  void main(){
118
+ if(uSectionEnabled==1&&dot(vWorldPos,uSectionPlane.xyz)>uSectionPlane.w)discard;
117
119
  vec4 base=uBaseColor;
118
120
  if(uHasTexture==1)base*=texture(uBaseColorTexture,vUV);
119
121
  if(length(vNormal)<1e-4&&uHasTexture==1){
@@ -194,24 +196,13 @@ color=color*(vec3(1.0)-ccF)+getStudioRadiance(R,uClearcoat.y)*ccF*uEnvIntensity;
194
196
  }
195
197
  color=applyToneMapping(color,uToneMapping);
196
198
  float outAlpha=base.a;
197
- if(uXrDepthEnabled==1){
198
- vec2 normViewUV=gl_FragCoord.xy/max(uViewportSize,vec2(1.0));
199
- vec2 depthUV=(uXrDepthUVTransform*vec4(normViewUV,0.0,1.0)).xy;
200
- vec4 depthSample=texture(uXrDepthTex,depthUV);
201
- float realDepth=(uXrDepthFormat==1?depthSample.r:(depthSample.r+depthSample.a*256.0))*uXrRawValueToMeters;
202
- float virtDepth=length(uCameraPos-vWorldPos);
203
- if(realDepth>0.05&&virtDepth>realDepth){
204
- float occAlpha=1.0-smoothstep(0.0,0.025,virtDepth-realDepth);
205
- outAlpha*=occAlpha;
206
- if(outAlpha<0.01)discard;
207
- }
208
- }
199
+ /*XRD_O*/
209
200
  fragColor=vec4(color,outAlpha);
210
- }`,it=`#version 300 es
201
+ }`,nt=`#version 300 es
211
202
  layout(location=0) in vec3 aPosition;
212
203
  uniform mat4 uMVP;
213
- void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,rt=`#version 300 es
204
+ void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,st=`#version 300 es
214
205
  precision highp float;
215
206
  uniform vec4 uColorId;
216
207
  out vec4 fragColor;
217
- void main(){fragColor=uColorId;}`;function Le(n,t,e){let r=n.createShader(t);if(n.shaderSource(r,e),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 Te(n,t,e){let r=Le(n,35633,t),i=Le(n,35632,e),s=n.createProgram();if(n.attachShader(s,r),n.attachShader(s,i),n.linkProgram(s),!n.getProgramParameter(s,35714)){let u=n.getProgramInfoLog(s);throw n.deleteProgram(s),new Error(`Program link error: ${u}`)}return s}function Me(n,t,e){let r={};for(let i of e)r[i]=n.getUniformLocation(t,i);return r}var Ue=["uMVP","uModel","uNormalMatrix","uUvTransform","uBaseColor","uMetallic","uRoughness","uClearcoat","uEmissive","uCameraPos","uBaseColorTexture","uHasTexture","uMetallicRoughnessTexture","uHasMetallicRoughnessTexture","uNormalTexture","uHasNormalTexture","uNormalScale","uOcclusionTexture","uHasOcclusionTexture","uOcclusionStrength","uToneMapping","uEnvironmentMap","uHasEnvironmentMap","uAmbientColor","uNumDirLights","uDirLightDir","uDirLightColor","uNumPointLights","uPointLightPos","uPointLightColor","uEnvIntensity","uXrDepthTex","uXrDepthEnabled","uXrDepthFormat","uXrRawValueToMeters","uXrDepthUVTransform","uViewportSize"];function nt(n){if(typeof n!="string")return null;let t=n.trim();if(!t||/[\x00-\x1f\x7f]/.test(t))return null;let e=t.toLowerCase();return e.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(t)?t:null:e.startsWith("https://")||e.startsWith("blob:")?t:e.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(t)||/(^|[\\/])\.\.([\\/]|$)/.test(t)?null:t}function ye(n,t,e,r,i,s,u){if(r===void 0||!t.accessors?.[r])return null;let c=t.accessors[r],o=t.bufferViews[c.bufferView],l=(o.byteOffset||0)+(c.byteOffset||0),a=o.byteStride&&o.byteStride>s*4?o.byteStride>>2:s,h;if(a===s)h=new Float32Array(e,l,c.count*s);else{h=new Float32Array(c.count*s);let b=new Float32Array(e,o.byteOffset||0,Math.floor(o.byteLength/4)),p=(c.byteOffset||0)>>2;for(let y=0;y<c.count;y++){let g=p+y*a;for(let M=0;M<s;M++)h[y*s+M]=b[g+M]}}let m=n.createBuffer();return u.push(m),n.bindBuffer(34962,m),n.bufferData(34962,h,35044),n.enableVertexAttribArray(i),n.vertexAttribPointer(i,s,5126,!1,0,0),h}var Oe=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),Ge=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Fe(n,t,e=Ge,r){if(!t||!t.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:i,bin:s}=t,u=[],c=Se(i),o=[];if(Array.isArray(i.nodes))for(let A=0;A<i.nodes.length;A++){let f=i.nodes[A];f.mesh!==void 0&&i.meshes&&i.meshes[f.mesh]&&o.push({node:f,nodeIdx:A,meshIdx:f.mesh})}let l=o.length>0?o:(i.meshes||[]).map((A,f)=>({node:A,nodeIdx:-1,meshIdx:f})),a=[];if(Array.isArray(t.lights)&&t.lights.length>0)a.push(...t.lights);else if(i.extensions?.KHR_lights_punctual?.lights){let A=i.extensions.KHR_lights_punctual.lights;for(let f of A){let P=f.type==="directional"?"directional":f.type==="point"?"point":"ambient";a.push({type:P,color:f.color||[1,1,1],intensity:f.intensity!==void 0?f.intensity:1})}}if(a.length===0&&(a.push({type:"ambient",color:[1,1,1],intensity:.35}),a.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),l.length>e.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${e.maxMeshes}). Found: ${l.length}`);let h=[];if(i.textures&&i.images){if(i.textures.length>e.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${e.maxTextures}). Found: ${i.textures.length}`);for(let A=0;A<i.textures.length;A++){let f=i.textures[A],P=i.images[f.source];if(P){let D=n.createTexture();if(n.bindTexture(3553,D),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),P.bufferView!==void 0){let d=i.bufferViews[P.bufferView],C=s.slice(d.byteOffset||0,(d.byteOffset||0)+d.byteLength),E=new Blob([C],{type:P.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(E).then(X=>{n.bindTexture(3553,D),n.texImage2D(3553,0,6408,6408,5121,X),n.generateMipmap(3553),r?.()}).catch(()=>{})}else if(P.uri){let d=nt(P.uri);if(d){let C=new Image;C.crossOrigin="anonymous",C.referrerPolicy="no-referrer",C.onload=()=>{n.bindTexture(3553,D),n.texImage2D(3553,0,6408,6408,5121,C),n.generateMipmap(3553),r?.()},C.src=d}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",P.uri)}h.push(D)}else h.push(null)}}let m=[1/0,1/0,1/0],b=[-1/0,-1/0,-1/0],p=0,y=0;for(let A=0;A<l.length;A++){let f=l[A],P=i.meshes[f.meshIdx],D=f.nodeIdx>=0?c[f.nodeIdx]:V(),d=new Float32Array(9);se(d,D);let C={name:f.node.name||P.name||`Mesh_${f.meshIdx}`,nodeIndex:f.nodeIdx,transform:D,normalMatrix:d,primitives:[],extras:f.node.extras||P.extras};for(let E of P.primitives||[]){if(E.extensions?.KHR_draco_mesh_compression){let F=me("draco");F&&F.decodePrimitive(i,E,s)}let X=[],ee=n.createVertexArray();n.bindVertexArray(ee);let j=i.accessors[E.attributes.POSITION],_=Number(j?.count??0);if(!Number.isFinite(_)||_<0||p+_>e.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${e.maxVertices}).`);if(p+=_,j?.min&&j?.max)for(let F=0;F<3;F++){let q=D[12+F],ae=D[12+F];for(let Q=0;Q<3;Q++){let fe=D[Q*4+F]*j.min[Q],be=D[Q*4+F]*j.max[Q];q+=fe<be?fe:be,ae+=fe>be?fe:be}q<m[F]&&(m[F]=q),ae>b[F]&&(b[F]=ae)}let ue=ye(n,i,s,E.attributes.POSITION,0,3,X);ye(n,i,s,E.attributes.NORMAL,1,3,X),ye(n,i,s,E.attributes.TEXCOORD_0,2,2,X);let k=0,W=5123,I=null;if(E.indices!==void 0){let F=i.accessors[E.indices],ae=(i.bufferViews[F.bufferView].byteOffset||0)+(F.byteOffset||0);if(k=Number(F.count??0),!Number.isFinite(k)||k<0||y+k>e.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${e.maxIndices}).`);y+=k,W=F.componentType===5125?5125||5125:5123||5123;let Q=n.createBuffer();X.push(Q),n.bindBuffer(34963,Q),F.componentType===5125?(I=new Uint32Array(s,ae,F.count),n.bufferData(34963,I,35044)):(I=new Uint16Array(s,ae,F.count),n.bufferData(34963,I,35044))}else k=j.count;let L={};for(let F of O)if(F.onBuildPrimitiveVAO){let q=F.onBuildPrimitiveVAO(n,ee,E,i,s);q&&(L[F.name]=q)}n.bindVertexArray(null);let B=i.materials&&E.material!==void 0?i.materials[E.material]:null,H=ke,K=Ne,J=!1;for(let F of O)if(F.onResolveShader){let q=F.onResolveShader(E,B,H,K);q&&(H=q.vs,K=q.fs,J=!0)}let Z=J?Te(n,H,K):null,pe=Z?Me(n,Z,Ue):null,z=B?.pbrMetallicRoughness,$=z?.baseColorFactor||[.8,.8,.8,1],ce=z?.metallicFactor??.1,le=z?.roughnessFactor??.5,ne=B?.extensions?.KHR_materials_clearcoat,te=ne?ne.clearcoatFactor??1:0,ie=Math.max(.04,ne?.clearcoatRoughnessFactor??.04),re=z?.baseColorTexture!==void 0&&h[z.baseColorTexture.index]?h[z.baseColorTexture.index]:null,he=z?.metallicRoughnessTexture!==void 0&&h[z.metallicRoughnessTexture.index]?h[z.metallicRoughnessTexture.index]:null,Ve=B?.normalTexture!==void 0&&h[B.normalTexture.index]?h[B.normalTexture.index]:null,Xe=B?.normalTexture?.scale??1,We=B?.occlusionTexture!==void 0&&h[B.occlusionTexture.index]?h[B.occlusionTexture.index]:null,ze=B?.occlusionTexture?.strength??1,Ye=!!(B?.extensions?.KHR_materials_transmission||L.materials?.isTransmissive);C.primitives.push({vao:ee,indexCount:k,indexType:W,baseColor:$,metallic:ce,roughness:le,clearcoat:te,clearcoatRoughness:ie,positions:ue,indices:I,texture:re,metallicRoughnessTexture:he,normalTexture:Ve,occlusionTexture:We,normalScale:Xe,occlusionStrength:ze,buffers:X,materialIndex:E.material,pluginData:L,customProgram:Z,customUniforms:pe,isTransmissive:Ye})}u.push(C)}isFinite(m[0])||(m=[-1,-1,-1]),isFinite(b[0])||(b=[1,1,1]);let g=[(m[0]+b[0])/2,(m[1]+b[1])/2,(m[2]+b[2])/2],M=b[0]-m[0],w=b[1]-m[1],R=b[2]-m[2],T=Math.max(Math.hypot(M,w,R)/2,.5),v=[m[0],m[1],m[2]],x=[b[0],b[1],b[2]],S=t.animations;if(!S){for(let A of O)if(A.onParseGLB?.(t),t.animations){S=t.animations;break}}return S||(S=[]),{meshes:u,bounds:{center:g,radius:T,min:v,max:x},lights:a,animations:S,worldMatrices:c}}var G=class{constructor(t,e,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=V();this.clearColor=[0,0,0,0];this.envIntensity=1;this.shadowIntensity=0;this.shadowSoftness=.5;this.toneMapping="neutral";this.environmentTexture=null;this.animations=[];this.currentClip=null;this.animationTime=0;this.isPlayingAnimation=!1;this.autoplay=!1;this.animationName="";this.gltf=null;this.worldMatrices=[];this.initialNodeTransforms=[];this.projMatrix=V();this.viewMatrix=V();this.modelMatrix=V();this.mvpMatrix=V();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.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.xrDepthState={enabled:!1,texture:null,uvTransform:V(),rawValueToMeters:.001,format:0};this.container=t;let i,s;if(e&&typeof e.getContext=="function"?(i=e,s=r):(s=e,i=s?.canvas),!i){let o=t.querySelector("canvas");o||(o=document.createElement("canvas"),o.style.width="100%",o.style.height="100%",o.style.display="block",o.style.touchAction="none",t.prepend(o)),i=o}this.canvas=i,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let u=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!u:u&&(this.autoRotate=!1),this.opts.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=this.opts.autoRotateSpeed),this.opts.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(this.opts.autoRotateDelay)||0)),this.opts.exposure!==void 0&&(this.envIntensity=Math.max(0,Number(this.opts.exposure))),this.opts.camera&&this.setInitialCamera(this.opts.camera.theta,this.opts.camera.phi,this.opts.camera.distance,this.opts.camera.zoom),this.opts.shadowIntensity!==void 0&&(this.shadowIntensity=Math.max(0,Math.min(1,Number(this.opts.shadowIntensity)||0))),this.opts.shadowSoftness!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(this.opts.shadowSoftness)||0))),this.opts.toneMapping!==void 0&&(this.toneMapping=this.opts.toneMapping),this.opts.autoplay!==void 0&&(this.autoplay=this.opts.autoplay),this.opts.animationName!==void 0&&(this.animationName=this.opts.animationName),this.opts.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.renderProg=Te(c,ke,Ne),this.pickProg=Te(c,it,rt),this.uRender=Me(c,this.renderProg,Ue),this.uPick=Me(c,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo(),this.setupEvents(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(t,e){et(t,e)}static getDecoder(t){return me(t)}setupPickingFbo(){let t=this.gl;if(typeof t.createFramebuffer!="function")return;this.pickFbo=t.createFramebuffer(),this.pickTexture=t.createTexture(),this.pickDepth=t.createRenderbuffer();let e=Math.max(1,this.canvas.width),r=Math.max(1,this.canvas.height);this.pickFboWidth=e,this.pickFboHeight=r,t.bindTexture(3553,this.pickTexture),t.texImage2D(3553,0,6408,e,r,0,6408,5121,null),t.texParameteri(3553,10241,9728),t.texParameteri(3553,10240,9728),t.bindRenderbuffer(36161,this.pickDepth),t.renderbufferStorage(36161,33189,e,r),t.bindFramebuffer(36160,this.pickFbo),t.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),t.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),t.bindFramebuffer(36160,null)}resizePickingFbo(t,e){if(!this.pickFbo)return;let r=this.gl,i=Math.max(1,t),s=Math.max(1,e);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(t,e){let{meshes:r,bounds:i,lights:s,animations:u,worldMatrices:c}=Fe(this.gl,t,e,()=>this.render());if(this.disposeMeshGpuResources(),this.meshes=r,this.bounds=i,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=s,this.animations=u||[],this.worldMatrices=c||[],this.gltf=t.gltf,this.initialNodeTransforms=[],Array.isArray(t.gltf?.nodes))for(let l of t.gltf.nodes)this.initialNodeTransforms.push({t:l.translation?[l.translation[0],l.translation[1],l.translation[2]]:[0,0,0],r:l.rotation?[l.rotation[0],l.rotation[1],l.rotation[2],l.rotation[3]]:[0,0,0,1],s:l.scale?[l.scale[0],l.scale[1],l.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let l of O)l.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 o=t.exposure??t.environmentIntensity??t.gltf?.extras?.exposure??t.gltf?.extras?.environmentIntensity??t.gltf?.asset?.extras?.exposure??t.gltf?.asset?.extras?.environmentIntensity;o!==void 0&&(this.envIntensity=Math.max(0,Number(o))),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(t){this.loadGLBData(Be(t))}loadModel(t){this.loadGLBData(oe(t))}setBackdropGLB(t,e){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!t){this.update(0),this.render();return}let r=oe(t),{meshes:i}=Fe(this.gl,r,Ge,()=>this.render());if(e)for(let s of i)s.transform[12]+=e[0],s.transform[13]+=e[1],s.transform[14]+=e[2],se(s.normalMatrix,s.transform);this.backdropMeshes=i,this.update(0),this.render()}setClearColor(t,e,r,i=1){this.clearColor=[t,e,r,i]}updateMeshTransforms(t){for(let e=0;e<this.meshes.length;e++){let r=this.meshes[e],i;t instanceof Map?i=t.get(r.name)??t.get(e):Array.isArray(t)?i=t[e]:t&&typeof t=="object"&&(Object.prototype.hasOwnProperty.call(t,r.name)?i=t[r.name]:Object.prototype.hasOwnProperty.call(t,e)&&(i=t[e])),i&&i.length===16&&(r.transform.set(i),se(r.normalMatrix,r.transform))}}bindLights(t=this.uRender){let e=this.gl,r=[.28,.28,.28],i=[],s=[],u=[],c=[];for(let o of this.lights){let l=o.color||[1,1,1],a=o.intensity!==void 0?o.intensity:1;if(o.type==="ambient")r=[l[0]*a,l[1]*a,l[2]*a];else if(o.type==="directional"&&i.length<6){let h=o.direction||[.5,1,.8];i.push(h[0],h[1],h[2]),s.push(l[0]*a,l[1]*a,l[2]*a)}else if(o.type==="point"&&u.length<6){let h=o.position||[0,0,0];u.push(h[0],h[1],h[2]),c.push(l[0]*a,l[1]*a,l[2]*a)}}i.length===0&&(i.push(.5,1,.8),s.push(1,1,1)),e.uniform3fv(t.uAmbientColor,r),e.uniform1i(t.uNumDirLights,i.length/3),i.length>0&&(e.uniform3fv(t.uDirLightDir,i),e.uniform3fv(t.uDirLightColor,s)),e.uniform1i(t.uNumPointLights,u.length/3),u.length>0&&(e.uniform3fv(t.uPointLightPos,u),e.uniform3fv(t.uPointLightColor,c)),e.uniform1f(t.uEnvIntensity,this.envIntensity)}setExposure(t){this.envIntensity=Math.max(0,Number(t))}getExposure(){return this.envIntensity}setShadow(t,e){this.shadowIntensity=Math.max(0,Math.min(1,Number(t)||0)),e!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(e)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(t){this.toneMapping=t}getToneMapping(){return this.toneMapping}async setEnvironmentImage(t){for(let e of O)if(e.setEnvironmentImage){await e.setEnvironmentImage(this,t);return}}async setSkyboxImage(t){for(let e of O)if(e.setSkyboxImage){await e.setSkyboxImage(this,t);return}}setInteractive(t){this.interactive=t}isInteractive(){return this.interactive}getCameraOrbit(){let t=this.currTheta,e=this.currPhi,r=this.currDistance;return{theta:t,phi:e,radius:r,toString(){return`${t.toFixed(4)}rad ${e.toFixed(4)}rad ${r.toFixed(4)}m`}}}getCameraTarget(){let t=this.customTarget||this.bounds.center;return{x:t[0],y:t[1],z:t[2],toString(){return`${t[0].toFixed(4)}m ${t[1].toFixed(4)}m ${t[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let t=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return t.map((e,r)=>{let i=this.meshes.flatMap(a=>a.primitives.filter(h=>h.materialIndex===r||t.length===1&&h.materialIndex===void 0)),s=i[0],u=s?[...s.baseColor]:e.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],c=s?s.metallic:e.pbrMetallicRoughness?.metallicFactor??.1,o=s?s.roughness:e.pbrMetallicRoughness?.roughnessFactor??.5,l={baseColorFactor:u,metallicFactor:c,roughnessFactor:o,setBaseColorFactor:a=>{let h=[a[0],a[1],a[2],a[3]??1];l.baseColorFactor=h,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.baseColorFactor=h);for(let m of i)m.baseColor=h;this.render()},setMetallicFactor:a=>{l.metallicFactor=a,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.metallicFactor=a);for(let h of i)h.metallic=a;this.render()},setRoughnessFactor:a=>{l.roughnessFactor=a,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.roughnessFactor=a);for(let h of i)h.roughness=a;this.render()}};return{name:e.name||`Material_${r}`,pbrMetallicRoughness:l}})}playAnimation(t){if(this.animations.length!==0){if(t){let e=this.animations.find(r=>r.name===t);e&&(this.currentClip=e)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(t=>t.name)}setAutoplay(t){this.autoplay=t,t?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(t){this.animationName=t,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(t)}evaluateAnimation(t){for(let e of O)if(e.evaluateAnimation){e.evaluateAnimation(this,t);return}}setTarget(t,e,r){this.customTarget=[t,e,r],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(t){let e=Math.max(10,Math.min(90,t));this.fov=e*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(t){if(this.distanceMode=t,!this.customDistance){let e=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=e,this.targetDistance=e,this.currDistance=e,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(t){t.minTheta!==void 0&&(this.minTheta=t.minTheta*Math.PI/180),t.maxTheta!==void 0&&(this.maxTheta=t.maxTheta*Math.PI/180),t.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,t.minPhi*Math.PI/180)),t.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,t.maxPhi*Math.PI/180)),t.minDistance!==void 0&&(this.minDistanceLimit=t.minDistance),t.maxDistance!==void 0&&(this.maxDistanceLimit=t.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){return{minTheta:isFinite(this.minTheta)?this.minTheta*180/Math.PI:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*180/Math.PI:void 0,minPhi:this.minPhi*180/Math.PI,maxPhi:this.maxPhi*180/Math.PI,minDistance:this.minDistanceLimit!==null?this.minDistanceLimit:void 0,maxDistance:this.maxDistanceLimit!==null?this.maxDistanceLimit:void 0}}clampTheta(t){return Math.max(this.minTheta,Math.min(this.maxTheta,t))}clampPhi(t){return Math.max(this.minPhi,Math.min(this.maxPhi,t))}clampDistance(t){let e=this.minDistanceLimit!==null?this.minDistanceLimit:this.bounds?this.bounds.radius*.5:.1,r=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(e,Math.min(r,t))}setCamera(t,e,r,i){t!==void 0&&(this.targetTheta=this.clampTheta(t*Math.PI/180)),e!==void 0&&(this.targetPhi=this.clampPhi(e*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(t,e,r,i){if(t!==void 0&&(this.initialTheta=this.clampTheta(t*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),e!==void 0&&(this.initialPhi=this.clampPhi(e*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),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(t,e){let r=V();Y(r,this.projMatrix,this.viewMatrix);let[i,s,u]=t,c=e?e[0]:0,o=e?e[1]:0,l=e?e[2]:0,a=this.modelRootMatrix;a&&(i=a[0]*t[0]+a[4]*t[1]+a[8]*t[2]+a[12],s=a[1]*t[0]+a[5]*t[1]+a[9]*t[2]+a[13],u=a[2]*t[0]+a[6]*t[1]+a[10]*t[2]+a[14],e&&(c=a[0]*e[0]+a[4]*e[1]+a[8]*e[2],o=a[1]*e[0]+a[5]*e[1]+a[9]*e[2],l=a[2]*e[0]+a[6]*e[1]+a[10]*e[2]));let h=r[0]*i+r[4]*s+r[8]*u+r[12],m=r[1]*i+r[5]*s+r[9]*u+r[13],b=r[2]*i+r[6]*s+r[10]*u+r[14],p=r[3]*i+r[7]*s+r[11]*u+r[15];if(p<=1e-4)return{x:0,y:0,z:1,visible:!1};let y=h/p,g=m/p,M=b/p,w=this.canvas.getBoundingClientRect(),R=w.width||this.canvas.clientWidth||this.canvas.width||300,T=w.height||this.canvas.clientHeight||this.canvas.height||150,v=(y*.5+.5)*R,x=(-g*.5+.5)*T,S=y>=-1.1&&y<=1.1&&g>=-1.1&&g<=1.1&&M>=-1&&M<=1;if(S&&e){let A=this.customTarget||this.bounds.center,f=A[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),P=A[1]+this.currDistance*Math.sin(this.currPhi),D=A[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),d=[i-f,s-P,u-D];c*d[0]+o*d[1]+l*d[2]>.05&&(S=!1)}return{x:v,y:x,z:M,visible:S}}setSelectedMesh(t){this.selectedMeshName=t||""}setupEvents(){let t=this.canvas;this.boundContextMenu=e=>{e.preventDefault()},t.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=e=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.lastPointerX=e.clientX,this.lastPointerY=e.clientY,this.totalDragDist=0,this.activePointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.isPanning=e.button===2||e.shiftKey||this.activePointers.size===2,t.setPointerCapture(e.pointerId))},t.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=e=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=this.activePointers.get(e.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},i=e.clientX-r.x,s=e.clientY-r.y;if(this.activePointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.lastPointerX=e.clientX,this.lastPointerY=e.clientY,this.totalDragDist+=Math.hypot(i,s),this.isPanning||e.button===2||e.shiftKey||this.activePointers.size===2){let u=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],c=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],o=this.customTarget?[...this.customTarget]:[...this.bounds.center],l=this.currDistance/Math.max(t.clientHeight||300,1)*1.5;o[0]+=(-i*u[0]+s*c[0])*l,o[1]+=(-i*u[1]+s*c[1])*l,o[2]+=(-i*u[2]+s*c[2])*l,this.customTarget=o}else this.targetTheta=this.clampTheta(this.targetTheta-i*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},t.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=e=>{this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.activePointers.delete(e.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{t.releasePointerCapture(e.pointerId)}catch{}if(this.totalDragDist<5&&e.button===0){let r=t.getBoundingClientRect(),i=Math.floor((e.clientX-r.left)*(t.width/Math.max(r.width,1))),s=Math.floor((e.clientY-r.top)*(t.height/Math.max(r.height,1)));this.performMeshPick(i,s,!0)}},t.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=e=>{if(!this.interactive)return;e.preventDefault(),this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=Math.exp(e.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},t.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=e=>{let r=e.detail||{};r.reset?this.resetCamera():this.setCamera(r.theta,r.phi,r.distance,r.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),t.tabIndex!==void 0&&t.tabIndex<0&&(t.tabIndex=0),t.getAttribute?.("role")||t.setAttribute?.("role","region"),t.getAttribute?.("aria-label")||t.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=e=>{if(!this.interactive)return;let r=typeof performance<"u"?performance.now():Date.now();switch(e.key){case"ArrowLeft":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta-.1),e.preventDefault();break;case"ArrowRight":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta+.1),e.preventDefault();break;case"ArrowUp":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi+.08),e.preventDefault();break;case"ArrowDown":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi-.08),e.preventDefault();break;case"+":case"=":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*.9),e.preventDefault();break}case"-":case"_":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*1.1),e.preventDefault();break}case"Home":this.lastInteractionTime=r,this.resetCamera(),e.preventDefault();break}},t.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let t=this.canvas;this.boundContextMenu&&(t.removeEventListener("contextmenu",this.boundContextMenu),this.boundContextMenu=null),this.boundPointerDown&&(t.removeEventListener("pointerdown",this.boundPointerDown),this.boundPointerDown=null),this.boundPointerMove&&(t.removeEventListener("pointermove",this.boundPointerMove),this.boundPointerMove=null),this.boundPointerUp&&(t.removeEventListener("pointerup",this.boundPointerUp),this.boundPointerUp=null),this.boundWheel&&(t.removeEventListener("wheel",this.boundWheel),this.boundWheel=null),this.boundKeyDown&&(t.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(t,e){let r=this.canvas,i=r.getBoundingClientRect(),s=r.width||300,u=r.height||300,c=i.width>0?Math.floor((t-i.left)*(s/i.width)):Math.floor(t),o=i.height>0?Math.floor((e-i.top)*(u/i.height)):Math.floor(e);return this.performMeshPick(c,o,!1)}performMeshPick(t,e,r=!0){if(this.meshes.length===0)return null;let i=this.gl,s=Math.max(1,this.canvas.width||300),u=Math.max(1,this.canvas.height||300),c=V();Y(c,this.projMatrix,this.viewMatrix);let o=[],l=Math.max(0,Math.min(s-1,t)),a=Math.max(0,Math.min(u-1,u-1-e));if(this.pickFbo&&i){(this.pickFboWidth!==s||this.pickFboHeight!==u)&&this.resizePickingFbo(s,u),i.bindFramebuffer(36160,this.pickFbo),i.viewport(0,0,s,u),i.enable(2929),i.clearColor(0,0,0,0),i.clear(16384|256),i.useProgram(this.pickProg);for(let S=0;S<this.meshes.length;S++){let A=this.meshes[S];if(A.visible===!1||A.isPluginMesh)continue;let f=S+1,P=(f&255)/255,D=(f>>8&255)/255,d=(f>>16&255)/255;i.uniform4f(this.uPick.uColorId,P,D,d,1),Y(this.modelMatrix,this.modelRootMatrix,A.transform),Y(this.mvpMatrix,c,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let C of A.primitives)i.bindVertexArray(C.vao),i.drawElements(4,C.indexCount,C.indexType,0)}let v=new Uint8Array(4);i.readPixels(l,a,1,1,6408,5121,v),i.bindFramebuffer(36160,null);let x=v[0]+(v[1]<<8)+(v[2]<<16);x>0&&x<=this.meshes.length&&(o=[this.meshes[x-1]])}o.length===0&&(o=this.meshes.filter(v=>v.visible!==!1));let h=null,m=1/0,b=[0,0,0],p=[0,1,0],y=this.customTarget||this.bounds.center,g=y[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),M=y[1]+this.currDistance*Math.sin(this.currPhi),w=y[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let v of o){Y(this.modelMatrix,this.modelRootMatrix,v.transform),Y(this.mvpMatrix,c,this.modelMatrix);let x=V();if(!De(x,this.mvpMatrix))continue;let S=(l+.5)/s*2-1,A=(a+.5)/u*2-1,f=[0,0,0],P=[0,0,0];xe(f,S,A,-1,x),xe(P,S,A,1,x);let D=P[0]-f[0],d=P[1]-f[1],C=P[2]-f[2],E=Math.hypot(D,d,C)||1,X=D/E,ee=d/E,j=C/E,_={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((k=>{for(let W of v.primitives){if(!W.positions)continue;let I=W.positions,L=W.indices,B=Math.floor(L?L.length/3:I.length/9);for(let H=0;H<B;H++){let K=L?L[H*3]:H*3,J=L?L[H*3+1]:H*3+1,Z=L?L[H*3+2]:H*3+2;Ce(f[0],f[1],f[2],X,ee,j,I[K*3],I[K*3+1],I[K*3+2],I[J*3],I[J*3+1],I[J*3+2],I[Z*3],I[Z*3+1],I[Z*3+2],_,k)}}})(1e-4),isFinite(_.distance)){let k=_.point[0],W=_.point[1],I=_.point[2],L=this.modelMatrix,B=L[0]*k+L[4]*W+L[8]*I+L[12],H=L[1]*k+L[5]*W+L[9]*I+L[13],K=L[2]*k+L[6]*W+L[10]*I+L[14],J=B-g,Z=H-M,pe=K-w,z=Math.hypot(J,Z,pe);if(z<m){se(this.normalMatrix,this.modelMatrix);let $=this.normalMatrix,ce=_.normal[0],le=_.normal[1],ne=_.normal[2],te=$[0]*ce+$[3]*le+$[6]*ne,ie=$[1]*ce+$[4]*le+$[7]*ne,re=$[2]*ce+$[5]*le+$[8]*ne,he=Math.hypot(te,ie,re)||1;te/=he,ie/=he,re/=he,te*J+ie*Z+re*pe>0&&(te=-te,ie=-ie,re=-re),h=v,m=Math.round(z*1e3)/1e3,b=[Math.round(B*1e3)/1e3,Math.round(H*1e3)/1e3,Math.round(K*1e3)/1e3],p=[Math.round(te*1e3)/1e3,Math.round(ie*1e3)/1e3,Math.round(re*1e3)/1e3]}}}if(!h)return null;let T={meshIndex:this.meshes.indexOf(h),meshName:h.name,nodeIndex:h.nodeIndex,distance:m,hitPoint:b,normal:p,screenX:t,screenY:e};if(r){for(let v of O)v.onMeshSelect?.(this,T);this.opts.onMeshClick&&this.opts.onMeshClick(T),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:T}))}return T}resize(){let t=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),e=this.canvas.getBoundingClientRect(),r=Math.max(1,Math.floor(e.width*t)),i=Math.max(1,Math.floor(e.height*t));(this.canvas.width!==r||this.canvas.height!==i)&&(this.canvas.width=r,this.canvas.height=i,this.resizePickingFbo(r,i))}start(){if(this.animFrameId!==null)return;this.lastTime=performance.now();let t=e=>{let r=Math.min((e-this.lastTime)/1e3,.1);this.lastTime=e,this.isVisible&&(this.resize(),this.update(r),this.render()),this.animFrameId=requestAnimationFrame(t)};this.animFrameId=requestAnimationFrame(t)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(t){this.autoRotate=t}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(t){this.autoRotateSpeed=t}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(t){this.autoRotateDelay=Math.max(0,Number(t)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(t=0){this.turntableRotation=Number(t)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let t=Math.cos(this.turntableRotation),e=Math.sin(this.turntableRotation),r=this.bounds.center[0],i=this.bounds.center[2],s=this.modelRootMatrix;s[0]=t,s[1]=0,s[2]=-e,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=e,s[9]=0,s[10]=t,s[11]=0,s[12]=r-(t*r+e*i),s[13]=0,s[14]=i-(-e*r+t*i),s[15]=1}setVisible(t){this.isVisible=t}update(t){for(let m of O)m.onUpdate?.(this,t);let e=typeof performance<"u"?performance.now():Date.now();if(!this.isPointerDown&&this.autoRotate&&e-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*t,this.updateTurntableMatrix();for(let m of O)m.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;let r=(this.canvas.width||1)/(this.canvas.height||1),i=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):this.bounds.radius*20;Ee(this.projMatrix,this.fov,r,.1,i);let s=this.customTarget||this.bounds.center,u=s[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),c=s[1]+this.currDistance*Math.sin(this.currPhi),o=s[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);Ae(this.viewMatrix,[u,c,o],s,[0,1,0]),Y(this.mvpMatrix,this.projMatrix,this.viewMatrix),se(this.normalMatrix,this.modelMatrix);let l=Math.round((this.currTheta*180/Math.PI%360+360)%360),a=Math.round(this.currPhi*180/Math.PI),h=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(l-this.lastReportedTheta)>=1||Math.abs(a-this.lastReportedPhi)>=1||Math.abs(h-this.lastReportedZoom)>=.02){this.lastReportedTheta=l,this.lastReportedPhi=a,this.lastReportedZoom=h;let m={theta:l,phi:a,zoom:h,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(m),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:m}))}}renderXRView(t,e,r,i){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(t);let s=t?.transform?.inverse?.matrix||this.viewMatrix,u=t?.projectionMatrix||this.projMatrix,c=t?.transform?.position,o=c?[c.x,c.y,c.z]:[0,1.6,0];r&&e&&this.modelRootMatrix.set(e),this.render({viewMatrix:s,projMatrix:u,eyePos:o,viewport:i,eye:t?.eye||"none",clear:t?.eye!=="right"})}render(t){let e=this.gl,r=this.canvas.width,i=this.canvas.height;t?.viewport?(e.viewport(t.viewport[0],t.viewport[1],t.viewport[2],t.viewport[3]),r=t.viewport[2],i=t.viewport[3]):e.viewport(0,0,this.canvas.width,this.canvas.height),e.enable(2929),(!t||t.clear!==!1)&&(e.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),e.clear(16384|256));let s=V();Y(s,t?.projMatrix??this.projMatrix,t?.viewMatrix??this.viewMatrix);let u=this.toneMapping==="reinhard"?1:this.toneMapping==="none"?2:0,c=this.customTarget||this.bounds.center,o=t?t.eyePos[0]:c[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),l=t?t.eyePos[1]:c[1]+this.currDistance*Math.sin(this.currPhi),a=t?t.eyePos[2]:c[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let g of O)g.onBeforeDrawScene?.(this,e,s,[o,l,a],u);if(this.meshes.length===0&&this.backdropMeshes.length===0)return;let h=t?.eye||"none",m=!1,b=this.backdropMeshes.length,p=b>0?[...this.backdropMeshes,...this.meshes]:this.meshes,y=g=>{for(let M=0;M<p.length;M++){let w=p[M];if(w.visible===!1)continue;let R=this.selectedMeshName!==""&&w.name===this.selectedMeshName;M<b?this.modelMatrix.set(w.transform):Y(this.modelMatrix,this.modelRootMatrix,w.transform),Y(this.mvpMatrix,s,this.modelMatrix),se(w.normalMatrix,this.modelMatrix);let T=w.extras?.xr?.stereo||w.userData?.xr?.stereo,v=0,x=0,S=1,A=1;T==="sbs"?(S=.5,v=h==="right"?.5:0):T==="ou"&&(A=.5,x=h==="right"?.5:0);for(let f of w.primitives){let P=!!f.isTransmissive;if(!g&&P){m=!0;continue}if(g&&!P)continue;let D=f.customProgram||this.renderProg,d=f.customUniforms||this.uRender;e.useProgram(D),e.uniform1i(d.uToneMapping,u),e.uniform1f(d.uEnvIntensity,this.envIntensity),e.uniform3f(d.uCameraPos,o,l,a),e.uniform1f(d.uEmissive,R?1:0),e.uniformMatrix4fv(d.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(d.uModel,!1,this.modelMatrix),e.uniformMatrix3fv(d.uNormalMatrix,!1,w.normalMatrix),d.uUvTransform&&e.uniform4f(d.uUvTransform,v,x,S,A),d.uViewportSize&&e.uniform2f(d.uViewportSize,Math.max(1,r),Math.max(1,i)),this.xrDepthState.enabled&&this.xrDepthState.texture?(e.activeTexture(33989),e.bindTexture(3553,this.xrDepthState.texture),d.uXrDepthTex&&e.uniform1i(d.uXrDepthTex,5),d.uXrDepthEnabled&&e.uniform1i(d.uXrDepthEnabled,1),d.uXrDepthFormat&&e.uniform1i(d.uXrDepthFormat,this.xrDepthState.format||0),d.uXrRawValueToMeters&&e.uniform1f(d.uXrRawValueToMeters,this.xrDepthState.rawValueToMeters),d.uXrDepthUVTransform&&e.uniformMatrix4fv(d.uXrDepthUVTransform,!1,this.xrDepthState.uvTransform)):d.uXrDepthEnabled&&e.uniform1i(d.uXrDepthEnabled,0),this.environmentTexture?(e.activeTexture(33988),e.bindTexture(3553,this.environmentTexture),e.uniform1i(d.uEnvironmentMap,4),e.uniform1i(d.uHasEnvironmentMap,1)):e.uniform1i(d.uHasEnvironmentMap,0),this.bindLights(d);for(let C of O)C.onBeforeDrawPrimitive?.(e,D,f,w,this.worldMatrices||[],this.gltf);e.uniform4fv(d.uBaseColor,f.baseColor),e.uniform1f(d.uMetallic,f.metallic),e.uniform1f(d.uRoughness,f.roughness),d.uClearcoat&&e.uniform2f(d.uClearcoat,f.clearcoat??0,f.clearcoatRoughness??.04),f.texture?(e.activeTexture(33984),e.bindTexture(3553,f.texture),e.uniform1i(d.uBaseColorTexture,0),e.uniform1i(d.uHasTexture,1)):e.uniform1i(d.uHasTexture,0),f.metallicRoughnessTexture?(e.activeTexture(33985),e.bindTexture(3553,f.metallicRoughnessTexture),e.uniform1i(d.uMetallicRoughnessTexture,1),e.uniform1i(d.uHasMetallicRoughnessTexture,1)):e.uniform1i(d.uHasMetallicRoughnessTexture,0),f.normalTexture?(e.activeTexture(33986),e.bindTexture(3553,f.normalTexture),e.uniform1i(d.uNormalTexture,2),e.uniform1i(d.uHasNormalTexture,1),e.uniform1f(d.uNormalScale,f.normalScale)):e.uniform1i(d.uHasNormalTexture,0),f.occlusionTexture?(e.activeTexture(33987),e.bindTexture(3553,f.occlusionTexture),e.uniform1i(d.uOcclusionTexture,3),e.uniform1i(d.uHasOcclusionTexture,1),e.uniform1f(d.uOcclusionStrength,f.occlusionStrength)):e.uniform1i(d.uHasOcclusionTexture,0),e.bindVertexArray(f.vao),e.drawElements(4,f.indexCount,f.indexType,0)}}};if(y(!1),m){for(let g of O)g.onBeforeTransmissivePass?.(e,this);y(!0)}for(let g of O)g.onAfterRender?.(e,this,s)}disposeMeshListGpuResources(t){let e=this.gl;for(let r of t)for(let i of r.primitives){if(i.vao&&e.deleteVertexArray(i.vao),i.buffers)for(let s of i.buffers)e.deleteBuffer(s);i.texture&&e.deleteTexture(i.texture),i.metallicRoughnessTexture&&e.deleteTexture(i.metallicRoughnessTexture),i.normalTexture&&e.deleteTexture(i.normalTexture),i.occlusionTexture&&e.deleteTexture(i.occlusionTexture),i.customProgram&&e.deleteProgram(i.customProgram)}}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes),this.meshes=[]}disposeGpuResources(){let t=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let e of O)e.onDestroy?.(t,this);this.environmentTexture&&(t.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&t.deleteProgram(this.renderProg),this.pickProg&&t.deleteProgram(this.pickProg),this.pickFbo&&t.deleteFramebuffer(this.pickFbo),this.pickTexture&&t.deleteTexture(this.pickTexture),this.pickDepth&&t.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};G.registerPlugin=we,G.getRegisteredPlugins=Re;var _e='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).',He="Security Error: client-side scripts require allow-client-scripts opt-in.";var st=typeof HTMLElement<"u"?HTMLElement:class{};typeof CustomEvent>"u"&&typeof Event<"u"&&(globalThis.CustomEvent=class extends Event{constructor(n,t){super(n,t),this.detail=t?.detail??null}});var N=class N extends st{constructor(){super(...arguments);this.viewer=null;this.canvas=null;this.posterEl=null;this.arButton=null;this.currentModel=null;this.currentModelLimits=void 0;this.isModelLoaded=!1;this.scriptHandle=null;this.resizeObserver=null;this.mutationObserver=null}static get arProvider(){return U().arProvider}static set arProvider(e){U().arProvider=e}static get scriptRunner(){return U().scriptRunner}static set scriptRunner(e){U().scriptRunner=e}static get sandboxEngineSrc(){return U().sandboxEngineSrc??null}static set sandboxEngineSrc(e){U().sandboxEngineSrc=e}static get sandboxIframeSrc(){return U().sandboxIframeSrc??null}static set sandboxIframeSrc(e){U().sandboxIframeSrc=e}static get allowClientScripts(){return!!U().allowClientScripts}static set allowClientScripts(e){U().allowClientScripts=e}static registerScriptRunner(e){N.scriptRunner=e}static registerDecoder(e,r){G.registerDecoder(e,r)}static getDecoder(e){return G.getDecoder(e)}static registerAR(e){typeof e=="function"?N.arProvider={activateAR:e}:N.arProvider=e,typeof document<"u"&&document.querySelectorAll("three-live").forEach(i=>{i instanceof N&&i.updateARButtonVisibility()})}static isARSupported(){return!!N.arProvider}connectedCallback(){if(typeof document>"u")return;(!this.style.display||this.style.display==="inline")&&(this.style.display="block"),getComputedStyle(this).position==="static"&&(this.style.position="relative"),this.style.overflow="hidden",this.setupDOM(),this.initViewer(),this.setupResizeObserver();let e=this.getAttribute("src"),r=this.getAttribute("script-src");if(e)this.loadModelFromSrc(e).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 G.getRegisteredPlugins())i.onElementConnected?.(this)}disconnectedCallback(){for(let e of G.getRegisteredPlugins())e.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.viewer&&(this.viewer.destroy(),this.viewer=null),this.isModelLoaded=!1}attributeChangedCallback(e,r,i){if(r!==i){switch(e){case"src":i&&this.loadModelFromSrc(i).catch(()=>{});break;case"camera-target":this.applyCameraTarget(i);break;case"min-camera-orbit":case"max-camera-orbit":this.applyOrbitLimits();break;case"field-of-view":this.applyFieldOfView(i);break;case"script-src":i&&this.loadScriptFromSrc(i).catch(()=>{});break;case"sandbox":case"allow-client-scripts":case"ios-src":break;case"poster":this.updatePoster(i);break;case"camera-orbit":this.applyCameraOrbit(i);break;case"selected-mesh":this.viewer&&i!==null&&this.viewer.setSelectedMesh(i);break;case"exposure":if(this.viewer&&i!==null){let s=parseFloat(i);isNaN(s)||this.viewer.setExposure(s)}break;case"shadow-intensity":case"shadow-softness":this.viewer&&this.viewer.setShadow(this.shadowIntensity,this.shadowSoftness);break;case"tone-mapping":this.viewer&&i&&this.viewer.setToneMapping(i);break;case"environment-image":this.viewer&&this.viewer.setEnvironmentImage(i).catch(()=>{});break;case"skybox-image":this.viewer&&this.viewer.setSkyboxImage?.(i)?.catch?.(()=>{});break;case"camera-controls":{let s=this.cameraControls;this.viewer&&this.viewer.setInteractive?.(s),this.canvas&&(this.canvas.style.touchAction=s?"none":"auto");break}case"autoplay":this.viewer&&this.viewer.setAutoplay(i!==null&&i!=="false");break;case"animation-name":this.viewer&&i!==null&&this.viewer.setAnimationName(i);break;case"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 G.getRegisteredPlugins())s.onAttributeChanged?.(this,e,r,i)}}getAttr(e){return this.getAttribute(e)}setAttr(e,r){r!==null?this.setAttribute(e,r):this.removeAttribute(e)}getBoolAttr(e){return this.hasAttribute(e)&&this.getAttribute(e)!=="false"}setBoolAttr(e,r){r?this.setAttribute(e,""):this.removeAttribute(e)}getFloatAttr(e,r){let i=this.getAttribute(e);return i!==null?parseFloat(i):r}get src(){return this.getAttr("src")}set src(e){this.setAttr("src",e)}get cameraControls(){return this.getBoolAttr("camera-controls")}set cameraControls(e){this.setBoolAttr("camera-controls",e)}get cameraOrbit(){return this.getAttr("camera-orbit")}set cameraOrbit(e){this.setAttr("camera-orbit",e)}get cameraTarget(){return this.getAttr("camera-target")}set cameraTarget(e){this.setAttr("camera-target",e)}get minCameraOrbit(){return this.getAttr("min-camera-orbit")}set minCameraOrbit(e){this.setAttr("min-camera-orbit",e)}get maxCameraOrbit(){return this.getAttr("max-camera-orbit")}set maxCameraOrbit(e){this.setAttr("max-camera-orbit",e)}get fieldOfView(){return this.getAttr("field-of-view")}set fieldOfView(e){this.setAttr("field-of-view",e)}get iosSrc(){return this.getAttr("ios-src")}set iosSrc(e){this.setAttr("ios-src",e)}get scriptSrc(){return this.getAttr("script-src")}set scriptSrc(e){this.setAttr("script-src",e)}get sandbox(){return this.getAttribute("sandbox")||(U().sandboxIframeSrc?"iframe":"worker")}set sandbox(e){this.setAttribute("sandbox",e)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||N.allowClientScripts}set allowClientScripts(e){this.setBoolAttr("allow-client-scripts",e)}get poster(){return this.getAttr("poster")}set poster(e){this.setAttr("poster",e)}get selectedMesh(){return this.getAttr("selected-mesh")}set selectedMesh(e){this.setAttr("selected-mesh",e)}get exposure(){return this.getFloatAttr("exposure",1)}set exposure(e){this.setAttribute("exposure",String(e))}get autoRotate(){return this.getBoolAttr("auto-rotate")}set autoRotate(e){this.setBoolAttr("auto-rotate",e)}get autoRotateDelay(){return this.getFloatAttr("auto-rotate-delay",3e3)}set autoRotateDelay(e){this.setAttribute("auto-rotate-delay",String(e))}get rotationPerSecond(){return this.getAttr("rotation-per-second")||"30deg"}set rotationPerSecond(e){this.setAttr("rotation-per-second",e)}get turntableRotation(){return this.viewer?this.viewer.turntableRotation:0}get ar(){return this.hasAttribute("ar")}set ar(e){this.setBoolAttr("ar",e)}get arScale(){return this.getAttribute("ar-scale")||"auto"}set arScale(e){this.setAttribute("ar-scale",e)}get arPlacement(){return this.getAttribute("ar-placement")||"floor"}set arPlacement(e){this.setAttribute("ar-placement",e)}get canActivateAR(){return N.isARSupported()}get shadowIntensity(){return this.getFloatAttr("shadow-intensity",0)}set shadowIntensity(e){this.setAttribute("shadow-intensity",String(e))}get shadowSoftness(){return this.getFloatAttr("shadow-softness",.5)}set shadowSoftness(e){this.setAttribute("shadow-softness",String(e))}get toneMapping(){return this.getAttribute("tone-mapping")||"neutral"}set toneMapping(e){this.setAttribute("tone-mapping",e)}get environmentImage(){return this.getAttr("environment-image")}set environmentImage(e){this.setAttr("environment-image",e)}get skyboxImage(){return this.getAttr("skybox-image")}set skyboxImage(e){this.setAttr("skybox-image",e)}get autoplay(){return this.getBoolAttr("autoplay")}set autoplay(e){this.setBoolAttr("autoplay",e)}get animationName(){return this.getAttr("animation-name")}set animationName(e){this.setAttr("animation-name",e)}get availableAnimations(){return this.viewer?this.viewer.getAvailableAnimations():[]}get model(){let e=this.viewer?this.viewer.getModelMaterials():[];return{materials:e,getMaterialByName(r){return e.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(e=0){this.viewer?.resetTurntableRotation(e)}setCamera(e,r,i,s){this.viewer&&this.viewer.setCamera(e,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(e,r){return this.viewer&&this.viewer.render?.(),this.canvas?this.canvas.toDataURL(e,r):""}toBlob(e){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."))},e?.mimeType,e?.qualityArgument)})}positionAndNormalFromPoint(e,r){if(!this.viewer)return null;let i=this.viewer.raycastFromScreenPoint(e,r);if(!i)return null;let[s,u,c]=i.hitPoint||i.point,[o,l,a]=i.normal;return{position:{x:s,y:u,z:c,toString(){return`${s}m ${u}m ${c}m`}},normal:{x:o,y:l,z:a,toString(){return`${o}m ${l}m ${a}m`}}}}async loadModel(e){return this.loadModelWithLimits(e)}async loadModelWithLimits(e,r){if(!this.viewer){this.currentModel=e,this.currentModelLimits=r;return}try{let i;if(typeof e=="string"){let c=await fetch(e);if(!c.ok)throw new Error(`Failed to load 3D model from "${e}": HTTP ${c.status}`);i=await c.arrayBuffer()}else i=e;let s=oe(i);this.viewer.loadGLBData(s,r),this.currentModel=s,this.currentModelLimits=r,this.isModelLoaded=!0,this.hidePoster(),this.updateHotspots();let u=this.getAttribute("selected-mesh");u&&this.viewer.setSelectedMesh(u),this.dispatchEvent(new CustomEvent("load",{bubbles:!0,composed:!0,detail:{model:s}}))}catch(i){throw this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:i}})),i}}showToast(e,r=4e3){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 18px;background-color:rgba(15,23,42,0.92);color:#f8fafc;border:1px solid rgba(56,189,248,0.4);border-radius:9999px;font:500 13px system-ui,-apple-system,sans-serif;box-shadow:0 10px 25px rgba(0,0,0,0.4);backdrop-filter:blur(12px);pointer-events:none;opacity:0;transition:opacity .25s ease,transform .25s ease;max-width:90%;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis",this.appendChild(i)),i.textContent=e,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)"),setTimeout(()=>{i&&(i.style.opacity="0",i.style.transform="translateX(-50%) translateY(10px)")},r)}async activateAR(){if(!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),i}if(!N.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),i}let e=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 N.arProvider.activateAR({model:e||this.currentModel,glbUrl:typeof this.currentModel=="string"?this.currentModel:void 0,view:this.viewer||void 0,preferredModes:r.length>0?r:void 0,arScale:this.arScale,arPlacement:this.arPlacement,webXROptions:{onExit:()=>{this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"not-presenting"}}))},onError:s=>{this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:s}})),this.showToast(`AR error: ${s.message}`)}}});if(i.success)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{if(typeof document<"u"&&this.currentModel&&N.arProvider.createUSDZBlob)try{let s=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:N.arProvider.createUSDZBlob(this.currentModel),u=URL.createObjectURL(s),c=document.createElement("a");c.href=u,c.download="three_live_model.usdz",document.body.appendChild(c),c.click(),document.body.removeChild(c),setTimeout(()=>URL.revokeObjectURL(u),3e3),this.showToast("\u{1F4F1} AR camera requires iOS / Android. Downloaded USDZ for macOS Quick Look!")}catch{this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (Scene Viewer / WebXR) device.")}else this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (Scene Viewer / WebXR) device.");i.error&&this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i.error}}))}return i}catch(i){throw this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(`AR error: ${i.message||String(i)}`),i}}setupDOM(){let e=this.querySelector("canvas");e||(e=document.createElement("canvas"),e.style.width="100%",e.style.height="100%",e.style.display="block",e.style.touchAction=this.cameraControls?"none":"auto",e.style.outline="none",this.appendChild(e)),this.canvas=e;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 e=this.autoRotate,r=this.exposure,i=this.parseOrbitLimit(this.getAttribute("min-camera-orbit")),s=this.parseOrbitLimit(this.getAttribute("max-camera-orbit")),u=this.parseCameraTarget(this.getAttribute("camera-target")),c=this.parseFieldOfView(this.getAttribute("field-of-view"));this.viewer=new G(this,this.canvas,{autoRotate:e,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,fieldOfView:c,cameraTarget:u,minCameraOrbit:i,maxCameraOrbit:s,onMeshClick:l=>{this.dispatchEvent(new CustomEvent("meshclick",{bubbles:!0,composed:!0,detail:l}))},onCameraChange:l=>{this.updateHotspots();for(let a of G.getRegisteredPlugins())a.onCameraChange?.(this.viewer,this);this.dispatchEvent(new CustomEvent("camera-change",{bubbles:!0,composed:!0,detail:l}))}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let o=this.getAttribute("camera-orbit");o&&this.applyCameraOrbit(o),this.currentModel&&this.loadModelWithLimits(this.currentModel,this.currentModelLimits)}setupResizeObserver(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>{this.viewer&&(this.viewer.resize(),this.viewer.render(),this.updateHotspots())}),this.resizeObserver.observe(this))}updatePoster(e){if(!(typeof document>"u")){if(!e){this.posterEl&&(this.posterEl.remove(),this.posterEl=null);return}this.posterEl||(this.posterEl=document.createElement("img"),this.posterEl.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=e,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 e=document.createElement("button");e.setAttribute("type","button"),e.setAttribute("aria-label","View in Augmented Reality"),e.className="three-live-ar-button",e.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 u=document.createElementNS(r,"path");u.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 o=document.createElementNS(r,"line");o.setAttribute("x1","12"),o.setAttribute("y1","22.08"),o.setAttribute("x2","12"),o.setAttribute("y2","12"),s.appendChild(u),s.appendChild(c),s.appendChild(o),e.appendChild(s)}let i=document.createElement("span");i.textContent="View in AR",e.appendChild(i),e.style.cssText="position:absolute;right:16px;bottom:16px;z-index:2;align-items:center;justify-content:center;padding:8px 16px;background-color:rgba(15,23,42,0.85);color:#fff;border:1px solid rgba(255,255,255,0.15);border-radius:9999px;font:600 13px system-ui,-apple-system,sans-serif;cursor:pointer;backdrop-filter:blur(8px);box-shadow:0 4px 12px rgba(0,0,0,0.25);transition:transform .15s ease,background-color .15s ease;display:none",e.addEventListener("mouseenter",()=>{e.style.backgroundColor="rgba(30, 41, 59, 0.95)",e.style.transform="scale(1.04)"}),e.addEventListener("mouseleave",()=>{e.style.backgroundColor="rgba(15, 23, 42, 0.85)",e.style.transform="scale(1)"}),e.addEventListener("click",s=>{s.stopPropagation(),this.activateAR()}),this.arButton=e,this.appendChild(e)}this.updateARButtonVisibility()}}updateARButtonVisibility(){let e=this.hasAttribute("ar")&&!!N.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=e?r.dataset.tlOrigDisplay||"":"none"):this.arButton&&(this.arButton.style.display=e?"flex":"none")}applyCameraOrbit(e){if(!(!e||!this.viewer))try{let r=JSON.parse(e);this.viewer.setInitialCamera(r.theta,r.phi,r.distance,r.zoom)}catch{let r=e.trim().split(/\s+/);if(r.length>=2){let i=o=>o.endsWith("rad")?parseFloat(o)*180/Math.PI:parseFloat(o.replace(/deg$/,"")),s=r[0]==="auto"?void 0:i(r[0]),u=r[1]==="auto"?void 0:i(r[1]),c;r.length>=3&&r[2]!=="auto"&&(c=parseFloat(r[2].replace(/m$/,""))),(s!==void 0&&!isNaN(s)||u!==void 0&&!isNaN(u))&&this.viewer.setInitialCamera(s!==void 0&&!isNaN(s)?s:void 0,u!==void 0&&!isNaN(u)?u:void 0,c!==void 0&&!isNaN(c)?c:void 0)}}}parseOrbitLimit(e){if(!e)return{};let r=e.trim().split(/\s+/),i={};if(r.length>0&&r[0]!=="auto"){let s=r[0].endsWith("rad")?parseFloat(r[0])*180/Math.PI:parseFloat(r[0].replace(/deg$/,""));isNaN(s)||(i.theta=s)}if(r.length>1&&r[1]!=="auto"){let s=r[1].endsWith("rad")?parseFloat(r[1])*180/Math.PI:parseFloat(r[1].replace(/deg$/,""));isNaN(s)||(i.phi=s)}if(r.length>2&&r[2]!=="auto"){let s=parseFloat(r[2].replace(/m$/,""));isNaN(s)||(i.distance=s)}return i}applyOrbitLimits(){if(!this.viewer)return;let e=this.parseOrbitLimit(this.getAttribute("min-camera-orbit")),r=this.parseOrbitLimit(this.getAttribute("max-camera-orbit"));this.viewer.setOrbitLimits({minTheta:e.theta,maxTheta:r.theta,minPhi:e.phi,maxPhi:r.phi,minDistance:e.distance,maxDistance:r.distance})}parseCameraTarget(e){if(!e)return;let r=e.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(e){if(!e)return;let r=e.endsWith("rad")?parseFloat(e)*180/Math.PI:parseFloat(e.replace(/deg$/,""));return isNaN(r)?void 0:r}parseRotationPerSecond(e){if(!e)return Math.PI/6;let r=e.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(e){let r=this.parseCameraTarget(e);this.viewer&&r&&this.viewer.setTarget(r[0],r[1],r[2])}applyFieldOfView(e){let r=this.parseFieldOfView(e);this.viewer&&r!==void 0&&this.viewer.setFieldOfView(r)}updateHotspot(e){let r=this.querySelector(`[slot="${e.name}"]`);r&&(e.position!==void 0&&r.setAttribute("data-position",e.position),e.normal!==void 0&&r.setAttribute("data-normal",e.normal)),this.updateHotspots()}updateHotspots(){for(let e of G.getRegisteredPlugins())if(e.updateHotspotsForElement){e.updateHotspotsForElement(this,this.viewer);return}}async loadModelFromSrc(e){await this.loadModel(e)}runWithScriptRunner(e){let r=N.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),new Promise((i,s)=>{let u=!1;e(r,{onModelReady:o=>{this.loadModelWithLimits(o,Oe).then(()=>{u||(u=!0,i(o))},l=>{let a=l instanceof Error?l.message:String(l);this.showToast(a),u||(u=!0,s(l))})},onUpdateTransforms:o=>this.viewer?.updateMeshTransforms(o),onError:o=>{this.showToast(o.message),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:o}})),u||(u=!0,s(o))},onToast:o=>this.showToast(o)}).then(o=>{o&&(this.scriptHandle=o)},o=>{o instanceof Error&&o.message&&this.showToast(o.message),u||(u=!0,s(o))})})}loadScriptFromSrc(e){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(e,this.sandbox,i)})}executeScript(e){if(!N.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(_e);return this.showToast(He),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:r}})),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(e,this.sandbox,i,{allowClientScripts:!0}))}};N.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","environment-image","skybox-image","autoplay","animation-name","auto-rotate","auto-rotate-delay","rotation-per-second"],N.registerPlugin=G.registerPlugin,N.getRegisteredPlugins=G.getRegisteredPlugins;var de=N;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",de);return Je(at);})();
208
+ void main(){fragColor=uColorId;}`;function Le(n,t,e){let r=n.createShader(t);if(n.shaderSource(r,e),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 we(n,t,e){let r=Le(n,35633,t),i=Le(n,35632,e),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 Re(n,t,e){let r={};for(let i of e)r[i]=n.getUniformLocation(t,i);return r}var Fe=["uMVP","uModel","uNormalMatrix","uUvTransform","uBaseColor","uMetallic","uRoughness","uClearcoat","uEmissive","uCameraPos","uBaseColorTexture","uHasTexture","uMetallicRoughnessTexture","uHasMetallicRoughnessTexture","uNormalTexture","uHasNormalTexture","uNormalScale","uOcclusionTexture","uHasOcclusionTexture","uOcclusionStrength","uToneMapping","uEnvironmentMap","uHasEnvironmentMap","uAmbientColor","uNumDirLights","uDirLightDir","uDirLightColor","uNumPointLights","uPointLightPos","uPointLightColor","uEnvIntensity","uViewportSize","uSectionPlane","uSectionEnabled"];function Ue(){let n=_().xrDepthShader;return{fs:rt.replace("/*XRD_U*/",n?.uniformsGLSL||"").replace("/*XRD_O*/",n?.occlusionGLSL||""),uniforms:n?[...Fe,...n.uniformNames]:Fe}}function at(n){if(typeof n!="string")return null;let t=n.trim();if(!t||/[\x00-\x1f\x7f]/.test(t))return null;let e=t.toLowerCase();return e.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(t)?t:null:e.startsWith("https://")||e.startsWith("blob:")?t:e.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(t)||/(^|[\\/])\.\.([\\/]|$)/.test(t)?null:t}function Me(n,t,e,r,i,s,o){if(r===void 0||!t.accessors?.[r])return null;let l=t.accessors[r],u=t.bufferViews[l.bufferView],c=(u.byteOffset||0)+(l.byteOffset||0),a=u.byteStride&&u.byteStride>s*4?u.byteStride>>2:s,h;if(a===s)h=new Float32Array(e,c,l.count*s);else{h=new Float32Array(l.count*s);let b=new Float32Array(e,u.byteOffset||0,Math.floor(u.byteLength/4)),f=(l.byteOffset||0)>>2;for(let y=0;y<l.count;y++){let T=f+y*a;for(let w=0;w<s;w++)h[y*s+w]=b[T+w]}}let p=n.createBuffer();return o.push(p),n.bindBuffer(34962,p),n.bufferData(34962,h,35044),n.enableVertexAttribArray(i),n.vertexAttribPointer(i,s,5126,!1,0,0),h}var Ge=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),Oe=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Ie(n,t,e=Oe,r){if(!t||!t.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:i,bin:s}=t,o=[],l=Ce(i),u=[];if(Array.isArray(i.nodes))for(let E=0;E<i.nodes.length;E++){let g=i.nodes[E];g.mesh!==void 0&&i.meshes&&i.meshes[g.mesh]&&u.push({node:g,nodeIdx:E,meshIdx:g.mesh})}let c=u.length>0?u:(i.meshes||[]).map((E,g)=>({node:E,nodeIdx:-1,meshIdx:g})),a=[];if(Array.isArray(t.lights)&&t.lights.length>0)a.push(...t.lights);else if(i.extensions?.KHR_lights_punctual?.lights){let E=i.extensions.KHR_lights_punctual.lights;for(let g of E){let S=g.type==="directional"?"directional":g.type==="point"?"point":"ambient";a.push({type:S,color:g.color||[1,1,1],intensity:g.intensity!==void 0?g.intensity:1})}}if(a.length===0&&(a.push({type:"ambient",color:[1,1,1],intensity:.35}),a.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),c.length>e.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${e.maxMeshes}). Found: ${c.length}`);let h=[];if(i.textures&&i.images){if(i.textures.length>e.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${e.maxTextures}). Found: ${i.textures.length}`);for(let E=0;E<i.textures.length;E++){let g=i.textures[E],S=i.images[g.source];if(S){let D=n.createTexture();if(n.bindTexture(3553,D),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 C=i.bufferViews[S.bufferView],x=s.slice(C.byteOffset||0,(C.byteOffset||0)+C.byteLength),M=new Blob([x],{type:S.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(M).then(k=>{n.bindTexture(3553,D),n.texImage2D(3553,0,6408,6408,5121,k),n.generateMipmap(3553),r?.()}).catch(()=>{})}else if(S.uri){let C=at(S.uri);if(C){let x=new Image;x.crossOrigin="anonymous",x.referrerPolicy="no-referrer",x.onload=()=>{n.bindTexture(3553,D),n.texImage2D(3553,0,6408,6408,5121,x),n.generateMipmap(3553),r?.()},x.src=C}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",S.uri)}h.push(D)}else h.push(null)}}let p=[1/0,1/0,1/0],b=[-1/0,-1/0,-1/0],f=0,y=0;for(let E=0;E<c.length;E++){let g=c[E],S=i.meshes[g.meshIdx],D=g.nodeIdx>=0?l[g.nodeIdx]:W(),C=new Float32Array(9);ne(C,D);let x={name:g.node.name||S.name||`Mesh_${g.meshIdx}`,nodeIndex:g.nodeIdx,transform:D,normalMatrix:C,primitives:[],extras:g.node.extras||S.extras};for(let M of S.primitives||[]){if(M.extensions?.KHR_draco_mesh_compression){let I=me("draco");I&&I.decodePrimitive(i,M,s)}let k=[],A=n.createVertexArray();n.bindVertexArray(A);let z=i.accessors[M.attributes.POSITION],G=Number(z?.count??0);if(!Number.isFinite(G)||G<0||f+G>e.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${e.maxVertices}).`);if(f+=G,z?.min&&z?.max)for(let I=0;I<3;I++){let q=D[12+I],ae=D[12+I];for(let ee=0;ee<3;ee++){let fe=D[ee*4+I]*z.min[ee],be=D[ee*4+I]*z.max[ee];q+=fe<be?fe:be,ae+=fe>be?fe:be}q<p[I]&&(p[I]=q),ae>b[I]&&(b[I]=ae)}let re=Me(n,i,s,M.attributes.POSITION,0,3,k);Me(n,i,s,M.attributes.NORMAL,1,3,k),Me(n,i,s,M.attributes.TEXCOORD_0,2,2,k);let N=0,j=5123,B=null;if(M.indices!==void 0){let I=i.accessors[M.indices],ae=(i.bufferViews[I.bufferView].byteOffset||0)+(I.byteOffset||0);if(N=Number(I.count??0),!Number.isFinite(N)||N<0||y+N>e.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${e.maxIndices}).`);y+=N,j=I.componentType===5125?5125||5125:5123||5123;let ee=n.createBuffer();k.push(ee),n.bindBuffer(34963,ee),I.componentType===5125?(B=new Uint32Array(s,ae,I.count),n.bufferData(34963,B,35044)):(B=new Uint16Array(s,ae,I.count),n.bufferData(34963,B,35044))}else N=z.count;let F={};for(let I of H)if(I.onBuildPrimitiveVAO){let q=I.onBuildPrimitiveVAO(n,A,M,i,s);q&&(F[I.name]=q)}n.bindVertexArray(null);let U=i.materials&&M.material!==void 0?i.materials[M.material]:null,Y=Ue(),K=Ne,Z=Y.fs,Q=!1;for(let I of H)if(I.onResolveShader){let q=I.onResolveShader(M,U,K,Z);q&&(K=q.vs,Z=q.fs,Q=!0)}let se=Q?we(n,K,Z):null,pe=se?Re(n,se,Y.uniforms):null,O=U?.pbrMetallicRoughness,ue=O?.baseColorFactor||[.8,.8,.8,1],ce=O?.metallicFactor??.1,le=O?.roughnessFactor??.5,J=U?.extensions?.KHR_materials_clearcoat,te=J?J.clearcoatFactor??1:0,ie=Math.max(.04,J?.clearcoatRoughnessFactor??.04),he=O?.baseColorTexture!==void 0&&h[O.baseColorTexture.index]?h[O.baseColorTexture.index]:null,Ve=O?.metallicRoughnessTexture!==void 0&&h[O.metallicRoughnessTexture.index]?h[O.metallicRoughnessTexture.index]:null,We=U?.normalTexture!==void 0&&h[U.normalTexture.index]?h[U.normalTexture.index]:null,Xe=U?.normalTexture?.scale??1,ze=U?.occlusionTexture!==void 0&&h[U.occlusionTexture.index]?h[U.occlusionTexture.index]:null,je=U?.occlusionTexture?.strength??1,Ye=!!(U?.extensions?.KHR_materials_transmission||F.materials?.isTransmissive);x.primitives.push({vao:A,indexCount:N,indexType:j,baseColor:ue,metallic:ce,roughness:le,clearcoat:te,clearcoatRoughness:ie,positions:re,indices:B,texture:he,metallicRoughnessTexture:Ve,normalTexture:We,occlusionTexture:ze,normalScale:Xe,occlusionStrength:je,buffers:k,materialIndex:M.material,pluginData:F,customProgram:se,customUniforms:pe,isTransmissive:Ye})}o.push(x)}isFinite(p[0])||(p=[-1,-1,-1]),isFinite(b[0])||(b=[1,1,1]);let T=[(p[0]+b[0])/2,(p[1]+b[1])/2,(p[2]+b[2])/2],w=b[0]-p[0],P=b[1]-p[1],R=b[2]-p[2],v=Math.max(Math.hypot(w,P,R)/2,.5),d=[p[0],p[1],p[2]],m=[b[0],b[1],b[2]],L=t.animations;if(!L){for(let E of H)if(E.onParseGLB?.(t),t.animations){L=t.animations;break}}return L||(L=[]),{meshes:o,bounds:{center:T,radius:v,min:d,max:m},lights:a,animations:L,worldMatrices:l}}var X=class{constructor(t,e,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=W();this.clearColor=[0,0,0,0];this.envIntensity=1;this.shadowIntensity=0;this.shadowSoftness=.5;this.toneMapping="neutral";this.environmentTexture=null;this.animations=[];this.currentClip=null;this.animationTime=0;this.isPlayingAnimation=!1;this.autoplay=!1;this.animationName="";this.gltf=null;this.worldMatrices=[];this.initialNodeTransforms=[];this.projMatrix=W();this.viewMatrix=W();this.modelMatrix=W();this.mvpMatrix=W();this.normalMatrix=new Float32Array(9);this.initialTheta=.6;this.initialPhi=.35;this.initialDistance=null;this.customDistance=!1;this.distanceMode="auto";this.initialCustomTarget=null;this.customTarget=null;this.fov=Math.PI/4;this.minTheta=-1/0;this.maxTheta=1/0;this.minPhi=-Math.PI*.48;this.maxPhi=Math.PI*.48;this.minDistanceLimit=null;this.maxDistanceLimit=null;this.activePointers=new Map;this.isPanning=!1;this.targetTheta=.6;this.currTheta=.6;this.targetPhi=.35;this.currPhi=.35;this.targetDistance=3;this.currDistance=3;this.autoRotate=!1;this.autoRotateSpeed=Math.PI/6;this.autoRotateDelay=3e3;this.lastInteractionTime=-1/0;this.turntableRotation=0;this.isPointerDown=!1;this.interactive=!0;this.skyboxTexture=null;this.lastPointerX=0;this.lastPointerY=0;this.totalDragDist=0;this.selectedMeshName="";this.pickFbo=null;this.pickTexture=null;this.pickDepth=null;this.pickFboWidth=0;this.pickFboHeight=0;this.animFrameId=null;this.isVisible=!0;this.xrSessionActive=!1;this.lastTime=0;this.lastReportedTheta=-999;this.lastReportedPhi=-999;this.lastReportedZoom=-999;this.boundPointerDown=null;this.boundPointerMove=null;this.boundPointerUp=null;this.boundWheel=null;this.boundKeyDown=null;this.boundContextMenu=null;this.boundSetCamera=null;this.boundResetCamera=null;this.stereoSBS=!1;this.renderErrorReported=!1;this.xrDepthState={enabled:!1,texture:null,uvTransform:W(),rawValueToMeters:.001,format:0};this.container=t;let i,s;if(e&&typeof e.getContext=="function"?(i=e,s=r):(s=e,i=s?.canvas),!i){let c=t.querySelector("canvas");c||(c=document.createElement("canvas"),c.style.width="100%",c.style.height="100%",c.style.display="block",c.style.touchAction="none",t.prepend(c)),i=c}this.canvas=i,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let o=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!o:o&&(this.autoRotate=!1),this.opts.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=this.opts.autoRotateSpeed),this.opts.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(this.opts.autoRotateDelay)||0)),this.opts.exposure!==void 0&&(this.envIntensity=Math.max(0,Number(this.opts.exposure))),this.opts.camera&&this.setInitialCamera(this.opts.camera.theta,this.opts.camera.phi,this.opts.camera.distance,this.opts.camera.zoom),this.opts.shadowIntensity!==void 0&&(this.shadowIntensity=Math.max(0,Math.min(1,Number(this.opts.shadowIntensity)||0))),this.opts.shadowSoftness!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(this.opts.shadowSoftness)||0))),this.opts.toneMapping!==void 0&&(this.toneMapping=this.opts.toneMapping),this.opts.autoplay!==void 0&&(this.autoplay=this.opts.autoplay),this.opts.animationName!==void 0&&(this.animationName=this.opts.animationName),this.opts.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 l=i.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!l)throw new Error("WebGL2 not supported");this.gl=l;let u=Ue();this.renderProg=we(l,Ne,u.fs),this.pickProg=we(l,nt,st),this.uRender=Re(l,this.renderProg,u.uniforms),this.uPick=Re(l,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo(),this.setupEvents(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(t,e){tt(t,e)}static getDecoder(t){return me(t)}setupPickingFbo(){let t=this.gl;if(typeof t.createFramebuffer!="function")return;this.pickFbo=t.createFramebuffer(),this.pickTexture=t.createTexture(),this.pickDepth=t.createRenderbuffer();let e=Math.max(1,this.canvas.width),r=Math.max(1,this.canvas.height);this.pickFboWidth=e,this.pickFboHeight=r,t.bindTexture(3553,this.pickTexture),t.texImage2D(3553,0,6408,e,r,0,6408,5121,null),t.texParameteri(3553,10241,9728),t.texParameteri(3553,10240,9728),t.bindRenderbuffer(36161,this.pickDepth),t.renderbufferStorage(36161,33189,e,r),t.bindFramebuffer(36160,this.pickFbo),t.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),t.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),t.bindFramebuffer(36160,null)}resizePickingFbo(t,e){if(!this.pickFbo)return;let r=this.gl,i=Math.max(1,t),s=Math.max(1,e);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(t,e){let{meshes:r,bounds:i,lights:s,animations:o,worldMatrices:l}=Ie(this.gl,t,e,()=>this.render());if(this.disposeMeshGpuResources(),this.meshes=r,this.bounds=i,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=s,this.animations=o||[],this.worldMatrices=l||[],this.gltf=t.gltf,this.initialNodeTransforms=[],Array.isArray(t.gltf?.nodes))for(let c of t.gltf.nodes)this.initialNodeTransforms.push({t:c.translation?[c.translation[0],c.translation[1],c.translation[2]]:[0,0,0],r:c.rotation?[c.rotation[0],c.rotation[1],c.rotation[2],c.rotation[3]]:[0,0,0,1],s:c.scale?[c.scale[0],c.scale[1],c.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let c of H)c.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 u=t.exposure??t.environmentIntensity??t.gltf?.extras?.exposure??t.gltf?.extras?.environmentIntensity??t.gltf?.asset?.extras?.exposure??t.gltf?.asset?.extras?.environmentIntensity;u!==void 0&&(this.envIntensity=Math.max(0,Number(u))),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(t){this.loadGLBData(ke(t))}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(t){this.loadGLBData(oe(t))}setBackdropGLB(t,e){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!t){this.update(0),this.render();return}let r=oe(t),{meshes:i}=Ie(this.gl,r,Oe,()=>this.render());if(e)for(let s of i)s.transform[12]+=e[0],s.transform[13]+=e[1],s.transform[14]+=e[2],ne(s.normalMatrix,s.transform);this.backdropMeshes=i,this.update(0),this.render()}setClearColor(t,e,r,i=1){this.clearColor=[t,e,r,i]}updateMeshTransforms(t){for(let e=0;e<this.meshes.length;e++){let r=this.meshes[e],i;t instanceof Map?i=t.get(r.name)??t.get(e):Array.isArray(t)?i=t[e]:t&&typeof t=="object"&&(Object.prototype.hasOwnProperty.call(t,r.name)?i=t[r.name]:Object.prototype.hasOwnProperty.call(t,e)&&(i=t[e])),i&&i.length===16&&(r.transform.set(i),ne(r.normalMatrix,r.transform))}}bindLights(t=this.uRender){let e=this.gl,r=[.28,.28,.28],i=[],s=[],o=[],l=[];for(let u of this.lights){let c=u.color||[1,1,1],a=u.intensity!==void 0?u.intensity:1;if(u.type==="ambient")r=[c[0]*a,c[1]*a,c[2]*a];else if(u.type==="directional"&&i.length<6){let h=u.direction||[.5,1,.8];i.push(h[0],h[1],h[2]),s.push(c[0]*a,c[1]*a,c[2]*a)}else if(u.type==="point"&&o.length<6){let h=u.position||[0,0,0];o.push(h[0],h[1],h[2]),l.push(c[0]*a,c[1]*a,c[2]*a)}}i.length===0&&(i.push(.5,1,.8),s.push(1,1,1)),e.uniform3fv(t.uAmbientColor,r),e.uniform1i(t.uNumDirLights,i.length/3),i.length>0&&(e.uniform3fv(t.uDirLightDir,i),e.uniform3fv(t.uDirLightColor,s)),e.uniform1i(t.uNumPointLights,o.length/3),o.length>0&&(e.uniform3fv(t.uPointLightPos,o),e.uniform3fv(t.uPointLightColor,l)),e.uniform1f(t.uEnvIntensity,this.envIntensity)}setExposure(t){this.envIntensity=Math.max(0,Number(t))}getExposure(){return this.envIntensity}setShadow(t,e){this.shadowIntensity=Math.max(0,Math.min(1,Number(t)||0)),e!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(e)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(t){this.toneMapping=t}getToneMapping(){return this.toneMapping}async setEnvironmentImage(t){for(let e of H)if(e.setEnvironmentImage){await e.setEnvironmentImage(this,t);return}}async setSkyboxImage(t){for(let e of H)if(e.setSkyboxImage){await e.setSkyboxImage(this,t);return}}setInteractive(t){this.interactive=t}isInteractive(){return this.interactive}getCameraOrbit(){let t=this.currTheta,e=this.currPhi,r=this.currDistance;return{theta:t,phi:e,radius:r,toString(){return`${t.toFixed(4)}rad ${e.toFixed(4)}rad ${r.toFixed(4)}m`}}}getCameraTarget(){let t=this.customTarget||this.bounds.center;return{x:t[0],y:t[1],z:t[2],toString(){return`${t[0].toFixed(4)}m ${t[1].toFixed(4)}m ${t[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let t=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return t.map((e,r)=>{let i=this.meshes.flatMap(a=>a.primitives.filter(h=>h.materialIndex===r||t.length===1&&h.materialIndex===void 0)),s=i[0],o=s?[...s.baseColor]:e.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],l=s?s.metallic:e.pbrMetallicRoughness?.metallicFactor??.1,u=s?s.roughness:e.pbrMetallicRoughness?.roughnessFactor??.5,c={baseColorFactor:o,metallicFactor:l,roughnessFactor:u,setBaseColorFactor:a=>{let h=[a[0],a[1],a[2],a[3]??1];c.baseColorFactor=h,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.baseColorFactor=h);for(let p of i)p.baseColor=h;this.render()},setMetallicFactor:a=>{c.metallicFactor=a,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.metallicFactor=a);for(let h of i)h.metallic=a;this.render()},setRoughnessFactor:a=>{c.roughnessFactor=a,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.roughnessFactor=a);for(let h of i)h.roughness=a;this.render()}};return{name:e.name||`Material_${r}`,pbrMetallicRoughness:c}})}playAnimation(t){if(this.animations.length!==0){if(t){let e=this.animations.find(r=>r.name===t);e&&(this.currentClip=e)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(t=>t.name)}setAutoplay(t){this.autoplay=t,t?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(t){this.animationName=t,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(t)}evaluateAnimation(t){for(let e of H)if(e.evaluateAnimation){e.evaluateAnimation(this,t);return}}setTarget(t,e,r){this.customTarget=[t,e,r],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(t){let e=Math.max(10,Math.min(90,t));this.fov=e*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(t){if(this.distanceMode=t,!this.customDistance){let e=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=e,this.targetDistance=e,this.currDistance=e,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(t){t.minTheta!==void 0&&(this.minTheta=t.minTheta*Math.PI/180),t.maxTheta!==void 0&&(this.maxTheta=t.maxTheta*Math.PI/180),t.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,t.minPhi*Math.PI/180)),t.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,t.maxPhi*Math.PI/180)),t.minDistance!==void 0&&(this.minDistanceLimit=t.minDistance),t.maxDistance!==void 0&&(this.maxDistanceLimit=t.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){return{minTheta:isFinite(this.minTheta)?this.minTheta*180/Math.PI:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*180/Math.PI:void 0,minPhi:this.minPhi*180/Math.PI,maxPhi:this.maxPhi*180/Math.PI,minDistance:this.minDistanceLimit!==null?this.minDistanceLimit:void 0,maxDistance:this.maxDistanceLimit!==null?this.maxDistanceLimit:void 0}}clampTheta(t){return Math.max(this.minTheta,Math.min(this.maxTheta,t))}clampPhi(t){return Math.max(this.minPhi,Math.min(this.maxPhi,t))}clampDistance(t){let e=this.minDistanceLimit!==null?this.minDistanceLimit:this.bounds?this.bounds.radius*.5:.1,r=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(e,Math.min(r,t))}setCamera(t,e,r,i){t!==void 0&&(this.targetTheta=this.clampTheta(t*Math.PI/180)),e!==void 0&&(this.targetPhi=this.clampPhi(e*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(t,e,r,i){if(t!==void 0&&(this.initialTheta=this.clampTheta(t*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),e!==void 0&&(this.initialPhi=this.clampPhi(e*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),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(t,e){let r=W();$(r,this.projMatrix,this.viewMatrix);let[i,s,o]=t,l=e?e[0]:0,u=e?e[1]:0,c=e?e[2]:0,a=this.modelRootMatrix;a&&(i=a[0]*t[0]+a[4]*t[1]+a[8]*t[2]+a[12],s=a[1]*t[0]+a[5]*t[1]+a[9]*t[2]+a[13],o=a[2]*t[0]+a[6]*t[1]+a[10]*t[2]+a[14],e&&(l=a[0]*e[0]+a[4]*e[1]+a[8]*e[2],u=a[1]*e[0]+a[5]*e[1]+a[9]*e[2],c=a[2]*e[0]+a[6]*e[1]+a[10]*e[2]));let h=r[0]*i+r[4]*s+r[8]*o+r[12],p=r[1]*i+r[5]*s+r[9]*o+r[13],b=r[2]*i+r[6]*s+r[10]*o+r[14],f=r[3]*i+r[7]*s+r[11]*o+r[15];if(f<=1e-4)return{x:0,y:0,z:1,visible:!1};let y=h/f,T=p/f,w=b/f,P=this.canvas.getBoundingClientRect(),R=P.width||this.canvas.clientWidth||this.canvas.width||300,v=P.height||this.canvas.clientHeight||this.canvas.height||150,d=(y*.5+.5)*R,m=(-T*.5+.5)*v,L=y>=-1.1&&y<=1.1&&T>=-1.1&&T<=1.1&&w>=-1&&w<=1;if(L&&e){let E=this.customTarget||this.bounds.center,g=E[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),S=E[1]+this.currDistance*Math.sin(this.currPhi),D=E[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),C=[i-g,s-S,o-D];l*C[0]+u*C[1]+c*C[2]>.05&&(L=!1)}return{x:d,y:m,z:w,visible:L}}setSelectedMesh(t){this.selectedMeshName=t||""}setupEvents(){let t=this.canvas;this.boundContextMenu=e=>{e.preventDefault()},t.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=e=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.lastPointerX=e.clientX,this.lastPointerY=e.clientY,this.totalDragDist=0,this.activePointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.isPanning=e.button===2||e.shiftKey||this.activePointers.size===2,t.setPointerCapture(e.pointerId))},t.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=e=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=this.activePointers.get(e.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},i=e.clientX-r.x,s=e.clientY-r.y;if(this.activePointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.lastPointerX=e.clientX,this.lastPointerY=e.clientY,this.totalDragDist+=Math.hypot(i,s),this.isPanning||e.button===2||e.shiftKey||this.activePointers.size===2){let o=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],l=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],u=this.customTarget?[...this.customTarget]:[...this.bounds.center],c=this.currDistance/Math.max(t.clientHeight||300,1)*1.5;u[0]+=(-i*o[0]+s*l[0])*c,u[1]+=(-i*o[1]+s*l[1])*c,u[2]+=(-i*o[2]+s*l[2])*c,this.customTarget=u}else this.targetTheta=this.clampTheta(this.targetTheta-i*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},t.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=e=>{this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.activePointers.delete(e.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{t.releasePointerCapture(e.pointerId)}catch{}if(this.totalDragDist<5&&e.button===0){let r=t.getBoundingClientRect(),i=Math.floor((e.clientX-r.left)*(t.width/Math.max(r.width,1))),s=Math.floor((e.clientY-r.top)*(t.height/Math.max(r.height,1)));this.performMeshPick(i,s,!0)}},t.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=e=>{if(!this.interactive)return;e.preventDefault(),this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=Math.exp(e.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},t.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=e=>{let r=e.detail||{};r.reset?this.resetCamera():this.setCamera(r.theta,r.phi,r.distance,r.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),t.tabIndex!==void 0&&t.tabIndex<0&&(t.tabIndex=0),t.getAttribute?.("role")||t.setAttribute?.("role","region"),t.getAttribute?.("aria-label")||t.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=e=>{if(!this.interactive)return;let r=typeof performance<"u"?performance.now():Date.now();switch(e.key){case"ArrowLeft":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta-.1),e.preventDefault();break;case"ArrowRight":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta+.1),e.preventDefault();break;case"ArrowUp":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi+.08),e.preventDefault();break;case"ArrowDown":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi-.08),e.preventDefault();break;case"+":case"=":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*.9),e.preventDefault();break}case"-":case"_":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*1.1),e.preventDefault();break}case"Home":this.lastInteractionTime=r,this.resetCamera(),e.preventDefault();break}},t.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let t=this.canvas;this.boundContextMenu&&(t.removeEventListener("contextmenu",this.boundContextMenu),this.boundContextMenu=null),this.boundPointerDown&&(t.removeEventListener("pointerdown",this.boundPointerDown),this.boundPointerDown=null),this.boundPointerMove&&(t.removeEventListener("pointermove",this.boundPointerMove),this.boundPointerMove=null),this.boundPointerUp&&(t.removeEventListener("pointerup",this.boundPointerUp),this.boundPointerUp=null),this.boundWheel&&(t.removeEventListener("wheel",this.boundWheel),this.boundWheel=null),this.boundKeyDown&&(t.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(t,e){let r=this.canvas,i=r.getBoundingClientRect(),s=r.width||300,o=r.height||300,l=i.width>0?Math.floor((t-i.left)*(s/i.width)):Math.floor(t),u=i.height>0?Math.floor((e-i.top)*(o/i.height)):Math.floor(e);return this.performMeshPick(l,u,!1)}performMeshPick(t,e,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);t=this.mapStereoPickX(t,s);let l=W();$(l,this.projMatrix,this.viewMatrix);let u=[],c=Math.max(0,Math.min(s-1,t)),a=Math.max(0,Math.min(o-1,o-1-e));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 L=0;L<this.meshes.length;L++){let E=this.meshes[L];if(E.visible===!1||E.isPluginMesh)continue;let g=L+1,S=(g&255)/255,D=(g>>8&255)/255,C=(g>>16&255)/255;i.uniform4f(this.uPick.uColorId,S,D,C,1),$(this.modelMatrix,this.modelRootMatrix,E.transform),$(this.mvpMatrix,l,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let x of E.primitives)i.bindVertexArray(x.vao),i.drawElements(4,x.indexCount,x.indexType,0)}let d=new Uint8Array(4);i.readPixels(c,a,1,1,6408,5121,d),i.bindFramebuffer(36160,null);let m=d[0]+(d[1]<<8)+(d[2]<<16);m>0&&m<=this.meshes.length&&(u=[this.meshes[m-1]])}u.length===0&&(u=this.meshes.filter(d=>d.visible!==!1));let h=null,p=1/0,b=[0,0,0],f=[0,1,0],y=this.customTarget||this.bounds.center,T=y[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),w=y[1]+this.currDistance*Math.sin(this.currPhi),P=y[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let d of u){$(this.modelMatrix,this.modelRootMatrix,d.transform),$(this.mvpMatrix,l,this.modelMatrix);let m=W();if(!Se(m,this.mvpMatrix))continue;let L=(c+.5)/s*2-1,E=(a+.5)/o*2-1,g=[0,0,0],S=[0,0,0];Te(g,L,E,-1,m),Te(S,L,E,1,m);let D=S[0]-g[0],C=S[1]-g[1],x=S[2]-g[2],M=Math.hypot(D,C,x)||1,k=D/M,A=C/M,z=x/M,G={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((N=>{for(let j of d.primitives){if(!j.positions)continue;let B=j.positions,F=j.indices,U=Math.floor(F?F.length/3:B.length/9);for(let Y=0;Y<U;Y++){let K=F?F[Y*3]:Y*3,Z=F?F[Y*3+1]:Y*3+1,Q=F?F[Y*3+2]:Y*3+2;De(g[0],g[1],g[2],k,A,z,B[K*3],B[K*3+1],B[K*3+2],B[Z*3],B[Z*3+1],B[Z*3+2],B[Q*3],B[Q*3+1],B[Q*3+2],G,N)}}})(1e-4),isFinite(G.distance)){let N=G.point[0],j=G.point[1],B=G.point[2],F=this.modelMatrix,U=F[0]*N+F[4]*j+F[8]*B+F[12],Y=F[1]*N+F[5]*j+F[9]*B+F[13],K=F[2]*N+F[6]*j+F[10]*B+F[14],Z=U-T,Q=Y-w,se=K-P,pe=Math.hypot(Z,Q,se);if(pe<p){ne(this.normalMatrix,this.modelMatrix);let O=this.normalMatrix,ue=G.normal[0],ce=G.normal[1],le=G.normal[2],J=O[0]*ue+O[3]*ce+O[6]*le,te=O[1]*ue+O[4]*ce+O[7]*le,ie=O[2]*ue+O[5]*ce+O[8]*le,he=Math.hypot(J,te,ie)||1;J/=he,te/=he,ie/=he,J*Z+te*Q+ie*se>0&&(J=-J,te=-te,ie=-ie),h=d,p=Math.round(pe*1e3)/1e3,b=[Math.round(U*1e3)/1e3,Math.round(Y*1e3)/1e3,Math.round(K*1e3)/1e3],f=[Math.round(J*1e3)/1e3,Math.round(te*1e3)/1e3,Math.round(ie*1e3)/1e3]}}}if(!h)return null;let v={meshIndex:this.meshes.indexOf(h),meshName:h.name,nodeIndex:h.nodeIndex,distance:p,hitPoint:b,normal:f,screenX:t,screenY:e};if(r){for(let d of H)d.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(t,e){if(!this.stereoSBS||this.xrSessionActive||e<2)return t;let r=Math.max(1,Math.floor(e*.5)),i=t>=r,s=i?t-r:t,o=i?Math.max(1,e-r):r,l=(s+.5)/o*2-1;return Math.floor((l*.5+1)*.5*e)}setStereoSBS(t){this.stereoSBS=!!t,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let t=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),e=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);ge(this.projMatrix,this.fov,t,.1,e);let r=this.customTarget||this.bounds.center,i=r[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),s=r[1]+this.currDistance*Math.sin(this.currPhi),o=r[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);xe(this.viewMatrix,[i,s,o],r,[0,1,0]),$(this.mvpMatrix,this.projMatrix,this.viewMatrix),ne(this.normalMatrix,this.modelMatrix)}resize(){let t=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),e=this.canvas.getBoundingClientRect(),r=Math.max(1,Math.floor(e.width*t)),i=Math.max(1,Math.floor(e.height*t));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(t){let e=this.xrSessionActive;if(this.xrSessionActive=t,e&&!t){this.xrDepthState.enabled=!1;for(let r of H)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(t){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",t))}stepXRUpdate(t){for(let e of H)e.onUpdate?.(this,t)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let t=e=>{if(this.animFrameId===null)return;let r=Math.min(Math.max((e-this.lastTime)/1e3,0),.1);if(this.lastTime=e,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(r),this.render()}catch(i){this.reportRenderError(i)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(t))};this.animFrameId=requestAnimationFrame(t)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(t){this.autoRotate=t}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(t){this.autoRotateSpeed=t}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(t){this.autoRotateDelay=Math.max(0,Number(t)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(t=0){this.turntableRotation=Number(t)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let t=Math.cos(this.turntableRotation),e=Math.sin(this.turntableRotation),r=this.bounds.center[0],i=this.bounds.center[2],s=this.modelRootMatrix;s[0]=t,s[1]=0,s[2]=-e,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=e,s[9]=0,s[10]=t,s[11]=0,s[12]=r-(t*r+e*i),s[13]=0,s[14]=i-(-e*r+t*i),s[15]=1}setVisible(t){this.isVisible=t}update(t){for(let o of H)o.onUpdate?.(this,t);let e=typeof performance<"u"?performance.now():Date.now();if(!this.isPointerDown&&this.autoRotate&&e-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*t,this.updateTurntableMatrix();for(let o of H)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(t,e,r,i,s=!0,o=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(t);let l=t?.transform?.inverse?.matrix||this.viewMatrix,u=t?.projectionMatrix||this.projMatrix,c=t?.transform?.position,a=c?[c.x,c.y,c.z]:[0,1.6,0];e?this.modelRootMatrix.set(e):r&&e&&this.modelRootMatrix.set(e),this.render({viewMatrix:l,projMatrix:u,eyePos:a,viewport:i,eye:t?.eye||"none",clear:o>0?!1:t?.eye!=="right",isAR:s})}render(t){if(!t&&this.stereoSBS){let v=Math.max(2,this.canvas.width||2),d=Math.max(1,this.canvas.height||1),m=Math.max(1,Math.floor(v*.5)),L=Math.max(1,v-m),E=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),g=this.customTarget||this.bounds.center,S=g[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),D=g[1]+this.currDistance*Math.sin(this.currPhi),C=g[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),x=Math.cos(this.currTheta),M=-Math.sin(this.currTheta),k=.032,A=W(),z=W(),G=[S-x*k,D,C-M*k],re=[g[0]-x*k*.25,g[1],g[2]-M*k*.25];ge(A,this.fov,m/d,.1,E),xe(z,G,re,[0,1,0]);let N=W(),j=W(),B=[S+x*k,D,C+M*k],F=[g[0]+x*k*.25,g[1],g[2]+M*k*.25];ge(N,this.fov,L/d,.1,E),xe(j,B,F,[0,1,0]),this.render({viewMatrix:z,projMatrix:A,eyePos:G,viewport:[0,0,m,d],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:j,projMatrix:N,eyePos:B,viewport:[m,0,L,d],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,v,d);return}let e=this.gl,r=0,i=0,s=this.canvas.width,o=this.canvas.height;t?.viewport?(r=t.viewport[0],i=t.viewport[1],s=t.viewport[2],o=t.viewport[3],e.viewport(r,i,s,o)):e.viewport(0,0,this.canvas.width,this.canvas.height),e.enable(2929),(!t||t.clear!==!1)&&(t?.isAR?e.clearColor(0,0,0,0):e.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),e.clear(16384|256));let l=W(),u=t?.viewMatrix??this.viewMatrix;$(l,t?.projMatrix??this.projMatrix,u);let c=_().xrDepthShader,a=this.toneMapping==="reinhard"?1:this.toneMapping==="none"?2:0,h=this.customTarget||this.bounds.center,p=t?t.eyePos[0]:h[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),b=t?t.eyePos[1]:h[1]+this.currDistance*Math.sin(this.currPhi),f=t?t.eyePos[2]:h[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let v of H)v.onBeforeDrawScene?.(this,e,l,[p,b,f],a);let y=t?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&y===0)return;let T=t?.eye||"none",w=!1,P=y>0?[...this.backdropMeshes,...this.meshes]:this.meshes,R=v=>{for(let d=0;d<P.length;d++){let m=P[d];if(m.visible===!1)continue;let L=this.selectedMeshName!==""&&m.name===this.selectedMeshName;d<y||m.worldSpace===!0||m.name==="__xr_reticle__"?this.modelMatrix.set(m.transform):$(this.modelMatrix,this.modelRootMatrix,m.transform),$(this.mvpMatrix,l,this.modelMatrix),ne(m.normalMatrix,this.modelMatrix);let E=m.extras?.xr?.stereo||m.userData?.xr?.stereo,g=0,S=0,D=1,C=1;E==="sbs"?(D=.5,g=T==="right"?.5:0):E==="ou"&&(C=.5,S=T==="right"?.5:0);for(let x of m.primitives){let M=!!x.isTransmissive;if(!v&&M){w=!0;continue}if(v&&!M)continue;let k=x.customProgram||this.renderProg,A=x.customUniforms||this.uRender;e.useProgram(k),e.uniform1i(A.uToneMapping,a),e.uniform1f(A.uEnvIntensity,this.envIntensity),e.uniform3f(A.uCameraPos,p,b,f),e.uniform1f(A.uEmissive,L?1:0),e.uniformMatrix4fv(A.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(A.uModel,!1,this.modelMatrix),e.uniformMatrix3fv(A.uNormalMatrix,!1,m.normalMatrix),A.uUvTransform&&e.uniform4f(A.uUvTransform,g,S,D,C),A.uViewportSize&&e.uniform2f(A.uViewportSize,Math.max(1,s),Math.max(1,o)),c?.bind(e,A,this.xrDepthState,u,[r,i,Math.max(1,s),Math.max(1,o)]),this.environmentTexture?(e.activeTexture(33988),e.bindTexture(3553,this.environmentTexture),e.uniform1i(A.uEnvironmentMap,4),e.uniform1i(A.uHasEnvironmentMap,1)):e.uniform1i(A.uHasEnvironmentMap,0),this.bindLights(A),A.uSectionEnabled&&e.uniform1i(A.uSectionEnabled,0);for(let z of H)z.onBeforeDrawPrimitive?.(e,k,x,m,this.worldMatrices||[],this.gltf);e.uniform4fv(A.uBaseColor,x.baseColor),e.uniform1f(A.uMetallic,x.metallic),e.uniform1f(A.uRoughness,x.roughness),A.uClearcoat&&e.uniform2f(A.uClearcoat,x.clearcoat??0,x.clearcoatRoughness??.04),x.texture?(e.activeTexture(33984),e.bindTexture(3553,x.texture),e.uniform1i(A.uBaseColorTexture,0),e.uniform1i(A.uHasTexture,1)):e.uniform1i(A.uHasTexture,0),x.metallicRoughnessTexture?(e.activeTexture(33985),e.bindTexture(3553,x.metallicRoughnessTexture),e.uniform1i(A.uMetallicRoughnessTexture,1),e.uniform1i(A.uHasMetallicRoughnessTexture,1)):e.uniform1i(A.uHasMetallicRoughnessTexture,0),x.normalTexture?(e.activeTexture(33986),e.bindTexture(3553,x.normalTexture),e.uniform1i(A.uNormalTexture,2),e.uniform1i(A.uHasNormalTexture,1),e.uniform1f(A.uNormalScale,x.normalScale)):e.uniform1i(A.uHasNormalTexture,0),x.occlusionTexture?(e.activeTexture(33987),e.bindTexture(3553,x.occlusionTexture),e.uniform1i(A.uOcclusionTexture,3),e.uniform1i(A.uHasOcclusionTexture,1),e.uniform1f(A.uOcclusionStrength,x.occlusionStrength)):e.uniform1i(A.uHasOcclusionTexture,0),e.bindVertexArray(x.vao),e.drawElements(4,x.indexCount,x.indexType,0)}}};if(R(!1),w){for(let v of H)v.onBeforeTransmissivePass?.(e,this);R(!0)}for(let v of H)v.onAfterRender?.(e,this,l)}disposeMeshListGpuResources(t){let e=this.gl;for(let r of t)for(let i of r.primitives){if(i.vao&&e.deleteVertexArray(i.vao),i.buffers)for(let s of i.buffers)e.deleteBuffer(s);i.texture&&e.deleteTexture(i.texture),i.metallicRoughnessTexture&&e.deleteTexture(i.metallicRoughnessTexture),i.normalTexture&&e.deleteTexture(i.normalTexture),i.occlusionTexture&&e.deleteTexture(i.occlusionTexture),i.customProgram&&e.deleteProgram(i.customProgram)}}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes),this.meshes=[]}disposeGpuResources(){let t=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let e of H)e.onDestroy?.(t,this);this.environmentTexture&&(t.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&t.deleteProgram(this.renderProg),this.pickProg&&t.deleteProgram(this.pickProg),this.pickFbo&&t.deleteFramebuffer(this.pickFbo),this.pickTexture&&t.deleteTexture(this.pickTexture),this.pickDepth&&t.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};X.registerPlugin=Ae,X.getRegisteredPlugins=Ee;var _e='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).',He="Security Error: client-side scripts require allow-client-scripts opt-in.";var ot=typeof HTMLElement<"u"?HTMLElement:class{};typeof CustomEvent>"u"&&typeof Event<"u"&&(globalThis.CustomEvent=class extends Event{constructor(n,t){super(n,t),this.detail=t?.detail??null}});var V=class V extends ot{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 _().arProvider}static set arProvider(e){_().arProvider=e}static get scriptRunner(){return _().scriptRunner}static set scriptRunner(e){_().scriptRunner=e}static get sandboxEngineSrc(){return _().sandboxEngineSrc??null}static set sandboxEngineSrc(e){_().sandboxEngineSrc=e}static get sandboxIframeSrc(){return _().sandboxIframeSrc??null}static set sandboxIframeSrc(e){_().sandboxIframeSrc=e}static get allowClientScripts(){return!!_().allowClientScripts}static set allowClientScripts(e){_().allowClientScripts=e}static registerScriptRunner(e){V.scriptRunner=e}static registerDecoder(e,r){X.registerDecoder(e,r)}static getDecoder(e){return X.getDecoder(e)}static registerAR(e){typeof e=="function"?V.arProvider={activateAR:e}:V.arProvider=e,typeof document<"u"&&document.querySelectorAll("three-live").forEach(i=>{i instanceof V&&i.updateARButtonVisibility()})}static isARSupported(){return!!V.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 e=this.getAttribute("src"),r=this.getAttribute("script-src");if(e)this.loadModelFromSrc(e).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 X.getRegisteredPlugins())i.onElementConnected?.(this)}disconnectedCallback(){for(let e of X.getRegisteredPlugins())e.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(e,r,i){if(r!==i){switch(e){case"src":i&&this.loadModelFromSrc(i).catch(()=>{});break;case"camera-target":this.applyCameraTarget(i);break;case"min-camera-orbit":case"max-camera-orbit":this.applyOrbitLimits();break;case"field-of-view":this.applyFieldOfView(i);break;case"script-src":i&&this.loadScriptFromSrc(i).catch(()=>{});break;case"sandbox":case"allow-client-scripts":case"ios-src":break;case"poster":this.updatePoster(i);break;case"camera-orbit":this.applyCameraOrbit(i);break;case"selected-mesh":this.viewer&&i!==null&&this.viewer.setSelectedMesh(i);break;case"exposure":if(this.viewer&&i!==null){let s=parseFloat(i);isNaN(s)||this.viewer.setExposure(s)}break;case"shadow-intensity":case"shadow-softness":this.viewer&&this.viewer.setShadow(this.shadowIntensity,this.shadowSoftness);break;case"tone-mapping":this.viewer&&i&&this.viewer.setToneMapping(i);break;case"environment-image":this.viewer&&this.viewer.setEnvironmentImage(i).catch(()=>{});break;case"skybox-image":this.viewer&&this.viewer.setSkyboxImage?.(i)?.catch?.(()=>{});break;case"camera-controls":{let s=this.cameraControls;this.viewer&&this.viewer.setInteractive?.(s),this.canvas&&(this.canvas.style.touchAction=s?"none":"auto");break}case"autoplay":this.viewer&&this.viewer.setAutoplay(i!==null&&i!=="false");break;case"animation-name":this.viewer&&i!==null&&this.viewer.setAnimationName(i);break;case"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 X.getRegisteredPlugins())s.onAttributeChanged?.(this,e,r,i)}}getAttr(e){return this.getAttribute(e)}setAttr(e,r){r!==null?this.setAttribute(e,r):this.removeAttribute(e)}getBoolAttr(e){return this.hasAttribute(e)&&this.getAttribute(e)!=="false"}setBoolAttr(e,r){r?this.setAttribute(e,""):this.removeAttribute(e)}getFloatAttr(e,r){let i=this.getAttribute(e);return i!==null?parseFloat(i):r}get src(){return this.getAttr("src")}set src(e){this.setAttr("src",e)}get cameraControls(){return this.getBoolAttr("camera-controls")}set cameraControls(e){this.setBoolAttr("camera-controls",e)}get cameraOrbit(){return this.getAttr("camera-orbit")}set cameraOrbit(e){this.setAttr("camera-orbit",e)}get cameraTarget(){return this.getAttr("camera-target")}set cameraTarget(e){this.setAttr("camera-target",e)}get minCameraOrbit(){return this.getAttr("min-camera-orbit")}set minCameraOrbit(e){this.setAttr("min-camera-orbit",e)}get maxCameraOrbit(){return this.getAttr("max-camera-orbit")}set maxCameraOrbit(e){this.setAttr("max-camera-orbit",e)}get fieldOfView(){return this.getAttr("field-of-view")}set fieldOfView(e){this.setAttr("field-of-view",e)}get iosSrc(){return this.getAttr("ios-src")}set iosSrc(e){this.setAttr("ios-src",e)}get scriptSrc(){return this.getAttr("script-src")}set scriptSrc(e){this.setAttr("script-src",e)}get sandbox(){return this.getAttribute("sandbox")||(_().sandboxIframeSrc?"iframe":"worker")}set sandbox(e){this.setAttribute("sandbox",e)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||V.allowClientScripts}set allowClientScripts(e){this.setBoolAttr("allow-client-scripts",e)}get poster(){return this.getAttr("poster")}set poster(e){this.setAttr("poster",e)}get selectedMesh(){return this.getAttr("selected-mesh")}set selectedMesh(e){this.setAttr("selected-mesh",e)}get exposure(){return this.getFloatAttr("exposure",1)}set exposure(e){this.setAttribute("exposure",String(e))}get autoRotate(){return this.getBoolAttr("auto-rotate")}set autoRotate(e){this.setBoolAttr("auto-rotate",e)}get autoRotateDelay(){return this.getFloatAttr("auto-rotate-delay",3e3)}set autoRotateDelay(e){this.setAttribute("auto-rotate-delay",String(e))}get rotationPerSecond(){return this.getAttr("rotation-per-second")||"30deg"}set rotationPerSecond(e){this.setAttr("rotation-per-second",e)}get turntableRotation(){return this.viewer?this.viewer.turntableRotation:0}get ar(){return this.hasAttribute("ar")}set ar(e){this.setBoolAttr("ar",e)}get arScale(){return this.getAttribute("ar-scale")||"auto"}set arScale(e){this.setAttribute("ar-scale",e)}get arPlacement(){return this.getAttribute("ar-placement")||"floor"}set arPlacement(e){this.setAttribute("ar-placement",e)}get canActivateAR(){return V.isARSupported()}get shadowIntensity(){return this.getFloatAttr("shadow-intensity",0)}set shadowIntensity(e){this.setAttribute("shadow-intensity",String(e))}get shadowSoftness(){return this.getFloatAttr("shadow-softness",.5)}set shadowSoftness(e){this.setAttribute("shadow-softness",String(e))}get toneMapping(){return this.getAttribute("tone-mapping")||"neutral"}set toneMapping(e){this.setAttribute("tone-mapping",e)}get environmentImage(){return this.getAttr("environment-image")}set environmentImage(e){this.setAttr("environment-image",e)}get skyboxImage(){return this.getAttr("skybox-image")}set skyboxImage(e){this.setAttr("skybox-image",e)}get autoplay(){return this.getBoolAttr("autoplay")}set autoplay(e){this.setBoolAttr("autoplay",e)}get animationName(){return this.getAttr("animation-name")}set animationName(e){this.setAttr("animation-name",e)}get availableAnimations(){return this.viewer?this.viewer.getAvailableAnimations():[]}get model(){let e=this.viewer?this.viewer.getModelMaterials():[];return{materials:e,getMaterialByName(r){return e.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(e=0){this.viewer?.resetTurntableRotation(e)}setCamera(e,r,i,s){this.viewer&&this.viewer.setCamera(e,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(e,r){return this.viewer&&this.viewer.render?.(),this.canvas?this.canvas.toDataURL(e,r):""}toBlob(e){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."))},e?.mimeType,e?.qualityArgument)})}positionAndNormalFromPoint(e,r){if(!this.viewer)return null;let i=this.viewer.raycastFromScreenPoint(e,r);if(!i)return null;let[s,o,l]=i.hitPoint||i.point,[u,c,a]=i.normal;return{position:{x:s,y:o,z:l,toString(){return`${s}m ${o}m ${l}m`}},normal:{x:u,y:c,z:a,toString(){return`${u}m ${c}m ${a}m`}}}}async loadModel(e){return this.loadModelWithLimits(e)}async loadModelWithLimits(e,r){if(!this.viewer){this.currentModel=e,this.currentModelLimits=r;return}try{let i;if(typeof e=="string"){this.isModelLoaded=!1,this.viewer?.clearScene?.();let l=await fetch(e);if(!l.ok)throw new Error(`Failed to load 3D model from "${e}": HTTP ${l.status}`);i=await l.arrayBuffer()}else i=e;let s=oe(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),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(e,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=e,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(!V.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 e=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 V.arProvider.activateAR({model:e||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),l=/Android|iPhone|iPad|iPod/i.test(s);if(o&&!l&&typeof document<"u"&&this.currentModel&&V.arProvider.createUSDZBlob)try{let u=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:V.arProvider.createUSDZBlob(this.currentModel),c=URL.createObjectURL(u),a=document.createElement("a");a.href=c,a.download="three_live_model.usdz",document.body.appendChild(a),a.click(),document.body.removeChild(a),setTimeout(()=>URL.revokeObjectURL(c),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 e=this.querySelector("canvas");e||(e=document.createElement("canvas"),e.style.width="100%",e.style.height="100%",e.style.display="block",e.style.touchAction=this.cameraControls?"none":"auto",e.style.outline="none",this.appendChild(e)),this.canvas=e;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 e=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")),l=this.parseFieldOfView(this.getAttribute("field-of-view"));this.viewer=new X(this,this.canvas,{autoRotate:e,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,fieldOfView:l,cameraTarget:o,minCameraOrbit:i,maxCameraOrbit:s,onMeshClick:c=>{this.dispatchEvent(new CustomEvent("meshclick",{bubbles:!0,composed:!0,detail:c}))},onCameraChange:c=>{this.updateHotspots();for(let a of X.getRegisteredPlugins())a.onCameraChange?.(this.viewer,this);this.dispatchEvent(new CustomEvent("camera-change",{bubbles:!0,composed:!0,detail:c}))}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let u=this.getAttribute("camera-orbit");u&&this.applyCameraOrbit(u),this.currentModel&&this.loadModelWithLimits(this.currentModel,this.currentModelLimits)}setupResizeObserver(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>{this.viewer&&(this.viewer.resize(),this.viewer.render(),this.updateHotspots())}),this.resizeObserver.observe(this))}updatePoster(e){if(!(typeof document>"u")){if(!e){this.posterEl&&(this.posterEl.remove(),this.posterEl=null);return}this.posterEl||(this.posterEl=document.createElement("img"),this.posterEl.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=e,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 e=document.createElement("button");e.setAttribute("type","button"),e.setAttribute("aria-label","View in Augmented Reality"),e.className="three-live-ar-button",e.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 l=document.createElementNS(r,"polyline");l.setAttribute("points","3.27 6.96 12 12.01 20.73 6.96");let u=document.createElementNS(r,"line");u.setAttribute("x1","12"),u.setAttribute("y1","22.08"),u.setAttribute("x2","12"),u.setAttribute("y2","12"),s.appendChild(o),s.appendChild(l),s.appendChild(u),e.appendChild(s)}let i=document.createElement("span");i.textContent="View in AR",e.appendChild(i),e.style.cssText="position:absolute;right:16px;bottom:16px;z-index:2;align-items:center;justify-content:center;padding:8px 16px;background-color:rgba(15,23,42,0.85);color:#fff;border:1px solid rgba(255,255,255,0.15);border-radius:9999px;font:600 13px system-ui,-apple-system,sans-serif;cursor:pointer;backdrop-filter:blur(8px);box-shadow:0 4px 12px rgba(0,0,0,0.25);transition:transform .15s ease,background-color .15s ease;display:none",e.addEventListener("mouseenter",()=>{e.style.backgroundColor="rgba(30, 41, 59, 0.95)",e.style.transform="scale(1.04)"}),e.addEventListener("mouseleave",()=>{e.style.backgroundColor="rgba(15, 23, 42, 0.85)",e.style.transform="scale(1)"}),e.addEventListener("click",s=>{s.stopPropagation(),this.activateAR()}),this.arButton=e,this.appendChild(e)}this.updateARButtonVisibility()}}updateARButtonVisibility(){let e=this.hasAttribute("ar")&&!!V.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=e?r.dataset.tlOrigDisplay||"":"none"):this.arButton&&(this.arButton.style.display=e?"flex":"none")}applyCameraOrbit(e){if(!(!e||!this.viewer))try{let r=JSON.parse(e);this.viewer.setInitialCamera(r.theta,r.phi,r.distance,r.zoom)}catch{let r=e.trim().split(/\s+/);if(r.length>=2){let i=u=>u.endsWith("rad")?parseFloat(u)*180/Math.PI:parseFloat(u.replace(/deg$/,"")),s=r[0]==="auto"?void 0:i(r[0]),o=r[1]==="auto"?void 0:i(r[1]),l;r.length>=3&&r[2]!=="auto"&&(l=parseFloat(r[2].replace(/m$/,""))),(s!==void 0&&!isNaN(s)||o!==void 0&&!isNaN(o))&&this.viewer.setInitialCamera(s!==void 0&&!isNaN(s)?s:void 0,o!==void 0&&!isNaN(o)?o:void 0,l!==void 0&&!isNaN(l)?l:void 0)}}}parseOrbitLimit(e){if(!e)return{};let r=e.trim().split(/\s+/),i={};if(r.length>0&&r[0]!=="auto"){let s=r[0].endsWith("rad")?parseFloat(r[0])*180/Math.PI:parseFloat(r[0].replace(/deg$/,""));isNaN(s)||(i.theta=s)}if(r.length>1&&r[1]!=="auto"){let s=r[1].endsWith("rad")?parseFloat(r[1])*180/Math.PI:parseFloat(r[1].replace(/deg$/,""));isNaN(s)||(i.phi=s)}if(r.length>2&&r[2]!=="auto"){let s=parseFloat(r[2].replace(/m$/,""));isNaN(s)||(i.distance=s)}return i}applyOrbitLimits(){if(!this.viewer)return;let e=this.parseOrbitLimit(this.getAttribute("min-camera-orbit")),r=this.parseOrbitLimit(this.getAttribute("max-camera-orbit"));this.viewer.setOrbitLimits({minTheta:e.theta,maxTheta:r.theta,minPhi:e.phi,maxPhi:r.phi,minDistance:e.distance,maxDistance:r.distance})}parseCameraTarget(e){if(!e)return;let r=e.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(e){if(!e)return;let r=e.endsWith("rad")?parseFloat(e)*180/Math.PI:parseFloat(e.replace(/deg$/,""));return isNaN(r)?void 0:r}parseRotationPerSecond(e){if(!e)return Math.PI/6;let r=e.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(e){let r=this.parseCameraTarget(e);this.viewer&&r&&this.viewer.setTarget(r[0],r[1],r[2])}applyFieldOfView(e){let r=this.parseFieldOfView(e);this.viewer&&r!==void 0&&this.viewer.setFieldOfView(r)}updateHotspot(e){let r=this.querySelector(`[slot="${e.name}"]`);r&&(e.position!==void 0&&r.setAttribute("data-position",e.position),e.normal!==void 0&&r.setAttribute("data-normal",e.normal)),this.updateHotspots()}updateHotspots(){for(let e of X.getRegisteredPlugins())if(e.updateHotspotsForElement){e.updateHotspotsForElement(this,this.viewer);return}}async loadModelFromSrc(e){await this.loadModel(e)}runWithScriptRunner(e){let r=V.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;e(r,{onModelReady:u=>{this.loadModelWithLimits(u,Ge).then(()=>{o||(o=!0,i(u))},c=>{let a=c instanceof Error?c.message:String(c);this.showToast(a),o||(o=!0,s(c))})},onUpdateTransforms:u=>this.viewer?.updateMeshTransforms(u),onError:u=>{this.showToast(u.message),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:u}})),o||(o=!0,s(u))},onToast:u=>this.showToast(u)}).then(u=>{u&&(this.scriptHandle=u)},u=>{u instanceof Error&&u.message&&this.showToast(u.message),o||(o=!0,s(u))})})}loadScriptFromSrc(e){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(e,this.sandbox,i)})}executeScript(e){if(!V.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(_e);return this.showToast(He),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:r}})),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(e,this.sandbox,i,{allowClientScripts:!0}))}};V.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","environment-image","skybox-image","autoplay","animation-name","auto-rotate","auto-rotate-delay","rotation-per-second"],V.registerPlugin=X.registerPlugin,V.getRegisteredPlugins=X.getRegisteredPlugins;var de=V;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",de);return Qe(ut);})();