three-live 1.3.0 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +1 -1
  2. package/dist/index.d.ts +37 -0
  3. package/dist/three-author-engine.js +112 -61
  4. package/dist/three-author.cjs +110 -59
  5. package/dist/three-author.d.ts +37 -0
  6. package/dist/three-author.js +109 -58
  7. package/dist/three-convert.cjs +106 -59
  8. package/dist/three-convert.d.ts +37 -0
  9. package/dist/three-convert.js +105 -58
  10. package/dist/three-live-animation.cjs +8 -9
  11. package/dist/three-live-animation.d.ts +37 -0
  12. package/dist/three-live-animation.js +7 -8
  13. package/dist/three-live-animation.min.js +6 -7
  14. package/dist/three-live-cad.cjs +3 -4
  15. package/dist/three-live-cad.d.ts +37 -0
  16. package/dist/three-live-cad.js +2 -3
  17. package/dist/three-live-cad.min.js +3 -4
  18. package/dist/three-live-cli.js +231 -0
  19. package/dist/three-live-element.cjs +17 -20
  20. package/dist/three-live-element.d.ts +37 -0
  21. package/dist/three-live-element.js +16 -19
  22. package/dist/three-live-full.cjs +138 -87
  23. package/dist/three-live-full.js +137 -86
  24. package/dist/three-live-full.min.js +138 -87
  25. package/dist/three-live-studio.cjs +19 -20
  26. package/dist/three-live-studio.d.ts +37 -0
  27. package/dist/three-live-studio.js +18 -19
  28. package/dist/three-live-studio.min.js +18 -19
  29. package/dist/three-live-viewer.cjs +17 -20
  30. package/dist/three-live-viewer.d.ts +37 -0
  31. package/dist/three-live-viewer.js +16 -19
  32. package/dist/three-live-viewer.min.js +17 -20
  33. package/dist/three-live.cjs +115 -64
  34. package/dist/three-live.js +113 -62
  35. package/dist/three-live.min.js +115 -64
  36. package/dist/three-view.cjs +17 -20
  37. package/dist/three-view.d.ts +37 -0
  38. package/dist/three-view.js +16 -19
  39. package/dist/three-xr.cjs +105 -58
  40. package/dist/three-xr.d.ts +37 -0
  41. package/dist/three-xr.js +104 -57
  42. package/package.json +25 -1
@@ -1,4 +1,4 @@
1
- /**
1
+ "use strict";/**
2
2
  * @license
3
3
  * Copyright 2026 Google LLC
4
4
  *
@@ -13,8 +13,7 @@
13
13
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
- */
17
- "use strict";var ThreeLiveViewer=(()=>{var we=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var it=(n,t)=>{for(var e in t)we(n,e,{get:t[e],enumerable:!0})},rt=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of et(t))!tt.call(n,i)&&i!==e&&we(n,i,{get:()=>t[i],enumerable:!(r=Qe(t,i))||r.enumerable});return n};var nt=n=>rt(we({},"__esModule",{value:!0}),n);var yt={};it(yt,{ThreeLiveElement:()=>be,ThreeView:()=>te,toGLBData:()=>pe});function Ae(n,t){let e=n?.trim(),r=e?Number(e):NaN;return Number.isFinite(r)?r:t}var Fe='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).',Ne="Security Error: client-side scripts require allow-client-scripts opt-in.";var xe="__THREE_LIVE_REGISTRY__";function $(){let n=typeof globalThis<"u"?globalThis:{};if(!n[xe]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(n,xe,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{n[xe]=t}}return n[xe]}var Y=$().plugins;function Be(n){let t=$().plugins;t.some(e=>e.name===n.name)||t.push(n),n.onRegister?.()}function ke(){return $().plugins}function ye(n,t,e,r=!0){let i=[],s=null;try{for(let[o,l]of[[35633,t],[35632,e]]){let a=n.createShader(o);if(!a){if(r)throw new Error("Shader allocation failed");return null}if(i.push(a),n.shaderSource(a,l),n.compileShader(a),n.getShaderParameter&&!n.getShaderParameter(a,35713)){if(r)throw new Error(`Shader compile error: ${n.getShaderInfoLog(a)}`);return null}}if(s=n.createProgram(),!s){if(r)throw new Error("Program allocation failed");return null}for(let o of i)n.attachShader(s,o);if(n.linkProgram(s),n.getProgramParameter&&!n.getProgramParameter(s,35714)){let o=r?n.getProgramInfoLog(s):null;if(n.deleteProgram?.(s),s=null,r)throw new Error(`Program link error: ${o}`);return null}return s}finally{for(let o of i)s&&n.detachShader?.(s,o),n.deleteShader?.(o)}}var st={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function Ee(n,t,e,r){if(!e||e.bufferView===void 0)return null;let i=n.bufferViews?.[e.bufferView];if(!i)return null;let s=Number(e.count??0);if(!Number.isInteger(s)||s<=0)return null;let o=e.componentType??5126,l=st[o];if(!l)throw new RangeError(`glTF accessor has unsupported componentType ${o}`);let a=l*r,c=i.byteStride&&i.byteStride>0?i.byteStride:a,u=(i.byteOffset||0)+(e.byteOffset||0);if(!Number.isInteger(u)||u<0||c<a||u+(s-1)*c+a>t.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${t.byteLength} bytes)`);if(o===5126&&c===a&&u%4===0)return new Float32Array(t,u,s*r);let d=new DataView(t),m=e.normalized===!0,x=new Float32Array(s*r);for(let g=0;g<s;g++){let b=u+g*c;for(let v=0;v<r;v++){let y=b+v*l,w;switch(o){case 5126:w=d.getFloat32(y,!0);break;case 5120:w=d.getInt8(y),m&&(w=Math.max(w/127,-1));break;case 5121:w=d.getUint8(y),m&&(w/=255);break;case 5122:w=d.getInt16(y,!0),m&&(w=Math.max(w/32767,-1));break;case 5123:w=d.getUint16(y,!0),m&&(w/=65535);break;default:w=d.getUint32(y,!0),m&&(w/=4294967295)}x[g*r+v]=w}}return x}function _e(n,t){let e=Number(t.offset?.[0]??0)||0,r=Number(t.offset?.[1]??0)||0,i=Number(t.scale?.[0]??1),s=Number(t.scale?.[1]??1),o=Number(t.rotation??0)||0,l=Math.cos(o),a=Math.sin(o),c=(Number.isFinite(i)?i:1)*l,u=(Number.isFinite(i)?i:1)*a,d=-(Number.isFinite(s)?s:1)*a,m=(Number.isFinite(s)?s:1)*l;for(let x=0;x+1<n.length;x+=2){let g=n[x],b=n[x+1];n[x]=c*g+u*b+e,n[x+1]=d*g+m*b+r}}function X(){let n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n}function Te(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 Me(n,t,e,r){let[i,s,o]=t,[l,a,c]=r,[u,d,m]=e,x=i-u,g=s-d,b=o-m,v=Math.hypot(x,g,b);v<=1e-5?(x=0,g=0,b=1):(x/=v,g/=v,b/=v);let y=a*b-c*g,w=c*x-l*b,T=l*g-a*x;v=Math.hypot(y,w,T),v<=1e-5?(y=0,w=0,T=0):(y/=v,w/=v,T/=v);let M=g*T-b*w,p=b*y-x*T,R=x*w-g*y;return v=Math.hypot(M,p,R),v<=1e-5?(M=0,p=0,R=0):(M/=v,p/=v,R/=v),n[0]=y,n[1]=M,n[2]=x,n[3]=0,n[4]=w,n[5]=p,n[6]=g,n[7]=0,n[8]=T,n[9]=R,n[10]=b,n[11]=0,n[12]=-(y*i+w*s+T*o),n[13]=-(M*i+p*s+R*o),n[14]=-(x*i+g*s+b*o),n[15]=1,n}function ee(n,t,e){let r=t[0],i=t[1],s=t[2],o=t[3],l=t[4],a=t[5],c=t[6],u=t[7],d=t[8],m=t[9],x=t[10],g=t[11],b=t[12],v=t[13],y=t[14],w=t[15],T=e[0],M=e[1],p=e[2],R=e[3];return n[0]=T*r+M*l+p*d+R*b,n[1]=T*i+M*a+p*m+R*v,n[2]=T*s+M*c+p*x+R*y,n[3]=T*o+M*u+p*g+R*w,T=e[4],M=e[5],p=e[6],R=e[7],n[4]=T*r+M*l+p*d+R*b,n[5]=T*i+M*a+p*m+R*v,n[6]=T*s+M*c+p*x+R*y,n[7]=T*o+M*u+p*g+R*w,T=e[8],M=e[9],p=e[10],R=e[11],n[8]=T*r+M*l+p*d+R*b,n[9]=T*i+M*a+p*m+R*v,n[10]=T*s+M*c+p*x+R*y,n[11]=T*o+M*u+p*g+R*w,T=e[12],M=e[13],p=e[14],R=e[15],n[12]=T*r+M*l+p*d+R*b,n[13]=T*i+M*a+p*m+R*v,n[14]=T*s+M*c+p*x+R*y,n[15]=T*o+M*u+p*g+R*w,n}function Se(n,t,e,r){let i=t[0],s=t[1],o=t[2],l=t[3],a=i+i,c=s+s,u=o+o,d=i*a,m=i*c,x=i*u,g=s*c,b=s*u,v=o*u,y=l*a,w=l*c,T=l*u,M=r[0],p=r[1],R=r[2];return n[0]=(1-(g+v))*M,n[1]=(m+T)*M,n[2]=(x-w)*M,n[3]=0,n[4]=(m-T)*p,n[5]=(1-(d+v))*p,n[6]=(b+y)*p,n[7]=0,n[8]=(x+w)*R,n[9]=(b-y)*R,n[10]=(1-(d+g))*R,n[11]=0,n[12]=e[0],n[13]=e[1],n[14]=e[2],n[15]=1,n}function ce(n,t,e=0){let r=t[0],i=t[1],s=t[2],o=t[4],l=t[5],a=t[6],c=t[8],u=t[9],d=t[10],m=d*l-a*u,x=-d*o+a*c,g=u*o-l*c,b=r*m+i*x+s*g;return!b||e>0&&(!Number.isFinite(b)||Math.abs(b)<=e)||(b=1/b,n[0]=m*b,n[1]=x*b,n[2]=g*b,n[3]=(-d*i+s*u)*b,n[4]=(d*r-s*c)*b,n[5]=(-u*r+i*c)*b,n[6]=(a*i-s*l)*b,n[7]=(-a*r+s*o)*b,n[8]=(l*r-i*o)*b),n}function Ge(n,t){let e=t[0],r=t[1],i=t[2],s=t[3],o=t[4],l=t[5],a=t[6],c=t[7],u=t[8],d=t[9],m=t[10],x=t[11],g=t[12],b=t[13],v=t[14],y=t[15],w=e*l-r*o,T=e*a-i*o,M=e*c-s*o,p=r*a-i*l,R=r*c-s*l,_=i*c-s*a,L=u*b-d*g,O=u*v-m*g,V=u*y-x*g,F=d*v-m*b,h=d*y-x*b,E=m*y-x*v,A=w*E-T*h+M*F+p*V-R*O+_*L;return A?(A=1/A,n[0]=(l*E-a*h+c*F)*A,n[1]=(i*h-r*E-s*F)*A,n[2]=(b*_-v*R+y*p)*A,n[3]=(m*R-d*_-x*p)*A,n[4]=(a*V-o*E-c*O)*A,n[5]=(e*E-i*V+s*O)*A,n[6]=(v*M-g*_-y*T)*A,n[7]=(u*_-m*M+x*T)*A,n[8]=(o*h-l*V+c*L)*A,n[9]=(r*V-e*h-s*L)*A,n[10]=(g*R-b*M+y*w)*A,n[11]=(d*M-u*R-x*w)*A,n[12]=(l*O-o*F-a*L)*A,n[13]=(e*F-r*O+i*L)*A,n[14]=(b*T-g*p-v*w)*A,n[15]=(u*p-d*T+m*w)*A,n):null}function Pe(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],a=i[3]*t+i[7]*e+i[11]*r+i[15],c=a!==0?1/a:1;n[0]=s*c,n[1]=o*c,n[2]=l*c}function Oe(n,t,e,r,i,s,o,l,a,c,u,d,m,x,g,b,v=0){let y=c-o,w=u-l,T=d-a,M=m-o,p=x-l,R=g-a,_=i*R-s*p,L=s*M-r*R,O=r*p-i*M,V=y*_+w*L+T*O;if(V>-1e-7&&V<1e-7)return!1;let F=1/V,h=n-o,E=t-l,A=e-a,f=F*(h*_+E*L+A*O);if(f<-v||f>1+v)return!1;let N=E*T-A*w,P=A*y-h*T,K=h*w-E*y,S=F*(r*N+i*P+s*K);if(S<-v||f+S>1+v)return!1;let U=F*(M*N+p*P+R*K);if(U>1e-4&&U<b.distance){b.distance=U,b.point=[n+r*U,t+i*U,e+s*U];let k=w*R-T*p,Z=T*M-y*R,J=y*p-w*M,B=Math.hypot(k,Z,J)||1;return b.normal=[k/B,Z/B,J/B],!0}return!1}function Ue(n,t){let e=Array.isArray(n?.nodes)?n.nodes.length:0,r=[];for(let u=0;u<e;u++)r.push(X());if(e===0)return r;let i=new Set;for(let u of n.nodes)if(Array.isArray(u.children))for(let d of u.children)i.add(d);let s=new Set,o=128,l=(u,d,m=0)=>{if(m>o||u<0||u>=e||s.has(u))return;s.add(u);let x=n.nodes[u];if(!x)return;let g=X();if(t&&t[u])g.set(t[u]);else if(x.matrix&&x.matrix.length===16)g.set(x.matrix);else{let v=x.translation||[0,0,0],y=x.rotation||[0,0,0,1],w=x.scale||[1,1,1];Se(g,y,v,w)}let b=r[u];if(d?ee(b,d,g):b.set(g),Array.isArray(x.children))for(let v of x.children)typeof v=="number"&&l(v,b,m+1)},a=[],c=n.scenes&&n.scenes[n.scene!==void 0?n.scene:0];if(c&&Array.isArray(c.nodes))a.push(...c.nodes);else for(let u=0;u<e;u++)i.has(u)||a.push(u);for(let u of a)l(u,null);for(let u=0;u<e;u++)!i.has(u)&&!a.includes(u)&&l(u,null);return r}var We=["neutral","reinhard","none","aces","agx"];function de(n){let t=String(n??"").trim().toLowerCase();return We.includes(t)?t:"neutral"}function ot(n){return We.indexOf(de(n))}function at(n){return new TextDecoder().decode(n)}var Xe=$().decoders;function ut(n,t){Xe.set(n.toLowerCase(),t)}function me(n){return Xe.get(n.toLowerCase())}function ze(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),o=12,l=null,a=null;for(;o+8<=s&&o+8<=t.byteLength;){let m=e.getUint32(o,!0),x=e.getUint32(o+4,!0),g=o+8;if(g+m>t.byteLength)throw new Error(`Truncated GLB chunk: required ${g+m} bytes, buffer has ${t.byteLength}`);if(x===1313821514){let b=new Uint8Array(t,g,m),v=at(b);l=JSON.parse(v,(y,w)=>y==="__proto__"||y==="constructor"||y==="prototype"?void 0:w)}else x===5130562&&(a=t.slice(g,g+m));o=g+m}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).");for(let m of["EXT_meshopt_compression","KHR_meshopt_compression"])if(c.includes(m)&&!me("meshopt"))throw new Error(`Model requires ${m}. 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 u=a||new ArrayBuffer(0),d={gltf:l,bin:u,animations:[]};for(let m of Y)m.onParseGLB?.(d);return d}function lt(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 pe(n){if(lt(n))return n;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return ze(n);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var je=`#version 300 es
16
+ */var ThreeLiveViewer=(()=>{var wt=Object.defineProperty,$t=Object.getOwnPropertyDescriptor,qt=Object.getOwnPropertyNames,Kt=Object.prototype.hasOwnProperty,Yt=(e,t)=>{for(var i in t)wt(e,i,{get:t[i],enumerable:!0})},Zt=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of qt(t))!Kt.call(e,s)&&s!==i&&wt(e,s,{get:()=>t[s],enumerable:!(r=$t(t,s))||r.enumerable});return e},Jt=e=>Zt(wt({},"__esModule",{value:!0}),e),Et={};Yt(Et,{ThreeLiveElement:()=>Wt,ThreeView:()=>rt,toGLBData:()=>vt});function Lt(e,t){let i=e?.trim(),r=i?Number(i):NaN;return Number.isFinite(r)?r:t}var Qt='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).',te="Security Error: client-side scripts require allow-client-scripts opt-in.",gt="__THREE_LIVE_REGISTRY__";function Z(){let e=typeof globalThis<"u"?globalThis:{};if(!e[gt]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(e,gt,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{e[gt]=t}}return e[gt]}var G=Z().plugins;function ee(e){let t=Z().plugins;t.some(i=>i.name===e.name)||t.push(e),e.onRegister?.()}function ie(){return Z().plugins}var re={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function It(e,t,i,r){if(!i||i.bufferView===void 0)return null;let s=e.bufferViews?.[i.bufferView];if(!s)return null;let a=Number(i.count??0);if(!Number.isInteger(a)||a<=0)return null;let o=i.componentType??5126,h=re[o];if(!h)throw new RangeError(`glTF accessor has unsupported componentType ${o}`);let n=h*r,l=s.byteStride&&s.byteStride>0?s.byteStride:n,c=(s.byteOffset||0)+(i.byteOffset||0);if(!Number.isInteger(c)||c<0||l<n||c+(a-1)*l+n>t.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${t.byteLength} bytes)`);if(o===5126&&l===n&&c%4===0)return new Float32Array(t,c,a*r);let m=new DataView(t),x=i.normalized===!0,f=new Float32Array(a*r);for(let v=0;v<a;v++){let b=c+v*l;for(let T=0;T<r;T++){let M=b+T*h,d;switch(o){case 5126:d=m.getFloat32(M,!0);break;case 5120:d=m.getInt8(M),x&&(d=Math.max(d/127,-1));break;case 5121:d=m.getUint8(M),x&&(d/=255);break;case 5122:d=m.getInt16(M,!0),x&&(d=Math.max(d/32767,-1));break;case 5123:d=m.getUint16(M,!0),x&&(d/=65535);break;default:d=m.getUint32(M,!0),x&&(d/=4294967295)}f[v*r+T]=d}}return f}function se(e,t){let i=Number(t.offset?.[0]??0)||0,r=Number(t.offset?.[1]??0)||0,s=Number(t.scale?.[0]??1),a=Number(t.scale?.[1]??1),o=Number(t.rotation??0)||0,h=Math.cos(o),n=Math.sin(o),l=(Number.isFinite(s)?s:1)*h,c=(Number.isFinite(s)?s:1)*n,m=-(Number.isFinite(a)?a:1)*n,x=(Number.isFinite(a)?a:1)*h;for(let f=0;f+1<e.length;f+=2){let v=e[f],b=e[f+1];e[f]=l*v+c*b+i,e[f+1]=m*v+x*b+r}}function Tt(e,t,i,r=!0){let s=[],a=null;try{for(let[o,h]of[[35633,t],[35632,i]]){let n=e.createShader(o);if(!n){if(r)throw new Error("Shader allocation failed");return null}if(s.push(n),e.shaderSource(n,h),e.compileShader(n),e.getShaderParameter&&!e.getShaderParameter(n,35713)){if(r)throw new Error(`Shader compile error: ${e.getShaderInfoLog(n)}`);return null}}if(a=e.createProgram(),!a){if(r)throw new Error("Program allocation failed");return null}for(let o of s)e.attachShader(a,o);if(e.linkProgram(a),e.getProgramParameter&&!e.getProgramParameter(a,35714)){let o=r?e.getProgramInfoLog(a):null;if(e.deleteProgram?.(a),a=null,r)throw new Error(`Program link error: ${o}`);return null}return a}finally{for(let o of s)a&&e.detachShader?.(a,o),e.deleteShader?.(o)}}function z(){let e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function Pt(e,t,i,r,s){let a=1/Math.tan(t/2);e.fill(0),e[0]=a/i,e[5]=a,e[11]=-1;let o=1/(r-s);return e[10]=(s+r)*o,e[14]=2*s*r*o,e}function At(e,t,i,r){let[s,a,o]=t,[h,n,l]=r,[c,m,x]=i,f=s-c,v=a-m,b=o-x,T=Math.hypot(f,v,b);T<=1e-5?(f=0,v=0,b=1):(f/=T,v/=T,b/=T);let M=n*b-l*v,d=l*f-h*b,g=h*v-n*f;T=Math.hypot(M,d,g),T<=1e-5?(M=0,d=0,g=0):(M/=T,d/=T,g/=T);let p=v*g-b*d,A=b*M-f*g,w=f*d-v*M;return T=Math.hypot(p,A,w),T<=1e-5?(p=0,A=0,w=0):(p/=T,A/=T,w/=T),e[0]=M,e[1]=p,e[2]=f,e[3]=0,e[4]=d,e[5]=A,e[6]=v,e[7]=0,e[8]=g,e[9]=w,e[10]=b,e[11]=0,e[12]=-(M*s+d*a+g*o),e[13]=-(p*s+A*a+w*o),e[14]=-(f*s+v*a+b*o),e[15]=1,e}function J(e,t,i){let r=t[0],s=t[1],a=t[2],o=t[3],h=t[4],n=t[5],l=t[6],c=t[7],m=t[8],x=t[9],f=t[10],v=t[11],b=t[12],T=t[13],M=t[14],d=t[15],g=i[0],p=i[1],A=i[2],w=i[3];return e[0]=g*r+p*h+A*m+w*b,e[1]=g*s+p*n+A*x+w*T,e[2]=g*a+p*l+A*f+w*M,e[3]=g*o+p*c+A*v+w*d,g=i[4],p=i[5],A=i[6],w=i[7],e[4]=g*r+p*h+A*m+w*b,e[5]=g*s+p*n+A*x+w*T,e[6]=g*a+p*l+A*f+w*M,e[7]=g*o+p*c+A*v+w*d,g=i[8],p=i[9],A=i[10],w=i[11],e[8]=g*r+p*h+A*m+w*b,e[9]=g*s+p*n+A*x+w*T,e[10]=g*a+p*l+A*f+w*M,e[11]=g*o+p*c+A*v+w*d,g=i[12],p=i[13],A=i[14],w=i[15],e[12]=g*r+p*h+A*m+w*b,e[13]=g*s+p*n+A*x+w*T,e[14]=g*a+p*l+A*f+w*M,e[15]=g*o+p*c+A*v+w*d,e}function kt(e,t,i,r){let s=t[0],a=t[1],o=t[2],h=t[3],n=s+s,l=a+a,c=o+o,m=s*n,x=s*l,f=s*c,v=a*l,b=a*c,T=o*c,M=h*n,d=h*l,g=h*c,p=r[0],A=r[1],w=r[2];return e[0]=(1-(v+T))*p,e[1]=(x+g)*p,e[2]=(f-d)*p,e[3]=0,e[4]=(x-g)*A,e[5]=(1-(m+T))*A,e[6]=(b+M)*A,e[7]=0,e[8]=(f+d)*w,e[9]=(b-M)*w,e[10]=(1-(m+v))*w,e[11]=0,e[12]=i[0],e[13]=i[1],e[14]=i[2],e[15]=1,e}function ut(e,t,i=0){let r=t[0],s=t[1],a=t[2],o=t[4],h=t[5],n=t[6],l=t[8],c=t[9],m=t[10],x=m*h-n*c,f=-m*o+n*l,v=c*o-h*l,b=r*x+s*f+a*v;return!b||i>0&&(!Number.isFinite(b)||Math.abs(b)<=i)||(b=1/b,e[0]=x*b,e[1]=f*b,e[2]=v*b,e[3]=(-m*s+a*c)*b,e[4]=(m*r-a*l)*b,e[5]=(-c*r+s*l)*b,e[6]=(n*s-a*h)*b,e[7]=(-n*r+a*o)*b,e[8]=(h*r-s*o)*b),e}function ae(e,t){let i=t[0],r=t[1],s=t[2],a=t[3],o=t[4],h=t[5],n=t[6],l=t[7],c=t[8],m=t[9],x=t[10],f=t[11],v=t[12],b=t[13],T=t[14],M=t[15],d=i*h-r*o,g=i*n-s*o,p=i*l-a*o,A=r*n-s*h,w=r*l-a*h,V=s*l-a*n,_=c*b-m*v,U=c*T-x*v,E=c*M-f*v,y=m*T-x*b,L=m*M-f*b,P=x*M-f*T,u=d*P-g*L+p*y+A*E-w*U+V*_;return u?(u=1/u,e[0]=(h*P-n*L+l*y)*u,e[1]=(s*L-r*P-a*y)*u,e[2]=(b*V-T*w+M*A)*u,e[3]=(x*w-m*V-f*A)*u,e[4]=(n*E-o*P-l*U)*u,e[5]=(i*P-s*E+a*U)*u,e[6]=(T*p-v*V-M*g)*u,e[7]=(c*V-x*p+f*g)*u,e[8]=(o*L-h*E+l*_)*u,e[9]=(r*E-i*L-a*_)*u,e[10]=(v*w-b*p+M*d)*u,e[11]=(m*p-c*w-f*d)*u,e[12]=(h*U-o*y-n*_)*u,e[13]=(i*y-r*U+s*_)*u,e[14]=(b*g-v*A-T*d)*u,e[15]=(c*A-m*g+x*d)*u,e):null}function Nt(e,t,i,r,s){let a=s[0]*t+s[4]*i+s[8]*r+s[12],o=s[1]*t+s[5]*i+s[9]*r+s[13],h=s[2]*t+s[6]*i+s[10]*r+s[14],n=s[3]*t+s[7]*i+s[11]*r+s[15],l=n!==0?1/n:1;e[0]=a*l,e[1]=o*l,e[2]=h*l}function oe(e,t,i,r,s,a,o,h,n,l,c,m,x,f,v,b,T=0){let M=l-o,d=c-h,g=m-n,p=x-o,A=f-h,w=v-n,V=s*w-a*A,_=a*p-r*w,U=r*A-s*p,E=M*V+d*_+g*U;if(E>-1e-7&&E<1e-7)return!1;let y=1/E,L=e-o,P=t-h,u=i-n,C=y*(L*V+P*_+u*U);if(C<-T||C>1+T)return!1;let H=P*g-u*d,Q=u*M-L*g,I=L*d-P*M,k=y*(r*H+s*Q+a*I);if(k<-T||C+k>1+T)return!1;let R=y*(p*H+A*Q+w*I);if(R>1e-4&&R<b.distance){b.distance=R,b.point=[e+r*R,t+s*R,i+a*R];let N=d*w-g*A,B=g*p-M*w,F=M*A-d*p,$=Math.hypot(N,B,F)||1;return b.normal=[N/$,B/$,F/$],!0}return!1}function ne(e,t){let i=Array.isArray(e?.nodes)?e.nodes.length:0,r=[];for(let c=0;c<i;c++)r.push(z());if(i===0)return r;let s=new Set;for(let c of e.nodes)if(Array.isArray(c.children))for(let m of c.children)s.add(m);let a=new Set,o=128,h=(c,m,x=0)=>{if(x>o||c<0||c>=i||a.has(c))return;a.add(c);let f=e.nodes[c];if(!f)return;let v=z();if(t&&t[c])v.set(t[c]);else if(f.matrix&&f.matrix.length===16)v.set(f.matrix);else{let T=f.translation||[0,0,0],M=f.rotation||[0,0,0,1],d=f.scale||[1,1,1];kt(v,M,T,d)}let b=r[c];if(m?J(b,m,v):b.set(v),Array.isArray(f.children))for(let T of f.children)typeof T=="number"&&h(T,b,x+1)},n=[],l=e.scenes&&e.scenes[e.scene!==void 0?e.scene:0];if(l&&Array.isArray(l.nodes))n.push(...l.nodes);else for(let c=0;c<i;c++)s.has(c)||n.push(c);for(let c of n)h(c,null);for(let c=0;c<i;c++)!s.has(c)&&!n.includes(c)&&h(c,null);return r}var Vt=["neutral","reinhard","none","aces","agx"];function dt(e){let t=String(e??"").trim().toLowerCase();return Vt.includes(t)?t:"neutral"}function le(e){return Vt.indexOf(dt(e))}function he(e){return new TextDecoder().decode(e)}var Ft=Z().decoders;function ue(e,t){Ft.set(e.toLowerCase(),t)}function ct(e){return Ft.get(e.toLowerCase())}function Ot(e){let t=ArrayBuffer.isView(e)?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):e,i=new DataView(t);if(t.byteLength<12)throw new Error(`Invalid GLB buffer size: ${t.byteLength} bytes`);let r=i.getUint32(0,!0);if(r!==1179937895){let x=i.getUint8(0);throw x===123||x===32||x===10||x===13?new Error("[three-live] Multi-file JSON .gltf is not supported for performance reasons. Please pack your asset into a single binary .glb file."):new Error(`Invalid GLB magic: 0x${r.toString(16)}`)}let s=i.getUint32(4,!0);if(s!==2)throw new Error(`Unsupported GLB version: ${s}`);let a=i.getUint32(8,!0),o=12,h=null,n=null;for(;o+8<=a&&o+8<=t.byteLength;){let x=i.getUint32(o,!0),f=i.getUint32(o+4,!0),v=o+8;if(v+x>t.byteLength)throw new Error(`Truncated GLB chunk: required ${v+x} bytes, buffer has ${t.byteLength}`);if(f===1313821514){let b=new Uint8Array(t,v,x),T=he(b);h=JSON.parse(T,(M,d)=>M==="__proto__"||M==="constructor"||M==="prototype"?void 0:d)}else f===5130562&&(n=t.slice(v,v+x));o=v+x}if(!h)throw new Error("Missing JSON chunk in GLB");let l=h.extensionsRequired||[];if(l.includes("KHR_draco_mesh_compression")&&!ct("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");for(let x of["EXT_meshopt_compression","KHR_meshopt_compression"])if(l.includes(x)&&!ct("meshopt"))throw new Error(`Model requires ${x}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(l.includes("KHR_texture_basisu")&&!ct("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let c=n||new ArrayBuffer(0),m={gltf:h,bin:c,animations:[]};for(let x of G)x.onParseGLB?.(m);return m}function ce(e){return typeof e=="object"&&e!==null&&"gltf"in e&&typeof e.gltf=="object"&&e.gltf!==null&&"bin"in e&&(e.bin instanceof ArrayBuffer||ArrayBuffer.isView(e.bin))}function vt(e){if(ce(e))return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Ot(e);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var Bt=`#version 300 es
18
17
  layout(location=0) in vec3 aPos;
19
18
  layout(location=3) in vec3 aOff;
20
19
  layout(location=1) in vec3 aNormal;
@@ -49,7 +48,7 @@ vec2 scaleUV=uUvTransform.zw;
49
48
  if(scaleUV.x==0.0&&scaleUV.y==0.0)scaleUV=vec2(1.0);
50
49
  vUV=aUV*scaleUV+uUvTransform.xy;
51
50
  gl_Position=uMVP*vec4(aPosition,1.0);
52
- }`,ct=`#version 300 es
51
+ }`,me=`#version 300 es
53
52
  precision highp float;
54
53
  in vec3 vNormal,vWorldPos;
55
54
  in vec2 vUV;
@@ -66,7 +65,8 @@ uniform float uNormalScale,uOcclusionStrength;
66
65
  uniform vec2 uViewportSize;
67
66
  uniform vec4 uSectionPlane;
68
67
  uniform int uToneMapping,uNumDirLights,uNumPointLights,uSectionEnabled;
69
- uniform vec3 uDirLightDir[2],uDirLightColor[2],uPointLightPos[2],uPointLightColor[2];
68
+ uniform vec3 uDirLightDir[2],uDirLightColor[2],uPointLightPos[2],uPointLightColor[2],uPointLightSpotDir[2];
69
+ uniform vec2 uPointLightSpotCone[2];
70
70
  out vec4 fragColor;
71
71
 
72
72
  vec2 envBRDF(float r,float n){
@@ -157,6 +157,11 @@ if(mode==4)return agxToneMapping(color);
157
157
  return color;
158
158
  }
159
159
 
160
+ vec3 evalLight(vec3 L,vec3 V,vec3 N,vec3 base,float specExp,float specWeight){
161
+ float NoH=max(dot(N,normalize(L+V)),0.0);
162
+ return base*max(dot(N,L),0.0)*0.75+vec3(pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35);
163
+ }
164
+
160
165
  void main(){
161
166
  if(uSectionEnabled==1&&dot(vWorldPos,uSectionPlane.xyz)>uSectionPlane.w)discard;
162
167
  vec4 base=uBaseColor;
@@ -194,24 +199,16 @@ float specWeight=mix(0.22*gloss,1.0,metallic);
194
199
  vec3 directLight=vec3(0.0);
195
200
  for(int i=0;i<2;i++){
196
201
  if(i>=uNumDirLights)break;
197
- vec3 L=normalize(uDirLightDir[i]);
198
- float NdotL=max(dot(N,L),0.0);
199
- vec3 H=normalize(L+V);
200
- float NoH=max(dot(N,H),0.0);
201
- float spec=pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35;
202
- directLight+=(base.rgb*NdotL*0.75+vec3(spec))*uDirLightColor[i];
202
+ directLight+=evalLight(normalize(uDirLightDir[i]),V,N,base.rgb,specExp,specWeight)*uDirLightColor[i];
203
203
  }
204
204
  for(int i=0;i<2;i++){
205
205
  if(i>=uNumPointLights)break;
206
206
  vec3 toLight=uPointLightPos[i]-vWorldPos;
207
207
  float dist=length(toLight);
208
208
  vec3 L=toLight/max(dist,0.0001);
209
- float atten=1.0/(1.0+0.09*dist+0.032*dist*dist);
210
- float NdotL=max(dot(N,L),0.0);
211
- vec3 H=normalize(L+V);
212
- float NoH=max(dot(N,H),0.0);
213
- float spec=pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35;
214
- directLight+=(base.rgb*NdotL*0.75+vec3(spec))*uPointLightColor[i]*atten;
209
+ float spotAtt=clamp((dot(-L,uPointLightSpotDir[i])-uPointLightSpotCone[i].y)/max(uPointLightSpotCone[i].x-uPointLightSpotCone[i].y,0.0001),0.0,1.0);
210
+ spotAtt*=spotAtt;
211
+ directLight+=evalLight(L,V,N,base.rgb,specExp,specWeight)*uPointLightColor[i]*spotAtt/(1.0+0.09*dist+0.032*dist*dist);
215
212
  }
216
213
 
217
214
  vec3 R=reflect(-V,N);
@@ -242,11 +239,11 @@ color=applyToneMapping(color,uToneMapping);
242
239
  float outAlpha=base.a;
243
240
  /*XRD_O*/
244
241
  fragColor=vec4(color,outAlpha);
245
- }`;var ht=`#version 300 es
242
+ }`,de=`#version 300 es
246
243
  layout(location=0) in vec3 aPosition;
247
244
  uniform mat4 uMVP;
248
- void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,mt=`#version 300 es
245
+ void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,pe=`#version 300 es
249
246
  precision highp float;
250
247
  uniform vec4 uColorId;
251
248
  out vec4 fragColor;
252
- void main(){fragColor=uColorId;}`;function De(n,t,e){let r={};for(let i of e)r[i]=n.getUniformLocation(t,i);return r}var Ve=["uMVP","uModel","uInstanced","uViewProj","uNormalMatrix","uUvTransform","uBaseColor","uMetallic","uRoughness","uClearcoat","uEmissive","uCameraPos","uBaseColorTexture","uHasTexture","uMetallicRoughnessTexture","uHasMetallicRoughnessTexture","uNormalTexture","uHasNormalTexture","uNormalScale","uOcclusionTexture","uHasOcclusionTexture","uOcclusionStrength","uToneMapping","uEnvironmentMap","uHasEnvironmentMap","uAmbientColor","uNumDirLights","uDirLightDir","uDirLightColor","uNumPointLights","uPointLightPos","uPointLightColor","uEnvIntensity","uExposure","uViewportSize","uSectionPlane","uSectionEnabled"];function Ye(){let n=$().xrDepthShader;return{fs:ct.replace("/*XRD_U*/",n?.uniformsGLSL||"").replace("/*XRD_O*/",n?.occlusionGLSL||""),uniforms:n?[...Ve,...n.uniformNames]:Ve}}function dt(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 Ce(n,t,e,r,i,s,o,l){if(r===void 0||!t.accessors?.[r])return null;let a=Ee(t,e,t.accessors[r],s);if(!a)return null;l&&(a=a.slice(),_e(a,l));let c=n.createBuffer();return o.push(c),n.bindBuffer(34962,c),n.bufferData(34962,a,35044),n.enableVertexAttribArray(i),n.vertexAttribPointer(i,s,5126,!1,0,0),a}function Le(n){let t=Number(n);return Number.isFinite(t)?Math.max(0,t):1}function $e(n,t,e){let r=Ye(),i=je,s=r.fs,o=!1;for(let a of Y)if(a.onResolveShader){let c=a.onResolveShader(t,e,i,s);c&&(i=c.vs,s=c.fs,o=!0)}let l=o?ye(n,i,s):null;return{program:l,uniforms:l?De(n,l,r.uniforms):null}}function pt(n,t,e){let r=t.instanceMatrices;if(!r||r.length<16||typeof n.vertexAttribDivisor!="function"||typeof n.drawElementsInstanced!="function")return!1;let i=r.length>>4,s=t.instanceColors,o=new Float32Array(i*20);for(let a=0;a<i;a++)o.set(r.subarray(a*16,a*16+16),a*20),o[a*20+16]=s?s[a*3]:1,o[a*20+17]=s?s[a*3+1]:1,o[a*20+18]=s?s[a*3+2]:1,o[a*20+19]=1;let l=n.createBuffer();e.push(l),n.bindBuffer(34962,l),n.bufferData(34962,o,35044);for(let a=0;a<5;a++)n.enableVertexAttribArray(8+a),n.vertexAttribPointer(8+a,4,5126,!1,80,a*16),n.vertexAttribDivisor(8+a,1);return!0}function ft(n,t){let e=n.materials?.[t?.material];if(!e)return null;let r=[e.pbrMetallicRoughness?.baseColorTexture,e.pbrMetallicRoughness?.metallicRoughnessTexture,e.normalTexture,e.occlusionTexture,e.emissiveTexture];for(let i of r){let s=i?.extensions?.KHR_texture_transform;if(s&&typeof s=="object")return s}return null}var qe=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),Ke=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Re(n,t){t.indices?n.drawElements(4,t.indexCount,t.indexType,0):n.drawArrays(4,0,t.indexCount)}function Ze(n,t){let e=n?.pbrMetallicRoughness,r=e?.baseColorFactor,i=n?.extensions?.KHR_materials_clearcoat,s=o=>o!==void 0&&t[o.index]?t[o.index]:null;return{baseColor:r?[r[0],r[1],r[2],r[3]??1]:[.8,.8,.8,1],metallic:e?.metallicFactor??.1,roughness:e?.roughnessFactor??.5,clearcoat:i?i.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,i?.clearcoatRoughnessFactor??.04),texture:s(e?.baseColorTexture),metallicRoughnessTexture:s(e?.metallicRoughnessTexture),normalTexture:s(n?.normalTexture),normalScale:n?.normalTexture?.scale??1,occlusionTexture:s(n?.occlusionTexture),occlusionStrength:n?.occlusionTexture?.strength??1,isTransmissive:(n?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function Je(n,t,e){let r=new Set,i=s=>{s&&!r.has(s)&&(r.add(s),n.deleteTexture(s))};for(let s of t)for(let o of s.primitives){if(o.vao&&n.deleteVertexArray(o.vao),o.buffers)for(let a of o.buffers)n.deleteBuffer(a);i(o.texture),i(o.metallicRoughnessTexture),i(o.normalTexture),i(o.occlusionTexture);let l=new Set;o.customProgram&&l.add(o.customProgram);for(let a of o.programCache?.values()??[])a.program&&l.add(a.program);for(let a of l)n.deleteProgram(a)}if(e)for(let s of e)i(s)}function He(n,t,e=Ke,r){let i={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return bt(n,t,e,r,i)}catch(s){let o=i.mesh&&!i.meshes.includes(i.mesh)?[...i.meshes,i.mesh]:i.meshes;Je(n,o,i.gpuTextures),i.vao&&n.deleteVertexArray(i.vao);for(let l of i.buffers)n.deleteBuffer(l);throw s}}function bt(n,t,e,r,i){if(!t||!t.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:s}=t,o=me("meshopt");o?.decodeBufferViews&&o.decodeBufferViews(s,t);let l=t.bin,a=[];i.meshes=a;let c=[],u=s.extensions?.KHR_materials_variants;u&&Array.isArray(u.variants)&&u.variants.forEach((h,E)=>{c.push(typeof h?.name=="string"&&h.name?h.name:`Variant_${E}`)});let d=Ue(s),m=[];if(Array.isArray(s.nodes))for(let h=0;h<s.nodes.length;h++){let E=s.nodes[h];E.mesh!==void 0&&s.meshes&&s.meshes[E.mesh]&&m.push({node:E,nodeIdx:h,meshIdx:E.mesh})}let x=m.length>0?m:(s.meshes||[]).map((h,E)=>({node:h,nodeIdx:-1,meshIdx:E})),g=[];if(Array.isArray(t.lights)&&t.lights.length>0)g.push(...t.lights);else if(s.extensions?.KHR_lights_punctual?.lights){let h=s.extensions.KHR_lights_punctual.lights;for(let E of h){let A=E.type==="directional"?"directional":E.type==="point"?"point":"ambient";g.push({type:A,color:E.color||[1,1,1],intensity:E.intensity!==void 0?E.intensity:1})}}if(g.length===0&&(g.push({type:"ambient",color:[1,1,1],intensity:.35}),g.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),x.length>e.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${e.maxMeshes}). Found: ${x.length}`);let b=[];if(i.gpuTextures=b,s.textures&&s.images){if(s.textures.length>e.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${e.maxTextures}). Found: ${s.textures.length}`);for(let h=0;h<s.textures.length;h++){let E=s.textures[h],A=s.images[E.source];if(A){let f=n.createTexture();if(n.bindTexture(3553,f),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),A.bufferView!==void 0){let N=s.bufferViews[A.bufferView],P=l.slice(N.byteOffset||0,(N.byteOffset||0)+N.byteLength),K=new Blob([P],{type:A.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(K).then(S=>{n.bindTexture(3553,f),n.texImage2D(3553,0,6408,6408,5121,S),n.generateMipmap(3553),r?.()}).catch(()=>{})}else if(A.uri){let N=dt(A.uri);if(N){let P=new Image;P.crossOrigin="anonymous",P.referrerPolicy="no-referrer",P.onload=()=>{n.bindTexture(3553,f),n.texImage2D(3553,0,6408,6408,5121,P),n.generateMipmap(3553),r?.()},P.src=N}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",A.uri)}b.push(f)}else b.push(null)}}let v=[1/0,1/0,1/0],y=[-1/0,-1/0,-1/0],w=0,T=0;for(let h=0;h<x.length;h++){let E=x[h],A=s.meshes[E.meshIdx],f=E.nodeIdx>=0?d[E.nodeIdx]:X(),N=new Float32Array(9);ce(N,f);let P={name:E.node.name||A.name||`Mesh_${E.meshIdx}`,nodeIndex:E.nodeIdx,transform:f,normalMatrix:N,primitives:[],extras:E.node.extras||A.extras};i.mesh=P;let K=E.node?.extensions?.EXT_mesh_gpu_instancing;if(K&&K.attributes&&typeof K.attributes=="object"){let S=K.attributes,U=S.TRANSLATION!==void 0?s.accessors?.[S.TRANSLATION]:null,k=S.ROTATION!==void 0?s.accessors?.[S.ROTATION]:null,Z=S.SCALE!==void 0?s.accessors?.[S.SCALE]:null,J=S._COLOR_0!==void 0?s.accessors?.[S._COLOR_0]:null,B=Number(U?.count??k?.count??Z?.count??0);if(!Number.isFinite(B)||B<0||B>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${B}`);if(B>0){let z=(I,W)=>{if(!I||I.bufferView===void 0||!s.bufferViews?.[I.bufferView])return null;let ne=I.componentType??5126,ae=j=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${j})`),null);if(ne!==5120&&ne!==5121&&ne!==5122&&ne!==5123&&ne!==5126)return ae(`componentType ${ne}`);if(!(Number(I.count)>=B))return ae(`count ${I.count} < ${B}`);let C=null;try{C=Ee(s,l,{...I,count:B},W)}catch{return ae("out of bounds")}return!C||!C.every(Number.isFinite)?ae("non-finite value"):C},D=z(U,3),se=z(k,4),H=z(Z,3),ie=J?.type==="VEC4"?4:3,re=z(J,ie),oe=new Float32Array(B*16),le=X();for(let I=0;I<B;I++){let W=D?[D[I*3],D[I*3+1],D[I*3+2]]:[0,0,0],ne=se?[se[I*4],se[I*4+1],se[I*4+2],se[I*4+3]]:[0,0,0,1],ae=H?[H[I*3],H[I*3+1],H[I*3+2]]:[1,1,1];Se(le,ne,W,ae),oe.set(le,I*16)}if(P.instanceMatrices=oe,re){let I=new Float32Array(B*3);for(let W=0;W<B;W++)I[W*3]=re[W*ie],I[W*3+1]=re[W*ie+1],I[W*3+2]=re[W*ie+2];P.instanceColors=I}}}for(let S of A.primitives||[]){if(S.extensions?.KHR_draco_mesh_compression){let C=me("draco");C&&C.decodePrimitive(s,S,l)}let U=[],k=n.createVertexArray();i.vao=k,i.buffers=U,n.bindVertexArray(k);let Z=pt(n,P,U),J=s.accessors[S.attributes.POSITION],B=Number(J?.count??0);if(!Number.isFinite(B)||B<0||w+B>e.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${e.maxVertices}).`);if(w+=B,J?.min&&J?.max){let C=j=>{for(let G=0;G<3;G++){let Q=j[12+G],ue=j[12+G];for(let he=0;he<3;he++){let ge=j[he*4+G]*J.min[he],ve=j[he*4+G]*J.max[he];Q+=ge<ve?ge:ve,ue+=ge>ve?ge:ve}Q<v[G]&&(v[G]=Q),ue>y[G]&&(y[G]=ue)}};if(P.instanceMatrices&&P.instanceMatrices.length>=16){let j=P.instanceMatrices.length>>4,G=X();for(let Q=0;Q<j;Q++){let ue=P.instanceMatrices.subarray(Q*16,Q*16+16);ee(G,f,ue),C(G)}}else C(f)}let z=Ce(n,s,l,S.attributes.POSITION,0,3,U);Ce(n,s,l,S.attributes.NORMAL,1,3,U),Ce(n,s,l,S.attributes.TEXCOORD_0,2,2,U,ft(s,S));let D=0,se=5123,H=null;if(S.indices!==void 0){let C=s.accessors[S.indices],G=(s.bufferViews[C.bufferView].byteOffset||0)+(C.byteOffset||0);if(D=Number(C.count??0),!Number.isFinite(D)||D<0||T+D>e.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${e.maxIndices}).`);T+=D,se=C.componentType===5125?5125||5125:5123||5123;let Q=n.createBuffer();U.push(Q),n.bindBuffer(34963,Q),C.componentType===5125?(H=new Uint32Array(l,G,C.count),n.bufferData(34963,H,35044)):C.componentType===5121?(H=Uint16Array.from(new Uint8Array(l,G,C.count)),n.bufferData(34963,H,35044)):(H=G%2===0?new Uint16Array(l,G,C.count):new Uint16Array(l.slice(G,G+C.count*2)),n.bufferData(34963,H,35044))}else D=J.count;let ie={};for(let C of Y)if(C.onBuildPrimitiveVAO){let j=C.onBuildPrimitiveVAO(n,k,S,s,l);j&&(ie[C.name]=j)}n.bindVertexArray(null);let re=s.materials&&S.material!==void 0?s.materials[S.material]:null,{program:oe,uniforms:le}=$e(n,S,re),I=Ze(re,b),W=!!(re?.extensions?.KHR_materials_transmission||ie.materials?.isTransmissive),ne=S.extensions?.KHR_materials_variants?.mappings,ae=Array.isArray(ne)?ne.filter(C=>C&&typeof C.material=="number"&&Array.isArray(C.variants)).map(C=>({material:C.material|0,variants:C.variants.map(j=>Number(j)|0)})):void 0;P.primitives.push({vao:k,instanced:Z,indexCount:D,indexType:se,...I,positions:z,indices:H,buffers:U,materialIndex:S.material,defaultMaterialIndex:S.material,variantMappings:ae,primitiveDef:S,programCache:new Map([[S.material??-1,{program:oe,uniforms:le}]]),pluginData:ie,customProgram:oe,customUniforms:le,isTransmissive:W})}a.push(P)}isFinite(v[0])||(v=[-1,-1,-1]),isFinite(y[0])||(y=[1,1,1]);let M=[(v[0]+y[0])/2,(v[1]+y[1])/2,(v[2]+y[2])/2],p=y[0]-v[0],R=y[1]-v[1],_=y[2]-v[2],L=Math.max(Math.hypot(p,R,_)/2,.5),O=[v[0],v[1],v[2]],V=[y[0],y[1],y[2]],F=t.animations;if(!F){for(let h of Y)if(h.onParseGLB?.(t),t.animations){F=t.animations;break}}return F||(F=[]),{meshes:a,bounds:{center:M,radius:L,min:O,max:V},lights:g,animations:F,worldMatrices:d,gpuTextures:b,availableVariants:c}}function fe(n){let t=n.customTarget||n.bounds.center,e=n.currDistance*Math.cos(n.currPhi);return[t[0]+e*Math.sin(n.currTheta),t[1]+n.currDistance*Math.sin(n.currPhi),t[2]+e*Math.cos(n.currTheta)]}var te=class{constructor(t,e,r){this.supportsInstanceOffsets=!0;this.meshes=[];this.backdropMeshes=[];this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]};this.lights=[];this.modelRootMatrix=X();this.clearColor=[0,0,0,0];this.envIntensity=1;this.exposure=1;this.shadowIntensity=0;this.shadowSoftness=.5;this.toneMapping="neutral";this.environmentTexture=null;this.animations=[];this.currentClip=null;this.animationTime=0;this.isPlayingAnimation=!1;this.autoplay=!1;this.animationName="";this.gpuTextures=[];this.availableVariants=[];this.activeVariantName=null;this.gltf=null;this.worldMatrices=[];this.initialNodeTransforms=[];this.projMatrix=X();this.viewMatrix=X();this.activeViewMatrix=null;this.modelMatrix=X();this.mvpMatrix=X();this.normalMatrix=new Float32Array(9);this.initialTheta=.6;this.initialPhi=.35;this.initialDistance=null;this.customDistance=!1;this.distanceMode="auto";this.initialCustomTarget=null;this.customTarget=null;this.fov=Math.PI/4;this.minTheta=-1/0;this.maxTheta=1/0;this.minPhi=-Math.PI*.48;this.maxPhi=Math.PI*.48;this.minDistanceLimit=null;this.maxDistanceLimit=null;this.activePointers=new Map;this.isPanning=!1;this.targetTheta=.6;this.currTheta=.6;this.targetPhi=.35;this.currPhi=.35;this.targetDistance=3;this.currDistance=3;this.autoRotate=!1;this.autoRotateSpeed=Math.PI/6;this.autoRotateDelay=3e3;this.lastInteractionTime=-1/0;this.turntableRotation=0;this.isPointerDown=!1;this.interactive=!0;this.skyboxTexture=null;this.lastPointerX=0;this.lastPointerY=0;this.totalDragDist=0;this.selectedMeshName="";this.pickFbo=null;this.pickTexture=null;this.pickDepth=null;this.pickFboWidth=0;this.pickFboHeight=0;this.animFrameId=null;this.isVisible=!0;this.xrSessionActive=!1;this.lastTime=0;this.lastReportedTheta=-999;this.lastReportedPhi=-999;this.lastReportedZoom=-999;this.boundPointerDown=null;this.boundPointerMove=null;this.boundPointerUp=null;this.boundWheel=null;this.boundKeyDown=null;this.boundContextMenu=null;this.boundSetCamera=null;this.boundResetCamera=null;this.contextLost=!1;this.lastGlbData=null;this.boundContextLost=null;this.boundContextRestored=null;this.stereoSBS=!1;this.renderErrorReported=!1;this.xrDepthState={enabled:!1,texture:null,uvTransform:X(),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 a=t.querySelector("canvas");a||(a=document.createElement("canvas"),a.style.width="100%",a.style.height="100%",a.style.display="block",a.style.touchAction="none",t.prepend(a)),i=a}this.canvas=i,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let o=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!o:o&&(this.autoRotate=!1),this.opts.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=this.opts.autoRotateSpeed),this.opts.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(this.opts.autoRotateDelay)||0)),this.opts.exposure!==void 0&&(this.exposure=Le(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=de(this.opts.toneMapping)),this.opts.autoplay!==void 0&&(this.autoplay=this.opts.autoplay),this.opts.animationName!==void 0&&(this.animationName=this.opts.animationName),this.opts.variantName!==void 0&&(this.activeVariantName=this.opts.variantName||null),this.opts.fieldOfView!==void 0&&(this.fov=this.opts.fieldOfView*Math.PI/180),this.opts.distanceMode!==void 0&&(this.distanceMode=this.opts.distanceMode),this.opts.cameraTarget!==void 0&&(this.setTarget(this.opts.cameraTarget[0],this.opts.cameraTarget[1],this.opts.cameraTarget[2]),this.initialCustomTarget=[...this.opts.cameraTarget]),(this.opts.minCameraOrbit||this.opts.maxCameraOrbit)&&this.setOrbitLimits({minTheta:this.opts.minCameraOrbit?.theta,maxTheta:this.opts.maxCameraOrbit?.theta,minPhi:this.opts.minCameraOrbit?.phi,maxPhi:this.opts.maxCameraOrbit?.phi,minDistance:this.opts.minCameraOrbit?.distance,maxDistance:this.opts.maxCameraOrbit?.distance});let l=i.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!l)throw new Error("WebGL2 not supported");this.gl=l,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(t,e){ut(t,e)}static getDecoder(t){return me(t)}setupContextLossHandling(){let t=this.canvas;typeof t?.addEventListener=="function"&&(this.boundContextLost=e=>{e.preventDefault?.(),this.contextLost=!0,this.stop()},this.boundContextRestored=()=>this.restoreContext(),t.addEventListener("webglcontextlost",this.boundContextLost),t.addEventListener("webglcontextrestored",this.boundContextRestored))}initGlState(){let t=this.gl,e=Ye();this.renderProg=ye(t,je,e.fs),this.pickProg=ye(t,ht,mt),this.uRender=De(t,this.renderProg,e.uniforms),this.uPick=De(t,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let t=this.gl;this.contextLost=!1,this.initGlState();for(let e of Y)e.onContextRestored?.(t,this);this.meshes=[],this.gpuTextures=[],this.environmentTexture=null,this.lastGlbData&&this.loadGLBData(this.lastGlbData,this.lastLimits),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}setupPickingFbo(){let t=this.gl;if(typeof t.createFramebuffer!="function")return;this.pickFbo=t.createFramebuffer(),this.pickTexture=t.createTexture(),this.pickDepth=t.createRenderbuffer();let e=Math.max(1,this.canvas.width),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){this.lastGlbData=t,this.lastLimits=e;let{meshes:r,bounds:i,lights:s,animations:o,worldMatrices:l,gpuTextures:a,availableVariants:c}=He(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.gpuTextures=a||[],this.availableVariants=c||[],this.gltf=t.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(t.gltf?.nodes))for(let m of t.gltf.nodes)this.initialNodeTransforms.push({t:m.translation?[m.translation[0],m.translation[1],m.translation[2]]:[0,0,0],r:m.rotation?[m.rotation[0],m.rotation[1],m.rotation[2],m.rotation[3]]:[0,0,0,1],s:m.scale?[m.scale[0],m.scale[1],m.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let m of Y)m.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.gltf?.extras?.exposure??t.gltf?.asset?.extras?.exposure;u!==void 0&&(this.exposure=Le(u));let d=t.environmentIntensity??t.gltf?.extras?.environmentIntensity??t.gltf?.asset?.extras?.environmentIntensity;d!==void 0&&(this.envIntensity=Math.max(0,Number(d)||0)),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(t){this.loadGLBData(ze(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(pe(t))}setBackdropGLB(t,e){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!t){this.update(0),this.render();return}let r=pe(t),{meshes:i}=He(this.gl,r,Ke,()=>this.render());if(e)for(let s of i)s.transform[12]+=e[0],s.transform[13]+=e[1],s.transform[14]+=e[2],ce(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),ce(r.normalMatrix,r.transform))}}bindLights(t=this.uRender){let e=this.gl,r=[.28,.28,.28],i=[],s=[],o=[],l=[];for(let a of this.lights){let c=a.color||[1,1,1],u=a.intensity!==void 0?a.intensity:1;if(a.type==="ambient")r=[c[0]*u,c[1]*u,c[2]*u];else if(a.type==="directional"&&i.length<6){let d=a.direction||[.5,1,.8];i.push(d[0],d[1],d[2]),s.push(c[0]*u,c[1]*u,c[2]*u)}else if(a.type==="point"&&o.length<6){let d=a.position||[0,0,0];o.push(d[0],d[1],d[2]),l.push(c[0]*u,c[1]*u,c[2]*u)}}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.exposure=Le(t)}getExposure(){return this.exposure}setShadow(t,e){this.shadowIntensity=Math.max(0,Math.min(1,Number(t)||0)),e!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(e)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(t){this.toneMapping=de(t)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(t){for(let e of Y)if(e.setEnvironmentImage){await e.setEnvironmentImage(this,t);return}}async setSkyboxImage(t){for(let e of Y)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(u=>u.primitives.filter(d=>d.materialIndex===r||t.length===1&&d.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,a=s?s.roughness:e.pbrMetallicRoughness?.roughnessFactor??.5,c={baseColorFactor:o,metallicFactor:l,roughnessFactor:a,setBaseColorFactor:u=>{let d=[u[0],u[1],u[2],u[3]??1];c.baseColorFactor=d,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.baseColorFactor=d);for(let m of i)m.baseColor=d;this.render()},setMetallicFactor:u=>{c.metallicFactor=u,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.metallicFactor=u);for(let d of i)d.metallic=u;this.render()},setRoughnessFactor:u=>{c.roughnessFactor=u,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.roughnessFactor=u);for(let d of i)d.roughness=u;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)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(t){let e=this.applyVariantMaterial(t);return e&&this.gl&&this.render(),e}applyVariantMaterial(t){let e=t===null||t==="",r=-1;if(e)this.activeVariantName=null;else{if(r=this.availableVariants.indexOf(t),r<0)return!1;this.activeVariantName=t}let i=this.gltf?.materials;if(!Array.isArray(i))return e;for(let s of this.meshes)for(let o of s.primitives){let l=o.defaultMaterialIndex;if(!e&&Array.isArray(o.variantMappings)){for(let c of o.variantMappings)if(Array.isArray(c.variants)&&c.variants.includes(r)){l=c.material;break}}let a=l!==void 0?i[l]:void 0;o.materialIndex=a?l:void 0,Object.assign(o,Ze(a,this.gpuTextures)),this.applyPrimitiveProgram(o,o.materialIndex,a??null)}return!0}applyPrimitiveProgram(t,e,r){if(!this.gl||!t.primitiveDef)return;t.programCache??(t.programCache=new Map);let i=e??-1,s=t.programCache.get(i);s||(s=$e(this.gl,{...t.primitiveDef,material:e},r),t.programCache.set(i,s)),t.customProgram=s.program,t.customUniforms=s.uniforms,t.pluginData&&(t.pluginData.materials=t.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(t){this.autoplay=t,t?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(t){this.animationName=t,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(t)}evaluateAnimation(t){for(let e of Y)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=X();ee(r,this.projMatrix,this.viewMatrix);let[i,s,o]=t,l=e?e[0]:0,a=e?e[1]:0,c=e?e[2]:0,u=this.modelRootMatrix;u&&(i=u[0]*t[0]+u[4]*t[1]+u[8]*t[2]+u[12],s=u[1]*t[0]+u[5]*t[1]+u[9]*t[2]+u[13],o=u[2]*t[0]+u[6]*t[1]+u[10]*t[2]+u[14],e&&(l=u[0]*e[0]+u[4]*e[1]+u[8]*e[2],a=u[1]*e[0]+u[5]*e[1]+u[9]*e[2],c=u[2]*e[0]+u[6]*e[1]+u[10]*e[2]));let d=r[0]*i+r[4]*s+r[8]*o+r[12],m=r[1]*i+r[5]*s+r[9]*o+r[13],x=r[2]*i+r[6]*s+r[10]*o+r[14],g=r[3]*i+r[7]*s+r[11]*o+r[15];if(g<=1e-4)return{x:0,y:0,z:1,visible:!1};let b=d/g,v=m/g,y=x/g,w=this.canvas.getBoundingClientRect(),T=w.width||this.canvas.clientWidth||this.canvas.width||300,M=w.height||this.canvas.clientHeight||this.canvas.height||150,p=(b*.5+.5)*T,R=(-v*.5+.5)*M,_=b>=-1.1&&b<=1.1&&v>=-1.1&&v<=1.1&&y>=-1&&y<=1;if(_&&e){let[L,O,V]=fe(this),F=[i-L,s-O,o-V];l*F[0]+a*F[1]+c*F[2]>.05&&(_=!1)}return{x:p,y:R,z:y,visible:_}}setSelectedMesh(t){this.selectedMeshName=t||""}getSelectedMesh(){return this.selectedMeshName}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]],a=this.customTarget?[...this.customTarget]:[...this.bounds.center],c=this.currDistance/Math.max(t.clientHeight||300,1)*1.5;a[0]+=(-i*o[0]+s*l[0])*c,a[1]+=(-i*o[1]+s*l[1])*c,a[2]+=(-i*o[2]+s*l[2])*c,this.customTarget=a}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.boundContextLost&&(t.removeEventListener("webglcontextlost",this.boundContextLost),this.boundContextLost=null),this.boundContextRestored&&(t.removeEventListener("webglcontextrestored",this.boundContextRestored),this.boundContextRestored=null),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),a=i.height>0?Math.floor((e-i.top)*(o/i.height)):Math.floor(e);return this.performMeshPick(l,a,!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=X();ee(l,this.projMatrix,this.viewMatrix);let a=[],c=Math.max(0,Math.min(s-1,t)),u=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 _=0;_<this.meshes.length;_++){let L=this.meshes[_];if(L.visible===!1||L.isPluginMesh)continue;let O=_+1,V=(O&255)/255,F=(O>>8&255)/255,h=(O>>16&255)/255;i.uniform4f(this.uPick.uColorId,V,F,h,1),ee(this.modelMatrix,this.modelRootMatrix,L.transform);let E=L.instanceMatrices;if(E&&E.length>=16){let A=E.length>>4,f=X();for(let N of L.primitives){i.bindVertexArray(N.vao);for(let P=0;P<A;P++)ee(f,this.modelMatrix,E.subarray(P*16,P*16+16)),ee(this.mvpMatrix,l,f),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),Re(i,N)}}else{ee(this.mvpMatrix,l,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let A of L.primitives)i.bindVertexArray(A.vao),Re(i,A)}}let p=new Uint8Array(4);i.readPixels(c,u,1,1,6408,5121,p),i.bindFramebuffer(36160,null);let R=p[0]+(p[1]<<8)+(p[2]<<16);R>0&&R<=this.meshes.length&&(a=[this.meshes[R-1]])}a.length===0&&(a=this.meshes.filter(p=>p.visible!==!1));let d=null,m=1/0,x=[0,0,0],g=[0,1,0],[b,v,y]=fe(this),w=X();for(let p of a){ee(w,this.modelRootMatrix,p.transform);let R=p.instanceMatrices,_=R&&R.length>=16?R.length>>4:1;for(let L=0;L<_;L++){R&&R.length>=16?ee(this.modelMatrix,w,R.subarray(L*16,L*16+16)):this.modelMatrix.set(w),ee(this.mvpMatrix,l,this.modelMatrix);let O=X();if(!Ge(O,this.mvpMatrix))continue;let V=(c+.5)/s*2-1,F=(u+.5)/o*2-1,h=[0,0,0],E=[0,0,0];Pe(h,V,F,-1,O),Pe(E,V,F,1,O);let A=E[0]-h[0],f=E[1]-h[1],N=E[2]-h[2],P=Math.hypot(A,f,N)||1,K=A/P,S=f/P,U=N/P,k={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((J=>{for(let B of p.primitives){if(!B.positions)continue;let z=B.positions,D=B.indices,se=Math.floor(D?D.length/3:z.length/9);for(let H=0;H<se;H++){let ie=D?D[H*3]:H*3,re=D?D[H*3+1]:H*3+1,oe=D?D[H*3+2]:H*3+2;Oe(h[0],h[1],h[2],K,S,U,z[ie*3],z[ie*3+1],z[ie*3+2],z[re*3],z[re*3+1],z[re*3+2],z[oe*3],z[oe*3+1],z[oe*3+2],k,J)}}})(1e-4),isFinite(k.distance)){let J=k.point[0],B=k.point[1],z=k.point[2],D=this.modelMatrix,se=D[0]*J+D[4]*B+D[8]*z+D[12],H=D[1]*J+D[5]*B+D[9]*z+D[13],ie=D[2]*J+D[6]*B+D[10]*z+D[14],re=se-b,oe=H-v,le=ie-y,I=Math.hypot(re,oe,le);if(I<m){ce(this.normalMatrix,this.modelMatrix);let W=this.normalMatrix,ne=k.normal[0],ae=k.normal[1],C=k.normal[2],j=W[0]*ne+W[3]*ae+W[6]*C,G=W[1]*ne+W[4]*ae+W[7]*C,Q=W[2]*ne+W[5]*ae+W[8]*C,ue=Math.hypot(j,G,Q)||1;j/=ue,G/=ue,Q/=ue,j*re+G*oe+Q*le>0&&(j=-j,G=-G,Q=-Q),d=p,m=Math.round(I*1e3)/1e3,x=[Math.round(se*1e3)/1e3,Math.round(H*1e3)/1e3,Math.round(ie*1e3)/1e3],g=[Math.round(j*1e3)/1e3,Math.round(G*1e3)/1e3,Math.round(Q*1e3)/1e3]}}}}if(!d)return null;let M={meshIndex:this.meshes.indexOf(d),meshName:d.name,nodeIndex:d.nodeIndex,distance:m,hitPoint:x,normal:g,screenX:t,screenY:e};if(r){for(let p of Y)p.onMeshSelect?.(this,M);this.opts.onMeshClick&&this.opts.onMeshClick(M),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:M}))}return M}mapStereoPickX(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);Te(this.projMatrix,this.fov,t,.1,e);let r=this.customTarget||this.bounds.center;Me(this.viewMatrix,fe(this),r,[0,1,0]),ee(this.mvpMatrix,this.projMatrix,this.viewMatrix),ce(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 Y)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 Y)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 Y)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 Y)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,a=t?.projectionMatrix||this.projMatrix,c=t?.transform?.position,u=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:a,eyePos:u,viewport:i,eye:t?.eye||"none",clear:o>0?!1:t?.eye!=="right",isAR:s})}render(t){if(this.contextLost)return;if(!t&&this.stereoSBS){let T=Math.max(2,this.canvas.width||2),M=Math.max(1,this.canvas.height||1),p=Math.max(1,Math.floor(T*.5)),R=Math.max(1,T-p),_=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),L=this.customTarget||this.bounds.center,[O,V,F]=fe(this),h=Math.cos(this.currTheta),E=-Math.sin(this.currTheta),A=.032,f=X(),N=X(),P=[O-h*A,V,F-E*A],K=[L[0]-h*A*.25,L[1],L[2]-E*A*.25];Te(f,this.fov,p/M,.1,_),Me(N,P,K,[0,1,0]);let S=X(),U=X(),k=[O+h*A,V,F+E*A],Z=[L[0]+h*A*.25,L[1],L[2]+E*A*.25];Te(S,this.fov,R/M,.1,_),Me(U,k,Z,[0,1,0]),this.render({viewMatrix:N,projMatrix:f,eyePos:P,viewport:[0,0,p,M],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:U,projMatrix:S,eyePos:k,viewport:[p,0,R,M],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,T,M);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=X(),a=t?.viewMatrix??this.viewMatrix;this.activeViewMatrix=a,ee(l,t?.projMatrix??this.projMatrix,a);let c=$().xrDepthShader,u=ot(this.toneMapping),[d,m,x]=t?t.eyePos:fe(this);for(let T of Y)T.onBeforeDrawScene?.(this,e,l,[d,m,x],u);let g=t?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&g===0)return;let b=t?.eye||"none",v=!1,y=g>0?[...this.backdropMeshes,...this.meshes]:this.meshes,w=T=>{for(let M=0;M<y.length;M++){let p=y[M];if(p.visible===!1)continue;let R=this.selectedMeshName!==""&&p.name===this.selectedMeshName;M<g||p.worldSpace===!0||p.name==="__xr_reticle__"?this.modelMatrix.set(p.transform):ee(this.modelMatrix,this.modelRootMatrix,p.transform),ee(this.mvpMatrix,l,this.modelMatrix),ce(p.normalMatrix,this.modelMatrix);let _=p.extras?.xr?.stereo||p.userData?.xr?.stereo,L=0,O=0,V=1,F=1;_==="sbs"?(V=.5,L=b==="right"?.5:0):_==="ou"&&(F=.5,O=b==="right"?.5:0);for(let h of p.primitives){let E=!!h.isTransmissive;if(!T&&E){v=!0;continue}if(T&&!E)continue;let A=h.customProgram||this.renderProg,f=h.customUniforms||this.uRender;e.useProgram(A),e.vertexAttrib3f(3,0,0,0),f.uInstanced&&e.uniform1i(f.uInstanced,0),e.uniform1i(f.uToneMapping,u),e.uniform1f(f.uEnvIntensity,this.envIntensity),f.uExposure&&e.uniform1f(f.uExposure,this.exposure),e.uniform3f(f.uCameraPos,d,m,x),e.uniform1f(f.uEmissive,R?1:0),e.uniformMatrix4fv(f.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(f.uModel,!1,this.modelMatrix),e.uniformMatrix3fv(f.uNormalMatrix,!1,p.normalMatrix),f.uUvTransform&&e.uniform4f(f.uUvTransform,L,O,V,F),f.uViewportSize&&e.uniform2f(f.uViewportSize,Math.max(1,s),Math.max(1,o)),c?.bind(e,f,this.xrDepthState,a,[r,i,Math.max(1,s),Math.max(1,o)]),this.environmentTexture?(e.activeTexture(33988),e.bindTexture(3553,this.environmentTexture),e.uniform1i(f.uEnvironmentMap,4),e.uniform1i(f.uHasEnvironmentMap,1)):e.uniform1i(f.uHasEnvironmentMap,0),this.bindLights(f),f.uSectionEnabled&&e.uniform1i(f.uSectionEnabled,0);for(let P of Y)P.onBeforeDrawPrimitive?.(e,A,h,p,this.worldMatrices||[],this.gltf);e.uniform4fv(f.uBaseColor,h.baseColor),e.uniform1f(f.uMetallic,h.metallic),e.uniform1f(f.uRoughness,h.roughness),f.uClearcoat&&e.uniform2f(f.uClearcoat,h.clearcoat??0,h.clearcoatRoughness??.04),h.texture?(e.activeTexture(33984),e.bindTexture(3553,h.texture),e.uniform1i(f.uBaseColorTexture,0),e.uniform1i(f.uHasTexture,1)):e.uniform1i(f.uHasTexture,0),h.metallicRoughnessTexture?(e.activeTexture(33985),e.bindTexture(3553,h.metallicRoughnessTexture),e.uniform1i(f.uMetallicRoughnessTexture,1),e.uniform1i(f.uHasMetallicRoughnessTexture,1)):e.uniform1i(f.uHasMetallicRoughnessTexture,0),h.normalTexture?(e.activeTexture(33986),e.bindTexture(3553,h.normalTexture),e.uniform1i(f.uNormalTexture,2),e.uniform1i(f.uHasNormalTexture,1),e.uniform1f(f.uNormalScale,h.normalScale)):e.uniform1i(f.uHasNormalTexture,0),h.occlusionTexture?(e.activeTexture(33987),e.bindTexture(3553,h.occlusionTexture),e.uniform1i(f.uOcclusionTexture,3),e.uniform1i(f.uHasOcclusionTexture,1),e.uniform1f(f.uOcclusionStrength,h.occlusionStrength)):e.uniform1i(f.uHasOcclusionTexture,0),e.bindVertexArray(h.vao);let N=p.instanceMatrices;if(h.instanceCount!==void 0)e.drawElementsInstanced(4,h.indexCount,h.indexType,0,h.instanceCount);else if(N&&N.length>=16&&h.instanced&&f.uInstanced&&f.uViewProj){let P=N.length>>4;e.uniform1i(f.uInstanced,1),e.uniformMatrix4fv(f.uViewProj,!1,l),h.indices?e.drawElementsInstanced(4,h.indexCount,h.indexType,0,P):e.drawArraysInstanced(4,0,h.indexCount,P),e.uniform1i(f.uInstanced,0)}else if(N&&N.length>=16){let P=N.length>>4,K=p.instanceColors,S=X(),U=new Float32Array(9),k=[h.baseColor[0],h.baseColor[1],h.baseColor[2],h.baseColor[3]];for(let Z=0;Z<P;Z++)ee(S,this.modelMatrix,N.subarray(Z*16,Z*16+16)),ee(this.mvpMatrix,l,S),ce(U,S),e.uniformMatrix4fv(f.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(f.uModel,!1,S),e.uniformMatrix3fv(f.uNormalMatrix,!1,U),K&&(k[0]=h.baseColor[0]*K[Z*3],k[1]=h.baseColor[1]*K[Z*3+1],k[2]=h.baseColor[2]*K[Z*3+2],k[3]=h.baseColor[3],e.uniform4fv(f.uBaseColor,k)),Re(e,h)}else Re(e,h)}}};if(w(!1),v){for(let T of Y)T.onBeforeTransmissivePass?.(e,this);w(!0)}for(let T of Y)T.onAfterRender?.(e,this,l,t?.eye??"none",[r,i,s,o],t?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(t,e){Je(this.gl,t,e)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let t=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let e of Y)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()}};te.registerPlugin=Be,te.getRegisteredPlugins=ke;var Ie=(n,t,e)=>({x:n,y:t,z:e,toString:()=>`${n}m ${t}m ${e}m`}),xt=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 q=class q extends xt{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){q.scriptRunner=e}static registerDecoder(e,r){te.registerDecoder(e,r)}static getDecoder(e){return te.getDecoder(e)}static registerAR(e){typeof e=="function"?q.arProvider={activateAR:e}:q.arProvider=e,typeof document<"u"&&document.querySelectorAll("three-live").forEach(i=>{i instanceof q&&i.updateARButtonVisibility()})}static isARSupported(){return!!q.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.loadModel(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 te.getRegisteredPlugins())i.onElementConnected?.(this)}disconnectedCallback(){for(let e of te.getRegisteredPlugins())e.onElementDisconnected?.(this);this.scriptHandle?.terminate(),this.scriptHandle=null,this.mutationObserver?.disconnect(),this.mutationObserver=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.activeXRSession?.stop?.().catch?.(()=>{}),this.activeXRSession=null,this.toastTimer&&clearTimeout(this.toastTimer),this.toastTimer=null,this.viewer?.destroy(),this.viewer=null,this.isModelLoaded=!1}attributeChangedCallback(e,r,i){if(r!==i){switch(e){case"src":i&&this.loadModel(i).catch(()=>{});break;case"camera-target":this.applyCameraTarget(i);break;case"min-camera-orbit":case"max-camera-orbit":this.applyOrbitLimits();break;case"field-of-view":this.applyFieldOfView(i);break;case"script-src":i&&this.loadScriptFromSrc(i).catch(()=>{});break;case"sandbox":case"allow-client-scripts":case"ios-src":break;case"poster":this.updatePoster(i);break;case"camera-orbit":this.applyCameraOrbit(i);break;case"selected-mesh":this.viewer&&i!==null&&this.viewer.setSelectedMesh(i);break;case"exposure":if(this.viewer&&i!==null){let s=parseFloat(i);isNaN(s)||this.viewer.setExposure(s)}break;case"shadow-intensity":case"shadow-softness":this.viewer&&this.viewer.setShadow(this.shadowIntensity,this.shadowSoftness);break;case"tone-mapping":this.viewer?.setToneMapping(de(i));break;case"environment-image":this.viewer&&this.viewer.setEnvironmentImage(i).catch(()=>{});break;case"skybox-image":this.viewer&&this.viewer.setSkyboxImage?.(i)?.catch?.(()=>{});break;case"camera-controls":{let s=this.cameraControls;this.viewer&&this.viewer.setInteractive?.(s),this.canvas&&(this.canvas.style.touchAction=s?"none":"auto");break}case"autoplay":this.viewer&&this.viewer.setAutoplay(i!==null&&i!=="false");break;case"animation-name":this.viewer&&i!==null&&this.viewer.setAnimationName(i);break;case"variant-name":this.viewer&&this.selectVariant(i);break;case"auto-rotate":this.viewer&&this.viewer.setAutoRotate(i!==null&&i!=="false");break;case"auto-rotate-delay":this.viewer&&this.viewer.setAutoRotateDelay(this.autoRotateDelay);break;case"rotation-per-second":this.viewer&&this.viewer.setAutoRotateSpeed(this.parseRotationPerSecond(i));break;case"ar":this.updateARButtonVisibility();break}for(let s of te.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")||q.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 q.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 de(this.getAttribute("tone-mapping"))}set toneMapping(e){this.setAttribute("tone-mapping",e)}get bloom(){return this.getFloatAttr("bloom",0)}set bloom(e){this.setAttribute("bloom",String(e))}get bloomThreshold(){return Ae(this.getAttribute("bloom-threshold"),.62)}set bloomThreshold(e){this.setAttribute("bloom-threshold",String(e))}get bloomRadius(){return Ae(this.getAttribute("bloom-radius"),.75)}set bloomRadius(e){this.setAttribute("bloom-radius",String(e))}get outlineSelected(){return this.getBoolAttr("outline-selected")}set outlineSelected(e){this.setBoolAttr("outline-selected",e)}get outlineColor(){return this.getAttr("outline-color")||"#38bdf8"}set outlineColor(e){this.setAttr("outline-color",e)}get environmentImage(){return this.getAttr("environment-image")}set environmentImage(e){this.setAttr("environment-image",e)}get skyboxImage(){return this.getAttr("skybox-image")}set skyboxImage(e){this.setAttr("skybox-image",e)}get autoplay(){return this.getBoolAttr("autoplay")}set autoplay(e){this.setBoolAttr("autoplay",e)}get animationName(){return this.getAttr("animation-name")}set animationName(e){this.setAttr("animation-name",e)}get availableAnimations(){return this.viewer?this.viewer.getAvailableAnimations():[]}get variantName(){return this.viewer?this.viewer.getVariantName():this.getAttr("variant-name")}set variantName(e){this.setAttr("variant-name",e)}get availableVariants(){return this.viewer?this.viewer.getAvailableVariants():[]}fireEvent(e,r){this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:r}))}setSlotVisible(e,r){let i=typeof this.querySelector=="function"?this.querySelector(`[slot="${e}"]`):null;i&&(i.hidden=!r,i.style&&(i.style.display=r?"":"none"))}emitError(e,r="script"){this.setSlotVisible("error",!0),this.fireEvent("error",{error:e}),this.fireEvent("three-error",{error:e,message:e?.message||String(e),stage:r})}selectVariant(e){if(!this.viewer)return!1;let r=this.viewer.selectVariant(e);return r&&this.fireEvent("variant-applied",{variantName:this.viewer.getVariantName()}),r}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():Ie(0,0,0)}getFieldOfView(){return this.viewer?this.viewer.getFieldOfView():45}jumpCameraToGoal(){this.viewer?.jumpCameraToGoal()}toDataURL(e,r){return this.viewer?.render?.(),this.canvas?this.canvas.toDataURL(e,r):""}toBlob(e){return this.viewer?.render?.(),new Promise((r,i)=>{if(!this.canvas||typeof this.canvas.toBlob!="function"){i(new Error("Canvas toBlob is not supported in this environment."));return}this.canvas.toBlob(s=>{s?r(s):i(new Error("Failed to capture canvas blob."))},e?.mimeType,e?.qualityArgument)})}positionAndNormalFromPoint(e,r){let i=this.viewer?.raycastFromScreenPoint(e,r);if(!i)return null;let[s,o,l]=i.hitPoint||i.point,[a,c,u]=i.normal;return{position:Ie(s,o,l),normal:Ie(a,c,u)}}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 a=await fetch(e);if(!a.ok)throw new Error(`Failed to load 3D model from "${e}": HTTP ${a.status}`);i=await a.arrayBuffer()}else i=e;let s=pe(i);this.viewer.loadGLBData(s,r),this.currentModel=s,this.currentModelLimits=r,this.isModelLoaded=!0,this.hidePoster(),this.setSlotVisible("error",!1),this.updateHotspots();let o=this.getAttribute("selected-mesh");o&&this.viewer.setSelectedMesh(o);let l=this.getAttribute("variant-name");l&&this.selectVariant(l),this.fireEvent("load",{model:s}),this.fireEvent("three-load",{model:s,source:typeof e=="string"?"src":"model"})}catch(i){throw this.emitError(i,"load"),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);let s=()=>{i&&(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)")};typeof requestAnimationFrame<"u"?requestAnimationFrame(s):s(),this.toastTimer=setTimeout(()=>{i&&(i.style.opacity="0",i.style.transform="translateX(-50%) translateY(10px)"),this.toastTimer=null},r)}async activateAR(){this.activeXRSession?.isSessionActive?.()&&(await this.activeXRSession.stop().catch(()=>{}),this.activeXRSession=null);let e=(s,o=s.message)=>{throw this.fireEvent("ar-status",{status:"failed",error:s}),this.showToast(o,6e3),s};this.currentModel||e(new Error("No 3D model is loaded in <three-live>.")),q.arProvider||e(new Error("AR module not bundled. Use the default 'three-live' bundle or call ThreeLiveElement.registerAR()."));let r=this.getAttribute("ios-src"),i=(this.getAttribute("ar-modes")||"").split(/\s+/).filter(Boolean);try{this.fireEvent("ar-status",{status:"session-started"});let s=await q.arProvider.activateAR({model:r||this.currentModel,glbUrl:typeof this.currentModel=="string"?this.currentModel:void 0,view:this.viewer||void 0,element:this,preferredModes:i.length>0?i:void 0,arScale:this.arScale,arPlacement:this.arPlacement,webXROptions:{onExit:()=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"not-presenting"})},onError:o=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"failed",error:o}),this.showToast(`AR error: ${o.message}`,6e3)}}});if(s.success){s.session&&(this.activeXRSession=s.session);let o=s.mode==="quick-look"?"Opening Apple AR Quick Look...":s.mode==="scene-viewer"?"Opening Google Scene Viewer...":s.mode==="webxr"?"WebXR AR session started.":"";o&&this.showToast(o)}else{let o=typeof navigator<"u"&&navigator.userAgent||"",l=/Macintosh/i.test(o)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1),a=/Android|iPhone|iPad|iPod/i.test(o),c=s.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.";if(l&&!a&&typeof document<"u"&&this.currentModel&&q.arProvider.createUSDZBlob)try{let u=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:q.arProvider.createUSDZBlob(this.currentModel),d=URL.createObjectURL(u),m=document.createElement("a");m.href=d,m.download="three_live_model.usdz",document.body.appendChild(m),m.click(),document.body.removeChild(m),setTimeout(()=>URL.revokeObjectURL(d),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(c,6e3)}else this.showToast(c,6e3);s.error&&this.fireEvent("ar-status",{status:"failed",error:s.error})}return s}catch(s){return this.activeXRSession=null,e(s,`AR error: ${s.message||String(s)}`)}}setupDOM(){let e=this.querySelector("canvas");e||(e=document.createElement("canvas"),e.style.cssText=`width:100%;height:100%;display:block;touch-action:${this.cameraControls?"none":"auto"};outline:none`,this.appendChild(e)),this.canvas=e,typeof e.addEventListener=="function"&&!e.__tlCtxBound&&(e.__tlCtxBound=!0,e.addEventListener("webglcontextlost",i=>this.fireEvent("three-context-lost",{originalEvent:i})),e.addEventListener("webglcontextrestored",i=>this.fireEvent("three-context-restored",{originalEvent:i}))),this.setSlotVisible("error",!1),this.isModelLoaded||this.setSlotVisible("poster",!0);let r=this.getAttribute("poster");r&&this.updatePoster(r),this.createARButton(),typeof MutationObserver<"u"&&!this.mutationObserver&&(this.mutationObserver=new MutationObserver(()=>{this.updateARButtonVisibility()}),this.mutationObserver.observe(this,{childList:!0}))}initViewer(){if(!this.canvas)return;let 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 te(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,variantName:this.getAttribute("variant-name")||void 0,fieldOfView:l,cameraTarget:o,minCameraOrbit:i,maxCameraOrbit:s,onMeshClick:c=>{this.fireEvent("meshclick",c)},onCameraChange:c=>{this.updateHotspots();for(let u of te.getRegisteredPlugins())u.onCameraChange?.(this.viewer,this);this.fireEvent("camera-change",c)}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let a=this.getAttribute("camera-orbit");a&&this.applyCameraOrbit(a),this.currentModel&&this.loadModelWithLimits(this.currentModel,this.currentModelLimits)}setupResizeObserver(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>{this.viewer&&(this.viewer.resize(),this.viewer.render(),this.updateHotspots())}),this.resizeObserver.observe(this))}updatePoster(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.cssText="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity .35s ease-out;pointer-events:none;z-index:1",this.appendChild(this.posterEl)),this.posterEl.src=e,this.isModelLoaded||(this.posterEl.style.opacity="1")}}hidePoster(){this.setSlotVisible("poster",!1),this.posterEl&&(this.posterEl.style.opacity="0",setTimeout(()=>{this.isModelLoaded&&this.posterEl&&(this.posterEl.remove(),this.posterEl=null)},400))}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");for(let[l,a]of[["width","20"],["height","20"],["viewBox","0 0 24 24"],["fill","none"],["stroke","currentColor"],["stroke-width","2"],["stroke-linecap","round"],["stroke-linejoin","round"]])s.setAttribute(l,a);s.style.marginRight="6px";let o=document.createElementNS(r,"path");o.setAttribute("d","M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16zM3.27 6.96 12 12.01l8.73-5.05M12 22.08V12"),s.appendChild(o),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")&&!!q.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=this.parseOrbitLimit(e);(r.theta!==void 0||r.phi!==void 0)&&this.viewer.setInitialCamera(r.theta,r.phi,r.distance)}}parseOrbitLimit(e){if(!e)return{};let[r,i,s]=e.trim().split(/\s+/),o=s&&s!=="auto"?parseFloat(s):NaN;return{theta:r&&r!=="auto"?this.parseFieldOfView(r):void 0,phi:i&&i!=="auto"?this.parseFieldOfView(i):void 0,distance:isNaN(o)?void 0:o}}applyOrbitLimits(){if(!this.viewer)return;let 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(parseFloat);return r.length>=3&&!r.some(isNaN)?[r[0],r[1],r[2]]:void 0}parseFieldOfView(e){if(!e)return;let r=parseFloat(e);return isNaN(r)?void 0:e.endsWith("rad")?r*180/Math.PI: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 te.getRegisteredPlugins())if(e.updateHotspotsForElement){e.updateHotspotsForElement(this,this.viewer);return}}runWithScriptRunner(e){let r=q.scriptRunner;if(!r){let i=new Error('Procedural script execution requires "three-live/full" or ThreeLiveElement.registerScriptRunner().');return this.showToast(i.message),this.emitError(i,"script"),Promise.reject(i)}return this.scriptHandle&&(this.scriptHandle.terminate(),this.scriptHandle=null),this.isModelLoaded=!1,this.viewer?.clearScene?.(),new Promise((i,s)=>{let o=!1;e(r,{onModelReady:a=>{this.loadModelWithLimits(a,qe).then(()=>{o||(o=!0,i(a))},c=>{let u=c instanceof Error?c.message:String(c);this.showToast(u),o||(o=!0,s(c))})},onUpdateTransforms:a=>this.viewer?.updateMeshTransforms(a),onError:a=>{this.showToast(a.message),this.emitError(a,"script"),o||(o=!0,s(a))},onToast:a=>this.showToast(a)}).then(a=>{a&&(this.scriptHandle=a)},a=>{a instanceof Error&&a.message&&this.showToast(a.message),o||(o=!0,s(a))})})}loadScriptFromSrc(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(!q.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(Fe);return this.showToast(Ne),this.emitError(r,"security"),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(e,this.sandbox,i,{allowClientScripts:!0}))}};q.observedAttributes=["src","ios-src","script-src","sandbox","allow-client-scripts","poster","camera-controls","camera-orbit","camera-target","min-camera-orbit","max-camera-orbit","field-of-view","selected-mesh","ar","ar-modes","ar-scale","ar-placement","exposure","shadow-intensity","shadow-softness","tone-mapping","bloom","bloom-threshold","bloom-radius","outline","outline-selected","outline-color","environment-image","skybox-image","autoplay","animation-name","variant-name","auto-rotate","auto-rotate-delay","rotation-per-second"],q.registerPlugin=te.registerPlugin,q.getRegisteredPlugins=te.getRegisteredPlugins;var be=q;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",be);return nt(yt);})();
249
+ void main(){fragColor=uColorId;}`;function Rt(e,t,i){let r={};for(let s of i)r[s]=e.getUniformLocation(t,s);return r}var _t=["uMVP","uModel","uInstanced","uViewProj","uNormalMatrix","uUvTransform","uBaseColor","uMetallic","uRoughness","uClearcoat","uEmissive","uCameraPos","uBaseColorTexture","uHasTexture","uMetallicRoughnessTexture","uHasMetallicRoughnessTexture","uNormalTexture","uHasNormalTexture","uNormalScale","uOcclusionTexture","uHasOcclusionTexture","uOcclusionStrength","uToneMapping","uEnvironmentMap","uHasEnvironmentMap","uAmbientColor","uNumDirLights","uDirLightDir","uDirLightColor","uNumPointLights","uPointLightPos","uPointLightColor","uPointLightSpotDir","uPointLightSpotCone","uEnvIntensity","uExposure","uViewportSize","uSectionPlane","uSectionEnabled"];function Ut(){let e=Z().xrDepthShader;return{fs:me.replace("/*XRD_U*/",e?.uniformsGLSL||"").replace("/*XRD_O*/",e?.occlusionGLSL||""),uniforms:e?[..._t,...e.uniformNames]:_t}}function fe(e){if(typeof e!="string")return null;let t=e.trim();if(!t||/[\x00-\x1f\x7f]/.test(t))return null;let i=t.toLowerCase();return i.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(t)?t:null:i.startsWith("https://")||i.startsWith("blob:")?t:i.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(t)||/(^|[\\/])\.\.([\\/]|$)/.test(t)?null:t}function Ct(e,t,i,r,s,a,o,h){if(r===void 0||!t.accessors?.[r])return null;let n=It(t,i,t.accessors[r],a);if(!n)return null;h&&(n=n.slice(),se(n,h));let l=e.createBuffer();return o.push(l),e.bindBuffer(34962,l),e.bufferData(34962,n,35044),e.enableVertexAttribArray(s),e.vertexAttribPointer(s,a,5126,!1,0,0),n}function St(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,t):1}function Ht(e,t,i){let r=Ut(),s=Bt,a=r.fs,o=!1;for(let n of G)if(n.onResolveShader){let l=n.onResolveShader(t,i,s,a);l&&(s=l.vs,a=l.fs,o=!0)}let h=o?Tt(e,s,a):null;return{program:h,uniforms:h?Rt(e,h,r.uniforms):null}}function ge(e,t,i){let r=t.instanceMatrices;if(!r||r.length<16||typeof e.vertexAttribDivisor!="function"||typeof e.drawElementsInstanced!="function")return!1;let s=r.length>>4,a=t.instanceColors,o=new Float32Array(s*20);for(let n=0;n<s;n++)o.set(r.subarray(n*16,n*16+16),n*20),o[n*20+16]=a?a[n*3]:1,o[n*20+17]=a?a[n*3+1]:1,o[n*20+18]=a?a[n*3+2]:1,o[n*20+19]=1;let h=e.createBuffer();i.push(h),e.bindBuffer(34962,h),e.bufferData(34962,o,35044);for(let n=0;n<5;n++)e.enableVertexAttribArray(8+n),e.vertexAttribPointer(8+n,4,5126,!1,80,n*16),e.vertexAttribDivisor(8+n,1);return!0}function ve(e,t){let i=e.materials?.[t?.material];if(!i)return null;let r=[i.pbrMetallicRoughness?.baseColorTexture,i.pbrMetallicRoughness?.metallicRoughnessTexture,i.normalTexture,i.occlusionTexture,i.emissiveTexture];for(let s of r){let a=s?.extensions?.KHR_texture_transform;if(a&&typeof a=="object")return a}return null}var be=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),zt=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function bt(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}function jt(e,t){let i=e?.pbrMetallicRoughness,r=i?.baseColorFactor,s=e?.extensions?.KHR_materials_clearcoat,a=o=>o!==void 0&&t[o.index]?t[o.index]:null;return{baseColor:r?[r[0],r[1],r[2],r[3]??1]:[.8,.8,.8,1],metallic:i?.metallicFactor??.1,roughness:i?.roughnessFactor??.5,clearcoat:s?s.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,s?.clearcoatRoughnessFactor??.04),texture:a(i?.baseColorTexture),metallicRoughnessTexture:a(i?.metallicRoughnessTexture),normalTexture:a(e?.normalTexture),normalScale:e?.normalTexture?.scale??1,occlusionTexture:a(e?.occlusionTexture),occlusionStrength:e?.occlusionTexture?.strength??1,isTransmissive:(e?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function Gt(e,t,i){let r=new Set,s=a=>{a&&!r.has(a)&&(r.add(a),e.deleteTexture(a))};for(let a of t)for(let o of a.primitives){if(o.vao&&e.deleteVertexArray(o.vao),o.buffers)for(let n of o.buffers)e.deleteBuffer(n);s(o.texture),s(o.metallicRoughnessTexture),s(o.normalTexture),s(o.occlusionTexture);let h=new Set;o.customProgram&&h.add(o.customProgram);for(let n of o.programCache?.values()??[])n.program&&h.add(n.program);for(let n of h)e.deleteProgram(n)}if(i)for(let a of i)s(a)}function Xt(e,t,i=zt,r){let s={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return xe(e,t,i,r,s)}catch(a){let o=s.mesh&&!s.meshes.includes(s.mesh)?[...s.meshes,s.mesh]:s.meshes;Gt(e,o,s.gpuTextures),s.vao&&e.deleteVertexArray(s.vao);for(let h of s.buffers)e.deleteBuffer(h);throw a}}function xe(e,t,i,r,s){if(!t||!t.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:a}=t,o=ct("meshopt");o?.decodeBufferViews&&o.decodeBufferViews(a,t);let h=t.bin,n=[];s.meshes=n;let l=[],c=a.extensions?.KHR_materials_variants;c&&Array.isArray(c.variants)&&c.variants.forEach((P,u)=>{l.push(typeof P?.name=="string"&&P.name?P.name:`Variant_${u}`)});let m=ne(a),x=[];if(Array.isArray(a.nodes))for(let P=0;P<a.nodes.length;P++){let u=a.nodes[P];u.mesh!==void 0&&a.meshes&&a.meshes[u.mesh]&&x.push({node:u,nodeIdx:P,meshIdx:u.mesh})}let f=x.length>0?x:(a.meshes||[]).map((P,u)=>({node:P,nodeIdx:-1,meshIdx:u})),v=[],b=Array.isArray(t.lights)&&t.lights.length>0?t.lights:Array.isArray(a.asset?.extras?.lights)&&a.asset.extras.lights.length>0?a.asset.extras.lights:null;if(b)for(let P of b)v.push({...P,type:P.type||P.light_type||"point",innerConeAngle:P.innerConeAngle??P.inner_cone_angle,outerConeAngle:P.outerConeAngle??P.outer_cone_angle});else if(a.extensions?.KHR_lights_punctual?.lights){let P=a.extensions.KHR_lights_punctual.lights;for(let u of P){let C=u.type==="directional"?"directional":u.type==="point"?"point":u.type==="spot"?"spot":"ambient";v.push({type:C,color:u.color||[1,1,1],intensity:u.intensity!==void 0?u.intensity:1})}}if(v.length===0&&(v.push({type:"ambient",color:[1,1,1],intensity:.35}),v.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),f.length>i.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${i.maxMeshes}). Found: ${f.length}`);let T=[];if(s.gpuTextures=T,a.textures&&a.images){if(a.textures.length>i.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${i.maxTextures}). Found: ${a.textures.length}`);for(let P=0;P<a.textures.length;P++){let u=a.textures[P],C=a.images[u.source];if(C){let H=e.createTexture();e.bindTexture(3553,H),e.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),e.texParameteri(3553,10242,10497),e.texParameteri(3553,10243,10497),e.texParameteri(3553,10241,9729),e.texParameteri(3553,10240,9729);let Q=I=>{e.bindTexture(3553,H),e.texImage2D(3553,0,6408,6408,5121,I),e.generateMipmap(3553),r?.()};if(C.bufferView!==void 0){let I=a.bufferViews[C.bufferView],k=I.byteOffset||0,R=new Blob([h.slice(k,k+I.byteLength)],{type:C.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(R).then(Q).catch(()=>{})}else if(C.uri){let I=fe(C.uri);if(I){let k=new Image;k.crossOrigin="anonymous",k.referrerPolicy="no-referrer",k.onload=()=>Q(k),k.src=I}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",C.uri)}T.push(H)}else T.push(null)}}let M=[1/0,1/0,1/0],d=[-1/0,-1/0,-1/0],g=0,p=0;for(let P=0;P<f.length;P++){let u=f[P],C=a.meshes[u.meshIdx],H=u.nodeIdx>=0?m[u.nodeIdx]:z(),Q=new Float32Array(9);ut(Q,H);let I={name:u.node.name||C.name||`Mesh_${u.meshIdx}`,nodeIndex:u.nodeIdx,transform:H,normalMatrix:Q,primitives:[],extras:u.node.extras||C.extras,...u.node?.visible===!1||u.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{}};s.mesh=I;let k=u.node?.extensions?.EXT_mesh_gpu_instancing;if(k&&k.attributes&&typeof k.attributes=="object"){let R=k.attributes,N=R.TRANSLATION!==void 0?a.accessors?.[R.TRANSLATION]:null,B=R.ROTATION!==void 0?a.accessors?.[R.ROTATION]:null,F=R.SCALE!==void 0?a.accessors?.[R.SCALE]:null,$=R._COLOR_0!==void 0?a.accessors?.[R._COLOR_0]:null,O=Number(N?.count??B?.count??F?.count??0);if(!Number.isFinite(O)||O<0||O>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${O}`);if(O>0){let st=(D,j)=>{if(!D||D.bufferView===void 0||!a.bufferViews?.[D.bufferView])return null;let K=D.componentType??5126,it=X=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${X})`),null);if(K!==5120&&K!==5121&&K!==5122&&K!==5123&&K!==5126)return it(`componentType ${K}`);if(!(Number(D.count)>=O))return it(`count ${D.count} < ${O}`);let S=null;try{S=It(a,h,{...D,count:O},j)}catch{return it("out of bounds")}return!S||!S.every(Number.isFinite)?it("non-finite value"):S},W=st(N,3),et=st(B,4),at=st(F,3),ot=$?.type==="VEC4"?4:3,q=st($,ot),nt=new Float32Array(O*16),lt=z();for(let D=0;D<O;D++){let j=W?[W[D*3],W[D*3+1],W[D*3+2]]:[0,0,0],K=et?[et[D*4],et[D*4+1],et[D*4+2],et[D*4+3]]:[0,0,0,1],it=at?[at[D*3],at[D*3+1],at[D*3+2]]:[1,1,1];kt(lt,K,j,it),nt.set(lt,D*16)}if(I.instanceMatrices=nt,q){let D=new Float32Array(O*3);for(let j=0;j<O;j++)D[j*3]=q[j*ot],D[j*3+1]=q[j*ot+1],D[j*3+2]=q[j*ot+2];I.instanceColors=D}}}for(let R of C.primitives||[]){if(R.extensions?.KHR_draco_mesh_compression){let S=ct("draco");S&&S.decodePrimitive(a,R,h)}let N=[],B=e.createVertexArray();s.vao=B,s.buffers=N,e.bindVertexArray(B);let F=ge(e,I,N),$=a.accessors[R.attributes.POSITION],O=Number($?.count??0);if(!Number.isFinite(O)||O<0||g+O>i.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${i.maxVertices}).`);if(g+=O,$?.min&&$?.max){let S=X=>{for(let tt=0;tt<3;tt++){let ht=X[12+tt],ft=X[12+tt];for(let mt=0;mt<3;mt++){let yt=X[mt*4+tt]*$.min[mt],Mt=X[mt*4+tt]*$.max[mt];ht+=yt<Mt?yt:Mt,ft+=yt>Mt?yt:Mt}ht<M[tt]&&(M[tt]=ht),ft>d[tt]&&(d[tt]=ft)}};if(I.instanceMatrices&&I.instanceMatrices.length>=16){let X=I.instanceMatrices.length>>4,tt=z();for(let ht=0;ht<X;ht++){let ft=I.instanceMatrices.subarray(ht*16,ht*16+16);J(tt,H,ft),S(tt)}}else S(H)}let st=Ct(e,a,h,R.attributes.POSITION,0,3,N);Ct(e,a,h,R.attributes.NORMAL,1,3,N),Ct(e,a,h,R.attributes.TEXCOORD_0,2,2,N,ve(a,R));let W=0,et=5123,at=null;if(R.indices!==void 0){let S=a.accessors[R.indices],X=(a.bufferViews[S.bufferView].byteOffset||0)+(S.byteOffset||0);if(W=Number(S.count??0),!Number.isFinite(W)||W<0||p+W>i.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${i.maxIndices}).`);p+=W,et=S.componentType===5125?5125:5123;let tt=e.createBuffer();N.push(tt),e.bindBuffer(34963,tt),S.componentType===5125?at=new Uint32Array(h,X,S.count):S.componentType===5121?at=Uint16Array.from(new Uint8Array(h,X,S.count)):at=X%2===0?new Uint16Array(h,X,S.count):new Uint16Array(h.slice(X,X+S.count*2)),e.bufferData(34963,at,35044)}else W=$.count;let ot={};for(let S of G)if(S.onBuildPrimitiveVAO){let X=S.onBuildPrimitiveVAO(e,B,R,a,h);X&&(ot[S.name]=X)}e.bindVertexArray(null);let q=a.materials&&R.material!==void 0?a.materials[R.material]:null,{program:nt,uniforms:lt}=Ht(e,R,q),D=jt(q,T),j=!!(q?.extensions?.KHR_materials_transmission||ot.materials?.isTransmissive),K=R.extensions?.KHR_materials_variants?.mappings,it=Array.isArray(K)?K.filter(S=>S&&typeof S.material=="number"&&Array.isArray(S.variants)).map(S=>({material:S.material|0,variants:S.variants.map(X=>Number(X)|0)})):void 0;I.primitives.push({vao:B,instanced:F,indexCount:W,indexType:et,...D,positions:st,indices:at,buffers:N,materialIndex:R.material,defaultMaterialIndex:R.material,variantMappings:it,primitiveDef:R,programCache:new Map([[R.material??-1,{program:nt,uniforms:lt}]]),pluginData:ot,customProgram:nt,customUniforms:lt,isTransmissive:j})}n.push(I)}isFinite(M[0])||(M=[-1,-1,-1]),isFinite(d[0])||(d=[1,1,1]);let A=[(M[0]+d[0])/2,(M[1]+d[1])/2,(M[2]+d[2])/2],w=d[0]-M[0],V=d[1]-M[1],_=d[2]-M[2],U=Math.max(Math.hypot(w,V,_)/2,.5),E=[M[0],M[1],M[2]],y=[d[0],d[1],d[2]],L=t.animations;if(!L){for(let P of G)if(P.onParseGLB?.(t),t.animations){L=t.animations;break}}return L||(L=[]),{meshes:n,bounds:{center:A,radius:U,min:E,max:y},lights:v,animations:L,worldMatrices:m,gpuTextures:T,availableVariants:l}}function pt(e){let t=e.customTarget||e.bounds.center,i=e.currDistance*Math.cos(e.currPhi);return[t[0]+i*Math.sin(e.currTheta),t[1]+e.currDistance*Math.sin(e.currPhi),t[2]+i*Math.cos(e.currTheta)]}var rt=class{constructor(e,t,i){this.supportsInstanceOffsets=!0,this.meshes=[],this.backdropMeshes=[],this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]},this.lights=[],this.modelRootMatrix=z(),this.clearColor=[0,0,0,0],this.envIntensity=1,this.exposure=1,this.shadowIntensity=0,this.shadowSoftness=.5,this.toneMapping="neutral",this.environmentTexture=null,this.animations=[],this.currentClip=null,this.animationTime=0,this.isPlayingAnimation=!1,this.autoplay=!1,this.animationName="",this.gpuTextures=[],this.availableVariants=[],this.activeVariantName=null,this.gltf=null,this.worldMatrices=[],this.initialNodeTransforms=[],this.projMatrix=z(),this.viewMatrix=z(),this.activeViewMatrix=null,this.modelMatrix=z(),this.mvpMatrix=z(),this.normalMatrix=new Float32Array(9),this.initialTheta=.6,this.initialPhi=.35,this.initialDistance=null,this.customDistance=!1,this.distanceMode="auto",this.initialCustomTarget=null,this.customTarget=null,this.fov=Math.PI/4,this.minTheta=-1/0,this.maxTheta=1/0,this.minPhi=-Math.PI*.48,this.maxPhi=Math.PI*.48,this.minDistanceLimit=null,this.maxDistanceLimit=null,this.activePointers=new Map,this.isPanning=!1,this.targetTheta=.6,this.currTheta=.6,this.targetPhi=.35,this.currPhi=.35,this.targetDistance=3,this.currDistance=3,this.autoRotate=!1,this.autoRotateSpeed=Math.PI/6,this.autoRotateDelay=3e3,this.lastInteractionTime=-1/0,this.turntableRotation=0,this.isPointerDown=!1,this.interactive=!0,this.skyboxTexture=null,this.lastPointerX=0,this.lastPointerY=0,this.totalDragDist=0,this.selectedMeshName="",this.pickFbo=null,this.pickTexture=null,this.pickDepth=null,this.pickFboWidth=0,this.pickFboHeight=0,this.animFrameId=null,this.isVisible=!0,this.xrSessionActive=!1,this.lastTime=0,this.lastReportedTheta=-999,this.lastReportedPhi=-999,this.lastReportedZoom=-999,this.boundPointerDown=null,this.boundPointerMove=null,this.boundPointerUp=null,this.boundWheel=null,this.boundKeyDown=null,this.boundContextMenu=null,this.boundSetCamera=null,this.boundResetCamera=null,this.contextLost=!1,this.lastGlbData=null,this.boundContextLost=null,this.boundContextRestored=null,this.stereoSBS=!1,this.renderErrorReported=!1,this.xrDepthState={enabled:!1,texture:null,uvTransform:z(),rawValueToMeters:.001,format:0},this.container=e;let r,s;if(t&&typeof t.getContext=="function"?(r=t,s=i):(s=t,r=s?.canvas),!r){let h=e.querySelector("canvas");h||(h=document.createElement("canvas"),h.style.width="100%",h.style.height="100%",h.style.display="block",h.style.touchAction="none",e.prepend(h)),r=h}this.canvas=r,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!a:a&&(this.autoRotate=!1),this.opts.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=this.opts.autoRotateSpeed),this.opts.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(this.opts.autoRotateDelay)||0)),this.opts.exposure!==void 0&&(this.exposure=St(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=dt(this.opts.toneMapping)),this.opts.autoplay!==void 0&&(this.autoplay=this.opts.autoplay),this.opts.animationName!==void 0&&(this.animationName=this.opts.animationName),this.opts.variantName!==void 0&&(this.activeVariantName=this.opts.variantName||null),this.opts.fieldOfView!==void 0&&(this.fov=this.opts.fieldOfView*Math.PI/180),this.opts.distanceMode!==void 0&&(this.distanceMode=this.opts.distanceMode),this.opts.cameraTarget!==void 0&&(this.setTarget(this.opts.cameraTarget[0],this.opts.cameraTarget[1],this.opts.cameraTarget[2]),this.initialCustomTarget=[...this.opts.cameraTarget]),(this.opts.minCameraOrbit||this.opts.maxCameraOrbit)&&this.setOrbitLimits({minTheta:this.opts.minCameraOrbit?.theta,maxTheta:this.opts.maxCameraOrbit?.theta,minPhi:this.opts.minCameraOrbit?.phi,maxPhi:this.opts.maxCameraOrbit?.phi,minDistance:this.opts.minCameraOrbit?.distance,maxDistance:this.opts.maxCameraOrbit?.distance});let o=r.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!o)throw new Error("WebGL2 not supported");this.gl=o,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(e,t){ue(e,t)}static getDecoder(e){return ct(e)}setupContextLossHandling(){let e=this.canvas;typeof e?.addEventListener=="function"&&(this.boundContextLost=t=>{t.preventDefault?.(),this.contextLost=!0,this.stop()},this.boundContextRestored=()=>this.restoreContext(),e.addEventListener("webglcontextlost",this.boundContextLost),e.addEventListener("webglcontextrestored",this.boundContextRestored))}initGlState(){let e=this.gl,t=Ut();this.renderProg=Tt(e,Bt,t.fs),this.pickProg=Tt(e,de,pe),this.uRender=Rt(e,this.renderProg,t.uniforms),this.uPick=Rt(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of G)t.onContextRestored?.(e,this);this.meshes=[],this.gpuTextures=[],this.environmentTexture=null,this.lastGlbData&&this.loadGLBData(this.lastGlbData,this.lastLimits),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}setupPickingFbo(){let e=this.gl;if(typeof e.createFramebuffer!="function")return;this.pickFbo=e.createFramebuffer(),this.pickTexture=e.createTexture(),this.pickDepth=e.createRenderbuffer();let t=Math.max(1,this.canvas.width),i=Math.max(1,this.canvas.height);this.pickFboWidth=t,this.pickFboHeight=i,e.bindTexture(3553,this.pickTexture),e.texImage2D(3553,0,6408,t,i,0,6408,5121,null),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728),e.bindRenderbuffer(36161,this.pickDepth),e.renderbufferStorage(36161,33189,t,i),e.bindFramebuffer(36160,this.pickFbo),e.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),e.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),e.bindFramebuffer(36160,null)}resizePickingFbo(e,t){if(!this.pickFbo)return;let i=this.gl,r=Math.max(1,e),s=Math.max(1,t);this.pickFboWidth=r,this.pickFboHeight=s,i.bindTexture(3553,this.pickTexture),i.texImage2D(3553,0,6408,r,s,0,6408,5121,null),i.bindRenderbuffer(36161,this.pickDepth),i.renderbufferStorage(36161,33189,r,s)}loadGLBData(e,t){let{meshes:i,bounds:r,lights:s,animations:a,worldMatrices:o,gpuTextures:h,availableVariants:n}=Xt(this.gl,e,t,()=>this.render());if(this.lastGlbData=e,this.lastLimits=t,this.disposeMeshGpuResources(),this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.meshes=i,this.bounds=r,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=s,this.animations=a||[],this.worldMatrices=o||[],this.gpuTextures=h||[],this.availableVariants=n||[],this.gltf=e.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let m of e.gltf.nodes)this.initialNodeTransforms.push({t:m.translation?[m.translation[0],m.translation[1],m.translation[2]]:[0,0,0],r:m.rotation?[m.rotation[0],m.rotation[1],m.rotation[2],m.rotation[3]]:[0,0,0,1],s:m.scale?[m.scale[0],m.scale[1],m.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let m of G)m.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:r.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let l=e.exposure??e.gltf?.extras?.exposure??e.gltf?.asset?.extras?.exposure;l!==void 0&&(this.exposure=St(l));let c=e.environmentIntensity??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.environmentIntensity;c!==void 0&&(this.envIntensity=Math.max(0,Number(c)||0)),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(e){this.loadGLBData(Ot(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let e of G)e.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(vt(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let i=vt(e),{meshes:r}=Xt(this.gl,i,zt,()=>this.render());if(t)for(let s of r)s.transform[12]+=t[0],s.transform[13]+=t[1],s.transform[14]+=t[2],ut(s.normalMatrix,s.transform);this.backdropMeshes=r,this.update(0),this.render()}setClearColor(e,t,i,r=1){this.clearColor=[e,t,i,r]}updateMeshTransforms(e){for(let t=0;t<this.meshes.length;t++){let i=this.meshes[t],r;e instanceof Map?r=e.get(i.name)??e.get(t):Array.isArray(e)?r=e[t]:e&&typeof e=="object"&&(Object.prototype.hasOwnProperty.call(e,i.name)?r=e[i.name]:Object.prototype.hasOwnProperty.call(e,t)&&(r=e[t])),r&&r.length===16&&(i.transform.set(r),ut(i.normalMatrix,i.transform))}}bindLights(e=this.uRender){let t=this.gl,i=[.28,.28,.28],r=[],s=[],a=[],o=[],h=[],n=[];for(let l of this.lights){let c=l.color||[1,1,1],m=l.intensity!==void 0?l.intensity:1;if(l.type==="ambient")i=[c[0]*m,c[1]*m,c[2]*m];else if(l.type==="directional"&&r.length<6){let x=l.direction||[.5,1,.8];r.push(x[0],x[1],x[2]),s.push(c[0]*m,c[1]*m,c[2]*m)}else if((l.type==="point"||l.type==="spot")&&a.length<6){let x=l.position||[0,0,0];if(a.push(x[0],x[1],x[2]),o.push(c[0]*m,c[1]*m,c[2]*m),l.type==="spot"){let f=l.direction||[0,-1,0],v=Math.max(.01,Math.min(Math.PI/2,l.outerConeAngle??Math.PI/3)),b=Math.max(0,Math.min(v-1e-4,l.innerConeAngle??0));h.push(f[0],f[1],f[2]),n.push(Math.cos(b),Math.cos(v))}else h.push(0,-1,0),n.push(-2,-3)}}r.length===0&&(r.push(.5,1,.8),s.push(1,1,1)),t.uniform3fv(e.uAmbientColor,i),t.uniform1i(e.uNumDirLights,r.length/3),r.length>0&&(t.uniform3fv(e.uDirLightDir,r),t.uniform3fv(e.uDirLightColor,s)),t.uniform1i(e.uNumPointLights,a.length/3),a.length>0&&(t.uniform3fv(e.uPointLightPos,a),t.uniform3fv(e.uPointLightColor,o),e.uPointLightSpotDir&&t.uniform3fv(e.uPointLightSpotDir,h),e.uPointLightSpotCone&&t.uniform2fv(e.uPointLightSpotCone,n)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=St(e)}getExposure(){return this.exposure}setShadow(e,t){this.shadowIntensity=Math.max(0,Math.min(1,Number(e)||0)),t!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(t)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(e){this.toneMapping=dt(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of G)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of G)if(t.setSkyboxImage){await t.setSkyboxImage(this,e);return}}setInteractive(e){this.interactive=e}isInteractive(){return this.interactive}getCameraOrbit(){let e=this.currTheta,t=this.currPhi,i=this.currDistance;return{theta:e,phi:t,radius:i,toString(){return`${e.toFixed(4)}rad ${t.toFixed(4)}rad ${i.toFixed(4)}m`}}}getCameraTarget(){let e=this.customTarget||this.bounds.center;return{x:e[0],y:e[1],z:e[2],toString(){return`${e[0].toFixed(4)}m ${e[1].toFixed(4)}m ${e[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let e=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return e.map((t,i)=>{let r=this.meshes.flatMap(l=>l.primitives.filter(c=>c.materialIndex===i||e.length===1&&c.materialIndex===void 0)),s=r[0],a=s?[...s.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],o=s?s.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,h=s?s.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,n={baseColorFactor:a,metallicFactor:o,roughnessFactor:h,setBaseColorFactor:l=>{let c=[l[0],l[1],l[2],l[3]??1];n.baseColorFactor=c,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=c);for(let m of r)m.baseColor=c;this.render()},setMetallicFactor:l=>{n.metallicFactor=l,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=l);for(let c of r)c.metallic=l;this.render()},setRoughnessFactor:l=>{n.roughnessFactor=l,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=l);for(let c of r)c.roughness=l;this.render()}};return{name:t.name||`Material_${i}`,pbrMetallicRoughness:n}})}playAnimation(e){if(this.animations.length!==0){if(e){let t=this.animations.find(i=>i.name===e);t&&(this.currentClip=t)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(e=>e.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(e){let t=this.applyVariantMaterial(e);return t&&this.gl&&this.render(),t}applyVariantMaterial(e){let t=e===null||e==="",i=-1;if(t)this.activeVariantName=null;else{if(i=this.availableVariants.indexOf(e),i<0)return!1;this.activeVariantName=e}let r=this.gltf?.materials;if(!Array.isArray(r))return t;for(let s of this.meshes)for(let a of s.primitives){let o=a.defaultMaterialIndex;if(!t&&Array.isArray(a.variantMappings)){for(let n of a.variantMappings)if(Array.isArray(n.variants)&&n.variants.includes(i)){o=n.material;break}}let h=o!==void 0?r[o]:void 0;a.materialIndex=h?o:void 0,Object.assign(a,jt(h,this.gpuTextures)),this.applyPrimitiveProgram(a,a.materialIndex,h??null)}return!0}applyPrimitiveProgram(e,t,i){if(!this.gl||!e.primitiveDef)return;e.programCache??(e.programCache=new Map);let r=t??-1,s=e.programCache.get(r);s||(s=Ht(this.gl,{...e.primitiveDef,material:t},i),e.programCache.set(r,s)),e.customProgram=s.program,e.customUniforms=s.uniforms,e.pluginData&&(e.pluginData.materials=e.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(e){this.autoplay=e,e?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(e){this.animationName=e,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(e)}evaluateAnimation(e){for(let t of G)if(t.evaluateAnimation){t.evaluateAnimation(this,e);return}}setTarget(e,t,i){this.customTarget=[e,t,i],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(e){let t=Math.max(10,Math.min(90,e));this.fov=t*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(e){if(this.distanceMode=e,!this.customDistance){let t=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=t,this.targetDistance=t,this.currDistance=t,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(e){e.minTheta!==void 0&&(this.minTheta=e.minTheta*Math.PI/180),e.maxTheta!==void 0&&(this.maxTheta=e.maxTheta*Math.PI/180),e.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,e.minPhi*Math.PI/180)),e.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,e.maxPhi*Math.PI/180)),e.minDistance!==void 0&&(this.minDistanceLimit=e.minDistance),e.maxDistance!==void 0&&(this.maxDistanceLimit=e.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){return{minTheta:isFinite(this.minTheta)?this.minTheta*180/Math.PI:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*180/Math.PI:void 0,minPhi:this.minPhi*180/Math.PI,maxPhi:this.maxPhi*180/Math.PI,minDistance:this.minDistanceLimit!==null?this.minDistanceLimit:void 0,maxDistance:this.maxDistanceLimit!==null?this.maxDistanceLimit:void 0}}clampTheta(e){return Math.max(this.minTheta,Math.min(this.maxTheta,e))}clampPhi(e){return Math.max(this.minPhi,Math.min(this.maxPhi,e))}clampDistance(e){let t=this.minDistanceLimit!==null?this.minDistanceLimit:this.bounds?this.bounds.radius*.5:.1,i=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(t,Math.min(i,e))}setCamera(e,t,i,r){e!==void 0&&(this.targetTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.targetPhi=this.clampPhi(t*Math.PI/180)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(i)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/r))}setInitialCamera(e,t,i,r){if(e!==void 0&&(this.initialTheta=this.clampTheta(e*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),t!==void 0&&(this.initialPhi=this.clampPhi(t*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),i!==void 0&&i>0){let s=this.clampDistance(i);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else if(r!==void 0&&r>0){let s=this.clampDistance(this.bounds.radius*2.5/r);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else{this.customDistance=!1;let s=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=s,this.targetDistance=s,this.currDistance=s}this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.initialDistance!==null?this.targetDistance=this.clampDistance(this.initialDistance):this.targetDistance=this.clampDistance(this.bounds.radius*2.5),this.initialCustomTarget?this.customTarget=[...this.initialCustomTarget]:this.customTarget=null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(e,t){let i=z();J(i,this.projMatrix,this.viewMatrix);let[r,s,a]=e,o=t?t[0]:0,h=t?t[1]:0,n=t?t[2]:0,l=this.modelRootMatrix;l&&(r=l[0]*e[0]+l[4]*e[1]+l[8]*e[2]+l[12],s=l[1]*e[0]+l[5]*e[1]+l[9]*e[2]+l[13],a=l[2]*e[0]+l[6]*e[1]+l[10]*e[2]+l[14],t&&(o=l[0]*t[0]+l[4]*t[1]+l[8]*t[2],h=l[1]*t[0]+l[5]*t[1]+l[9]*t[2],n=l[2]*t[0]+l[6]*t[1]+l[10]*t[2]));let c=i[0]*r+i[4]*s+i[8]*a+i[12],m=i[1]*r+i[5]*s+i[9]*a+i[13],x=i[2]*r+i[6]*s+i[10]*a+i[14],f=i[3]*r+i[7]*s+i[11]*a+i[15];if(f<=1e-4)return{x:0,y:0,z:1,visible:!1};let v=c/f,b=m/f,T=x/f,M=this.canvas.getBoundingClientRect(),d=M.width||this.canvas.clientWidth||this.canvas.width||300,g=M.height||this.canvas.clientHeight||this.canvas.height||150,p=(v*.5+.5)*d,A=(-b*.5+.5)*g,w=v>=-1.1&&v<=1.1&&b>=-1.1&&b<=1.1&&T>=-1&&T<=1;if(w&&t){let[V,_,U]=pt(this),E=[r-V,s-_,a-U];o*E[0]+h*E[1]+n*E[2]>.05&&(w=!1)}return{x:p,y:A,z:T,visible:w}}setSelectedMesh(e){this.selectedMeshName=e||""}getSelectedMesh(){return this.selectedMeshName}setupEvents(){let e=this.canvas,t=()=>typeof performance<"u"?performance.now():Date.now();this.boundContextMenu=i=>{i.preventDefault()},e.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=i=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=t(),this.lastPointerX=i.clientX,this.lastPointerY=i.clientY,this.totalDragDist=0,this.activePointers.set(i.pointerId,{x:i.clientX,y:i.clientY}),this.isPanning=i.button===2||i.shiftKey||this.activePointers.size===2,e.setPointerCapture(i.pointerId))},e.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=i=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=t();let r=this.activePointers.get(i.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},s=i.clientX-r.x,a=i.clientY-r.y;if(this.activePointers.set(i.pointerId,{x:i.clientX,y:i.clientY}),this.lastPointerX=i.clientX,this.lastPointerY=i.clientY,this.totalDragDist+=Math.hypot(s,a),this.isPanning||i.button===2||i.shiftKey||this.activePointers.size===2){let o=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],h=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],n=this.customTarget?[...this.customTarget]:[...this.bounds.center],l=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;n[0]+=(-s*o[0]+a*h[0])*l,n[1]+=(-s*o[1]+a*h[1])*l,n[2]+=(-s*o[2]+a*h[2])*l,this.customTarget=n}else this.targetTheta=this.clampTheta(this.targetTheta-s*.008),this.targetPhi=this.clampPhi(this.targetPhi+a*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=i=>{this.lastInteractionTime=t(),this.activePointers.delete(i.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(i.pointerId)}catch{}if(this.totalDragDist<5&&i.button===0){let r=e.getBoundingClientRect(),s=Math.floor((i.clientX-r.left)*(e.width/Math.max(r.width,1))),a=Math.floor((i.clientY-r.top)*(e.height/Math.max(r.height,1)));this.performMeshPick(s,a,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=i=>{if(!this.interactive)return;i.preventDefault(),this.lastInteractionTime=t();let r=Math.exp(i.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=i=>{let r=i.detail||{};r.reset?this.resetCamera():this.setCamera(r.theta,r.phi,r.distance,r.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),e.tabIndex!==void 0&&e.tabIndex<0&&(e.tabIndex=0),e.getAttribute?.("role")||e.setAttribute?.("role","region"),e.getAttribute?.("aria-label")||e.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=i=>{if(this.interactive){switch(i.key){case"ArrowLeft":this.targetTheta=this.clampTheta(this.targetTheta-.1);break;case"ArrowRight":this.targetTheta=this.clampTheta(this.targetTheta+.1);break;case"ArrowUp":this.targetPhi=this.clampPhi(this.targetPhi+.08);break;case"ArrowDown":this.targetPhi=this.clampPhi(this.targetPhi-.08);break;case"+":case"=":this.targetDistance=this.clampDistance(this.targetDistance*.9);break;case"-":case"_":this.targetDistance=this.clampDistance(this.targetDistance*1.1);break;case"Home":this.resetCamera();break;default:return}this.lastInteractionTime=t(),i.preventDefault()}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=(i,r,s)=>{this[s]&&(i.removeEventListener(r,this[s]),this[s]=null)},t=this.canvas;e(t,"webglcontextlost","boundContextLost"),e(t,"webglcontextrestored","boundContextRestored"),e(t,"contextmenu","boundContextMenu"),e(t,"pointerdown","boundPointerDown"),e(t,"pointermove","boundPointerMove"),e(t,"pointerup","boundPointerUp"),e(t,"wheel","boundWheel"),e(t,"keydown","boundKeyDown"),e(this.container,"setCamera","boundSetCamera"),e(this.container,"resetCamera","boundResetCamera")}raycastFromScreenPoint(e,t){let i=this.canvas,r=i.getBoundingClientRect(),s=i.width||300,a=i.height||300,o=r.width>0?Math.floor((e-r.left)*(s/r.width)):Math.floor(e),h=r.height>0?Math.floor((t-r.top)*(a/r.height)):Math.floor(t);return this.performMeshPick(o,h,!1)}performMeshPick(e,t,i=!0){if(this.meshes.length===0)return null;let r=this.gl,s=Math.max(1,this.canvas.width||300),a=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,s);let o=z();J(o,this.projMatrix,this.viewMatrix);let h=[],n=Math.max(0,Math.min(s-1,e)),l=Math.max(0,Math.min(a-1,a-1-t));if(this.pickFbo&&r&&!this.xrSessionActive){(this.pickFboWidth!==s||this.pickFboHeight!==a)&&this.resizePickingFbo(s,a),r.bindFramebuffer(36160,this.pickFbo),r.viewport(0,0,s,a),r.enable(2929),r.clearColor(0,0,0,0),r.clear(16640),r.useProgram(this.pickProg);for(let A=0;A<this.meshes.length;A++){let w=this.meshes[A];if(w.visible===!1||w.isPluginMesh)continue;let V=A+1,_=(V&255)/255,U=(V>>8&255)/255,E=(V>>16&255)/255;r.uniform4f(this.uPick.uColorId,_,U,E,1),J(this.modelMatrix,this.modelRootMatrix,w.transform);let y=w.instanceMatrices;if(y&&y.length>=16){let L=y.length>>4,P=z();for(let u of w.primitives){r.bindVertexArray(u.vao);for(let C=0;C<L;C++)J(P,this.modelMatrix,y.subarray(C*16,C*16+16)),J(this.mvpMatrix,o,P),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),bt(r,u)}}else{J(this.mvpMatrix,o,this.modelMatrix),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let L of w.primitives)r.bindVertexArray(L.vao),bt(r,L)}}let g=new Uint8Array(4);r.readPixels(n,l,1,1,6408,5121,g),r.bindFramebuffer(36160,null);let p=g[0]+(g[1]<<8)+(g[2]<<16);p>0&&p<=this.meshes.length&&(h=[this.meshes[p-1]])}h.length===0&&(h=this.meshes.filter(g=>g.visible!==!1));let c=null,m=1/0,x=[0,0,0],f=[0,1,0],[v,b,T]=pt(this),M=z();for(let g of h){J(M,this.modelRootMatrix,g.transform);let p=g.instanceMatrices,A=p&&p.length>=16?p.length>>4:1;for(let w=0;w<A;w++){p&&p.length>=16?J(this.modelMatrix,M,p.subarray(w*16,w*16+16)):this.modelMatrix.set(M),J(this.mvpMatrix,o,this.modelMatrix);let V=z();if(!ae(V,this.mvpMatrix))continue;let _=(n+.5)/s*2-1,U=(l+.5)/a*2-1,E=[0,0,0],y=[0,0,0];Nt(E,_,U,-1,V),Nt(y,_,U,1,V);let L=y[0]-E[0],P=y[1]-E[1],u=y[2]-E[2],C=Math.hypot(L,P,u)||1,H=L/C,Q=P/C,I=u/C,k={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((R=>{for(let N of g.primitives){if(!N.positions)continue;let B=N.positions,F=N.indices,$=Math.floor(F?F.length/3:B.length/9);for(let O=0;O<$;O++){let st=F?F[O*3]:O*3,W=F?F[O*3+1]:O*3+1,et=F?F[O*3+2]:O*3+2;oe(E[0],E[1],E[2],H,Q,I,B[st*3],B[st*3+1],B[st*3+2],B[W*3],B[W*3+1],B[W*3+2],B[et*3],B[et*3+1],B[et*3+2],k,R)}}})(1e-4),isFinite(k.distance)){let R=k.point[0],N=k.point[1],B=k.point[2],F=this.modelMatrix,$=F[0]*R+F[4]*N+F[8]*B+F[12],O=F[1]*R+F[5]*N+F[9]*B+F[13],st=F[2]*R+F[6]*N+F[10]*B+F[14],W=$-v,et=O-b,at=st-T,ot=Math.hypot(W,et,at);if(ot<m){ut(this.normalMatrix,this.modelMatrix);let q=this.normalMatrix,nt=k.normal[0],lt=k.normal[1],D=k.normal[2],j=q[0]*nt+q[3]*lt+q[6]*D,K=q[1]*nt+q[4]*lt+q[7]*D,it=q[2]*nt+q[5]*lt+q[8]*D,S=Math.hypot(j,K,it)||1;j/=S,K/=S,it/=S,j*W+K*et+it*at>0&&(j=-j,K=-K,it=-it),c=g,m=Math.round(ot*1e3)/1e3,x=[Math.round($*1e3)/1e3,Math.round(O*1e3)/1e3,Math.round(st*1e3)/1e3],f=[Math.round(j*1e3)/1e3,Math.round(K*1e3)/1e3,Math.round(it*1e3)/1e3]}}}}if(!c)return null;let d={meshIndex:this.meshes.indexOf(c),meshName:c.name,nodeIndex:c.nodeIndex,distance:m,hitPoint:x,normal:f,screenX:e,screenY:t};if(i){for(let g of G)g.onMeshSelect?.(this,d);this.opts.onMeshClick&&this.opts.onMeshClick(d),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:d}))}return d}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let i=Math.max(1,Math.floor(t*.5)),r=e>=i,s=r?e-i:e,a=r?Math.max(1,t-i):i,o=(s+.5)/a*2-1;return Math.floor((o*.5+1)*.5*t)}setStereoSBS(e){this.stereoSBS=!!e,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let e=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),t=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);Pt(this.projMatrix,this.fov,e,.1,t);let i=this.customTarget||this.bounds.center;At(this.viewMatrix,pt(this),i,[0,1,0]),J(this.mvpMatrix,this.projMatrix,this.viewMatrix),ut(this.normalMatrix,this.modelMatrix)}resize(){let e=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),t=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.floor(t.width*e)),r=Math.max(1,Math.floor(t.height*e));this.canvas.width!==i||this.canvas.height!==r?(this.canvas.width=i,this.canvas.height=r,this.resizePickingFbo(i,r),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(e){let t=this.xrSessionActive;if(this.xrSessionActive=e,t&&!e){this.xrDepthState.enabled=!1;for(let i of G)i.onXRSessionEnd?.(this);if(this.lastTime=typeof performance<"u"?performance.now():Date.now(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(i){this.reportRenderError(i)}}}reportRenderError(e){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",e))}stepXRUpdate(e){for(let t of G)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let e=t=>{if(this.animFrameId===null)return;let i=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(i),this.render()}catch(r){this.reportRenderError(r)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(e))};this.animFrameId=requestAnimationFrame(e)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(e){this.autoRotate=e}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(e){this.autoRotateSpeed=e}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(e){this.autoRotateDelay=Math.max(0,Number(e)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(e=0){this.turntableRotation=Number(e)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let e=Math.cos(this.turntableRotation),t=Math.sin(this.turntableRotation),i=this.bounds.center[0],r=this.bounds.center[2],s=this.modelRootMatrix;s[0]=e,s[1]=0,s[2]=-t,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=t,s[9]=0,s[10]=e,s[11]=0,s[12]=i-(e*i+t*r),s[13]=0,s[14]=r-(-t*i+e*r),s[15]=1}setVisible(e){this.isVisible=e}update(e){for(let a of G)a.onUpdate?.(this,e);let t=typeof performance<"u"?performance.now():Date.now();if(!this.isPointerDown&&this.autoRotate&&t-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*e,this.updateTurntableMatrix();for(let a of G)a.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let i=Math.round((this.currTheta*180/Math.PI%360+360)%360),r=Math.round(this.currPhi*180/Math.PI),s=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(i-this.lastReportedTheta)>=1||Math.abs(r-this.lastReportedPhi)>=1||Math.abs(s-this.lastReportedZoom)>=.02){this.lastReportedTheta=i,this.lastReportedPhi=r,this.lastReportedZoom=s;let a={theta:i,phi:r,zoom:s,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(a),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:a}))}}renderXRView(e,t,i,r,s=!0,a=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let o=e?.transform?.inverse?.matrix||this.viewMatrix,h=e?.projectionMatrix||this.projMatrix,n=e?.transform?.position,l=n?[n.x,n.y,n.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):i&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:o,projMatrix:h,eyePos:l,viewport:r,eye:e?.eye||"none",clear:a>0?!1:e?.eye!=="right",isAR:s})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let d=Math.max(2,this.canvas.width||2),g=Math.max(1,this.canvas.height||1),p=Math.max(1,Math.floor(d*.5)),A=Math.max(1,d-p),w=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),V=this.customTarget||this.bounds.center,[_,U,E]=pt(this),y=Math.cos(this.currTheta),L=-Math.sin(this.currTheta),P=.032,u=z(),C=z(),H=[_-y*P,U,E-L*P],Q=[V[0]-y*P*.25,V[1],V[2]-L*P*.25];Pt(u,this.fov,p/g,.1,w),At(C,H,Q,[0,1,0]);let I=z(),k=z(),R=[_+y*P,U,E+L*P],N=[V[0]+y*P*.25,V[1],V[2]+L*P*.25];Pt(I,this.fov,A/g,.1,w),At(k,R,N,[0,1,0]),this.render({viewMatrix:C,projMatrix:u,eyePos:H,viewport:[0,0,p,g],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:k,projMatrix:I,eyePos:R,viewport:[p,0,A,g],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,d,g);return}let t=this.gl,i=0,r=0,s=this.canvas.width,a=this.canvas.height;e?.viewport?(i=e.viewport[0],r=e.viewport[1],s=e.viewport[2],a=e.viewport[3],t.viewport(i,r,s,a)):t.viewport(0,0,this.canvas.width,this.canvas.height),t.enable(2929),(!e||e.clear!==!1)&&(e?.isAR?t.clearColor(0,0,0,0):t.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),t.clear(16640));let o=z(),h=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=h,J(o,e?.projMatrix??this.projMatrix,h);let n=Z().xrDepthShader,l=le(this.toneMapping),[c,m,x]=e?e.eyePos:pt(this);for(let d of G)d.onBeforeDrawScene?.(this,t,o,[c,m,x],l);let f=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&f===0)return;let v=e?.eye||"none",b=!1,T=f>0?[...this.backdropMeshes,...this.meshes]:this.meshes,M=d=>{for(let g=0;g<T.length;g++){let p=T[g];if(p.visible===!1)continue;let A=this.selectedMeshName!==""&&p.name===this.selectedMeshName;g<f||p.worldSpace===!0||p.name==="__xr_reticle__"?this.modelMatrix.set(p.transform):J(this.modelMatrix,this.modelRootMatrix,p.transform),J(this.mvpMatrix,o,this.modelMatrix),ut(p.normalMatrix,this.modelMatrix);let w=p.extras?.xr?.stereo||p.userData?.xr?.stereo,V=0,_=0,U=1,E=1;w==="sbs"?(U=.5,V=v==="right"?.5:0):w==="ou"&&(E=.5,_=v==="right"?.5:0);for(let y of p.primitives){let L=!!y.isTransmissive;if(!d&&L){b=!0;continue}if(d&&!L)continue;let P=y.customProgram||this.renderProg,u=y.customUniforms||this.uRender;t.useProgram(P),t.vertexAttrib3f(3,0,0,0),u.uInstanced&&t.uniform1i(u.uInstanced,0),t.uniform1i(u.uToneMapping,l),t.uniform1f(u.uEnvIntensity,this.envIntensity),u.uExposure&&t.uniform1f(u.uExposure,this.exposure),t.uniform3f(u.uCameraPos,c,m,x),t.uniform1f(u.uEmissive,A?1:0),t.uniformMatrix4fv(u.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(u.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(u.uNormalMatrix,!1,p.normalMatrix),u.uUvTransform&&t.uniform4f(u.uUvTransform,V,_,U,E),u.uViewportSize&&t.uniform2f(u.uViewportSize,Math.max(1,s),Math.max(1,a)),n?.bind(t,u,this.xrDepthState,h,[i,r,Math.max(1,s),Math.max(1,a)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(u.uEnvironmentMap,4),t.uniform1i(u.uHasEnvironmentMap,1)):t.uniform1i(u.uHasEnvironmentMap,0),this.bindLights(u),u.uSectionEnabled&&t.uniform1i(u.uSectionEnabled,0);for(let H of G)H.onBeforeDrawPrimitive?.(t,P,y,p,this.worldMatrices||[],this.gltf);t.uniform4fv(u.uBaseColor,y.baseColor),t.uniform1f(u.uMetallic,y.metallic),t.uniform1f(u.uRoughness,y.roughness),u.uClearcoat&&t.uniform2f(u.uClearcoat,y.clearcoat??0,y.clearcoatRoughness??.04),y.texture?(t.activeTexture(33984),t.bindTexture(3553,y.texture),t.uniform1i(u.uBaseColorTexture,0),t.uniform1i(u.uHasTexture,1)):t.uniform1i(u.uHasTexture,0),y.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,y.metallicRoughnessTexture),t.uniform1i(u.uMetallicRoughnessTexture,1),t.uniform1i(u.uHasMetallicRoughnessTexture,1)):t.uniform1i(u.uHasMetallicRoughnessTexture,0),y.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,y.normalTexture),t.uniform1i(u.uNormalTexture,2),t.uniform1i(u.uHasNormalTexture,1),t.uniform1f(u.uNormalScale,y.normalScale)):t.uniform1i(u.uHasNormalTexture,0),y.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,y.occlusionTexture),t.uniform1i(u.uOcclusionTexture,3),t.uniform1i(u.uHasOcclusionTexture,1),t.uniform1f(u.uOcclusionStrength,y.occlusionStrength)):t.uniform1i(u.uHasOcclusionTexture,0),t.bindVertexArray(y.vao);let C=p.instanceMatrices;if(y.instanceCount!==void 0)t.drawElementsInstanced(4,y.indexCount,y.indexType,0,y.instanceCount);else if(C&&C.length>=16&&y.instanced&&u.uInstanced&&u.uViewProj){let H=C.length>>4;t.uniform1i(u.uInstanced,1),t.uniformMatrix4fv(u.uViewProj,!1,o),y.indices?t.drawElementsInstanced(4,y.indexCount,y.indexType,0,H):t.drawArraysInstanced(4,0,y.indexCount,H),t.uniform1i(u.uInstanced,0)}else if(C&&C.length>=16){let H=C.length>>4,Q=p.instanceColors,I=z(),k=new Float32Array(9),R=[y.baseColor[0],y.baseColor[1],y.baseColor[2],y.baseColor[3]];for(let N=0;N<H;N++)J(I,this.modelMatrix,C.subarray(N*16,N*16+16)),J(this.mvpMatrix,o,I),ut(k,I),t.uniformMatrix4fv(u.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(u.uModel,!1,I),t.uniformMatrix3fv(u.uNormalMatrix,!1,k),Q&&(R[0]=y.baseColor[0]*Q[N*3],R[1]=y.baseColor[1]*Q[N*3+1],R[2]=y.baseColor[2]*Q[N*3+2],R[3]=y.baseColor[3],t.uniform4fv(u.uBaseColor,R)),bt(t,y)}else bt(t,y)}}};if(M(!1),b){for(let d of G)d.onBeforeTransmissivePass?.(t,this);M(!0)}for(let d of G)d.onAfterRender?.(t,this,o,e?.eye??"none",[i,r,s,a],e?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(e,t){Gt(this.gl,e,t)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let e=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let t of G)t.onDestroy?.(e,this);this.environmentTexture&&(e.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&e.deleteProgram(this.renderProg),this.pickProg&&e.deleteProgram(this.pickProg),this.pickFbo&&e.deleteFramebuffer(this.pickFbo),this.pickTexture&&e.deleteTexture(this.pickTexture),this.pickDepth&&e.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};rt.registerPlugin=ee,rt.getRegisteredPlugins=ie;var Dt=(e,t,i)=>({x:e,y:t,z:i,toString:()=>`${e}m ${t}m ${i}m`}),ye=typeof HTMLElement<"u"?HTMLElement:class{};typeof CustomEvent>"u"&&typeof Event<"u"&&(globalThis.CustomEvent=class extends Event{constructor(e,t){super(e,t),this.detail=t?.detail??null}});var xt=class Y extends ye{constructor(){super(...arguments),this.viewer=null,this.canvas=null,this.posterEl=null,this.arButton=null,this.currentModel=null,this.activeXRSession=null,this.toastTimer=null,this.currentModelLimits=void 0,this.isModelLoaded=!1,this.scriptHandle=null,this.loadController=null,this.resizeObserver=null,this.mutationObserver=null}static get arProvider(){return Z().arProvider}static set arProvider(t){Z().arProvider=t}static get scriptRunner(){return Z().scriptRunner}static set scriptRunner(t){Z().scriptRunner=t}static get sandboxEngineSrc(){return Z().sandboxEngineSrc??null}static set sandboxEngineSrc(t){Z().sandboxEngineSrc=t}static get sandboxIframeSrc(){return Z().sandboxIframeSrc??null}static set sandboxIframeSrc(t){Z().sandboxIframeSrc=t}static get allowClientScripts(){return!!Z().allowClientScripts}static set allowClientScripts(t){Z().allowClientScripts=t}static registerScriptRunner(t){Y.scriptRunner=t}static defineModelViewer(t="model-viewer"){if(typeof customElements>"u")return!1;let i=customElements.get(t);if(i!=null)return i===Y||i.prototype instanceof Y;class r extends Y{}return customElements.define(t,r),!0}static registerDecoder(t,i){rt.registerDecoder(t,i)}static getDecoder(t){return rt.getDecoder(t)}static registerAR(t){typeof t=="function"?Y.arProvider={activateAR:t}:Y.arProvider=t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(i=>{i instanceof Y&&i.updateARButtonVisibility()})}static isARSupported(){return!!Y.arProvider}getLoadedModel(){return this.currentModel}beginLoad(){let t=this.loadController,i=this.scriptHandle,r=new AbortController;return this.loadController=r,this.scriptHandle=null,t?.abort(),i?.terminate(),r}connectedCallback(){if(typeof document>"u")return;(!this.style.display||this.style.display==="inline")&&(this.style.display="block"),getComputedStyle(this).position==="static"&&(this.style.position="relative"),this.style.overflow="hidden",this.setupDOM(),this.initViewer(),this.setupResizeObserver();let t=this.getAttribute("src"),i=this.getAttribute("script-src");if(t)this.loadModel(t).catch(()=>{});else if(i)this.loadScriptFromSrc(i).catch(()=>{});else{let r=this.querySelector('script[type="text/three"], script[type="text/three-live"]');r&&r.textContent&&this.executeScript(r.textContent).catch(()=>{})}for(let r of rt.getRegisteredPlugins())r.onElementConnected?.(this)}disconnectedCallback(){for(let t of rt.getRegisteredPlugins())t.onElementDisconnected?.(this);this.beginLoad().abort(),this.mutationObserver?.disconnect(),this.mutationObserver=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.activeXRSession?.stop?.().catch?.(()=>{}),this.activeXRSession=null,this.toastTimer&&clearTimeout(this.toastTimer),this.toastTimer=null,this.viewer?.destroy(),this.viewer=null,this.isModelLoaded=!1}attributeChangedCallback(t,i,r){if(i!==r){switch(t){case"src":r&&this.loadModel(r).catch(()=>{});break;case"camera-target":this.applyCameraTarget(r);break;case"min-camera-orbit":case"max-camera-orbit":this.applyOrbitLimits();break;case"field-of-view":this.applyFieldOfView(r);break;case"script-src":r&&this.loadScriptFromSrc(r).catch(()=>{});break;case"sandbox":case"allow-client-scripts":case"ios-src":break;case"poster":this.updatePoster(r);break;case"camera-orbit":this.applyCameraOrbit(r);break;case"selected-mesh":this.viewer&&r!==null&&this.viewer.setSelectedMesh(r);break;case"exposure":if(this.viewer&&r!==null){let s=parseFloat(r);isNaN(s)||this.viewer.setExposure(s)}break;case"shadow-intensity":case"shadow-softness":this.viewer&&this.viewer.setShadow(this.shadowIntensity,this.shadowSoftness);break;case"tone-mapping":this.viewer?.setToneMapping(dt(r));break;case"environment-image":this.viewer&&this.viewer.setEnvironmentImage(r).catch(()=>{});break;case"skybox-image":this.viewer&&this.viewer.setSkyboxImage?.(r)?.catch?.(()=>{});break;case"camera-controls":{let s=this.cameraControls;this.viewer&&this.viewer.setInteractive?.(s),this.canvas&&(this.canvas.style.touchAction=s?"none":"auto");break}case"autoplay":this.viewer&&this.viewer.setAutoplay(r!==null&&r!=="false");break;case"animation-name":this.viewer&&r!==null&&this.viewer.setAnimationName(r);break;case"variant-name":this.viewer&&this.selectVariant(r);break;case"auto-rotate":this.viewer&&this.viewer.setAutoRotate(r!==null&&r!=="false");break;case"auto-rotate-delay":this.viewer&&this.viewer.setAutoRotateDelay(this.autoRotateDelay);break;case"rotation-per-second":this.viewer&&this.viewer.setAutoRotateSpeed(this.parseRotationPerSecond(r));break;case"ar":this.updateARButtonVisibility();break}for(let s of rt.getRegisteredPlugins())s.onAttributeChanged?.(this,t,i,r)}}getAttr(t){return this.getAttribute(t)}setAttr(t,i){i!==null?this.setAttribute(t,String(i)):this.removeAttribute(t)}getBoolAttr(t){return this.hasAttribute(t)&&this.getAttr(t)!=="false"}setBoolAttr(t,i){this.setAttr(t,i?"":null)}getFloatAttr(t,i){let r=this.getAttr(t);return r!==null?parseFloat(r):i}get src(){return this.getAttr("src")}set src(t){this.setAttr("src",t)}get cameraControls(){return this.getBoolAttr("camera-controls")}set cameraControls(t){this.setBoolAttr("camera-controls",t)}get cameraOrbit(){return this.getAttr("camera-orbit")}set cameraOrbit(t){this.setAttr("camera-orbit",t)}get cameraTarget(){return this.getAttr("camera-target")}set cameraTarget(t){this.setAttr("camera-target",t)}get minCameraOrbit(){return this.getAttr("min-camera-orbit")}set minCameraOrbit(t){this.setAttr("min-camera-orbit",t)}get maxCameraOrbit(){return this.getAttr("max-camera-orbit")}set maxCameraOrbit(t){this.setAttr("max-camera-orbit",t)}get fieldOfView(){return this.getAttr("field-of-view")}set fieldOfView(t){this.setAttr("field-of-view",t)}get iosSrc(){return this.getAttr("ios-src")}set iosSrc(t){this.setAttr("ios-src",t)}get scriptSrc(){return this.getAttr("script-src")}set scriptSrc(t){this.setAttr("script-src",t)}get sandbox(){return this.getAttr("sandbox")||(Z().sandboxIframeSrc?"iframe":"worker")}set sandbox(t){this.setAttr("sandbox",t)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||Y.allowClientScripts}set allowClientScripts(t){this.setBoolAttr("allow-client-scripts",t)}get poster(){return this.getAttr("poster")}set poster(t){this.setAttr("poster",t)}get selectedMesh(){return this.getAttr("selected-mesh")}set selectedMesh(t){this.setAttr("selected-mesh",t)}get exposure(){return this.getFloatAttr("exposure",1)}set exposure(t){this.setAttr("exposure",t)}get autoRotate(){return this.getBoolAttr("auto-rotate")}set autoRotate(t){this.setBoolAttr("auto-rotate",t)}get autoRotateDelay(){return this.getFloatAttr("auto-rotate-delay",3e3)}set autoRotateDelay(t){this.setAttr("auto-rotate-delay",t)}get rotationPerSecond(){return this.getAttr("rotation-per-second")||"30deg"}set rotationPerSecond(t){this.setAttr("rotation-per-second",t)}get turntableRotation(){return this.viewer?this.viewer.turntableRotation:0}get ar(){return this.hasAttribute("ar")}set ar(t){this.setBoolAttr("ar",t)}get arScale(){return this.getAttr("ar-scale")||"auto"}set arScale(t){this.setAttr("ar-scale",t)}get arPlacement(){return this.getAttr("ar-placement")||"floor"}set arPlacement(t){this.setAttr("ar-placement",t)}get canActivateAR(){return Y.isARSupported()}get shadowIntensity(){return this.getFloatAttr("shadow-intensity",0)}set shadowIntensity(t){this.setAttr("shadow-intensity",t)}get shadowSoftness(){return this.getFloatAttr("shadow-softness",.5)}set shadowSoftness(t){this.setAttr("shadow-softness",t)}get toneMapping(){return dt(this.getAttr("tone-mapping"))}set toneMapping(t){this.setAttr("tone-mapping",t)}get bloom(){return this.getFloatAttr("bloom",0)}set bloom(t){this.setAttr("bloom",t)}get bloomThreshold(){return Lt(this.getAttr("bloom-threshold"),.62)}set bloomThreshold(t){this.setAttr("bloom-threshold",t)}get bloomRadius(){return Lt(this.getAttr("bloom-radius"),.75)}set bloomRadius(t){this.setAttr("bloom-radius",t)}get outlineSelected(){return this.getBoolAttr("outline-selected")}set outlineSelected(t){this.setBoolAttr("outline-selected",t)}get outlineColor(){return this.getAttr("outline-color")||"#38bdf8"}set outlineColor(t){this.setAttr("outline-color",t)}get environmentImage(){return this.getAttr("environment-image")}set environmentImage(t){this.setAttr("environment-image",t)}get skyboxImage(){return this.getAttr("skybox-image")}set skyboxImage(t){this.setAttr("skybox-image",t)}get autoplay(){return this.getBoolAttr("autoplay")}set autoplay(t){this.setBoolAttr("autoplay",t)}get animationName(){return this.getAttr("animation-name")}set animationName(t){this.setAttr("animation-name",t)}get availableAnimations(){return this.viewer?this.viewer.getAvailableAnimations():[]}get variantName(){return this.viewer?this.viewer.getVariantName():this.getAttr("variant-name")}set variantName(t){this.setAttr("variant-name",t)}get availableVariants(){return this.viewer?this.viewer.getAvailableVariants():[]}fireEvent(t,i){this.dispatchEvent(new CustomEvent(t,{bubbles:!0,composed:!0,detail:i}))}setSlotVisible(t,i){let r=typeof this.querySelector=="function"?this.querySelector(`[slot="${t}"]`):null;r&&(r.hidden=!i,r.style&&(r.style.display=i?"":"none"))}emitError(t,i="script"){this.setSlotVisible("error",!0),this.fireEvent("error",{error:t}),this.fireEvent("three-error",{error:t,message:t?.message||String(t),stage:i})}selectVariant(t){if(!this.viewer)return!1;let i=this.viewer.selectVariant(t);return i&&this.fireEvent("variant-applied",{variantName:this.viewer.getVariantName()}),i}get model(){let t=this.viewer?this.viewer.getModelMaterials():[];return{materials:t,getMaterialByName(i){return t.find(r=>r.name===i)??null}}}play(){this.viewer&&this.viewer.playAnimation(this.animationName||void 0)}pause(){this.viewer&&this.viewer.pauseAnimation()}resetCamera(){this.viewer?.resetCamera()}resetTurntableRotation(t=0){this.viewer?.resetTurntableRotation(t)}setCamera(t,i,r,s){this.viewer&&this.viewer.setCamera(t,i,r,s)}getCameraOrbit(){return this.viewer?this.viewer.getCameraOrbit():{theta:0,phi:0,radius:3,toString(){return"0rad 0rad 3m"}}}getCameraTarget(){return this.viewer?this.viewer.getCameraTarget():Dt(0,0,0)}getFieldOfView(){return this.viewer?this.viewer.getFieldOfView():45}jumpCameraToGoal(){this.viewer?.jumpCameraToGoal()}toDataURL(t,i){return this.viewer?.render?.(),this.canvas?this.canvas.toDataURL(t,i):""}toBlob(t){return this.viewer?.render?.(),new Promise((i,r)=>{if(!this.canvas||typeof this.canvas.toBlob!="function"){r(new Error("Canvas toBlob is not supported in this environment."));return}this.canvas.toBlob(s=>{s?i(s):r(new Error("Failed to capture canvas blob."))},t?.mimeType,t?.qualityArgument)})}positionAndNormalFromPoint(t,i){let r=this.viewer?.raycastFromScreenPoint(t,i);if(!r)return null;let[s,a,o]=r.hitPoint||r.point,[h,n,l]=r.normal;return{position:Dt(s,a,o),normal:Dt(h,n,l)}}loadModel(t){return this.loadModelWithLimits(t)}async loadModelWithLimits(t,i,r=this.beginLoad()){if(r.signal.throwIfAborted(),!this.viewer){this.currentModel=t,this.currentModelLimits=i;return}try{let s;if(typeof t=="string"){let n=await fetch(t,{signal:r.signal});if(!n.ok)throw new Error(`Failed to load "${t}": HTTP ${n.status}`);s=await n.arrayBuffer()}else s=t;r.signal.throwIfAborted();let a=vt(s);this.viewer.loadGLBData(a,i),this.currentModel=a,this.currentModelLimits=i,this.isModelLoaded=!0,this.hidePoster(),this.setSlotVisible("error",!1),this.updateHotspots();let o=this.getAttr("selected-mesh");o&&this.viewer.setSelectedMesh(o);let h=this.getAttr("variant-name");h&&this.selectVariant(h),this.fireEvent("load",{model:a}),this.fireEvent("three-load",{model:a,source:typeof t=="string"?"src":"model"})}catch(s){throw r.signal.aborted||this.emitError(s,"load"),s}}showToast(t,i=4500){if(typeof document>"u")return;let r=this.querySelector(".three-live-toast");r||(r=document.createElement("div"),r.className="three-live-toast",r.style.cssText="position:absolute;bottom:70px;left:50%;transform:translateX(-50%) translateY(10px);z-index:10;padding:10px 16px;background-color:rgba(15,23,42,0.94);color:#f8fafc;border:1px solid rgba(56,189,248,0.45);border-radius:14px;font:500 13px/1.35 system-ui,-apple-system,sans-serif;box-shadow:0 10px 25px rgba(0,0,0,0.45);backdrop-filter:blur(12px);pointer-events:none;opacity:0;transition:opacity .25s ease,transform .25s ease;max-width:88%;text-align:center;white-space:normal;word-break:break-word",this.appendChild(r)),r.textContent=t,this.toastTimer&&clearTimeout(this.toastTimer);let s=()=>{r&&(r.style.opacity="1",r.style.transform="translateX(-50%) translateY(0)")};typeof requestAnimationFrame<"u"?requestAnimationFrame(s):s(),this.toastTimer=setTimeout(()=>{r&&(r.style.opacity="0",r.style.transform="translateX(-50%) translateY(10px)"),this.toastTimer=null},i)}async activateAR(){this.activeXRSession?.isSessionActive?.()&&(await this.activeXRSession.stop().catch(()=>{}),this.activeXRSession=null);let t=(s,a=s.message)=>{throw this.fireEvent("ar-status",{status:"failed",error:s}),this.showToast(a,6e3),s};this.currentModel||t(new Error("No 3D model is loaded in <three-live>.")),Y.arProvider||t(new Error("AR module not bundled. Use the default 'three-live' bundle or call ThreeLiveElement.registerAR()."));let i=this.getAttr("ios-src"),r=(this.getAttr("ar-modes")||"").split(/\s+/).filter(Boolean);try{this.fireEvent("ar-status",{status:"session-started"});let s=await Y.arProvider.activateAR({model:i||this.currentModel,glbUrl:typeof this.currentModel=="string"?this.currentModel:void 0,view:this.viewer||void 0,element:this,preferredModes:r.length>0?r:void 0,arScale:this.arScale,arPlacement:this.arPlacement,webXROptions:{onExit:()=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"not-presenting"})},onError:a=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"failed",error:a}),this.showToast(`AR error: ${a.message}`,6e3)}}});if(s.success){s.session&&(this.activeXRSession=s.session);let a=s.mode==="quick-look"?"Opening Apple AR Quick Look...":s.mode==="scene-viewer"?"Opening Google Scene Viewer...":s.mode==="webxr"?"WebXR AR session started.":"";a&&this.showToast(a)}else{let a=s.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.";if(this.isDesktopMac()&&typeof document<"u"&&this.currentModel&&Y.arProvider.createUSDZBlob)try{let o=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:Y.arProvider.createUSDZBlob(this.currentModel),h=URL.createObjectURL(o),n=document.createElement("a");n.href=h,n.download="three_live_model.usdz",document.body.appendChild(n),n.click(),document.body.removeChild(n),setTimeout(()=>URL.revokeObjectURL(h),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(a,6e3)}else this.showToast(a,6e3);s.error&&this.fireEvent("ar-status",{status:"failed",error:s.error})}return s}catch(s){return this.activeXRSession=null,t(s,`AR error: ${s.message||String(s)}`)}}setupDOM(){let t=this.querySelector("canvas");t||(t=document.createElement("canvas"),t.style.cssText=`width:100%;height:100%;display:block;touch-action:${this.cameraControls?"none":"auto"};outline:none`,this.appendChild(t)),this.canvas=t,typeof t.addEventListener=="function"&&!t.__tlCtxBound&&(t.__tlCtxBound=!0,t.addEventListener("webglcontextlost",r=>this.fireEvent("three-context-lost",{originalEvent:r})),t.addEventListener("webglcontextrestored",r=>this.fireEvent("three-context-restored",{originalEvent:r}))),this.setSlotVisible("error",!1),this.isModelLoaded||this.setSlotVisible("poster",!0);let i=this.getAttr("poster");i&&this.updatePoster(i),this.createARButton(),typeof MutationObserver<"u"&&!this.mutationObserver&&(this.mutationObserver=new MutationObserver(()=>{this.updateARButtonVisibility()}),this.mutationObserver.observe(this,{childList:!0}))}initViewer(){if(!this.canvas)return;let t=this.autoRotate,i=this.exposure,r=this.parseOrbitLimit(this.getAttr("min-camera-orbit")),s=this.parseOrbitLimit(this.getAttr("max-camera-orbit")),a=this.parseCameraTarget(this.getAttr("camera-target")),o=this.parseFieldOfView(this.getAttr("field-of-view"));this.viewer=new rt(this,this.canvas,{autoRotate:t,autoRotateDelay:this.autoRotateDelay,autoRotateSpeed:this.parseRotationPerSecond(this.getAttr("rotation-per-second")),exposure:i,shadowIntensity:this.shadowIntensity,shadowSoftness:this.shadowSoftness,toneMapping:this.toneMapping,environmentImage:this.environmentImage,autoplay:this.autoplay,animationName:this.animationName||void 0,variantName:this.getAttr("variant-name")||void 0,fieldOfView:o,cameraTarget:a,minCameraOrbit:r,maxCameraOrbit:s,onMeshClick:n=>{this.fireEvent("meshclick",n)},onCameraChange:n=>{this.updateHotspots();for(let l of rt.getRegisteredPlugins())l.onCameraChange?.(this.viewer,this);this.fireEvent("camera-change",n)}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let h=this.getAttr("camera-orbit");h&&this.applyCameraOrbit(h),this.currentModel&&this.loadModelWithLimits(this.currentModel,this.currentModelLimits)}setupResizeObserver(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>{this.viewer&&(this.viewer.resize(),this.viewer.render(),this.updateHotspots())}),this.resizeObserver.observe(this))}updatePoster(t){if(!(typeof document>"u")){if(!t){this.posterEl&&(this.posterEl.remove(),this.posterEl=null);return}this.posterEl||(this.posterEl=document.createElement("img"),this.posterEl.alt="3D Scene Preview",this.posterEl.style.cssText="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity .35s ease-out;pointer-events:none;z-index:1",this.appendChild(this.posterEl)),this.posterEl.src=t,this.isModelLoaded||(this.posterEl.style.opacity="1")}}hidePoster(){this.setSlotVisible("poster",!1),this.posterEl&&(this.posterEl.style.opacity="0",setTimeout(()=>{this.isModelLoaded&&this.posterEl&&(this.posterEl.remove(),this.posterEl=null)},400))}isDesktopMac(){let t=typeof navigator<"u"&&navigator.userAgent||"";return/Macintosh/i.test(t)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1)&&!/Android|iPhone|iPad|iPod/i.test(t)}syncARButtonLabel(t){let i=this.isDesktopMac(),r=i?"Quick Look (.usdz)":"View in AR",s=i?"Download .usdz preview for macOS Quick Look (live camera AR requires iOS or Android)":"View in Augmented Reality";typeof t.setAttribute=="function"&&(t.setAttribute("aria-label",s),t.setAttribute("title",s));let a=t._labelSpan||(typeof t.querySelector=="function"?t.querySelector("span"):null);a&&(a.textContent=r)}createARButton(){if(!(typeof document>"u")){if(!this.arButton){let t=document.createElement("button");t.type="button",t.className="three-live-ar-button",t.setAttribute("part","default-ar-button");let i="http://www.w3.org/2000/svg";if(typeof document.createElementNS=="function"){let s=document.createElementNS(i,"svg");for(let[o,h]of[["width","20"],["height","20"],["viewBox","0 0 24 24"],["fill","none"],["stroke","currentColor"],["stroke-width","2"],["stroke-linecap","round"],["stroke-linejoin","round"]])s.setAttribute(o,h);s.style.marginRight="6px";let a=document.createElementNS(i,"path");a.setAttribute("d","M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16zM3.27 6.96 12 12.01l8.73-5.05M12 22.08V12"),s.appendChild(a),t.appendChild(s)}let r=document.createElement("span");t._labelSpan=r,t.appendChild(r),this.syncARButtonLabel(t),t.style.cssText="position:absolute;right:16px;bottom:16px;z-index:2;align-items:center;justify-content:center;padding:8px 16px;background-color:rgba(15,23,42,0.85);color:#fff;border:1px solid rgba(255,255,255,0.15);border-radius:9999px;font:600 13px system-ui,-apple-system,sans-serif;cursor:pointer;backdrop-filter:blur(8px);box-shadow:0 4px 12px rgba(0,0,0,0.25);transition:transform .15s ease,background-color .15s ease;display:none",t.addEventListener("mouseenter",()=>{t.style.backgroundColor="rgba(30, 41, 59, 0.95)",t.style.transform="scale(1.04)"}),t.addEventListener("mouseleave",()=>{t.style.backgroundColor="rgba(15, 23, 42, 0.85)",t.style.transform="scale(1)"}),t.addEventListener("click",s=>{s.stopPropagation(),this.activateAR()}),this.arButton=t,this.appendChild(t)}this.updateARButtonVisibility()}}updateARButtonVisibility(){let t=this.hasAttribute("ar")&&!!Y.arProvider,i=typeof this.querySelector=="function"?this.querySelector('[slot="ar-button"]'):null;i?(this.arButton&&(this.arButton.style.display="none"),i.__tlARBound||(i.__tlARBound=!0,i.addEventListener("click",r=>{r.stopPropagation(),this.activateAR()})),i.dataset.tlOrigDisplay===void 0&&(i.dataset.tlOrigDisplay=i.style.display==="none"?"":i.style.display),i.style.display=t?i.dataset.tlOrigDisplay||"":"none"):this.arButton&&(this.syncARButtonLabel(this.arButton),this.arButton.style.display=t?"flex":"none")}applyCameraOrbit(t){if(!(!t||!this.viewer))try{let i=JSON.parse(t);this.viewer.setInitialCamera(i.theta,i.phi,i.distance,i.zoom)}catch{let i=this.parseOrbitLimit(t);(i.theta!==void 0||i.phi!==void 0)&&this.viewer.setInitialCamera(i.theta,i.phi,i.distance)}}parseOrbitLimit(t){if(!t)return{};let[i,r,s]=t.trim().split(/\s+/),a=s&&s!=="auto"?parseFloat(s):NaN;return{theta:i&&i!=="auto"?this.parseFieldOfView(i):void 0,phi:r&&r!=="auto"?this.parseFieldOfView(r):void 0,distance:isNaN(a)?void 0:a}}applyOrbitLimits(){if(!this.viewer)return;let t=this.parseOrbitLimit(this.getAttr("min-camera-orbit")),i=this.parseOrbitLimit(this.getAttr("max-camera-orbit"));this.viewer.setOrbitLimits({minTheta:t.theta,maxTheta:i.theta,minPhi:t.phi,maxPhi:i.phi,minDistance:t.distance,maxDistance:i.distance})}parseCameraTarget(t){if(!t)return;let i=t.trim().split(/\s+/).map(parseFloat);return i.length>=3&&!i.some(isNaN)?[i[0],i[1],i[2]]:void 0}parseFieldOfView(t){if(!t)return;let i=parseFloat(t);return isNaN(i)?void 0:t.endsWith("rad")?i*180/Math.PI:i}parseRotationPerSecond(t){if(!t)return Math.PI/6;let i=t.trim(),r=parseFloat(i);return isNaN(r)?Math.PI/6:i.endsWith("rad")?r:i.endsWith("%")?r/100*Math.PI*2:r*Math.PI/180}applyCameraTarget(t){let i=this.parseCameraTarget(t);this.viewer&&i&&this.viewer.setTarget(i[0],i[1],i[2])}applyFieldOfView(t){let i=this.parseFieldOfView(t);this.viewer&&i!==void 0&&this.viewer.setFieldOfView(i)}updateHotspot(t){let i=this.querySelector(`[slot="${t.name}"]`);i&&(t.position!==void 0&&i.setAttribute("data-position",t.position),t.normal!==void 0&&i.setAttribute("data-normal",t.normal)),this.updateHotspots()}updateHotspots(){for(let t of rt.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}runWithScriptRunner(t){let i=Y.scriptRunner;if(!i){let a=new Error('Script execution requires "three-live/full" or registerScriptRunner().');return this.showToast(a.message),this.emitError(a,"script"),Promise.reject(a)}let r=this.beginLoad(),s=()=>!r.signal.aborted;return new Promise((a,o)=>{let h=()=>o(r.signal.reason);if(r.signal.addEventListener("abort",h,{once:!0}),!s()){h();return}let n={onModelReady:l=>{this.loadModelWithLimits(l,be,r).then(()=>a(l),o)},onUpdateTransforms:l=>{s()&&this.viewer?.updateMeshTransforms(l)},onError:l=>{s()&&(this.showToast(l.message),this.emitError(l,"script"),o(l))},onToast:l=>{s()&&this.showToast(l)}};t(i,n).then(l=>{s()?this.scriptHandle=l||null:l?.terminate()},l=>{s()&&n.onError?.(l)})})}loadScriptFromSrc(t){return this.runWithScriptRunner((i,r)=>{if(typeof i.executeUrl!="function"){let s=new Error("Registered ScriptRunner does not support executeUrl() for server-generated scripts.");return r.onError?.(s),Promise.reject(s)}return i.executeUrl(t,this.sandbox,r)})}executeScript(t){if(!Y.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let i=new Error(Qt);return this.showToast(te),this.emitError(i,"security"),Promise.reject(i)}return this.runWithScriptRunner((i,r)=>i.execute(t,this.sandbox,r,{allowClientScripts:!0}))}};xt.observedAttributes=["src","ios-src","script-src","sandbox","allow-client-scripts","poster","camera-controls","camera-orbit","camera-target","min-camera-orbit","max-camera-orbit","field-of-view","selected-mesh","ar","ar-modes","ar-scale","ar-placement","exposure","shadow-intensity","shadow-softness","tone-mapping","bloom","bloom-threshold","bloom-radius","outline","outline-selected","outline-color","environment-image","skybox-image","autoplay","animation-name","variant-name","auto-rotate","auto-rotate-delay","rotation-per-second"],xt.registerPlugin=rt.registerPlugin,xt.getRegisteredPlugins=rt.getRegisteredPlugins;var Wt=xt;return typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",Wt),Jt(Et)})();