three-live 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +1 -1
  2. package/dist/index.d.ts +36 -0
  3. package/dist/three-author-engine.js +86 -62
  4. package/dist/three-author.cjs +84 -60
  5. package/dist/three-author.d.ts +36 -0
  6. package/dist/three-author.js +83 -59
  7. package/dist/three-convert.cjs +78 -58
  8. package/dist/three-convert.d.ts +36 -0
  9. package/dist/three-convert.js +77 -57
  10. package/dist/three-live-animation.cjs +8 -9
  11. package/dist/three-live-animation.d.ts +36 -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 +36 -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 +36 -0
  21. package/dist/three-live-element.js +16 -19
  22. package/dist/three-live-full.cjs +110 -86
  23. package/dist/three-live-full.js +107 -83
  24. package/dist/three-live-full.min.js +110 -86
  25. package/dist/three-live-studio.cjs +19 -20
  26. package/dist/three-live-studio.d.ts +36 -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 +36 -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 +87 -63
  34. package/dist/three-live.js +86 -62
  35. package/dist/three-live.min.js +86 -62
  36. package/dist/three-view.cjs +17 -20
  37. package/dist/three-view.d.ts +36 -0
  38. package/dist/three-view.js +16 -19
  39. package/dist/three-xr.cjs +78 -58
  40. package/dist/three-xr.d.ts +36 -0
  41. package/dist/three-xr.js +77 -57
  42. package/package.json +7 -1
package/dist/three-xr.js CHANGED
@@ -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
- function re(){let n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n}function ve(n,e,t,r,i){let s=1/Math.tan(e/2);n.fill(0),n[0]=s/t,n[5]=s,n[11]=-1;let a=1/(r-i);return n[10]=(i+r)*a,n[14]=2*i*r*a,n}function Me(n,e,t,r){let[i,s,a]=e,[c,o,l]=r,[u,d,f]=t,T=i-u,g=s-d,m=a-f,p=Math.hypot(T,g,m);p<=1e-5?(T=0,g=0,m=1):(T/=p,g/=p,m/=p);let R=o*m-l*g,A=l*T-c*m,v=c*g-o*T;p=Math.hypot(R,A,v),p<=1e-5?(R=0,A=0,v=0):(R/=p,A/=p,v/=p);let D=g*v-m*A,y=m*R-T*v,P=T*A-g*R;return p=Math.hypot(D,y,P),p<=1e-5?(D=0,y=0,P=0):(D/=p,y/=p,P/=p),n[0]=R,n[1]=D,n[2]=T,n[3]=0,n[4]=A,n[5]=y,n[6]=g,n[7]=0,n[8]=v,n[9]=P,n[10]=m,n[11]=0,n[12]=-(R*i+A*s+v*a),n[13]=-(D*i+y*s+P*a),n[14]=-(T*i+g*s+m*a),n[15]=1,n}function se(n,e,t){let r=e[0],i=e[1],s=e[2],a=e[3],c=e[4],o=e[5],l=e[6],u=e[7],d=e[8],f=e[9],T=e[10],g=e[11],m=e[12],p=e[13],R=e[14],A=e[15],v=t[0],D=t[1],y=t[2],P=t[3];return n[0]=v*r+D*c+y*d+P*m,n[1]=v*i+D*o+y*f+P*p,n[2]=v*s+D*l+y*T+P*R,n[3]=v*a+D*u+y*g+P*A,v=t[4],D=t[5],y=t[6],P=t[7],n[4]=v*r+D*c+y*d+P*m,n[5]=v*i+D*o+y*f+P*p,n[6]=v*s+D*l+y*T+P*R,n[7]=v*a+D*u+y*g+P*A,v=t[8],D=t[9],y=t[10],P=t[11],n[8]=v*r+D*c+y*d+P*m,n[9]=v*i+D*o+y*f+P*p,n[10]=v*s+D*l+y*T+P*R,n[11]=v*a+D*u+y*g+P*A,v=t[12],D=t[13],y=t[14],P=t[15],n[12]=v*r+D*c+y*d+P*m,n[13]=v*i+D*o+y*f+P*p,n[14]=v*s+D*l+y*T+P*R,n[15]=v*a+D*u+y*g+P*A,n}function ye(n,e,t,r){let i=e[0],s=e[1],a=e[2],c=e[3],o=i+i,l=s+s,u=a+a,d=i*o,f=i*l,T=i*u,g=s*l,m=s*u,p=a*u,R=c*o,A=c*l,v=c*u,D=r[0],y=r[1],P=r[2];return n[0]=(1-(g+p))*D,n[1]=(f+v)*D,n[2]=(T-A)*D,n[3]=0,n[4]=(f-v)*y,n[5]=(1-(d+p))*y,n[6]=(m+R)*y,n[7]=0,n[8]=(T+A)*P,n[9]=(m-R)*P,n[10]=(1-(d+g))*P,n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n}function me(n,e,t=0){let r=e[0],i=e[1],s=e[2],a=e[4],c=e[5],o=e[6],l=e[8],u=e[9],d=e[10],f=d*c-o*u,T=-d*a+o*l,g=u*a-c*l,m=r*f+i*T+s*g;return!m||t>0&&(!Number.isFinite(m)||Math.abs(m)<=t)||(m=1/m,n[0]=f*m,n[1]=T*m,n[2]=g*m,n[3]=(-d*i+s*u)*m,n[4]=(d*r-s*l)*m,n[5]=(-u*r+i*l)*m,n[6]=(o*i-s*c)*m,n[7]=(-o*r+s*a)*m,n[8]=(c*r-i*a)*m),n}function Ge(n,e){let t=e[0],r=e[1],i=e[2],s=e[3],a=e[4],c=e[5],o=e[6],l=e[7],u=e[8],d=e[9],f=e[10],T=e[11],g=e[12],m=e[13],p=e[14],R=e[15],A=t*c-r*a,v=t*o-i*a,D=t*l-s*a,y=r*o-i*c,P=r*l-s*c,E=i*l-s*o,b=u*m-d*g,F=u*p-f*g,L=u*R-T*g,C=d*p-f*m,h=d*R-T*m,w=f*R-T*p,S=A*w-v*h+D*C+y*L-P*F+E*b;return S?(S=1/S,n[0]=(c*w-o*h+l*C)*S,n[1]=(i*h-r*w-s*C)*S,n[2]=(m*E-p*P+R*y)*S,n[3]=(f*P-d*E-T*y)*S,n[4]=(o*L-a*w-l*F)*S,n[5]=(t*w-i*L+s*F)*S,n[6]=(p*D-g*E-R*v)*S,n[7]=(u*E-f*D+T*v)*S,n[8]=(a*h-c*L+l*b)*S,n[9]=(r*L-t*h-s*b)*S,n[10]=(g*P-m*D+R*A)*S,n[11]=(d*D-u*P-T*A)*S,n[12]=(c*F-a*C-o*b)*S,n[13]=(t*C-r*F+i*b)*S,n[14]=(m*v-g*y-p*A)*S,n[15]=(u*y-d*v+f*A)*S,n):null}function De(n,e,t,r,i){let s=i[0]*e+i[4]*t+i[8]*r+i[12],a=i[1]*e+i[5]*t+i[9]*r+i[13],c=i[2]*e+i[6]*t+i[10]*r+i[14],o=i[3]*e+i[7]*t+i[11]*r+i[15],l=o!==0?1/o:1;n[0]=s*l,n[1]=a*l,n[2]=c*l}function ze(n,e,t,r,i,s,a,c,o,l,u,d,f,T,g,m,p=0){let R=l-a,A=u-c,v=d-o,D=f-a,y=T-c,P=g-o,E=i*P-s*y,b=s*D-r*P,F=r*y-i*D,L=R*E+A*b+v*F;if(L>-1e-7&&L<1e-7)return!1;let C=1/L,h=n-a,w=e-c,S=t-o,M=C*(h*E+w*b+S*F);if(M<-p||M>1+p)return!1;let k=w*v-S*A,_=S*R-h*v,K=h*A-w*R,U=C*(r*k+i*_+s*K);if(U<-p||M+U>1+p)return!1;let O=C*(D*k+y*_+P*K);if(O>1e-4&&O<m.distance){m.distance=O,m.point=[n+r*O,e+i*O,t+s*O];let B=A*P-v*y,q=v*D-R*P,Y=R*y-A*D,W=Math.hypot(B,q,Y)||1;return m.normal=[B/W,q/W,Y/W],!0}return!1}function Te(n,e){let t=Array.isArray(n?.nodes)?n.nodes.length:0,r=[];for(let u=0;u<t;u++)r.push(re());if(t===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,a=128,c=(u,d,f=0)=>{if(f>a||u<0||u>=t||s.has(u))return;s.add(u);let T=n.nodes[u];if(!T)return;let g=re();if(e&&e[u])g.set(e[u]);else if(T.matrix&&T.matrix.length===16)g.set(T.matrix);else{let p=T.translation||[0,0,0],R=T.rotation||[0,0,0,1],A=T.scale||[1,1,1];ye(g,R,p,A)}let m=r[u];if(d?se(m,d,g):m.set(g),Array.isArray(T.children))for(let p of T.children)typeof p=="number"&&c(p,m,f+1)},o=[],l=n.scenes&&n.scenes[n.scene!==void 0?n.scene:0];if(l&&Array.isArray(l.nodes))o.push(...l.nodes);else for(let u=0;u<t;u++)i.has(u)||o.push(u);for(let u of o)c(u,null);for(let u=0;u<t;u++)!i.has(u)&&!o.includes(u)&&c(u,null);return r}var Ae="__THREE_LIVE_REGISTRY__";function he(){let n=typeof globalThis<"u"?globalThis:{};if(!n[Ae]){let e={plugins:[],decoders:new Map};try{Object.defineProperty(n,Ae,{value:e,writable:!1,configurable:!1,enumerable:!1})}catch{n[Ae]=e}}return n[Ae]}var ae=he().plugins;function He(n){let e=he().plugins;e.some(t=>t.name===n.name)||e.push(n),n.onRegister?.()}function We(){return he().plugins}function we(n,e,t,r=!0){let i=[],s=null;try{for(let[a,c]of[[35633,e],[35632,t]]){let o=n.createShader(a);if(!o){if(r)throw new Error("Shader allocation failed");return null}if(i.push(o),n.shaderSource(o,c),n.compileShader(o),n.getShaderParameter&&!n.getShaderParameter(o,35713)){if(r)throw new Error(`Shader compile error: ${n.getShaderInfoLog(o)}`);return null}}if(s=n.createProgram(),!s){if(r)throw new Error("Program allocation failed");return null}for(let a of i)n.attachShader(s,a);if(n.linkProgram(s),n.getProgramParameter&&!n.getProgramParameter(s,35714)){let a=r?n.getProgramInfoLog(s):null;if(n.deleteProgram?.(s),s=null,r)throw new Error(`Program link error: ${a}`);return null}return s}finally{for(let a of i)s&&n.detachShader?.(s,a),n.deleteShader?.(a)}}var yt={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function Fe(n,e,t,r){if(!t||t.bufferView===void 0)return null;let i=n.bufferViews?.[t.bufferView];if(!i)return null;let s=Number(t.count??0);if(!Number.isInteger(s)||s<=0)return null;let a=t.componentType??5126,c=yt[a];if(!c)throw new RangeError(`glTF accessor has unsupported componentType ${a}`);let o=c*r,l=i.byteStride&&i.byteStride>0?i.byteStride:o,u=(i.byteOffset||0)+(t.byteOffset||0);if(!Number.isInteger(u)||u<0||l<o||u+(s-1)*l+o>e.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${e.byteLength} bytes)`);if(a===5126&&l===o&&u%4===0)return new Float32Array(e,u,s*r);let d=new DataView(e),f=t.normalized===!0,T=new Float32Array(s*r);for(let g=0;g<s;g++){let m=u+g*l;for(let p=0;p<r;p++){let R=m+p*c,A;switch(a){case 5126:A=d.getFloat32(R,!0);break;case 5120:A=d.getInt8(R),f&&(A=Math.max(A/127,-1));break;case 5121:A=d.getUint8(R),f&&(A/=255);break;case 5122:A=d.getInt16(R,!0),f&&(A=Math.max(A/32767,-1));break;case 5123:A=d.getUint16(R,!0),f&&(A/=65535);break;default:A=d.getUint32(R,!0),f&&(A/=4294967295)}T[g*r+p]=A}}return T}function Xe(n,e){let t=Number(e.offset?.[0]??0)||0,r=Number(e.offset?.[1]??0)||0,i=Number(e.scale?.[0]??1),s=Number(e.scale?.[1]??1),a=Number(e.rotation??0)||0,c=Math.cos(a),o=Math.sin(a),l=(Number.isFinite(i)?i:1)*c,u=(Number.isFinite(i)?i:1)*o,d=-(Number.isFinite(s)?s:1)*o,f=(Number.isFinite(s)?s:1)*c;for(let T=0;T+1<n.length;T+=2){let g=n[T],m=n[T+1];n[T]=l*g+u*m+t,n[T+1]=d*g+f*m+r}}var Ye=["neutral","reinhard","none","aces","agx"];function _e(n){let e=String(n??"").trim().toLowerCase();return Ye.includes(e)?e:"neutral"}function gt(n){return Ye.indexOf(_e(n))}function xt(n){return new TextDecoder().decode(n)}var Ke=he().decoders;function vt(n,e){Ke.set(n.toLowerCase(),e)}function pe(n){return Ke.get(n.toLowerCase())}function Ze(n){let e=ArrayBuffer.isView(n)?n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength):n,t=new DataView(e);if(e.byteLength<12)throw new Error(`Invalid GLB buffer size: ${e.byteLength} bytes`);let r=t.getUint32(0,!0);if(r!==1179937895){let f=t.getUint8(0);throw f===123||f===32||f===10||f===13?new Error("[three-live] Multi-file JSON .gltf is not supported for performance reasons. Please pack your asset into a single binary .glb file."):new Error(`Invalid GLB magic: 0x${r.toString(16)}`)}let i=t.getUint32(4,!0);if(i!==2)throw new Error(`Unsupported GLB version: ${i}`);let s=t.getUint32(8,!0),a=12,c=null,o=null;for(;a+8<=s&&a+8<=e.byteLength;){let f=t.getUint32(a,!0),T=t.getUint32(a+4,!0),g=a+8;if(g+f>e.byteLength)throw new Error(`Truncated GLB chunk: required ${g+f} bytes, buffer has ${e.byteLength}`);if(T===1313821514){let m=new Uint8Array(e,g,f),p=xt(m);c=JSON.parse(p,(R,A)=>R==="__proto__"||R==="constructor"||R==="prototype"?void 0:A)}else T===5130562&&(o=e.slice(g,g+f));a=g+f}if(!c)throw new Error("Missing JSON chunk in GLB");let l=c.extensionsRequired||[];if(l.includes("KHR_draco_mesh_compression")&&!pe("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");for(let f of["EXT_meshopt_compression","KHR_meshopt_compression"])if(l.includes(f)&&!pe("meshopt"))throw new Error(`Model requires ${f}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(l.includes("KHR_texture_basisu")&&!pe("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let u=o||new ArrayBuffer(0),d={gltf:c,bin:u,animations:[]};for(let f of ae)f.onParseGLB?.(d);return d}function Mt(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 xe(n){if(Mt(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
+ */function le(){let e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function _e(e,t,i,r,a){let s=1/Math.tan(t/2);e.fill(0),e[0]=s/i,e[5]=s,e[11]=-1;let u=1/(r-a);return e[10]=(a+r)*u,e[14]=2*a*r*u,e}function Fe(e,t,i,r){let[a,s,u]=t,[o,d,f]=r,[p,y,D]=i,S=a-p,h=s-y,v=u-D,P=Math.hypot(S,h,v);P<=1e-5?(S=0,h=0,v=1):(S/=P,h/=P,v/=P);let T=d*v-f*h,x=f*S-o*v,c=o*h-d*S;P=Math.hypot(T,x,c),P<=1e-5?(T=0,x=0,c=0):(T/=P,x/=P,c/=P);let l=h*c-v*x,b=v*T-S*c,w=S*x-h*T;return P=Math.hypot(l,b,w),P<=1e-5?(l=0,b=0,w=0):(l/=P,b/=P,w/=P),e[0]=T,e[1]=l,e[2]=S,e[3]=0,e[4]=x,e[5]=b,e[6]=h,e[7]=0,e[8]=c,e[9]=w,e[10]=v,e[11]=0,e[12]=-(T*a+x*s+c*u),e[13]=-(l*a+b*s+w*u),e[14]=-(S*a+h*s+v*u),e[15]=1,e}function me(e,t,i){let r=t[0],a=t[1],s=t[2],u=t[3],o=t[4],d=t[5],f=t[6],p=t[7],y=t[8],D=t[9],S=t[10],h=t[11],v=t[12],P=t[13],T=t[14],x=t[15],c=i[0],l=i[1],b=i[2],w=i[3];return e[0]=c*r+l*o+b*y+w*v,e[1]=c*a+l*d+b*D+w*P,e[2]=c*s+l*f+b*S+w*T,e[3]=c*u+l*p+b*h+w*x,c=i[4],l=i[5],b=i[6],w=i[7],e[4]=c*r+l*o+b*y+w*v,e[5]=c*a+l*d+b*D+w*P,e[6]=c*s+l*f+b*S+w*T,e[7]=c*u+l*p+b*h+w*x,c=i[8],l=i[9],b=i[10],w=i[11],e[8]=c*r+l*o+b*y+w*v,e[9]=c*a+l*d+b*D+w*P,e[10]=c*s+l*f+b*S+w*T,e[11]=c*u+l*p+b*h+w*x,c=i[12],l=i[13],b=i[14],w=i[15],e[12]=c*r+l*o+b*y+w*v,e[13]=c*a+l*d+b*D+w*P,e[14]=c*s+l*f+b*S+w*T,e[15]=c*u+l*p+b*h+w*x,e}function Ke(e,t,i,r){let a=t[0],s=t[1],u=t[2],o=t[3],d=a+a,f=s+s,p=u+u,y=a*d,D=a*f,S=a*p,h=s*f,v=s*p,P=u*p,T=o*d,x=o*f,c=o*p,l=r[0],b=r[1],w=r[2];return e[0]=(1-(h+P))*l,e[1]=(D+c)*l,e[2]=(S-x)*l,e[3]=0,e[4]=(D-c)*b,e[5]=(1-(y+P))*b,e[6]=(v+T)*b,e[7]=0,e[8]=(S+x)*w,e[9]=(v-T)*w,e[10]=(1-(y+h))*w,e[11]=0,e[12]=i[0],e[13]=i[1],e[14]=i[2],e[15]=1,e}function be(e,t,i=0){let r=t[0],a=t[1],s=t[2],u=t[4],o=t[5],d=t[6],f=t[8],p=t[9],y=t[10],D=y*o-d*p,S=-y*u+d*f,h=p*u-o*f,v=r*D+a*S+s*h;return!v||i>0&&(!Number.isFinite(v)||Math.abs(v)<=i)||(v=1/v,e[0]=D*v,e[1]=S*v,e[2]=h*v,e[3]=(-y*a+s*p)*v,e[4]=(y*r-s*f)*v,e[5]=(-p*r+a*f)*v,e[6]=(d*a-s*o)*v,e[7]=(-d*r+s*u)*v,e[8]=(o*r-a*u)*v),e}function Tt(e,t){let i=t[0],r=t[1],a=t[2],s=t[3],u=t[4],o=t[5],d=t[6],f=t[7],p=t[8],y=t[9],D=t[10],S=t[11],h=t[12],v=t[13],P=t[14],T=t[15],x=i*o-r*u,c=i*d-a*u,l=i*f-s*u,b=r*d-a*o,w=r*f-s*o,O=a*f-s*d,B=p*v-y*h,E=p*P-D*h,N=p*T-S*h,R=y*P-D*v,L=y*T-S*v,M=D*T-S*P,n=x*M-c*L+l*R+b*N-w*E+O*B;return n?(n=1/n,e[0]=(o*M-d*L+f*R)*n,e[1]=(a*L-r*M-s*R)*n,e[2]=(v*O-P*w+T*b)*n,e[3]=(D*w-y*O-S*b)*n,e[4]=(d*N-u*M-f*E)*n,e[5]=(i*M-a*N+s*E)*n,e[6]=(P*l-h*O-T*c)*n,e[7]=(p*O-D*l+S*c)*n,e[8]=(u*L-o*N+f*B)*n,e[9]=(r*N-i*L-s*B)*n,e[10]=(h*w-v*l+T*x)*n,e[11]=(y*l-p*w-S*x)*n,e[12]=(o*E-u*R-d*B)*n,e[13]=(i*R-r*E+a*B)*n,e[14]=(v*c-h*b-P*x)*n,e[15]=(p*b-y*c+D*x)*n,e):null}function Xe(e,t,i,r,a){let s=a[0]*t+a[4]*i+a[8]*r+a[12],u=a[1]*t+a[5]*i+a[9]*r+a[13],o=a[2]*t+a[6]*i+a[10]*r+a[14],d=a[3]*t+a[7]*i+a[11]*r+a[15],f=d!==0?1/d:1;e[0]=s*f,e[1]=u*f,e[2]=o*f}function Pt(e,t,i,r,a,s,u,o,d,f,p,y,D,S,h,v,P=0){let T=f-u,x=p-o,c=y-d,l=D-u,b=S-o,w=h-d,O=a*w-s*b,B=s*l-r*w,E=r*b-a*l,N=T*O+x*B+c*E;if(N>-1e-7&&N<1e-7)return!1;let R=1/N,L=e-u,M=t-o,n=i-d,$=R*(L*O+M*B+n*E);if($<-P||$>1+P)return!1;let W=M*c-n*x,g=n*T-L*c,_=L*x-M*T,m=R*(r*W+a*g+s*_);if(m<-P||$+m>1+P)return!1;let A=R*(l*W+b*g+w*_);if(A>1e-4&&A<v.distance){v.distance=A,v.point=[e+r*A,t+a*A,i+s*A];let q=x*w-c*b,K=c*l-T*w,H=T*b-x*l,Q=Math.hypot(q,K,H)||1;return v.normal=[q/Q,K/Q,H/Q],!0}return!1}function At(e,t){let i=Array.isArray(e?.nodes)?e.nodes.length:0,r=[];for(let p=0;p<i;p++)r.push(le());if(i===0)return r;let a=new Set;for(let p of e.nodes)if(Array.isArray(p.children))for(let y of p.children)a.add(y);let s=new Set,u=128,o=(p,y,D=0)=>{if(D>u||p<0||p>=i||s.has(p))return;s.add(p);let S=e.nodes[p];if(!S)return;let h=le();if(t&&t[p])h.set(t[p]);else if(S.matrix&&S.matrix.length===16)h.set(S.matrix);else{let P=S.translation||[0,0,0],T=S.rotation||[0,0,0,1],x=S.scale||[1,1,1];Ke(h,T,P,x)}let v=r[p];if(y?me(v,y,h):v.set(h),Array.isArray(S.children))for(let P of S.children)typeof P=="number"&&o(P,v,D+1)},d=[],f=e.scenes&&e.scenes[e.scene!==void 0?e.scene:0];if(f&&Array.isArray(f.nodes))d.push(...f.nodes);else for(let p=0;p<i;p++)a.has(p)||d.push(p);for(let p of d)o(p,null);for(let p=0;p<i;p++)!a.has(p)&&!d.includes(p)&&o(p,null);return r}var Pe="__THREE_LIVE_REGISTRY__";function pe(){let e=typeof globalThis<"u"?globalThis:{};if(!e[Pe]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(e,Pe,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{e[Pe]=t}}return e[Pe]}var he=pe().plugins;function Rt(e){let t=pe().plugins;t.some(i=>i.name===e.name)||t.push(e),e.onRegister?.()}function Ct(){return pe().plugins}function St(e,t,i){let r=[],a=new Map,s=[],u=[],o=[],d=new Map,f=c=>{let l=a.get(c);return l===void 0&&(l=r.length,r.push({op:c}),a.set(c,l)),l},p=c=>{let l=d.get(c);return l===void 0&&(l=o.length,o.push({id:c}),d.set(c,l)),l},y=(c,l={})=>s.push({declaration:f(c),...l})-1,D=(c,l,b)=>u.push({id:c,type:l,value:b})-1,S=c=>({node:c,socket:"value"}),h=i?.interactivity??i?.gltfExtensions?.KHR_interactivity;if(h&&typeof h=="object"){let c=Array.isArray(h.graphs)?h.graphs[h.graph??0]:h;if(c&&Array.isArray(c.nodes)){let l=Array.isArray(c.declarations)?c.declarations:[];for(let b of l)b?.op&&f(b.op);Array.isArray(c.variables)&&u.push(...c.variables);for(let b of c.events||[])b?.id&&p(b.id);for(let b of c.nodes){if(!b||typeof b!="object")continue;let w=b.op||(typeof b.declaration=="number"?l[b.declaration]?.op:"");s.push(w?{...b,declaration:f(w)}:{...b})}}}let v=(c,l,b="translation")=>b==="baseColorFactor"||b==="metallicFactor"||b==="roughnessFactor"?`/materials/${Math.max(0,l)}/pbrMetallicRoughness/${b}`:b==="emissiveFactor"||b==="alphaCutoff"?`/materials/${Math.max(0,l)}/${b}`:b==="visible"?`/nodes/${c}/extensions/KHR_node_visibility/visible`:`/nodes/${c}/${b}`,P=new Map;e.forEach((c,l)=>{typeof c?.name=="string"&&!P.has(c.name)&&P.set(c.name,l)});let T=(c,l)=>typeof c.target=="string"&&P.has(c.target)?P.get(c.target):typeof c.targetNode=="number"?c.targetNode:l,x=c=>{let l=e[c];return(typeof l?.mesh=="number"?t[l.mesh]?.primitives?.[0]?.material:0)??0};for(let c=0;c<e.length;c++){let l=e[c],b=l?.extras?.interactivity;if(!b||typeof b!="object")continue;let w=(typeof l.mesh=="number"?t[l.mesh]?.primitives?.[0]?.material:0)??0,O=E=>{let N=Array.isArray(E)?E:[E],R=[];for(let M=0;M<N.length;M++){let n=N[M];if(!n||typeof n!="object")continue;let $=n.action||"interpolate",W=typeof n.duration=="number"?n.duration:.35;if($==="toggleTransform"){let g=n.property==="rotation"||n.property==="scale"?n.property:"translation",_=g==="rotation"?l.rotation||[0,0,0,1]:g==="scale"?l.scale||[1,1,1]:l.translation||[0,0,0],m=`/nodes/${c}/${g}`,A=D(`__toggle_${c}_${M}`,"bool",!1),q=y("variable/get",{configuration:{variable:A}}),K=y("math/not",{values:{a:S(q)}}),H=y("variable/set",{configuration:{variable:A},values:{value:S(K)}}),Q=y("pointer/interpolate",{configuration:{pointer:m},values:{value:{value:Array.isArray(n.to)?n.to:_},duration:{value:W}}}),C=y("pointer/interpolate",{configuration:{pointer:m},values:{value:{value:Array.isArray(n.from)?n.from:_},duration:{value:W}}});s[H].flows={out:{node:y("flow/branch",{values:{condition:S(q)},flows:{true:{node:Q},false:{node:C}}})}},R.push(H)}else if($==="interpolate"){let g=n.to??n.value;if(g===void 0)continue;let _={value:{value:g},duration:{value:W}};n.from!==void 0&&(_.from={value:n.from}),R.push(y("pointer/interpolate",{configuration:{pointer:typeof n.pointer=="string"?n.pointer:v(T(n,c),x(T(n,c)),n.property)},values:_}))}else if($==="setProperty"){if(n.value===void 0)continue;R.push(y("pointer/set",{configuration:{pointer:typeof n.pointer=="string"?n.pointer:v(T(n,c),x(T(n,c)),n.property)},values:{value:{value:n.value}}}))}else if($==="toggleVisibility"){let g=T(n,c),_=D(`__vis_${g}_${M}`,"bool",!0),m=y("variable/get",{configuration:{variable:_}}),A=y("math/not",{values:{a:S(m)}}),q=y("variable/set",{configuration:{variable:_},values:{value:S(A)}});s[q].flows={out:{node:y("pointer/set",{configuration:{pointer:`/nodes/${g}/extensions/KHR_node_visibility/visible`},values:{value:S(m)}})}},R.push(q)}else if($==="cycleMaterialColor"&&Array.isArray(n.colors)&&n.colors.length>0){let g=typeof n.duration=="number"?n.duration:.25,_=`/materials/${Math.max(0,w)}/pbrMetallicRoughness/baseColorFactor`,m=D(`__color_idx_${c}_${M}`,"int",0),A=y("variable/get",{configuration:{variable:m}}),q=y("math/add",{values:{a:S(A),b:{value:1}}}),K=y("math/rem",{values:{a:S(q),b:{value:n.colors.length}}}),H=y("variable/set",{configuration:{variable:m},values:{value:S(K)}}),Q={};for(let C=0;C<n.colors.length;C++){let U=n.colors[C],k=Array.isArray(U)&&U.length>=3?[U[0],U[1],U[2],U[3]??1]:[1,1,1,1];Q[String(C)]={node:g>0?y("pointer/interpolate",{configuration:{pointer:_},values:{value:{value:k},duration:{value:g}}}):y("pointer/set",{configuration:{pointer:_},values:{value:{value:k}}})}}s[H].flows={out:{node:y("flow/switch",{values:{selection:S(A)},flows:Q})}},R.push(H)}else if($==="playAnimation")R.push(y("animation/start",{configuration:{animation:n.animation??n.clip??0}}));else if($==="stopAnimation")R.push(y("animation/stop"));else if($==="sendEvent"){let g={};for(let[_,m]of Object.entries(n.values||{}))g[_]={value:m};R.push(y("event/send",{configuration:{event:p(String(n.event??n.id??"custom"))},values:g}))}}if(!R.length)return null;if(R.length===1)return R[0];let L={};return R.forEach((M,n)=>{L[String(n)]={node:M}}),y("flow/sequence",{flows:L})},B=(E,N,R)=>{let L=O(N);L!==null&&y(E,{...R?{configuration:R}:{},flows:{out:{node:L}}})};if(b.onSelect&&B("pointer/onSelect",b.onSelect,{nodeIndex:c}),b.onHoverIn&&B("pointer/onHoverIn",b.onHoverIn,{nodeIndex:c}),b.onHoverOut&&B("pointer/onHoverOut",b.onHoverOut,{nodeIndex:c}),b.onStart&&B("event/onStart",b.onStart),b.onReceive&&typeof b.onReceive=="object")for(let[E,N]of Object.entries(b.onReceive))B("event/receive",N,{event:p(E)})}return s.length?{graphs:[{declarations:r,nodes:s,variables:u,events:o}],graph:0}:null}var Dt={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function We(e,t,i,r){if(!i||i.bufferView===void 0)return null;let a=e.bufferViews?.[i.bufferView];if(!a)return null;let s=Number(i.count??0);if(!Number.isInteger(s)||s<=0)return null;let u=i.componentType??5126,o=Dt[u];if(!o)throw new RangeError(`glTF accessor has unsupported componentType ${u}`);let d=o*r,f=a.byteStride&&a.byteStride>0?a.byteStride:d,p=(a.byteOffset||0)+(i.byteOffset||0);if(!Number.isInteger(p)||p<0||f<d||p+(s-1)*f+d>t.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${t.byteLength} bytes)`);if(u===5126&&f===d&&p%4===0)return new Float32Array(t,p,s*r);let y=new DataView(t),D=i.normalized===!0,S=new Float32Array(s*r);for(let h=0;h<s;h++){let v=p+h*f;for(let P=0;P<r;P++){let T=v+P*o,x;switch(u){case 5126:x=y.getFloat32(T,!0);break;case 5120:x=y.getInt8(T),D&&(x=Math.max(x/127,-1));break;case 5121:x=y.getUint8(T),D&&(x/=255);break;case 5122:x=y.getInt16(T,!0),D&&(x=Math.max(x/32767,-1));break;case 5123:x=y.getUint16(T,!0),D&&(x/=65535);break;default:x=y.getUint32(T,!0),D&&(x/=4294967295)}S[h*r+P]=x}}return S}function Lt(e,t){let i=Number(t.offset?.[0]??0)||0,r=Number(t.offset?.[1]??0)||0,a=Number(t.scale?.[0]??1),s=Number(t.scale?.[1]??1),u=Number(t.rotation??0)||0,o=Math.cos(u),d=Math.sin(u),f=(Number.isFinite(a)?a:1)*o,p=(Number.isFinite(a)?a:1)*d,y=-(Number.isFinite(s)?s:1)*d,D=(Number.isFinite(s)?s:1)*o;for(let S=0;S+1<e.length;S+=2){let h=e[S],v=e[S+1];e[S]=f*h+p*v+i,e[S+1]=y*h+D*v+r}}function Ee(e,t,i,r=!0){let a=[],s=null;try{for(let[u,o]of[[35633,t],[35632,i]]){let d=e.createShader(u);if(!d){if(r)throw new Error("Shader allocation failed");return null}if(a.push(d),e.shaderSource(d,o),e.compileShader(d),e.getShaderParameter&&!e.getShaderParameter(d,35713)){if(r)throw new Error(`Shader compile error: ${e.getShaderInfoLog(d)}`);return null}}if(s=e.createProgram(),!s){if(r)throw new Error("Program allocation failed");return null}for(let u of a)e.attachShader(s,u);if(e.linkProgram(s),e.getProgramParameter&&!e.getProgramParameter(s,35714)){let u=r?e.getProgramInfoLog(s):null;if(e.deleteProgram?.(s),s=null,r)throw new Error(`Program link error: ${u}`);return null}return s}finally{for(let u of a)s&&e.detachShader?.(s,u),e.deleteShader?.(u)}}var Ye=["neutral","reinhard","none","aces","agx"];function ke(e){let t=String(e??"").trim().toLowerCase();return Ye.includes(t)?t:"neutral"}function It(e){return Ye.indexOf(ke(e))}function _t(e){return new TextDecoder().decode(e)}var Ze=pe().decoders;function Ft(e,t){Ze.set(e.toLowerCase(),t)}function Me(e){return Ze.get(e.toLowerCase())}function Qe(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 D=i.getUint8(0);throw D===123||D===32||D===10||D===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 a=i.getUint32(4,!0);if(a!==2)throw new Error(`Unsupported GLB version: ${a}`);let s=i.getUint32(8,!0),u=12,o=null,d=null;for(;u+8<=s&&u+8<=t.byteLength;){let D=i.getUint32(u,!0),S=i.getUint32(u+4,!0),h=u+8;if(h+D>t.byteLength)throw new Error(`Truncated GLB chunk: required ${h+D} bytes, buffer has ${t.byteLength}`);if(S===1313821514){let v=new Uint8Array(t,h,D),P=_t(v);o=JSON.parse(P,(T,x)=>T==="__proto__"||T==="constructor"||T==="prototype"?void 0:x)}else S===5130562&&(d=t.slice(h,h+D));u=h+D}if(!o)throw new Error("Missing JSON chunk in GLB");let f=o.extensionsRequired||[];if(f.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 D of["EXT_meshopt_compression","KHR_meshopt_compression"])if(f.includes(D)&&!Me("meshopt"))throw new Error(`Model requires ${D}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(f.includes("KHR_texture_basisu")&&!Me("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let p=d||new ArrayBuffer(0),y={gltf:o,bin:p,animations:[]};for(let D of he)D.onParseGLB?.(y);return y}function Et(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 Ae(e){if(Et(e))return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Qe(e);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var Je=`#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
- }`,Tt=`#version 300 es
51
+ }`,kt=`#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,80 +239,103 @@ color=applyToneMapping(color,uToneMapping);
242
239
  float outAlpha=base.a;
243
240
  /*XRD_O*/
244
241
  fragColor=vec4(color,outAlpha);
245
- }`;var At=`#version 300 es
242
+ }`,Nt=`#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);}`,wt=`#version 300 es
245
+ void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,Vt=`#version 300 es
249
246
  precision highp float;
250
247
  uniform vec4 uColorId;
251
248
  out vec4 fragColor;
252
- void main(){fragColor=uColorId;}`;function Ne(n,e,t){let r={};for(let i of t)r[i]=n.getUniformLocation(e,i);return r}var $e=["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 Qe(){let n=he().xrDepthShader;return{fs:Tt.replace("/*XRD_U*/",n?.uniformsGLSL||"").replace("/*XRD_O*/",n?.occlusionGLSL||""),uniforms:n?[...$e,...n.uniformNames]:$e}}function Rt(n){if(typeof n!="string")return null;let e=n.trim();if(!e||/[\x00-\x1f\x7f]/.test(e))return null;let t=e.toLowerCase();return t.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(e)?e:null:t.startsWith("https://")||t.startsWith("blob:")?e:t.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(e)||/(^|[\\/])\.\.([\\/]|$)/.test(e)?null:e}function Ce(n,e,t,r,i,s,a,c){if(r===void 0||!e.accessors?.[r])return null;let o=Fe(e,t,e.accessors[r],s);if(!o)return null;c&&(o=o.slice(),Xe(o,c));let l=n.createBuffer();return a.push(l),n.bindBuffer(34962,l),n.bufferData(34962,o,35044),n.enableVertexAttribArray(i),n.vertexAttribPointer(i,s,5126,!1,0,0),o}function Ie(n){let e=Number(n);return Number.isFinite(e)?Math.max(0,e):1}function Je(n,e,t){let r=Qe(),i=je,s=r.fs,a=!1;for(let o of ae)if(o.onResolveShader){let l=o.onResolveShader(e,t,i,s);l&&(i=l.vs,s=l.fs,a=!0)}let c=a?we(n,i,s):null;return{program:c,uniforms:c?Ne(n,c,r.uniforms):null}}function Et(n,e,t){let r=e.instanceMatrices;if(!r||r.length<16||typeof n.vertexAttribDivisor!="function"||typeof n.drawElementsInstanced!="function")return!1;let i=r.length>>4,s=e.instanceColors,a=new Float32Array(i*20);for(let o=0;o<i;o++)a.set(r.subarray(o*16,o*16+16),o*20),a[o*20+16]=s?s[o*3]:1,a[o*20+17]=s?s[o*3+1]:1,a[o*20+18]=s?s[o*3+2]:1,a[o*20+19]=1;let c=n.createBuffer();t.push(c),n.bindBuffer(34962,c),n.bufferData(34962,a,35044);for(let o=0;o<5;o++)n.enableVertexAttribArray(8+o),n.vertexAttribPointer(8+o,4,5126,!1,80,o*16),n.vertexAttribDivisor(8+o,1);return!0}function Lt(n,e){let t=n.materials?.[e?.material];if(!t)return null;let r=[t.pbrMetallicRoughness?.baseColorTexture,t.pbrMetallicRoughness?.metallicRoughnessTexture,t.normalTexture,t.occlusionTexture,t.emissiveTexture];for(let i of r){let s=i?.extensions?.KHR_texture_transform;if(s&&typeof s=="object")return s}return null}var $t=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),et=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Re(n,e){e.indices?n.drawElements(4,e.indexCount,e.indexType,0):n.drawArrays(4,0,e.indexCount)}function tt(n,e){let t=n?.pbrMetallicRoughness,r=t?.baseColorFactor,i=n?.extensions?.KHR_materials_clearcoat,s=a=>a!==void 0&&e[a.index]?e[a.index]:null;return{baseColor:r?[r[0],r[1],r[2],r[3]??1]:[.8,.8,.8,1],metallic:t?.metallicFactor??.1,roughness:t?.roughnessFactor??.5,clearcoat:i?i.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,i?.clearcoatRoughnessFactor??.04),texture:s(t?.baseColorTexture),metallicRoughnessTexture:s(t?.metallicRoughnessTexture),normalTexture:s(n?.normalTexture),normalScale:n?.normalTexture?.scale??1,occlusionTexture:s(n?.occlusionTexture),occlusionStrength:n?.occlusionTexture?.strength??1,isTransmissive:(n?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function nt(n,e,t){let r=new Set,i=s=>{s&&!r.has(s)&&(r.add(s),n.deleteTexture(s))};for(let s of e)for(let a of s.primitives){if(a.vao&&n.deleteVertexArray(a.vao),a.buffers)for(let o of a.buffers)n.deleteBuffer(o);i(a.texture),i(a.metallicRoughnessTexture),i(a.normalTexture),i(a.occlusionTexture);let c=new Set;a.customProgram&&c.add(a.customProgram);for(let o of a.programCache?.values()??[])o.program&&c.add(o.program);for(let o of c)n.deleteProgram(o)}if(t)for(let s of t)i(s)}function qe(n,e,t=et,r){let i={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return St(n,e,t,r,i)}catch(s){let a=i.mesh&&!i.meshes.includes(i.mesh)?[...i.meshes,i.mesh]:i.meshes;nt(n,a,i.gpuTextures),i.vao&&n.deleteVertexArray(i.vao);for(let c of i.buffers)n.deleteBuffer(c);throw s}}function St(n,e,t,r,i){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:s}=e,a=pe("meshopt");a?.decodeBufferViews&&a.decodeBufferViews(s,e);let c=e.bin,o=[];i.meshes=o;let l=[],u=s.extensions?.KHR_materials_variants;u&&Array.isArray(u.variants)&&u.variants.forEach((h,w)=>{l.push(typeof h?.name=="string"&&h.name?h.name:`Variant_${w}`)});let d=Te(s),f=[];if(Array.isArray(s.nodes))for(let h=0;h<s.nodes.length;h++){let w=s.nodes[h];w.mesh!==void 0&&s.meshes&&s.meshes[w.mesh]&&f.push({node:w,nodeIdx:h,meshIdx:w.mesh})}let T=f.length>0?f:(s.meshes||[]).map((h,w)=>({node:h,nodeIdx:-1,meshIdx:w})),g=[];if(Array.isArray(e.lights)&&e.lights.length>0)g.push(...e.lights);else if(s.extensions?.KHR_lights_punctual?.lights){let h=s.extensions.KHR_lights_punctual.lights;for(let w of h){let S=w.type==="directional"?"directional":w.type==="point"?"point":"ambient";g.push({type:S,color:w.color||[1,1,1],intensity:w.intensity!==void 0?w.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]})),T.length>t.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${t.maxMeshes}). Found: ${T.length}`);let m=[];if(i.gpuTextures=m,s.textures&&s.images){if(s.textures.length>t.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${t.maxTextures}). Found: ${s.textures.length}`);for(let h=0;h<s.textures.length;h++){let w=s.textures[h],S=s.images[w.source];if(S){let M=n.createTexture();if(n.bindTexture(3553,M),n.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),n.texParameteri(3553,10242,10497),n.texParameteri(3553,10243,10497),n.texParameteri(3553,10241,9729),n.texParameteri(3553,10240,9729),S.bufferView!==void 0){let k=s.bufferViews[S.bufferView],_=c.slice(k.byteOffset||0,(k.byteOffset||0)+k.byteLength),K=new Blob([_],{type:S.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(K).then(U=>{n.bindTexture(3553,M),n.texImage2D(3553,0,6408,6408,5121,U),n.generateMipmap(3553),r?.()}).catch(()=>{})}else if(S.uri){let k=Rt(S.uri);if(k){let _=new Image;_.crossOrigin="anonymous",_.referrerPolicy="no-referrer",_.onload=()=>{n.bindTexture(3553,M),n.texImage2D(3553,0,6408,6408,5121,_),n.generateMipmap(3553),r?.()},_.src=k}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",S.uri)}m.push(M)}else m.push(null)}}let p=[1/0,1/0,1/0],R=[-1/0,-1/0,-1/0],A=0,v=0;for(let h=0;h<T.length;h++){let w=T[h],S=s.meshes[w.meshIdx],M=w.nodeIdx>=0?d[w.nodeIdx]:re(),k=new Float32Array(9);me(k,M);let _={name:w.node.name||S.name||`Mesh_${w.meshIdx}`,nodeIndex:w.nodeIdx,transform:M,normalMatrix:k,primitives:[],extras:w.node.extras||S.extras};i.mesh=_;let K=w.node?.extensions?.EXT_mesh_gpu_instancing;if(K&&K.attributes&&typeof K.attributes=="object"){let U=K.attributes,O=U.TRANSLATION!==void 0?s.accessors?.[U.TRANSLATION]:null,B=U.ROTATION!==void 0?s.accessors?.[U.ROTATION]:null,q=U.SCALE!==void 0?s.accessors?.[U.SCALE]:null,Y=U._COLOR_0!==void 0?s.accessors?.[U._COLOR_0]:null,W=Number(O?.count??B?.count??q?.count??0);if(!Number.isFinite(W)||W<0||W>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${W}`);if(W>0){let j=(H,$)=>{if(!H||H.bufferView===void 0||!s.bufferViews?.[H.bufferView])return null;let G=H.componentType??5126,te=J=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${J})`),null);if(G!==5120&&G!==5121&&G!==5122&&G!==5123&&G!==5126)return te(`componentType ${G}`);if(!(Number(H.count)>=W))return te(`count ${H.count} < ${W}`);let V=null;try{V=Fe(s,c,{...H,count:W},$)}catch{return te("out of bounds")}return!V||!V.every(Number.isFinite)?te("non-finite value"):V},x=j(O,3),I=j(B,4),N=j(q,3),z=Y?.type==="VEC4"?4:3,ee=j(Y,z),ie=new Float32Array(W*16),oe=re();for(let H=0;H<W;H++){let $=x?[x[H*3],x[H*3+1],x[H*3+2]]:[0,0,0],G=I?[I[H*4],I[H*4+1],I[H*4+2],I[H*4+3]]:[0,0,0,1],te=N?[N[H*3],N[H*3+1],N[H*3+2]]:[1,1,1];ye(oe,G,$,te),ie.set(oe,H*16)}if(_.instanceMatrices=ie,ee){let H=new Float32Array(W*3);for(let $=0;$<W;$++)H[$*3]=ee[$*z],H[$*3+1]=ee[$*z+1],H[$*3+2]=ee[$*z+2];_.instanceColors=H}}}for(let U of S.primitives||[]){if(U.extensions?.KHR_draco_mesh_compression){let V=pe("draco");V&&V.decodePrimitive(s,U,c)}let O=[],B=n.createVertexArray();i.vao=B,i.buffers=O,n.bindVertexArray(B);let q=Et(n,_,O),Y=s.accessors[U.attributes.POSITION],W=Number(Y?.count??0);if(!Number.isFinite(W)||W<0||A+W>t.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${t.maxVertices}).`);if(A+=W,Y?.min&&Y?.max){let V=J=>{for(let Q=0;Q<3;Q++){let Z=J[12+Q],ne=J[12+Q];for(let le=0;le<3;le++){let ce=J[le*4+Q]*Y.min[le],ue=J[le*4+Q]*Y.max[le];Z+=ce<ue?ce:ue,ne+=ce>ue?ce:ue}Z<p[Q]&&(p[Q]=Z),ne>R[Q]&&(R[Q]=ne)}};if(_.instanceMatrices&&_.instanceMatrices.length>=16){let J=_.instanceMatrices.length>>4,Q=re();for(let Z=0;Z<J;Z++){let ne=_.instanceMatrices.subarray(Z*16,Z*16+16);se(Q,M,ne),V(Q)}}else V(M)}let j=Ce(n,s,c,U.attributes.POSITION,0,3,O);Ce(n,s,c,U.attributes.NORMAL,1,3,O),Ce(n,s,c,U.attributes.TEXCOORD_0,2,2,O,Lt(s,U));let x=0,I=5123,N=null;if(U.indices!==void 0){let V=s.accessors[U.indices],Q=(s.bufferViews[V.bufferView].byteOffset||0)+(V.byteOffset||0);if(x=Number(V.count??0),!Number.isFinite(x)||x<0||v+x>t.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${t.maxIndices}).`);v+=x,I=V.componentType===5125?5125||5125:5123||5123;let Z=n.createBuffer();O.push(Z),n.bindBuffer(34963,Z),V.componentType===5125?(N=new Uint32Array(c,Q,V.count),n.bufferData(34963,N,35044)):V.componentType===5121?(N=Uint16Array.from(new Uint8Array(c,Q,V.count)),n.bufferData(34963,N,35044)):(N=Q%2===0?new Uint16Array(c,Q,V.count):new Uint16Array(c.slice(Q,Q+V.count*2)),n.bufferData(34963,N,35044))}else x=Y.count;let z={};for(let V of ae)if(V.onBuildPrimitiveVAO){let J=V.onBuildPrimitiveVAO(n,B,U,s,c);J&&(z[V.name]=J)}n.bindVertexArray(null);let ee=s.materials&&U.material!==void 0?s.materials[U.material]:null,{program:ie,uniforms:oe}=Je(n,U,ee),H=tt(ee,m),$=!!(ee?.extensions?.KHR_materials_transmission||z.materials?.isTransmissive),G=U.extensions?.KHR_materials_variants?.mappings,te=Array.isArray(G)?G.filter(V=>V&&typeof V.material=="number"&&Array.isArray(V.variants)).map(V=>({material:V.material|0,variants:V.variants.map(J=>Number(J)|0)})):void 0;_.primitives.push({vao:B,instanced:q,indexCount:x,indexType:I,...H,positions:j,indices:N,buffers:O,materialIndex:U.material,defaultMaterialIndex:U.material,variantMappings:te,primitiveDef:U,programCache:new Map([[U.material??-1,{program:ie,uniforms:oe}]]),pluginData:z,customProgram:ie,customUniforms:oe,isTransmissive:$})}o.push(_)}isFinite(p[0])||(p=[-1,-1,-1]),isFinite(R[0])||(R=[1,1,1]);let D=[(p[0]+R[0])/2,(p[1]+R[1])/2,(p[2]+R[2])/2],y=R[0]-p[0],P=R[1]-p[1],E=R[2]-p[2],b=Math.max(Math.hypot(y,P,E)/2,.5),F=[p[0],p[1],p[2]],L=[R[0],R[1],R[2]],C=e.animations;if(!C){for(let h of ae)if(h.onParseGLB?.(e),e.animations){C=e.animations;break}}return C||(C=[]),{meshes:o,bounds:{center:D,radius:b,min:F,max:L},lights:g,animations:C,worldMatrices:d,gpuTextures:m,availableVariants:l}}function ge(n){let e=n.customTarget||n.bounds.center,t=n.currDistance*Math.cos(n.currPhi);return[e[0]+t*Math.sin(n.currTheta),e[1]+n.currDistance*Math.sin(n.currPhi),e[2]+t*Math.cos(n.currTheta)]}var Ee=class{constructor(e,t,r){this.supportsInstanceOffsets=!0;this.meshes=[];this.backdropMeshes=[];this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]};this.lights=[];this.modelRootMatrix=re();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=re();this.viewMatrix=re();this.activeViewMatrix=null;this.modelMatrix=re();this.mvpMatrix=re();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:re(),rawValueToMeters:.001,format:0};this.container=e;let i,s;if(t&&typeof t.getContext=="function"?(i=t,s=r):(s=t,i=s?.canvas),!i){let o=e.querySelector("canvas");o||(o=document.createElement("canvas"),o.style.width="100%",o.style.height="100%",o.style.display="block",o.style.touchAction="none",e.prepend(o)),i=o}this.canvas=i,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=Ie(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=_e(this.opts.toneMapping)),this.opts.autoplay!==void 0&&(this.autoplay=this.opts.autoplay),this.opts.animationName!==void 0&&(this.animationName=this.opts.animationName),this.opts.variantName!==void 0&&(this.activeVariantName=this.opts.variantName||null),this.opts.fieldOfView!==void 0&&(this.fov=this.opts.fieldOfView*Math.PI/180),this.opts.distanceMode!==void 0&&(this.distanceMode=this.opts.distanceMode),this.opts.cameraTarget!==void 0&&(this.setTarget(this.opts.cameraTarget[0],this.opts.cameraTarget[1],this.opts.cameraTarget[2]),this.initialCustomTarget=[...this.opts.cameraTarget]),(this.opts.minCameraOrbit||this.opts.maxCameraOrbit)&&this.setOrbitLimits({minTheta:this.opts.minCameraOrbit?.theta,maxTheta:this.opts.maxCameraOrbit?.theta,minPhi:this.opts.minCameraOrbit?.phi,maxPhi:this.opts.maxCameraOrbit?.phi,minDistance:this.opts.minCameraOrbit?.distance,maxDistance:this.opts.maxCameraOrbit?.distance});let c=i.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!c)throw new Error("WebGL2 not supported");this.gl=c,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(e,t){vt(e,t)}static getDecoder(e){return pe(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=Qe();this.renderProg=we(e,je,t.fs),this.pickProg=we(e,At,wt),this.uRender=Ne(e,this.renderProg,t.uniforms),this.uPick=Ne(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of ae)t.onContextRestored?.(e,this);this.meshes=[],this.gpuTextures=[],this.environmentTexture=null,this.lastGlbData&&this.loadGLBData(this.lastGlbData,this.lastLimits),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}setupPickingFbo(){let e=this.gl;if(typeof e.createFramebuffer!="function")return;this.pickFbo=e.createFramebuffer(),this.pickTexture=e.createTexture(),this.pickDepth=e.createRenderbuffer();let t=Math.max(1,this.canvas.width),r=Math.max(1,this.canvas.height);this.pickFboWidth=t,this.pickFboHeight=r,e.bindTexture(3553,this.pickTexture),e.texImage2D(3553,0,6408,t,r,0,6408,5121,null),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728),e.bindRenderbuffer(36161,this.pickDepth),e.renderbufferStorage(36161,33189,t,r),e.bindFramebuffer(36160,this.pickFbo),e.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),e.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),e.bindFramebuffer(36160,null)}resizePickingFbo(e,t){if(!this.pickFbo)return;let r=this.gl,i=Math.max(1,e),s=Math.max(1,t);this.pickFboWidth=i,this.pickFboHeight=s,r.bindTexture(3553,this.pickTexture),r.texImage2D(3553,0,6408,i,s,0,6408,5121,null),r.bindRenderbuffer(36161,this.pickDepth),r.renderbufferStorage(36161,33189,i,s)}loadGLBData(e,t){this.lastGlbData=e,this.lastLimits=t;let{meshes:r,bounds:i,lights:s,animations:a,worldMatrices:c,gpuTextures:o,availableVariants:l}=qe(this.gl,e,t,()=>this.render());if(this.disposeMeshGpuResources(),this.meshes=r,this.bounds=i,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=s,this.animations=a||[],this.worldMatrices=c||[],this.gpuTextures=o||[],this.availableVariants=l||[],this.gltf=e.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let f of e.gltf.nodes)this.initialNodeTransforms.push({t:f.translation?[f.translation[0],f.translation[1],f.translation[2]]:[0,0,0],r:f.rotation?[f.rotation[0],f.rotation[1],f.rotation[2],f.rotation[3]]:[0,0,0,1],s:f.scale?[f.scale[0],f.scale[1],f.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let f of ae)f.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=e.exposure??e.gltf?.extras?.exposure??e.gltf?.asset?.extras?.exposure;u!==void 0&&(this.exposure=Ie(u));let d=e.environmentIntensity??e.gltf?.extras?.environmentIntensity??e.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(e){this.loadGLBData(Ze(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(xe(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=xe(e),{meshes:i}=qe(this.gl,r,et,()=>this.render());if(t)for(let s of i)s.transform[12]+=t[0],s.transform[13]+=t[1],s.transform[14]+=t[2],me(s.normalMatrix,s.transform);this.backdropMeshes=i,this.update(0),this.render()}setClearColor(e,t,r,i=1){this.clearColor=[e,t,r,i]}updateMeshTransforms(e){for(let t=0;t<this.meshes.length;t++){let r=this.meshes[t],i;e instanceof Map?i=e.get(r.name)??e.get(t):Array.isArray(e)?i=e[t]:e&&typeof e=="object"&&(Object.prototype.hasOwnProperty.call(e,r.name)?i=e[r.name]:Object.prototype.hasOwnProperty.call(e,t)&&(i=e[t])),i&&i.length===16&&(r.transform.set(i),me(r.normalMatrix,r.transform))}}bindLights(e=this.uRender){let t=this.gl,r=[.28,.28,.28],i=[],s=[],a=[],c=[];for(let o of this.lights){let l=o.color||[1,1,1],u=o.intensity!==void 0?o.intensity:1;if(o.type==="ambient")r=[l[0]*u,l[1]*u,l[2]*u];else if(o.type==="directional"&&i.length<6){let d=o.direction||[.5,1,.8];i.push(d[0],d[1],d[2]),s.push(l[0]*u,l[1]*u,l[2]*u)}else if(o.type==="point"&&a.length<6){let d=o.position||[0,0,0];a.push(d[0],d[1],d[2]),c.push(l[0]*u,l[1]*u,l[2]*u)}}i.length===0&&(i.push(.5,1,.8),s.push(1,1,1)),t.uniform3fv(e.uAmbientColor,r),t.uniform1i(e.uNumDirLights,i.length/3),i.length>0&&(t.uniform3fv(e.uDirLightDir,i),t.uniform3fv(e.uDirLightColor,s)),t.uniform1i(e.uNumPointLights,a.length/3),a.length>0&&(t.uniform3fv(e.uPointLightPos,a),t.uniform3fv(e.uPointLightColor,c)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=Ie(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=_e(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of ae)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of ae)if(t.setSkyboxImage){await t.setSkyboxImage(this,e);return}}setInteractive(e){this.interactive=e}isInteractive(){return this.interactive}getCameraOrbit(){let e=this.currTheta,t=this.currPhi,r=this.currDistance;return{theta:e,phi:t,radius:r,toString(){return`${e.toFixed(4)}rad ${t.toFixed(4)}rad ${r.toFixed(4)}m`}}}getCameraTarget(){let e=this.customTarget||this.bounds.center;return{x:e[0],y:e[1],z:e[2],toString(){return`${e[0].toFixed(4)}m ${e[1].toFixed(4)}m ${e[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let e=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return e.map((t,r)=>{let i=this.meshes.flatMap(u=>u.primitives.filter(d=>d.materialIndex===r||e.length===1&&d.materialIndex===void 0)),s=i[0],a=s?[...s.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],c=s?s.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,o=s?s.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,l={baseColorFactor:a,metallicFactor:c,roughnessFactor:o,setBaseColorFactor:u=>{let d=[u[0],u[1],u[2],u[3]??1];l.baseColorFactor=d,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=d);for(let f of i)f.baseColor=d;this.render()},setMetallicFactor:u=>{l.metallicFactor=u,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=u);for(let d of i)d.metallic=u;this.render()},setRoughnessFactor:u=>{l.roughnessFactor=u,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=u);for(let d of i)d.roughness=u;this.render()}};return{name:t.name||`Material_${r}`,pbrMetallicRoughness:l}})}playAnimation(e){if(this.animations.length!==0){if(e){let t=this.animations.find(r=>r.name===e);t&&(this.currentClip=t)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(e=>e.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(e){let t=this.applyVariantMaterial(e);return t&&this.gl&&this.render(),t}applyVariantMaterial(e){let t=e===null||e==="",r=-1;if(t)this.activeVariantName=null;else{if(r=this.availableVariants.indexOf(e),r<0)return!1;this.activeVariantName=e}let i=this.gltf?.materials;if(!Array.isArray(i))return t;for(let s of this.meshes)for(let a of s.primitives){let c=a.defaultMaterialIndex;if(!t&&Array.isArray(a.variantMappings)){for(let l of a.variantMappings)if(Array.isArray(l.variants)&&l.variants.includes(r)){c=l.material;break}}let o=c!==void 0?i[c]:void 0;a.materialIndex=o?c:void 0,Object.assign(a,tt(o,this.gpuTextures)),this.applyPrimitiveProgram(a,a.materialIndex,o??null)}return!0}applyPrimitiveProgram(e,t,r){if(!this.gl||!e.primitiveDef)return;e.programCache??(e.programCache=new Map);let i=t??-1,s=e.programCache.get(i);s||(s=Je(this.gl,{...e.primitiveDef,material:t},r),e.programCache.set(i,s)),e.customProgram=s.program,e.customUniforms=s.uniforms,e.pluginData&&(e.pluginData.materials=e.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(e){this.autoplay=e,e?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(e){this.animationName=e,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(e)}evaluateAnimation(e){for(let t of ae)if(t.evaluateAnimation){t.evaluateAnimation(this,e);return}}setTarget(e,t,r){this.customTarget=[e,t,r],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(e){let t=Math.max(10,Math.min(90,e));this.fov=t*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(e){if(this.distanceMode=e,!this.customDistance){let t=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=t,this.targetDistance=t,this.currDistance=t,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(e){e.minTheta!==void 0&&(this.minTheta=e.minTheta*Math.PI/180),e.maxTheta!==void 0&&(this.maxTheta=e.maxTheta*Math.PI/180),e.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,e.minPhi*Math.PI/180)),e.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,e.maxPhi*Math.PI/180)),e.minDistance!==void 0&&(this.minDistanceLimit=e.minDistance),e.maxDistance!==void 0&&(this.maxDistanceLimit=e.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){return{minTheta:isFinite(this.minTheta)?this.minTheta*180/Math.PI:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*180/Math.PI:void 0,minPhi:this.minPhi*180/Math.PI,maxPhi:this.maxPhi*180/Math.PI,minDistance:this.minDistanceLimit!==null?this.minDistanceLimit:void 0,maxDistance:this.maxDistanceLimit!==null?this.maxDistanceLimit:void 0}}clampTheta(e){return Math.max(this.minTheta,Math.min(this.maxTheta,e))}clampPhi(e){return Math.max(this.minPhi,Math.min(this.maxPhi,e))}clampDistance(e){let t=this.minDistanceLimit!==null?this.minDistanceLimit:this.bounds?this.bounds.radius*.5:.1,r=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(t,Math.min(r,e))}setCamera(e,t,r,i){e!==void 0&&(this.targetTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.targetPhi=this.clampPhi(t*Math.PI/180)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(r)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/i))}setInitialCamera(e,t,r,i){if(e!==void 0&&(this.initialTheta=this.clampTheta(e*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),t!==void 0&&(this.initialPhi=this.clampPhi(t*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),r!==void 0&&r>0){let s=this.clampDistance(r);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else if(i!==void 0&&i>0){let s=this.clampDistance(this.bounds.radius*2.5/i);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else{this.customDistance=!1;let s=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=s,this.targetDistance=s,this.currDistance=s}this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.initialDistance!==null?this.targetDistance=this.clampDistance(this.initialDistance):this.targetDistance=this.clampDistance(this.bounds.radius*2.5),this.initialCustomTarget?this.customTarget=[...this.initialCustomTarget]:this.customTarget=null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(e,t){let r=re();se(r,this.projMatrix,this.viewMatrix);let[i,s,a]=e,c=t?t[0]:0,o=t?t[1]:0,l=t?t[2]:0,u=this.modelRootMatrix;u&&(i=u[0]*e[0]+u[4]*e[1]+u[8]*e[2]+u[12],s=u[1]*e[0]+u[5]*e[1]+u[9]*e[2]+u[13],a=u[2]*e[0]+u[6]*e[1]+u[10]*e[2]+u[14],t&&(c=u[0]*t[0]+u[4]*t[1]+u[8]*t[2],o=u[1]*t[0]+u[5]*t[1]+u[9]*t[2],l=u[2]*t[0]+u[6]*t[1]+u[10]*t[2]));let d=r[0]*i+r[4]*s+r[8]*a+r[12],f=r[1]*i+r[5]*s+r[9]*a+r[13],T=r[2]*i+r[6]*s+r[10]*a+r[14],g=r[3]*i+r[7]*s+r[11]*a+r[15];if(g<=1e-4)return{x:0,y:0,z:1,visible:!1};let m=d/g,p=f/g,R=T/g,A=this.canvas.getBoundingClientRect(),v=A.width||this.canvas.clientWidth||this.canvas.width||300,D=A.height||this.canvas.clientHeight||this.canvas.height||150,y=(m*.5+.5)*v,P=(-p*.5+.5)*D,E=m>=-1.1&&m<=1.1&&p>=-1.1&&p<=1.1&&R>=-1&&R<=1;if(E&&t){let[b,F,L]=ge(this),C=[i-b,s-F,a-L];c*C[0]+o*C[1]+l*C[2]>.05&&(E=!1)}return{x:y,y:P,z:R,visible:E}}setSelectedMesh(e){this.selectedMeshName=e||""}getSelectedMesh(){return this.selectedMeshName}setupEvents(){let e=this.canvas;this.boundContextMenu=t=>{t.preventDefault()},e.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=t=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.lastPointerX=t.clientX,this.lastPointerY=t.clientY,this.totalDragDist=0,this.activePointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.isPanning=t.button===2||t.shiftKey||this.activePointers.size===2,e.setPointerCapture(t.pointerId))},e.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=t=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=this.activePointers.get(t.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},i=t.clientX-r.x,s=t.clientY-r.y;if(this.activePointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.lastPointerX=t.clientX,this.lastPointerY=t.clientY,this.totalDragDist+=Math.hypot(i,s),this.isPanning||t.button===2||t.shiftKey||this.activePointers.size===2){let a=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],c=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],o=this.customTarget?[...this.customTarget]:[...this.bounds.center],l=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;o[0]+=(-i*a[0]+s*c[0])*l,o[1]+=(-i*a[1]+s*c[1])*l,o[2]+=(-i*a[2]+s*c[2])*l,this.customTarget=o}else this.targetTheta=this.clampTheta(this.targetTheta-i*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=t=>{this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.activePointers.delete(t.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(t.pointerId)}catch{}if(this.totalDragDist<5&&t.button===0){let r=e.getBoundingClientRect(),i=Math.floor((t.clientX-r.left)*(e.width/Math.max(r.width,1))),s=Math.floor((t.clientY-r.top)*(e.height/Math.max(r.height,1)));this.performMeshPick(i,s,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=t=>{if(!this.interactive)return;t.preventDefault(),this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=Math.exp(t.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=t=>{let r=t.detail||{};r.reset?this.resetCamera():this.setCamera(r.theta,r.phi,r.distance,r.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),e.tabIndex!==void 0&&e.tabIndex<0&&(e.tabIndex=0),e.getAttribute?.("role")||e.setAttribute?.("role","region"),e.getAttribute?.("aria-label")||e.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=t=>{if(!this.interactive)return;let r=typeof performance<"u"?performance.now():Date.now();switch(t.key){case"ArrowLeft":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta-.1),t.preventDefault();break;case"ArrowRight":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta+.1),t.preventDefault();break;case"ArrowUp":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi+.08),t.preventDefault();break;case"ArrowDown":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi-.08),t.preventDefault();break;case"+":case"=":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*.9),t.preventDefault();break}case"-":case"_":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*1.1),t.preventDefault();break}case"Home":this.lastInteractionTime=r,this.resetCamera(),t.preventDefault();break}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=this.canvas;this.boundContextLost&&(e.removeEventListener("webglcontextlost",this.boundContextLost),this.boundContextLost=null),this.boundContextRestored&&(e.removeEventListener("webglcontextrestored",this.boundContextRestored),this.boundContextRestored=null),this.boundContextMenu&&(e.removeEventListener("contextmenu",this.boundContextMenu),this.boundContextMenu=null),this.boundPointerDown&&(e.removeEventListener("pointerdown",this.boundPointerDown),this.boundPointerDown=null),this.boundPointerMove&&(e.removeEventListener("pointermove",this.boundPointerMove),this.boundPointerMove=null),this.boundPointerUp&&(e.removeEventListener("pointerup",this.boundPointerUp),this.boundPointerUp=null),this.boundWheel&&(e.removeEventListener("wheel",this.boundWheel),this.boundWheel=null),this.boundKeyDown&&(e.removeEventListener("keydown",this.boundKeyDown),this.boundKeyDown=null),this.boundSetCamera&&(this.container.removeEventListener("setCamera",this.boundSetCamera),this.boundSetCamera=null),this.boundResetCamera&&(this.container.removeEventListener("resetCamera",this.boundResetCamera),this.boundResetCamera=null)}raycastFromScreenPoint(e,t){let r=this.canvas,i=r.getBoundingClientRect(),s=r.width||300,a=r.height||300,c=i.width>0?Math.floor((e-i.left)*(s/i.width)):Math.floor(e),o=i.height>0?Math.floor((t-i.top)*(a/i.height)):Math.floor(t);return this.performMeshPick(c,o,!1)}performMeshPick(e,t,r=!0){if(this.meshes.length===0)return null;let i=this.gl,s=Math.max(1,this.canvas.width||300),a=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,s);let c=re();se(c,this.projMatrix,this.viewMatrix);let o=[],l=Math.max(0,Math.min(s-1,e)),u=Math.max(0,Math.min(a-1,a-1-t));if(this.pickFbo&&i&&!this.xrSessionActive){(this.pickFboWidth!==s||this.pickFboHeight!==a)&&this.resizePickingFbo(s,a),i.bindFramebuffer(36160,this.pickFbo),i.viewport(0,0,s,a),i.enable(2929),i.clearColor(0,0,0,0),i.clear(16384|256),i.useProgram(this.pickProg);for(let E=0;E<this.meshes.length;E++){let b=this.meshes[E];if(b.visible===!1||b.isPluginMesh)continue;let F=E+1,L=(F&255)/255,C=(F>>8&255)/255,h=(F>>16&255)/255;i.uniform4f(this.uPick.uColorId,L,C,h,1),se(this.modelMatrix,this.modelRootMatrix,b.transform);let w=b.instanceMatrices;if(w&&w.length>=16){let S=w.length>>4,M=re();for(let k of b.primitives){i.bindVertexArray(k.vao);for(let _=0;_<S;_++)se(M,this.modelMatrix,w.subarray(_*16,_*16+16)),se(this.mvpMatrix,c,M),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),Re(i,k)}}else{se(this.mvpMatrix,c,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let S of b.primitives)i.bindVertexArray(S.vao),Re(i,S)}}let y=new Uint8Array(4);i.readPixels(l,u,1,1,6408,5121,y),i.bindFramebuffer(36160,null);let P=y[0]+(y[1]<<8)+(y[2]<<16);P>0&&P<=this.meshes.length&&(o=[this.meshes[P-1]])}o.length===0&&(o=this.meshes.filter(y=>y.visible!==!1));let d=null,f=1/0,T=[0,0,0],g=[0,1,0],[m,p,R]=ge(this),A=re();for(let y of o){se(A,this.modelRootMatrix,y.transform);let P=y.instanceMatrices,E=P&&P.length>=16?P.length>>4:1;for(let b=0;b<E;b++){P&&P.length>=16?se(this.modelMatrix,A,P.subarray(b*16,b*16+16)):this.modelMatrix.set(A),se(this.mvpMatrix,c,this.modelMatrix);let F=re();if(!Ge(F,this.mvpMatrix))continue;let L=(l+.5)/s*2-1,C=(u+.5)/a*2-1,h=[0,0,0],w=[0,0,0];De(h,L,C,-1,F),De(w,L,C,1,F);let S=w[0]-h[0],M=w[1]-h[1],k=w[2]-h[2],_=Math.hypot(S,M,k)||1,K=S/_,U=M/_,O=k/_,B={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((Y=>{for(let W of y.primitives){if(!W.positions)continue;let j=W.positions,x=W.indices,I=Math.floor(x?x.length/3:j.length/9);for(let N=0;N<I;N++){let z=x?x[N*3]:N*3,ee=x?x[N*3+1]:N*3+1,ie=x?x[N*3+2]:N*3+2;ze(h[0],h[1],h[2],K,U,O,j[z*3],j[z*3+1],j[z*3+2],j[ee*3],j[ee*3+1],j[ee*3+2],j[ie*3],j[ie*3+1],j[ie*3+2],B,Y)}}})(1e-4),isFinite(B.distance)){let Y=B.point[0],W=B.point[1],j=B.point[2],x=this.modelMatrix,I=x[0]*Y+x[4]*W+x[8]*j+x[12],N=x[1]*Y+x[5]*W+x[9]*j+x[13],z=x[2]*Y+x[6]*W+x[10]*j+x[14],ee=I-m,ie=N-p,oe=z-R,H=Math.hypot(ee,ie,oe);if(H<f){me(this.normalMatrix,this.modelMatrix);let $=this.normalMatrix,G=B.normal[0],te=B.normal[1],V=B.normal[2],J=$[0]*G+$[3]*te+$[6]*V,Q=$[1]*G+$[4]*te+$[7]*V,Z=$[2]*G+$[5]*te+$[8]*V,ne=Math.hypot(J,Q,Z)||1;J/=ne,Q/=ne,Z/=ne,J*ee+Q*ie+Z*oe>0&&(J=-J,Q=-Q,Z=-Z),d=y,f=Math.round(H*1e3)/1e3,T=[Math.round(I*1e3)/1e3,Math.round(N*1e3)/1e3,Math.round(z*1e3)/1e3],g=[Math.round(J*1e3)/1e3,Math.round(Q*1e3)/1e3,Math.round(Z*1e3)/1e3]}}}}if(!d)return null;let D={meshIndex:this.meshes.indexOf(d),meshName:d.name,nodeIndex:d.nodeIndex,distance:f,hitPoint:T,normal:g,screenX:e,screenY:t};if(r){for(let y of ae)y.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 r=Math.max(1,Math.floor(t*.5)),i=e>=r,s=i?e-r:e,a=i?Math.max(1,t-r):r,c=(s+.5)/a*2-1;return Math.floor((c*.5+1)*.5*t)}setStereoSBS(e){this.stereoSBS=!!e,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let e=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),t=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);ve(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center;Me(this.viewMatrix,ge(this),r,[0,1,0]),se(this.mvpMatrix,this.projMatrix,this.viewMatrix),me(this.normalMatrix,this.modelMatrix)}resize(){let e=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),t=this.canvas.getBoundingClientRect(),r=Math.max(1,Math.floor(t.width*e)),i=Math.max(1,Math.floor(t.height*e));this.canvas.width!==r||this.canvas.height!==i?(this.canvas.width=r,this.canvas.height=i,this.resizePickingFbo(r,i),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(e){let t=this.xrSessionActive;if(this.xrSessionActive=e,t&&!e){this.xrDepthState.enabled=!1;for(let r of ae)r.onXRSessionEnd?.(this);if(this.lastTime=typeof performance<"u"?performance.now():Date.now(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(r){this.reportRenderError(r)}}}reportRenderError(e){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",e))}stepXRUpdate(e){for(let t of ae)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let e=t=>{if(this.animFrameId===null)return;let r=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(r),this.render()}catch(i){this.reportRenderError(i)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(e))};this.animFrameId=requestAnimationFrame(e)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(e){this.autoRotate=e}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(e){this.autoRotateSpeed=e}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(e){this.autoRotateDelay=Math.max(0,Number(e)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(e=0){this.turntableRotation=Number(e)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let e=Math.cos(this.turntableRotation),t=Math.sin(this.turntableRotation),r=this.bounds.center[0],i=this.bounds.center[2],s=this.modelRootMatrix;s[0]=e,s[1]=0,s[2]=-t,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=t,s[9]=0,s[10]=e,s[11]=0,s[12]=r-(e*r+t*i),s[13]=0,s[14]=i-(-t*r+e*i),s[15]=1}setVisible(e){this.isVisible=e}update(e){for(let a of ae)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 ae)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 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 a={theta:r,phi:i,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,r,i,s=!0,a=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let c=e?.transform?.inverse?.matrix||this.viewMatrix,o=e?.projectionMatrix||this.projMatrix,l=e?.transform?.position,u=l?[l.x,l.y,l.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):r&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:c,projMatrix:o,eyePos:u,viewport:i,eye:e?.eye||"none",clear:a>0?!1:e?.eye!=="right",isAR:s})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let v=Math.max(2,this.canvas.width||2),D=Math.max(1,this.canvas.height||1),y=Math.max(1,Math.floor(v*.5)),P=Math.max(1,v-y),E=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),b=this.customTarget||this.bounds.center,[F,L,C]=ge(this),h=Math.cos(this.currTheta),w=-Math.sin(this.currTheta),S=.032,M=re(),k=re(),_=[F-h*S,L,C-w*S],K=[b[0]-h*S*.25,b[1],b[2]-w*S*.25];ve(M,this.fov,y/D,.1,E),Me(k,_,K,[0,1,0]);let U=re(),O=re(),B=[F+h*S,L,C+w*S],q=[b[0]+h*S*.25,b[1],b[2]+w*S*.25];ve(U,this.fov,P/D,.1,E),Me(O,B,q,[0,1,0]),this.render({viewMatrix:k,projMatrix:M,eyePos:_,viewport:[0,0,y,D],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:O,projMatrix:U,eyePos:B,viewport:[y,0,P,D],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,v,D);return}let t=this.gl,r=0,i=0,s=this.canvas.width,a=this.canvas.height;e?.viewport?(r=e.viewport[0],i=e.viewport[1],s=e.viewport[2],a=e.viewport[3],t.viewport(r,i,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(16384|256));let c=re(),o=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=o,se(c,e?.projMatrix??this.projMatrix,o);let l=he().xrDepthShader,u=gt(this.toneMapping),[d,f,T]=e?e.eyePos:ge(this);for(let v of ae)v.onBeforeDrawScene?.(this,t,c,[d,f,T],u);let g=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&g===0)return;let m=e?.eye||"none",p=!1,R=g>0?[...this.backdropMeshes,...this.meshes]:this.meshes,A=v=>{for(let D=0;D<R.length;D++){let y=R[D];if(y.visible===!1)continue;let P=this.selectedMeshName!==""&&y.name===this.selectedMeshName;D<g||y.worldSpace===!0||y.name==="__xr_reticle__"?this.modelMatrix.set(y.transform):se(this.modelMatrix,this.modelRootMatrix,y.transform),se(this.mvpMatrix,c,this.modelMatrix),me(y.normalMatrix,this.modelMatrix);let E=y.extras?.xr?.stereo||y.userData?.xr?.stereo,b=0,F=0,L=1,C=1;E==="sbs"?(L=.5,b=m==="right"?.5:0):E==="ou"&&(C=.5,F=m==="right"?.5:0);for(let h of y.primitives){let w=!!h.isTransmissive;if(!v&&w){p=!0;continue}if(v&&!w)continue;let S=h.customProgram||this.renderProg,M=h.customUniforms||this.uRender;t.useProgram(S),t.vertexAttrib3f(3,0,0,0),M.uInstanced&&t.uniform1i(M.uInstanced,0),t.uniform1i(M.uToneMapping,u),t.uniform1f(M.uEnvIntensity,this.envIntensity),M.uExposure&&t.uniform1f(M.uExposure,this.exposure),t.uniform3f(M.uCameraPos,d,f,T),t.uniform1f(M.uEmissive,P?1:0),t.uniformMatrix4fv(M.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(M.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(M.uNormalMatrix,!1,y.normalMatrix),M.uUvTransform&&t.uniform4f(M.uUvTransform,b,F,L,C),M.uViewportSize&&t.uniform2f(M.uViewportSize,Math.max(1,s),Math.max(1,a)),l?.bind(t,M,this.xrDepthState,o,[r,i,Math.max(1,s),Math.max(1,a)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(M.uEnvironmentMap,4),t.uniform1i(M.uHasEnvironmentMap,1)):t.uniform1i(M.uHasEnvironmentMap,0),this.bindLights(M),M.uSectionEnabled&&t.uniform1i(M.uSectionEnabled,0);for(let _ of ae)_.onBeforeDrawPrimitive?.(t,S,h,y,this.worldMatrices||[],this.gltf);t.uniform4fv(M.uBaseColor,h.baseColor),t.uniform1f(M.uMetallic,h.metallic),t.uniform1f(M.uRoughness,h.roughness),M.uClearcoat&&t.uniform2f(M.uClearcoat,h.clearcoat??0,h.clearcoatRoughness??.04),h.texture?(t.activeTexture(33984),t.bindTexture(3553,h.texture),t.uniform1i(M.uBaseColorTexture,0),t.uniform1i(M.uHasTexture,1)):t.uniform1i(M.uHasTexture,0),h.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,h.metallicRoughnessTexture),t.uniform1i(M.uMetallicRoughnessTexture,1),t.uniform1i(M.uHasMetallicRoughnessTexture,1)):t.uniform1i(M.uHasMetallicRoughnessTexture,0),h.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,h.normalTexture),t.uniform1i(M.uNormalTexture,2),t.uniform1i(M.uHasNormalTexture,1),t.uniform1f(M.uNormalScale,h.normalScale)):t.uniform1i(M.uHasNormalTexture,0),h.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,h.occlusionTexture),t.uniform1i(M.uOcclusionTexture,3),t.uniform1i(M.uHasOcclusionTexture,1),t.uniform1f(M.uOcclusionStrength,h.occlusionStrength)):t.uniform1i(M.uHasOcclusionTexture,0),t.bindVertexArray(h.vao);let k=y.instanceMatrices;if(h.instanceCount!==void 0)t.drawElementsInstanced(4,h.indexCount,h.indexType,0,h.instanceCount);else if(k&&k.length>=16&&h.instanced&&M.uInstanced&&M.uViewProj){let _=k.length>>4;t.uniform1i(M.uInstanced,1),t.uniformMatrix4fv(M.uViewProj,!1,c),h.indices?t.drawElementsInstanced(4,h.indexCount,h.indexType,0,_):t.drawArraysInstanced(4,0,h.indexCount,_),t.uniform1i(M.uInstanced,0)}else if(k&&k.length>=16){let _=k.length>>4,K=y.instanceColors,U=re(),O=new Float32Array(9),B=[h.baseColor[0],h.baseColor[1],h.baseColor[2],h.baseColor[3]];for(let q=0;q<_;q++)se(U,this.modelMatrix,k.subarray(q*16,q*16+16)),se(this.mvpMatrix,c,U),me(O,U),t.uniformMatrix4fv(M.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(M.uModel,!1,U),t.uniformMatrix3fv(M.uNormalMatrix,!1,O),K&&(B[0]=h.baseColor[0]*K[q*3],B[1]=h.baseColor[1]*K[q*3+1],B[2]=h.baseColor[2]*K[q*3+2],B[3]=h.baseColor[3],t.uniform4fv(M.uBaseColor,B)),Re(t,h)}else Re(t,h)}}};if(A(!1),p){for(let v of ae)v.onBeforeTransmissivePass?.(t,this);A(!0)}for(let v of ae)v.onAfterRender?.(t,this,c,e?.eye??"none",[r,i,s,a],e?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(e,t){nt(this.gl,e,t)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let e=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let t of ae)t.onDestroy?.(e,this);this.environmentTexture&&(e.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&e.deleteProgram(this.renderProg),this.pickProg&&e.deleteProgram(this.pickProg),this.pickFbo&&e.deleteFramebuffer(this.pickFbo),this.pickTexture&&e.deleteTexture(this.pickTexture),this.pickDepth&&e.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};Ee.registerPlugin=He,Ee.getRegisteredPlugins=We;function Be(n){return new TextEncoder().encode(n)}function Pt(n,e){n.updateMatrixWorld(!0);let t=[];return n.traverse(r=>{if(r.geometry){let i=r.geometry,s=i.attributes.position;if(!s||s.count===0)return;let a=s.count,c=new Float32Array(a*3),o=r.matrixWorld.elements;for(let b=0;b<a;b++){let F=s.getX(b),L=s.getY(b),C=s.getZ(b);c[b*3]=o[0]*F+o[4]*L+o[8]*C+o[12],c[b*3+1]=o[1]*F+o[5]*L+o[9]*C+o[13],c[b*3+2]=o[2]*F+o[6]*L+o[10]*C+o[14]}let l;if(i.attributes.normal){let b=i.attributes.normal;l=new Float32Array(a*3);let F=new Float32Array(9);me(F,o);for(let L=0;L<a;L++){let C=b.getX(L),h=b.getY(L),w=b.getZ(L),S=F[0]*C+F[3]*h+F[6]*w,M=F[1]*C+F[4]*h+F[7]*w,k=F[2]*C+F[5]*h+F[8]*w,_=Math.hypot(S,M,k)||1;l[L*3]=S/_,l[L*3+1]=M/_,l[L*3+2]=k/_}}let u;if(i.attributes.uv){let b=i.attributes.uv;u=new Float32Array(a*2);for(let F=0;F<a;F++)u[F*2]=b.getX(F),u[F*2+1]=b.getY(F)}let d;if(i.index)d=i.index.array;else{d=a>65535?new Uint32Array(a):new Uint16Array(a);for(let b=0;b<a;b++)d[b]=b}let f="DefaultMaterial",T=[.8,.8,.8],g=.5,m=.1,p=0,R=0,A=1.5,v=1,D=[0,0,0];if(r.material){let b=r.material;f=b.name||`Material_${t.length}`,b.color&&(T=[b.color.r,b.color.g,b.color.b]),typeof b.roughness=="number"&&(g=b.roughness),typeof b.metalness=="number"&&(m=b.metalness),typeof b.clearcoat=="number"&&(p=b.clearcoat),typeof b.clearcoatRoughness=="number"&&(R=b.clearcoatRoughness),typeof b.ior=="number"&&(A=b.ior);let F=typeof b.opacity=="number"?b.opacity:1,L=typeof b.transmission=="number"?b.transmission:0;if(v=F*(1-L),b.emissive&&(b.emissive.r>0||b.emissive.g>0||b.emissive.b>0)){let C=b.emissiveIntensity??1;D=[b.emissive.r*C,b.emissive.g*C,b.emissive.b*C]}}let y,P=e?.animateCallback||e?.animateFn||(typeof n.userData?.animate=="function"?n.userData.animate:typeof n.__animateFn=="function"?n.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0);if(typeof P=="function"){let b=e?.duration??4,F=e?.fps??4,L=Math.max(2,Math.round(b*F)+1),C=[],h=[],w=[],S=[],M=[r.position.x,r.position.y,r.position.z],k=[r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w],_=[r.scale.x,r.scale.y,r.scale.z],K=!1;for(let U=0;U<L;U++){let O=U/(L-1)*b;C.push(O);try{P(O)}catch{}h.push([r.position.x,r.position.y,r.position.z]),w.push([r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w]),S.push([r.scale.x,r.scale.y,r.scale.z]),(Math.abs(r.position.x-M[0])>1e-4||Math.abs(r.position.y-M[1])>1e-4||Math.abs(r.position.z-M[2])>1e-4||Math.abs(r.quaternion.x-k[0])>1e-4||Math.abs(r.quaternion.y-k[1])>1e-4||Math.abs(r.quaternion.z-k[2])>1e-4||Math.abs(r.quaternion.w-k[3])>1e-4||Math.abs(r.scale.x-_[0])>1e-4)&&(K=!0)}r.position.set(M[0],M[1],M[2]),r.quaternion.set(k[0],k[1],k[2],k[3]),r.scale.set(_[0],_[1],_[2]),K&&(y={times:C,translations:h,rotations:w,scales:S})}let E=r;if(E.isInstancedMesh&&typeof E.count=="number"&&E.count>0&&E.instanceMatrix?.array){let b=Math.min(1e3,Math.floor(E.count)),F=E.instanceMatrix.array,L=E.instanceColor?.array,C=r.name||`Mesh_${t.length}`,h=new Float32Array(16),w=new Float32Array(9);for(let S=0;S<b;S++){let M=F.subarray(S*16,(S+1)*16);se(h,o,M);let k=new Float32Array(a*3);for(let O=0;O<a;O++){let B=s.getX(O),q=s.getY(O),Y=s.getZ(O);k[O*3]=h[0]*B+h[4]*q+h[8]*Y+h[12],k[O*3+1]=h[1]*B+h[5]*q+h[9]*Y+h[13],k[O*3+2]=h[2]*B+h[6]*q+h[10]*Y+h[14]}let _;if(i.attributes.normal){let O=i.attributes.normal;_=new Float32Array(a*3),me(w,h);for(let B=0;B<a;B++){let q=O.getX(B),Y=O.getY(B),W=O.getZ(B),j=w[0]*q+w[3]*Y+w[6]*W,x=w[1]*q+w[4]*Y+w[7]*W,I=w[2]*q+w[5]*Y+w[8]*W,N=Math.hypot(j,x,I)||1;_[B*3]=j/N,_[B*3+1]=x/N,_[B*3+2]=I/N}}let K=T,U=f;L&&L.length>=(S+1)*3&&(K=[T[0]*L[S*3],T[1]*L[S*3+1],T[2]*L[S*3+2]],U=`${f}_inst_${S}`),t.push({name:`${C}_${S}`,positions:k,indices:d,normals:_,uvs:u,materialName:U,color:K,roughness:g,metallic:m,clearcoat:p,clearcoatRoughness:R,ior:A,opacity:v,emissiveColor:D,xrTraits:r.userData?.xr})}return}t.push({name:r.name||`Mesh_${t.length}`,positions:c,indices:d,normals:l,uvs:u,materialName:f,color:T,roughness:g,metallic:m,clearcoat:p,clearcoatRoughness:R,ior:A,opacity:v,emissiveColor:D,xrTraits:r.userData?.xr,timeSamples:y})}}),t}function st(n){let e=[],t=n.gltf,r=he().decoders.get("meshopt");r&&typeof r.decodeBufferViews=="function"&&r.decodeBufferViews(t,n);let i=n.bin,s=i instanceof ArrayBuffer?i:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),a=t.accessors||[],c=t.bufferViews||[],o=t.materials||[],l=t.meshes||[],u=t.nodes||[];function d(g){let m=a[g];if(!m)throw new Error(`Accessor ${g} not found`);let p=c[m.bufferView||0],R=(p.byteOffset||0)+(m.byteOffset||0),A=p.byteLength||0,v=s.slice(R,R+A);return{acc:m,buffer:v}}let f=new Map;if(u.length>0){let g=Te(t);for(let m=0;m<g.length;m++)f.set(m,g[m])}function T(g,m,p,R){let A=l[g];if(!A)return;let v=new Float32Array(9);me(v,m);for(let D=0;D<(A.primitives||[]).length;D++){let y=A.primitives[D],P=y.attributes?.POSITION;if(P===void 0)continue;let{acc:E,buffer:b}=d(P),F=new Float32Array(b,0,E.count*3),L=new Float32Array(F.length);for(let x=0;x<E.count;x++){let I=F[x*3],N=F[x*3+1],z=F[x*3+2];L[x*3]=m[0]*I+m[4]*N+m[8]*z+m[12],L[x*3+1]=m[1]*I+m[5]*N+m[9]*z+m[13],L[x*3+2]=m[2]*I+m[6]*N+m[10]*z+m[14]}let C,h=y.attributes?.NORMAL;if(h!==void 0){let{acc:x,buffer:I}=d(h),N=new Float32Array(I,0,x.count*3);C=new Float32Array(N.length);for(let z=0;z<x.count;z++){let ee=N[z*3],ie=N[z*3+1],oe=N[z*3+2],H=v[0]*ee+v[3]*ie+v[6]*oe,$=v[1]*ee+v[4]*ie+v[7]*oe,G=v[2]*ee+v[5]*ie+v[8]*oe,te=Math.hypot(H,$,G)||1;C[z*3]=H/te,C[z*3+1]=$/te,C[z*3+2]=G/te}}let w,S=y.attributes?.TEXCOORD_0;if(S!==void 0){let{acc:x,buffer:I}=d(S);w=new Float32Array(I,0,x.count*2)}let M;if(y.indices!==void 0){let{acc:x,buffer:I}=d(y.indices);x.componentType===5125?M=new Uint32Array(I,0,x.count):M=new Uint16Array(I,0,x.count);let N=E.count;for(let z of M)if(z>=N)throw new Error(`SecurityError: Index buffer value (${z}) out of vertex bounds [0, ${N}).`)}else{let x=E.count;M=x>65535?new Uint32Array(x):new Uint16Array(x);for(let I=0;I<x;I++)M[I]=I}let k="DefaultMaterial",_=[.8,.8,.8],K=.5,U=.1,O=0,B=0,q=1.5,Y=1,W=[0,0,0];if(y.material!==void 0&&o[y.material]){let x=o[y.material];k=x.name||`Material_${y.material}`;let I=x.pbrMetallicRoughness||{},N=1;Array.isArray(I.baseColorFactor)&&(_=[I.baseColorFactor[0],I.baseColorFactor[1],I.baseColorFactor[2]],typeof I.baseColorFactor[3]=="number"&&(N=I.baseColorFactor[3])),typeof I.roughnessFactor=="number"&&(K=I.roughnessFactor),typeof I.metallicFactor=="number"&&(U=I.metallicFactor),Array.isArray(x.emissiveFactor)&&x.emissiveFactor.length>=3&&(W=[x.emissiveFactor[0],x.emissiveFactor[1],x.emissiveFactor[2]]);let z=x.extensions||{};z.KHR_materials_clearcoat&&(O=z.KHR_materials_clearcoat.clearcoatFactor??0,B=z.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),z.KHR_materials_ior&&typeof z.KHR_materials_ior.ior=="number"&&(q=z.KHR_materials_ior.ior);let ee=z.KHR_materials_transmission?.transmissionFactor??0;Y=N*(1-ee)}let j=(A.primitives||[]).length>1?`${p}_p${D}`:p;e.push({name:j,positions:L,indices:M,normals:C,uvs:w,materialName:k,color:_,roughness:K,metallic:U,clearcoat:O,clearcoatRoughness:B,ior:q,opacity:Y,emissiveColor:W,xrTraits:R?.xr||A.extras?.xr})}}if(u.length>0)for(let g=0;g<u.length;g++){let m=u[g];if(m.mesh!==void 0&&m.mesh<l.length){let p=f.get(g)||re(),R=m.name||l[m.mesh].name||`Node_${g}`,A=m.extensions?.EXT_mesh_gpu_instancing?.attributes;if(A&&typeof A=="object"){let v=A.TRANSLATION,D=A.ROTATION,y=A.SCALE,P=v!==void 0?(()=>{let{acc:L,buffer:C}=d(v);return new Float32Array(C,0,L.count*3)})():null,E=D!==void 0?(()=>{let{acc:L,buffer:C}=d(D);return new Float32Array(C,0,L.count*4)})():null,b=y!==void 0?(()=>{let{acc:L,buffer:C}=d(y);return new Float32Array(C,0,L.count*3)})():null,F=Math.min(1e3,P?P.length/3:E?E.length/4:b?b.length/3:0);if(F>0){let L=new Float32Array(16),C=new Float32Array(16);for(let h=0;h<F;h++){let w=P?[P[h*3],P[h*3+1],P[h*3+2]]:[0,0,0],S=E?[E[h*4],E[h*4+1],E[h*4+2],E[h*4+3]]:[0,0,0,1],M=b?[b[h*3],b[h*3+1],b[h*3+2]]:[1,1,1];ye(L,S,w,M),se(C,p,L),T(m.mesh,C,`${R}_${h}`,m.extras)}continue}}T(m.mesh,p,R,m.extras)}}else{let g=re();for(let m=0;m<l.length;m++){let p=l[m].name||`Mesh_${m}`;T(m,g,p,l[m].extras)}}return e}function Ue(n,e){if(!n||typeof n!="string")return e;let t=n.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(t)&&(t="_"+t),t||e}function rt(n){return String(n??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function X(n){if(!Number.isFinite(n)||Math.abs(n)<1e-7)return"0";let e=Number(n.toFixed(5)).toString();return e.indexOf(".")===-1?`${e}.0`:e}function it(n){let e=n.length/3,t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${X(n[r*3])}, ${X(n[r*3+1])}, ${X(n[r*3+2])})`;return t.join(", ")}function Dt(n,e){let t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${X(n[r*2])}, ${X(1-n[r*2+1])})`;return t.join(", ")}function Ft(n){return Array.from(n).join(", ")}function ke(n){let e=new Map;for(let o of n){let l=Ue(o.materialName,"DefaultMaterial");e.has(l)||e.set(l,{color:o.color||[.8,.8,.8],roughness:o.roughness??.5,metallic:o.metallic??0,clearcoat:o.clearcoat??0,clearcoatRoughness:o.clearcoatRoughness??0,ior:o.ior??1.5,opacity:o.opacity??1,emissiveColor:o.emissiveColor||[0,0,0]})}let t=0,r=null;for(let o of n){if(o.timeSamples&&o.timeSamples.times.length>0){let l=o.timeSamples.times[o.timeSamples.times.length-1];l>t&&(t=l)}o.xrTraits?.anchor&&!r&&(r=o.xrTraits.anchor==="vertical"||o.xrTraits.anchor==="wall"?"vertical":"horizontal")}let i="";t>0&&(i=`startTimeCode = 0
253
- endTimeCode = ${X(t)}
249
+ void main(){fragColor=uColorId;}`;function Ne(e,t,i){let r={};for(let a of i)r[a]=e.getUniformLocation(t,a);return r}var et=["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 tt(){let e=pe().xrDepthShader;return{fs:kt.replace("/*XRD_U*/",e?.uniformsGLSL||"").replace("/*XRD_O*/",e?.occlusionGLSL||""),uniforms:e?[...et,...e.uniformNames]:et}}function Ot(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 Ve(e,t,i,r,a,s,u,o){if(r===void 0||!t.accessors?.[r])return null;let d=We(t,i,t.accessors[r],s);if(!d)return null;o&&(d=d.slice(),Lt(d,o));let f=e.createBuffer();return u.push(f),e.bindBuffer(34962,f),e.bufferData(34962,d,35044),e.enableVertexAttribArray(a),e.vertexAttribPointer(a,s,5126,!1,0,0),d}function Oe(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,t):1}function it(e,t,i){let r=tt(),a=Je,s=r.fs,u=!1;for(let d of he)if(d.onResolveShader){let f=d.onResolveShader(t,i,a,s);f&&(a=f.vs,s=f.fs,u=!0)}let o=u?Ee(e,a,s):null;return{program:o,uniforms:o?Ne(e,o,r.uniforms):null}}function $t(e,t,i){let r=t.instanceMatrices;if(!r||r.length<16||typeof e.vertexAttribDivisor!="function"||typeof e.drawElementsInstanced!="function")return!1;let a=r.length>>4,s=t.instanceColors,u=new Float32Array(a*20);for(let d=0;d<a;d++)u.set(r.subarray(d*16,d*16+16),d*20),u[d*20+16]=s?s[d*3]:1,u[d*20+17]=s?s[d*3+1]:1,u[d*20+18]=s?s[d*3+2]:1,u[d*20+19]=1;let o=e.createBuffer();i.push(o),e.bindBuffer(34962,o),e.bufferData(34962,u,35044);for(let d=0;d<5;d++)e.enableVertexAttribArray(8+d),e.vertexAttribPointer(8+d,4,5126,!1,80,d*16),e.vertexAttribDivisor(8+d,1);return!0}function Ut(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 a of r){let s=a?.extensions?.KHR_texture_transform;if(s&&typeof s=="object")return s}return null}var ti=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),rt=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Re(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}function at(e,t){let i=e?.pbrMetallicRoughness,r=i?.baseColorFactor,a=e?.extensions?.KHR_materials_clearcoat,s=u=>u!==void 0&&t[u.index]?t[u.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:a?a.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,a?.clearcoatRoughnessFactor??.04),texture:s(i?.baseColorTexture),metallicRoughnessTexture:s(i?.metallicRoughnessTexture),normalTexture:s(e?.normalTexture),normalScale:e?.normalTexture?.scale??1,occlusionTexture:s(e?.occlusionTexture),occlusionStrength:e?.occlusionTexture?.strength??1,isTransmissive:(e?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function st(e,t,i){let r=new Set,a=s=>{s&&!r.has(s)&&(r.add(s),e.deleteTexture(s))};for(let s of t)for(let u of s.primitives){if(u.vao&&e.deleteVertexArray(u.vao),u.buffers)for(let d of u.buffers)e.deleteBuffer(d);a(u.texture),a(u.metallicRoughnessTexture),a(u.normalTexture),a(u.occlusionTexture);let o=new Set;u.customProgram&&o.add(u.customProgram);for(let d of u.programCache?.values()??[])d.program&&o.add(d.program);for(let d of o)e.deleteProgram(d)}if(i)for(let s of i)a(s)}function nt(e,t,i=rt,r){let a={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return Bt(e,t,i,r,a)}catch(s){let u=a.mesh&&!a.meshes.includes(a.mesh)?[...a.meshes,a.mesh]:a.meshes;st(e,u,a.gpuTextures),a.vao&&e.deleteVertexArray(a.vao);for(let o of a.buffers)e.deleteBuffer(o);throw s}}function Bt(e,t,i,r,a){if(!t||!t.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:s}=t,u=Me("meshopt");u?.decodeBufferViews&&u.decodeBufferViews(s,t);let o=t.bin,d=[];a.meshes=d;let f=[],p=s.extensions?.KHR_materials_variants;p&&Array.isArray(p.variants)&&p.variants.forEach((M,n)=>{f.push(typeof M?.name=="string"&&M.name?M.name:`Variant_${n}`)});let y=At(s),D=[];if(Array.isArray(s.nodes))for(let M=0;M<s.nodes.length;M++){let n=s.nodes[M];n.mesh!==void 0&&s.meshes&&s.meshes[n.mesh]&&D.push({node:n,nodeIdx:M,meshIdx:n.mesh})}let S=D.length>0?D:(s.meshes||[]).map((M,n)=>({node:M,nodeIdx:-1,meshIdx:n})),h=[],v=Array.isArray(t.lights)&&t.lights.length>0?t.lights:Array.isArray(s.asset?.extras?.lights)&&s.asset.extras.lights.length>0?s.asset.extras.lights:null;if(v)for(let M of v)h.push({...M,type:M.type||M.light_type||"point",innerConeAngle:M.innerConeAngle??M.inner_cone_angle,outerConeAngle:M.outerConeAngle??M.outer_cone_angle});else if(s.extensions?.KHR_lights_punctual?.lights){let M=s.extensions.KHR_lights_punctual.lights;for(let n of M){let $=n.type==="directional"?"directional":n.type==="point"?"point":n.type==="spot"?"spot":"ambient";h.push({type:$,color:n.color||[1,1,1],intensity:n.intensity!==void 0?n.intensity:1})}}if(h.length===0&&(h.push({type:"ambient",color:[1,1,1],intensity:.35}),h.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),S.length>i.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${i.maxMeshes}). Found: ${S.length}`);let P=[];if(a.gpuTextures=P,s.textures&&s.images){if(s.textures.length>i.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${i.maxTextures}). Found: ${s.textures.length}`);for(let M=0;M<s.textures.length;M++){let n=s.textures[M],$=s.images[n.source];if($){let W=e.createTexture();e.bindTexture(3553,W),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 g=_=>{e.bindTexture(3553,W),e.texImage2D(3553,0,6408,6408,5121,_),e.generateMipmap(3553),r?.()};if($.bufferView!==void 0){let _=s.bufferViews[$.bufferView],m=_.byteOffset||0,A=new Blob([o.slice(m,m+_.byteLength)],{type:$.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(A).then(g).catch(()=>{})}else if($.uri){let _=Ot($.uri);if(_){let m=new Image;m.crossOrigin="anonymous",m.referrerPolicy="no-referrer",m.onload=()=>g(m),m.src=_}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",$.uri)}P.push(W)}else P.push(null)}}let T=[1/0,1/0,1/0],x=[-1/0,-1/0,-1/0],c=0,l=0;for(let M=0;M<S.length;M++){let n=S[M],$=s.meshes[n.meshIdx],W=n.nodeIdx>=0?y[n.nodeIdx]:le(),g=new Float32Array(9);be(g,W);let _={name:n.node.name||$.name||`Mesh_${n.meshIdx}`,nodeIndex:n.nodeIdx,transform:W,normalMatrix:g,primitives:[],extras:n.node.extras||$.extras,...n.node?.visible===!1||n.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{}};a.mesh=_;let m=n.node?.extensions?.EXT_mesh_gpu_instancing;if(m&&m.attributes&&typeof m.attributes=="object"){let A=m.attributes,q=A.TRANSLATION!==void 0?s.accessors?.[A.TRANSLATION]:null,K=A.ROTATION!==void 0?s.accessors?.[A.ROTATION]:null,H=A.SCALE!==void 0?s.accessors?.[A.SCALE]:null,Q=A._COLOR_0!==void 0?s.accessors?.[A._COLOR_0]:null,C=Number(q?.count??K?.count??H?.count??0);if(!Number.isFinite(C)||C<0||C>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${C}`);if(C>0){let U=(I,J)=>{if(!I||I.bufferView===void 0||!s.bufferViews?.[I.bufferView])return null;let Y=I.componentType??5126,ae=te=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${te})`),null);if(Y!==5120&&Y!==5121&&Y!==5122&&Y!==5123&&Y!==5126)return ae(`componentType ${Y}`);if(!(Number(I.count)>=C))return ae(`count ${I.count} < ${C}`);let Z=null;try{Z=We(s,o,{...I,count:C},J)}catch{return ae("out of bounds")}return!Z||!Z.every(Number.isFinite)?ae("non-finite value"):Z},k=U(q,3),j=U(K,4),F=U(H,3),G=Q?.type==="VEC4"?4:3,V=U(Q,G),X=new Float32Array(C*16),z=le();for(let I=0;I<C;I++){let J=k?[k[I*3],k[I*3+1],k[I*3+2]]:[0,0,0],Y=j?[j[I*4],j[I*4+1],j[I*4+2],j[I*4+3]]:[0,0,0,1],ae=F?[F[I*3],F[I*3+1],F[I*3+2]]:[1,1,1];Ke(z,Y,J,ae),X.set(z,I*16)}if(_.instanceMatrices=X,V){let I=new Float32Array(C*3);for(let J=0;J<C;J++)I[J*3]=V[J*G],I[J*3+1]=V[J*G+1],I[J*3+2]=V[J*G+2];_.instanceColors=I}}}for(let A of $.primitives||[]){if(A.extensions?.KHR_draco_mesh_compression){let Z=Me("draco");Z&&Z.decodePrimitive(s,A,o)}let q=[],K=e.createVertexArray();a.vao=K,a.buffers=q,e.bindVertexArray(K);let H=$t(e,_,q),Q=s.accessors[A.attributes.POSITION],C=Number(Q?.count??0);if(!Number.isFinite(C)||C<0||c+C>i.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${i.maxVertices}).`);if(c+=C,Q?.min&&Q?.max){let Z=te=>{for(let ie=0;ie<3;ie++){let ce=te[12+ie],re=te[12+ie];for(let se=0;se<3;se++){let ne=te[se*4+ie]*Q.min[se],oe=te[se*4+ie]*Q.max[se];ce+=ne<oe?ne:oe,re+=ne>oe?ne:oe}ce<T[ie]&&(T[ie]=ce),re>x[ie]&&(x[ie]=re)}};if(_.instanceMatrices&&_.instanceMatrices.length>=16){let te=_.instanceMatrices.length>>4,ie=le();for(let ce=0;ce<te;ce++){let re=_.instanceMatrices.subarray(ce*16,ce*16+16);me(ie,W,re),Z(ie)}}else Z(W)}let U=Ve(e,s,o,A.attributes.POSITION,0,3,q);Ve(e,s,o,A.attributes.NORMAL,1,3,q),Ve(e,s,o,A.attributes.TEXCOORD_0,2,2,q,Ut(s,A));let k=0,j=5123,F=null;if(A.indices!==void 0){let Z=s.accessors[A.indices],te=(s.bufferViews[Z.bufferView].byteOffset||0)+(Z.byteOffset||0);if(k=Number(Z.count??0),!Number.isFinite(k)||k<0||l+k>i.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${i.maxIndices}).`);l+=k,j=Z.componentType===5125?5125:5123;let ie=e.createBuffer();q.push(ie),e.bindBuffer(34963,ie),Z.componentType===5125?F=new Uint32Array(o,te,Z.count):Z.componentType===5121?F=Uint16Array.from(new Uint8Array(o,te,Z.count)):F=te%2===0?new Uint16Array(o,te,Z.count):new Uint16Array(o.slice(te,te+Z.count*2)),e.bufferData(34963,F,35044)}else k=Q.count;let G={};for(let Z of he)if(Z.onBuildPrimitiveVAO){let te=Z.onBuildPrimitiveVAO(e,K,A,s,o);te&&(G[Z.name]=te)}e.bindVertexArray(null);let V=s.materials&&A.material!==void 0?s.materials[A.material]:null,{program:X,uniforms:z}=it(e,A,V),I=at(V,P),J=!!(V?.extensions?.KHR_materials_transmission||G.materials?.isTransmissive),Y=A.extensions?.KHR_materials_variants?.mappings,ae=Array.isArray(Y)?Y.filter(Z=>Z&&typeof Z.material=="number"&&Array.isArray(Z.variants)).map(Z=>({material:Z.material|0,variants:Z.variants.map(te=>Number(te)|0)})):void 0;_.primitives.push({vao:K,instanced:H,indexCount:k,indexType:j,...I,positions:U,indices:F,buffers:q,materialIndex:A.material,defaultMaterialIndex:A.material,variantMappings:ae,primitiveDef:A,programCache:new Map([[A.material??-1,{program:X,uniforms:z}]]),pluginData:G,customProgram:X,customUniforms:z,isTransmissive:J})}d.push(_)}isFinite(T[0])||(T=[-1,-1,-1]),isFinite(x[0])||(x=[1,1,1]);let b=[(T[0]+x[0])/2,(T[1]+x[1])/2,(T[2]+x[2])/2],w=x[0]-T[0],O=x[1]-T[1],B=x[2]-T[2],E=Math.max(Math.hypot(w,O,B)/2,.5),N=[T[0],T[1],T[2]],R=[x[0],x[1],x[2]],L=t.animations;if(!L){for(let M of he)if(M.onParseGLB?.(t),t.animations){L=t.animations;break}}return L||(L=[]),{meshes:d,bounds:{center:b,radius:E,min:N,max:R},lights:h,animations:L,worldMatrices:y,gpuTextures:P,availableVariants:f}}function we(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 ot=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=le(),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=le(),this.viewMatrix=le(),this.activeViewMatrix=null,this.modelMatrix=le(),this.mvpMatrix=le(),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:le(),rawValueToMeters:.001,format:0},this.container=e;let r,a;if(t&&typeof t.getContext=="function"?(r=t,a=i):(a=t,r=a?.canvas),!r){let o=e.querySelector("canvas");o||(o=document.createElement("canvas"),o.style.width="100%",o.style.height="100%",o.style.display="block",o.style.touchAction="none",e.prepend(o)),r=o}this.canvas=r,this.opts=a||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!s:s&&(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=Oe(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=ke(this.opts.toneMapping)),this.opts.autoplay!==void 0&&(this.autoplay=this.opts.autoplay),this.opts.animationName!==void 0&&(this.animationName=this.opts.animationName),this.opts.variantName!==void 0&&(this.activeVariantName=this.opts.variantName||null),this.opts.fieldOfView!==void 0&&(this.fov=this.opts.fieldOfView*Math.PI/180),this.opts.distanceMode!==void 0&&(this.distanceMode=this.opts.distanceMode),this.opts.cameraTarget!==void 0&&(this.setTarget(this.opts.cameraTarget[0],this.opts.cameraTarget[1],this.opts.cameraTarget[2]),this.initialCustomTarget=[...this.opts.cameraTarget]),(this.opts.minCameraOrbit||this.opts.maxCameraOrbit)&&this.setOrbitLimits({minTheta:this.opts.minCameraOrbit?.theta,maxTheta:this.opts.maxCameraOrbit?.theta,minPhi:this.opts.minCameraOrbit?.phi,maxPhi:this.opts.maxCameraOrbit?.phi,minDistance:this.opts.minCameraOrbit?.distance,maxDistance:this.opts.maxCameraOrbit?.distance});let u=r.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!u)throw new Error("WebGL2 not supported");this.gl=u,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){Ft(e,t)}static getDecoder(e){return Me(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=tt();this.renderProg=Ee(e,Je,t.fs),this.pickProg=Ee(e,Nt,Vt),this.uRender=Ne(e,this.renderProg,t.uniforms),this.uPick=Ne(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of he)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),a=Math.max(1,t);this.pickFboWidth=r,this.pickFboHeight=a,i.bindTexture(3553,this.pickTexture),i.texImage2D(3553,0,6408,r,a,0,6408,5121,null),i.bindRenderbuffer(36161,this.pickDepth),i.renderbufferStorage(36161,33189,r,a)}loadGLBData(e,t){let{meshes:i,bounds:r,lights:a,animations:s,worldMatrices:u,gpuTextures:o,availableVariants:d}=nt(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=a,this.animations=s||[],this.worldMatrices=u||[],this.gpuTextures=o||[],this.availableVariants=d||[],this.gltf=e.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let y of e.gltf.nodes)this.initialNodeTransforms.push({t:y.translation?[y.translation[0],y.translation[1],y.translation[2]]:[0,0,0],r:y.rotation?[y.rotation[0],y.rotation[1],y.rotation[2],y.rotation[3]]:[0,0,0,1],s:y.scale?[y.scale[0],y.scale[1],y.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let y of he)y.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 f=e.exposure??e.gltf?.extras?.exposure??e.gltf?.asset?.extras?.exposure;f!==void 0&&(this.exposure=Oe(f));let p=e.environmentIntensity??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.environmentIntensity;p!==void 0&&(this.envIntensity=Math.max(0,Number(p)||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(Qe(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let e of he)e.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(Ae(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let i=Ae(e),{meshes:r}=nt(this.gl,i,rt,()=>this.render());if(t)for(let a of r)a.transform[12]+=t[0],a.transform[13]+=t[1],a.transform[14]+=t[2],be(a.normalMatrix,a.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),be(i.normalMatrix,i.transform))}}bindLights(e=this.uRender){let t=this.gl,i=[.28,.28,.28],r=[],a=[],s=[],u=[],o=[],d=[];for(let f of this.lights){let p=f.color||[1,1,1],y=f.intensity!==void 0?f.intensity:1;if(f.type==="ambient")i=[p[0]*y,p[1]*y,p[2]*y];else if(f.type==="directional"&&r.length<6){let D=f.direction||[.5,1,.8];r.push(D[0],D[1],D[2]),a.push(p[0]*y,p[1]*y,p[2]*y)}else if((f.type==="point"||f.type==="spot")&&s.length<6){let D=f.position||[0,0,0];if(s.push(D[0],D[1],D[2]),u.push(p[0]*y,p[1]*y,p[2]*y),f.type==="spot"){let S=f.direction||[0,-1,0],h=Math.max(.01,Math.min(Math.PI/2,f.outerConeAngle??Math.PI/3)),v=Math.max(0,Math.min(h-1e-4,f.innerConeAngle??0));o.push(S[0],S[1],S[2]),d.push(Math.cos(v),Math.cos(h))}else o.push(0,-1,0),d.push(-2,-3)}}r.length===0&&(r.push(.5,1,.8),a.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,a)),t.uniform1i(e.uNumPointLights,s.length/3),s.length>0&&(t.uniform3fv(e.uPointLightPos,s),t.uniform3fv(e.uPointLightColor,u),e.uPointLightSpotDir&&t.uniform3fv(e.uPointLightSpotDir,o),e.uPointLightSpotCone&&t.uniform2fv(e.uPointLightSpotCone,d)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=Oe(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=ke(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of he)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of he)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(f=>f.primitives.filter(p=>p.materialIndex===i||e.length===1&&p.materialIndex===void 0)),a=r[0],s=a?[...a.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],u=a?a.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,o=a?a.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,d={baseColorFactor:s,metallicFactor:u,roughnessFactor:o,setBaseColorFactor:f=>{let p=[f[0],f[1],f[2],f[3]??1];d.baseColorFactor=p,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=p);for(let y of r)y.baseColor=p;this.render()},setMetallicFactor:f=>{d.metallicFactor=f,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=f);for(let p of r)p.metallic=f;this.render()},setRoughnessFactor:f=>{d.roughnessFactor=f,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=f);for(let p of r)p.roughness=f;this.render()}};return{name:t.name||`Material_${i}`,pbrMetallicRoughness:d}})}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 a of this.meshes)for(let s of a.primitives){let u=s.defaultMaterialIndex;if(!t&&Array.isArray(s.variantMappings)){for(let d of s.variantMappings)if(Array.isArray(d.variants)&&d.variants.includes(i)){u=d.material;break}}let o=u!==void 0?r[u]:void 0;s.materialIndex=o?u:void 0,Object.assign(s,at(o,this.gpuTextures)),this.applyPrimitiveProgram(s,s.materialIndex,o??null)}return!0}applyPrimitiveProgram(e,t,i){if(!this.gl||!e.primitiveDef)return;e.programCache??(e.programCache=new Map);let r=t??-1,a=e.programCache.get(r);a||(a=it(this.gl,{...e.primitiveDef,material:t},i),e.programCache.set(r,a)),e.customProgram=a.program,e.customUniforms=a.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 he)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 a=this.clampDistance(i);this.initialDistance=a,this.customDistance=!0,this.targetDistance=a,this.currDistance=a}else if(r!==void 0&&r>0){let a=this.clampDistance(this.bounds.radius*2.5/r);this.initialDistance=a,this.customDistance=!0,this.targetDistance=a,this.currDistance=a}else{this.customDistance=!1;let a=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=a,this.targetDistance=a,this.currDistance=a}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=le();me(i,this.projMatrix,this.viewMatrix);let[r,a,s]=e,u=t?t[0]:0,o=t?t[1]:0,d=t?t[2]:0,f=this.modelRootMatrix;f&&(r=f[0]*e[0]+f[4]*e[1]+f[8]*e[2]+f[12],a=f[1]*e[0]+f[5]*e[1]+f[9]*e[2]+f[13],s=f[2]*e[0]+f[6]*e[1]+f[10]*e[2]+f[14],t&&(u=f[0]*t[0]+f[4]*t[1]+f[8]*t[2],o=f[1]*t[0]+f[5]*t[1]+f[9]*t[2],d=f[2]*t[0]+f[6]*t[1]+f[10]*t[2]));let p=i[0]*r+i[4]*a+i[8]*s+i[12],y=i[1]*r+i[5]*a+i[9]*s+i[13],D=i[2]*r+i[6]*a+i[10]*s+i[14],S=i[3]*r+i[7]*a+i[11]*s+i[15];if(S<=1e-4)return{x:0,y:0,z:1,visible:!1};let h=p/S,v=y/S,P=D/S,T=this.canvas.getBoundingClientRect(),x=T.width||this.canvas.clientWidth||this.canvas.width||300,c=T.height||this.canvas.clientHeight||this.canvas.height||150,l=(h*.5+.5)*x,b=(-v*.5+.5)*c,w=h>=-1.1&&h<=1.1&&v>=-1.1&&v<=1.1&&P>=-1&&P<=1;if(w&&t){let[O,B,E]=we(this),N=[r-O,a-B,s-E];u*N[0]+o*N[1]+d*N[2]>.05&&(w=!1)}return{x:l,y:b,z:P,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},a=i.clientX-r.x,s=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(a,s),this.isPanning||i.button===2||i.shiftKey||this.activePointers.size===2){let u=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],o=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],d=this.customTarget?[...this.customTarget]:[...this.bounds.center],f=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;d[0]+=(-a*u[0]+s*o[0])*f,d[1]+=(-a*u[1]+s*o[1])*f,d[2]+=(-a*u[2]+s*o[2])*f,this.customTarget=d}else this.targetTheta=this.clampTheta(this.targetTheta-a*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.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(),a=Math.floor((i.clientX-r.left)*(e.width/Math.max(r.width,1))),s=Math.floor((i.clientY-r.top)*(e.height/Math.max(r.height,1)));this.performMeshPick(a,s,!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,a)=>{this[a]&&(i.removeEventListener(r,this[a]),this[a]=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(),a=i.width||300,s=i.height||300,u=r.width>0?Math.floor((e-r.left)*(a/r.width)):Math.floor(e),o=r.height>0?Math.floor((t-r.top)*(s/r.height)):Math.floor(t);return this.performMeshPick(u,o,!1)}performMeshPick(e,t,i=!0){if(this.meshes.length===0)return null;let r=this.gl,a=Math.max(1,this.canvas.width||300),s=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,a);let u=le();me(u,this.projMatrix,this.viewMatrix);let o=[],d=Math.max(0,Math.min(a-1,e)),f=Math.max(0,Math.min(s-1,s-1-t));if(this.pickFbo&&r&&!this.xrSessionActive){(this.pickFboWidth!==a||this.pickFboHeight!==s)&&this.resizePickingFbo(a,s),r.bindFramebuffer(36160,this.pickFbo),r.viewport(0,0,a,s),r.enable(2929),r.clearColor(0,0,0,0),r.clear(16640),r.useProgram(this.pickProg);for(let b=0;b<this.meshes.length;b++){let w=this.meshes[b];if(w.visible===!1||w.isPluginMesh)continue;let O=b+1,B=(O&255)/255,E=(O>>8&255)/255,N=(O>>16&255)/255;r.uniform4f(this.uPick.uColorId,B,E,N,1),me(this.modelMatrix,this.modelRootMatrix,w.transform);let R=w.instanceMatrices;if(R&&R.length>=16){let L=R.length>>4,M=le();for(let n of w.primitives){r.bindVertexArray(n.vao);for(let $=0;$<L;$++)me(M,this.modelMatrix,R.subarray($*16,$*16+16)),me(this.mvpMatrix,u,M),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),Re(r,n)}}else{me(this.mvpMatrix,u,this.modelMatrix),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let L of w.primitives)r.bindVertexArray(L.vao),Re(r,L)}}let c=new Uint8Array(4);r.readPixels(d,f,1,1,6408,5121,c),r.bindFramebuffer(36160,null);let l=c[0]+(c[1]<<8)+(c[2]<<16);l>0&&l<=this.meshes.length&&(o=[this.meshes[l-1]])}o.length===0&&(o=this.meshes.filter(c=>c.visible!==!1));let p=null,y=1/0,D=[0,0,0],S=[0,1,0],[h,v,P]=we(this),T=le();for(let c of o){me(T,this.modelRootMatrix,c.transform);let l=c.instanceMatrices,b=l&&l.length>=16?l.length>>4:1;for(let w=0;w<b;w++){l&&l.length>=16?me(this.modelMatrix,T,l.subarray(w*16,w*16+16)):this.modelMatrix.set(T),me(this.mvpMatrix,u,this.modelMatrix);let O=le();if(!Tt(O,this.mvpMatrix))continue;let B=(d+.5)/a*2-1,E=(f+.5)/s*2-1,N=[0,0,0],R=[0,0,0];Xe(N,B,E,-1,O),Xe(R,B,E,1,O);let L=R[0]-N[0],M=R[1]-N[1],n=R[2]-N[2],$=Math.hypot(L,M,n)||1,W=L/$,g=M/$,_=n/$,m={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((A=>{for(let q of c.primitives){if(!q.positions)continue;let K=q.positions,H=q.indices,Q=Math.floor(H?H.length/3:K.length/9);for(let C=0;C<Q;C++){let U=H?H[C*3]:C*3,k=H?H[C*3+1]:C*3+1,j=H?H[C*3+2]:C*3+2;Pt(N[0],N[1],N[2],W,g,_,K[U*3],K[U*3+1],K[U*3+2],K[k*3],K[k*3+1],K[k*3+2],K[j*3],K[j*3+1],K[j*3+2],m,A)}}})(1e-4),isFinite(m.distance)){let A=m.point[0],q=m.point[1],K=m.point[2],H=this.modelMatrix,Q=H[0]*A+H[4]*q+H[8]*K+H[12],C=H[1]*A+H[5]*q+H[9]*K+H[13],U=H[2]*A+H[6]*q+H[10]*K+H[14],k=Q-h,j=C-v,F=U-P,G=Math.hypot(k,j,F);if(G<y){be(this.normalMatrix,this.modelMatrix);let V=this.normalMatrix,X=m.normal[0],z=m.normal[1],I=m.normal[2],J=V[0]*X+V[3]*z+V[6]*I,Y=V[1]*X+V[4]*z+V[7]*I,ae=V[2]*X+V[5]*z+V[8]*I,Z=Math.hypot(J,Y,ae)||1;J/=Z,Y/=Z,ae/=Z,J*k+Y*j+ae*F>0&&(J=-J,Y=-Y,ae=-ae),p=c,y=Math.round(G*1e3)/1e3,D=[Math.round(Q*1e3)/1e3,Math.round(C*1e3)/1e3,Math.round(U*1e3)/1e3],S=[Math.round(J*1e3)/1e3,Math.round(Y*1e3)/1e3,Math.round(ae*1e3)/1e3]}}}}if(!p)return null;let x={meshIndex:this.meshes.indexOf(p),meshName:p.name,nodeIndex:p.nodeIndex,distance:y,hitPoint:D,normal:S,screenX:e,screenY:t};if(i){for(let c of he)c.onMeshSelect?.(this,x);this.opts.onMeshClick&&this.opts.onMeshClick(x),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:x}))}return x}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let i=Math.max(1,Math.floor(t*.5)),r=e>=i,a=r?e-i:e,s=r?Math.max(1,t-i):i,u=(a+.5)/s*2-1;return Math.floor((u*.5+1)*.5*t)}setStereoSBS(e){this.stereoSBS=!!e,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let e=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),t=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);_e(this.projMatrix,this.fov,e,.1,t);let i=this.customTarget||this.bounds.center;Fe(this.viewMatrix,we(this),i,[0,1,0]),me(this.mvpMatrix,this.projMatrix,this.viewMatrix),be(this.normalMatrix,this.modelMatrix)}resize(){let e=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),t=this.canvas.getBoundingClientRect(),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 he)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 he)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],a=this.modelRootMatrix;a[0]=e,a[1]=0,a[2]=-t,a[3]=0,a[4]=0,a[5]=1,a[6]=0,a[7]=0,a[8]=t,a[9]=0,a[10]=e,a[11]=0,a[12]=i-(e*i+t*r),a[13]=0,a[14]=r-(-t*i+e*r),a[15]=1}setVisible(e){this.isVisible=e}update(e){for(let s of he)s.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 s of he)s.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),a=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(a-this.lastReportedZoom)>=.02){this.lastReportedTheta=i,this.lastReportedPhi=r,this.lastReportedZoom=a;let s={theta:i,phi:r,zoom:a,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(s),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:s}))}}renderXRView(e,t,i,r,a=!0,s=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let u=e?.transform?.inverse?.matrix||this.viewMatrix,o=e?.projectionMatrix||this.projMatrix,d=e?.transform?.position,f=d?[d.x,d.y,d.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):i&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:u,projMatrix:o,eyePos:f,viewport:r,eye:e?.eye||"none",clear:s>0?!1:e?.eye!=="right",isAR:a})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let x=Math.max(2,this.canvas.width||2),c=Math.max(1,this.canvas.height||1),l=Math.max(1,Math.floor(x*.5)),b=Math.max(1,x-l),w=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),O=this.customTarget||this.bounds.center,[B,E,N]=we(this),R=Math.cos(this.currTheta),L=-Math.sin(this.currTheta),M=.032,n=le(),$=le(),W=[B-R*M,E,N-L*M],g=[O[0]-R*M*.25,O[1],O[2]-L*M*.25];_e(n,this.fov,l/c,.1,w),Fe($,W,g,[0,1,0]);let _=le(),m=le(),A=[B+R*M,E,N+L*M],q=[O[0]+R*M*.25,O[1],O[2]+L*M*.25];_e(_,this.fov,b/c,.1,w),Fe(m,A,q,[0,1,0]),this.render({viewMatrix:$,projMatrix:n,eyePos:W,viewport:[0,0,l,c],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:m,projMatrix:_,eyePos:A,viewport:[l,0,b,c],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,x,c);return}let t=this.gl,i=0,r=0,a=this.canvas.width,s=this.canvas.height;e?.viewport?(i=e.viewport[0],r=e.viewport[1],a=e.viewport[2],s=e.viewport[3],t.viewport(i,r,a,s)):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 u=le(),o=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=o,me(u,e?.projMatrix??this.projMatrix,o);let d=pe().xrDepthShader,f=It(this.toneMapping),[p,y,D]=e?e.eyePos:we(this);for(let x of he)x.onBeforeDrawScene?.(this,t,u,[p,y,D],f);let S=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&S===0)return;let h=e?.eye||"none",v=!1,P=S>0?[...this.backdropMeshes,...this.meshes]:this.meshes,T=x=>{for(let c=0;c<P.length;c++){let l=P[c];if(l.visible===!1)continue;let b=this.selectedMeshName!==""&&l.name===this.selectedMeshName;c<S||l.worldSpace===!0||l.name==="__xr_reticle__"?this.modelMatrix.set(l.transform):me(this.modelMatrix,this.modelRootMatrix,l.transform),me(this.mvpMatrix,u,this.modelMatrix),be(l.normalMatrix,this.modelMatrix);let w=l.extras?.xr?.stereo||l.userData?.xr?.stereo,O=0,B=0,E=1,N=1;w==="sbs"?(E=.5,O=h==="right"?.5:0):w==="ou"&&(N=.5,B=h==="right"?.5:0);for(let R of l.primitives){let L=!!R.isTransmissive;if(!x&&L){v=!0;continue}if(x&&!L)continue;let M=R.customProgram||this.renderProg,n=R.customUniforms||this.uRender;t.useProgram(M),t.vertexAttrib3f(3,0,0,0),n.uInstanced&&t.uniform1i(n.uInstanced,0),t.uniform1i(n.uToneMapping,f),t.uniform1f(n.uEnvIntensity,this.envIntensity),n.uExposure&&t.uniform1f(n.uExposure,this.exposure),t.uniform3f(n.uCameraPos,p,y,D),t.uniform1f(n.uEmissive,b?1:0),t.uniformMatrix4fv(n.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(n.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(n.uNormalMatrix,!1,l.normalMatrix),n.uUvTransform&&t.uniform4f(n.uUvTransform,O,B,E,N),n.uViewportSize&&t.uniform2f(n.uViewportSize,Math.max(1,a),Math.max(1,s)),d?.bind(t,n,this.xrDepthState,o,[i,r,Math.max(1,a),Math.max(1,s)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(n.uEnvironmentMap,4),t.uniform1i(n.uHasEnvironmentMap,1)):t.uniform1i(n.uHasEnvironmentMap,0),this.bindLights(n),n.uSectionEnabled&&t.uniform1i(n.uSectionEnabled,0);for(let W of he)W.onBeforeDrawPrimitive?.(t,M,R,l,this.worldMatrices||[],this.gltf);t.uniform4fv(n.uBaseColor,R.baseColor),t.uniform1f(n.uMetallic,R.metallic),t.uniform1f(n.uRoughness,R.roughness),n.uClearcoat&&t.uniform2f(n.uClearcoat,R.clearcoat??0,R.clearcoatRoughness??.04),R.texture?(t.activeTexture(33984),t.bindTexture(3553,R.texture),t.uniform1i(n.uBaseColorTexture,0),t.uniform1i(n.uHasTexture,1)):t.uniform1i(n.uHasTexture,0),R.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,R.metallicRoughnessTexture),t.uniform1i(n.uMetallicRoughnessTexture,1),t.uniform1i(n.uHasMetallicRoughnessTexture,1)):t.uniform1i(n.uHasMetallicRoughnessTexture,0),R.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,R.normalTexture),t.uniform1i(n.uNormalTexture,2),t.uniform1i(n.uHasNormalTexture,1),t.uniform1f(n.uNormalScale,R.normalScale)):t.uniform1i(n.uHasNormalTexture,0),R.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,R.occlusionTexture),t.uniform1i(n.uOcclusionTexture,3),t.uniform1i(n.uHasOcclusionTexture,1),t.uniform1f(n.uOcclusionStrength,R.occlusionStrength)):t.uniform1i(n.uHasOcclusionTexture,0),t.bindVertexArray(R.vao);let $=l.instanceMatrices;if(R.instanceCount!==void 0)t.drawElementsInstanced(4,R.indexCount,R.indexType,0,R.instanceCount);else if($&&$.length>=16&&R.instanced&&n.uInstanced&&n.uViewProj){let W=$.length>>4;t.uniform1i(n.uInstanced,1),t.uniformMatrix4fv(n.uViewProj,!1,u),R.indices?t.drawElementsInstanced(4,R.indexCount,R.indexType,0,W):t.drawArraysInstanced(4,0,R.indexCount,W),t.uniform1i(n.uInstanced,0)}else if($&&$.length>=16){let W=$.length>>4,g=l.instanceColors,_=le(),m=new Float32Array(9),A=[R.baseColor[0],R.baseColor[1],R.baseColor[2],R.baseColor[3]];for(let q=0;q<W;q++)me(_,this.modelMatrix,$.subarray(q*16,q*16+16)),me(this.mvpMatrix,u,_),be(m,_),t.uniformMatrix4fv(n.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(n.uModel,!1,_),t.uniformMatrix3fv(n.uNormalMatrix,!1,m),g&&(A[0]=R.baseColor[0]*g[q*3],A[1]=R.baseColor[1]*g[q*3+1],A[2]=R.baseColor[2]*g[q*3+2],A[3]=R.baseColor[3],t.uniform4fv(n.uBaseColor,A)),Re(t,R)}else Re(t,R)}}};if(T(!1),v){for(let x of he)x.onBeforeTransmissivePass?.(t,this);T(!0)}for(let x of he)x.onAfterRender?.(t,this,u,e?.eye??"none",[i,r,a,s],e?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(e,t){st(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 he)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()}};ot.registerPlugin=Rt,ot.getRegisteredPlugins=Ct;function Ht(e){return e+3&-4}var ee=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t;function lt(e,t){let i=t,r=1;for(;e.has(i);)i=`${t}_${r++}`;return e.add(i),i}function ht(e,t=0){let[i,r,a,,s,u,o,,d,f,p,,y,D,S]=Array.from({length:15},(m,A)=>ee(e[t+A],A%5===0?1:0)),h=Math.hypot(i,r,a),v=Math.hypot(s,u,o),P=Math.hypot(d,f,p);i*(u*p-f*o)-s*(r*p-f*a)+d*(r*o-u*a)<0&&(h=-h);let T=Math.abs(h)>1e-8?1/h:0,x=Math.abs(v)>1e-8?1/v:0,c=Math.abs(P)>1e-8?1/P:0,l=i*T,b=r*T,w=a*T,O=s*x,B=u*x,E=o*x,N=d*c,R=f*c,L=p*c,M=l+B+L,n=0,$=0,W=0,g=1;if(M>0){let m=.5/Math.sqrt(M+1);g=.25/m,n=(E-R)*m,$=(N-w)*m,W=(b-O)*m}else if(l>B&&l>L){let m=2*Math.sqrt(Math.max(0,1+l-B-L));m>1e-8&&(g=(E-R)/m,n=.25*m,$=(O+b)/m,W=(N+w)/m)}else if(B>L){let m=2*Math.sqrt(Math.max(0,1+B-l-L));m>1e-8&&(g=(N-w)/m,n=(O+b)/m,$=.25*m,W=(E+R)/m)}else{let m=2*Math.sqrt(Math.max(0,1+L-l-B));m>1e-8&&(g=(b-O)/m,n=(N+w)/m,$=(E+R)/m,W=.25*m)}let _=Math.hypot(n,$,W,g);return _>1e-8&&Number.isFinite(_)?(n/=_,$/=_,W/=_,g/=_):(n=0,$=0,W=0,g=1),{t:[y,D,S],r:[n,$,W,g],s:[h,v,P]}}function zt(e){let t={};return e.grab&&(t.interactable={mode:typeof e.grab=="string"?e.grab:"2-hand"},t.movable={scaleInZ:!!e.scale,minScale:typeof e.scale=="object"?e.scale.min??.1:.1,maxScale:typeof e.scale=="object"?e.scale.max??10:10}),e.billboard&&(t.billboard={mode:typeof e.billboard=="string"?e.billboard:"capsule"}),e.follow&&(t.follow={target:typeof e.follow=="object"?e.follow.mode??"head":e.follow}),e.anchor&&(t.anchor={plane:e.anchor}),e.physics&&e.physics!=="none"&&(t.rigidbody={type:e.physics}),t}var ve=(e,t,i,r)=>typeof e=="number"&&Number.isFinite(e)?Math.max(t,Math.min(i,e)):r;function ut(e){let t=e?.audioEmitter??e?.spatialAudio??(typeof e?.audio=="object"&&e.audio&&("preset"in e.audio||"distanceModel"in e.audio||"coneInnerAngle"in e.audio||"maxDistance"in e.audio||"volume"in e.audio)?e.audio:typeof e?.audio=="string"&&/^(hum|reactor|wind|beacon|geiger|chimeLoop|machinery|water)$/.test(e.audio)?{preset:e.audio}:void 0);if(!t||typeof t=="object"&&t.enabled===!1)return null;let i=typeof t=="string"?{preset:t}:t,r=typeof i.src=="string"&&!/[\x00-\x20\\%]|^\s*(javascript|data|file|http):/i.test(i.src)?i.src:void 0,a=typeof i.preset=="string"?i.preset:void 0;return!r&&!a?null:{ae:i,src:r,preset:a,volume:ve(i.volume,0,2,.6),loop:typeof i.loop=="boolean"?i.loop:!0,isGlobal:i.type==="global"||i.positional===!1}}function jt(e,t){e.updateMatrixWorld(!0);let i=[],r=0,a=[],s=[],u=[],o=[],d=new Set,f=[],p=[],y=new Map,D=[],S=[],h=[],v=new Map,P=[],T=[];function x(g){let _=y.get(g);if(_!==void 0)return _;_=p.length,y.set(g,_);let m=g,A=m.color?.r??.8,q=m.color?.g??.8,K=m.color?.b??.8,H=m.opacity??1,Q={baseColorFactor:[A,q,K,H],metallicFactor:m.metalness??0,roughnessFactor:m.roughness??.5},C={};if(m.map){let j="";typeof m.map=="string"?j=m.map:typeof m.map.source=="string"?j=m.map.source:typeof m.map.image=="string"&&(j=m.map.image);let F=j.trim(),G=F&&!/[\x00-\x1f\x7f\\]|\.\./.test(F)&&(/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(F)||!F.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(F))?F:null;if(G){let X=v.get(G);if(X===void 0){let z=D.length;D.push({uri:G}),S.length===0&&S.push({magFilter:9729,minFilter:9987,wrapS:10497,wrapT:10497}),X=h.length,h.push({sampler:0,source:z}),v.set(G,X)}Q.baseColorTexture={index:X}}let V=m.map.avgColor;Array.isArray(V)&&V.length>=3&&(C.avgColor=[V[0],V[1],V[2]])}let U={name:m.name||"",pbrMetallicRoughness:Q,doubleSided:m.side===2||!!m.doubleSided,...Object.keys(C).length>0?{extras:C}:{}};if(m.emissive&&(m.emissive.r>0||m.emissive.g>0||m.emissive.b>0)){let j=m.emissiveIntensity??1;U.emissiveFactor=[m.emissive.r*j,m.emissive.g*j,m.emissive.b*j]}let k={};return m.clearcoat&&m.clearcoat>0&&(k.KHR_materials_clearcoat={clearcoatFactor:m.clearcoat,clearcoatRoughnessFactor:m.clearcoatRoughness||0}),m.sheen&&m.sheen>0&&(k.KHR_materials_sheen={sheenColorFactor:m.sheenColor?[m.sheenColor.r,m.sheenColor.g,m.sheenColor.b]:[1,1,1],sheenRoughnessFactor:m.sheenRoughness||0}),m.transmission&&m.transmission>0&&(k.KHR_materials_transmission={transmissionFactor:m.transmission}),m.thickness&&m.thickness>0&&(k.KHR_materials_volume={thicknessFactor:m.thickness,attenuationDistance:m.attenuationDistance??1/0,attenuationColor:m.attenuationColor?[m.attenuationColor.r,m.attenuationColor.g,m.attenuationColor.b]:[1,1,1]}),m.ior!==void 0&&m.ior!==1.5&&(k.KHR_materials_ior={ior:m.ior}),m.dispersion&&m.dispersion>0&&(k.KHR_materials_dispersion={dispersion:m.dispersion}),m.iridescence&&m.iridescence>0&&(k.KHR_materials_iridescence={iridescenceFactor:m.iridescence,iridescenceIor:m.iridescenceIOR??1.3}),Object.keys(k).length>0&&(U.extensions=k),p.push(U),_}function c(g,_){let m=new Uint8Array(g.buffer,g.byteOffset,g.byteLength),A=Ht(m.byteLength),q=new Uint8Array(A);q.set(m),i.push(q);let K=a.length;return a.push({buffer:0,byteOffset:r,byteLength:m.byteLength,target:_}),r+=A,K}function l(g,_,m,A,q,K,H){let Q=c(g,m),C=s.length,U={bufferView:Q,byteOffset:0,componentType:A,count:q,type:_};return K&&(U.min=K),H&&(U.max=H),s.push(U),C}e.traverse(g=>{if(g.isLight||g.color&&g.intensity!==void 0){let _=g.matrixWorld?.elements,m=ee(_?_[12]:g.position?.x,0),A=ee(_?_[13]:g.position?.y,0),q=ee(_?_[14]:g.position?.z,0),K=g.target,H=K?.parent?K?.matrixWorld?.elements:void 0,Q=ee(H?H[12]:K?.position?.x,0),C=ee(H?H[13]:K?.position?.y,0),U=ee(H?H[14]:K?.position?.z,0),k=Q-m,j=C-A,F=U-q,G=Math.hypot(k,j,F),V=Math.max(.01,Math.min(Math.PI/2,ee(g.angle,Math.PI/3))),X=Math.max(0,Math.min(1,ee(g.penumbra,0)));T.push({type:g.type,color:[g.color.r,g.color.g,g.color.b],intensity:g.intensity,position:[m,A,q],...g.type==="spot"?{direction:G>1e-6?[k/G,j/G,F/G]:[0,-1,0],outerConeAngle:V,innerConeAngle:Math.max(0,V*(1-X)),range:Math.max(0,ee(g.distance,0))}:g.type==="point"?{range:Math.max(0,ee(g.distance,0))}:{}})}});let b=[],w=new Set([e]),O=[];if(Array.isArray(e.children))for(let g=e.children.length-1;g>=0;g--)O.push({obj:e.children[g],parentKids:b});for(;O.length>0;){let{obj:g,parentKids:_}=O.pop();if(!g||typeof g!="object"||w.has(g))continue;w.add(g),g._bakeAuthorGeometry?.(),pe().materializeDeclarativeGeometry?.(g);let m=!!(g.userData&&(g.userData.xr&&typeof g.userData.xr=="object"&&Object.keys(g.userData.xr).length>0||g.userData.interactivity&&typeof g.userData.interactivity=="object"&&Object.keys(g.userData.interactivity).length>0)),A={name:g.name||(m?`Node_${o.length}`:"")},q=ee(g.position?.x,0),K=ee(g.position?.y,0),H=ee(g.position?.z,0),Q=ee(g.quaternion?.x,0),C=ee(g.quaternion?.y,0),U=ee(g.quaternion?.z,0),k=ee(g.quaternion?.w,1),j=ee(g.scale?.x,1),F=ee(g.scale?.y,1),G=ee(g.scale?.z,1);if((q||K||H)&&(A.translation=[q,K,H]),(Q||C||U||k!==1)&&(A.rotation=[Q,C,U,k]),(j!==1||F!==1||G!==1)&&(A.scale=[j,F,G]),g.visible===!1&&(A.extensions={...A.extensions||{},KHR_node_visibility:{visible:!1}},d.add("KHR_node_visibility")),g.userData&&Object.keys(g.userData).length>0&&(A.extras=JSON.parse(JSON.stringify(g.userData,(z,I)=>{if(!(z==="__proto__"||z==="prototype"||z==="constructor"))return typeof I=="function"?void 0:I})),g.userData.xr)){let z=zt(g.userData.xr);A.extensions={...A.extensions||{},MOZ_hubs_components:z,ANDROID_xr_scenecore:z},pe().xrTraitSerializer?.gltfNode(A,g.userData.xr),d.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(g.geometry){let z=g.geometry,I=z.attributes.position;if(I&&I.count>0){let J=[1/0,1/0,1/0],Y=[-1/0,-1/0,-1/0];for(let re=0;re<I.count;re++){let se=I.getX(re),ne=I.getY(re),oe=I.getZ(re);se<J[0]&&(J[0]=se),se>Y[0]&&(Y[0]=se),ne<J[1]&&(J[1]=ne),ne>Y[1]&&(Y[1]=ne),oe<J[2]&&(J[2]=oe),oe>Y[2]&&(Y[2]=oe)}let ae={attributes:{POSITION:l(I.array,"VEC3",34962,5126,I.count,J,Y)}};if(z.attributes.normal&&(ae.attributes.NORMAL=l(z.attributes.normal.array,"VEC3",34962,5126,z.attributes.normal.count)),z.attributes.uv&&(ae.attributes.TEXCOORD_0=l(z.attributes.uv.array,"VEC2",34962,5126,z.attributes.uv.count)),z.index){let re=z.index.array instanceof Uint32Array;ae.indices=l(z.index.array,"SCALAR",34963,re?5125:5123,z.index.count)}let Z=Array.isArray(g.material)?g.material[0]:g.material;Z&&(ae.material=x(Z));let te=g.userData?.variants;if(te&&typeof te=="object"){let re=new Map;for(let se of Object.keys(te)){if(!se||se==="__proto__"||se==="constructor"||se==="prototype")continue;let ne=te[se];if(!ne||typeof ne!="object")continue;let oe=P.indexOf(se);if(oe===-1&&P.length<256&&(oe=P.length,P.push(se)),oe===-1)continue;let de=x(ne),xe=re.get(de);xe||(xe=[],re.set(de,xe)),xe.push(oe)}if(re.size>0){let se=[];for(let[ne,oe]of re.entries())se.push({material:ne,variants:oe});ae.extensions={...ae.extensions||{},KHR_materials_variants:{mappings:se}},d.add("KHR_materials_variants")}}let ie=g;if(ie.isInstancedMesh&&typeof ie.count=="number"&&ie.count>0&&ie.instanceMatrix?.array){let re=Math.min(1e4,Math.floor(ie.count)),se=ie.instanceMatrix.array,ne=new Float32Array(re*3),oe=new Float32Array(re*4),de=new Float32Array(re*3);for(let fe=0;fe<re;fe++){let{t:Le,r:Te,s:Ie}=ht(se,fe*16);ne[fe*3]=Le[0],ne[fe*3+1]=Le[1],ne[fe*3+2]=Le[2],oe[fe*4]=Te[0],oe[fe*4+1]=Te[1],oe[fe*4+2]=Te[2],oe[fe*4+3]=Te[3],de[fe*3]=Ie[0],de[fe*3+1]=Ie[1],de[fe*3+2]=Ie[2]}let xe={TRANSLATION:l(ne,"VEC3",0,5126,re),ROTATION:l(oe,"VEC4",0,5126,re),SCALE:l(de,"VEC3",0,5126,re)};if(ie.instanceColor?.array&&ie.instanceColor.array.length>=re*3){let fe=new Float32Array(ie.instanceColor.array.subarray(0,re*3));xe._COLOR_0=l(fe,"VEC3",0,5126,re)}A.extensions={...A.extensions||{},EXT_mesh_gpu_instancing:{attributes:xe}},d.add("EXT_mesh_gpu_instancing")}let ce=u.length;u.push({primitives:[ae],name:g.name,...A.extras?{extras:A.extras}:{}}),A.mesh=ce}}let V=o.length;o.push(A),f.push(g),_.push(V);let X=g.children;if(Array.isArray(X)&&X.length>0){let z=[];A.children=z;for(let I=X.length-1;I>=0;I--)O.push({obj:X[I],parentKids:z})}}for(let g=0;g<o.length;g++){let _=o[g];_.children&&_.children.length===0?delete _.children:_.children&&_.children.length>0&&(_.extras?.xr?.lod||_.extensions?.ANDROID_xr_scenecore?.lod||f[g]?.isLOD)&&(_.extensions={..._.extensions||{},MSFT_lod:{ids:[..._.children]}},d.add("MSFT_lod"))}let B=t?.animateCallback||t?.animateFn||(typeof e.userData?.animate=="function"?e.userData.animate:typeof e.__animateFn=="function"?e.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0),E=[];if(typeof B=="function"&&f.length>0){let g=t?.duration??4,_=t?.fps??15,m=Math.max(2,Math.round(g*_)+1),A=new Float32Array(m),q=f.map(F=>[ee(F.position?.x,0),ee(F.position?.y,0),ee(F.position?.z,0),ee(F.quaternion?.x,0),ee(F.quaternion?.y,0),ee(F.quaternion?.z,0),ee(F.quaternion?.w,1),ee(F.scale?.x,1),ee(F.scale?.y,1),ee(F.scale?.z,1)]),K=f.map(()=>new Float32Array(m*3)),H=f.map(()=>new Float32Array(m*4)),Q=f.map(()=>new Float32Array(m*3));for(let F=0;F<m;F++){let G=F/(m-1)*g;A[F]=G;try{B(G)}catch{}for(let V=0;V<f.length;V++){let X=f[V];K[V][F*3]=ee(X.position?.x,0),K[V][F*3+1]=ee(X.position?.y,0),K[V][F*3+2]=ee(X.position?.z,0);let z=ee(X.quaternion?.x,0),I=ee(X.quaternion?.y,0),J=ee(X.quaternion?.z,0),Y=ee(X.quaternion?.w,1),ae=Math.hypot(z,I,J,Y)||1;if(z/=ae,I/=ae,J/=ae,Y/=ae,F>0){let Z=(F-1)*4,te=H[V];te[Z]*z+te[Z+1]*I+te[Z+2]*J+te[Z+3]*Y<0&&(z=-z,I=-I,J=-J,Y=-Y)}H[V][F*4]=z,H[V][F*4+1]=I,H[V][F*4+2]=J,H[V][F*4+3]=Y,Q[V][F*3]=ee(X.scale?.x,1),Q[V][F*3+1]=ee(X.scale?.y,1),Q[V][F*3+2]=ee(X.scale?.z,1)}}for(let F=0;F<f.length;F++){let G=f[F],V=q[F];G.position?.set(V[0],V[1],V[2]),G.quaternion?.set(V[3],V[4],V[5],V[6]),G.scale?.set(V[7],V[8],V[9])}e.updateMatrixWorld(!0);let C=null,U=()=>(C===null&&(C=l(A,"SCALAR",0,5126,m,[0],[g])),C),k=[],j=[];for(let F=0;F<f.length;F++){let G=q[F],V=(z,I,J)=>z.some((Y,ae)=>Math.abs(Y-G[J+ae%I])>1e-4),X=(z,I,J,Y)=>{z&&j.push({sampler:k.push({input:U(),interpolation:"LINEAR",output:l(I,J,0,5126,m)})-1,target:{node:F,path:Y}})};X(V(K[F],3,0),K[F],"VEC3","translation"),X(V(H[F],4,3),H[F],"VEC4","rotation"),X(V(Q[F],3,7),Q[F],"VEC3","scale")}j.length>0&&E.push({name:"ProceduralLoop",samplers:k,channels:j})}let N=St(o,u,e.userData),R=[],L=[],M=[];for(let g=0;g<o.length;g++){let _=o[g],m=ut(_.extras?.xr);if(!m)continue;let{ae:A,src:q,preset:K,volume:H,loop:Q,isGlobal:C}=m,U=_.name||`Node_${g}`,k=L.length;L.push({name:`${U}_source`,gain:H,loop:Q,autoPlay:typeof A.autoplay=="boolean"?A.autoplay:!0,...q!==void 0?{audio:R.push({uri:q})-1}:{},...K?{extras:{preset:K,pitch:ve(A.pitch,.25,4,1)}}:{}});let j=M.length,F=ve(A.refDistance,.05,100,1),G=ve(A.coneInnerAngle,0,360,360),V=ve(A.coneOuterAngle,G,360,360);M.push({name:`${U}_emitter`,type:C?"global":"positional",gain:H,sources:[k],...C?{}:{positional:{distanceModel:A.distanceModel==="linear"||A.distanceModel==="exponential"?A.distanceModel:"inverse",refDistance:F,maxDistance:ve(A.maxDistance,F,500,Math.max(F,25)),rolloffFactor:ve(A.rolloffFactor,0,10,1),coneInnerAngle:+(G*Math.PI/180).toFixed(6),coneOuterAngle:+(V*Math.PI/180).toFixed(6),coneOuterGain:ve(A.coneOuterGain,0,1,0)}}}),_.extensions={..._.extensions||{},KHR_audio_emitter:{emitter:j}},d.add("KHR_audio_emitter")}let n={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:e.environmentIntensity}},scenes:[{nodes:b}],scene:0,nodes:o,meshes:u,materials:p,...D.length>0?{images:D}:{},...S.length>0?{samplers:S}:{},...h.length>0?{textures:h}:{},accessors:s,bufferViews:a,buffers:[{byteLength:r}],...E.length>0?{animations:E}:{},...N||d.size>0?{extensionsUsed:[...N?["KHR_interactivity"]:[],...d]}:{},...N||P.length>0||M.length>0?{extensions:{...N?{KHR_interactivity:N}:{},...P.length>0?{KHR_materials_variants:{variants:P.map(g=>({name:g}))}}:{},...M.length>0?{KHR_audio_emitter:{...R.length>0?{audio:R}:{},sources:L,emitters:M}}:{}}}:{}},$=new Uint8Array(r),W=0;for(let g of i)$.set(g,W),W+=g.byteLength;return[{gltf:n,bin:$.buffer,lights:T,environmentIntensity:e.environmentIntensity},f]}function ct(e){return new TextEncoder().encode(e)}function qt(e,t){let[i,r]=jt(e,t);return $e(i,r)}function $e(e,t){let i=[],r=e.gltf,a=pe().decoders.get("meshopt");a&&typeof a.decodeBufferViews=="function"&&a.decodeBufferViews(r,e);let s=e.bin,u=s instanceof ArrayBuffer?s:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),o=r.accessors||[],d=r.bufferViews||[],f=r.materials||[],p=r.meshes||[],y=r.nodes||[],D=new Set,S=f.map((P,T)=>lt(D,Ce(P?.name,`Material_${T}`)));function h(P){let T=o[P];if(!T)throw new Error(`Accessor ${P} not found`);let x=d[T.bufferView||0],c=(x.byteOffset||0)+(T.byteOffset||0),l=x.byteLength||0;return{acc:T,buffer:u.slice(c,c+l)}}function v(P,T,x,c){let l=[],b=p[P];if(!b)return l;let w=b.primitives||[];for(let O=0;O<w.length;O++){let B=w[O],E=B.attributes?.POSITION;if(E===void 0)continue;let{acc:N,buffer:R}=h(E),L=new Float32Array(R,0,N.count*3),M,n=B.attributes?.NORMAL;if(n!==void 0){let{acc:k,buffer:j}=h(n),F=new Float32Array(j,0,k.count*3);M=new Float32Array(F.length);for(let G=0;G<k.count;G++){let V=F[G*3],X=F[G*3+1],z=F[G*3+2],I=Math.hypot(V,X,z)||1;M[G*3]=V/I,M[G*3+1]=X/I,M[G*3+2]=z/I}}let $,W=B.attributes?.TEXCOORD_0;if(W!==void 0){let{acc:k,buffer:j}=h(W);$=new Float32Array(j,0,k.count*2)}let g;if(B.indices!==void 0){let{acc:k,buffer:j}=h(B.indices);g=k.componentType===5125?new Uint32Array(j,0,k.count):new Uint16Array(j,0,k.count);let F=N.count;for(let G of g)if(G>=F)throw new Error(`SecurityError: Index buffer value (${G}) out of vertex bounds [0, ${F}).`)}else{let k=N.count;g=k>65535?new Uint32Array(k):new Uint16Array(k);for(let j=0;j<k;j++)g[j]=j}let _="DefaultMaterial",m=[.8,.8,.8],A=.5,q=0,K=0,H=0,Q=1.5,C=1,U=[0,0,0];if(B.material!==void 0&&f[B.material]){let k=f[B.material];_=S[B.material]||`Material_${B.material}`;let j=k.pbrMetallicRoughness||{},F=(z,I)=>Array.isArray(z)&&z.length>=3?[z[0],z[1],z[2]]:I;m=F(j.baseColorFactor,[1,1,1]);let G=k.extras?.avgColor;Array.isArray(G)&&G.length>=3&&(m=[m[0]*G[0],m[1]*G[1],m[2]*G[2]]);let V=Array.isArray(j.baseColorFactor)&&typeof j.baseColorFactor[3]=="number"?j.baseColorFactor[3]:1;typeof j.roughnessFactor=="number"&&(A=j.roughnessFactor),typeof j.metallicFactor=="number"&&(q=j.metallicFactor),U=F(k.emissiveFactor,[0,0,0]);let X=k.extensions||{};X.KHR_materials_clearcoat&&(K=X.KHR_materials_clearcoat.clearcoatFactor??0,H=X.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),typeof X.KHR_materials_ior?.ior=="number"&&(Q=X.KHR_materials_ior.ior),C=V*(1-(X.KHR_materials_transmission?.transmissionFactor??0))}l.push({name:w.length>1?`${T}_p${O}`:T,positions:L,indices:g,normals:M,uvs:$,materialName:_,color:m,roughness:A,metallic:q,clearcoat:K,clearcoatRoughness:H,ior:Q,opacity:C,emissiveColor:U,xrTraits:x||b.extras?.xr,...c?{invisible:!0}:{}})}return l}if(y.length>0){let P=new Float32Array(0),T=new Uint16Array(0),x=(L,M)=>{if(L===void 0)return null;let{acc:n,buffer:$}=h(L);return new Float32Array($,0,n.count*M)},c=(L,M)=>Array.isArray(L)&&L.length>=3?[ee(L[0],M),ee(L[1],M),ee(L[2],M)]:[M,M,M],l=(L,M,n)=>L&&L.length>=(M+1)*3?[L[M*3],L[M*3+1],L[M*3+2]]:n,b=(L,M,n)=>L&&L.length>=(M+1)*4?[L[M*4],L[M*4+1],L[M*4+2],L[M*4+3]]:n,w=new Map,O=r.animations?.[0];if(O&&Array.isArray(O.channels)&&Array.isArray(O.samplers))for(let L of O.channels){let M=O.samplers[L?.sampler],n=L?.target?.node,$=L?.target?.path;if(!M||typeof n!="number"||M.input===void 0)continue;let W=w.get(n);W||(W={input:M.input},w.set(n,W)),$==="translation"?W.t=M.output:$==="rotation"?W.r=M.output:$==="scale"&&(W.s=M.output)}let B=r.scenes?.[r.scene??0]?.nodes??[];if(!Array.isArray(B)||B.length===0){let L=new Set;for(let M of y)if(Array.isArray(M?.children))for(let n of M.children)L.add(n);B=[];for(let M=0;M<y.length;M++)L.has(M)||B.push(M);B.length===0&&(B=[0])}let E=new Set,N=[],R=(L,M)=>{if(Array.isArray(L))for(let n=L.length-1;n>=0;n--)N.push({idx:L[n],out:M})};for(R(B,i);N.length>0;){let{idx:L,out:M}=N.pop();if(typeof L!="number"||L<0||L>=y.length||E.has(L))continue;E.add(L);let n=y[L];if(!n)continue;let $=[0,0,0],W=[0,0,0,1],g=[1,1,1];if(Array.isArray(n.matrix)&&n.matrix.length===16){let C=ht(n.matrix);$=C.t,W=C.r,g=C.s}else $=c(n.translation,0),Array.isArray(n.rotation)&&n.rotation.length>=4&&(W=[ee(n.rotation[0],0),ee(n.rotation[1],0),ee(n.rotation[2],0),ee(n.rotation[3],1)]),g=c(n.scale,1);let _,m=w.get(L);if(m){let C=x(m.input,1);if(C&&C.length>0){let U=x(m.t,3),k=x(m.r,4),j=x(m.s,3),F=Array.from(C),G=[],V=[],X=[];for(let z=0;z<C.length;z++)G.push(l(U,z,$)),V.push(b(k,z,W)),X.push(l(j,z,g));_={times:F,translations:G,rotations:V,scales:X}}}let A=Array.isArray(n.children)?n.children:[],q=typeof n.mesh=="number"&&n.mesh>=0&&n.mesh<p.length,K=t?.[L]?.userData?.xr??n.extras?.xr;if(!q&&A.length===0&&(n.camera!==void 0||n.extensions?.KHR_lights_punctual||!n.name&&!n.extras&&!K&&!_))continue;let H=(C,U,k)=>({name:C,positions:P,indices:T,isXform:!0,xrTraits:K,timeSamples:_,translation:$,rotation:W,scale:g,children:U,...k?{invisible:!0}:{}}),Q=n.visible===!1||n.extensions?.KHR_node_visibility?.visible===!1||t?.[L]?.visible===!1;if(q){let C=n.name||p[n.mesh]?.name||`Mesh_${L}`,U=v(n.mesh,C,K,Q),k=n.extensions?.EXT_mesh_gpu_instancing?.attributes;if(k&&typeof k=="object"&&U.length>0){let j=x(k.TRANSLATION,3),F=x(k.ROTATION,4),G=x(k.SCALE,3),V=x(k._COLOR_0,3),X=Math.min(1e3,j?j.length/3:F?F.length/4:G?G.length/3:0);if(X>0){let z=[];for(let I=0;I<X;I++){let J=l(j,I,[0,0,0]),Y=b(F,I,[0,0,0,1]),ae=l(G,I,[1,1,1]);for(let Z of U){let te=Z.color||[.8,.8,.8],ie=V&&V.length>=(I+1)*3;z.push({...Z,name:`${Z.name}_${I}`,materialName:ie?`${Z.materialName}_inst_${I}`:Z.materialName,color:ie?[te[0]*V[I*3],te[1]*V[I*3+1],te[2]*V[I*3+2]]:Z.color,translation:J,rotation:Y,scale:ae})}}R(A,z),M.push(H(C,z,Q));continue}}if(U.length===1)U[0].translation=$,U[0].rotation=W,U[0].scale=g,U[0].timeSamples=_,A.length>0&&(U[0].children=[],R(A,U[0].children)),M.push(U[0]);else{let j=[...U];R(A,j),M.push(H(C,j,Q))}}else{let C=[];R(A,C),M.push(H(n.name||`Group_${L}`,C,Q))}}}else for(let P=0;P<p.length;P++){let T=p[P].name||`Mesh_${P}`;i.push(...v(P,T,p[P].extras?.xr))}return i}function Ce(e,t){if(!e||typeof e!="string")return t;let i=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(i)&&(i="_"+i),i||t}function Ue(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function ue(e){if(!Number.isFinite(e)||Math.abs(e)<1e-7)return"0";let t=Number(e.toFixed(5)).toString();return t.indexOf(".")===-1?`${t}.0`:t}var ge=(e,t,i)=>`(${ue(e)}, ${ue(t)}, ${ue(i)})`,mt=(e,t,i,r)=>`(${ue(e)}, ${ue(t)}, ${ue(i)}, ${ue(r)})`;function ft(e){let t=e.length/3,i=new Array(t);for(let r=0;r<t;r++)i[r]=ge(e[r*3],e[r*3+1],e[r*3+2]);return i.join(", ")}function Gt(e,t){let i=new Array(t);for(let r=0;r<t;r++)i[r]=`(${ue(e[r*2])}, ${ue(1-e[r*2+1])})`;return i.join(", ")}function Kt(e){return Array.from(e).join(", ")}function Be(e){let t=new Map,i=0,r=null,a=[...e];for(;a.length>0;){let h=a.pop();if(!h.isXform&&h.positions&&h.positions.length>0){let v=Ce(h.materialName,"DefaultMaterial");t.has(v)||t.set(v,{color:h.color||[.8,.8,.8],roughness:h.roughness??.5,metallic:h.metallic??0,clearcoat:h.clearcoat??0,clearcoatRoughness:h.clearcoatRoughness??0,ior:h.ior??1.5,opacity:h.opacity??1,emissiveColor:h.emissiveColor||[0,0,0]})}if(h.timeSamples&&h.timeSamples.times.length>0){let v=h.timeSamples.times[h.timeSamples.times.length-1];v>i&&(i=v)}if(h.xrTraits?.anchor&&!r&&(r=h.xrTraits.anchor==="vertical"||h.xrTraits.anchor==="wall"?"vertical":"horizontal"),h.children)for(let v=h.children.length-1;v>=0;v--)a.push(h.children[v])}let s="";i>0&&(s=`startTimeCode = 0
250
+ endTimeCode = ${ue(i)}
254
251
  timeCodesPerSecond = 1.0
255
- `);let s="";r&&(s=`uniform token preliminary:anchoring:type = "plane"
252
+ `);let u="";r&&(u=`uniform token preliminary:anchoring:type = "plane"
256
253
  uniform token preliminary:planeAnchoring:alignment = "${r}"
257
- `);let a=`#usda 1.0
254
+ `);let o=`#usda 1.0
258
255
  (
259
256
  defaultPrim = "Root"
260
257
  metersPerUnit = 1.0
261
258
  upAxis = "Y"
262
- ${i})
259
+ ${s})
263
260
 
264
261
  def Xform "Root" (
265
262
  kind = "component"
266
263
  )
267
264
  {
268
- ${s}def Scope "Materials"
265
+ ${u}def Scope "Materials"
269
266
  {
270
- `;for(let[o,l]of e.entries()){let[u,d,f]=l.color,[T,g,m]=l.emissiveColor,p="";l.clearcoat>0&&(p+=`float inputs:clearcoat = ${X(l.clearcoat)}
271
- `,p+=`float inputs:clearcoatRoughness = ${X(l.clearcoatRoughness)}
272
- `),l.ior!==1.5&&(p+=`float inputs:ior = ${X(l.ior)}
273
- `),l.opacity<1&&(p+=`float inputs:opacity = ${X(l.opacity)}
274
- `),(T>0||g>0||m>0)&&(p+=`color3f inputs:emissiveColor = (${X(T)}, ${X(g)}, ${X(m)})
275
- `),a+=`def Material "${o}"
267
+ `;for(let[h,v]of t.entries()){let[P,T,x]=v.color,[c,l,b]=v.emissiveColor,w="";v.clearcoat>0&&(w+=`float inputs:clearcoat = ${ue(v.clearcoat)}
268
+ `,w+=`float inputs:clearcoatRoughness = ${ue(v.clearcoatRoughness)}
269
+ `),v.ior!==1.5&&(w+=`float inputs:ior = ${ue(v.ior)}
270
+ `),v.opacity<1&&(w+=`float inputs:opacity = ${ue(v.opacity)}
271
+ `),(c>0||l>0||b>0)&&(w+=`color3f inputs:emissiveColor = ${ge(c,l,b)}
272
+ `),o+=`def Material "${h}"
276
273
  {
277
274
  def Shader "PBRShader"
278
275
  {
279
276
  uniform token info:id = "UsdPreviewSurface"
280
- color3f inputs:diffuseColor = (${X(u)}, ${X(d)}, ${X(f)})
281
- float inputs:metallic = ${X(l.metallic)}
282
- float inputs:roughness = ${X(l.roughness)}
283
- ${p}token outputs:surface
277
+ color3f inputs:diffuseColor = ${ge(P,T,x)}
278
+ float inputs:metallic = ${ue(v.metallic)}
279
+ float inputs:roughness = ${ue(v.roughness)}
280
+ ${w}token outputs:surface
284
281
  }
285
- token outputs:surface.connect = </Root/Materials/${o}/PBRShader.outputs:surface>
282
+ token outputs:surface.connect = </Root/Materials/${h}/PBRShader.outputs:surface>
286
283
  }
287
- `}a+=`}
284
+ `}o+=`}
288
285
  def Scope "Meshes"
289
286
  {
290
- `;let c=new Set;for(let o=0;o<n.length;o++){let l=n[o],u=l.positions.length/3,d=1/0,f=1/0,T=1/0,g=-1/0,m=-1/0,p=-1/0;for(let E=0;E<u;E++){let b=l.positions[E*3],F=l.positions[E*3+1],L=l.positions[E*3+2];b<d&&(d=b),b>g&&(g=b),F<f&&(f=F),F>m&&(m=F),L<T&&(T=L),L>p&&(p=L)}isFinite(d)||(d=f=T=-1,g=m=p=1);let R=Math.floor(l.indices.length/3),A=Ue(l.materialName,"DefaultMaterial"),v=Ue(l.name,`Mesh_${o}`);c.has(v)&&(v=`${v}_${o}`),c.add(v);let D=R>0?R===1?"3":"3, ".repeat(R-1)+"3":"",y=l.xrTraits,P="";if(y){let E=[];y.physics&&y.physics!=="none"&&E.push('prepend apiSchemas = ["PhysicsBodyAPI", "PhysicsCollisionAPI"]');let b=he().xrTraitSerializer?.usdLines(y,rt)??[];if(!b.length)for(let F of["grab","billboard","follow","anchor","physics"]){let L=F==="follow"&&typeof y.follow=="object"?y.follow.mode??"head":y[F];L!==void 0&&b.push(`string ${F} = "${rt(L)}"`)}b.length>0&&E.push(`customData = {
287
+ `;let d=(h,v,P)=>{let T=[];v&&T.push('"MaterialBindingAPI"');let x=!!(h?.rigidBody&&h.rigidBody!=="none"&&(typeof h.rigidBody!="object"||h.rigidBody.enabled!==!1)),c=!!(h?.physics&&h.physics!=="none"||x);c&&T.push(...x?['"PhysicsBodyAPI"','"PhysicsRigidBodyAPI"','"PhysicsCollisionAPI"','"PhysicsMassAPI"']:['"PhysicsBodyAPI"','"PhysicsCollisionAPI"']);let l=[];if(T.length>0&&l.push(`prepend apiSchemas = [${T.join(", ")}]`),h){let E=pe().xrTraitSerializer?.usdLines(h,Ue)??[];if(!E.length)for(let N of["grab","billboard","follow","anchor","physics"]){let R=N==="follow"&&typeof h.follow=="object"?h.follow.mode??"head":h[N];R!==void 0&&E.push(`string ${N} = "${Ue(R)}"`)}E.length>0&&l.push(`customData = {
291
288
  dictionary xr = {
292
- ${b.join(`
289
+ ${E.join(`
293
290
  `)}
294
291
  }
295
- }`),E.length>0&&(P=` (
296
- ${E.join(`
292
+ }`)}let b=l.length>0?` (
293
+ ${l.join(`
297
294
  `)}
298
- )`)}if(a+=`def Mesh "${v}"${P}
299
- {
300
- `,y?.physics&&y.physics!=="none"){let E=y.physics==="static"?"true":"false";a+=`bool physics:rigidBodyEnabled = true
301
- bool physics:kinematicEnabled = ${E}
295
+ )`:"",w=P?`uniform token visibility = "invisible"
296
+ `:"";if(c){let E=h?.rigidBody??h?.physics,N=E?.body??E?.mode??E;w+=`bool physics:rigidBodyEnabled = true
297
+ bool physics:kinematicEnabled = ${N==="static"||N==="kinematic"}
302
298
  bool physics:collisionEnabled = true
303
- `}if(l.timeSamples&&l.timeSamples.times.length>0){let E=l.timeSamples,b=E.times.map((C,h)=>{let w=E.translations?.[h]||[0,0,0];return`${X(C)}: (${X(w[0])}, ${X(w[1])}, ${X(w[2])})`}).join(", "),F=E.times.map((C,h)=>{let w=E.rotations?.[h]||[0,0,0,1];return`${X(C)}: (${X(w[3])}, ${X(w[0])}, ${X(w[1])}, ${X(w[2])})`}).join(", "),L=E.times.map((C,h)=>{let w=E.scales?.[h]||[1,1,1];return`${X(C)}: (${X(w[0])}, ${X(w[1])}, ${X(w[2])})`}).join(", ");a+=`double3 xformOp:translate.timeSamples = { ${b} }
304
- quatf xformOp:orient.timeSamples = { ${F} }
305
- double3 xformOp:scale.timeSamples = { ${L} }
299
+ `,E?.mass>0&&Number.isFinite(E.mass)&&(w+=`float physics:mass = ${ue(E.mass)}
300
+ `)}let O=ut(h),B=O?`def SpatialAudio "AudioEmitter"
301
+ {
302
+ ${O.src?`asset inputs:file = @${Ue(O.src)}@
303
+ `:""}uniform token inputs:auralMode = "${O.isGlobal?"nonSpatial":"spatial"}"
304
+ uniform token inputs:playbackMode = "${O.loop?"loopFromStart":"onceFromStart"}"
305
+ double gain = ${ue(O.volume)}
306
+ }
307
+ `:"";return{header:b,body:w,tail:B}},f=h=>{if(h.timeSamples&&h.timeSamples.times.length>0){let l=h.timeSamples,b=(E,N,R)=>l.times.map((L,M)=>`${ue(L)}: ${R(E?.[M]||N)}`).join(", "),w=b(l.translations,[0,0,0],E=>ge(E[0],E[1],E[2])),O=b(l.rotations,[0,0,0,1],E=>{let N=Math.hypot(E[0],E[1],E[2],E[3])||1;return mt(E[3]/N,E[0]/N,E[1]/N,E[2]/N)}),B=b(l.scales,[1,1,1],E=>ge(E[0],E[1],E[2]));return`double3 xformOp:translate.timeSamples = { ${w} }
308
+ quatf xformOp:orient.timeSamples = { ${O} }
309
+ double3 xformOp:scale.timeSamples = { ${B} }
306
310
  uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:orient", "xformOp:scale"]
307
- `}a+=`float3[] extent = [(${X(d)}, ${X(f)}, ${X(T)}), (${X(g)}, ${X(m)}, ${X(p)})]
308
- int[] faceVertexCounts = [${D}]
309
- int[] faceVertexIndices = [${Ft(l.indices)}]
310
- point3f[] points = [${it(l.positions)}]
311
- `,l.normals&&l.normals.length===l.positions.length&&(a+=`normal3f[] normals = [${it(l.normals)}] (
311
+ `}let v=[],P="",T=h.translation;T&&(Math.abs(T[0])>1e-7||Math.abs(T[1])>1e-7||Math.abs(T[2])>1e-7)&&(P+=`double3 xformOp:translate = ${ge(T[0],T[1],T[2])}
312
+ `,v.push('"xformOp:translate"'));let x=h.rotation;if(x){let l=Math.hypot(x[0],x[1],x[2],x[3])||1,b=x[0]/l,w=x[1]/l,O=x[2]/l,B=x[3]/l;(1-Math.abs(B)>1e-7||Math.hypot(b,w,O)>1e-7)&&(P+=`quatf xformOp:orient = ${mt(B,b,w,O)}
313
+ `,v.push('"xformOp:orient"'))}let c=h.scale;return c&&(Math.abs(c[0]-1)>1e-7||Math.abs(c[1]-1)>1e-7||Math.abs(c[2]-1)>1e-7)&&(P+=`float3 xformOp:scale = ${ge(c[0],c[1],c[2])}
314
+ `,v.push('"xformOp:scale"')),v.length>0&&(P+=`uniform token[] xformOpOrder = [${v.join(", ")}]
315
+ `),P},p=h=>{let v=h.positions.length/3,P=1/0,T=1/0,x=1/0,c=-1/0,l=-1/0,b=-1/0;for(let N=0;N<v;N++){let R=h.positions[N*3],L=h.positions[N*3+1],M=h.positions[N*3+2];R<P&&(P=R),R>c&&(c=R),L<T&&(T=L),L>l&&(l=L),M<x&&(x=M),M>b&&(b=M)}isFinite(P)||(P=T=x=-1,c=l=b=1);let w=Math.floor(h.indices.length/3),O=Ce(h.materialName,"DefaultMaterial"),B=w>0?w===1?"3":"3, ".repeat(w-1)+"3":"",E=`float3[] extent = [${ge(P,T,x)}, ${ge(c,l,b)}]
316
+ int[] faceVertexCounts = [${B}]
317
+ int[] faceVertexIndices = [${Kt(h.indices)}]
318
+ point3f[] points = [${ft(h.positions)}]
319
+ `;return h.normals&&h.normals.length===h.positions.length&&(E+=`normal3f[] normals = [${ft(h.normals)}] (
312
320
  interpolation = "vertex"
313
321
  )
314
- `),l.uvs&&l.uvs.length===u*2&&(a+=`texCoord2f[] primvars:st = [${Dt(l.uvs,u)}] (
322
+ `),h.uvs&&h.uvs.length===v*2&&(E+=`texCoord2f[] primvars:st = [${Gt(h.uvs,v)}] (
315
323
  interpolation = "vertex"
316
324
  )
317
- `),a+=`rel material:binding = </Root/Materials/${A}>
318
- }
319
- `}return a+=`}
325
+ `),E+=`rel material:binding = </Root/Materials/${O}>
326
+ `,E},y=new Set,D=[];for(let h=e.length-1;h>=0;h--)D.push({node:e[h],siblings:y});let S=0;for(;D.length>0;){let h=D.pop();if(h.close){o+=`}
327
+ `;continue}let{node:v,siblings:P}=h,T=!!(v.isXform||v.positions.length===0),x=lt(P,Ce(v.name,T?`Group_${S}`:`Mesh_${S}`));S++;let c=v.children||[];if(T){let l=d(v.xrTraits,!1,v.invisible);o+=`def Xform "${x}"${l.header}
328
+ {
329
+ ${l.body}${f(v)}${l.tail}`,D.push({close:!0});let b=new Set;for(let w=c.length-1;w>=0;w--)D.push({node:c[w],siblings:b})}else if(c.length>0){let l=d(v.xrTraits,!1,v.invisible),b=`${x}_mesh`;o+=`def Xform "${x}"${l.header}
330
+ {
331
+ ${l.body}${f(v)}${l.tail}`,o+=`def Mesh "${b}" (
332
+ prepend apiSchemas = ["MaterialBindingAPI"]
333
+ )
334
+ {
335
+ ${p(v)}}
336
+ `,D.push({close:!0});let w=new Set([b]);for(let O=c.length-1;O>=0;O--)D.push({node:c[O],siblings:w})}else{let l=d(v.xrTraits,!0,v.invisible);o+=`def Mesh "${x}"${l.header}
337
+ {
338
+ ${l.body}${f(v)}${p(v)}${l.tail}}
339
+ `}}return o+=`}
320
340
  }
321
- `,a}function at(n,e){if(n&&typeof n.traverse=="function"){let i=Pt(n,e);return ke(i)}let t=xe(n),r=st(t);return ke(r)}var Le=null;function ot(n){if(!Le){Le=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let i=0;i<8;i++)r=r&1?3988292384^r>>>1:r>>>1;Le[t]=r}}let e=4294967295;for(let t=0;t<n.length;t++)e=Le[(e^n[t])&255]^e>>>8;return(e^4294967295)>>>0}function Ve(n){let e=[],t=0,r=[];for(let u of n){let d=Be(u.filename),f=ot(u.data),T=u.data.length,g=30+d.length,m=t+g,p=0,R=m%64;R!==0&&(p=64-R);let A=new Uint8Array(g+p),v=new DataView(A.buffer);v.setUint32(0,67324752,!0),v.setUint16(4,20,!0),v.setUint16(6,0,!0),v.setUint16(8,0,!0),v.setUint16(10,0,!0),v.setUint16(12,0,!0),v.setUint32(14,f,!0),v.setUint32(18,T,!0),v.setUint32(22,T,!0),v.setUint16(26,d.length,!0),v.setUint16(28,p,!0),A.set(d,30),p>0&&A.fill(0,30+d.length),e.push({offset:t,size:T,crc:f,filenameBytes:d,entry:u}),r.push(A),r.push(u.data),t+=A.length+u.data.length}let i=t;for(let u of e){let d=new Uint8Array(46+u.filenameBytes.length),f=new DataView(d.buffer);f.setUint32(0,33639248,!0),f.setUint16(4,20,!0),f.setUint16(6,20,!0),f.setUint16(8,0,!0),f.setUint16(10,0,!0),f.setUint16(12,0,!0),f.setUint16(14,0,!0),f.setUint32(16,u.crc,!0),f.setUint32(20,u.size,!0),f.setUint32(24,u.size,!0),f.setUint16(28,u.filenameBytes.length,!0),f.setUint16(30,0,!0),f.setUint16(32,0,!0),f.setUint16(34,0,!0),f.setUint16(36,0,!0),f.setUint32(38,0,!0),f.setUint32(42,u.offset,!0),d.set(u.filenameBytes,46),r.push(d),t+=d.length}let s=t-i,a=new Uint8Array(22),c=new DataView(a.buffer);c.setUint32(0,101010256,!0),c.setUint16(4,0,!0),c.setUint16(6,0,!0),c.setUint16(8,e.length,!0),c.setUint16(10,e.length,!0),c.setUint32(12,s,!0),c.setUint32(16,i,!0),c.setUint16(20,0,!0),r.push(a),t+=22;let o=new Uint8Array(t),l=0;for(let u of r)o.set(u,l),l+=u.length;return o}function Ct(n){let e=at(n),t=Be(e);return Ve([{filename:"model.usda",data:t}])}function ct(n){let e=xe(n),t=st(e),r=ke(t),i=Be(r);return Ve([{filename:"model.usda",data:i}])}function ut(n){return n&&typeof n.toUSDZ=="function"?n.toUSDZ():n&&typeof n.traverse=="function"?Ct(n):ct(n)}function lt(n){let e=ut(n);return new Blob([e],{type:"model/vnd.usdz+zip"})}function ft(){if(typeof window>"u"||typeof navigator>"u")return!1;let n=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(n)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))return!1;let t=document.createElement("a");return t.relList!==void 0&&t.relList.supports!==void 0&&t.relList.supports("ar")}function dt(){if(typeof navigator>"u")return!1;let n=navigator.userAgent||"";return/android/i.test(n)}async function pt(){if(typeof navigator>"u")return!1;let n=navigator;if(!n.xr||typeof n.xr.isSessionSupported!="function")return!1;try{return await n.xr.isSessionSupported("immersive-ar")?!0:await n.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function en(){let n=[];return await pt()&&n.push("webxr"),ft()&&n.push("quick-look"),dt()&&n.push("scene-viewer"),n}async function tn(){return(await bt()).bestMode}async function bt(){let[n,e,t]=await Promise.all([pt(),Promise.resolve(ft()),Promise.resolve(dt())]),r=[];e&&r.push("quick-look"),n&&r.push("webxr"),t&&r.push("scene-viewer");let i=null;return e?i="quick-look":n?i="webxr":t&&(i="scene-viewer"),{webxr:n,quickLook:e,sceneViewer:t,availableModes:r,bestMode:i}}function mt(n,e={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let t,r=!1;if(typeof n=="string"){if(t=_t(n),!t)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else t=URL.createObjectURL(n),r=!0;let i=[];if(e.allowScale===!1&&i.push("allowsContentScaling=0"),e.canonicalWebPageUrl){let c=Se(e.canonicalWebPageUrl,!1);c&&i.push(`canonicalWebPageURL=${encodeURIComponent(c)}`)}e.checkoutTitle&&i.push(`checkoutTitle=${encodeURIComponent(e.checkoutTitle)}`),e.checkoutSubtitle&&i.push(`checkoutSubtitle=${encodeURIComponent(e.checkoutSubtitle)}`),e.price&&i.push(`price=${encodeURIComponent(e.price)}`),i.length>0&&(t+=`#${i.join("&")}`);let s=document.createElement("a");s.setAttribute("rel","ar"),s.setAttribute("href",t);let a=document.createElement("img");a.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),a.style.display="none",s.appendChild(a),document.body.appendChild(s),s.click(),setTimeout(()=>{document.body.removeChild(s),r&&URL.revokeObjectURL(t.split("#")[0])},3e3)}function Se(n,e=!1){if(typeof n!="string")return"";let t=n.replace(/[\x00-\x1f\x7f]+/g,"").trim();if(!t)return"";if(/^[\\/]{2}/.test(t))throw new Error(`[XR-Live Security] Rejected protocol-relative URL in Scene Viewer intent: ${t.slice(0,32)}`);let r=t.toLowerCase();if(r.startsWith("https://")||r.startsWith("http://")||e&&r.startsWith("blob:")||!/^[a-z][a-z0-9+.-]*:/i.test(t))return t;throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Scene Viewer intent: ${t.slice(0,32)}`)}function _t(n){try{return Se(n,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(n||"").trim().slice(0,32)}`)}}function Nt(n,e={}){let t=Se(n,!0),r=e.mode||"ar_preferred",i=new URLSearchParams({file:t,mode:r,resizable:e.resizable!==!1?"true":"false",enable_vertical_placement:e.enableVerticalPlacement?"true":"false"});return e.title&&i.set("title",e.title),e.link&&i.set("link",Se(e.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${i.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function Ut(n,e={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let t=Nt(n,e);window.location.href=t}var de=null;function kt(n,e){let r=new Float32Array(144),i=new Float32Array(144),s=new Float32Array(96),a=new Uint16Array(144);for(let d=0;d<24;d++){let f=d/24*Math.PI*2,T=Math.cos(f),g=Math.sin(f),m=d*2,p=m+1,R=(d+1)%24*2;r[m*3]=T*.11,r[m*3+1]=.002,r[m*3+2]=g*.11,r[p*3]=T*.145,r[p*3+1]=.002,r[p*3+2]=g*.145,i[m*3+1]=i[p*3+1]=1,a.set([m,R,p,p,R,R+1],d*6)}let c=n.createVertexArray();n.bindVertexArray(c);let o=(d,f,T)=>{let g=n.createBuffer();return n.bindBuffer(34962,g),n.bufferData(34962,d,35044),n.enableVertexAttribArray(f),n.vertexAttribPointer(f,T,5126,!1,0,0),g},l=[o(r,0,3),o(i,1,3),o(s,2,2)],u=n.createBuffer();return l.push(u),n.bindBuffer(34963,u),n.bufferData(34963,a,35044),n.bindVertexArray(null),{name:"__xr_reticle__",nodeIndex:-1,worldSpace:!0,visible:!1,transform:new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),normalMatrix:new Float32Array([1,0,0,0,1,0,0,0,1]),primitives:[{vao:c,indexCount:a.length,indexType:5123,baseColor:e&&e.length>=3?[e[0],e[1],e[2],e[3]??.95]:[.22,.74,.97,.95],metallic:0,roughness:.2,positions:r,indices:a,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:l}]}}function ht(n,e,t,r,i){let s=Math.cos(r),a=Math.sin(r),c=Math.max(.01,i);n.fill(0),n[0]=c*s,n[2]=-c*a,n[5]=c,n[8]=c*a,n[10]=c*s,n[12]=e[0]-c*(s*t[0]+a*t[2]),n[13]=e[1]-c*t[1],n[14]=e[2]-c*(-a*t[0]+s*t[2]),n[15]=1}var Oe=class{constructor(e={}){this.s=null;this.placed=!1;this.placedMat=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);this.cleanFn=null;this.opts=e}isSessionActive(){return this.s!==null}hasPlacedModel(){return this.placed}getPlacedMatrix(){return this.placedMat}async start(e,t){if(typeof navigator>"u"||!navigator.xr)throw new Error("WebXR is not supported on this browser.");de&&de!==this&&de.isSessionActive()&&await de.stop().catch(()=>{});let r=navigator.xr,i=this.opts,s=t||e?.container,a=String(s?.tagName||"").toLowerCase()==="xr-live",c=e?.bounds,o=Number(c?.radius)||1,l=Array.isArray(c?.center)?c.center:[0,0,0],u=Array.isArray(c?.min)?c.min:[-.5,-.5,-.5],d=typeof navigator<"u"&&navigator.userAgent||"",f=/Android|iPhone|iPad|iPod/i.test(d)&&!/Quest|Oculus|Pico|Vision/i.test(d),T=a?i.arScale==="fixed"?1:f?.55:1:i.arScale==="fixed"?1:o>.45?.3/o:o<.05?.12/Math.max(o,.001):1,g=a?[0,-.25,0]:[l[0]||0,i.arPlacement==="wall"?l[1]:u[1]??0,l[2]||0],m="immersive-ar";try{await r.isSessionSupported("immersive-ar")||(m="immersive-vr")}catch{m="immersive-vr"}let p=s?.querySelector?.('[slot="ar-overlay"]')||null,R=!1,A=null,v=()=>{R&&p?.parentNode&&p.parentNode.removeChild(p),p=null,A=null,R=!1};if(m==="immersive-ar"){if(p)p.addEventListener?.("beforexrselect",x=>x.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let x=document.createElement("div");x.style.cssText="position:fixed;inset:0;pointer-events:none;background:transparent!important;z-index:2147483647;font-family:system-ui,sans-serif;user-select:none";let I=document.createElement("button");I.type="button",I.textContent="\u2715 Exit AR",I.style.cssText="position:absolute;top:max(16px,env(safe-area-inset-top,16px));right:16px;pointer-events:auto;padding:8px 14px;border-radius:99px;border:1px solid rgba(255,255,255,.3);background:rgba(15,23,42,.8);color:#f8fafc;font:600 13px system-ui,sans-serif",I.addEventListener("beforexrselect",N=>N.preventDefault()),I.addEventListener("click",N=>{N.stopPropagation(),this.stop().catch(()=>{})}),A=document.createElement("div"),A.style.cssText="position:absolute;bottom:max(28px,env(safe-area-inset-bottom,28px));left:50%;transform:translateX(-50%);padding:8px 15px;border-radius:99px;border:1px solid rgba(56,189,248,.4);background:rgba(15,23,42,.82);color:#f8fafc;font:500 12.5px system-ui,sans-serif;text-align:center;max-width:88vw",A.textContent="Move phone to detect a surface \u2022 Tap to place",x.appendChild(I),x.appendChild(A),document.body.appendChild(x),p=x,R=!0}}let D=new Set(i.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),y={requiredFeatures:i.requiredFeatures?[...i.requiredFeatures]:[],optionalFeatures:Array.from(D)};p&&(D.add("dom-overlay"),y.optionalFeatures=Array.from(D),y.domOverlay={root:p});for(let x of ae)x.onConfigureXRSessionInit?.(s,y);Array.isArray(y.optionalFeatures)&&y.optionalFeatures.includes("dom-overlay")&&!y.domOverlay?.root&&(y.optionalFeatures=y.optionalFeatures.filter(x=>x!=="dom-overlay"));let P=x=>{let I=String(x?.name||"");return I==="NotAllowedError"||I==="SecurityError"};try{this.s=await r.requestSession(m,y)}catch(x){if(v(),P(x))throw i.onError?.(x),x;try{this.s=await r.requestSession(m,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(I){if(P(I))throw i.onError?.(I),I;try{this.s=await r.requestSession(m)}catch(N){throw i.onError?.(N),N}}}let E=this.s;de=this,this.placed=!1;let b=null,F=null,L=null,C=null,h=null,w=[0,-.25,-1.2],S=[0,-.25,-1.2],M=new Float32Array(16),k=new Float32Array(16),_=!1,K=1,U=0,O=!1,B=null,q=null,Y=0,W=null,j=()=>{de===this&&(de=null),W?.(),W=null;try{F?.cancel?.()}catch{}if(F=null,L){let x=e?.meshes;if(Array.isArray(x)){let N=x.indexOf(L);N!==-1&&x.splice(N,1)}let I=e.getGLContext?.()||e?.gl;if(I)for(let N of L.primitives||[]){I.deleteVertexArray?.(N.vao);for(let z of N.buffers||[])I.deleteBuffer?.(z)}L=null}e?.setXRSessionActive?.(!1),v(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=j,E.addEventListener("end",()=>{j(),i.onExit?.()}),E.addEventListener("select",()=>{if(!this.placed){let x=h||w;S=[x[0],x[1],x[2]],ht(this.placedMat,S,g,U,T*K),this.placed=!0,L&&(L.visible=!1),A&&(A.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),i.onPlaced?.(this.placedMat)}});try{let x=e.getGLContext?.()||e?.gl;x&&typeof x.makeXRCompatible=="function"&&await x.makeXRCompatible();let I=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;x&&typeof I=="function"&&typeof E.updateRenderState=="function"&&E.updateRenderState({baseLayer:new I(E,x,{alpha:!0})});try{b=await E.requestReferenceSpace("local")}catch{try{b=await E.requestReferenceSpace("local-floor")}catch{b=await E.requestReferenceSpace("viewer")}}let N=await E.requestReferenceSpace("viewer").catch(()=>b);if(typeof E.requestHitTestSource=="function"&&N&&(F=await E.requestHitTestSource({space:N}).catch(()=>null)),m==="immersive-ar"&&x&&typeof x.createVertexArray=="function"&&Array.isArray(e.meshes)&&(L=kt(x,i.reticleColor),e.meshes.push(L)),typeof window<"u"&&typeof window.addEventListener=="function"){let ee=G=>Math.hypot(G.touches[1].clientX-G.touches[0].clientX,G.touches[1].clientY-G.touches[0].clientY),ie=G=>Math.atan2(G.touches[1].clientY-G.touches[0].clientY,G.touches[1].clientX-G.touches[0].clientX),oe=G=>{this.s&&(G.touches.length===1&&this.placed?O=!0:G.touches.length>=2&&(O=!1,B=ee(G),q=ie(G)))},H=G=>{if(!this.s||G.touches.length<2)return;let te=ee(G),V=ie(G);if(B&&B>4&&i.arScale!=="fixed"&&(K=Math.max(.15,Math.min(6,K*(te/B)))),q!==null){let J=V-q;J>Math.PI&&(J-=Math.PI*2),J<-Math.PI&&(J+=Math.PI*2),U-=J}B=te,q=V},$=G=>{(!G.touches||G.touches.length===0)&&(O=!1),(!G.touches||G.touches.length<2)&&(B=null,q=null)};window.addEventListener("touchstart",oe,{passive:!0}),window.addEventListener("touchmove",H,{passive:!0}),window.addEventListener("touchend",$,{passive:!0}),window.addEventListener("touchcancel",$,{passive:!0}),W=()=>{window.removeEventListener("touchstart",oe),window.removeEventListener("touchmove",H),window.removeEventListener("touchend",$),window.removeEventListener("touchcancel",$)}}e.setXRSessionActive?.(!0);let z=(ee,ie)=>{if(this.s!==E)return;E.requestAnimationFrame(z);let oe=Y>0?Math.min(Math.max((ee-Y)/1e3,0),.1):1/60;Y=ee,e?.stepXRUpdate?.(oe);let H=ie.getViewerPose(b);if(!H)return;let $=H.views?.[0];if(!_&&$?.transform){let Z=$.transform.position,ne=$.transform.matrix,le=Z?.x??(ne?ne[12]:0),ce=Z?.y??(ne?ne[13]:0),ue=Z?.z??(ne?ne[14]:0),fe=ne?-ne[8]:0,be=ne?-ne[10]:-1,Pe=Math.hypot(fe,be);Pe>1e-4?(fe/=Pe,be/=Pe):(fe=0,be=-1),w=[le+fe*1.2,ce-.25,ue+be*1.2],U=Math.atan2(-fe,-be),_=!0}if(F&&typeof ie.getHitTestResults=="function"&&(!this.placed||O)){let Z=ie.getHitTestResults(F)||[],ne=!1;for(let le of Z){let ce=le.getPose(b);if(ce?.transform?.matrix){let ue=ce.transform.matrix,fe=ue[5];if(i.arPlacement==="wall"&&Math.abs(fe)>.35||i.arPlacement==="floor"&&Math.abs(fe)<.65)continue;C||(C=new Float32Array(16)),C.set(ue),h=[ue[12],ue[13],ue[14]],this.placed&&O&&(S=[ue[12],ue[13],ue[14]]),L&&(L.visible=!this.placed||O,L.transform.set(ue)),!this.placed&&A&&(A.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),i.onHit?.(C),ne=!0;break}}!ne&&L&&(L.visible=!1)}ht(M,this.placed?S:h||w,g,U,T*K),this.placed&&this.placedMat.set(M);let G=e.xrRigMatrix;G instanceof Float32Array&&G.length===16?se(k,G,M):k.set(M),e.modelRootMatrix&&e.modelRootMatrix.set(k);for(let Z of ae)Z.onXRFrame?.(e,E,ie,b);let te=e.getGLContext?.()||e?.gl,V=E.renderState?.baseLayer;te&&V&&V.framebuffer!==void 0&&te.bindFramebuffer(36160,V.framebuffer);let J=m==="immersive-ar",Q=H.views||[];for(let Z=0;Z<Q.length;Z++){let ne=Q[Z];if(typeof e.renderXRView=="function"){let le;if(V&&typeof V.getViewport=="function"){let ce=V.getViewport(ne);ce&&ce.width>0&&ce.height>0&&(le=[ce.x,ce.y,ce.width,ce.height])}else V?.framebufferWidth>0&&V?.framebufferHeight>0&&(le=[0,0,V.framebufferWidth,V.framebufferHeight]);e.renderXRView(ne,k,this.placed,le,J,Z)}}te&&V&&V.framebuffer&&te.bindFramebuffer(36160,null)};E.requestAnimationFrame(z)}catch(x){throw typeof E.end=="function"&&await E.end().catch(()=>{}),j(),i.onError?.(x),x}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function nn(n){let e=await bt(),t=n.preferredModes||["quick-look","webxr","scene-viewer"],r=null;for(let c of t)if(e.availableModes.includes(c)){r=c;break}if(r||(r=e.bestMode),!r)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let i={...n.quickLookOptions,allowScale:n.arScale==="fixed"?!1:n.quickLookOptions?.allowScale},s={...n.sceneViewerOptions,resizable:n.arScale==="fixed"?!1:n.sceneViewerOptions?.resizable,enableVerticalPlacement:n.arPlacement==="wall"?!0:n.sceneViewerOptions?.enableVerticalPlacement},a={...n.webXROptions,arScale:n.arScale||n.webXROptions?.arScale,arPlacement:n.arPlacement||n.webXROptions?.arPlacement};try{if(r==="quick-look"){let c;if(n.model instanceof Blob&&n.model.type==="model/vnd.usdz+zip")c=n.model;else{if(typeof n.model=="string")return mt(n.model,i),{mode:"quick-look",success:!0};c=lt(n.model)}return mt(c,i),{mode:"quick-look",success:!0}}if(r==="scene-viewer"){let c=n.glbUrl||(typeof n.model=="string"?n.model:null);if(!c)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return Ut(c,s),{mode:"scene-viewer",success:!0}}if(r==="webxr"){if(!n.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let c=new Oe(a);return await c.start(n.view,n.element),{mode:"webxr",success:!0,session:c}}}catch(c){return{mode:r,success:!1,error:c}}return{mode:r,success:!1,error:new Error(`Unhandled AR mode: ${r}`)}}export{Oe as WebXRSessionManager,nn as activateAR,Ve as buildUSDZZip,ot as calculateCRC32,Nt as createSceneViewerIntent,lt as createUSDZBlob,at as generateUSDA,ut as generateUSDZ,bt as getARCapabilities,en as getAvailableARModes,tn as getBestARMode,ct as glbToUSDZ,ft as isQuickLookSupported,dt as isSceneViewerSupported,pt as isWebXRSupported,mt as launchQuickLook,Ut as launchSceneViewer};
341
+ `,o}function Xt(e,t){if(e&&typeof e.traverse=="function"){let a=qt(e,t);return Be(a)}let i=Ae(e),r=$e(i);return Be(r)}var Se=null;function dt(e){if(!Se){Se=new Uint32Array(256);for(let i=0;i<256;i++){let r=i;for(let a=0;a<8;a++)r=r&1?3988292384^r>>>1:r>>>1;Se[i]=r}}let t=4294967295;for(let i=0;i<e.length;i++)t=Se[(t^e[i])&255]^t>>>8;return(t^4294967295)>>>0}function pt(e){let t=[],i=0,r=[];for(let p of e){let y=ct(p.filename),D=dt(p.data),S=p.data.length,h=30+y.length,v=(i+h)%64,P=v!==0?64-v:0,T=new Uint8Array(h+P),x=new DataView(T.buffer);x.setUint32(0,67324752,!0),x.setUint16(4,20,!0),x.setUint32(14,D,!0),x.setUint32(18,S,!0),x.setUint32(22,S,!0),x.setUint16(26,y.length,!0),x.setUint16(28,P,!0),T.set(y,30),t.push({offset:i,size:S,crc:D,filenameBytes:y,entry:p}),r.push(T,p.data),i+=T.length+p.data.length}let a=i;for(let p of t){let y=new Uint8Array(46+p.filenameBytes.length),D=new DataView(y.buffer);D.setUint32(0,33639248,!0),D.setUint16(4,20,!0),D.setUint16(6,20,!0),D.setUint32(16,p.crc,!0),D.setUint32(20,p.size,!0),D.setUint32(24,p.size,!0),D.setUint16(28,p.filenameBytes.length,!0),D.setUint32(42,p.offset,!0),y.set(p.filenameBytes,46),r.push(y),i+=y.length}let s=i-a,u=new Uint8Array(22),o=new DataView(u.buffer);o.setUint32(0,101010256,!0),o.setUint16(8,t.length,!0),o.setUint16(10,t.length,!0),o.setUint32(12,s,!0),o.setUint32(16,a,!0),r.push(u),i+=22;let d=new Uint8Array(i),f=0;for(let p of r)d.set(p,f),f+=p.length;return d}var Wt=e=>pt([{filename:"model.usda",data:ct(e)}]);function gt(e){return Wt(Be($e(Ae(e))))}function vt(e){return e&&typeof e.toUSDZ=="function"?e.toUSDZ():gt(e)}function xt(e){let t=vt(e);return new Blob([t],{type:"model/vnd.usdz+zip"})}function He(){if(typeof window>"u"||typeof navigator>"u")return!1;let e=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(e)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))return!1;let t=document.createElement("a");return t.relList!==void 0&&t.relList.supports!==void 0&&t.relList.supports("ar")}function ze(){if(typeof navigator>"u")return!1;let e=navigator.userAgent||"";return/android/i.test(e)}async function je(){if(typeof navigator>"u")return!1;let e=navigator;if(!e.xr||typeof e.xr.isSessionSupported!="function")return!1;try{return await e.xr.isSessionSupported("immersive-ar")?!0:await e.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function Yt(){let e=[];return await je()&&e.push("webxr"),He()&&e.push("quick-look"),ze()&&e.push("scene-viewer"),e}async function Zt(){return(await qe()).bestMode}async function qe(){let[e,t,i]=await Promise.all([je(),Promise.resolve(He()),Promise.resolve(ze())]),r=[];t&&r.push("quick-look"),e&&r.push("webxr"),i&&r.push("scene-viewer");let a=null;return t?a="quick-look":e?a="webxr":i&&(a="scene-viewer"),{webxr:e,quickLook:t,sceneViewer:i,availableModes:r,bestMode:a}}function Ge(e,t={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let i,r=!1;if(typeof e=="string"){if(i=Qt(e),!i)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else i=URL.createObjectURL(e),r=!0;let a=[];if(t.allowScale===!1&&a.push("allowsContentScaling=0"),t.canonicalWebPageUrl){let o=De(t.canonicalWebPageUrl,!1);o&&a.push(`canonicalWebPageURL=${encodeURIComponent(o)}`)}t.checkoutTitle&&a.push(`checkoutTitle=${encodeURIComponent(t.checkoutTitle)}`),t.checkoutSubtitle&&a.push(`checkoutSubtitle=${encodeURIComponent(t.checkoutSubtitle)}`),t.price&&a.push(`price=${encodeURIComponent(t.price)}`),a.length>0&&(i+=`#${a.join("&")}`);let s=document.createElement("a");s.setAttribute("rel","ar"),s.setAttribute("href",i);let u=document.createElement("img");u.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),u.style.display="none",s.appendChild(u),document.body.appendChild(s),s.click(),setTimeout(()=>{document.body.removeChild(s),r&&URL.revokeObjectURL(i.split("#")[0])},3e3)}function De(e,t=!1){if(typeof e!="string")return"";let i=e.replace(/[\x00-\x1f\x7f]+/g,"").trim();if(!i)return"";if(/^[\\/]{2}/.test(i))throw new Error(`[XR-Live Security] Rejected protocol-relative URL in Scene Viewer intent: ${i.slice(0,32)}`);let r=i.toLowerCase();if(r.startsWith("https://")||r.startsWith("http://")||t&&r.startsWith("blob:")||!/^[a-z][a-z0-9+.-]*:/i.test(i))return i;throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Scene Viewer intent: ${i.slice(0,32)}`)}function Qt(e){try{return De(e,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(e||"").trim().slice(0,32)}`)}}function bt(e,t={}){let i=De(e,!0),r=t.mode||"ar_preferred",a=new URLSearchParams({file:i,mode:r,resizable:t.resizable!==!1?"true":"false",enable_vertical_placement:t.enableVerticalPlacement?"true":"false"});return t.title&&a.set("title",t.title),t.link&&a.set("link",De(t.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${a.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function yt(e,t={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let i=bt(e,t);window.location.href=i}var ye=null;function Jt(e,t){let i=new Float32Array(144),r=new Float32Array(144),a=new Float32Array(96),s=new Uint16Array(144);for(let p=0;p<24;p++){let y=p/24*Math.PI*2,D=Math.cos(y),S=Math.sin(y),h=p*2,v=h+1,P=(p+1)%24*2;i[h*3]=D*.11,i[h*3+1]=.002,i[h*3+2]=S*.11,i[v*3]=D*.145,i[v*3+1]=.002,i[v*3+2]=S*.145,r[h*3+1]=r[v*3+1]=1,s.set([h,P,v,v,P,P+1],p*6)}let u=e.createVertexArray();e.bindVertexArray(u);let o=(p,y,D)=>{let S=e.createBuffer();return e.bindBuffer(34962,S),e.bufferData(34962,p,35044),e.enableVertexAttribArray(y),e.vertexAttribPointer(y,D,5126,!1,0,0),S},d=[o(i,0,3),o(r,1,3),o(a,2,2)],f=e.createBuffer();return d.push(f),e.bindBuffer(34963,f),e.bufferData(34963,s,35044),e.bindVertexArray(null),{name:"__xr_reticle__",nodeIndex:-1,worldSpace:!0,visible:!1,transform:new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),normalMatrix:new Float32Array([1,0,0,0,1,0,0,0,1]),primitives:[{vao:u,indexCount:s.length,indexType:5123,baseColor:t&&t.length>=3?[t[0],t[1],t[2],t[3]??.95]:[.22,.74,.97,.95],metallic:0,roughness:.2,positions:i,indices:s,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:d}]}}function Mt(e,t,i,r,a){let s=Math.cos(r),u=Math.sin(r),o=Math.max(.01,a);e.fill(0),e[0]=o*s,e[2]=-o*u,e[5]=o,e[8]=o*u,e[10]=o*s,e[12]=t[0]-o*(s*i[0]+u*i[2]),e[13]=t[1]-o*i[1],e[14]=t[2]-o*(-u*i[0]+s*i[2]),e[15]=1}var wt=class{constructor(e={}){this.s=null,this.placed=!1,this.placedMat=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this.cleanFn=null,this.opts=e}isSessionActive(){return this.s!==null}hasPlacedModel(){return this.placed}getPlacedMatrix(){return this.placedMat}async start(e,t){if(typeof navigator>"u"||!navigator.xr)throw new Error("WebXR is not supported on this browser.");ye&&ye!==this&&ye.isSessionActive()&&await ye.stop().catch(()=>{});let i=navigator.xr,r=this.opts,a=t||e?.container,s=String(a?.tagName||"").toLowerCase()==="xr-live",u=e?.bounds,o=Number(u?.radius)||1,d=Array.isArray(u?.center)?u.center:[0,0,0],f=Array.isArray(u?.min)?u.min:[-.5,-.5,-.5],p=typeof navigator<"u"&&navigator.userAgent||"",y=/Android|iPhone|iPad|iPod/i.test(p)&&!/Quest|Oculus|Pico|Vision/i.test(p),D=s?r.arScale==="fixed"?1:y?.55:1:r.arScale==="fixed"?1:o>.45?.3/o:o<.05?.12/Math.max(o,.001):1,S=s?[0,-.25,0]:[d[0]||0,r.arPlacement==="wall"?d[1]:f[1]??0,d[2]||0],h="immersive-ar";try{await i.isSessionSupported("immersive-ar")||(h="immersive-vr")}catch{h="immersive-vr"}let v=a?.querySelector?.('[slot="ar-overlay"]')||null,P=!1,T=null,x=()=>{P&&v?.parentNode&&v.parentNode.removeChild(v),v=null,T=null,P=!1};if(h==="immersive-ar"){if(v)v.addEventListener?.("beforexrselect",C=>C.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let C=document.createElement("div");C.style.cssText="position:fixed;inset:0;pointer-events:none;background:transparent!important;z-index:2147483647;font-family:system-ui,sans-serif;user-select:none";let U=document.createElement("button");U.type="button",U.textContent="\u2715 Exit AR",U.style.cssText="position:absolute;top:max(16px,env(safe-area-inset-top,16px));right:16px;pointer-events:auto;padding:8px 14px;border-radius:99px;border:1px solid rgba(255,255,255,.3);background:rgba(15,23,42,.8);color:#f8fafc;font:600 13px system-ui,sans-serif",U.addEventListener("beforexrselect",k=>k.preventDefault()),U.addEventListener("click",k=>{k.stopPropagation(),this.stop().catch(()=>{})}),T=document.createElement("div"),T.style.cssText="position:absolute;bottom:max(28px,env(safe-area-inset-bottom,28px));left:50%;transform:translateX(-50%);padding:8px 15px;border-radius:99px;border:1px solid rgba(56,189,248,.4);background:rgba(15,23,42,.82);color:#f8fafc;font:500 12.5px system-ui,sans-serif;text-align:center;max-width:88vw",T.textContent="Move phone to detect a surface \u2022 Tap to place",C.appendChild(U),C.appendChild(T),document.body.appendChild(C),v=C,P=!0}}let c=new Set(r.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),l={requiredFeatures:r.requiredFeatures?[...r.requiredFeatures]:[],optionalFeatures:Array.from(c)};v&&(c.add("dom-overlay"),l.optionalFeatures=Array.from(c),l.domOverlay={root:v});for(let C of he)C.onConfigureXRSessionInit?.(a,l);Array.isArray(l.optionalFeatures)&&l.optionalFeatures.includes("dom-overlay")&&!l.domOverlay?.root&&(l.optionalFeatures=l.optionalFeatures.filter(C=>C!=="dom-overlay"));let b=C=>{let U=String(C?.name||"");return U==="NotAllowedError"||U==="SecurityError"};try{this.s=await i.requestSession(h,l)}catch(C){if(x(),b(C))throw r.onError?.(C),C;try{this.s=await i.requestSession(h,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(U){if(b(U))throw r.onError?.(U),U;try{this.s=await i.requestSession(h)}catch(k){throw r.onError?.(k),k}}}let w=this.s;ye=this,this.placed=!1;let O=null,B=null,E=null,N=null,R=null,L=[0,-.25,-1.2],M=[0,-.25,-1.2],n=new Float32Array(16),$=new Float32Array(16),W=!1,g=1,_=0,m=!1,A=null,q=null,K=0,H=null,Q=()=>{ye===this&&(ye=null),H?.(),H=null;try{B?.cancel?.()}catch{}if(B=null,E){let C=e?.meshes;if(Array.isArray(C)){let k=C.indexOf(E);k!==-1&&C.splice(k,1)}let U=e.getGLContext?.()||e?.gl;if(U)for(let k of E.primitives||[]){U.deleteVertexArray?.(k.vao);for(let j of k.buffers||[])U.deleteBuffer?.(j)}E=null}e?.setXRSessionActive?.(!1),x(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=Q,w.addEventListener("end",()=>{Q(),r.onExit?.()}),w.addEventListener("select",()=>{if(!this.placed){let C=R||L;M=[C[0],C[1],C[2]],Mt(this.placedMat,M,S,_,D*g),this.placed=!0,E&&(E.visible=!1),T&&(T.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),r.onPlaced?.(this.placedMat)}});try{let C=e.getGLContext?.()||e?.gl;C&&typeof C.makeXRCompatible=="function"&&await C.makeXRCompatible();let U=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;C&&typeof U=="function"&&typeof w.updateRenderState=="function"&&w.updateRenderState({baseLayer:new U(w,C,{alpha:!0})});try{O=await w.requestReferenceSpace("local")}catch{try{O=await w.requestReferenceSpace("local-floor")}catch{O=await w.requestReferenceSpace("viewer")}}let k=await w.requestReferenceSpace("viewer").catch(()=>O);if(typeof w.requestHitTestSource=="function"&&k&&(B=await w.requestHitTestSource({space:k}).catch(()=>null)),h==="immersive-ar"&&C&&typeof C.createVertexArray=="function"&&Array.isArray(e.meshes)&&(E=Jt(C,r.reticleColor),e.meshes.push(E)),typeof window<"u"&&typeof window.addEventListener=="function"){let F=I=>Math.hypot(I.touches[1].clientX-I.touches[0].clientX,I.touches[1].clientY-I.touches[0].clientY),G=I=>Math.atan2(I.touches[1].clientY-I.touches[0].clientY,I.touches[1].clientX-I.touches[0].clientX),V=I=>{this.s&&(I.touches.length===1&&this.placed?m=!0:I.touches.length>=2&&(m=!1,A=F(I),q=G(I)))},X=I=>{if(!this.s||I.touches.length<2)return;let J=F(I),Y=G(I);if(A&&A>4&&r.arScale!=="fixed"&&(g=Math.max(.15,Math.min(6,g*(J/A)))),q!==null){let ae=Y-q;ae>Math.PI&&(ae-=Math.PI*2),ae<-Math.PI&&(ae+=Math.PI*2),_-=ae}A=J,q=Y},z=I=>{(!I.touches||I.touches.length===0)&&(m=!1),(!I.touches||I.touches.length<2)&&(A=null,q=null)};window.addEventListener("touchstart",V,{passive:!0}),window.addEventListener("touchmove",X,{passive:!0}),window.addEventListener("touchend",z,{passive:!0}),window.addEventListener("touchcancel",z,{passive:!0}),H=()=>{window.removeEventListener("touchstart",V),window.removeEventListener("touchmove",X),window.removeEventListener("touchend",z),window.removeEventListener("touchcancel",z)}}e.setXRSessionActive?.(!0);let j=(F,G)=>{if(this.s!==w)return;w.requestAnimationFrame(j);let V=K>0?Math.min(Math.max((F-K)/1e3,0),.1):1/60;K=F,e?.stepXRUpdate?.(V);let X=G.getViewerPose(O);if(!X)return;let z=X.views?.[0];if(!W&&z?.transform){let te=z.transform.position,ie=z.transform.matrix,ce=te?.x??(ie?ie[12]:0),re=te?.y??(ie?ie[13]:0),se=te?.z??(ie?ie[14]:0),ne=ie?-ie[8]:0,oe=ie?-ie[10]:-1,de=Math.hypot(ne,oe);de>1e-4?(ne/=de,oe/=de):(ne=0,oe=-1),L=[ce+ne*1.2,re-.25,se+oe*1.2],_=Math.atan2(-ne,-oe),W=!0}if(B&&typeof G.getHitTestResults=="function"&&(!this.placed||m)){let te=G.getHitTestResults(B)||[],ie=!1;for(let ce of te){let re=ce.getPose(O);if(re?.transform?.matrix){let se=re.transform.matrix,ne=se[5];if(r.arPlacement==="wall"&&Math.abs(ne)>.35||r.arPlacement==="floor"&&Math.abs(ne)<.65)continue;N||(N=new Float32Array(16)),N.set(se),R=[se[12],se[13],se[14]],this.placed&&m&&(M=[se[12],se[13],se[14]]),E&&(E.visible=!this.placed||m,E.transform.set(se)),!this.placed&&T&&(T.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),r.onHit?.(N),ie=!0;break}}!ie&&E&&(E.visible=!1)}Mt(n,this.placed?M:R||L,S,_,D*g),this.placed&&this.placedMat.set(n);let I=e.xrRigMatrix;I instanceof Float32Array&&I.length===16?me($,I,n):$.set(n),e.modelRootMatrix&&e.modelRootMatrix.set($);for(let te of he)te.onXRFrame?.(e,w,G,O);let J=e.getGLContext?.()||e?.gl,Y=w.renderState?.baseLayer;J&&Y&&Y.framebuffer!==void 0&&J.bindFramebuffer(36160,Y.framebuffer);let ae=h==="immersive-ar",Z=X.views||[];for(let te=0;te<Z.length;te++){let ie=Z[te];if(typeof e.renderXRView=="function"){let ce;if(Y&&typeof Y.getViewport=="function"){let re=Y.getViewport(ie);re&&re.width>0&&re.height>0&&(ce=[re.x,re.y,re.width,re.height])}else Y?.framebufferWidth>0&&Y?.framebufferHeight>0&&(ce=[0,0,Y.framebufferWidth,Y.framebufferHeight]);e.renderXRView(ie,$,this.placed,ce,ae,te)}}J&&Y&&Y.framebuffer&&J.bindFramebuffer(36160,null)};w.requestAnimationFrame(j)}catch(C){throw typeof w.end=="function"&&await w.end().catch(()=>{}),Q(),r.onError?.(C),C}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function ei(e){let t=await qe(),i=e.preferredModes||["quick-look","webxr","scene-viewer"],r=null;for(let o of i)if(t.availableModes.includes(o)){r=o;break}if(r||(r=t.bestMode),!r)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let a={...e.quickLookOptions,allowScale:e.arScale==="fixed"?!1:e.quickLookOptions?.allowScale},s={...e.sceneViewerOptions,resizable:e.arScale==="fixed"?!1:e.sceneViewerOptions?.resizable,enableVerticalPlacement:e.arPlacement==="wall"?!0:e.sceneViewerOptions?.enableVerticalPlacement},u={...e.webXROptions,arScale:e.arScale||e.webXROptions?.arScale,arPlacement:e.arPlacement||e.webXROptions?.arPlacement};try{if(r==="quick-look"){let o;if(e.model instanceof Blob&&e.model.type==="model/vnd.usdz+zip")o=e.model;else{if(typeof e.model=="string")return Ge(e.model,a),{mode:"quick-look",success:!0};o=xt(e.model)}return Ge(o,a),{mode:"quick-look",success:!0}}if(r==="scene-viewer"){let o=e.glbUrl||(typeof e.model=="string"?e.model:null);if(!o)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return yt(o,s),{mode:"scene-viewer",success:!0}}if(r==="webxr"){if(!e.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let o=new wt(u);return await o.start(e.view,e.element),{mode:"webxr",success:!0,session:o}}}catch(o){return{mode:r,success:!1,error:o}}return{mode:r,success:!1,error:new Error(`Unhandled AR mode: ${r}`)}}export{wt as WebXRSessionManager,ei as activateAR,pt as buildUSDZZip,dt as calculateCRC32,bt as createSceneViewerIntent,xt as createUSDZBlob,Xt as generateUSDA,vt as generateUSDZ,qe as getARCapabilities,Yt as getAvailableARModes,Zt as getBestARMode,gt as glbToUSDZ,He as isQuickLookSupported,ze as isSceneViewerSupported,je as isWebXRSupported,Ge as launchQuickLook,yt as launchSceneViewer};