three-live 1.3.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +4 -1
  2. package/dist/index.d.ts +191 -0
  3. package/dist/three-author-engine.js +179 -144
  4. package/dist/three-author.cjs +153 -144
  5. package/dist/three-author.d.ts +191 -0
  6. package/dist/three-author.js +153 -144
  7. package/dist/three-convert.cjs +150 -141
  8. package/dist/three-convert.d.ts +191 -0
  9. package/dist/three-convert.js +150 -141
  10. package/dist/three-live-ai.cjs +41 -0
  11. package/dist/three-live-ai.d.ts +759 -0
  12. package/dist/three-live-ai.js +41 -0
  13. package/dist/three-live-ai.min.js +41 -0
  14. package/dist/three-live-animation.cjs +6 -6
  15. package/dist/three-live-animation.d.ts +191 -0
  16. package/dist/three-live-animation.js +5 -5
  17. package/dist/three-live-animation.min.js +5 -5
  18. package/dist/three-live-cad.cjs +2 -2
  19. package/dist/three-live-cad.d.ts +191 -0
  20. package/dist/three-live-cad.js +2 -2
  21. package/dist/three-live-cad.min.js +2 -2
  22. package/dist/three-live-element.cjs +50 -85
  23. package/dist/three-live-element.d.ts +191 -0
  24. package/dist/three-live-element.js +50 -85
  25. package/dist/three-live-full.cjs +915 -170
  26. package/dist/three-live-full.js +917 -172
  27. package/dist/three-live-full.min.js +915 -170
  28. package/dist/three-live-procedural.cjs +16 -0
  29. package/dist/three-live-procedural.d.ts +759 -0
  30. package/dist/three-live-procedural.js +16 -0
  31. package/dist/three-live-procedural.min.js +16 -0
  32. package/dist/three-live-sandbox.html +11 -1
  33. package/dist/three-live-studio.cjs +72 -17
  34. package/dist/three-live-studio.d.ts +191 -0
  35. package/dist/three-live-studio.js +72 -17
  36. package/dist/three-live-studio.min.js +73 -18
  37. package/dist/three-live-tsl.cjs +103 -0
  38. package/dist/three-live-tsl.d.ts +759 -0
  39. package/dist/three-live-tsl.js +103 -0
  40. package/dist/three-live-tsl.min.js +103 -0
  41. package/dist/three-live-viewer.cjs +50 -85
  42. package/dist/three-live-viewer.d.ts +191 -0
  43. package/dist/three-live-viewer.js +50 -85
  44. package/dist/three-live-viewer.min.js +50 -85
  45. package/dist/three-live-webgpu.cjs +585 -0
  46. package/dist/three-live-webgpu.d.ts +759 -0
  47. package/dist/three-live-webgpu.js +585 -0
  48. package/dist/three-live-webgpu.min.js +585 -0
  49. package/dist/three-live.cjs +155 -146
  50. package/dist/three-live.js +155 -146
  51. package/dist/three-live.min.js +155 -146
  52. package/dist/three-view.cjs +49 -84
  53. package/dist/three-view.d.ts +191 -0
  54. package/dist/three-view.js +50 -85
  55. package/dist/three-xr.cjs +150 -141
  56. package/dist/three-xr.d.ts +191 -0
  57. package/dist/three-xr.js +150 -141
  58. package/package.json +39 -1
@@ -13,7 +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
- */var Ge=Object.defineProperty,Rt=Object.getOwnPropertyDescriptor,Dt=Object.getOwnPropertyNames,Et=Object.prototype.hasOwnProperty,St=(t,e)=>{for(var i in e)Ge(t,i,{get:e[i],enumerable:!0})},Pt=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Dt(e))!Et.call(t,a)&&a!==i&&Ge(t,a,{get:()=>e[a],enumerable:!(r=Rt(e,a))||r.enumerable});return t},Ct=t=>Pt(Ge({},"__esModule",{value:!0}),t),Yt={};St(Yt,{buildUSDZZip:()=>Mt,calculateCRC32:()=>xt,compileInteractivityGraph:()=>Oe,createUSDZBlob:()=>qt,encodeUtf8:()=>Ne,extractMeshesFromGLB:()=>Be,extractMeshesFromScene:()=>yt,generateUSDA:()=>vt,generateUSDAFromMeshes:()=>Fe,generateUSDZ:()=>wt,glbToUSDZ:()=>At,sanitizeUsdIdentifier:()=>we,sanitizeUsdStringLiteral:()=>_e,sceneToCanvas3D:()=>bt,sceneToGLB:()=>Wt,sceneToUSDZ:()=>Kt}),module.exports=Ct(Yt);function Oe(t,e,i){let r=[],a=new Map,s=[],m=[],f=[],p=new Map,u=h=>{let n=a.get(h);return n===void 0&&(n=r.length,r.push({op:h}),a.set(h,n)),n},d=h=>{let n=p.get(h);return n===void 0&&(n=f.length,f.push({id:h}),p.set(h,n)),n},y=(h,n={})=>s.push({declaration:u(h),...n})-1,R=(h,n,b)=>m.push({id:h,type:n,value:b})-1,S=h=>({node:h,socket:"value"}),l=i?.interactivity??i?.gltfExtensions?.KHR_interactivity;if(l&&typeof l=="object"){let h=Array.isArray(l.graphs)?l.graphs[l.graph??0]:l;if(h&&Array.isArray(h.nodes)){let n=Array.isArray(h.declarations)?h.declarations:[];for(let b of n)b?.op&&u(b.op);Array.isArray(h.variables)&&m.push(...h.variables);for(let b of h.events||[])b?.id&&d(b.id);for(let b of h.nodes){if(!b||typeof b!="object")continue;let A=b.op||(typeof b.declaration=="number"?n[b.declaration]?.op:"");s.push(A?{...b,declaration:u(A)}:{...b})}}}let x=(h,n,b="translation")=>b==="baseColorFactor"||b==="metallicFactor"||b==="roughnessFactor"?`/materials/${Math.max(0,n)}/pbrMetallicRoughness/${b}`:b==="emissiveFactor"||b==="alphaCutoff"?`/materials/${Math.max(0,n)}/${b}`:b==="visible"?`/nodes/${h}/extensions/KHR_node_visibility/visible`:`/nodes/${h}/${b}`,T=new Map;t.forEach((h,n)=>{typeof h?.name=="string"&&!T.has(h.name)&&T.set(h.name,n)});let w=(h,n)=>typeof h.target=="string"&&T.has(h.target)?T.get(h.target):typeof h.targetNode=="number"?h.targetNode:n,v=h=>{let n=t[h];return(typeof n?.mesh=="number"?e[n.mesh]?.primitives?.[0]?.material:0)??0};for(let h=0;h<t.length;h++){let n=t[h],b=n?.extras?.interactivity;if(!b||typeof b!="object")continue;let A=(typeof n.mesh=="number"?e[n.mesh]?.primitives?.[0]?.material:0)??0,$=_=>{let L=Array.isArray(_)?_:[_],C=[];for(let M=0;M<L.length;M++){let o=L[M];if(!o||typeof o!="object")continue;let V=o.action||"interpolate",X=typeof o.duration=="number"?o.duration:.35;if(V==="toggleTransform"){let g=o.property==="rotation"||o.property==="scale"?o.property:"translation",I=g==="rotation"?n.rotation||[0,0,0,1]:g==="scale"?n.scale||[1,1,1]:n.translation||[0,0,0],c=`/nodes/${h}/${g}`,P=R(`__toggle_${h}_${M}`,"bool",!1),j=y("variable/get",{configuration:{variable:P}}),G=y("math/not",{values:{a:S(j)}}),U=y("variable/set",{configuration:{variable:P},values:{value:S(G)}}),Z=y("pointer/interpolate",{configuration:{pointer:c},values:{value:{value:Array.isArray(o.to)?o.to:I},duration:{value:X}}}),E=y("pointer/interpolate",{configuration:{pointer:c},values:{value:{value:Array.isArray(o.from)?o.from:I},duration:{value:X}}});s[U].flows={out:{node:y("flow/branch",{values:{condition:S(j)},flows:{true:{node:Z},false:{node:E}}})}},C.push(U)}else if(V==="interpolate"){let g=o.to??o.value;if(g===void 0)continue;let I={value:{value:g},duration:{value:X}};o.from!==void 0&&(I.from={value:o.from}),C.push(y("pointer/interpolate",{configuration:{pointer:typeof o.pointer=="string"?o.pointer:x(w(o,h),v(w(o,h)),o.property)},values:I}))}else if(V==="setProperty"){if(o.value===void 0)continue;C.push(y("pointer/set",{configuration:{pointer:typeof o.pointer=="string"?o.pointer:x(w(o,h),v(w(o,h)),o.property)},values:{value:{value:o.value}}}))}else if(V==="toggleVisibility"){let g=w(o,h),I=R(`__vis_${g}_${M}`,"bool",!0),c=y("variable/get",{configuration:{variable:I}}),P=y("math/not",{values:{a:S(c)}}),j=y("variable/set",{configuration:{variable:I},values:{value:S(P)}});s[j].flows={out:{node:y("pointer/set",{configuration:{pointer:`/nodes/${g}/extensions/KHR_node_visibility/visible`},values:{value:S(c)}})}},C.push(j)}else if(V==="cycleMaterialColor"&&Array.isArray(o.colors)&&o.colors.length>0){let g=typeof o.duration=="number"?o.duration:.25,I=`/materials/${Math.max(0,A)}/pbrMetallicRoughness/baseColorFactor`,c=R(`__color_idx_${h}_${M}`,"int",0),P=y("variable/get",{configuration:{variable:c}}),j=y("math/add",{values:{a:S(P),b:{value:1}}}),G=y("math/rem",{values:{a:S(j),b:{value:o.colors.length}}}),U=y("variable/set",{configuration:{variable:c},values:{value:S(G)}}),Z={};for(let E=0;E<o.colors.length;E++){let q=o.colors[E],k=Array.isArray(q)&&q.length>=3?[q[0],q[1],q[2],q[3]??1]:[1,1,1,1];Z[String(E)]={node:g>0?y("pointer/interpolate",{configuration:{pointer:I},values:{value:{value:k},duration:{value:g}}}):y("pointer/set",{configuration:{pointer:I},values:{value:{value:k}}})}}s[U].flows={out:{node:y("flow/switch",{values:{selection:S(P)},flows:Z})}},C.push(U)}else if(V==="playAnimation")C.push(y("animation/start",{configuration:{animation:o.animation??o.clip??0}}));else if(V==="stopAnimation")C.push(y("animation/stop"));else if(V==="sendEvent"){let g={};for(let[I,c]of Object.entries(o.values||{}))g[I]={value:c};C.push(y("event/send",{configuration:{event:d(String(o.event??o.id??"custom"))},values:g}))}}if(!C.length)return null;if(C.length===1)return C[0];let D={};return C.forEach((M,o)=>{D[String(o)]={node:M}}),y("flow/sequence",{flows:D})},B=(_,L,C)=>{let D=$(L);D!==null&&y(_,{...C?{configuration:C}:{},flows:{out:{node:D}}})};if(b.onSelect&&B("pointer/onSelect",b.onSelect,{nodeIndex:h}),b.onHoverIn&&B("pointer/onHoverIn",b.onHoverIn,{nodeIndex:h}),b.onHoverOut&&B("pointer/onHoverOut",b.onHoverOut,{nodeIndex:h}),b.onStart&&B("event/onStart",b.onStart),b.onReceive&&typeof b.onReceive=="object")for(let[_,L]of Object.entries(b.onReceive))B("event/receive",L,{event:d(_)})}return s.length?{graphs:[{declarations:r,nodes:s,variables:m,events:f}],graph:0}:null}var De="__THREE_LIVE_REGISTRY__";function de(){let t=typeof globalThis<"u"?globalThis:{};if(!t[De]){let e={plugins:[],decoders:new Map};try{Object.defineProperty(t,De,{value:e,writable:!1,configurable:!1,enumerable:!1})}catch{t[De]=e}}return t[De]}var ue=de().plugins;function Ke(t){let e=de().plugins;e.some(i=>i.name===t.name)||e.push(t),t.onRegister?.()}function qe(){return de().plugins}var Lt={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function Ve(t,e,i,r){if(!i||i.bufferView===void 0)return null;let a=t.bufferViews?.[i.bufferView];if(!a)return null;let s=Number(i.count??0);if(!Number.isInteger(s)||s<=0)return null;let m=i.componentType??5126,f=Lt[m];if(!f)throw new RangeError(`glTF accessor has unsupported componentType ${m}`);let p=f*r,u=a.byteStride&&a.byteStride>0?a.byteStride:p,d=(a.byteOffset||0)+(i.byteOffset||0);if(!Number.isInteger(d)||d<0||u<p||d+(s-1)*u+p>e.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${e.byteLength} bytes)`);if(m===5126&&u===p&&d%4===0)return new Float32Array(e,d,s*r);let y=new DataView(e),R=i.normalized===!0,S=new Float32Array(s*r);for(let l=0;l<s;l++){let x=d+l*u;for(let T=0;T<r;T++){let w=x+T*f,v;switch(m){case 5126:v=y.getFloat32(w,!0);break;case 5120:v=y.getInt8(w),R&&(v=Math.max(v/127,-1));break;case 5121:v=y.getUint8(w),R&&(v/=255);break;case 5122:v=y.getInt16(w,!0),R&&(v=Math.max(v/32767,-1));break;case 5123:v=y.getUint16(w,!0),R&&(v/=65535);break;default:v=y.getUint32(w,!0),R&&(v/=4294967295)}S[l*r+T]=v}}return S}function Ye(t,e){let i=Number(e.offset?.[0]??0)||0,r=Number(e.offset?.[1]??0)||0,a=Number(e.scale?.[0]??1),s=Number(e.scale?.[1]??1),m=Number(e.rotation??0)||0,f=Math.cos(m),p=Math.sin(m),u=(Number.isFinite(a)?a:1)*f,d=(Number.isFinite(a)?a:1)*p,y=-(Number.isFinite(s)?s:1)*p,R=(Number.isFinite(s)?s:1)*f;for(let S=0;S+1<t.length;S+=2){let l=t[S],x=t[S+1];t[S]=u*l+d*x+i,t[S+1]=y*l+R*x+r}}function Ee(t,e,i,r=!0){let a=[],s=null;try{for(let[m,f]of[[35633,e],[35632,i]]){let p=t.createShader(m);if(!p){if(r)throw new Error("Shader allocation failed");return null}if(a.push(p),t.shaderSource(p,f),t.compileShader(p),t.getShaderParameter&&!t.getShaderParameter(p,35713)){if(r)throw new Error(`Shader compile error: ${t.getShaderInfoLog(p)}`);return null}}if(s=t.createProgram(),!s){if(r)throw new Error("Program allocation failed");return null}for(let m of a)t.attachShader(s,m);if(t.linkProgram(s),t.getProgramParameter&&!t.getProgramParameter(s,35714)){let m=r?t.getProgramInfoLog(s):null;if(t.deleteProgram?.(s),s=null,r)throw new Error(`Program link error: ${m}`);return null}return s}finally{for(let m of a)s&&t.detachShader?.(s,m),t.deleteShader?.(m)}}function se(){let t=new Float32Array(16);return t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function Se(t,e,i,r,a){let s=1/Math.tan(e/2);t.fill(0),t[0]=s/i,t[5]=s,t[11]=-1;let m=1/(r-a);return t[10]=(a+r)*m,t[14]=2*a*r*m,t}function Pe(t,e,i,r){let[a,s,m]=e,[f,p,u]=r,[d,y,R]=i,S=a-d,l=s-y,x=m-R,T=Math.hypot(S,l,x);T<=1e-5?(S=0,l=0,x=1):(S/=T,l/=T,x/=T);let w=p*x-u*l,v=u*S-f*x,h=f*l-p*S;T=Math.hypot(w,v,h),T<=1e-5?(w=0,v=0,h=0):(w/=T,v/=T,h/=T);let n=l*h-x*v,b=x*w-S*h,A=S*v-l*w;return T=Math.hypot(n,b,A),T<=1e-5?(n=0,b=0,A=0):(n/=T,b/=T,A/=T),t[0]=w,t[1]=n,t[2]=S,t[3]=0,t[4]=v,t[5]=b,t[6]=l,t[7]=0,t[8]=h,t[9]=A,t[10]=x,t[11]=0,t[12]=-(w*a+v*s+h*m),t[13]=-(n*a+b*s+A*m),t[14]=-(S*a+l*s+x*m),t[15]=1,t}function me(t,e,i){let r=e[0],a=e[1],s=e[2],m=e[3],f=e[4],p=e[5],u=e[6],d=e[7],y=e[8],R=e[9],S=e[10],l=e[11],x=e[12],T=e[13],w=e[14],v=e[15],h=i[0],n=i[1],b=i[2],A=i[3];return t[0]=h*r+n*f+b*y+A*x,t[1]=h*a+n*p+b*R+A*T,t[2]=h*s+n*u+b*S+A*w,t[3]=h*m+n*d+b*l+A*v,h=i[4],n=i[5],b=i[6],A=i[7],t[4]=h*r+n*f+b*y+A*x,t[5]=h*a+n*p+b*R+A*T,t[6]=h*s+n*u+b*S+A*w,t[7]=h*m+n*d+b*l+A*v,h=i[8],n=i[9],b=i[10],A=i[11],t[8]=h*r+n*f+b*y+A*x,t[9]=h*a+n*p+b*R+A*T,t[10]=h*s+n*u+b*S+A*w,t[11]=h*m+n*d+b*l+A*v,h=i[12],n=i[13],b=i[14],A=i[15],t[12]=h*r+n*f+b*y+A*x,t[13]=h*a+n*p+b*R+A*T,t[14]=h*s+n*u+b*S+A*w,t[15]=h*m+n*d+b*l+A*v,t}function He(t,e,i,r){let a=e[0],s=e[1],m=e[2],f=e[3],p=a+a,u=s+s,d=m+m,y=a*p,R=a*u,S=a*d,l=s*u,x=s*d,T=m*d,w=f*p,v=f*u,h=f*d,n=r[0],b=r[1],A=r[2];return t[0]=(1-(l+T))*n,t[1]=(R+h)*n,t[2]=(S-v)*n,t[3]=0,t[4]=(R-h)*b,t[5]=(1-(y+T))*b,t[6]=(x+w)*b,t[7]=0,t[8]=(S+v)*A,t[9]=(x-w)*A,t[10]=(1-(y+l))*A,t[11]=0,t[12]=i[0],t[13]=i[1],t[14]=i[2],t[15]=1,t}function be(t,e,i=0){let r=e[0],a=e[1],s=e[2],m=e[4],f=e[5],p=e[6],u=e[8],d=e[9],y=e[10],R=y*f-p*d,S=-y*m+p*u,l=d*m-f*u,x=r*R+a*S+s*l;return!x||i>0&&(!Number.isFinite(x)||Math.abs(x)<=i)||(x=1/x,t[0]=R*x,t[1]=S*x,t[2]=l*x,t[3]=(-y*a+s*d)*x,t[4]=(y*r-s*u)*x,t[5]=(-d*r+a*u)*x,t[6]=(p*a-s*f)*x,t[7]=(-p*r+s*m)*x,t[8]=(f*r-a*m)*x),t}function Ze(t,e){let i=e[0],r=e[1],a=e[2],s=e[3],m=e[4],f=e[5],p=e[6],u=e[7],d=e[8],y=e[9],R=e[10],S=e[11],l=e[12],x=e[13],T=e[14],w=e[15],v=i*f-r*m,h=i*p-a*m,n=i*u-s*m,b=r*p-a*f,A=r*u-s*f,$=a*u-s*p,B=d*x-y*l,_=d*T-R*l,L=d*w-S*l,C=y*T-R*x,D=y*w-S*x,M=R*w-S*T,o=v*M-h*D+n*C+b*L-A*_+$*B;return o?(o=1/o,t[0]=(f*M-p*D+u*C)*o,t[1]=(a*D-r*M-s*C)*o,t[2]=(x*$-T*A+w*b)*o,t[3]=(R*A-y*$-S*b)*o,t[4]=(p*L-m*M-u*_)*o,t[5]=(i*M-a*L+s*_)*o,t[6]=(T*n-l*$-w*h)*o,t[7]=(d*$-R*n+S*h)*o,t[8]=(m*D-f*L+u*B)*o,t[9]=(r*L-i*D-s*B)*o,t[10]=(l*A-x*n+w*v)*o,t[11]=(y*n-d*A-S*v)*o,t[12]=(f*_-m*C-p*B)*o,t[13]=(i*C-r*_+a*B)*o,t[14]=(x*h-l*b-T*v)*o,t[15]=(d*b-y*h+R*v)*o,t):null}function $e(t,e,i,r,a){let s=a[0]*e+a[4]*i+a[8]*r+a[12],m=a[1]*e+a[5]*i+a[9]*r+a[13],f=a[2]*e+a[6]*i+a[10]*r+a[14],p=a[3]*e+a[7]*i+a[11]*r+a[15],u=p!==0?1/p:1;t[0]=s*u,t[1]=m*u,t[2]=f*u}function Je(t,e,i,r,a,s,m,f,p,u,d,y,R,S,l,x,T=0){let w=u-m,v=d-f,h=y-p,n=R-m,b=S-f,A=l-p,$=a*A-s*b,B=s*n-r*A,_=r*b-a*n,L=w*$+v*B+h*_;if(L>-1e-7&&L<1e-7)return!1;let C=1/L,D=t-m,M=e-f,o=i-p,V=C*(D*$+M*B+o*_);if(V<-T||V>1+T)return!1;let X=M*h-o*v,g=o*w-D*h,I=D*v-M*w,c=C*(r*X+a*g+s*I);if(c<-T||V+c>1+T)return!1;let P=C*(n*X+b*g+A*I);if(P>1e-4&&P<x.distance){x.distance=P,x.point=[t+r*P,e+a*P,i+s*P];let j=v*A-h*b,G=h*n-w*A,U=w*b-v*n,Z=Math.hypot(j,G,U)||1;return x.normal=[j/Z,G/Z,U/Z],!0}return!1}function Qe(t,e){let i=Array.isArray(t?.nodes)?t.nodes.length:0,r=[];for(let d=0;d<i;d++)r.push(se());if(i===0)return r;let a=new Set;for(let d of t.nodes)if(Array.isArray(d.children))for(let y of d.children)a.add(y);let s=new Set,m=128,f=(d,y,R=0)=>{if(R>m||d<0||d>=i||s.has(d))return;s.add(d);let S=t.nodes[d];if(!S)return;let l=se();if(e&&e[d])l.set(e[d]);else if(S.matrix&&S.matrix.length===16)l.set(S.matrix);else{let T=S.translation||[0,0,0],w=S.rotation||[0,0,0,1],v=S.scale||[1,1,1];He(l,w,T,v)}let x=r[d];if(y?me(x,y,l):x.set(l),Array.isArray(S.children))for(let T of S.children)typeof T=="number"&&f(T,x,R+1)},p=[],u=t.scenes&&t.scenes[t.scene!==void 0?t.scene:0];if(u&&Array.isArray(u.nodes))p.push(...u.nodes);else for(let d=0;d<i;d++)a.has(d)||p.push(d);for(let d of p)f(d,null);for(let d=0;d<i;d++)!a.has(d)&&!p.includes(d)&&f(d,null);return r}var nt=["neutral","reinhard","none","aces","agx"];function je(t){let e=String(t??"").trim().toLowerCase();return nt.includes(e)?e:"neutral"}function It(t){return nt.indexOf(je(t))}function _t(t){return new TextDecoder().decode(t)}var rt=de().decoders;function Ft(t,e){rt.set(t.toLowerCase(),e)}function Me(t){return rt.get(t.toLowerCase())}function it(t){let e=ArrayBuffer.isView(t)?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t,i=new DataView(e);if(e.byteLength<12)throw new Error(`Invalid GLB buffer size: ${e.byteLength} bytes`);let r=i.getUint32(0,!0);if(r!==1179937895){let R=i.getUint8(0);throw R===123||R===32||R===10||R===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),m=12,f=null,p=null;for(;m+8<=s&&m+8<=e.byteLength;){let R=i.getUint32(m,!0),S=i.getUint32(m+4,!0),l=m+8;if(l+R>e.byteLength)throw new Error(`Truncated GLB chunk: required ${l+R} bytes, buffer has ${e.byteLength}`);if(S===1313821514){let x=new Uint8Array(e,l,R),T=_t(x);f=JSON.parse(T,(w,v)=>w==="__proto__"||w==="constructor"||w==="prototype"?void 0:v)}else S===5130562&&(p=e.slice(l,l+R));m=l+R}if(!f)throw new Error("Missing JSON chunk in GLB");let u=f.extensionsRequired||[];if(u.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 R of["EXT_meshopt_compression","KHR_meshopt_compression"])if(u.includes(R)&&!Me("meshopt"))throw new Error(`Model requires ${R}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(u.includes("KHR_texture_basisu")&&!Me("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let d=p||new ArrayBuffer(0),y={gltf:f,bin:d,animations:[]};for(let R of ue)R.onParseGLB?.(y);return y}function Nt(t){return typeof t=="object"&&t!==null&&"gltf"in t&&typeof t.gltf=="object"&&t.gltf!==null&&"bin"in t&&(t.bin instanceof ArrayBuffer||ArrayBuffer.isView(t.bin))}function Ae(t){if(Nt(t))return t;if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))return it(t);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var st=`#version 300 es
16
+ */var Ye=Object.defineProperty,Bt=Object.getOwnPropertyDescriptor,kt=Object.getOwnPropertyNames,Gt=Object.prototype.hasOwnProperty,Ot=(e,t)=>{for(var i in t)Ye(e,i,{get:t[i],enumerable:!0})},Vt=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of kt(t))!Gt.call(e,n)&&n!==i&&Ye(e,n,{get:()=>t[n],enumerable:!(r=Bt(t,n))||r.enumerable});return e},$t=e=>Vt(Ye({},"__esModule",{value:!0}),e),hn={};Ot(hn,{aiTextureKeyOf:()=>mt,buildUSDZZip:()=>It,calculateCRC32:()=>_t,compileInteractivityGraph:()=>Ze,createUSDZBlob:()=>mn,encodeUtf8:()=>je,extractMeshesFromGLB:()=>We,extractMeshesFromScene:()=>ht,generateUSDA:()=>cn,generateUSDAFromMeshes:()=>He,generateUSDZ:()=>Ut,glbToUSDZ:()=>Nt,sanitizeUsdIdentifier:()=>Pe,sanitizeUsdStringLiteral:()=>Ne,sceneToCanvas3D:()=>Ct,sceneToGLB:()=>sn,sceneToUSDZ:()=>ln,withAITextureKey:()=>on}),module.exports=$t(hn);function Ze(e,t,i){let r=[],n=new Map,a=[],l=[],h=[],c=new Map,T=m=>{let y=n.get(m);return y===void 0&&(y=r.length,r.push({op:m}),n.set(m,y)),y},d=m=>{let y=c.get(m);return y===void 0&&(y=h.length,h.push({id:m}),c.set(m,y)),y},g=(m,y={})=>a.push({declaration:T(m),...y})-1,I=(m,y,w)=>l.push({id:m,type:y,value:w})-1,L=m=>({node:m,socket:"value"}),D=i?.interactivity??i?.gltfExtensions?.KHR_interactivity;if(D&&typeof D=="object"){let m=Array.isArray(D.graphs)?D.graphs[D.graph??0]:D;if(m&&Array.isArray(m.nodes)){let y=Array.isArray(m.declarations)?m.declarations:[];for(let w of y)w?.op&&T(w.op);Array.isArray(m.variables)&&l.push(...m.variables);for(let w of m.events||[])w?.id&&d(w.id);for(let w of m.nodes){if(!w||typeof w!="object")continue;let x=w.op||(typeof w.declaration=="number"?y[w.declaration]?.op:"");a.push(x?{...w,declaration:T(x)}:{...w})}}}let O=(m,y,w="translation")=>w==="baseColorFactor"||w==="metallicFactor"||w==="roughnessFactor"?`/materials/${Math.max(0,y)}/pbrMetallicRoughness/${w}`:w==="emissiveFactor"||w==="alphaCutoff"?`/materials/${Math.max(0,y)}/${w}`:w==="visible"?`/nodes/${m}/extensions/KHR_node_visibility/visible`:`/nodes/${m}/${w}`,o=new Map;e.forEach((m,y)=>{typeof m?.name=="string"&&!o.has(m.name)&&o.set(m.name,y)});let f=(m,y)=>typeof m.target=="string"&&o.has(m.target)?o.get(m.target):typeof m.targetNode=="number"?m.targetNode:y,p=m=>{let y=e[m];return(typeof y?.mesh=="number"?t[y.mesh]?.primitives?.[0]?.material:0)??0};for(let m=0;m<e.length;m++){let y=e[m],w=y?.extras?.interactivity;if(!w||typeof w!="object")continue;let x=(typeof y.mesh=="number"?t[y.mesh]?.primitives?.[0]?.material:0)??0,z=_=>{let C=Array.isArray(_)?_:[_],S=[];for(let V=0;V<C.length;V++){let b=C[V];if(!b||typeof b!="object")continue;let P=b.action||"interpolate",E=typeof b.duration=="number"?b.duration:.35;if(P==="toggleTransform"){let j=b.property==="rotation"||b.property==="scale"?b.property:"translation",v=j==="rotation"?y.rotation||[0,0,0,1]:j==="scale"?y.scale||[1,1,1]:y.translation||[0,0,0],$=`/nodes/${m}/${j}`,s=I(`__toggle_${m}_${V}`,"bool",!1),M=g("variable/get",{configuration:{variable:s}}),u=g("math/not",{values:{a:L(M)}}),A=g("variable/set",{configuration:{variable:s},values:{value:L(u)}}),H=g("pointer/interpolate",{configuration:{pointer:$},values:{value:{value:Array.isArray(b.to)?b.to:v},duration:{value:E}}}),q=g("pointer/interpolate",{configuration:{pointer:$},values:{value:{value:Array.isArray(b.from)?b.from:v},duration:{value:E}}});a[A].flows={out:{node:g("flow/branch",{values:{condition:L(M)},flows:{true:{node:H},false:{node:q}}})}},S.push(A)}else if(P==="interpolate"){let j=b.to??b.value;if(j===void 0)continue;let v={value:{value:j},duration:{value:E}};b.from!==void 0&&(v.from={value:b.from}),S.push(g("pointer/interpolate",{configuration:{pointer:typeof b.pointer=="string"?b.pointer:O(f(b,m),p(f(b,m)),b.property)},values:v}))}else if(P==="setProperty"){if(b.value===void 0)continue;S.push(g("pointer/set",{configuration:{pointer:typeof b.pointer=="string"?b.pointer:O(f(b,m),p(f(b,m)),b.property)},values:{value:{value:b.value}}}))}else if(P==="toggleVisibility"){let j=f(b,m),v=I(`__vis_${j}_${V}`,"bool",!0),$=g("variable/get",{configuration:{variable:v}}),s=g("math/not",{values:{a:L($)}}),M=g("variable/set",{configuration:{variable:v},values:{value:L(s)}});a[M].flows={out:{node:g("pointer/set",{configuration:{pointer:`/nodes/${j}/extensions/KHR_node_visibility/visible`},values:{value:L($)}})}},S.push(M)}else if(P==="cycleMaterialColor"&&Array.isArray(b.colors)&&b.colors.length>0){let j=typeof b.duration=="number"?b.duration:.25,v=`/materials/${Math.max(0,x)}/pbrMetallicRoughness/baseColorFactor`,$=I(`__color_idx_${m}_${V}`,"int",0),s=g("variable/get",{configuration:{variable:$}}),M=g("math/add",{values:{a:L(s),b:{value:1}}}),u=g("math/rem",{values:{a:L(M),b:{value:b.colors.length}}}),A=g("variable/set",{configuration:{variable:$},values:{value:L(u)}}),H={};for(let q=0;q<b.colors.length;q++){let Z=b.colors[q],W=Array.isArray(Z)&&Z.length>=3?[Z[0],Z[1],Z[2],Z[3]??1]:[1,1,1,1];H[String(q)]={node:j>0?g("pointer/interpolate",{configuration:{pointer:v},values:{value:{value:W},duration:{value:j}}}):g("pointer/set",{configuration:{pointer:v},values:{value:{value:W}}})}}a[A].flows={out:{node:g("flow/switch",{values:{selection:L(s)},flows:H})}},S.push(A)}else if(P==="playAnimation")S.push(g("animation/start",{configuration:{animation:b.animation??b.clip??0}}));else if(P==="stopAnimation")S.push(g("animation/stop"));else if(P==="sendEvent"){let j={};for(let[v,$]of Object.entries(b.values||{}))j[v]={value:$};S.push(g("event/send",{configuration:{event:d(String(b.event??b.id??"custom"))},values:j}))}}if(!S.length)return null;if(S.length===1)return S[0];let N={};return S.forEach((V,b)=>{N[String(b)]={node:V}}),g("flow/sequence",{flows:N})},R=(_,C,S)=>{let N=z(C);N!==null&&g(_,{...S?{configuration:S}:{},flows:{out:{node:N}}})};if(w.onSelect&&R("pointer/onSelect",w.onSelect,{nodeIndex:m}),w.onHoverIn&&R("pointer/onHoverIn",w.onHoverIn,{nodeIndex:m}),w.onHoverOut&&R("pointer/onHoverOut",w.onHoverOut,{nodeIndex:m}),w.onStart&&R("event/onStart",w.onStart),w.onReceive&&typeof w.onReceive=="object")for(let[_,C]of Object.entries(w.onReceive))R("event/receive",C,{event:d(_)})}return a.length?{graphs:[{declarations:r,nodes:a,variables:l,events:h}],graph:0}:null}var Be="__THREE_LIVE_REGISTRY__";function Ae(){let e=typeof globalThis<"u"?globalThis:{};if(!e[Be]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(e,Be,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{e[Be]=t}}return e[Be]}var fe=Ae().plugins;function dt(e){let t=Ae().plugins;t.some(i=>i.name===e.name)||t.push(e),e.onRegister?.()}function ft(){return Ae().plugins}var zt={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function Je(e,t,i,r){if(!i||i.bufferView===void 0)return null;let n=e.bufferViews?.[i.bufferView];if(!n)return null;let a=Number(i.count??0);if(!Number.isInteger(a)||a<=0)return null;let l=i.componentType??5126,h=zt[l];if(!h)throw new RangeError(`glTF accessor has unsupported componentType ${l}`);let c=h*r,T=n.byteStride&&n.byteStride>0?n.byteStride:c,d=(n.byteOffset||0)+(i.byteOffset||0);if(!Number.isInteger(d)||d<0||T<c||d+(a-1)*T+c>t.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${t.byteLength} bytes)`);if(l===5126&&T===c&&d%4===0)return new Float32Array(t,d,a*r);let g=new DataView(t),I=i.normalized===!0,L=new Float32Array(a*r);for(let D=0;D<a;D++){let O=d+D*T;for(let o=0;o<r;o++){let f=O+o*h,p;switch(l){case 5126:p=g.getFloat32(f,!0);break;case 5120:p=g.getInt8(f),I&&(p=Math.max(p/127,-1));break;case 5121:p=g.getUint8(f),I&&(p/=255);break;case 5122:p=g.getInt16(f,!0),I&&(p=Math.max(p/32767,-1));break;case 5123:p=g.getUint16(f,!0),I&&(p/=65535);break;default:p=g.getUint32(f,!0),I&&(p/=4294967295)}L[D*r+o]=p}}return L}function pt(e,t){let i=Number(t.offset?.[0]??0)||0,r=Number(t.offset?.[1]??0)||0,n=Number(t.scale?.[0]??1),a=Number(t.scale?.[1]??1),l=Number(t.rotation??0)||0,h=Math.cos(l),c=Math.sin(l),T=(Number.isFinite(n)?n:1)*h,d=(Number.isFinite(n)?n:1)*c,g=-(Number.isFinite(a)?a:1)*c,I=(Number.isFinite(a)?a:1)*h;for(let L=0;L+1<e.length;L+=2){let D=e[L],O=e[L+1];e[L]=T*D+d*O+i,e[L+1]=g*D+I*O+r}}function Ee(e,t,i,r=!0){let n=[],a=null;try{for(let[l,h]of[[35633,t],[35632,i]]){let c=e.createShader(l);if(!c){if(r)throw new Error("Shader allocation failed");return null}if(n.push(c),e.shaderSource(c,h),e.compileShader(c),e.getShaderParameter&&!e.getShaderParameter(c,35713)){if(r)throw new Error(`Shader compile error: ${e.getShaderInfoLog(c)}`);return null}}if(a=e.createProgram(),!a){if(r)throw new Error("Program allocation failed");return null}for(let l of n)e.attachShader(a,l);if(e.linkProgram(a),e.getProgramParameter&&!e.getProgramParameter(a,35714)){let l=r?e.getProgramInfoLog(a):null;if(e.deleteProgram?.(a),a=null,r)throw new Error(`Program link error: ${l}`);return null}return a}finally{for(let l of n)a&&e.detachShader?.(a,l),e.deleteShader?.(l)}}function be(){let e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function Qe(e,t,i,r,n){let a=1/Math.tan(t/2);e.fill(0),e[0]=a/i,e[5]=a,e[11]=-1;let l=1/(r-n);return e[10]=(n+r)*l,e[14]=2*n*r*l,e}function et(e,t,i,r){let[n,a,l]=t,[h,c,T]=r,[d,g,I]=i,L=n-d,D=a-g,O=l-I,o=Math.hypot(L,D,O);o<=1e-5?(L=0,D=0,O=1):(L/=o,D/=o,O/=o);let f=c*O-T*D,p=T*L-h*O,m=h*D-c*L;o=Math.hypot(f,p,m),o<=1e-5?(f=0,p=0,m=0):(f/=o,p/=o,m/=o);let y=D*m-O*p,w=O*f-L*m,x=L*p-D*f;return o=Math.hypot(y,w,x),o<=1e-5?(y=0,w=0,x=0):(y/=o,w/=o,x/=o),e[0]=f,e[1]=y,e[2]=L,e[3]=0,e[4]=p,e[5]=w,e[6]=D,e[7]=0,e[8]=m,e[9]=x,e[10]=O,e[11]=0,e[12]=-(f*n+p*a+m*l),e[13]=-(y*n+w*a+x*l),e[14]=-(L*n+D*a+O*l),e[15]=1,e}function ye(e,t,i){let r=t[0],n=t[1],a=t[2],l=t[3],h=t[4],c=t[5],T=t[6],d=t[7],g=t[8],I=t[9],L=t[10],D=t[11],O=t[12],o=t[13],f=t[14],p=t[15],m=i[0],y=i[1],w=i[2],x=i[3];return e[0]=m*r+y*h+w*g+x*O,e[1]=m*n+y*c+w*I+x*o,e[2]=m*a+y*T+w*L+x*f,e[3]=m*l+y*d+w*D+x*p,m=i[4],y=i[5],w=i[6],x=i[7],e[4]=m*r+y*h+w*g+x*O,e[5]=m*n+y*c+w*I+x*o,e[6]=m*a+y*T+w*L+x*f,e[7]=m*l+y*d+w*D+x*p,m=i[8],y=i[9],w=i[10],x=i[11],e[8]=m*r+y*h+w*g+x*O,e[9]=m*n+y*c+w*I+x*o,e[10]=m*a+y*T+w*L+x*f,e[11]=m*l+y*d+w*D+x*p,m=i[12],y=i[13],w=i[14],x=i[15],e[12]=m*r+y*h+w*g+x*O,e[13]=m*n+y*c+w*I+x*o,e[14]=m*a+y*T+w*L+x*f,e[15]=m*l+y*d+w*D+x*p,e}function tt(e,t,i,r){let n=t[0],a=t[1],l=t[2],h=t[3],c=n+n,T=a+a,d=l+l,g=n*c,I=n*T,L=n*d,D=a*T,O=a*d,o=l*d,f=h*c,p=h*T,m=h*d,y=r[0],w=r[1],x=r[2];return e[0]=(1-(D+o))*y,e[1]=(I+m)*y,e[2]=(L-p)*y,e[3]=0,e[4]=(I-m)*w,e[5]=(1-(g+o))*w,e[6]=(O+f)*w,e[7]=0,e[8]=(L+p)*x,e[9]=(O-f)*x,e[10]=(1-(g+D))*x,e[11]=0,e[12]=i[0],e[13]=i[1],e[14]=i[2],e[15]=1,e}function Le(e,t,i=0){let r=t[0],n=t[1],a=t[2],l=t[4],h=t[5],c=t[6],T=t[8],d=t[9],g=t[10],I=g*h-c*d,L=-g*l+c*T,D=d*l-h*T,O=r*I+n*L+a*D;return!O||i>0&&(!Number.isFinite(O)||Math.abs(O)<=i)||(O=1/O,e[0]=I*O,e[1]=L*O,e[2]=D*O,e[3]=(-g*n+a*d)*O,e[4]=(g*r-a*T)*O,e[5]=(-d*r+n*T)*O,e[6]=(c*n-a*h)*O,e[7]=(-c*r+a*l)*O,e[8]=(h*r-n*l)*O),e}function bt(e,t){let i=t[0],r=t[1],n=t[2],a=t[3],l=t[4],h=t[5],c=t[6],T=t[7],d=t[8],g=t[9],I=t[10],L=t[11],D=t[12],O=t[13],o=t[14],f=t[15],p=i*h-r*l,m=i*c-n*l,y=i*T-a*l,w=r*c-n*h,x=r*T-a*h,z=n*T-a*c,R=d*O-g*D,_=d*o-I*D,C=d*f-L*D,S=g*o-I*O,N=g*f-L*O,V=I*f-L*o,b=p*V-m*N+y*S+w*C-x*_+z*R;return b?(b=1/b,e[0]=(h*V-c*N+T*S)*b,e[1]=(n*N-r*V-a*S)*b,e[2]=(O*z-o*x+f*w)*b,e[3]=(I*x-g*z-L*w)*b,e[4]=(c*C-l*V-T*_)*b,e[5]=(i*V-n*C+a*_)*b,e[6]=(o*y-D*z-f*m)*b,e[7]=(d*z-I*y+L*m)*b,e[8]=(l*N-h*C+T*R)*b,e[9]=(r*C-i*N-a*R)*b,e[10]=(D*x-O*y+f*p)*b,e[11]=(g*y-d*x-L*p)*b,e[12]=(h*_-l*S-c*R)*b,e[13]=(i*S-r*_+n*R)*b,e[14]=(O*m-D*w-o*p)*b,e[15]=(d*w-g*m+I*p)*b,e):null}function nt(e,t,i,r,n){let a=n[0]*t+n[4]*i+n[8]*r+n[12],l=n[1]*t+n[5]*i+n[9]*r+n[13],h=n[2]*t+n[6]*i+n[10]*r+n[14],c=n[3]*t+n[7]*i+n[11]*r+n[15],T=c!==0?1/c:1;e[0]=a*T,e[1]=l*T,e[2]=h*T}function gt(e,t,i,r,n,a,l,h,c,T,d,g,I,L,D,O,o=0){let f=T-l,p=d-h,m=g-c,y=I-l,w=L-h,x=D-c,z=n*x-a*w,R=a*y-r*x,_=r*w-n*y,C=f*z+p*R+m*_;if(C>-1e-7&&C<1e-7)return!1;let S=1/C,N=e-l,V=t-h,b=i-c,P=S*(N*z+V*R+b*_);if(P<-o||P>1+o)return!1;let E=V*m-b*p,j=b*f-N*m,v=N*p-V*f,$=S*(r*E+n*j+a*v);if($<-o||P+$>1+o)return!1;let s=S*(y*E+w*j+x*v);if(s>1e-4&&s<O.distance){O.distance=s,O.point=[e+r*s,t+n*s,i+a*s];let M=p*x-m*w,u=m*y-f*x,A=f*w-p*y,H=Math.hypot(M,u,A)||1;return O.normal=[M/H,u/H,A/H],!0}return!1}function rt(e,t){let i=Array.isArray(e?.nodes)?e.nodes.length:0,r=[];for(let d=0;d<i;d++)r.push(be());if(i===0)return r;let n=new Set;for(let d of e.nodes)if(Array.isArray(d.children))for(let g of d.children)n.add(g);let a=new Set,l=128,h=(d,g,I=0)=>{if(I>l||d<0||d>=i||a.has(d))return;a.add(d);let L=e.nodes[d];if(!L)return;let D=be();if(t&&t[d])D.set(t[d]);else if(L.matrix&&L.matrix.length===16)D.set(L.matrix);else{let o=L.translation||[0,0,0],f=L.rotation||[0,0,0,1],p=L.scale||[1,1,1];tt(D,f,o,p)}let O=r[d];if(g?ye(O,g,D):O.set(D),Array.isArray(L.children))for(let o of L.children)typeof o=="number"&&h(o,O,I+1)},c=[],T=e.scenes&&e.scenes[e.scene!==void 0?e.scene:0];if(T&&Array.isArray(T.nodes))c.push(...T.nodes);else for(let d=0;d<i;d++)n.has(d)||c.push(d);for(let d of c)h(d,null);for(let d=0;d<i;d++)!n.has(d)&&!c.includes(d)&&h(d,null);return r}var xt=["neutral","reinhard","none","aces","agx"];function st(e){let t=String(e??"").trim().toLowerCase();return xt.includes(t)?t:"neutral"}function Ht(e){return xt.indexOf(st(e))}function jt(e){return new TextDecoder().decode(e)}var vt=Ae().decoders;function Wt(e,t){vt.set(e.toLowerCase(),t)}function $e(e){return vt.get(e.toLowerCase())}function Mt(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 I=i.getUint8(0);throw I===123||I===32||I===10||I===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 n=i.getUint32(4,!0);if(n!==2)throw new Error(`Unsupported GLB version: ${n}`);let a=i.getUint32(8,!0),l=12,h=null,c=null;for(;l+8<=a&&l+8<=t.byteLength;){let I=i.getUint32(l,!0),L=i.getUint32(l+4,!0),D=l+8;if(D+I>t.byteLength)throw new Error(`Truncated GLB chunk: required ${D+I} bytes, buffer has ${t.byteLength}`);if(L===1313821514){let O=new Uint8Array(t,D,I),o=jt(O);h=JSON.parse(o,(f,p)=>f==="__proto__"||f==="constructor"||f==="prototype"?void 0:p)}else L===5130562&&(c=t.slice(D,D+I));l=D+I}if(!h)throw new Error("Missing JSON chunk in GLB");let T=h.extensionsRequired||[];for(let[I,L]of[["KHR_draco_mesh_compression","draco"],["EXT_meshopt_compression","meshopt"],["KHR_meshopt_compression","meshopt"],["KHR_texture_basisu","ktx2"]])if(T.includes(I)&&!$e(L))throw new Error(`Model requires ${I}. Register a decoder via ThreeLiveElement.registerDecoder('${L}', decoder).`);let d=c||new ArrayBuffer(0),g={gltf:h,bin:d,animations:[],animationsParsed:!1};for(let I of fe)I.onParseGLB?.(g);return g}function ct(e,t=rt(e)){let i=e?.extensions?.KHR_lights_punctual?.lights;if(!Array.isArray(i))return[];let r=[],n=new Set,a=(l,h,c,T)=>{let d=l.type,g=d==="directional"||d==="point"||d==="spot"?d:"ambient",I=h?h[8]:-.5,L=h?h[9]:-1,D=h?h[10]:-.8,O=Math.hypot(I,L,D)||1,o=l.extras?.shadow??c,f=l.name||T,p={type:g,color:l.color||[1,1,1],intensity:l.intensity??1};f&&(p.name=f),h&&(p.position=[h[12],h[13],h[14]]),g==="directional"&&h?p.direction=[I/O,L/O,D/O]:(g==="spot"&&(p.direction=h?[-I/O,-L/O,-D/O]:[0,-1,0],p.innerConeAngle=l.spot?.innerConeAngle??0,p.outerConeAngle=l.spot?.outerConeAngle??Math.PI/4),p.range=l.range),o&&(p.shadow=o),r.push(p)};return(e.nodes||[]).forEach((l,h)=>{let c=l?.extensions?.KHR_lights_punctual?.light;typeof c=="number"&&i[c]&&(n.add(c),a(i[c],t[h],l.extras?.shadow,l.name))}),i.forEach((l,h)=>{n.has(h)||a(l)}),r}function Xt(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 Ie(e){if(Xt(e))return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Mt(e);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var at=`#version 300 es
17
17
  layout(location=0) in vec3 aPos;
18
18
  layout(location=3) in vec3 aOff;
19
19
  layout(location=1) in vec3 aNormal;
@@ -48,7 +48,7 @@ vec2 scaleUV=uUvTransform.zw;
48
48
  if(scaleUV.x==0.0&&scaleUV.y==0.0)scaleUV=vec2(1.0);
49
49
  vUV=aUV*scaleUV+uUvTransform.xy;
50
50
  gl_Position=uMVP*vec4(aPosition,1.0);
51
- }`,Bt=`#version 300 es
51
+ }`,Kt=`#version 300 es
52
52
  precision highp float;
53
53
  in vec3 vNormal,vWorldPos;
54
54
  in vec2 vUV;
@@ -57,117 +57,81 @@ in vec4 vInstTint;
57
57
  #define uBaseColor (uBaseColor*vInstTint)
58
58
  uniform float uMetallic,uRoughness,uEmissive,uEnvIntensity,uExposure;
59
59
  uniform vec2 uClearcoat;
60
- uniform vec3 uCameraPos,uAmbientColor;
61
- uniform sampler2D uBaseColorTexture,uMetallicRoughnessTexture,uNormalTexture,uOcclusionTexture,uEnvironmentMap;
62
- uniform int uHasTexture,uHasMetallicRoughnessTexture,uHasNormalTexture,uHasOcclusionTexture,uHasEnvironmentMap;
60
+ uniform vec3 uCameraPos,uAmbientColor,uEmissiveFactor;
61
+ uniform mat3 uHemi;
62
+ uniform sampler2D uBaseColorTexture,uMetallicRoughnessTexture,uNormalTexture,uOcclusionTexture,uEnvironmentMap,uEmissiveTexture;
63
+ uniform int uHasTexture,uHasMetallicRoughnessTexture,uHasNormalTexture,uHasOcclusionTexture,uHasEnvironmentMap,uHasEmissiveTexture;
63
64
  uniform float uNormalScale,uOcclusionStrength;
64
- /*XRD_U*/
65
+ /*XRD_U*//*SHD_U*/
65
66
  uniform vec2 uViewportSize;
66
67
  uniform vec4 uSectionPlane;
67
68
  uniform int uToneMapping,uNumDirLights,uNumPointLights,uSectionEnabled;
68
69
  uniform vec3 uDirLightDir[2],uDirLightColor[2],uPointLightPos[2],uPointLightColor[2],uPointLightSpotDir[2];
69
70
  uniform vec2 uPointLightSpotCone[2];
70
71
  out vec4 fragColor;
71
-
72
72
  vec2 envBRDF(float r,float n){
73
- vec4 c0=vec4(-1.0,-0.0275,-0.572,0.022),c1=vec4(1.0,0.0425,1.04,-0.04);
74
- vec4 rv=r*c0+c1;
73
+ vec4 c0=vec4(-1.0,-0.0275,-0.572,0.022),c1=vec4(1.0,0.0425,1.04,-0.04),rv=r*c0+c1;
75
74
  float a=min(rv.x*rv.x,exp2(-9.28*n))*rv.x+rv.y;
76
75
  return vec2(-1.04,1.04)*a+rv.zw;
77
76
  }
78
-
79
77
  vec3 F_SchlickRoughness(vec3 F0,float r,float n){
80
78
  return F0+(max(vec3(1.0-r),F0)-F0)*pow(clamp(1.0-n,0.0,1.0),5.0);
81
79
  }
82
-
83
80
  vec3 getStudioRadiance(vec3 R,float r){
84
- vec3 kd=normalize(vec3(0.0,1.0,0.35));
81
+ vec3 kd=normalize(vec3(0.0,1.0,0.35)),fd=normalize(vec3(-0.85,0.45,-0.35));
85
82
  float ki=pow(max(dot(R,kd),0.0),mix(96.0,1.5,r))*mix(2.4,0.5,r);
86
- vec3 fd=normalize(vec3(-0.85,0.45,-0.35));
87
83
  float fi=pow(max(dot(R,fd),0.0),mix(36.0,1.2,r))*mix(1.3,0.35,r);
88
84
  float ri=pow(clamp(1.0-abs(R.y),0.0,1.0),3.5)*mix(0.55,0.22,r);
89
- vec3 ag=mix(vec3(0.06,0.06,0.08),vec3(0.48,0.50,0.55),R.y*0.5+0.5);
90
- return ag+vec3(1.0,0.98,0.94)*ki+vec3(0.85,0.92,1.0)*fi+vec3(0.65,0.72,0.85)*ri;
85
+ return mix(vec3(0.06,0.06,0.08),vec3(0.48,0.50,0.55),R.y*0.5+0.5)+vec3(1.0,0.98,0.94)*ki+vec3(0.85,0.92,1.0)*fi+vec3(0.65,0.72,0.85)*ri;
91
86
  }
92
-
93
- vec3 perturbNormal(vec3 N,vec3 V,vec2 uv,sampler2D normalMap,float scale){
94
- vec3 mapNormal=texture(normalMap,uv).xyz*2.0-1.0;
95
- mapNormal.xy*=scale;
96
- vec3 dp1=dFdx(vWorldPos);
97
- vec3 dp2=dFdy(vWorldPos);
98
- vec2 duv1=dFdx(uv);
99
- vec2 duv2=dFdy(uv);
100
- vec3 dp2perp=cross(dp2,N);
101
- vec3 dp1perp=cross(N,dp1);
102
- vec3 T=dp2perp*duv1.x+dp1perp*duv2.x;
103
- vec3 B=dp2perp*duv1.y+dp1perp*duv2.y;
104
- float invmax=inversesqrt(max(dot(T,T),dot(B,B)));
105
- return normalize(mat3(T*invmax,B*invmax,N)*normalize(mapNormal));
87
+ vec3 perturbNormal(vec3 N,vec3 V,vec2 uv,sampler2D m,float s){
88
+ vec3 q=texture(m,uv).xyz*2.0-1.0;q.xy*=s;
89
+ vec3 p1=dFdx(vWorldPos),p2=dFdy(vWorldPos),c2=cross(p2,N),c1=cross(N,p1);
90
+ vec2 u1=dFdx(uv),u2=dFdy(uv);
91
+ vec3 T=c2*u1.x+c1*u2.x,B=c2*u1.y+c1*u2.y;
92
+ float k=inversesqrt(max(dot(T,T),dot(B,B)));
93
+ return normalize(mat3(T*k,B*k,N)*normalize(q));
106
94
  }
107
-
108
95
  vec2 equirectangularUV(vec3 dir){
109
96
  vec3 d=normalize(dir);
110
- float u=atan(d.z,d.x)*0.15915494309+0.5;
111
- float v=asin(clamp(d.y,-1.0,1.0))*0.31830988618+0.5;
112
- return vec2(u,1.0-v);
97
+ return vec2(atan(d.z,d.x)*0.15915494309+0.5,0.5-asin(clamp(d.y,-1.0,1.0))*0.31830988618);
113
98
  }
114
-
115
- vec3 neutralToneMapping(vec3 color){
116
- const float startCompression=0.76;
117
- const float desaturation=0.15;
118
- float x=min(color.r,min(color.g,color.b));
119
- float offset=x<0.08?x-6.25*x*x:0.04;
120
- color-=offset;
121
- float peak=max(color.r,max(color.g,color.b));
122
- if(peak<startCompression)return color;
123
- const float d=1.0-startCompression;
124
- float newPeak=1.0-d*d/(peak+d-startCompression);
125
- color*=newPeak/peak;
126
- float g=1.0-1.0/(desaturation*(peak-newPeak)+1.0);
127
- return mix(color,newPeak*vec3(1.0),g);
99
+ vec3 neutralToneMapping(vec3 c){
100
+ float x=min(c.r,min(c.g,c.b));
101
+ c-=x<0.08?x-6.25*x*x:0.04;
102
+ float p=max(c.r,max(c.g,c.b));
103
+ if(p<0.76)return c;
104
+ float n=1.0-0.0576/(p-0.52);
105
+ c*=n/p;
106
+ return mix(c,vec3(n),1.0-1.0/(0.15*(p-n)+1.0));
128
107
  }
129
-
130
- vec3 acesToneMapping(vec3 color){
131
- color*=0.6;
132
- return clamp((color*(2.51*color+0.03))/(color*(2.43*color+0.59)+0.14),0.0,1.0);
108
+ vec3 acesToneMapping(vec3 c){
109
+ c*=0.6;return clamp((c*(2.51*c+0.03))/(c*(2.43*c+0.59)+0.14),0.0,1.0);
133
110
  }
134
-
135
- vec3 agxToneMapping(vec3 color){
136
- color=max(color,vec3(0.0));
137
- vec3 inset=vec3(
138
- 0.84247906*color.r+0.0784336*color.g+0.07922375*color.b,
139
- 0.04232824*color.r+0.87846864*color.g+0.07916613*color.b,
140
- 0.04237565*color.r+0.0784336*color.g+0.87914297*color.b);
141
- vec3 ev=clamp((log2(max(inset,vec3(1e-6)))+12.47393)/16.5,0.0,1.0);
142
- vec3 x2=ev*ev;
143
- vec3 x4=x2*x2;
144
- vec3 s=15.5*x4*x2-40.14*x4*ev+31.96*x4-6.868*x2*ev+0.4298*x2+0.1191*ev-0.00232;
145
- vec3 outset=vec3(
146
- 1.196879*s.r-0.09802088*s.g-0.09902974*s.b,
147
- -0.05289685*s.r+1.15190313*s.g-0.09896118*s.b,
148
- -0.05297164*s.r-0.09804345*s.g+1.15107367*s.b);
149
- return clamp(pow(max(outset,vec3(0.0)),vec3(2.2)),0.0,1.0);
111
+ vec3 agxToneMapping(vec3 c){
112
+ c=max(c,vec3(0.0));
113
+ vec3 i=mat3(0.84247906,0.04232824,0.04237565,0.0784336,0.87846864,0.0784336,0.07922375,0.07916613,0.87914297)*c;
114
+ vec3 e=clamp((log2(max(i,vec3(1e-6)))+12.47393)/16.5,0.0,1.0),x2=e*e,x4=x2*x2;
115
+ vec3 s=15.5*x4*x2-40.14*x4*e+31.96*x4-6.868*x2*e+0.4298*x2+0.1191*e-0.00232;
116
+ vec3 o=mat3(1.196879,-0.05289685,-0.05297164,-0.09802088,1.15190313,-0.09804345,-0.09902974,-0.09896118,1.15107367)*s;
117
+ return clamp(pow(max(o,vec3(0.0)),vec3(2.2)),0.0,1.0);
150
118
  }
151
-
152
- vec3 applyToneMapping(vec3 color,int mode){
153
- if(mode==0)return neutralToneMapping(color);
154
- if(mode==1)return color/(color+vec3(1.0));
155
- if(mode==3)return acesToneMapping(color);
156
- if(mode==4)return agxToneMapping(color);
157
- return color;
119
+ vec3 applyToneMapping(vec3 c,int m){
120
+ return m==0?neutralToneMapping(c):m==1?c/(c+vec3(1.0)):m==3?acesToneMapping(c):m==4?agxToneMapping(c):c;
158
121
  }
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);
122
+ vec3 evalLight(vec3 L,vec3 V,vec3 N,vec3 b,float e,float w){
123
+ float h=max(dot(N,normalize(L+V)),0.0);
124
+ return b*max(dot(N,L),0.0)*0.75+vec3(pow(h,e)*w+uClearcoat.x*pow(h,mix(64.0,512.0,1.0-uClearcoat.y))*0.35);
163
125
  }
164
126
 
165
127
  void main(){
166
128
  if(uSectionEnabled==1&&dot(vWorldPos,uSectionPlane.xyz)>uSectionPlane.w)discard;
167
129
  vec4 base=uBaseColor;
168
130
  if(uHasTexture==1)base*=texture(uBaseColorTexture,vUV);
131
+ if(base.a<0.004)discard;
132
+ vec3 em=uHasEmissiveTexture==1?uEmissiveFactor*texture(uEmissiveTexture,vUV).rgb:uEmissiveFactor;
169
133
  if(length(vNormal)<1e-4&&uHasTexture==1){
170
- vec3 unlit=base.rgb+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
134
+ vec3 unlit=base.rgb+em+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
171
135
  fragColor=vec4(unlit,base.a);
172
136
  return;
173
137
  }
@@ -199,7 +163,7 @@ float specWeight=mix(0.22*gloss,1.0,metallic);
199
163
  vec3 directLight=vec3(0.0);
200
164
  for(int i=0;i<2;i++){
201
165
  if(i>=uNumDirLights)break;
202
- directLight+=evalLight(normalize(uDirLightDir[i]),V,N,base.rgb,specExp,specWeight)*uDirLightColor[i];
166
+ directLight+=evalLight(normalize(uDirLightDir[i]),V,N,base.rgb,specExp,specWeight)*uDirLightColor[i]/*SHD_D*/;
203
167
  }
204
168
  for(int i=0;i<2;i++){
205
169
  if(i>=uNumPointLights)break;
@@ -208,7 +172,7 @@ float dist=length(toLight);
208
172
  vec3 L=toLight/max(dist,0.0001);
209
173
  float spotAtt=clamp((dot(-L,uPointLightSpotDir[i])-uPointLightSpotCone[i].y)/max(uPointLightSpotCone[i].x-uPointLightSpotCone[i].y,0.0001),0.0,1.0);
210
174
  spotAtt*=spotAtt;
211
- directLight+=evalLight(L,V,N,base.rgb,specExp,specWeight)*uPointLightColor[i]*spotAtt/(1.0+0.09*dist+0.032*dist*dist);
175
+ directLight+=evalLight(L,V,N,base.rgb,specExp,specWeight)*uPointLightColor[i]*spotAtt/(1.0+0.09*dist+0.032*dist*dist)/*SHD_P*/;
212
176
  }
213
177
 
214
178
  vec3 R=reflect(-V,N);
@@ -228,8 +192,9 @@ envDiffuse=mix(vec3(0.10,0.10,0.12),vec3(0.52,0.54,0.58),N.y*0.5+0.5);
228
192
  }
229
193
 
230
194
  vec3 kD=(vec3(1.0)-F)*(1.0-metallic);
195
+ directLight+=kD*base.rgb*mix(uHemi[1],uHemi[0],dot(N,uHemi[2])*0.5+0.5)*occ;
231
196
  vec3 diffuseIBL=kD*base.rgb*(uAmbientColor+envDiffuse*0.5)*occ;
232
- vec3 color=directLight+(diffuseIBL+specularIBL)*uEnvIntensity+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
197
+ vec3 color=directLight+(diffuseIBL+specularIBL)*uEnvIntensity+em+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
233
198
  if(uClearcoat.x>0.0){
234
199
  vec3 ccF=F_SchlickRoughness(vec3(0.04),uClearcoat.y,NoV)*uClearcoat.x;
235
200
  color=color*(vec3(1.0)-ccF)+getStudioRadiance(R,uClearcoat.y)*ccF*uEnvIntensity;
@@ -239,103 +204,147 @@ color=applyToneMapping(color,uToneMapping);
239
204
  float outAlpha=base.a;
240
205
  /*XRD_O*/
241
206
  fragColor=vec4(color,outAlpha);
242
- }`,kt=`#version 300 es
207
+ }`,qt=`#version 300 es
243
208
  layout(location=0) in vec3 aPosition;
244
209
  uniform mat4 uMVP;
245
- void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,Ut=`#version 300 es
210
+ void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,Yt=`#version 300 es
246
211
  precision highp float;
247
212
  uniform vec4 uColorId;
248
213
  out vec4 fragColor;
249
- void main(){fragColor=uColorId;}`;function Xe(t,e,i){let r={};for(let a of i)r[a]=t.getUniformLocation(e,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 ot(){let t=de().xrDepthShader;return{fs:Bt.replace("/*XRD_U*/",t?.uniformsGLSL||"").replace("/*XRD_O*/",t?.occlusionGLSL||""),uniforms:t?[...et,...t.uniformNames]:et}}function Gt(t){if(typeof t!="string")return null;let e=t.trim();if(!e||/[\x00-\x1f\x7f]/.test(e))return null;let i=e.toLowerCase();return i.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(e)?e:null:i.startsWith("https://")||i.startsWith("blob:")?e:i.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(e)||/(^|[\\/])\.\.([\\/]|$)/.test(e)?null:e}function ze(t,e,i,r,a,s,m,f){if(r===void 0||!e.accessors?.[r])return null;let p=Ve(e,i,e.accessors[r],s);if(!p)return null;f&&(p=p.slice(),Ye(p,f));let u=t.createBuffer();return m.push(u),t.bindBuffer(34962,u),t.bufferData(34962,p,35044),t.enableVertexAttribArray(a),t.vertexAttribPointer(a,s,5126,!1,0,0),p}function We(t){let e=Number(t);return Number.isFinite(e)?Math.max(0,e):1}function at(t,e,i){let r=ot(),a=st,s=r.fs,m=!1;for(let p of ue)if(p.onResolveShader){let u=p.onResolveShader(e,i,a,s);u&&(a=u.vs,s=u.fs,m=!0)}let f=m?Ee(t,a,s):null;return{program:f,uniforms:f?Xe(t,f,r.uniforms):null}}function Ot(t,e,i){let r=e.instanceMatrices;if(!r||r.length<16||typeof t.vertexAttribDivisor!="function"||typeof t.drawElementsInstanced!="function")return!1;let a=r.length>>4,s=e.instanceColors,m=new Float32Array(a*20);for(let p=0;p<a;p++)m.set(r.subarray(p*16,p*16+16),p*20),m[p*20+16]=s?s[p*3]:1,m[p*20+17]=s?s[p*3+1]:1,m[p*20+18]=s?s[p*3+2]:1,m[p*20+19]=1;let f=t.createBuffer();i.push(f),t.bindBuffer(34962,f),t.bufferData(34962,m,35044);for(let p=0;p<5;p++)t.enableVertexAttribArray(8+p),t.vertexAttribPointer(8+p,4,5126,!1,80,p*16),t.vertexAttribDivisor(8+p,1);return!0}function Vt(t,e){let i=t.materials?.[e?.material];if(!i)return null;let r=[i.pbrMetallicRoughness?.baseColorTexture,i.pbrMetallicRoughness?.metallicRoughnessTexture,i.normalTexture,i.occlusionTexture,i.emissiveTexture];for(let a of r){let s=a?.extensions?.KHR_texture_transform;if(s&&typeof s=="object")return s}return null}var un=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),ut=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Ce(t,e){e.indices?t.drawElements(4,e.indexCount,e.indexType,0):t.drawArrays(4,0,e.indexCount)}function ct(t,e){let i=t?.pbrMetallicRoughness,r=i?.baseColorFactor,a=t?.extensions?.KHR_materials_clearcoat,s=m=>m!==void 0&&e[m.index]?e[m.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(t?.normalTexture),normalScale:t?.normalTexture?.scale??1,occlusionTexture:s(t?.occlusionTexture),occlusionStrength:t?.occlusionTexture?.strength??1,isTransmissive:(t?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function lt(t,e,i){let r=new Set,a=s=>{s&&!r.has(s)&&(r.add(s),t.deleteTexture(s))};for(let s of e)for(let m of s.primitives){if(m.vao&&t.deleteVertexArray(m.vao),m.buffers)for(let p of m.buffers)t.deleteBuffer(p);a(m.texture),a(m.metallicRoughnessTexture),a(m.normalTexture),a(m.occlusionTexture);let f=new Set;m.customProgram&&f.add(m.customProgram);for(let p of m.programCache?.values()??[])p.program&&f.add(p.program);for(let p of f)t.deleteProgram(p)}if(i)for(let s of i)a(s)}function tt(t,e,i=ut,r){let a={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return Ht(t,e,i,r,a)}catch(s){let m=a.mesh&&!a.meshes.includes(a.mesh)?[...a.meshes,a.mesh]:a.meshes;lt(t,m,a.gpuTextures),a.vao&&t.deleteVertexArray(a.vao);for(let f of a.buffers)t.deleteBuffer(f);throw s}}function Ht(t,e,i,r,a){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:s}=e,m=Me("meshopt");m?.decodeBufferViews&&m.decodeBufferViews(s,e);let f=e.bin,p=[];a.meshes=p;let u=[],d=s.extensions?.KHR_materials_variants;d&&Array.isArray(d.variants)&&d.variants.forEach((M,o)=>{u.push(typeof M?.name=="string"&&M.name?M.name:`Variant_${o}`)});let y=Qe(s),R=[];if(Array.isArray(s.nodes))for(let M=0;M<s.nodes.length;M++){let o=s.nodes[M];o.mesh!==void 0&&s.meshes&&s.meshes[o.mesh]&&R.push({node:o,nodeIdx:M,meshIdx:o.mesh})}let S=R.length>0?R:(s.meshes||[]).map((M,o)=>({node:M,nodeIdx:-1,meshIdx:o})),l=[],x=Array.isArray(e.lights)&&e.lights.length>0?e.lights:Array.isArray(s.asset?.extras?.lights)&&s.asset.extras.lights.length>0?s.asset.extras.lights:null;if(x)for(let M of x)l.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 o of M){let V=o.type==="directional"?"directional":o.type==="point"?"point":o.type==="spot"?"spot":"ambient";l.push({type:V,color:o.color||[1,1,1],intensity:o.intensity!==void 0?o.intensity:1})}}if(l.length===0&&(l.push({type:"ambient",color:[1,1,1],intensity:.35}),l.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 T=[];if(a.gpuTextures=T,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 o=s.textures[M],V=s.images[o.source];if(V){let X=t.createTexture();t.bindTexture(3553,X),t.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),t.texParameteri(3553,10242,10497),t.texParameteri(3553,10243,10497),t.texParameteri(3553,10241,9729),t.texParameteri(3553,10240,9729);let g=I=>{t.bindTexture(3553,X),t.texImage2D(3553,0,6408,6408,5121,I),t.generateMipmap(3553),r?.()};if(V.bufferView!==void 0){let I=s.bufferViews[V.bufferView],c=I.byteOffset||0,P=new Blob([f.slice(c,c+I.byteLength)],{type:V.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(P).then(g).catch(()=>{})}else if(V.uri){let I=Gt(V.uri);if(I){let c=new Image;c.crossOrigin="anonymous",c.referrerPolicy="no-referrer",c.onload=()=>g(c),c.src=I}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",V.uri)}T.push(X)}else T.push(null)}}let w=[1/0,1/0,1/0],v=[-1/0,-1/0,-1/0],h=0,n=0;for(let M=0;M<S.length;M++){let o=S[M],V=s.meshes[o.meshIdx],X=o.nodeIdx>=0?y[o.nodeIdx]:se(),g=new Float32Array(9);be(g,X);let I={name:o.node.name||V.name||`Mesh_${o.meshIdx}`,nodeIndex:o.nodeIdx,transform:X,normalMatrix:g,primitives:[],extras:o.node.extras||V.extras,...o.node?.visible===!1||o.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{}};a.mesh=I;let c=o.node?.extensions?.EXT_mesh_gpu_instancing;if(c&&c.attributes&&typeof c.attributes=="object"){let P=c.attributes,j=P.TRANSLATION!==void 0?s.accessors?.[P.TRANSLATION]:null,G=P.ROTATION!==void 0?s.accessors?.[P.ROTATION]:null,U=P.SCALE!==void 0?s.accessors?.[P.SCALE]:null,Z=P._COLOR_0!==void 0?s.accessors?.[P._COLOR_0]:null,E=Number(j?.count??G?.count??U?.count??0);if(!Number.isFinite(E)||E<0||E>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${E}`);if(E>0){let q=(N,Q)=>{if(!N||N.bufferView===void 0||!s.bufferViews?.[N.bufferView])return null;let Zt=N.componentType??5126,Qt=Jt=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${Jt})`),null);if(Zt!==5120&&Zt!==5121&&Zt!==5122&&Zt!==5123&&Zt!==5126)return Qt(`componentType ${Zt}`);if(!(Number(N.count)>=E))return Qt(`count ${N.count} < ${E}`);let Y=null;try{Y=Ve(s,f,{...N,count:E},Q)}catch{return Qt("out of bounds")}return!Y||!Y.every(Number.isFinite)?Qt("non-finite value"):Y},k=q(j,3),H=q(G,4),F=q(U,3),K=Z?.type==="VEC4"?4:3,O=q(Z,K),W=new Float32Array(E*16),z=se();for(let N=0;N<E;N++){let Q=k?[k[N*3],k[N*3+1],k[N*3+2]]:[0,0,0],Zt=H?[H[N*4],H[N*4+1],H[N*4+2],H[N*4+3]]:[0,0,0,1],Qt=F?[F[N*3],F[N*3+1],F[N*3+2]]:[1,1,1];He(z,Zt,Q,Qt),W.set(z,N*16)}if(I.instanceMatrices=W,O){let N=new Float32Array(E*3);for(let Q=0;Q<E;Q++)N[Q*3]=O[Q*K],N[Q*3+1]=O[Q*K+1],N[Q*3+2]=O[Q*K+2];I.instanceColors=N}}}for(let P of V.primitives||[]){if(P.extensions?.KHR_draco_mesh_compression){let Y=Me("draco");Y&&Y.decodePrimitive(s,P,f)}let j=[],G=t.createVertexArray();a.vao=G,a.buffers=j,t.bindVertexArray(G);let U=Ot(t,I,j),Z=s.accessors[P.attributes.POSITION],E=Number(Z?.count??0);if(!Number.isFinite(E)||E<0||h+E>i.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${i.maxVertices}).`);if(h+=E,Z?.min&&Z?.max){let Y=Jt=>{for(let te=0;te<3;te++){let ne=Jt[12+te],ee=Jt[12+te];for(let ie=0;ie<3;ie++){let ae=Jt[ie*4+te]*Z.min[ie],re=Jt[ie*4+te]*Z.max[ie];ne+=ae<re?ae:re,ee+=ae>re?ae:re}ne<w[te]&&(w[te]=ne),ee>v[te]&&(v[te]=ee)}};if(I.instanceMatrices&&I.instanceMatrices.length>=16){let Jt=I.instanceMatrices.length>>4,te=se();for(let ne=0;ne<Jt;ne++){let ee=I.instanceMatrices.subarray(ne*16,ne*16+16);me(te,X,ee),Y(te)}}else Y(X)}let q=ze(t,s,f,P.attributes.POSITION,0,3,j);ze(t,s,f,P.attributes.NORMAL,1,3,j),ze(t,s,f,P.attributes.TEXCOORD_0,2,2,j,Vt(s,P));let k=0,H=5123,F=null;if(P.indices!==void 0){let Y=s.accessors[P.indices],Jt=(s.bufferViews[Y.bufferView].byteOffset||0)+(Y.byteOffset||0);if(k=Number(Y.count??0),!Number.isFinite(k)||k<0||n+k>i.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${i.maxIndices}).`);n+=k,H=Y.componentType===5125?5125:5123;let te=t.createBuffer();j.push(te),t.bindBuffer(34963,te),Y.componentType===5125?F=new Uint32Array(f,Jt,Y.count):Y.componentType===5121?F=Uint16Array.from(new Uint8Array(f,Jt,Y.count)):F=Jt%2===0?new Uint16Array(f,Jt,Y.count):new Uint16Array(f.slice(Jt,Jt+Y.count*2)),t.bufferData(34963,F,35044)}else k=Z.count;let K={};for(let Y of ue)if(Y.onBuildPrimitiveVAO){let Jt=Y.onBuildPrimitiveVAO(t,G,P,s,f);Jt&&(K[Y.name]=Jt)}t.bindVertexArray(null);let O=s.materials&&P.material!==void 0?s.materials[P.material]:null,{program:W,uniforms:z}=at(t,P,O),N=ct(O,T),Q=!!(O?.extensions?.KHR_materials_transmission||K.materials?.isTransmissive),Zt=P.extensions?.KHR_materials_variants?.mappings,Qt=Array.isArray(Zt)?Zt.filter(Y=>Y&&typeof Y.material=="number"&&Array.isArray(Y.variants)).map(Y=>({material:Y.material|0,variants:Y.variants.map(Jt=>Number(Jt)|0)})):void 0;I.primitives.push({vao:G,instanced:U,indexCount:k,indexType:H,...N,positions:q,indices:F,buffers:j,materialIndex:P.material,defaultMaterialIndex:P.material,variantMappings:Qt,primitiveDef:P,programCache:new Map([[P.material??-1,{program:W,uniforms:z}]]),pluginData:K,customProgram:W,customUniforms:z,isTransmissive:Q})}p.push(I)}isFinite(w[0])||(w=[-1,-1,-1]),isFinite(v[0])||(v=[1,1,1]);let b=[(w[0]+v[0])/2,(w[1]+v[1])/2,(w[2]+v[2])/2],A=v[0]-w[0],$=v[1]-w[1],B=v[2]-w[2],_=Math.max(Math.hypot(A,$,B)/2,.5),L=[w[0],w[1],w[2]],C=[v[0],v[1],v[2]],D=e.animations;if(!D){for(let M of ue)if(M.onParseGLB?.(e),e.animations){D=e.animations;break}}return D||(D=[]),{meshes:p,bounds:{center:b,radius:_,min:L,max:C},lights:l,animations:D,worldMatrices:y,gpuTextures:T,availableVariants:u}}function Te(t){let e=t.customTarget||t.bounds.center,i=t.currDistance*Math.cos(t.currPhi);return[e[0]+i*Math.sin(t.currTheta),e[1]+t.currDistance*Math.sin(t.currPhi),e[2]+i*Math.cos(t.currTheta)]}var Le=class{constructor(t,e,i){this.supportsInstanceOffsets=!0,this.meshes=[],this.backdropMeshes=[],this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]},this.lights=[],this.modelRootMatrix=se(),this.clearColor=[0,0,0,0],this.envIntensity=1,this.exposure=1,this.shadowIntensity=0,this.shadowSoftness=.5,this.toneMapping="neutral",this.environmentTexture=null,this.animations=[],this.currentClip=null,this.animationTime=0,this.isPlayingAnimation=!1,this.autoplay=!1,this.animationName="",this.gpuTextures=[],this.availableVariants=[],this.activeVariantName=null,this.gltf=null,this.worldMatrices=[],this.initialNodeTransforms=[],this.projMatrix=se(),this.viewMatrix=se(),this.activeViewMatrix=null,this.modelMatrix=se(),this.mvpMatrix=se(),this.normalMatrix=new Float32Array(9),this.initialTheta=.6,this.initialPhi=.35,this.initialDistance=null,this.customDistance=!1,this.distanceMode="auto",this.initialCustomTarget=null,this.customTarget=null,this.fov=Math.PI/4,this.minTheta=-1/0,this.maxTheta=1/0,this.minPhi=-Math.PI*.48,this.maxPhi=Math.PI*.48,this.minDistanceLimit=null,this.maxDistanceLimit=null,this.activePointers=new Map,this.isPanning=!1,this.targetTheta=.6,this.currTheta=.6,this.targetPhi=.35,this.currPhi=.35,this.targetDistance=3,this.currDistance=3,this.autoRotate=!1,this.autoRotateSpeed=Math.PI/6,this.autoRotateDelay=3e3,this.lastInteractionTime=-1/0,this.turntableRotation=0,this.isPointerDown=!1,this.interactive=!0,this.skyboxTexture=null,this.lastPointerX=0,this.lastPointerY=0,this.totalDragDist=0,this.selectedMeshName="",this.pickFbo=null,this.pickTexture=null,this.pickDepth=null,this.pickFboWidth=0,this.pickFboHeight=0,this.animFrameId=null,this.isVisible=!0,this.xrSessionActive=!1,this.lastTime=0,this.lastReportedTheta=-999,this.lastReportedPhi=-999,this.lastReportedZoom=-999,this.boundPointerDown=null,this.boundPointerMove=null,this.boundPointerUp=null,this.boundWheel=null,this.boundKeyDown=null,this.boundContextMenu=null,this.boundSetCamera=null,this.boundResetCamera=null,this.contextLost=!1,this.lastGlbData=null,this.boundContextLost=null,this.boundContextRestored=null,this.stereoSBS=!1,this.renderErrorReported=!1,this.xrDepthState={enabled:!1,texture:null,uvTransform:se(),rawValueToMeters:.001,format:0},this.container=t;let r,a;if(e&&typeof e.getContext=="function"?(r=e,a=i):(a=e,r=a?.canvas),!r){let f=t.querySelector("canvas");f||(f=document.createElement("canvas"),f.style.width="100%",f.style.height="100%",f.style.display="block",f.style.touchAction="none",t.prepend(f)),r=f}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=We(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=je(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 m=r.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!m)throw new Error("WebGL2 not supported");this.gl=m,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(t,e){Ft(t,e)}static getDecoder(t){return Me(t)}setupContextLossHandling(){let t=this.canvas;typeof t?.addEventListener=="function"&&(this.boundContextLost=e=>{e.preventDefault?.(),this.contextLost=!0,this.stop()},this.boundContextRestored=()=>this.restoreContext(),t.addEventListener("webglcontextlost",this.boundContextLost),t.addEventListener("webglcontextrestored",this.boundContextRestored))}initGlState(){let t=this.gl,e=ot();this.renderProg=Ee(t,st,e.fs),this.pickProg=Ee(t,kt,Ut),this.uRender=Xe(t,this.renderProg,e.uniforms),this.uPick=Xe(t,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let t=this.gl;this.contextLost=!1,this.initGlState();for(let e of ue)e.onContextRestored?.(t,this);this.meshes=[],this.gpuTextures=[],this.environmentTexture=null,this.lastGlbData&&this.loadGLBData(this.lastGlbData,this.lastLimits),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}setupPickingFbo(){let t=this.gl;if(typeof t.createFramebuffer!="function")return;this.pickFbo=t.createFramebuffer(),this.pickTexture=t.createTexture(),this.pickDepth=t.createRenderbuffer();let e=Math.max(1,this.canvas.width),i=Math.max(1,this.canvas.height);this.pickFboWidth=e,this.pickFboHeight=i,t.bindTexture(3553,this.pickTexture),t.texImage2D(3553,0,6408,e,i,0,6408,5121,null),t.texParameteri(3553,10241,9728),t.texParameteri(3553,10240,9728),t.bindRenderbuffer(36161,this.pickDepth),t.renderbufferStorage(36161,33189,e,i),t.bindFramebuffer(36160,this.pickFbo),t.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),t.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),t.bindFramebuffer(36160,null)}resizePickingFbo(t,e){if(!this.pickFbo)return;let i=this.gl,r=Math.max(1,t),a=Math.max(1,e);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(t,e){let{meshes:i,bounds:r,lights:a,animations:s,worldMatrices:m,gpuTextures:f,availableVariants:p}=tt(this.gl,t,e,()=>this.render());if(this.lastGlbData=t,this.lastLimits=e,this.disposeMeshGpuResources(),this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.meshes=i,this.bounds=r,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=a,this.animations=s||[],this.worldMatrices=m||[],this.gpuTextures=f||[],this.availableVariants=p||[],this.gltf=t.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(t.gltf?.nodes))for(let y of t.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 ue)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 u=t.exposure??t.gltf?.extras?.exposure??t.gltf?.asset?.extras?.exposure;u!==void 0&&(this.exposure=We(u));let d=t.environmentIntensity??t.gltf?.extras?.environmentIntensity??t.gltf?.asset?.extras?.environmentIntensity;d!==void 0&&(this.envIntensity=Math.max(0,Number(d)||0)),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(t){this.loadGLBData(it(t))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let t of ue)t.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(t){this.loadGLBData(Ae(t))}setBackdropGLB(t,e){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!t){this.update(0),this.render();return}let i=Ae(t),{meshes:r}=tt(this.gl,i,ut,()=>this.render());if(e)for(let a of r)a.transform[12]+=e[0],a.transform[13]+=e[1],a.transform[14]+=e[2],be(a.normalMatrix,a.transform);this.backdropMeshes=r,this.update(0),this.render()}setClearColor(t,e,i,r=1){this.clearColor=[t,e,i,r]}updateMeshTransforms(t){for(let e=0;e<this.meshes.length;e++){let i=this.meshes[e],r;t instanceof Map?r=t.get(i.name)??t.get(e):Array.isArray(t)?r=t[e]:t&&typeof t=="object"&&(Object.prototype.hasOwnProperty.call(t,i.name)?r=t[i.name]:Object.prototype.hasOwnProperty.call(t,e)&&(r=t[e])),r&&r.length===16&&(i.transform.set(r),be(i.normalMatrix,i.transform))}}bindLights(t=this.uRender){let e=this.gl,i=[.28,.28,.28],r=[],a=[],s=[],m=[],f=[],p=[];for(let u of this.lights){let d=u.color||[1,1,1],y=u.intensity!==void 0?u.intensity:1;if(u.type==="ambient")i=[d[0]*y,d[1]*y,d[2]*y];else if(u.type==="directional"&&r.length<6){let R=u.direction||[.5,1,.8];r.push(R[0],R[1],R[2]),a.push(d[0]*y,d[1]*y,d[2]*y)}else if((u.type==="point"||u.type==="spot")&&s.length<6){let R=u.position||[0,0,0];if(s.push(R[0],R[1],R[2]),m.push(d[0]*y,d[1]*y,d[2]*y),u.type==="spot"){let S=u.direction||[0,-1,0],l=Math.max(.01,Math.min(Math.PI/2,u.outerConeAngle??Math.PI/3)),x=Math.max(0,Math.min(l-1e-4,u.innerConeAngle??0));f.push(S[0],S[1],S[2]),p.push(Math.cos(x),Math.cos(l))}else f.push(0,-1,0),p.push(-2,-3)}}r.length===0&&(r.push(.5,1,.8),a.push(1,1,1)),e.uniform3fv(t.uAmbientColor,i),e.uniform1i(t.uNumDirLights,r.length/3),r.length>0&&(e.uniform3fv(t.uDirLightDir,r),e.uniform3fv(t.uDirLightColor,a)),e.uniform1i(t.uNumPointLights,s.length/3),s.length>0&&(e.uniform3fv(t.uPointLightPos,s),e.uniform3fv(t.uPointLightColor,m),t.uPointLightSpotDir&&e.uniform3fv(t.uPointLightSpotDir,f),t.uPointLightSpotCone&&e.uniform2fv(t.uPointLightSpotCone,p)),e.uniform1f(t.uEnvIntensity,this.envIntensity)}setExposure(t){this.exposure=We(t)}getExposure(){return this.exposure}setShadow(t,e){this.shadowIntensity=Math.max(0,Math.min(1,Number(t)||0)),e!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(e)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(t){this.toneMapping=je(t)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(t){for(let e of ue)if(e.setEnvironmentImage){await e.setEnvironmentImage(this,t);return}}async setSkyboxImage(t){for(let e of ue)if(e.setSkyboxImage){await e.setSkyboxImage(this,t);return}}setInteractive(t){this.interactive=t}isInteractive(){return this.interactive}getCameraOrbit(){let t=this.currTheta,e=this.currPhi,i=this.currDistance;return{theta:t,phi:e,radius:i,toString(){return`${t.toFixed(4)}rad ${e.toFixed(4)}rad ${i.toFixed(4)}m`}}}getCameraTarget(){let t=this.customTarget||this.bounds.center;return{x:t[0],y:t[1],z:t[2],toString(){return`${t[0].toFixed(4)}m ${t[1].toFixed(4)}m ${t[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let t=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return t.map((e,i)=>{let r=this.meshes.flatMap(u=>u.primitives.filter(d=>d.materialIndex===i||t.length===1&&d.materialIndex===void 0)),a=r[0],s=a?[...a.baseColor]:e.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],m=a?a.metallic:e.pbrMetallicRoughness?.metallicFactor??.1,f=a?a.roughness:e.pbrMetallicRoughness?.roughnessFactor??.5,p={baseColorFactor:s,metallicFactor:m,roughnessFactor:f,setBaseColorFactor:u=>{let d=[u[0],u[1],u[2],u[3]??1];p.baseColorFactor=d,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.baseColorFactor=d);for(let y of r)y.baseColor=d;this.render()},setMetallicFactor:u=>{p.metallicFactor=u,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.metallicFactor=u);for(let d of r)d.metallic=u;this.render()},setRoughnessFactor:u=>{p.roughnessFactor=u,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.roughnessFactor=u);for(let d of r)d.roughness=u;this.render()}};return{name:e.name||`Material_${i}`,pbrMetallicRoughness:p}})}playAnimation(t){if(this.animations.length!==0){if(t){let e=this.animations.find(i=>i.name===t);e&&(this.currentClip=e)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(t=>t.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(t){let e=this.applyVariantMaterial(t);return e&&this.gl&&this.render(),e}applyVariantMaterial(t){let e=t===null||t==="",i=-1;if(e)this.activeVariantName=null;else{if(i=this.availableVariants.indexOf(t),i<0)return!1;this.activeVariantName=t}let r=this.gltf?.materials;if(!Array.isArray(r))return e;for(let a of this.meshes)for(let s of a.primitives){let m=s.defaultMaterialIndex;if(!e&&Array.isArray(s.variantMappings)){for(let p of s.variantMappings)if(Array.isArray(p.variants)&&p.variants.includes(i)){m=p.material;break}}let f=m!==void 0?r[m]:void 0;s.materialIndex=f?m:void 0,Object.assign(s,ct(f,this.gpuTextures)),this.applyPrimitiveProgram(s,s.materialIndex,f??null)}return!0}applyPrimitiveProgram(t,e,i){if(!this.gl||!t.primitiveDef)return;t.programCache??(t.programCache=new Map);let r=e??-1,a=t.programCache.get(r);a||(a=at(this.gl,{...t.primitiveDef,material:e},i),t.programCache.set(r,a)),t.customProgram=a.program,t.customUniforms=a.uniforms,t.pluginData&&(t.pluginData.materials=t.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(t){this.autoplay=t,t?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(t){this.animationName=t,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(t)}evaluateAnimation(t){for(let e of ue)if(e.evaluateAnimation){e.evaluateAnimation(this,t);return}}setTarget(t,e,i){this.customTarget=[t,e,i],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(t){let e=Math.max(10,Math.min(90,t));this.fov=e*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(t){if(this.distanceMode=t,!this.customDistance){let e=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=e,this.targetDistance=e,this.currDistance=e,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(t){t.minTheta!==void 0&&(this.minTheta=t.minTheta*Math.PI/180),t.maxTheta!==void 0&&(this.maxTheta=t.maxTheta*Math.PI/180),t.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,t.minPhi*Math.PI/180)),t.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,t.maxPhi*Math.PI/180)),t.minDistance!==void 0&&(this.minDistanceLimit=t.minDistance),t.maxDistance!==void 0&&(this.maxDistanceLimit=t.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){return{minTheta:isFinite(this.minTheta)?this.minTheta*180/Math.PI:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*180/Math.PI:void 0,minPhi:this.minPhi*180/Math.PI,maxPhi:this.maxPhi*180/Math.PI,minDistance:this.minDistanceLimit!==null?this.minDistanceLimit:void 0,maxDistance:this.maxDistanceLimit!==null?this.maxDistanceLimit:void 0}}clampTheta(t){return Math.max(this.minTheta,Math.min(this.maxTheta,t))}clampPhi(t){return Math.max(this.minPhi,Math.min(this.maxPhi,t))}clampDistance(t){let e=this.minDistanceLimit!==null?this.minDistanceLimit:this.bounds?this.bounds.radius*.5:.1,i=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(e,Math.min(i,t))}setCamera(t,e,i,r){t!==void 0&&(this.targetTheta=this.clampTheta(t*Math.PI/180)),e!==void 0&&(this.targetPhi=this.clampPhi(e*Math.PI/180)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(i)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/r))}setInitialCamera(t,e,i,r){if(t!==void 0&&(this.initialTheta=this.clampTheta(t*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),e!==void 0&&(this.initialPhi=this.clampPhi(e*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),i!==void 0&&i>0){let 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(t,e){let i=se();me(i,this.projMatrix,this.viewMatrix);let[r,a,s]=t,m=e?e[0]:0,f=e?e[1]:0,p=e?e[2]:0,u=this.modelRootMatrix;u&&(r=u[0]*t[0]+u[4]*t[1]+u[8]*t[2]+u[12],a=u[1]*t[0]+u[5]*t[1]+u[9]*t[2]+u[13],s=u[2]*t[0]+u[6]*t[1]+u[10]*t[2]+u[14],e&&(m=u[0]*e[0]+u[4]*e[1]+u[8]*e[2],f=u[1]*e[0]+u[5]*e[1]+u[9]*e[2],p=u[2]*e[0]+u[6]*e[1]+u[10]*e[2]));let d=i[0]*r+i[4]*a+i[8]*s+i[12],y=i[1]*r+i[5]*a+i[9]*s+i[13],R=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 l=d/S,x=y/S,T=R/S,w=this.canvas.getBoundingClientRect(),v=w.width||this.canvas.clientWidth||this.canvas.width||300,h=w.height||this.canvas.clientHeight||this.canvas.height||150,n=(l*.5+.5)*v,b=(-x*.5+.5)*h,A=l>=-1.1&&l<=1.1&&x>=-1.1&&x<=1.1&&T>=-1&&T<=1;if(A&&e){let[$,B,_]=Te(this),L=[r-$,a-B,s-_];m*L[0]+f*L[1]+p*L[2]>.05&&(A=!1)}return{x:n,y:b,z:T,visible:A}}setSelectedMesh(t){this.selectedMeshName=t||""}getSelectedMesh(){return this.selectedMeshName}setupEvents(){let t=this.canvas,e=()=>typeof performance<"u"?performance.now():Date.now();this.boundContextMenu=i=>{i.preventDefault()},t.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=i=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=e(),this.lastPointerX=i.clientX,this.lastPointerY=i.clientY,this.totalDragDist=0,this.activePointers.set(i.pointerId,{x:i.clientX,y:i.clientY}),this.isPanning=i.button===2||i.shiftKey||this.activePointers.size===2,t.setPointerCapture(i.pointerId))},t.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=i=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=e();let r=this.activePointers.get(i.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},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 m=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],f=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],p=this.customTarget?[...this.customTarget]:[...this.bounds.center],u=this.currDistance/Math.max(t.clientHeight||300,1)*1.5;p[0]+=(-a*m[0]+s*f[0])*u,p[1]+=(-a*m[1]+s*f[1])*u,p[2]+=(-a*m[2]+s*f[2])*u,this.customTarget=p}else this.targetTheta=this.clampTheta(this.targetTheta-a*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},t.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=i=>{this.lastInteractionTime=e(),this.activePointers.delete(i.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{t.releasePointerCapture(i.pointerId)}catch{}if(this.totalDragDist<5&&i.button===0){let r=t.getBoundingClientRect(),a=Math.floor((i.clientX-r.left)*(t.width/Math.max(r.width,1))),s=Math.floor((i.clientY-r.top)*(t.height/Math.max(r.height,1)));this.performMeshPick(a,s,!0)}},t.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=i=>{if(!this.interactive)return;i.preventDefault(),this.lastInteractionTime=e();let r=Math.exp(i.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},t.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=i=>{let r=i.detail||{};r.reset?this.resetCamera():this.setCamera(r.theta,r.phi,r.distance,r.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),t.tabIndex!==void 0&&t.tabIndex<0&&(t.tabIndex=0),t.getAttribute?.("role")||t.setAttribute?.("role","region"),t.getAttribute?.("aria-label")||t.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=i=>{if(this.interactive){switch(i.key){case"ArrowLeft":this.targetTheta=this.clampTheta(this.targetTheta-.1);break;case"ArrowRight":this.targetTheta=this.clampTheta(this.targetTheta+.1);break;case"ArrowUp":this.targetPhi=this.clampPhi(this.targetPhi+.08);break;case"ArrowDown":this.targetPhi=this.clampPhi(this.targetPhi-.08);break;case"+":case"=":this.targetDistance=this.clampDistance(this.targetDistance*.9);break;case"-":case"_":this.targetDistance=this.clampDistance(this.targetDistance*1.1);break;case"Home":this.resetCamera();break;default:return}this.lastInteractionTime=e(),i.preventDefault()}},t.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let t=(i,r,a)=>{this[a]&&(i.removeEventListener(r,this[a]),this[a]=null)},e=this.canvas;t(e,"webglcontextlost","boundContextLost"),t(e,"webglcontextrestored","boundContextRestored"),t(e,"contextmenu","boundContextMenu"),t(e,"pointerdown","boundPointerDown"),t(e,"pointermove","boundPointerMove"),t(e,"pointerup","boundPointerUp"),t(e,"wheel","boundWheel"),t(e,"keydown","boundKeyDown"),t(this.container,"setCamera","boundSetCamera"),t(this.container,"resetCamera","boundResetCamera")}raycastFromScreenPoint(t,e){let i=this.canvas,r=i.getBoundingClientRect(),a=i.width||300,s=i.height||300,m=r.width>0?Math.floor((t-r.left)*(a/r.width)):Math.floor(t),f=r.height>0?Math.floor((e-r.top)*(s/r.height)):Math.floor(e);return this.performMeshPick(m,f,!1)}performMeshPick(t,e,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);t=this.mapStereoPickX(t,a);let m=se();me(m,this.projMatrix,this.viewMatrix);let f=[],p=Math.max(0,Math.min(a-1,t)),u=Math.max(0,Math.min(s-1,s-1-e));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 A=this.meshes[b];if(A.visible===!1||A.isPluginMesh)continue;let $=b+1,B=($&255)/255,_=($>>8&255)/255,L=($>>16&255)/255;r.uniform4f(this.uPick.uColorId,B,_,L,1),me(this.modelMatrix,this.modelRootMatrix,A.transform);let C=A.instanceMatrices;if(C&&C.length>=16){let D=C.length>>4,M=se();for(let o of A.primitives){r.bindVertexArray(o.vao);for(let V=0;V<D;V++)me(M,this.modelMatrix,C.subarray(V*16,V*16+16)),me(this.mvpMatrix,m,M),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),Ce(r,o)}}else{me(this.mvpMatrix,m,this.modelMatrix),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let D of A.primitives)r.bindVertexArray(D.vao),Ce(r,D)}}let h=new Uint8Array(4);r.readPixels(p,u,1,1,6408,5121,h),r.bindFramebuffer(36160,null);let n=h[0]+(h[1]<<8)+(h[2]<<16);n>0&&n<=this.meshes.length&&(f=[this.meshes[n-1]])}f.length===0&&(f=this.meshes.filter(h=>h.visible!==!1));let d=null,y=1/0,R=[0,0,0],S=[0,1,0],[l,x,T]=Te(this),w=se();for(let h of f){me(w,this.modelRootMatrix,h.transform);let n=h.instanceMatrices,b=n&&n.length>=16?n.length>>4:1;for(let A=0;A<b;A++){n&&n.length>=16?me(this.modelMatrix,w,n.subarray(A*16,A*16+16)):this.modelMatrix.set(w),me(this.mvpMatrix,m,this.modelMatrix);let $=se();if(!Ze($,this.mvpMatrix))continue;let B=(p+.5)/a*2-1,_=(u+.5)/s*2-1,L=[0,0,0],C=[0,0,0];$e(L,B,_,-1,$),$e(C,B,_,1,$);let D=C[0]-L[0],M=C[1]-L[1],o=C[2]-L[2],V=Math.hypot(D,M,o)||1,X=D/V,g=M/V,I=o/V,c={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((P=>{for(let j of h.primitives){if(!j.positions)continue;let G=j.positions,U=j.indices,Z=Math.floor(U?U.length/3:G.length/9);for(let E=0;E<Z;E++){let q=U?U[E*3]:E*3,k=U?U[E*3+1]:E*3+1,H=U?U[E*3+2]:E*3+2;Je(L[0],L[1],L[2],X,g,I,G[q*3],G[q*3+1],G[q*3+2],G[k*3],G[k*3+1],G[k*3+2],G[H*3],G[H*3+1],G[H*3+2],c,P)}}})(1e-4),isFinite(c.distance)){let P=c.point[0],j=c.point[1],G=c.point[2],U=this.modelMatrix,Z=U[0]*P+U[4]*j+U[8]*G+U[12],E=U[1]*P+U[5]*j+U[9]*G+U[13],q=U[2]*P+U[6]*j+U[10]*G+U[14],k=Z-l,H=E-x,F=q-T,K=Math.hypot(k,H,F);if(K<y){be(this.normalMatrix,this.modelMatrix);let O=this.normalMatrix,W=c.normal[0],z=c.normal[1],N=c.normal[2],Q=O[0]*W+O[3]*z+O[6]*N,Zt=O[1]*W+O[4]*z+O[7]*N,Qt=O[2]*W+O[5]*z+O[8]*N,Y=Math.hypot(Q,Zt,Qt)||1;Q/=Y,Zt/=Y,Qt/=Y,Q*k+Zt*H+Qt*F>0&&(Q=-Q,Zt=-Zt,Qt=-Qt),d=h,y=Math.round(K*1e3)/1e3,R=[Math.round(Z*1e3)/1e3,Math.round(E*1e3)/1e3,Math.round(q*1e3)/1e3],S=[Math.round(Q*1e3)/1e3,Math.round(Zt*1e3)/1e3,Math.round(Qt*1e3)/1e3]}}}}if(!d)return null;let v={meshIndex:this.meshes.indexOf(d),meshName:d.name,nodeIndex:d.nodeIndex,distance:y,hitPoint:R,normal:S,screenX:t,screenY:e};if(i){for(let h of ue)h.onMeshSelect?.(this,v);this.opts.onMeshClick&&this.opts.onMeshClick(v),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:v}))}return v}mapStereoPickX(t,e){if(!this.stereoSBS||this.xrSessionActive||e<2)return t;let i=Math.max(1,Math.floor(e*.5)),r=t>=i,a=r?t-i:t,s=r?Math.max(1,e-i):i,m=(a+.5)/s*2-1;return Math.floor((m*.5+1)*.5*e)}setStereoSBS(t){this.stereoSBS=!!t,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let t=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),e=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);Se(this.projMatrix,this.fov,t,.1,e);let i=this.customTarget||this.bounds.center;Pe(this.viewMatrix,Te(this),i,[0,1,0]),me(this.mvpMatrix,this.projMatrix,this.viewMatrix),be(this.normalMatrix,this.modelMatrix)}resize(){let t=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),e=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.floor(e.width*t)),r=Math.max(1,Math.floor(e.height*t));this.canvas.width!==i||this.canvas.height!==r?(this.canvas.width=i,this.canvas.height=r,this.resizePickingFbo(i,r),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(t){let e=this.xrSessionActive;if(this.xrSessionActive=t,e&&!t){this.xrDepthState.enabled=!1;for(let i of ue)i.onXRSessionEnd?.(this);if(this.lastTime=typeof performance<"u"?performance.now():Date.now(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(i){this.reportRenderError(i)}}}reportRenderError(t){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",t))}stepXRUpdate(t){for(let e of ue)e.onUpdate?.(this,t)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let t=e=>{if(this.animFrameId===null)return;let i=Math.min(Math.max((e-this.lastTime)/1e3,0),.1);if(this.lastTime=e,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(i),this.render()}catch(r){this.reportRenderError(r)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(t))};this.animFrameId=requestAnimationFrame(t)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(t){this.autoRotate=t}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(t){this.autoRotateSpeed=t}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(t){this.autoRotateDelay=Math.max(0,Number(t)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(t=0){this.turntableRotation=Number(t)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let t=Math.cos(this.turntableRotation),e=Math.sin(this.turntableRotation),i=this.bounds.center[0],r=this.bounds.center[2],a=this.modelRootMatrix;a[0]=t,a[1]=0,a[2]=-e,a[3]=0,a[4]=0,a[5]=1,a[6]=0,a[7]=0,a[8]=e,a[9]=0,a[10]=t,a[11]=0,a[12]=i-(t*i+e*r),a[13]=0,a[14]=r-(-e*i+t*r),a[15]=1}setVisible(t){this.isVisible=t}update(t){for(let s of ue)s.onUpdate?.(this,t);let e=typeof performance<"u"?performance.now():Date.now();if(!this.isPointerDown&&this.autoRotate&&e-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*t,this.updateTurntableMatrix();for(let s of ue)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(t,e,i,r,a=!0,s=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(t);let m=t?.transform?.inverse?.matrix||this.viewMatrix,f=t?.projectionMatrix||this.projMatrix,p=t?.transform?.position,u=p?[p.x,p.y,p.z]:[0,1.6,0];e?this.modelRootMatrix.set(e):i&&e&&this.modelRootMatrix.set(e),this.render({viewMatrix:m,projMatrix:f,eyePos:u,viewport:r,eye:t?.eye||"none",clear:s>0?!1:t?.eye!=="right",isAR:a})}render(t){if(this.contextLost)return;if(!t&&this.stereoSBS){let v=Math.max(2,this.canvas.width||2),h=Math.max(1,this.canvas.height||1),n=Math.max(1,Math.floor(v*.5)),b=Math.max(1,v-n),A=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),$=this.customTarget||this.bounds.center,[B,_,L]=Te(this),C=Math.cos(this.currTheta),D=-Math.sin(this.currTheta),M=.032,o=se(),V=se(),X=[B-C*M,_,L-D*M],g=[$[0]-C*M*.25,$[1],$[2]-D*M*.25];Se(o,this.fov,n/h,.1,A),Pe(V,X,g,[0,1,0]);let I=se(),c=se(),P=[B+C*M,_,L+D*M],j=[$[0]+C*M*.25,$[1],$[2]+D*M*.25];Se(I,this.fov,b/h,.1,A),Pe(c,P,j,[0,1,0]),this.render({viewMatrix:V,projMatrix:o,eyePos:X,viewport:[0,0,n,h],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:c,projMatrix:I,eyePos:P,viewport:[n,0,b,h],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,v,h);return}let e=this.gl,i=0,r=0,a=this.canvas.width,s=this.canvas.height;t?.viewport?(i=t.viewport[0],r=t.viewport[1],a=t.viewport[2],s=t.viewport[3],e.viewport(i,r,a,s)):e.viewport(0,0,this.canvas.width,this.canvas.height),e.enable(2929),(!t||t.clear!==!1)&&(t?.isAR?e.clearColor(0,0,0,0):e.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),e.clear(16640));let m=se(),f=t?.viewMatrix??this.viewMatrix;this.activeViewMatrix=f,me(m,t?.projMatrix??this.projMatrix,f);let p=de().xrDepthShader,u=It(this.toneMapping),[d,y,R]=t?t.eyePos:Te(this);for(let v of ue)v.onBeforeDrawScene?.(this,e,m,[d,y,R],u);let S=t?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&S===0)return;let l=t?.eye||"none",x=!1,T=S>0?[...this.backdropMeshes,...this.meshes]:this.meshes,w=v=>{for(let h=0;h<T.length;h++){let n=T[h];if(n.visible===!1)continue;let b=this.selectedMeshName!==""&&n.name===this.selectedMeshName;h<S||n.worldSpace===!0||n.name==="__xr_reticle__"?this.modelMatrix.set(n.transform):me(this.modelMatrix,this.modelRootMatrix,n.transform),me(this.mvpMatrix,m,this.modelMatrix),be(n.normalMatrix,this.modelMatrix);let A=n.extras?.xr?.stereo||n.userData?.xr?.stereo,$=0,B=0,_=1,L=1;A==="sbs"?(_=.5,$=l==="right"?.5:0):A==="ou"&&(L=.5,B=l==="right"?.5:0);for(let C of n.primitives){let D=!!C.isTransmissive;if(!v&&D){x=!0;continue}if(v&&!D)continue;let M=C.customProgram||this.renderProg,o=C.customUniforms||this.uRender;e.useProgram(M),e.vertexAttrib3f(3,0,0,0),o.uInstanced&&e.uniform1i(o.uInstanced,0),e.uniform1i(o.uToneMapping,u),e.uniform1f(o.uEnvIntensity,this.envIntensity),o.uExposure&&e.uniform1f(o.uExposure,this.exposure),e.uniform3f(o.uCameraPos,d,y,R),e.uniform1f(o.uEmissive,b?1:0),e.uniformMatrix4fv(o.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(o.uModel,!1,this.modelMatrix),e.uniformMatrix3fv(o.uNormalMatrix,!1,n.normalMatrix),o.uUvTransform&&e.uniform4f(o.uUvTransform,$,B,_,L),o.uViewportSize&&e.uniform2f(o.uViewportSize,Math.max(1,a),Math.max(1,s)),p?.bind(e,o,this.xrDepthState,f,[i,r,Math.max(1,a),Math.max(1,s)]),this.environmentTexture?(e.activeTexture(33988),e.bindTexture(3553,this.environmentTexture),e.uniform1i(o.uEnvironmentMap,4),e.uniform1i(o.uHasEnvironmentMap,1)):e.uniform1i(o.uHasEnvironmentMap,0),this.bindLights(o),o.uSectionEnabled&&e.uniform1i(o.uSectionEnabled,0);for(let X of ue)X.onBeforeDrawPrimitive?.(e,M,C,n,this.worldMatrices||[],this.gltf);e.uniform4fv(o.uBaseColor,C.baseColor),e.uniform1f(o.uMetallic,C.metallic),e.uniform1f(o.uRoughness,C.roughness),o.uClearcoat&&e.uniform2f(o.uClearcoat,C.clearcoat??0,C.clearcoatRoughness??.04),C.texture?(e.activeTexture(33984),e.bindTexture(3553,C.texture),e.uniform1i(o.uBaseColorTexture,0),e.uniform1i(o.uHasTexture,1)):e.uniform1i(o.uHasTexture,0),C.metallicRoughnessTexture?(e.activeTexture(33985),e.bindTexture(3553,C.metallicRoughnessTexture),e.uniform1i(o.uMetallicRoughnessTexture,1),e.uniform1i(o.uHasMetallicRoughnessTexture,1)):e.uniform1i(o.uHasMetallicRoughnessTexture,0),C.normalTexture?(e.activeTexture(33986),e.bindTexture(3553,C.normalTexture),e.uniform1i(o.uNormalTexture,2),e.uniform1i(o.uHasNormalTexture,1),e.uniform1f(o.uNormalScale,C.normalScale)):e.uniform1i(o.uHasNormalTexture,0),C.occlusionTexture?(e.activeTexture(33987),e.bindTexture(3553,C.occlusionTexture),e.uniform1i(o.uOcclusionTexture,3),e.uniform1i(o.uHasOcclusionTexture,1),e.uniform1f(o.uOcclusionStrength,C.occlusionStrength)):e.uniform1i(o.uHasOcclusionTexture,0),e.bindVertexArray(C.vao);let V=n.instanceMatrices;if(C.instanceCount!==void 0)e.drawElementsInstanced(4,C.indexCount,C.indexType,0,C.instanceCount);else if(V&&V.length>=16&&C.instanced&&o.uInstanced&&o.uViewProj){let X=V.length>>4;e.uniform1i(o.uInstanced,1),e.uniformMatrix4fv(o.uViewProj,!1,m),C.indices?e.drawElementsInstanced(4,C.indexCount,C.indexType,0,X):e.drawArraysInstanced(4,0,C.indexCount,X),e.uniform1i(o.uInstanced,0)}else if(V&&V.length>=16){let X=V.length>>4,g=n.instanceColors,I=se(),c=new Float32Array(9),P=[C.baseColor[0],C.baseColor[1],C.baseColor[2],C.baseColor[3]];for(let j=0;j<X;j++)me(I,this.modelMatrix,V.subarray(j*16,j*16+16)),me(this.mvpMatrix,m,I),be(c,I),e.uniformMatrix4fv(o.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(o.uModel,!1,I),e.uniformMatrix3fv(o.uNormalMatrix,!1,c),g&&(P[0]=C.baseColor[0]*g[j*3],P[1]=C.baseColor[1]*g[j*3+1],P[2]=C.baseColor[2]*g[j*3+2],P[3]=C.baseColor[3],e.uniform4fv(o.uBaseColor,P)),Ce(e,C)}else Ce(e,C)}}};if(w(!1),x){for(let v of ue)v.onBeforeTransmissivePass?.(e,this);w(!0)}for(let v of ue)v.onAfterRender?.(e,this,m,t?.eye??"none",[i,r,a,s],t?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(t,e){lt(this.gl,t,e)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let t=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let e of ue)e.onDestroy?.(t,this);this.environmentTexture&&(t.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&t.deleteProgram(this.renderProg),this.pickProg&&t.deleteProgram(this.pickProg),this.pickFbo&&t.deleteFramebuffer(this.pickFbo),this.pickTexture&&t.deleteTexture(this.pickTexture),this.pickDepth&&t.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};Le.registerPlugin=Ke,Le.getRegisteredPlugins=qe;function $t(t){return t+3&-4}var J=(t,e)=>typeof t=="number"&&Number.isFinite(t)?t:e;function ft(t,e){let i=e,r=1;for(;t.has(i);)i=`${e}_${r++}`;return t.add(i),i}function dt(t,e=0){let[i,r,a,,s,m,f,,p,u,d,,y,R,S]=Array.from({length:15},(c,P)=>J(t[e+P],P%5===0?1:0)),l=Math.hypot(i,r,a),x=Math.hypot(s,m,f),T=Math.hypot(p,u,d);i*(m*d-u*f)-s*(r*d-u*a)+p*(r*f-m*a)<0&&(l=-l);let w=Math.abs(l)>1e-8?1/l:0,v=Math.abs(x)>1e-8?1/x:0,h=Math.abs(T)>1e-8?1/T:0,n=i*w,b=r*w,A=a*w,$=s*v,B=m*v,_=f*v,L=p*h,C=u*h,D=d*h,M=n+B+D,o=0,V=0,X=0,g=1;if(M>0){let c=.5/Math.sqrt(M+1);g=.25/c,o=(_-C)*c,V=(L-A)*c,X=(b-$)*c}else if(n>B&&n>D){let c=2*Math.sqrt(Math.max(0,1+n-B-D));c>1e-8&&(g=(_-C)/c,o=.25*c,V=($+b)/c,X=(L+A)/c)}else if(B>D){let c=2*Math.sqrt(Math.max(0,1+B-n-D));c>1e-8&&(g=(L-A)/c,o=($+b)/c,V=.25*c,X=(_+C)/c)}else{let c=2*Math.sqrt(Math.max(0,1+D-n-B));c>1e-8&&(g=(b-$)/c,o=(L+A)/c,V=(_+C)/c,X=.25*c)}let I=Math.hypot(o,V,X,g);return I>1e-8&&Number.isFinite(I)?(o/=I,V/=I,X/=I,g/=I):(o=0,V=0,X=0,g=1),{t:[y,R,S],r:[o,V,X,g],s:[l,x,T]}}function zt(t){let e={};return t.grab&&(e.interactable={mode:typeof t.grab=="string"?t.grab:"2-hand"},e.movable={scaleInZ:!!t.scale,minScale:typeof t.scale=="object"?t.scale.min??.1:.1,maxScale:typeof t.scale=="object"?t.scale.max??10:10}),t.billboard&&(e.billboard={mode:typeof t.billboard=="string"?t.billboard:"capsule"}),t.follow&&(e.follow={target:typeof t.follow=="object"?t.follow.mode??"head":t.follow}),t.anchor&&(e.anchor={plane:t.anchor}),t.physics&&t.physics!=="none"&&(e.rigidbody={type:t.physics}),e}var ge=(t,e,i,r)=>typeof t=="number"&&Number.isFinite(t)?Math.max(e,Math.min(i,t)):r;function pt(t){let e=t?.audioEmitter??t?.spatialAudio??(typeof t?.audio=="object"&&t.audio&&("preset"in t.audio||"distanceModel"in t.audio||"coneInnerAngle"in t.audio||"maxDistance"in t.audio||"volume"in t.audio)?t.audio:typeof t?.audio=="string"&&/^(hum|reactor|wind|beacon|geiger|chimeLoop|machinery|water)$/.test(t.audio)?{preset:t.audio}:void 0);if(!e||typeof e=="object"&&e.enabled===!1)return null;let i=typeof e=="string"?{preset:e}:e,r=typeof i.src=="string"&&!/[\x00-\x20\\%]|^\s*(javascript|data|file|http):/i.test(i.src)?i.src:void 0,a=typeof i.preset=="string"?i.preset:void 0;return!r&&!a?null:{ae:i,src:r,preset:a,volume:ge(i.volume,0,2,.6),loop:typeof i.loop=="boolean"?i.loop:!0,isGlobal:i.type==="global"||i.positional===!1}}function bt(t,e){return gt(t,e)[0]}function gt(t,e){t.updateMatrixWorld(!0);let i=[],r=0,a=[],s=[],m=[],f=[],p=new Set,u=[],d=[],y=new Map,R=[],S=[],l=[],x=new Map,T=[],w=[];function v(g){let I=y.get(g);if(I!==void 0)return I;I=d.length,y.set(g,I);let c=g,P=c.color?.r??.8,j=c.color?.g??.8,G=c.color?.b??.8,U=c.opacity??1,Z={baseColorFactor:[P,j,G,U],metallicFactor:c.metalness??0,roughnessFactor:c.roughness??.5},E={};if(c.map){let H="";typeof c.map=="string"?H=c.map:typeof c.map.source=="string"?H=c.map.source:typeof c.map.image=="string"&&(H=c.map.image);let F=H.trim(),K=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(K){let W=x.get(K);if(W===void 0){let z=R.length;R.push({uri:K}),S.length===0&&S.push({magFilter:9729,minFilter:9987,wrapS:10497,wrapT:10497}),W=l.length,l.push({sampler:0,source:z}),x.set(K,W)}Z.baseColorTexture={index:W}}let O=c.map.avgColor;Array.isArray(O)&&O.length>=3&&(E.avgColor=[O[0],O[1],O[2]])}let q={name:c.name||"",pbrMetallicRoughness:Z,doubleSided:c.side===2||!!c.doubleSided,...Object.keys(E).length>0?{extras:E}:{}};if(c.emissive&&(c.emissive.r>0||c.emissive.g>0||c.emissive.b>0)){let H=c.emissiveIntensity??1;q.emissiveFactor=[c.emissive.r*H,c.emissive.g*H,c.emissive.b*H]}let k={};return c.clearcoat&&c.clearcoat>0&&(k.KHR_materials_clearcoat={clearcoatFactor:c.clearcoat,clearcoatRoughnessFactor:c.clearcoatRoughness||0}),c.sheen&&c.sheen>0&&(k.KHR_materials_sheen={sheenColorFactor:c.sheenColor?[c.sheenColor.r,c.sheenColor.g,c.sheenColor.b]:[1,1,1],sheenRoughnessFactor:c.sheenRoughness||0}),c.transmission&&c.transmission>0&&(k.KHR_materials_transmission={transmissionFactor:c.transmission}),c.thickness&&c.thickness>0&&(k.KHR_materials_volume={thicknessFactor:c.thickness,attenuationDistance:c.attenuationDistance??1/0,attenuationColor:c.attenuationColor?[c.attenuationColor.r,c.attenuationColor.g,c.attenuationColor.b]:[1,1,1]}),c.ior!==void 0&&c.ior!==1.5&&(k.KHR_materials_ior={ior:c.ior}),c.dispersion&&c.dispersion>0&&(k.KHR_materials_dispersion={dispersion:c.dispersion}),c.iridescence&&c.iridescence>0&&(k.KHR_materials_iridescence={iridescenceFactor:c.iridescence,iridescenceIor:c.iridescenceIOR??1.3}),Object.keys(k).length>0&&(q.extensions=k),d.push(q),I}function h(g,I){let c=new Uint8Array(g.buffer,g.byteOffset,g.byteLength),P=$t(c.byteLength),j=new Uint8Array(P);j.set(c),i.push(j);let G=a.length;return a.push({buffer:0,byteOffset:r,byteLength:c.byteLength,target:I}),r+=P,G}function n(g,I,c,P,j,G,U){let Z=h(g,c),E=s.length,q={bufferView:Z,byteOffset:0,componentType:P,count:j,type:I};return G&&(q.min=G),U&&(q.max=U),s.push(q),E}t.traverse(g=>{if(g.isLight||g.color&&g.intensity!==void 0){let I=g.matrixWorld?.elements,c=J(I?I[12]:g.position?.x,0),P=J(I?I[13]:g.position?.y,0),j=J(I?I[14]:g.position?.z,0),G=g.target,U=G?.parent?G?.matrixWorld?.elements:void 0,Z=J(U?U[12]:G?.position?.x,0),E=J(U?U[13]:G?.position?.y,0),q=J(U?U[14]:G?.position?.z,0),k=Z-c,H=E-P,F=q-j,K=Math.hypot(k,H,F),O=Math.max(.01,Math.min(Math.PI/2,J(g.angle,Math.PI/3))),W=Math.max(0,Math.min(1,J(g.penumbra,0)));w.push({type:g.type,color:[g.color.r,g.color.g,g.color.b],intensity:g.intensity,position:[c,P,j],...g.type==="spot"?{direction:K>1e-6?[k/K,H/K,F/K]:[0,-1,0],outerConeAngle:O,innerConeAngle:Math.max(0,O*(1-W)),range:Math.max(0,J(g.distance,0))}:g.type==="point"?{range:Math.max(0,J(g.distance,0))}:{}})}});let b=[],A=new Set([t]),$=[];if(Array.isArray(t.children))for(let g=t.children.length-1;g>=0;g--)$.push({obj:t.children[g],parentKids:b});for(;$.length>0;){let{obj:g,parentKids:I}=$.pop();if(!g||typeof g!="object"||A.has(g))continue;A.add(g),g._bakeAuthorGeometry?.(),de().materializeDeclarativeGeometry?.(g);let c=!!(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)),P={name:g.name||(c?`Node_${f.length}`:"")},j=J(g.position?.x,0),G=J(g.position?.y,0),U=J(g.position?.z,0),Z=J(g.quaternion?.x,0),E=J(g.quaternion?.y,0),q=J(g.quaternion?.z,0),k=J(g.quaternion?.w,1),H=J(g.scale?.x,1),F=J(g.scale?.y,1),K=J(g.scale?.z,1);if((j||G||U)&&(P.translation=[j,G,U]),(Z||E||q||k!==1)&&(P.rotation=[Z,E,q,k]),(H!==1||F!==1||K!==1)&&(P.scale=[H,F,K]),g.visible===!1&&(P.extensions={...P.extensions||{},KHR_node_visibility:{visible:!1}},p.add("KHR_node_visibility")),g.userData&&Object.keys(g.userData).length>0&&(P.extras=JSON.parse(JSON.stringify(g.userData,(z,N)=>{if(!(z==="__proto__"||z==="prototype"||z==="constructor"))return typeof N=="function"?void 0:N})),g.userData.xr)){let z=zt(g.userData.xr);P.extensions={...P.extensions||{},MOZ_hubs_components:z,ANDROID_xr_scenecore:z},de().xrTraitSerializer?.gltfNode(P,g.userData.xr),p.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(g.geometry){let z=g.geometry,N=z.attributes.position;if(N&&N.count>0){let Q=[1/0,1/0,1/0],Zt=[-1/0,-1/0,-1/0];for(let ee=0;ee<N.count;ee++){let ie=N.getX(ee),ae=N.getY(ee),re=N.getZ(ee);ie<Q[0]&&(Q[0]=ie),ie>Zt[0]&&(Zt[0]=ie),ae<Q[1]&&(Q[1]=ae),ae>Zt[1]&&(Zt[1]=ae),re<Q[2]&&(Q[2]=re),re>Zt[2]&&(Zt[2]=re)}let Qt={attributes:{POSITION:n(N.array,"VEC3",34962,5126,N.count,Q,Zt)}};if(z.attributes.normal&&(Qt.attributes.NORMAL=n(z.attributes.normal.array,"VEC3",34962,5126,z.attributes.normal.count)),z.attributes.uv&&(Qt.attributes.TEXCOORD_0=n(z.attributes.uv.array,"VEC2",34962,5126,z.attributes.uv.count)),z.index){let ee=z.index.array instanceof Uint32Array;Qt.indices=n(z.index.array,"SCALAR",34963,ee?5125:5123,z.index.count)}let Y=Array.isArray(g.material)?g.material[0]:g.material;Y&&(Qt.material=v(Y));let Jt=g.userData?.variants;if(Jt&&typeof Jt=="object"){let ee=new Map;for(let ie of Object.keys(Jt)){if(!ie||ie==="__proto__"||ie==="constructor"||ie==="prototype")continue;let ae=Jt[ie];if(!ae||typeof ae!="object")continue;let re=T.indexOf(ie);if(re===-1&&T.length<256&&(re=T.length,T.push(ie)),re===-1)continue;let he=v(ae),ce=ee.get(he);ce||(ce=[],ee.set(he,ce)),ce.push(re)}if(ee.size>0){let ie=[];for(let[ae,re]of ee.entries())ie.push({material:ae,variants:re});Qt.extensions={...Qt.extensions||{},KHR_materials_variants:{mappings:ie}},p.add("KHR_materials_variants")}}let te=g;if(te.isInstancedMesh&&typeof te.count=="number"&&te.count>0&&te.instanceMatrix?.array){let ee=Math.min(1e4,Math.floor(te.count)),ie=te.instanceMatrix.array,ae=new Float32Array(ee*3),re=new Float32Array(ee*4),he=new Float32Array(ee*3);for(let oe=0;oe<ee;oe++){let{t:ve,r:fe,s:xe}=dt(ie,oe*16);ae[oe*3]=ve[0],ae[oe*3+1]=ve[1],ae[oe*3+2]=ve[2],re[oe*4]=fe[0],re[oe*4+1]=fe[1],re[oe*4+2]=fe[2],re[oe*4+3]=fe[3],he[oe*3]=xe[0],he[oe*3+1]=xe[1],he[oe*3+2]=xe[2]}let ce={TRANSLATION:n(ae,"VEC3",0,5126,ee),ROTATION:n(re,"VEC4",0,5126,ee),SCALE:n(he,"VEC3",0,5126,ee)};if(te.instanceColor?.array&&te.instanceColor.array.length>=ee*3){let oe=new Float32Array(te.instanceColor.array.subarray(0,ee*3));ce._COLOR_0=n(oe,"VEC3",0,5126,ee)}P.extensions={...P.extensions||{},EXT_mesh_gpu_instancing:{attributes:ce}},p.add("EXT_mesh_gpu_instancing")}let ne=m.length;m.push({primitives:[Qt],name:g.name,...P.extras?{extras:P.extras}:{}}),P.mesh=ne}}let O=f.length;f.push(P),u.push(g),I.push(O);let W=g.children;if(Array.isArray(W)&&W.length>0){let z=[];P.children=z;for(let N=W.length-1;N>=0;N--)$.push({obj:W[N],parentKids:z})}}for(let g=0;g<f.length;g++){let I=f[g];I.children&&I.children.length===0?delete I.children:I.children&&I.children.length>0&&(I.extras?.xr?.lod||I.extensions?.ANDROID_xr_scenecore?.lod||u[g]?.isLOD)&&(I.extensions={...I.extensions||{},MSFT_lod:{ids:[...I.children]}},p.add("MSFT_lod"))}let B=e?.animateCallback||e?.animateFn||(typeof t.userData?.animate=="function"?t.userData.animate:typeof t.__animateFn=="function"?t.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0),_=[];if(typeof B=="function"&&u.length>0){let g=e?.duration??4,I=e?.fps??15,c=Math.max(2,Math.round(g*I)+1),P=new Float32Array(c),j=u.map(F=>[J(F.position?.x,0),J(F.position?.y,0),J(F.position?.z,0),J(F.quaternion?.x,0),J(F.quaternion?.y,0),J(F.quaternion?.z,0),J(F.quaternion?.w,1),J(F.scale?.x,1),J(F.scale?.y,1),J(F.scale?.z,1)]),G=u.map(()=>new Float32Array(c*3)),U=u.map(()=>new Float32Array(c*4)),Z=u.map(()=>new Float32Array(c*3));for(let F=0;F<c;F++){let K=F/(c-1)*g;P[F]=K;try{B(K)}catch{}for(let O=0;O<u.length;O++){let W=u[O];G[O][F*3]=J(W.position?.x,0),G[O][F*3+1]=J(W.position?.y,0),G[O][F*3+2]=J(W.position?.z,0);let z=J(W.quaternion?.x,0),N=J(W.quaternion?.y,0),Q=J(W.quaternion?.z,0),Zt=J(W.quaternion?.w,1),Qt=Math.hypot(z,N,Q,Zt)||1;if(z/=Qt,N/=Qt,Q/=Qt,Zt/=Qt,F>0){let Y=(F-1)*4,Jt=U[O];Jt[Y]*z+Jt[Y+1]*N+Jt[Y+2]*Q+Jt[Y+3]*Zt<0&&(z=-z,N=-N,Q=-Q,Zt=-Zt)}U[O][F*4]=z,U[O][F*4+1]=N,U[O][F*4+2]=Q,U[O][F*4+3]=Zt,Z[O][F*3]=J(W.scale?.x,1),Z[O][F*3+1]=J(W.scale?.y,1),Z[O][F*3+2]=J(W.scale?.z,1)}}for(let F=0;F<u.length;F++){let K=u[F],O=j[F];K.position?.set(O[0],O[1],O[2]),K.quaternion?.set(O[3],O[4],O[5],O[6]),K.scale?.set(O[7],O[8],O[9])}t.updateMatrixWorld(!0);let E=null,q=()=>(E===null&&(E=n(P,"SCALAR",0,5126,c,[0],[g])),E),k=[],H=[];for(let F=0;F<u.length;F++){let K=j[F],O=(z,N,Q)=>z.some((Zt,Qt)=>Math.abs(Zt-K[Q+Qt%N])>1e-4),W=(z,N,Q,Zt)=>{z&&H.push({sampler:k.push({input:q(),interpolation:"LINEAR",output:n(N,Q,0,5126,c)})-1,target:{node:F,path:Zt}})};W(O(G[F],3,0),G[F],"VEC3","translation"),W(O(U[F],4,3),U[F],"VEC4","rotation"),W(O(Z[F],3,7),Z[F],"VEC3","scale")}H.length>0&&_.push({name:"ProceduralLoop",samplers:k,channels:H})}let L=Oe(f,m,t.userData),C=[],D=[],M=[];for(let g=0;g<f.length;g++){let I=f[g],c=pt(I.extras?.xr);if(!c)continue;let{ae:P,src:j,preset:G,volume:U,loop:Z,isGlobal:E}=c,q=I.name||`Node_${g}`,k=D.length;D.push({name:`${q}_source`,gain:U,loop:Z,autoPlay:typeof P.autoplay=="boolean"?P.autoplay:!0,...j!==void 0?{audio:C.push({uri:j})-1}:{},...G?{extras:{preset:G,pitch:ge(P.pitch,.25,4,1)}}:{}});let H=M.length,F=ge(P.refDistance,.05,100,1),K=ge(P.coneInnerAngle,0,360,360),O=ge(P.coneOuterAngle,K,360,360);M.push({name:`${q}_emitter`,type:E?"global":"positional",gain:U,sources:[k],...E?{}:{positional:{distanceModel:P.distanceModel==="linear"||P.distanceModel==="exponential"?P.distanceModel:"inverse",refDistance:F,maxDistance:ge(P.maxDistance,F,500,Math.max(F,25)),rolloffFactor:ge(P.rolloffFactor,0,10,1),coneInnerAngle:+(K*Math.PI/180).toFixed(6),coneOuterAngle:+(O*Math.PI/180).toFixed(6),coneOuterGain:ge(P.coneOuterGain,0,1,0)}}}),I.extensions={...I.extensions||{},KHR_audio_emitter:{emitter:H}},p.add("KHR_audio_emitter")}let o={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:t.environmentIntensity}},scenes:[{nodes:b}],scene:0,nodes:f,meshes:m,materials:d,...R.length>0?{images:R}:{},...S.length>0?{samplers:S}:{},...l.length>0?{textures:l}:{},accessors:s,bufferViews:a,buffers:[{byteLength:r}],..._.length>0?{animations:_}:{},...L||p.size>0?{extensionsUsed:[...L?["KHR_interactivity"]:[],...p]}:{},...L||T.length>0||M.length>0?{extensions:{...L?{KHR_interactivity:L}:{},...T.length>0?{KHR_materials_variants:{variants:T.map(g=>({name:g}))}}:{},...M.length>0?{KHR_audio_emitter:{...C.length>0?{audio:C}:{},sources:D,emitters:M}}:{}}}:{}},V=new Uint8Array(r),X=0;for(let g of i)V.set(g,X),X+=g.byteLength;return[{gltf:o,bin:V.buffer,lights:w,environmentIntensity:t.environmentIntensity},u]}function Ne(t){return new TextEncoder().encode(t)}function Wt(t,e){let{gltf:i,bin:r}=bt(t,e),a=JSON.stringify(i),s=Ne(a),m=(4-s.byteLength%4)%4,f=s.byteLength+m,p=20+f+8+r.byteLength,u=new Uint8Array(p),d=new DataView(u.buffer);d.setUint32(0,1179937895,!0),d.setUint32(4,2,!0),d.setUint32(8,p,!0),d.setUint32(12,f,!0),d.setUint32(16,1313821514,!0),u.set(s,20);for(let R=0;R<m;R++)u[20+s.byteLength+R]=32;let y=20+f;return d.setUint32(y,r.byteLength,!0),d.setUint32(y+4,5130562,!0),u.set(new Uint8Array(r),y+8),u}function yt(t,e){let[i,r]=gt(t,e);return Be(i,r)}function Be(t,e){let i=[],r=t.gltf,a=de().decoders.get("meshopt");a&&typeof a.decodeBufferViews=="function"&&a.decodeBufferViews(r,t);let s=t.bin,m=s instanceof ArrayBuffer?s:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),f=r.accessors||[],p=r.bufferViews||[],u=r.materials||[],d=r.meshes||[],y=r.nodes||[],R=new Set,S=u.map((T,w)=>ft(R,we(T?.name,`Material_${w}`)));function l(T){let w=f[T];if(!w)throw new Error(`Accessor ${T} not found`);let v=p[w.bufferView||0],h=(v.byteOffset||0)+(w.byteOffset||0),n=v.byteLength||0;return{acc:w,buffer:m.slice(h,h+n)}}function x(T,w,v,h){let n=[],b=d[T];if(!b)return n;let A=b.primitives||[];for(let $=0;$<A.length;$++){let B=A[$],_=B.attributes?.POSITION;if(_===void 0)continue;let{acc:L,buffer:C}=l(_),D=new Float32Array(C,0,L.count*3),M,o=B.attributes?.NORMAL;if(o!==void 0){let{acc:k,buffer:H}=l(o),F=new Float32Array(H,0,k.count*3);M=new Float32Array(F.length);for(let K=0;K<k.count;K++){let O=F[K*3],W=F[K*3+1],z=F[K*3+2],N=Math.hypot(O,W,z)||1;M[K*3]=O/N,M[K*3+1]=W/N,M[K*3+2]=z/N}}let V,X=B.attributes?.TEXCOORD_0;if(X!==void 0){let{acc:k,buffer:H}=l(X);V=new Float32Array(H,0,k.count*2)}let g;if(B.indices!==void 0){let{acc:k,buffer:H}=l(B.indices);g=k.componentType===5125?new Uint32Array(H,0,k.count):new Uint16Array(H,0,k.count);let F=L.count;for(let K of g)if(K>=F)throw new Error(`SecurityError: Index buffer value (${K}) out of vertex bounds [0, ${F}).`)}else{let k=L.count;g=k>65535?new Uint32Array(k):new Uint16Array(k);for(let H=0;H<k;H++)g[H]=H}let I="DefaultMaterial",c=[.8,.8,.8],P=.5,j=0,G=0,U=0,Z=1.5,E=1,q=[0,0,0];if(B.material!==void 0&&u[B.material]){let k=u[B.material];I=S[B.material]||`Material_${B.material}`;let H=k.pbrMetallicRoughness||{},F=(z,N)=>Array.isArray(z)&&z.length>=3?[z[0],z[1],z[2]]:N;c=F(H.baseColorFactor,[1,1,1]);let K=k.extras?.avgColor;Array.isArray(K)&&K.length>=3&&(c=[c[0]*K[0],c[1]*K[1],c[2]*K[2]]);let O=Array.isArray(H.baseColorFactor)&&typeof H.baseColorFactor[3]=="number"?H.baseColorFactor[3]:1;typeof H.roughnessFactor=="number"&&(P=H.roughnessFactor),typeof H.metallicFactor=="number"&&(j=H.metallicFactor),q=F(k.emissiveFactor,[0,0,0]);let W=k.extensions||{};W.KHR_materials_clearcoat&&(G=W.KHR_materials_clearcoat.clearcoatFactor??0,U=W.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),typeof W.KHR_materials_ior?.ior=="number"&&(Z=W.KHR_materials_ior.ior),E=O*(1-(W.KHR_materials_transmission?.transmissionFactor??0))}n.push({name:A.length>1?`${w}_p${$}`:w,positions:D,indices:g,normals:M,uvs:V,materialName:I,color:c,roughness:P,metallic:j,clearcoat:G,clearcoatRoughness:U,ior:Z,opacity:E,emissiveColor:q,xrTraits:v||b.extras?.xr,...h?{invisible:!0}:{}})}return n}if(y.length>0){let T=new Float32Array(0),w=new Uint16Array(0),v=(D,M)=>{if(D===void 0)return null;let{acc:o,buffer:V}=l(D);return new Float32Array(V,0,o.count*M)},h=(D,M)=>Array.isArray(D)&&D.length>=3?[J(D[0],M),J(D[1],M),J(D[2],M)]:[M,M,M],n=(D,M,o)=>D&&D.length>=(M+1)*3?[D[M*3],D[M*3+1],D[M*3+2]]:o,b=(D,M,o)=>D&&D.length>=(M+1)*4?[D[M*4],D[M*4+1],D[M*4+2],D[M*4+3]]:o,A=new Map,$=r.animations?.[0];if($&&Array.isArray($.channels)&&Array.isArray($.samplers))for(let D of $.channels){let M=$.samplers[D?.sampler],o=D?.target?.node,V=D?.target?.path;if(!M||typeof o!="number"||M.input===void 0)continue;let X=A.get(o);X||(X={input:M.input},A.set(o,X)),V==="translation"?X.t=M.output:V==="rotation"?X.r=M.output:V==="scale"&&(X.s=M.output)}let B=r.scenes?.[r.scene??0]?.nodes??[];if(!Array.isArray(B)||B.length===0){let D=new Set;for(let M of y)if(Array.isArray(M?.children))for(let o of M.children)D.add(o);B=[];for(let M=0;M<y.length;M++)D.has(M)||B.push(M);B.length===0&&(B=[0])}let _=new Set,L=[],C=(D,M)=>{if(Array.isArray(D))for(let o=D.length-1;o>=0;o--)L.push({idx:D[o],out:M})};for(C(B,i);L.length>0;){let{idx:D,out:M}=L.pop();if(typeof D!="number"||D<0||D>=y.length||_.has(D))continue;_.add(D);let o=y[D];if(!o)continue;let V=[0,0,0],X=[0,0,0,1],g=[1,1,1];if(Array.isArray(o.matrix)&&o.matrix.length===16){let E=dt(o.matrix);V=E.t,X=E.r,g=E.s}else V=h(o.translation,0),Array.isArray(o.rotation)&&o.rotation.length>=4&&(X=[J(o.rotation[0],0),J(o.rotation[1],0),J(o.rotation[2],0),J(o.rotation[3],1)]),g=h(o.scale,1);let I,c=A.get(D);if(c){let E=v(c.input,1);if(E&&E.length>0){let q=v(c.t,3),k=v(c.r,4),H=v(c.s,3),F=Array.from(E),K=[],O=[],W=[];for(let z=0;z<E.length;z++)K.push(n(q,z,V)),O.push(b(k,z,X)),W.push(n(H,z,g));I={times:F,translations:K,rotations:O,scales:W}}}let P=Array.isArray(o.children)?o.children:[],j=typeof o.mesh=="number"&&o.mesh>=0&&o.mesh<d.length,G=e?.[D]?.userData?.xr??o.extras?.xr;if(!j&&P.length===0&&(o.camera!==void 0||o.extensions?.KHR_lights_punctual||!o.name&&!o.extras&&!G&&!I))continue;let U=(E,q,k)=>({name:E,positions:T,indices:w,isXform:!0,xrTraits:G,timeSamples:I,translation:V,rotation:X,scale:g,children:q,...k?{invisible:!0}:{}}),Z=o.visible===!1||o.extensions?.KHR_node_visibility?.visible===!1||e?.[D]?.visible===!1;if(j){let E=o.name||d[o.mesh]?.name||`Mesh_${D}`,q=x(o.mesh,E,G,Z),k=o.extensions?.EXT_mesh_gpu_instancing?.attributes;if(k&&typeof k=="object"&&q.length>0){let H=v(k.TRANSLATION,3),F=v(k.ROTATION,4),K=v(k.SCALE,3),O=v(k._COLOR_0,3),W=Math.min(1e3,H?H.length/3:F?F.length/4:K?K.length/3:0);if(W>0){let z=[];for(let N=0;N<W;N++){let Q=n(H,N,[0,0,0]),Zt=b(F,N,[0,0,0,1]),Qt=n(K,N,[1,1,1]);for(let Y of q){let Jt=Y.color||[.8,.8,.8],te=O&&O.length>=(N+1)*3;z.push({...Y,name:`${Y.name}_${N}`,materialName:te?`${Y.materialName}_inst_${N}`:Y.materialName,color:te?[Jt[0]*O[N*3],Jt[1]*O[N*3+1],Jt[2]*O[N*3+2]]:Y.color,translation:Q,rotation:Zt,scale:Qt})}}C(P,z),M.push(U(E,z,Z));continue}}if(q.length===1)q[0].translation=V,q[0].rotation=X,q[0].scale=g,q[0].timeSamples=I,P.length>0&&(q[0].children=[],C(P,q[0].children)),M.push(q[0]);else{let H=[...q];C(P,H),M.push(U(E,H,Z))}}else{let E=[];C(P,E),M.push(U(o.name||`Group_${D}`,E,Z))}}}else for(let T=0;T<d.length;T++){let w=d[T].name||`Mesh_${T}`;i.push(...x(T,w,d[T].extras?.xr))}return i}function we(t,e){if(!t||typeof t!="string")return e;let i=t.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(i)&&(i="_"+i),i||e}function _e(t){return String(t??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function le(t){if(!Number.isFinite(t)||Math.abs(t)<1e-7)return"0";let e=Number(t.toFixed(5)).toString();return e.indexOf(".")===-1?`${e}.0`:e}var pe=(t,e,i)=>`(${le(t)}, ${le(e)}, ${le(i)})`,mt=(t,e,i,r)=>`(${le(t)}, ${le(e)}, ${le(i)}, ${le(r)})`;function ht(t){let e=t.length/3,i=new Array(e);for(let r=0;r<e;r++)i[r]=pe(t[r*3],t[r*3+1],t[r*3+2]);return i.join(", ")}function jt(t,e){let i=new Array(e);for(let r=0;r<e;r++)i[r]=`(${le(t[r*2])}, ${le(1-t[r*2+1])})`;return i.join(", ")}function Xt(t){return Array.from(t).join(", ")}function Fe(t){let e=new Map,i=0,r=null,a=[...t];for(;a.length>0;){let l=a.pop();if(!l.isXform&&l.positions&&l.positions.length>0){let x=we(l.materialName,"DefaultMaterial");e.has(x)||e.set(x,{color:l.color||[.8,.8,.8],roughness:l.roughness??.5,metallic:l.metallic??0,clearcoat:l.clearcoat??0,clearcoatRoughness:l.clearcoatRoughness??0,ior:l.ior??1.5,opacity:l.opacity??1,emissiveColor:l.emissiveColor||[0,0,0]})}if(l.timeSamples&&l.timeSamples.times.length>0){let x=l.timeSamples.times[l.timeSamples.times.length-1];x>i&&(i=x)}if(l.xrTraits?.anchor&&!r&&(r=l.xrTraits.anchor==="vertical"||l.xrTraits.anchor==="wall"?"vertical":"horizontal"),l.children)for(let x=l.children.length-1;x>=0;x--)a.push(l.children[x])}let s="";i>0&&(s=`startTimeCode = 0
250
- endTimeCode = ${le(i)}
214
+ void main(){fragColor=uColorId;}`;function Ve(e,t,i){let r={};for(let n of i)r[n]=e.getUniformLocation(t,n);return r}var Zt="uMVP uModel uInstanced uViewProj uNormalMatrix uUvTransform uBaseColor uMetallic uRoughness uClearcoat uEmissive uCameraPos uBaseColorTexture uHasTexture uMetallicRoughnessTexture uHasMetallicRoughnessTexture uNormalTexture uHasNormalTexture uNormalScale uOcclusionTexture uHasOcclusionTexture uOcclusionStrength uEmissiveFactor uEmissiveTexture uHasEmissiveTexture uToneMapping uEnvironmentMap uHasEnvironmentMap uAmbientColor uHemi uNumDirLights uDirLightDir uDirLightColor uNumPointLights uPointLightPos uPointLightColor uPointLightSpotDir uPointLightSpotCone uEnvIntensity uExposure uViewportSize uSectionPlane uSectionEnabled".split(" ");function ut(){let e=Ae(),t=e.xrDepthShader,i=e.shadowMapShader;return{fs:Kt.replace("/*XRD_U*/",t?.uniformsGLSL||"").replace("/*XRD_O*/",t?.occlusionGLSL||"").replace("/*SHD_U*/",i?.uniformsGLSL||"").replace("/*SHD_D*/",i?.dirGLSL||"").replace("/*SHD_P*/",i?.ptGLSL||""),uniforms:[...Zt,...t?.uniformNames||[],...i?.uniformNames||[]]}}function Jt(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 it(e,t,i,r,n,a,l,h){if(r===void 0||!t.accessors?.[r])return null;let c=Je(t,i,t.accessors[r],a);if(!c)return null;h&&(c=c.slice(),pt(c,h));let T=e.createBuffer();return l.push(T),e.bindBuffer(34962,T),e.bufferData(34962,c,35044),e.enableVertexAttribArray(n),e.vertexAttribPointer(n,a,5126,!1,0,0),c}function ot(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,t):1}function At(e,t,i){let r=ut(),n=at,a=r.fs,l=!1;for(let c of fe)if(c.onResolveShader){let T=c.onResolveShader(t,i,n,a);T&&(n=T.vs,a=T.fs,l=!0)}let h=l?Ee(e,n,a):null;return{program:h,uniforms:h?Ve(e,h,r.uniforms):null}}function Qt(e,t,i){let r=t.instanceMatrices;if(!r||r.length<16||typeof e.vertexAttribDivisor!="function"||typeof e.drawElementsInstanced!="function")return!1;let n=r.length>>4,a=t.instanceColors,l=new Float32Array(n*20);for(let c=0;c<n;c++)l.set(r.subarray(c*16,c*16+16),c*20),l[c*20+16]=a?a[c*3]:1,l[c*20+17]=a?a[c*3+1]:1,l[c*20+18]=a?a[c*3+2]:1,l[c*20+19]=1;let h=e.createBuffer();i.push(h),e.bindBuffer(34962,h),e.bufferData(34962,l,35044);for(let c=0;c<5;c++)e.enableVertexAttribArray(8+c),e.vertexAttribPointer(8+c,4,5126,!1,80,c*16),e.vertexAttribDivisor(8+c,1);return!0}function en(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 n of r){let a=n?.extensions?.KHR_texture_transform;if(a&&typeof a=="object")return a}return null}var Tn=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),Tt=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function ke(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}function wt(e,t){let i=e?.pbrMetallicRoughness,r=i?.baseColorFactor,n=e?.emissiveFactor,a=e?.extensions?.KHR_materials_clearcoat,l=h=>h!==void 0&&t[h.index]?t[h.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:l(i?.baseColorTexture),metallicRoughnessTexture:l(i?.metallicRoughnessTexture),normalTexture:l(e?.normalTexture),normalScale:e?.normalTexture?.scale??1,occlusionTexture:l(e?.occlusionTexture),occlusionStrength:e?.occlusionTexture?.strength??1,emissiveTexture:l(e?.emissiveTexture),emissiveFactor:Array.isArray(n)&&n.length>=3?[n[0],n[1],n[2]]:[0,0,0],isTransmissive:(e?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function St(e,t,i){let r=new Set,n=a=>{a&&!r.has(a)&&(r.add(a),e.deleteTexture(a))};for(let a of t)for(let l of a.primitives){if(l.vao&&e.deleteVertexArray(l.vao),l.buffers)for(let c of l.buffers)e.deleteBuffer(c);for(let c of[l.texture,l.metallicRoughnessTexture,l.normalTexture,l.occlusionTexture,l.emissiveTexture])n(c);let h=new Set;l.customProgram&&h.add(l.customProgram);for(let c of l.programCache?.values()??[])c.program&&h.add(c.program);for(let c of h)e.deleteProgram(c)}if(i)for(let a of i)n(a)}function yt(e,t,i=Tt,r){let n={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return tn(e,t,i,r,n)}catch(a){let l=n.mesh&&!n.meshes.includes(n.mesh)?[...n.meshes,n.mesh]:n.meshes;St(e,l,n.gpuTextures),n.vao&&e.deleteVertexArray(n.vao);for(let h of n.buffers)e.deleteBuffer(h);throw a}}function tn(e,t,i,r,n){if(!t||!t.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:a}=t,l=$e("meshopt");l?.decodeBufferViews&&l.decodeBufferViews(a,t);let h=t.bin,c=[];n.meshes=c;let T=[],d=a.extensions?.KHR_materials_variants;d&&Array.isArray(d.variants)&&d.variants.forEach((C,S)=>{T.push(typeof C?.name=="string"&&C.name?C.name:`Variant_${S}`)});let g=rt(a),I=[];if(Array.isArray(a.nodes))for(let C=0;C<a.nodes.length;C++){let S=a.nodes[C];S.mesh!==void 0&&a.meshes&&a.meshes[S.mesh]&&I.push({node:S,nodeIdx:C,meshIdx:S.mesh})}let L=I.length>0?I:(a.meshes||[]).map((C,S)=>({node:C,nodeIdx:-1,meshIdx:S})),D=[],O=Array.isArray(t.lights)&&t.lights.length>0?t.lights:Array.isArray(a.asset?.extras?.lights)&&a.asset.extras.lights.length>0?a.asset.extras.lights:null;if(O)for(let C of O)D.push({...C,type:C.type||C.light_type||"point",groundColor:C.groundColor??C.ground_color,innerConeAngle:C.innerConeAngle??C.inner_cone_angle,outerConeAngle:C.outerConeAngle??C.outer_cone_angle});else a.extensions?.KHR_lights_punctual?.lights&&D.push(...ct(a,g));if(D.length===0&&(D.push({type:"ambient",color:[1,1,1],intensity:.35}),D.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),L.length>i.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${i.maxMeshes}). Found: ${L.length}`);let o=[];if(n.gpuTextures=o,a.textures&&a.images){if(a.textures.length>i.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${i.maxTextures}). Found: ${a.textures.length}`);for(let C=0;C<a.textures.length;C++){let S=a.textures[C],N=a.images[S.source];if(N){let V=e.createTexture();e.bindTexture(3553,V),e.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255]));for(let[P,E]of[[10242,10497],[10243,10497],[10241,9729],[10240,9729]])e.texParameteri(3553,P,E);let b=P=>{V.__gpuImageSource=P,e.bindTexture(3553,V),e.texImage2D(3553,0,6408,6408,5121,P),e.generateMipmap(3553),r?.()};if(N.bufferView!==void 0){let P=a.bufferViews[N.bufferView],E=P.byteOffset||0,j=new Blob([h.slice(E,E+P.byteLength)],{type:N.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(j).then(b).catch(()=>{})}else if(N.uri){let P=Jt(N.uri);if(P){let E=new Image;E.crossOrigin="anonymous",E.referrerPolicy="no-referrer",E.onload=()=>b(E),E.src=P}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",N.uri)}o.push(V)}else o.push(null)}}let f=[1/0,1/0,1/0],p=[-1/0,-1/0,-1/0],m=0,y=0;for(let C=0;C<L.length;C++){let S=L[C],N=a.meshes[S.meshIdx],V=S.nodeIdx>=0?g[S.nodeIdx]:be(),b=new Float32Array(9);Le(b,V);let P=S.node?.extras?.shadow,E={name:S.node.name||N.name||`Mesh_${S.meshIdx}`,nodeIndex:S.nodeIdx,transform:V,normalMatrix:b,primitives:[],extras:S.node.extras||N.extras,...S.node?.visible===!1||S.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{},...typeof P?.cast=="boolean"?{castShadow:P.cast}:{},...typeof P?.receive=="boolean"?{receiveShadow:P.receive}:{}};n.mesh=E;let j=S.node?.extensions?.EXT_mesh_gpu_instancing;if(j&&j.attributes&&typeof j.attributes=="object"){let v=j.attributes,$=v.TRANSLATION!==void 0?a.accessors?.[v.TRANSLATION]:null,s=v.ROTATION!==void 0?a.accessors?.[v.ROTATION]:null,M=v.SCALE!==void 0?a.accessors?.[v.SCALE]:null,u=v._COLOR_0!==void 0?a.accessors?.[v._COLOR_0]:null,A=Number($?.count??s?.count??M?.count??0);if(!Number.isFinite(A)||A<0||A>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${A}`);if(A>0){let H=(U,K)=>{if(!U||U.bufferView===void 0||!a.bufferViews?.[U.bufferView])return null;let k=U.componentType??5126,Q=X=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${X})`),null);if(k!==5120&&k!==5121&&k!==5122&&k!==5123&&k!==5126)return Q(`componentType ${k}`);if(!(Number(U.count)>=A))return Q(`count ${U.count} < ${A}`);let ee=null;try{ee=Je(a,h,{...U,count:A},K)}catch{return Q("out of bounds")}return!ee||!ee.every(Number.isFinite)?Q("non-finite value"):ee},q=H($,3),Z=H(s,4),W=H(M,3),ne=u?.type==="VEC4"?4:3,ae=H(u,ne),he=new Float32Array(A*16),oe=be();for(let U=0;U<A;U++){let K=U*3,k=U*4;tt(oe,Z?[Z[k],Z[k+1],Z[k+2],Z[k+3]]:[0,0,0,1],q?[q[K],q[K+1],q[K+2]]:[0,0,0],W?[W[K],W[K+1],W[K+2]]:[1,1,1]),he.set(oe,U*16)}if(E.instanceMatrices=he,ae){let U=new Float32Array(A*3);for(let K=0;K<A;K++)U[K*3]=ae[K*ne],U[K*3+1]=ae[K*ne+1],U[K*3+2]=ae[K*ne+2];E.instanceColors=U}}}for(let v of N.primitives||[]){if(v.extensions?.KHR_draco_mesh_compression){let F=$e("draco");F&&F.decodePrimitive(a,v,h)}let $=[],s=e.createVertexArray();n.vao=s,n.buffers=$,e.bindVertexArray(s);let M=Qt(e,E,$),u=a.accessors[v.attributes.POSITION],A=Number(u?.count??0);if(!Number.isFinite(A)||A<0||m+A>i.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${i.maxVertices}).`);if(m+=A,u?.min&&u?.max){let F=B=>{for(let G=0;G<3;G++){let Y=B[12+G],re=Y;for(let ie=0;ie<3;ie++){let me=B[ie*4+G]*u.min[ie],te=B[ie*4+G]*u.max[ie];Y+=me<te?me:te,re+=me>te?me:te}Y<f[G]&&(f[G]=Y),re>p[G]&&(p[G]=re)}};if(E.instanceMatrices&&E.instanceMatrices.length>=16){let B=E.instanceMatrices.length>>4,G=be();for(let Y=0;Y<B;Y++)ye(G,V,E.instanceMatrices.subarray(Y*16,Y*16+16)),F(G)}else F(V)}let H=it(e,a,h,v.attributes.POSITION,0,3,$),q=it(e,a,h,v.attributes.NORMAL,1,3,$),Z=it(e,a,h,v.attributes.TEXCOORD_0,2,2,$,en(a,v)),W=0,ne=5123,ae=null;if(v.indices!==void 0){let F=a.accessors[v.indices],B=(a.bufferViews[F.bufferView].byteOffset||0)+(F.byteOffset||0);if(W=Number(F.count??0),!Number.isFinite(W)||W<0||y+W>i.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${i.maxIndices}).`);y+=W,ne=F.componentType===5125?5125:5123;let G=e.createBuffer();$.push(G),e.bindBuffer(34963,G),F.componentType===5125?ae=new Uint32Array(h,B,F.count):F.componentType===5121?ae=Uint16Array.from(new Uint8Array(h,B,F.count)):ae=B%2===0?new Uint16Array(h,B,F.count):new Uint16Array(h.slice(B,B+F.count*2)),e.bufferData(34963,ae,35044)}else W=u.count;let he={};for(let F of fe)if(F.onBuildPrimitiveVAO){let B=F.onBuildPrimitiveVAO(e,s,v,a,h);B&&(he[F.name]=B)}e.bindVertexArray(null);let oe=a.materials&&v.material!==void 0?a.materials[v.material]:null,{program:U,uniforms:K}=At(e,v,oe),k=wt(oe,o),Q=!!(oe?.extensions?.KHR_materials_transmission||he.materials?.isTransmissive),ee=v.extensions?.KHR_materials_variants?.mappings,X=Array.isArray(ee)?ee.filter(F=>F&&typeof F.material=="number"&&Array.isArray(F.variants)).map(F=>({material:F.material|0,variants:F.variants.map(B=>Number(B)|0)})):void 0;E.primitives.push({vao:s,instanced:M,indexCount:W,indexType:ne,...k,positions:H,normals:q,uvs:Z,indices:ae,buffers:$,materialIndex:v.material,defaultMaterialIndex:v.material,variantMappings:X,primitiveDef:v,programCache:new Map([[v.material??-1,{program:U,uniforms:K}]]),pluginData:he,customProgram:U,customUniforms:K,isTransmissive:Q})}c.push(E)}isFinite(f[0])||(f=[-1,-1,-1]),isFinite(p[0])||(p=[1,1,1]);let w=[(f[0]+p[0])/2,(f[1]+p[1])/2,(f[2]+p[2])/2],x=Math.max(Math.hypot(p[0]-f[0],p[1]-f[1],p[2]-f[2])/2,.5),z=[...f],R=[...p],_=t.animations;if(t.animationsParsed===!1||!_){for(let C of fe)if(C.onParseGLB?.(t),t.animations){_=t.animations;break}}return _||(_=[]),{meshes:c,bounds:{center:w,radius:x,min:z,max:R},lights:D,animations:_,worldMatrices:g,gpuTextures:o,availableVariants:T}}function Ge(){return typeof performance<"u"?performance.now():Date.now()}function _e(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 Oe=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=be(),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.environmentSource=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=be(),this.viewMatrix=be(),this.activeViewMatrix=null,this.modelMatrix=be(),this.mvpMatrix=be(),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.selectedMeshNames=new Set,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:be(),rawValueToMeters:.001,format:0},this.container=e;let r,n;if(t&&typeof t.getContext=="function"?(r=t,n=i):(n=t,r=n?.canvas),!r){let c=e.querySelector("canvas");c||(c=document.createElement("canvas"),c.style.cssText="width:100%;height:100%;display:block;touch-action:none",e.prepend(c)),r=c}this.canvas=r;let a=this.opts=n||{};a.clearColor&&(this.clearColor=a.clearColor);let l=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;a.autoRotate!==void 0?this.autoRotate=a.autoRotate&&!l:l&&(this.autoRotate=!1),a.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=a.autoRotateSpeed),a.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(a.autoRotateDelay)||0)),a.exposure!==void 0&&(this.exposure=ot(a.exposure)),a.camera&&this.setInitialCamera(a.camera.theta,a.camera.phi,a.camera.distance,a.camera.zoom),(a.shadowIntensity!==void 0||a.shadowSoftness!==void 0)&&this.setShadow(a.shadowIntensity??0,a.shadowSoftness),a.shadowMaps!==void 0&&(this.shadowMaps=a.shadowMaps),a.toneMapping!==void 0&&(this.toneMapping=st(a.toneMapping)),a.autoplay!==void 0&&(this.autoplay=a.autoplay),a.animationName!==void 0&&(this.animationName=a.animationName),a.variantName!==void 0&&(this.activeVariantName=a.variantName||null),a.fieldOfView!==void 0&&(this.fov=a.fieldOfView*Math.PI/180),a.distanceMode!==void 0&&(this.distanceMode=a.distanceMode),a.cameraTarget!==void 0&&(this.setTarget(a.cameraTarget[0],a.cameraTarget[1],a.cameraTarget[2]),this.initialCustomTarget=[...a.cameraTarget]),(a.minCameraOrbit||a.maxCameraOrbit)&&this.setOrbitLimits({minTheta:a.minCameraOrbit?.theta,maxTheta:a.maxCameraOrbit?.theta,minPhi:a.minCameraOrbit?.phi,maxPhi:a.maxCameraOrbit?.phi,minDistance:a.minCameraOrbit?.distance,maxDistance:a.maxCameraOrbit?.distance});let h=r.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!h)throw new Error("WebGL2 not supported");this.gl=h,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),a.environmentImage&&this.setEnvironmentImage(a.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&a.autoStart!==!1&&this.start()}static registerDecoder(e,t){Wt(e,t)}static getDecoder(e){return $e(e)}setupContextLossHandling(){let e=this.canvas;typeof e?.addEventListener=="function"&&(this.boundContextLost=t=>{t.preventDefault?.(),this.contextLost=!0,this.stop()},this.boundContextRestored=()=>this.restoreContext(),e.addEventListener("webglcontextlost",this.boundContextLost),e.addEventListener("webglcontextrestored",this.boundContextRestored))}initGlState(){let e=this.gl,t=ut();this.renderProg=Ee(e,at,t.fs),this.pickProg=Ee(e,qt,Yt),this.uRender=Ve(e,this.renderProg,t.uniforms),this.uPick=Ve(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}recompileRenderProgram(){if(this.contextLost)return;let e=this.gl,t=ut();this.renderProg&&e.deleteProgram(this.renderProg),this.renderProg=Ee(e,at,t.fs),this.uRender=Ve(e,this.renderProg,t.uniforms);for(let i of this.meshes)for(let r of i.primitives)r.customProgram&&(e.deleteProgram(r.customProgram),r.programCache?.clear(),this.applyPrimitiveProgram(r,r.materialIndex,this.gltf?.materials?.[r.materialIndex??-1]??null))}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of fe)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;typeof e.createFramebuffer=="function"&&(this.pickFbo=e.createFramebuffer(),this.pickTexture=e.createTexture(),this.pickDepth=e.createRenderbuffer(),this.resizePickingFbo(this.canvas.width,this.canvas.height),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),n=Math.max(1,t);this.pickFboWidth=r,this.pickFboHeight=n,i.bindTexture(3553,this.pickTexture),i.texImage2D(3553,0,6408,r,n,0,6408,5121,null),i.texParameteri(3553,10241,9728),i.texParameteri(3553,10240,9728),i.bindRenderbuffer(36161,this.pickDepth),i.renderbufferStorage(36161,33189,r,n)}loadGLBData(e,t){let{meshes:i,bounds:r,lights:n,animations:a,worldMatrices:l,gpuTextures:h,availableVariants:c}=yt(this.gl,e,t,()=>this.render());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=n,this.animations=a||[],this.worldMatrices=l||[],this.gpuTextures=h||[],this.availableVariants=c||[],this.gltf=e.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=(e.gltf?.nodes||[]).map(g=>({t:[g.translation?.[0]??0,g.translation?.[1]??0,g.translation?.[2]??0],r:[g.rotation?.[0]??0,g.rotation?.[1]??0,g.rotation?.[2]??0,g.rotation?.[3]??1],s:[g.scale?.[0]??1,g.scale?.[1]??1,g.scale?.[2]??1]})),this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let g of fe)g.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 T=e.exposure??e.gltf?.extras?.exposure??e.gltf?.asset?.extras?.exposure;T!==void 0&&(this.exposure=ot(T));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(Mt(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let e of fe)e.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(Ie(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let i=Ie(e),{meshes:r}=yt(this.gl,i,Tt,()=>this.render());if(t)for(let n of r)n.transform[12]+=t[0],n.transform[13]+=t[1],n.transform[14]+=t[2],Le(n.normalMatrix,n.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?e.get(i.name)??e.get(t):Array.isArray(e)?e[t]:e&&typeof e=="object"?Object.prototype.hasOwnProperty.call(e,i.name)?e[i.name]:Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0:void 0;r&&r.length===16&&(i.transform.set(r),Le(i.normalMatrix,i.transform))}}bindLights(e=this.uRender){let t=this.gl,i=[.28,.28,.28],r=[0,0,0,0,0,0,0,1,0],n=!1,a=[],l=[],h=[],c=[],T=[],d=[];for(let g of this.lights){let I=g.color||[1,1,1],L=g.intensity!==void 0?g.intensity:1;if(g.type==="ambient")i=[I[0]*L,I[1]*L,I[2]*L];else if(g.type==="hemisphere"){n=!0;let D=g.groundColor||[.2,.2,.2],O=L*.65;for(let p=0;p<3;p++)r[p]+=I[p]*O,r[p+3]+=D[p]*O;let o=g.position||[0,1,0],f=Math.hypot(o[0],o[1],o[2]);f>1e-5&&(r[6]=o[0]/f,r[7]=o[1]/f,r[8]=o[2]/f)}else if(g.type==="directional"&&a.length<6){let D=g.direction||[.5,1,.8];a.push(D[0],D[1],D[2]),l.push(I[0]*L,I[1]*L,I[2]*L)}else if((g.type==="point"||g.type==="spot")&&h.length<6){let D=g.position||[0,0,0];if(h.push(D[0],D[1],D[2]),c.push(I[0]*L,I[1]*L,I[2]*L),g.type==="spot"){let O=g.direction||[0,-1,0],o=Math.max(.01,Math.min(Math.PI/2,g.outerConeAngle??Math.PI/3)),f=Math.max(0,Math.min(o-1e-4,g.innerConeAngle??0));T.push(O[0],O[1],O[2]),d.push(Math.cos(f),Math.cos(o))}else T.push(0,-1,0),d.push(-2,-3)}}a.length===0&&!n&&(a.push(.5,1,.8),l.push(1,1,1)),t.uniform3fv(e.uAmbientColor,i),e.uHemi&&t.uniformMatrix3fv(e.uHemi,!1,r),t.uniform1i(e.uNumDirLights,a.length/3),a.length>0&&(t.uniform3fv(e.uDirLightDir,a),t.uniform3fv(e.uDirLightColor,l)),t.uniform1i(e.uNumPointLights,h.length/3),h.length>0&&(t.uniform3fv(e.uPointLightPos,h),t.uniform3fv(e.uPointLightColor,c),e.uPointLightSpotDir&&t.uniform3fv(e.uPointLightSpotDir,T),e.uPointLightSpotCone&&t.uniform2fv(e.uPointLightSpotCone,d)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=ot(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=st(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){this.environmentSource=e&&typeof e=="object"?e:null;for(let t of fe)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e),this.render();return}this.render()}async setSkyboxImage(e){for(let t of fe)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(d=>d.primitives.filter(g=>g.materialIndex===i||e.length===1&&g.materialIndex===void 0)),n=r[0],a=n?[...n.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],l=n?n.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,h=n?n.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,c=(d,g,I)=>{T[d]=I,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness[d]=I);for(let L of r)L[g]=I;this.render()},T={baseColorFactor:a,metallicFactor:l,roughnessFactor:h,setBaseColorFactor:d=>c("baseColorFactor","baseColor",[d[0],d[1],d[2],d[3]??1]),setMetallicFactor:d=>c("metallicFactor","metallic",d),setRoughnessFactor:d=>c("roughnessFactor","roughness",d)};return{name:t.name||`Material_${i}`,pbrMetallicRoughness:T}})}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 n of this.meshes)for(let a of n.primitives){let l=a.defaultMaterialIndex;if(!t&&Array.isArray(a.variantMappings)){for(let c of a.variantMappings)if(Array.isArray(c.variants)&&c.variants.includes(i)){l=c.material;break}}let h=l!==void 0?r[l]:void 0;a.materialIndex=h?l:void 0,Object.assign(a,wt(h,this.gpuTextures)),this.applyPrimitiveProgram(a,a.materialIndex,h??null)}return!0}applyPrimitiveProgram(e,t,i){if(!this.gl||!e.primitiveDef)return;e.programCache??(e.programCache=new Map);let r=t??-1,n=e.programCache.get(r);n||(n=At(this.gl,{...e.primitiveDef,material:t},i),e.programCache.set(r,n)),e.customProgram=n.program,e.customUniforms=n.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 fe)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){let t=Math.PI/180,i=Math.PI*.48;e.minTheta!==void 0&&(this.minTheta=e.minTheta*t),e.maxTheta!==void 0&&(this.maxTheta=e.maxTheta*t),e.minPhi!==void 0&&(this.minPhi=Math.max(-i,e.minPhi*t)),e.maxPhi!==void 0&&(this.maxPhi=Math.min(i,e.maxPhi*t)),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(){let e=180/Math.PI;return{minTheta:isFinite(this.minTheta)?this.minTheta*e:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*e:void 0,minPhi:this.minPhi*e,maxPhi:this.maxPhi*e,minDistance:this.minDistanceLimit??void 0,maxDistance: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.bounds?.radius;return Math.max(this.minDistanceLimit??(t?t*.5:.1),Math.min(this.maxDistanceLimit??(t?t*8:100),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){e!==void 0&&(this.initialTheta=this.targetTheta=this.currTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.initialPhi=this.targetPhi=this.currPhi=this.clampPhi(t*Math.PI/180));let n=i!==void 0&&i>0?i:r!==void 0&&r>0?this.bounds.radius*2.5/r:null;this.customDistance=n!==null,this.initialDistance=this.targetDistance=this.currDistance=this.clampDistance(n??(this.distanceMode==="absolute"?3:this.bounds.radius*2.5)),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.targetDistance=this.clampDistance(this.initialDistance??this.bounds.radius*2.5),this.customTarget=this.initialCustomTarget?[...this.initialCustomTarget]:null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(e,t){let i=be();ye(i,this.projMatrix,this.viewMatrix);let r=(R,_,C=1)=>[R[0]*_[0]+R[4]*_[1]+R[8]*_[2]+R[12]*C,R[1]*_[0]+R[5]*_[1]+R[9]*_[2]+R[13]*C,R[2]*_[0]+R[6]*_[1]+R[10]*_[2]+R[14]*C,R[3]*_[0]+R[7]*_[1]+R[11]*_[2]+R[15]*C],n=this.modelRootMatrix,[a,l,h]=n?r(n,e):e,[c,T,d]=t?n?r(n,t,0):t:[0,0,0],[g,I,L,D]=r(i,[a,l,h]);if(D<=1e-4)return{x:0,y:0,z:1,visible:!1};let O=g/D,o=I/D,f=L/D,p=this.canvas.getBoundingClientRect(),m=p.width||this.canvas.clientWidth||this.canvas.width||300,y=p.height||this.canvas.clientHeight||this.canvas.height||150,w=(O*.5+.5)*m,x=(-o*.5+.5)*y,z=O>=-1.1&&O<=1.1&&o>=-1.1&&o<=1.1&&f>=-1&&f<=1;if(z&&t){let[R,_,C]=_e(this),S=[a-R,l-_,h-C];c*S[0]+T*S[1]+d*S[2]>.05&&(z=!1)}return{x:w,y:x,z:f,visible:z}}setSelectedMesh(e){this.setSelectedMeshes([e])}setSelectedMeshes(e){this.selectedMeshNames=new Set(e.filter(Boolean))}getSelectedMesh(){return[...this.selectedMeshNames][0]||""}setupEvents(){let e=this.canvas,t=Ge;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},n=i.clientX-r.x,a=i.clientY-r.y;if(this.activePointers.set(i.pointerId,{x:i.clientX,y:i.clientY}),this.lastPointerX=i.clientX,this.lastPointerY=i.clientY,this.totalDragDist+=Math.hypot(n,a),this.isPanning||i.button===2||i.shiftKey||this.activePointers.size===2){let l=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],h=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],c=this.customTarget?[...this.customTarget]:[...this.bounds.center],T=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;c[0]+=(-n*l[0]+a*h[0])*T,c[1]+=(-n*l[1]+a*h[1])*T,c[2]+=(-n*l[2]+a*h[2])*T,this.customTarget=c}else this.targetTheta=this.clampTheta(this.targetTheta-n*.008),this.targetPhi=this.clampPhi(this.targetPhi+a*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=i=>{this.lastInteractionTime=t(),this.activePointers.delete(i.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(i.pointerId)}catch{}if(this.totalDragDist<5&&i.button===0){let r=e.getBoundingClientRect(),n=Math.floor((i.clientX-r.left)*(e.width/Math.max(r.width,1))),a=Math.floor((i.clientY-r.top)*(e.height/Math.max(r.height,1)));this.performMeshPick(n,a,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=i=>{if(!this.interactive)return;i.preventDefault(),this.lastInteractionTime=t();let r=Math.exp(i.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=i=>{let r=i.detail||{};r.reset?this.resetCamera():this.setCamera(r.theta,r.phi,r.distance,r.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),e.tabIndex!==void 0&&e.tabIndex<0&&(e.tabIndex=0),e.getAttribute?.("role")||e.setAttribute?.("role","region"),e.getAttribute?.("aria-label")||e.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=i=>{if(this.interactive){switch(i.key){case"ArrowLeft":this.targetTheta=this.clampTheta(this.targetTheta-.1);break;case"ArrowRight":this.targetTheta=this.clampTheta(this.targetTheta+.1);break;case"ArrowUp":this.targetPhi=this.clampPhi(this.targetPhi+.08);break;case"ArrowDown":this.targetPhi=this.clampPhi(this.targetPhi-.08);break;case"+":case"=":this.targetDistance=this.clampDistance(this.targetDistance*.9);break;case"-":case"_":this.targetDistance=this.clampDistance(this.targetDistance*1.1);break;case"Home":this.resetCamera();break;default:return}this.lastInteractionTime=t(),i.preventDefault()}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=(i,r,n)=>{this[n]&&(i.removeEventListener(r,this[n]),this[n]=null)},t=this.canvas;for(let[i,r]of[["webglcontextlost","boundContextLost"],["webglcontextrestored","boundContextRestored"],["contextmenu","boundContextMenu"],["pointerdown","boundPointerDown"],["pointermove","boundPointerMove"],["pointerup","boundPointerUp"],["wheel","boundWheel"],["keydown","boundKeyDown"]])e(t,i,r);e(this.container,"setCamera","boundSetCamera"),e(this.container,"resetCamera","boundResetCamera")}raycastFromScreenPoint(e,t){let i=this.canvas,r=i.getBoundingClientRect(),n=i.width||300,a=i.height||300,l=r.width>0?Math.floor((e-r.left)*(n/r.width)):Math.floor(e),h=r.height>0?Math.floor((t-r.top)*(a/r.height)):Math.floor(t);return this.performMeshPick(l,h,!1)}performMeshPick(e,t,i=!0){if(this.meshes.length===0)return null;let r=this.gl,n=Math.max(1,this.canvas.width||300),a=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,n);let l=be();ye(l,this.projMatrix,this.viewMatrix);let h=[],c=Math.max(0,Math.min(n-1,e)),T=Math.max(0,Math.min(a-1,a-1-t));if(this.pickFbo&&r&&!this.xrSessionActive){(this.pickFboWidth!==n||this.pickFboHeight!==a)&&this.resizePickingFbo(n,a),r.bindFramebuffer(36160,this.pickFbo),r.viewport(0,0,n,a),r.enable(2929),r.clearColor(0,0,0,0),r.clear(16640),r.useProgram(this.pickProg);for(let w=0;w<this.meshes.length;w++){let x=this.meshes[w];if(x.visible===!1||x.isPluginMesh)continue;let z=w+1,R=(z&255)/255,_=(z>>8&255)/255,C=(z>>16&255)/255;r.uniform4f(this.uPick.uColorId,R,_,C,1),ye(this.modelMatrix,this.modelRootMatrix,x.transform);let S=x.instanceMatrices;if(S&&S.length>=16){let N=S.length>>4,V=be();for(let b of x.primitives){r.bindVertexArray(b.vao);for(let P=0;P<N;P++)ye(V,this.modelMatrix,S.subarray(P*16,P*16+16)),ye(this.mvpMatrix,l,V),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),ke(r,b)}}else{ye(this.mvpMatrix,l,this.modelMatrix),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let N of x.primitives)r.bindVertexArray(N.vao),ke(r,N)}}let m=new Uint8Array(4);r.readPixels(c,T,1,1,6408,5121,m),r.bindFramebuffer(36160,null);let y=m[0]+(m[1]<<8)+(m[2]<<16);y>0&&y<=this.meshes.length&&(h=[this.meshes[y-1]])}h.length===0&&(h=this.meshes.filter(m=>m.visible!==!1));let d=null,g=1/0,I=[0,0,0],L=[0,1,0],[D,O,o]=_e(this),f=be();for(let m of h){ye(f,this.modelRootMatrix,m.transform);let y=m.instanceMatrices,w=y&&y.length>=16?y.length>>4:1;for(let x=0;x<w;x++){y&&y.length>=16?ye(this.modelMatrix,f,y.subarray(x*16,x*16+16)):this.modelMatrix.set(f),ye(this.mvpMatrix,l,this.modelMatrix);let z=be();if(!bt(z,this.mvpMatrix))continue;let R=(c+.5)/n*2-1,_=(T+.5)/a*2-1,C=[0,0,0],S=[0,0,0];nt(C,R,_,-1,z),nt(S,R,_,1,z);let N=S[0]-C[0],V=S[1]-C[1],b=S[2]-C[2],P=Math.hypot(N,V,b)||1,E=N/P,j=V/P,v=b/P,$={distance:1/0,point:[0,0,0],normal:[0,1,0]};for(let s of m.primitives){if(!s.positions)continue;let M=s.positions,u=s.indices,A=Math.floor(u?u.length/3:M.length/9);for(let H=0;H<A;H++){let q=(u?u[H*3]:H*3)*3,Z=(u?u[H*3+1]:H*3+1)*3,W=(u?u[H*3+2]:H*3+2)*3;gt(C[0],C[1],C[2],E,j,v,M[q],M[q+1],M[q+2],M[Z],M[Z+1],M[Z+2],M[W],M[W+1],M[W+2],$,1e-4)}}if(isFinite($.distance)){let s=$.point[0],M=$.point[1],u=$.point[2],A=this.modelMatrix,H=A[0]*s+A[4]*M+A[8]*u+A[12],q=A[1]*s+A[5]*M+A[9]*u+A[13],Z=A[2]*s+A[6]*M+A[10]*u+A[14],W=H-D,ne=q-O,ae=Z-o,he=Math.hypot(W,ne,ae);if(he<g){Le(this.normalMatrix,this.modelMatrix);let oe=this.normalMatrix,U=$.normal[0],K=$.normal[1],k=$.normal[2],Q=oe[0]*U+oe[3]*K+oe[6]*k,ee=oe[1]*U+oe[4]*K+oe[7]*k,X=oe[2]*U+oe[5]*K+oe[8]*k,F=Math.hypot(Q,ee,X)||1;Q/=F,ee/=F,X/=F,Q*W+ee*ne+X*ae>0&&(Q=-Q,ee=-ee,X=-X);let B=G=>Math.round(G*1e3)/1e3;d=m,g=B(he),I=[B(H),B(q),B(Z)],L=[B(Q),B(ee),B(X)]}}}}if(!d)return null;let p={meshIndex:this.meshes.indexOf(d),meshName:d.name,nodeIndex:d.nodeIndex,distance:g,hitPoint:I,normal:L,screenX:e,screenY:t};if(i){for(let m of fe)m.onMeshSelect?.(this,p);this.opts.onMeshClick&&this.opts.onMeshClick(p),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:p}))}return p}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let i=Math.max(1,Math.floor(t*.5)),r=e>=i,n=r?e-i:e,a=r?Math.max(1,t-i):i,l=(n+.5)/a*2-1;return Math.floor((l*.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);Qe(this.projMatrix,this.fov,e,.1,t);let i=this.customTarget||this.bounds.center;et(this.viewMatrix,_e(this),i,[0,1,0]),ye(this.mvpMatrix,this.projMatrix,this.viewMatrix),Le(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 fe)i.onXRSessionEnd?.(this);if(this.lastTime=Ge(),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 fe)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=Ge();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,,r]=this.bounds.center;this.modelRootMatrix.set([e,0,-t,0,0,1,0,0,t,0,e,0,i-(e*i+t*r),0,r-(-t*i+e*r),1])}setVisible(e){this.isVisible=e}update(e){for(let a of fe)a.onUpdate?.(this,e);let t=Ge();if(!this.isPointerDown&&this.autoRotate&&t-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*e,this.updateTurntableMatrix();for(let a of fe)a.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let i=Math.round((this.currTheta*180/Math.PI%360+360)%360),r=Math.round(this.currPhi*180/Math.PI),n=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(n-this.lastReportedZoom)>=.02){this.lastReportedTheta=i,this.lastReportedPhi=r,this.lastReportedZoom=n;let a={theta:i,phi:r,zoom:n,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(a),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:a}))}}renderXRView(e,t,i,r,n=!0,a=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let l=e?.transform?.inverse?.matrix||this.viewMatrix,h=e?.projectionMatrix||this.projMatrix,c=e?.transform?.position,T=c?[c.x,c.y,c.z]:[0,1.6,0];t&&this.modelRootMatrix.set(t),this.render({viewMatrix:l,projMatrix:h,eyePos:T,viewport:r,eye:e?.eye||"none",clear:a>0?!1:e?.eye!=="right",isAR:n})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let x=Math.max(2,this.canvas.width||2),z=Math.max(1,this.canvas.height||1),R=Math.max(1,Math.floor(x*.5)),_=Math.max(1,x-R),C=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),S=this.customTarget||this.bounds.center,[N,V,b]=_e(this),P=Math.cos(this.currTheta),E=-Math.sin(this.currTheta),j=.032;for(let v of[-1,1]){let $=be(),s=be(),M=v<0?R:_,u=[N+v*P*j,V,b+v*E*j];Qe($,this.fov,M/z,.1,C),et(s,u,[S[0]+v*P*j*.25,S[1],S[2]+v*E*j*.25],[0,1,0]),this.render({viewMatrix:s,projMatrix:$,eyePos:u,viewport:[v<0?0:R,0,M,z],eye:v<0?"left":"right",clear:v<0,isAR:!1})}this.gl.viewport(0,0,x,z);return}let t=this.gl,[i,r,n,a]=e?.viewport||[0,0,this.canvas.width,this.canvas.height];if(t.viewport(i,r,n,a),t.enable(2929),!e||e.clear!==!1){let x=e?.isAR?[0,0,0,0]:this.clearColor;t.clearColor(x[0],x[1],x[2],x[3]),t.clear(16640)}let l=be(),h=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=h;let c=e?.projMatrix??this.projMatrix;ye(l,c,h);let T=Ae(),d=T.xrDepthShader,g=Ht(this.toneMapping),[I,L,D]=e?e.eyePos:_e(this);for(let x of fe)x.onBeforeDrawScene?.(this,t,l,[I,L,D],g);let O=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&O===0){T.gpuSceneAccelerator?.hideLayer?.(this);return}let o=e?.eye||"none",f=!e||e.clear!==!1;if(!this.xrSessionActive&&T.gpuSceneAccelerator?.renderScene(this,l,c,h,[I,L,D],g,[i,r,n,a],o,f,!!e?.isAR)){f&&!this.skyboxTexture&&(t.clearColor(0,0,0,0),t.clear(16384));for(let x of fe)x.name.includes("webgpu")&&x.onAfterRender?.(t,this,l,o,[i,r,n,a],c);return}let p=!1,m=O>0?[...this.backdropMeshes,...this.meshes]:this.meshes,y=(x,z,R,_)=>{z?(t.activeTexture(33984+x),t.bindTexture(3553,z),t.uniform1i(R,x),t.uniform1i(_,1)):t.uniform1i(_,0)},w=x=>{for(let z=0;z<m.length;z++){let R=m[z];if(R.visible===!1)continue;let _=this.selectedMeshNames.has(R.name);if(z<O||R.worldSpace===!0||R.name==="__xr_reticle__")this.modelMatrix.set(R.transform);else{ye(this.modelMatrix,this.modelRootMatrix,R.transform);let P=!e&&(R.extras?.xr?.billboard??R.userData?.xr?.billboard);if(P){let E=this.modelMatrix,j=Math.hypot(E[0],E[1],E[2])||1,v=Math.hypot(E[4],E[5],E[6])||1,$=Math.hypot(E[8],E[9],E[10])||1,s=P==="y"||P==="cylindrical"||P==="capsule",M=I-E[12],u=D-E[14],A=Math.hypot(M,u),H=A>1e-5?M/A:0,q=A>1e-5?u/A:1;E.set(s?[q*j,0,-H*j,0,0,v,0,0,H*$,0,q*$]:[h[0]*j,h[4]*j,h[8]*j,0,h[1]*v,h[5]*v,h[9]*v,0,h[2]*$,h[6]*$,h[10]*$])}}ye(this.mvpMatrix,l,this.modelMatrix),Le(R.normalMatrix,this.modelMatrix);let C=R.extras?.xr?.stereo||R.userData?.xr?.stereo,S=0,N=0,V=1,b=1;C==="sbs"?(V=.5,S=o==="right"?.5:0):C==="ou"&&(b=.5,N=o==="right"?.5:0);for(let P of R.primitives){let E=!!P.isTransmissive;if(!x&&E){p=!0;continue}if(x&&!E)continue;let j=P.customProgram||this.renderProg,v=P.customUniforms||this.uRender;t.useProgram(j),t.vertexAttrib3f(3,0,0,0),v.uInstanced&&t.uniform1i(v.uInstanced,0),t.uniform1i(v.uToneMapping,g),t.uniform1f(v.uEnvIntensity,this.envIntensity),v.uExposure&&t.uniform1f(v.uExposure,this.exposure),t.uniform3f(v.uCameraPos,I,L,D),t.uniform1f(v.uEmissive,_?1:0),t.uniformMatrix4fv(v.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(v.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(v.uNormalMatrix,!1,R.normalMatrix),v.uUvTransform&&t.uniform4f(v.uUvTransform,S,N,V,b),v.uViewportSize&&t.uniform2f(v.uViewportSize,Math.max(1,n),Math.max(1,a)),d?.bind(t,v,this.xrDepthState,h,[i,r,Math.max(1,n),Math.max(1,a)]),T.shadowMapShader?.bind(t,v,this,R),y(4,this.environmentTexture,v.uEnvironmentMap,v.uHasEnvironmentMap),this.bindLights(v),v.uSectionEnabled&&t.uniform1i(v.uSectionEnabled,0);for(let s of fe)s.onBeforeDrawPrimitive?.(t,j,P,R,this.worldMatrices||[],this.gltf);t.uniform4fv(v.uBaseColor,P.baseColor),t.uniform1f(v.uMetallic,P.metallic),t.uniform1f(v.uRoughness,P.roughness),v.uClearcoat&&t.uniform2f(v.uClearcoat,P.clearcoat??0,P.clearcoatRoughness??.04),y(0,P.texture,v.uBaseColorTexture,v.uHasTexture),y(1,P.metallicRoughnessTexture,v.uMetallicRoughnessTexture,v.uHasMetallicRoughnessTexture),y(2,P.normalTexture,v.uNormalTexture,v.uHasNormalTexture),P.normalTexture&&t.uniform1f(v.uNormalScale,P.normalScale),y(3,P.occlusionTexture,v.uOcclusionTexture,v.uHasOcclusionTexture),P.occlusionTexture&&t.uniform1f(v.uOcclusionStrength,P.occlusionStrength),t.uniform3fv(v.uEmissiveFactor,P.emissiveFactor),y(8,P.emissiveTexture,v.uEmissiveTexture,v.uHasEmissiveTexture),t.bindVertexArray(P.vao);let $=R.instanceMatrices;if(P.instanceCount!==void 0)t.drawElementsInstanced(4,P.indexCount,P.indexType,0,P.instanceCount);else if($&&$.length>=16&&P.instanced&&v.uInstanced&&v.uViewProj){let s=$.length>>4;t.uniform1i(v.uInstanced,1),t.uniformMatrix4fv(v.uViewProj,!1,l),P.indices?t.drawElementsInstanced(4,P.indexCount,P.indexType,0,s):t.drawArraysInstanced(4,0,P.indexCount,s),t.uniform1i(v.uInstanced,0)}else if($&&$.length>=16){let s=$.length>>4,M=R.instanceColors,u=be(),A=new Float32Array(9);for(let H=0;H<s;H++){if(ye(u,this.modelMatrix,$.subarray(H*16,H*16+16)),ye(this.mvpMatrix,l,u),Le(A,u),t.uniformMatrix4fv(v.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(v.uModel,!1,u),t.uniformMatrix3fv(v.uNormalMatrix,!1,A),M){let q=P.baseColor,Z=H*3;t.uniform4fv(v.uBaseColor,[q[0]*M[Z],q[1]*M[Z+1],q[2]*M[Z+2],q[3]])}ke(t,P)}}else ke(t,P)}}};if(w(!1),p){for(let x of fe)x.onBeforeTransmissivePass?.(t,this);w(!0)}for(let x of fe)x.onAfterRender?.(t,this,l,o,[i,r,n,a],c)}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 fe)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()}};Oe.registerPlugin=dt,Oe.getRegisteredPlugins=ft;function nn(e){return e+3&-4}var J=(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 Lt(e,t,i){let r=Math.hypot(e,t,i)||1,n=e/r,a=t/r,l=-(i/r);if(l<-.999999)return[0,1,0,0];let h=Math.sqrt((1+l)*2);return[a/h,-n/h,0,h*.5]}function Dt(e,t=0){let[i,r,n,,a,l,h,,c,T,d,,g,I,L]=Array.from({length:15},($,s)=>J(e[t+s],s%5===0?1:0)),D=Math.hypot(i,r,n),O=Math.hypot(a,l,h),o=Math.hypot(c,T,d);i*(l*d-T*h)-a*(r*d-T*n)+c*(r*h-l*n)<0&&(D=-D);let f=Math.abs(D)>1e-8?1/D:0,p=Math.abs(O)>1e-8?1/O:0,m=Math.abs(o)>1e-8?1/o:0,y=i*f,w=r*f,x=n*f,z=a*p,R=l*p,_=h*p,C=c*m,S=T*m,N=d*m,V=y+R+N,b=0,P=0,E=0,j=1;if(V>0){let $=.5/Math.sqrt(V+1);j=.25/$,b=(_-S)*$,P=(C-x)*$,E=(w-z)*$}else if(y>R&&y>N){let $=2*Math.sqrt(Math.max(0,1+y-R-N));$>1e-8&&(j=(_-S)/$,b=.25*$,P=(z+w)/$,E=(C+x)/$)}else if(R>N){let $=2*Math.sqrt(Math.max(0,1+R-y-N));$>1e-8&&(j=(C-x)/$,b=(z+w)/$,P=.25*$,E=(_+S)/$)}else{let $=2*Math.sqrt(Math.max(0,1+N-y-R));$>1e-8&&(j=(w-z)/$,b=(C+x)/$,P=(_+S)/$,E=.25*$)}let v=Math.hypot(b,P,E,j);return v>1e-8&&Number.isFinite(v)?(b/=v,P/=v,E/=v,j/=v):(b=0,P=0,E=0,j=1),{t:[g,I,L],r:[b,P,E,j],s:[D,O,o]}}function rn(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 Te=(e,t,i,r)=>typeof e=="number"&&Number.isFinite(e)?Math.max(t,Math.min(i,e)):r;function Pt(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,n=typeof i.preset=="string"?i.preset:void 0;return!r&&!n?null:{ae:i,src:r,preset:n,volume:Te(i.volume,0,2,.6),loop:typeof i.loop=="boolean"?i.loop:!0,isGlobal:i.type==="global"||i.positional===!1}}function mt(e){let t=e?.material,i=t?._presetMaps?.map;if(!i||i!==t.map)return null;let r=/^ai_([0-9a-f]{16})_albedo$/.exec(String(i.name??""));return r?r[1]:null}function on(e,t){let i=mt(t),r=e?.material;return!i||!r||typeof r!="object"||Array.isArray(r)?e:{...e,material:{...r,textureKey:i}}}function Ct(e,t){return Et(e,t)[0]}function Et(e,t){e.updateMatrixWorld(!0);let i=[],r=0,n=[],a=[],l=[],h=[],c=new Set,T=[],d=[],g=new Map,I=[],L=[],D=[],O=new Map,o=[],f=[],p=[],m=!1;function y(s){let M=g.get(s);if(M!==void 0)return M;M=d.length,g.set(s,M);let u=s,A=u.color?.r??1,H=u.color?.g??1,q=u.color?.b??1,Z=u.opacity??1,W={baseColorFactor:[A,H,q,Z],metallicFactor:u.metalness??0,roughnessFactor:u.roughness??.5},ne={},ae=te=>{if(!te)return;let ve=(typeof te=="string"?te:typeof te.source=="string"?te.source:typeof te.image=="string"?te.image:"").trim();if(!ve||/[\x00-\x1f\x7f\\]|\.\./.test(ve)||!(/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(ve)||!ve.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(ve)))return;let se=O.get(ve);if(se===void 0){let ce=I.length;I.push({uri:ve}),L.length===0&&L.push({magFilter:9729,minFilter:9987,wrapS:10497,wrapT:10497}),se=D.length,D.push({sampler:0,source:ce}),O.set(ve,se)}return{index:se}},he=u._packPbr?.(),oe=ae(u.map);oe&&(W.baseColorTexture=oe);let U=ae(he?.mrUri||u.roughnessMap||u.metalnessMap);U&&(W.metallicRoughnessTexture=U);let K=u.map?.avgColor;Array.isArray(K)&&K.length>=3&&(ne.avgColor=[K[0],K[1],K[2]]);let k=ae(he?.normUri||u.normalMap),Q=u.normalScale,ee=he?.normUri?he.normScale??1:typeof Q=="number"?Math.max(0,J(Q,1)):Q?Math.max(0,(J(Q.x,1)+J(Q.y,1))*.5):1;k&&ee!==1&&(k.scale=ee);let X=ae(u.emissiveMap),F=ae(u.aoMap),B=Math.max(0,Math.min(1,J(u.aoMapIntensity,1)));F&&B!==1&&(F.strength=B);let G={name:u.name||"",pbrMetallicRoughness:W,doubleSided:u.side===2||!!u.doubleSided,...Z<1||u.transparent?{alphaMode:"BLEND"}:{},...k?{normalTexture:k}:{},...X?{emissiveTexture:X}:{},...F?{occlusionTexture:F}:{},...Object.keys(ne).length>0?{extras:ne}:{}},Y=Math.max(0,J(u.emissiveIntensity,1)),re=u.emissive&&(u.emissive.r>0||u.emissive.g>0||u.emissive.b>0);(re||X&&!u._em&&Y>0)&&(G.emissiveFactor=re?[u.emissive.r*Y,u.emissive.g*Y,u.emissive.b*Y]:[Y,Y,Y]);let ie={};u.clearcoat&&u.clearcoat>0&&(ie.KHR_materials_clearcoat={clearcoatFactor:u.clearcoat,clearcoatRoughnessFactor:u.clearcoatRoughness||0}),u.sheen&&u.sheen>0&&(ie.KHR_materials_sheen={sheenColorFactor:u.sheenColor?[u.sheenColor.r,u.sheenColor.g,u.sheenColor.b]:[1,1,1],sheenRoughnessFactor:u.sheenRoughness||0}),u.transmission&&u.transmission>0&&(ie.KHR_materials_transmission={transmissionFactor:u.transmission}),u.thickness&&u.thickness>0&&(ie.KHR_materials_volume={thicknessFactor:u.thickness,attenuationDistance:u.attenuationDistance??1/0,attenuationColor:u.attenuationColor?[u.attenuationColor.r,u.attenuationColor.g,u.attenuationColor.b]:[1,1,1]}),u.ior!==void 0&&u.ior!==1.5&&(ie.KHR_materials_ior={ior:u.ior}),u.dispersion&&u.dispersion>0&&(ie.KHR_materials_dispersion={dispersion:u.dispersion}),u.iridescence&&u.iridescence>0&&(ie.KHR_materials_iridescence={iridescenceFactor:u.iridescence,iridescenceIor:u.iridescenceIOR??1.3});let me=u._serializeTslGraph?.();return me&&(ie.GOOGLE_material_tsl=me,c.add("GOOGLE_material_tsl")),Object.keys(ie).length>0&&(G.extensions=ie),d.push(G),M}function w(s,M){let u=new Uint8Array(s.buffer,s.byteOffset,s.byteLength),A=nn(u.byteLength),H=new Uint8Array(A);H.set(u),i.push(H);let q=n.length;return n.push({buffer:0,byteOffset:r,byteLength:u.byteLength,target:M}),r+=A,q}function x(s,M,u,A,H,q,Z){let W=w(s,u),ne=a.length,ae={bufferView:W,byteOffset:0,componentType:A,count:H,type:M};return q&&(ae.min=q),Z&&(ae.max=Z),a.push(ae),ne}let z=[],R=[],_=new Set([e]),C=[];if(Array.isArray(e.children))for(let s=e.children.length-1;s>=0;s--)C.push({obj:e.children[s],parentKids:R});for(;C.length>0;){let{obj:s,parentKids:M}=C.pop();if(!s||typeof s!="object"||_.has(s))continue;_.add(s),s._bakeAuthorGeometry?.(),Ae().materializeDeclarativeGeometry?.(s);let u=!!(s.userData&&(s.userData.xr&&typeof s.userData.xr=="object"&&Object.keys(s.userData.xr).length>0||s.userData.interactivity&&typeof s.userData.interactivity=="object"&&Object.keys(s.userData.interactivity).length>0)),A={name:s.name||(u?`Node_${h.length}`:"")},H=J(s.position?.x,0),q=J(s.position?.y,0),Z=J(s.position?.z,0),W=J(s.quaternion?.x,0),ne=J(s.quaternion?.y,0),ae=J(s.quaternion?.z,0),he=J(s.quaternion?.w,1),oe=J(s.scale?.x,1),U=J(s.scale?.y,1),K=J(s.scale?.z,1);if((H||q||Z)&&(A.translation=[H,q,Z]),(W||ne||ae||he!==1)&&(A.rotation=[W,ne,ae,he]),(oe!==1||U!==1||K!==1)&&(A.scale=[oe,U,K]),s.visible===!1&&(A.extensions={...A.extensions||{},KHR_node_visibility:{visible:!1}},c.add("KHR_node_visibility")),s.userData&&Object.keys(s.userData).length>0&&(A.extras=JSON.parse(JSON.stringify(s.userData,(F,B)=>{if(!(F==="__proto__"||F==="prototype"||F==="constructor"))return typeof B=="function"?void 0:B})),s.userData.xr)){let F=rn(s.userData.xr);A.extensions={...A.extensions||{},MOZ_hubs_components:F,ANDROID_xr_scenecore:F},Ae().xrTraitSerializer?.gltfNode(A,s.userData.xr);let B=mt(s),G=A.extras?.xr?.material;B&&G&&typeof G=="object"&&!Array.isArray(G)&&(G.textureKey=B),c.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}let k=s,Q=k.isLight||k.color&&k.intensity!==void 0;if(!Q&&(k._castShdSet||k._recvShdSet||s.castShadow||s.receiveShadow)&&(A.extras={...A.extras||{},shadow:{cast:!!s.castShadow,receive:k._recvShdSet?!!s.receiveShadow:!!(s.receiveShadow||s.castShadow)}}),Q){let F=k.matrixWorld?.elements,B=J(F?F[12]:s.position?.x,0),G=J(F?F[13]:s.position?.y,0),Y=J(F?F[14]:s.position?.z,0),re=k.target,ie=re?.parent?re?.matrixWorld?.elements:void 0,me=J(ie?ie[12]:re?.position?.x,0),te=J(ie?ie[13]:re?.position?.y,0),ve=J(ie?ie[14]:re?.position?.z,0),se=me-B,ce=te-G,le=ve-Y,ue=Math.hypot(se,ce,le),ge=Math.max(.01,Math.min(Math.PI/2,J(k.angle,Math.PI/3))),xe=Math.max(0,Math.min(1,J(k.penumbra,0))),de=Math.max(0,ge*(1-xe)),Me=Math.max(0,J(k.distance,0)),Ce=s.type==="directional"||s.type==="spot"||s.type==="point",Se;if(s.castShadow&&Ce){let Re=k.shadow,qe=Math.max(256,Math.min(2048,Math.round(J(Re?.mapSize?.x??Re?.mapSize?.width,1024))));Se={cast:!0,mapSize:qe<=384?256:qe<=768?512:qe<=1536?1024:2048,bias:Te(Re?.bias,-.05,.05,-5e-4),normalBias:Te(Re?.normalBias,0,.2,.015),radius:Te(Re?.radius,0,8,1.5)},m=!0}let Ue=B-me,Ke=G-te,Xe=Y-ve,De=Math.hypot(Ue,Ke,Xe);f.push({type:s.type,color:[s.color.r,s.color.g,s.color.b],intensity:s.intensity,position:s.type==="directional"?[Ue,Ke,Xe]:[B,G,Y],...s.type==="directional"?{direction:De>1e-6?[Ue/De,Ke/De,Xe/De]:[0,1,0]}:s.type==="spot"?{direction:ue>1e-6?[se/ue,ce/ue,le/ue]:[0,-1,0],outerConeAngle:ge,innerConeAngle:de,range:Me}:s.type==="point"?{range:Me}:s.type==="hemisphere"&&k.groundColor?{groundColor:[k.groundColor.r,k.groundColor.g,k.groundColor.b]}:{},...Se?{shadow:Se}:{}}),Ce&&z.push({node:A,obj:s,px:B,py:G,pz:Y,tx:me,ty:te,tz:ve,dx:se,dy:ce,dz:le,dLen:ue,outerAngle:ge,innerAngle:de,range:Me,shadowSpec:Se})}if(s.geometry){let F=s.geometry,B=F.attributes.position;if(B&&B.count>0){let G=[1/0,1/0,1/0],Y=[-1/0,-1/0,-1/0];for(let se=0;se<B.count;se++){let ce=B.getX(se),le=B.getY(se),ue=B.getZ(se);ce<G[0]&&(G[0]=ce),ce>Y[0]&&(Y[0]=ce),le<G[1]&&(G[1]=le),le>Y[1]&&(Y[1]=le),ue<G[2]&&(G[2]=ue),ue>Y[2]&&(Y[2]=ue)}let re={attributes:{POSITION:x(B.array,"VEC3",34962,5126,B.count,G,Y)}};if(F.attributes.normal&&(re.attributes.NORMAL=x(F.attributes.normal.array,"VEC3",34962,5126,F.attributes.normal.count)),F.attributes.uv&&(re.attributes.TEXCOORD_0=x(F.attributes.uv.array,"VEC2",34962,5126,F.attributes.uv.count)),F.index){let se=F.index.array instanceof Uint32Array;re.indices=x(F.index.array,"SCALAR",34963,se?5125:5123,F.index.count)}let ie=Array.isArray(s.material)?s.material[0]:s.material;ie&&(re.material=y(ie));let me=s.userData?.variants;if(me&&typeof me=="object"){let se=new Map;for(let ce of Object.keys(me)){if(!ce||ce==="__proto__"||ce==="constructor"||ce==="prototype")continue;let le=me[ce];if(!le||typeof le!="object")continue;let ue=o.indexOf(ce);if(ue===-1&&o.length<256&&(ue=o.length,o.push(ce)),ue===-1)continue;let ge=y(le),xe=se.get(ge);xe||(xe=[],se.set(ge,xe)),xe.push(ue)}if(se.size>0){let ce=[];for(let[le,ue]of se.entries())ce.push({material:le,variants:ue});re.extensions={...re.extensions||{},KHR_materials_variants:{mappings:ce}},c.add("KHR_materials_variants")}}let te=s;if(te.isInstancedMesh&&typeof te.count=="number"&&te.count>0&&te.instanceMatrix?.array){let se=Math.min(1e4,Math.floor(te.count)),ce=te.instanceMatrix.array,le=new Float32Array(se*3),ue=new Float32Array(se*4),ge=new Float32Array(se*3);for(let de=0;de<se;de++){let{t:Me,r:Ce,s:Se}=Dt(ce,de*16);le[de*3]=Me[0],le[de*3+1]=Me[1],le[de*3+2]=Me[2],ue[de*4]=Ce[0],ue[de*4+1]=Ce[1],ue[de*4+2]=Ce[2],ue[de*4+3]=Ce[3],ge[de*3]=Se[0],ge[de*3+1]=Se[1],ge[de*3+2]=Se[2]}let xe={TRANSLATION:x(le,"VEC3",0,5126,se),ROTATION:x(ue,"VEC4",0,5126,se),SCALE:x(ge,"VEC3",0,5126,se)};if(te.instanceColor?.array&&te.instanceColor.array.length>=se*3){let de=new Float32Array(te.instanceColor.array.subarray(0,se*3));xe._COLOR_0=x(de,"VEC3",0,5126,se)}A.extensions={...A.extensions||{},EXT_mesh_gpu_instancing:{attributes:xe}},c.add("EXT_mesh_gpu_instancing")}let ve=l.length;l.push({primitives:[re],name:s.name,...A.extras?{extras:A.extras}:{}}),A.mesh=ve}}let ee=h.length;h.push(A),T.push(s),M.push(ee);let X=s.children;if(Array.isArray(X)&&X.length>0){let F=[];A.children=F;for(let B=X.length-1;B>=0;B--)C.push({obj:X[B],parentKids:F})}}if(m)for(let s of z){let M=p.length;if(p.push({name:s.obj.name||`Light_${M}`,type:s.obj.type,color:[s.obj.color.r,s.obj.color.g,s.obj.color.b],intensity:s.obj.intensity,...s.range>0&&(s.obj.type==="point"||s.obj.type==="spot")?{range:s.range}:{},...s.obj.type==="spot"?{spot:{innerConeAngle:s.innerAngle,outerConeAngle:s.outerAngle}}:{},...s.shadowSpec?{extras:{shadow:s.shadowSpec}}:{}}),s.node.extensions={...s.node.extensions||{},KHR_lights_punctual:{light:M}},c.add("KHR_lights_punctual"),s.obj.type==="directional"||s.obj.type==="spot"){let u=s.dLen>1e-6?s.dx/s.dLen:0,A=s.dLen>1e-6?s.dy/s.dLen:-1,H=s.dLen>1e-6?s.dz/s.dLen:0;s.node.rotation=Lt(u,A,H),s.obj.type==="directional"&&(s.tx||s.ty||s.tz)&&(s.node.translation=[s.px-s.tx,s.py-s.ty,s.pz-s.tz])}}for(let s=0;s<h.length;s++){let M=h[s];M.children&&M.children.length===0?delete M.children:M.children&&M.children.length>0&&(M.extras?.xr?.lod||M.extensions?.ANDROID_xr_scenecore?.lod||T[s]?.isLOD)&&(M.extensions={...M.extensions||{},MSFT_lod:{ids:[...M.children]}},c.add("MSFT_lod"))}let S=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),N=[];if(typeof S=="function"&&T.length>0){let s=t?.duration??4,M=t?.fps??15,u=Math.max(2,Math.round(s*M)+1),A=new Float32Array(u),H=T.map(U=>[J(U.position?.x,0),J(U.position?.y,0),J(U.position?.z,0),J(U.quaternion?.x,0),J(U.quaternion?.y,0),J(U.quaternion?.z,0),J(U.quaternion?.w,1),J(U.scale?.x,1),J(U.scale?.y,1),J(U.scale?.z,1)]),q=T.map(()=>new Float32Array(u*3)),Z=T.map(()=>new Float32Array(u*4)),W=T.map(()=>new Float32Array(u*3));for(let U=0;U<u;U++){let K=U/(u-1)*s;A[U]=K;try{S(K)}catch{}for(let k=0;k<T.length;k++){let Q=T[k];q[k][U*3]=J(Q.position?.x,0),q[k][U*3+1]=J(Q.position?.y,0),q[k][U*3+2]=J(Q.position?.z,0);let ee=J(Q.quaternion?.x,0),X=J(Q.quaternion?.y,0),F=J(Q.quaternion?.z,0),B=J(Q.quaternion?.w,1),G=Math.hypot(ee,X,F,B)||1;if(ee/=G,X/=G,F/=G,B/=G,U>0){let Y=(U-1)*4,re=Z[k];re[Y]*ee+re[Y+1]*X+re[Y+2]*F+re[Y+3]*B<0&&(ee=-ee,X=-X,F=-F,B=-B)}Z[k][U*4]=ee,Z[k][U*4+1]=X,Z[k][U*4+2]=F,Z[k][U*4+3]=B,W[k][U*3]=J(Q.scale?.x,1),W[k][U*3+1]=J(Q.scale?.y,1),W[k][U*3+2]=J(Q.scale?.z,1)}}for(let U=0;U<T.length;U++){let K=T[U],k=H[U];K.position?.set(k[0],k[1],k[2]),K.quaternion?.set(k[3],k[4],k[5],k[6]),K.scale?.set(k[7],k[8],k[9])}e.updateMatrixWorld(!0);let ne=null,ae=()=>(ne===null&&(ne=x(A,"SCALAR",0,5126,u,[0],[s])),ne),he=[],oe=[];for(let U=0;U<T.length;U++){let K=H[U],k=(ee,X,F)=>ee.some((B,G)=>Math.abs(B-K[F+G%X])>1e-4),Q=(ee,X,F,B)=>{ee&&oe.push({sampler:he.push({input:ae(),interpolation:"LINEAR",output:x(X,F,0,5126,u)})-1,target:{node:U,path:B}})};Q(k(q[U],3,0),q[U],"VEC3","translation"),Q(k(Z[U],4,3),Z[U],"VEC4","rotation"),Q(k(W[U],3,7),W[U],"VEC3","scale")}oe.length>0&&N.push({name:"ProceduralLoop",samplers:he,channels:oe})}let V=Ze(h,l,e.userData),b=[],P=[],E=[];for(let s=0;s<h.length;s++){let M=h[s],u=Pt(M.extras?.xr);if(!u)continue;let{ae:A,src:H,preset:q,volume:Z,loop:W,isGlobal:ne}=u,ae=M.name||`Node_${s}`,he=P.length;P.push({name:`${ae}_source`,gain:Z,loop:W,autoPlay:typeof A.autoplay=="boolean"?A.autoplay:!0,...H!==void 0?{audio:b.push({uri:H})-1}:{},...q?{extras:{preset:q,pitch:Te(A.pitch,.25,4,1)}}:{}});let oe=E.length,U=Te(A.refDistance,.05,100,1),K=Te(A.coneInnerAngle,0,360,360),k=Te(A.coneOuterAngle,K,360,360);E.push({name:`${ae}_emitter`,type:ne?"global":"positional",gain:Z,sources:[he],...ne?{}:{positional:{distanceModel:A.distanceModel==="linear"||A.distanceModel==="exponential"?A.distanceModel:"inverse",refDistance:U,maxDistance:Te(A.maxDistance,U,500,Math.max(U,25)),rolloffFactor:Te(A.rolloffFactor,0,10,1),coneInnerAngle:+(K*Math.PI/180).toFixed(6),coneOuterAngle:+(k*Math.PI/180).toFixed(6),coneOuterGain:Te(A.coneOuterGain,0,1,0)}}}),M.extensions={...M.extensions||{},KHR_audio_emitter:{emitter:oe}},c.add("KHR_audio_emitter")}let j={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:e.environmentIntensity,...f.length>0?{lights:f}:{}}},scenes:[{nodes:R}],scene:0,nodes:h,meshes:l,materials:d,...I.length>0?{images:I}:{},...L.length>0?{samplers:L}:{},...D.length>0?{textures:D}:{},accessors:a,bufferViews:n,buffers:[{byteLength:r}],...N.length>0?{animations:N}:{},...V||c.size>0?{extensionsUsed:[...V?["KHR_interactivity"]:[],...c]}:{},...V||o.length>0||E.length>0||p.length>0?{extensions:{...V?{KHR_interactivity:V}:{},...o.length>0?{KHR_materials_variants:{variants:o.map(s=>({name:s}))}}:{},...E.length>0?{KHR_audio_emitter:{...b.length>0?{audio:b}:{},sources:P,emitters:E}}:{},...p.length>0?{KHR_lights_punctual:{lights:p}}:{}}}:{}},v=new Uint8Array(r),$=0;for(let s of i)v.set(s,$),$+=s.byteLength;return[{gltf:j,bin:v.buffer,lights:f,environmentIntensity:e.environmentIntensity},T]}function je(e){return new TextEncoder().encode(e)}function sn(e,t){let{gltf:i,bin:r}=Ct(e,t),n=JSON.stringify(i),a=je(n),l=(4-a.byteLength%4)%4,h=a.byteLength+l,c=20+h+8+r.byteLength,T=new Uint8Array(c),d=new DataView(T.buffer);d.setUint32(0,1179937895,!0),d.setUint32(4,2,!0),d.setUint32(8,c,!0),d.setUint32(12,h,!0),d.setUint32(16,1313821514,!0),T.set(a,20);for(let I=0;I<l;I++)T[20+a.byteLength+I]=32;let g=20+h;return d.setUint32(g,r.byteLength,!0),d.setUint32(g+4,5130562,!0),T.set(new Uint8Array(r),g+8),T}function ht(e,t){let[i,r]=Et(e,t);return We(i,r)}function We(e,t){let i=[],r=e.gltf,n=Ae().decoders.get("meshopt");n&&typeof n.decodeBufferViews=="function"&&n.decodeBufferViews(r,e);let a=e.bin,l=a instanceof ArrayBuffer?a:a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),h=r.accessors||[],c=r.bufferViews||[],T=r.materials||[],d=r.meshes||[],g=r.nodes||[],I=r.textures||[],L=r.images||[],D=r.samplers||[],O=new Set,o=T.map((R,_)=>lt(O,Pe(R?.name,`Material_${_}`))),f=new Map;function p(R){let _=/^data:image\/(png|jpe?g)(?:;[^,]*)?;base64,([A-Za-z0-9+/=\s]+)$/i.exec(R);if(!_)return null;let C=_[2].replace(/\s+/g,""),S=C.endsWith("==")?2:C.endsWith("=")?1:0,N=new Uint8Array((C.length*3>>2)-S),V=P=>{let E=C.charCodeAt(P);return E>96?E-71:E>64?E-65:E>47?E+4:E===43?62:E===47?63:0},b=0;for(let P=0;P<C.length;P+=4){let E=V(P)<<18|V(P+1)<<12|V(P+2)<<6|V(P+3);N[b++]=E>>16&255,b<N.length&&(N[b++]=E>>8&255),b<N.length&&(N[b++]=E&255)}return N}function m(R,_,C){let S=R?.index;if(typeof S!="number")return;let N=I[S],V=N?.source;if(typeof V!="number"||!L[V])return;let b=f.get(V);if(b===void 0){b=null;let j=L[V],v=null;if(typeof j.bufferView=="number"){let $=c[j.bufferView],s=$?.byteOffset||0,M=$?.byteLength||0;$&&M>0&&s>=0&&s+M<=l.byteLength&&(v=new Uint8Array(l,s,M))}else typeof j.uri=="string"&&(v=p(j.uri));if(v&&v.byteLength>0){let $=v[0]===255&&v[1]===216&&v[2]===255||!(v[0]===137&&v[1]===80)&&/jpe?g/i.test(j.mimeType||j.uri||"");b={file:`texture_${V}.${$?"jpg":"png"}`,data:v}}f.set(V,b)}if(!b)return;let P=typeof N.sampler=="number"?D[N.sampler]:void 0,E=j=>j===33071?"clamp":j===33648?"mirror":"repeat";return{file:b.file,data:b.data,wrapS:E(P?.wrapS),wrapT:E(P?.wrapT),..._?{scale:_}:{},...C?{bias:C}:{}}}function y(R){let _=h[R];if(!_)throw new Error(`Accessor ${R} not found`);let C=c[_.bufferView||0],S=(C.byteOffset||0)+(_.byteOffset||0),N=C.byteLength||0;return{acc:_,buffer:l.slice(S,S+N)}}function w(R,_,C,S){let N=[],V=d[R];if(!V)return N;let b=V.primitives||[];for(let P=0;P<b.length;P++){let E=b[P],j=E.attributes?.POSITION;if(j===void 0)continue;let{acc:v,buffer:$}=y(j),s=new Float32Array($,0,v.count*3),M,u=E.attributes?.NORMAL;if(u!==void 0){let{acc:X,buffer:F}=y(u),B=new Float32Array(F,0,X.count*3);M=new Float32Array(B.length);for(let G=0;G<X.count;G++){let Y=B[G*3],re=B[G*3+1],ie=B[G*3+2],me=Math.hypot(Y,re,ie)||1;M[G*3]=Y/me,M[G*3+1]=re/me,M[G*3+2]=ie/me}}let A,H=E.attributes?.TEXCOORD_0;if(H!==void 0){let{acc:X,buffer:F}=y(H);A=new Float32Array(F,0,X.count*2)}let q;if(E.indices!==void 0){let{acc:X,buffer:F}=y(E.indices);q=X.componentType===5125?new Uint32Array(F,0,X.count):new Uint16Array(F,0,X.count);let B=v.count;for(let G of q)if(G>=B)throw new Error(`SecurityError: Index buffer value (${G}) out of vertex bounds [0, ${B}).`)}else{let X=v.count;q=X>65535?new Uint32Array(X):new Uint16Array(X);for(let F=0;F<X;F++)q[F]=F}let Z="DefaultMaterial",W=[1,1,1],ne=.5,ae=0,he=0,oe=0,U=1.5,K=1,k=[0,0,0],Q,ee={};if(E.material!==void 0&&T[E.material]){let X=T[E.material];Z=o[E.material]||`Material_${E.material}`;let F=X.pbrMetallicRoughness||{},B=(de,Me)=>Array.isArray(de)&&de.length>=3?[de[0],de[1],de[2]]:Me;W=B(F.baseColorFactor,[1,1,1]);let G=Array.isArray(F.baseColorFactor)&&typeof F.baseColorFactor[3]=="number"?F.baseColorFactor[3]:1,Y=W[0]!==1||W[1]!==1||W[2]!==1||G!==1,re=m(F.baseColorTexture,Y?[W[0],W[1],W[2],G]:void 0),ie=X.extras?.avgColor;!re&&Array.isArray(ie)&&ie.length>=3&&(W=[W[0]*ie[0],W[1]*ie[1],W[2]*ie[2]]),typeof F.roughnessFactor=="number"&&(ne=F.roughnessFactor),typeof F.metallicFactor=="number"&&(ae=F.metallicFactor);let me=typeof F.roughnessFactor=="number"?F.roughnessFactor:1,te=typeof F.metallicFactor=="number"?F.metallicFactor:1,ve=m(F.metallicRoughnessTexture,me!==1||te!==1?[1,me,te,1]:void 0);k=B(X.emissiveFactor,[0,0,0]);let se=(k[0]>0||k[1]>0||k[2]>0)&&(k[0]!==1||k[1]!==1||k[2]!==1)?[k[0],k[1],k[2],1]:void 0,ce=m(X.emissiveTexture,se),le=typeof X.normalTexture?.scale=="number"?X.normalTexture.scale:1,ue=m(X.normalTexture,[2*le,2*le,2,1],[-le,-le,-1,0]),ge=typeof X.occlusionTexture?.strength=="number"?X.occlusionTexture.strength:1,xe=ge!==1?m(X.occlusionTexture,[ge,ge,ge,1],[1-ge,1-ge,1-ge,0]):m(X.occlusionTexture);(re||ve||ue||ce||xe)&&(Q=[re,ve,ue,ce,xe]),ee=X.extensions||{},ee.KHR_materials_clearcoat&&(he=ee.KHR_materials_clearcoat.clearcoatFactor??0,oe=ee.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),typeof ee.KHR_materials_ior?.ior=="number"&&(U=ee.KHR_materials_ior.ior),K=G*(1-(ee.KHR_materials_transmission?.transmissionFactor??0))}N.push({name:b.length>1?`${_}_p${P}`:_,positions:s,indices:q,normals:M,uvs:A,materialName:Z,color:W,roughness:ne,metallic:ae,clearcoat:he,clearcoatRoughness:oe,ior:U,opacity:K,emissiveColor:k,...Q?{textures:Q}:{},...ee.GOOGLE_material_tsl?{tslGraph:ee.GOOGLE_material_tsl}:{},xrTraits:C||V.extras?.xr,...S?{invisible:!0}:{}})}return N}if(g.length>0){let R=new Float32Array(0),_=new Uint16Array(0),C=(s,M)=>{if(s===void 0)return null;let{acc:u,buffer:A}=y(s);return new Float32Array(A,0,u.count*M)},S=(s,M)=>Array.isArray(s)&&s.length>=3?[J(s[0],M),J(s[1],M),J(s[2],M)]:[M,M,M],N=(s,M,u)=>s&&s.length>=(M+1)*3?[s[M*3],s[M*3+1],s[M*3+2]]:u,V=(s,M,u)=>s&&s.length>=(M+1)*4?[s[M*4],s[M*4+1],s[M*4+2],s[M*4+3]]:u,b=new Map,P=r.animations?.[0];if(P&&Array.isArray(P.channels)&&Array.isArray(P.samplers))for(let s of P.channels){let M=P.samplers[s?.sampler],u=s?.target?.node,A=s?.target?.path;if(!M||typeof u!="number"||M.input===void 0)continue;let H=b.get(u);H||(H={input:M.input},b.set(u,H)),A==="translation"?H.t=M.output:A==="rotation"?H.r=M.output:A==="scale"&&(H.s=M.output)}let E=r.scenes?.[r.scene??0]?.nodes??[];if(!Array.isArray(E)||E.length===0){let s=new Set;for(let M of g)if(Array.isArray(M?.children))for(let u of M.children)s.add(u);E=[];for(let M=0;M<g.length;M++)s.has(M)||E.push(M);E.length===0&&(E=[0])}let j=new Set,v=[],$=(s,M)=>{if(Array.isArray(s))for(let u=s.length-1;u>=0;u--)v.push({idx:s[u],out:M})};for($(E,i);v.length>0;){let{idx:s,out:M}=v.pop();if(typeof s!="number"||s<0||s>=g.length||j.has(s))continue;j.add(s);let u=g[s];if(!u)continue;let A=[0,0,0],H=[0,0,0,1],q=[1,1,1];if(Array.isArray(u.matrix)&&u.matrix.length===16){let K=Dt(u.matrix);A=K.t,H=K.r,q=K.s}else A=S(u.translation,0),Array.isArray(u.rotation)&&u.rotation.length>=4&&(H=[J(u.rotation[0],0),J(u.rotation[1],0),J(u.rotation[2],0),J(u.rotation[3],1)]),q=S(u.scale,1);let Z,W=b.get(s);if(W){let K=C(W.input,1);if(K&&K.length>0){let k=C(W.t,3),Q=C(W.r,4),ee=C(W.s,3),X=Array.from(K),F=[],B=[],G=[];for(let Y=0;Y<K.length;Y++)F.push(N(k,Y,A)),B.push(V(Q,Y,H)),G.push(N(ee,Y,q));Z={times:X,translations:F,rotations:B,scales:G}}}let ne=Array.isArray(u.children)?u.children:[],ae=typeof u.mesh=="number"&&u.mesh>=0&&u.mesh<d.length,he=t?.[s]?.userData?.xr??u.extras?.xr;if(!ae&&ne.length===0&&(u.camera!==void 0||u.extensions?.KHR_lights_punctual||!u.name&&!u.extras&&!he&&!Z))continue;let oe=(K,k,Q)=>({name:K,positions:R,indices:_,isXform:!0,xrTraits:he,timeSamples:Z,translation:A,rotation:H,scale:q,children:k,...Q?{invisible:!0}:{}}),U=u.visible===!1||u.extensions?.KHR_node_visibility?.visible===!1||t?.[s]?.visible===!1;if(ae){let K=u.name||d[u.mesh]?.name||`Mesh_${s}`,k=w(u.mesh,K,he,U),Q=t?.[s],ee=!!(Q?._castShdSet||Q?._recvShdSet),X=typeof u.extras?.shadow?.cast=="boolean"?u.extras.shadow.cast:ee?!!Q?.castShadow:void 0;if(X!==void 0)for(let B of k)B.castShadow=X;let F=u.extensions?.EXT_mesh_gpu_instancing?.attributes;if(F&&typeof F=="object"&&k.length>0){let B=C(F.TRANSLATION,3),G=C(F.ROTATION,4),Y=C(F.SCALE,3),re=C(F._COLOR_0,3),ie=Math.min(1e3,B?B.length/3:G?G.length/4:Y?Y.length/3:0);if(ie>0){let me=[];for(let te=0;te<ie;te++){let ve=N(B,te,[0,0,0]),se=V(G,te,[0,0,0,1]),ce=N(Y,te,[1,1,1]);for(let le of k){let ue=le.color||[.8,.8,.8],ge=re&&re.length>=(te+1)*3;me.push({...le,name:`${le.name}_${te}`,materialName:ge?`${le.materialName}_inst_${te}`:le.materialName,color:ge?[ue[0]*re[te*3],ue[1]*re[te*3+1],ue[2]*re[te*3+2]]:le.color,translation:ve,rotation:se,scale:ce})}}$(ne,me),M.push(oe(K,me,U));continue}}if(k.length===1)k[0].translation=A,k[0].rotation=H,k[0].scale=q,k[0].timeSamples=Z,ne.length>0&&(k[0].children=[],$(ne,k[0].children)),M.push(k[0]);else{let B=[...k];$(ne,B),M.push(oe(K,B,U))}}else{let K=[];$(ne,K),M.push(oe(u.name||`Group_${s}`,K,U))}}}else for(let R=0;R<d.length;R++){let _=d[R].name||`Mesh_${R}`;i.push(...w(R,_,d[R].extras?.xr))}let x=(Array.isArray(e.lights)&&e.lights.length>0?e.lights:void 0)??ct(r)??(Array.isArray(r?.asset?.extras?.lights)?r.asset.extras.lights:[]),z=[];for(let R=0;R<x.length;R++){let _=x[R];_?.shadow?.cast&&(_.type==="directional"||_.type==="spot"||_.type==="point")&&z.push({name:`Light_${R}`,type:_.type,color:_.color,intensity:_.intensity,position:_.position,direction:_.direction,range:_.range,innerConeAngle:_.innerConeAngle,outerConeAngle:_.outerConeAngle,shadow:_.shadow})}return z.length>0&&(i.__usdaShadowLights=z),i}function Pe(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 Ne(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function pe(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 we=(e,t,i)=>`(${pe(e)}, ${pe(t)}, ${pe(i)})`,Fe=(e,t,i,r)=>`(${pe(e)}, ${pe(t)}, ${pe(i)}, ${pe(r)})`;function Rt(e){let t=e.length/3,i=new Array(t);for(let r=0;r<t;r++)i[r]=we(e[r*3],e[r*3+1],e[r*3+2]);return i.join(", ")}function an(e,t){let i=new Array(t);for(let r=0;r<t;r++)i[r]=`(${pe(e[r*2])}, ${pe(1-e[r*2+1])})`;return i.join(", ")}function un(e){return Array.from(e).join(", ")}function He(e,t){let i=(t??e.__usdaShadowLights??[]).filter(o=>o?.shadow?.cast),r=new Map,n=0,a=null,l=[...e];for(;l.length>0;){let o=l.pop();if(!o.isXform&&o.positions&&o.positions.length>0){let f=Pe(o.materialName,"DefaultMaterial");r.has(f)||r.set(f,{color:o.color||[1,1,1],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],textures:o.textures,tslGraph:o.tslGraph})}if(o.timeSamples&&o.timeSamples.times.length>0){let f=o.timeSamples.times[o.timeSamples.times.length-1];f>n&&(n=f)}else o.tslGraph&&n<=0&&JSON.stringify(o.tslGraph).includes('"time"')&&(n=60);if(o.xrTraits?.anchor&&!a&&(a=o.xrTraits.anchor==="vertical"||o.xrTraits.anchor==="wall"?"vertical":"horizontal"),o.children)for(let f=o.children.length-1;f>=0;f--)l.push(o.children[f])}let h="";n>0&&(h=`startTimeCode = 0
215
+ endTimeCode = ${pe(n)}
251
216
  timeCodesPerSecond = 1.0
252
- `);let m="";r&&(m=`uniform token preliminary:anchoring:type = "plane"
253
- uniform token preliminary:planeAnchoring:alignment = "${r}"
254
- `);let f=`#usda 1.0
217
+ `);let c="";a&&(c=`uniform token preliminary:anchoring:type = "plane"
218
+ uniform token preliminary:planeAnchoring:alignment = "${a}"
219
+ `);let T=`#usda 1.0
255
220
  (
256
221
  defaultPrim = "Root"
257
222
  metersPerUnit = 1.0
258
223
  upAxis = "Y"
259
- ${s})
224
+ ${h})
260
225
 
261
226
  def Xform "Root" (
262
227
  kind = "component"
263
228
  )
264
229
  {
265
- ${m}def Scope "Materials"
230
+ ${c}def Scope "Materials"
231
+ {
232
+ `;for(let[o,f]of r.entries()){let[p,m,y]=f.color,[w,x,z]=f.emissiveColor,R=`/Root/Materials/${o}`,[_,C,S,N,V]=f.textures||[],b=(M,u)=>`.connect = <${R}/${M}.outputs:${u}>`,P=_?`color3f inputs:diffuseColor${b("DiffuseTexture","rgb")}`:`color3f inputs:diffuseColor = ${we(p,m,y)}`,E=C?`float inputs:metallic${b("MetallicRoughnessTexture","b")}
233
+ float inputs:roughness${b("MetallicRoughnessTexture","g")}`:`float inputs:metallic = ${pe(f.metallic)}
234
+ float inputs:roughness = ${pe(f.roughness)}`,j="";f.clearcoat>0&&(j+=`float inputs:clearcoat = ${pe(f.clearcoat)}
235
+ `,j+=`float inputs:clearcoatRoughness = ${pe(f.clearcoatRoughness)}
236
+ `),f.ior!==1.5&&(j+=`float inputs:ior = ${pe(f.ior)}
237
+ `),f.opacity<1&&(j+=`float inputs:opacity = ${pe(f.opacity)}
238
+ `),N?j+=`color3f inputs:emissiveColor${b("EmissiveTexture","rgb")}
239
+ `:(w>0||x>0||z>0)&&(j+=`color3f inputs:emissiveColor = ${we(w,x,z)}
240
+ `),S&&(j+=`normal3f inputs:normal${b("NormalTexture","rgb")}
241
+ `),V&&(j+=`float inputs:occlusion${b("OcclusionTexture","r")}
242
+ `);let v="";if(_||C||S||N||V){v+=`def Shader "PrimvarReader"
266
243
  {
267
- `;for(let[l,x]of e.entries()){let[T,w,v]=x.color,[h,n,b]=x.emissiveColor,A="";x.clearcoat>0&&(A+=`float inputs:clearcoat = ${le(x.clearcoat)}
268
- `,A+=`float inputs:clearcoatRoughness = ${le(x.clearcoatRoughness)}
269
- `),x.ior!==1.5&&(A+=`float inputs:ior = ${le(x.ior)}
270
- `),x.opacity<1&&(A+=`float inputs:opacity = ${le(x.opacity)}
271
- `),(h>0||n>0||b>0)&&(A+=`color3f inputs:emissiveColor = ${pe(h,n,b)}
272
- `),f+=`def Material "${l}"
244
+ uniform token info:id = "UsdPrimvarReader_float2"
245
+ string inputs:varname = "st"
246
+ float2 outputs:result
247
+ }
248
+ `;let M=(u,A,H,q)=>{if(!A)return;let Z=A.scale?`float4 inputs:scale = ${Fe(A.scale[0],A.scale[1],A.scale[2],A.scale[3])}
249
+ `:"",W=A.bias?`float4 inputs:bias = ${Fe(A.bias[0],A.bias[1],A.bias[2],A.bias[3])}
250
+ `:"";v+=`def Shader "${u}"
251
+ {
252
+ uniform token info:id = "UsdUVTexture"
253
+ asset inputs:file = @${Ne(A.file)}@
254
+ float2 inputs:st${b("PrimvarReader","result")}
255
+ token inputs:sourceColorSpace = "${H}"
256
+ token inputs:wrapS = "${A.wrapS||"repeat"}"
257
+ token inputs:wrapT = "${A.wrapT||"repeat"}"
258
+ ${Z}${W}${q}}
259
+ `};M("DiffuseTexture",_,"sRGB",`float3 outputs:rgb
260
+ `),M("MetallicRoughnessTexture",C,"raw",`float outputs:g
261
+ float outputs:b
262
+ `),M("NormalTexture",S,"raw",`float3 outputs:rgb
263
+ `),M("EmissiveTexture",N,"sRGB",`float3 outputs:rgb
264
+ `),M("OcclusionTexture",V,"raw",`float outputs:r
265
+ `)}let $=`${P}
266
+ ${E}
267
+ ${j}`,s=f.tslGraph&&Ae().tslUsdzSerializer?.(f.tslGraph,o,$);s&&($=s.surfaceInputsUsda||$,v+=s.nodeGraphUsda),T+=`def Material "${o}"
273
268
  {
274
269
  def Shader "PBRShader"
275
270
  {
276
271
  uniform token info:id = "UsdPreviewSurface"
277
- color3f inputs:diffuseColor = ${pe(T,w,v)}
278
- float inputs:metallic = ${le(x.metallic)}
279
- float inputs:roughness = ${le(x.roughness)}
280
- ${A}token outputs:surface
281
- }
282
- token outputs:surface.connect = </Root/Materials/${l}/PBRShader.outputs:surface>
272
+ ${$}token outputs:surface
283
273
  }
284
- `}f+=`}
274
+ token outputs:surface${b("PBRShader","surface")}
275
+ ${v}}
276
+ `}T+=`}
285
277
  def Scope "Meshes"
286
278
  {
287
- `;let p=(l,x,T)=>{let w=[];x&&w.push('"MaterialBindingAPI"');let v=!!(l?.rigidBody&&l.rigidBody!=="none"&&(typeof l.rigidBody!="object"||l.rigidBody.enabled!==!1)),h=!!(l?.physics&&l.physics!=="none"||v);h&&w.push(...v?['"PhysicsBodyAPI"','"PhysicsRigidBodyAPI"','"PhysicsCollisionAPI"','"PhysicsMassAPI"']:['"PhysicsBodyAPI"','"PhysicsCollisionAPI"']);let n=[];if(w.length>0&&n.push(`prepend apiSchemas = [${w.join(", ")}]`),l){let _=de().xrTraitSerializer?.usdLines(l,_e)??[];if(!_.length)for(let L of["grab","billboard","follow","anchor","physics"]){let C=L==="follow"&&typeof l.follow=="object"?l.follow.mode??"head":l[L];C!==void 0&&_.push(`string ${L} = "${_e(C)}"`)}_.length>0&&n.push(`customData = {
279
+ `;let d=(o,f,p)=>{let m=[];f&&m.push('"MaterialBindingAPI"');let y=!!(o?.rigidBody&&o.rigidBody!=="none"&&(typeof o.rigidBody!="object"||o.rigidBody.enabled!==!1)),w=!!(o?.physics&&o.physics!=="none"||y);w&&m.push(...y?['"PhysicsBodyAPI"','"PhysicsRigidBodyAPI"','"PhysicsCollisionAPI"','"PhysicsMassAPI"']:['"PhysicsBodyAPI"','"PhysicsCollisionAPI"']);let x=[];m.length>0&&x.push(`prepend apiSchemas = [${m.join(", ")}]`);let z=Ae().xrTraitSerializer;if(o){let N=z?.usdLines(o,Ne)??[];if(!N.length)for(let V of["grab","billboard","follow","anchor","physics"]){let b=V==="follow"&&typeof o.follow=="object"?o.follow.mode??"head":o[V];b!==void 0&&N.push(`string ${V} = "${Ne(b)}"`)}N.length>0&&x.push(`customData = {
288
280
  dictionary xr = {
289
- ${_.join(`
281
+ ${N.join(`
290
282
  `)}
291
283
  }
292
- }`)}let b=n.length>0?` (
293
- ${n.join(`
284
+ }`)}let R=x.length>0?` (
285
+ ${x.join(`
294
286
  `)}
295
- )`:"",A=T?`uniform token visibility = "invisible"
296
- `:"";if(h){let _=l?.rigidBody??l?.physics,L=_?.body??_?.mode??_;A+=`bool physics:rigidBodyEnabled = true
297
- bool physics:kinematicEnabled = ${L==="static"||L==="kinematic"}
287
+ )`:"",_=p?`uniform token visibility = "invisible"
288
+ `:"";if(w){let N=o?.rigidBody??o?.physics,V=N?.body??N?.mode??N;_+=`bool physics:rigidBodyEnabled = true
289
+ bool physics:kinematicEnabled = ${V==="static"||V==="kinematic"}
298
290
  bool physics:collisionEnabled = true
299
- `,_?.mass>0&&Number.isFinite(_.mass)&&(A+=`float physics:mass = ${le(_.mass)}
300
- `)}let $=pt(l),B=$?`def SpatialAudio "AudioEmitter"
291
+ `,N?.mass>0&&Number.isFinite(N.mass)&&(_+=`float physics:mass = ${pe(N.mass)}
292
+ `)}let C=Pt(o),S=(C?`def SpatialAudio "AudioEmitter"
301
293
  {
302
- ${$.src?`asset inputs:file = @${_e($.src)}@
303
- `:""}uniform token inputs:auralMode = "${$.isGlobal?"nonSpatial":"spatial"}"
304
- uniform token inputs:playbackMode = "${$.loop?"loopFromStart":"onceFromStart"}"
305
- double gain = ${le($.volume)}
294
+ ${C.src?`asset inputs:file = @${Ne(C.src)}@
295
+ `:""}uniform token inputs:auralMode = "${C.isGlobal?"nonSpatial":"spatial"}"
296
+ uniform token inputs:playbackMode = "${C.loop?"loopFromStart":"onceFromStart"}"
297
+ double gain = ${pe(C.volume)}
306
298
  }
307
- `:"";return{header:b,body:A,tail:B}},u=l=>{if(l.timeSamples&&l.timeSamples.times.length>0){let n=l.timeSamples,b=(_,L,C)=>n.times.map((D,M)=>`${le(D)}: ${C(_?.[M]||L)}`).join(", "),A=b(n.translations,[0,0,0],_=>pe(_[0],_[1],_[2])),$=b(n.rotations,[0,0,0,1],_=>{let L=Math.hypot(_[0],_[1],_[2],_[3])||1;return mt(_[3]/L,_[0]/L,_[1]/L,_[2]/L)}),B=b(n.scales,[1,1,1],_=>pe(_[0],_[1],_[2]));return`double3 xformOp:translate.timeSamples = { ${A} }
308
- quatf xformOp:orient.timeSamples = { ${$} }
309
- double3 xformOp:scale.timeSamples = { ${B} }
299
+ `:"")+(o?z?.usdPrims?.(o)??"":"");return{header:R,body:_,tail:S}},g=o=>{if(o.timeSamples&&o.timeSamples.times.length>0){let x=o.timeSamples,z=(S,N,V)=>x.times.map((b,P)=>`${pe(b)}: ${V(S?.[P]||N)}`).join(", "),R=z(x.translations,[0,0,0],S=>we(S[0],S[1],S[2])),_=z(x.rotations,[0,0,0,1],S=>{let N=Math.hypot(S[0],S[1],S[2],S[3])||1;return Fe(S[3]/N,S[0]/N,S[1]/N,S[2]/N)}),C=z(x.scales,[1,1,1],S=>we(S[0],S[1],S[2]));return`double3 xformOp:translate.timeSamples = { ${R} }
300
+ quatf xformOp:orient.timeSamples = { ${_} }
301
+ double3 xformOp:scale.timeSamples = { ${C} }
310
302
  uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:orient", "xformOp:scale"]
311
- `}let x=[],T="",w=l.translation;w&&(Math.abs(w[0])>1e-7||Math.abs(w[1])>1e-7||Math.abs(w[2])>1e-7)&&(T+=`double3 xformOp:translate = ${pe(w[0],w[1],w[2])}
312
- `,x.push('"xformOp:translate"'));let v=l.rotation;if(v){let n=Math.hypot(v[0],v[1],v[2],v[3])||1,b=v[0]/n,A=v[1]/n,$=v[2]/n,B=v[3]/n;(1-Math.abs(B)>1e-7||Math.hypot(b,A,$)>1e-7)&&(T+=`quatf xformOp:orient = ${mt(B,b,A,$)}
313
- `,x.push('"xformOp:orient"'))}let h=l.scale;return h&&(Math.abs(h[0]-1)>1e-7||Math.abs(h[1]-1)>1e-7||Math.abs(h[2]-1)>1e-7)&&(T+=`float3 xformOp:scale = ${pe(h[0],h[1],h[2])}
314
- `,x.push('"xformOp:scale"')),x.length>0&&(T+=`uniform token[] xformOpOrder = [${x.join(", ")}]
315
- `),T},d=l=>{let x=l.positions.length/3,T=1/0,w=1/0,v=1/0,h=-1/0,n=-1/0,b=-1/0;for(let L=0;L<x;L++){let C=l.positions[L*3],D=l.positions[L*3+1],M=l.positions[L*3+2];C<T&&(T=C),C>h&&(h=C),D<w&&(w=D),D>n&&(n=D),M<v&&(v=M),M>b&&(b=M)}isFinite(T)||(T=w=v=-1,h=n=b=1);let A=Math.floor(l.indices.length/3),$=we(l.materialName,"DefaultMaterial"),B=A>0?A===1?"3":"3, ".repeat(A-1)+"3":"",_=`float3[] extent = [${pe(T,w,v)}, ${pe(h,n,b)}]
316
- int[] faceVertexCounts = [${B}]
317
- int[] faceVertexIndices = [${Xt(l.indices)}]
318
- point3f[] points = [${ht(l.positions)}]
319
- `;return l.normals&&l.normals.length===l.positions.length&&(_+=`normal3f[] normals = [${ht(l.normals)}] (
303
+ `}let f=[],p="",m=o.translation;m&&(Math.abs(m[0])>1e-7||Math.abs(m[1])>1e-7||Math.abs(m[2])>1e-7)&&(p+=`double3 xformOp:translate = ${we(m[0],m[1],m[2])}
304
+ `,f.push('"xformOp:translate"'));let y=o.rotation;if(y){let x=Math.hypot(y[0],y[1],y[2],y[3])||1,z=y[0]/x,R=y[1]/x,_=y[2]/x,C=y[3]/x;(1-Math.abs(C)>1e-7||Math.hypot(z,R,_)>1e-7)&&(p+=`quatf xformOp:orient = ${Fe(C,z,R,_)}
305
+ `,f.push('"xformOp:orient"'))}let w=o.scale;return w&&(Math.abs(w[0]-1)>1e-7||Math.abs(w[1]-1)>1e-7||Math.abs(w[2]-1)>1e-7)&&(p+=`float3 xformOp:scale = ${we(w[0],w[1],w[2])}
306
+ `,f.push('"xformOp:scale"')),f.length>0&&(p+=`uniform token[] xformOpOrder = [${f.join(", ")}]
307
+ `),p},I=o=>{let f=o.positions.length/3,p=1/0,m=1/0,y=1/0,w=-1/0,x=-1/0,z=-1/0;for(let N=0;N<f;N++){let V=o.positions[N*3],b=o.positions[N*3+1],P=o.positions[N*3+2];V<p&&(p=V),V>w&&(w=V),b<m&&(m=b),b>x&&(x=b),P<y&&(y=P),P>z&&(z=P)}isFinite(p)||(p=m=y=-1,w=x=z=1);let R=Math.floor(o.indices.length/3),_=Pe(o.materialName,"DefaultMaterial"),C=R>0?R===1?"3":"3, ".repeat(R-1)+"3":"",S=`float3[] extent = [${we(p,m,y)}, ${we(w,x,z)}]
308
+ int[] faceVertexCounts = [${C}]
309
+ int[] faceVertexIndices = [${un(o.indices)}]
310
+ point3f[] points = [${Rt(o.positions)}]
311
+ `;return o.normals&&o.normals.length===o.positions.length&&(S+=`normal3f[] normals = [${Rt(o.normals)}] (
320
312
  interpolation = "vertex"
321
313
  )
322
- `),l.uvs&&l.uvs.length===x*2&&(_+=`texCoord2f[] primvars:st = [${jt(l.uvs,x)}] (
314
+ `),o.uvs&&o.uvs.length===f*2&&(S+=`texCoord2f[] primvars:st = [${an(o.uvs,f)}] (
323
315
  interpolation = "vertex"
324
316
  )
325
- `),_+=`rel material:binding = </Root/Materials/${$}>
326
- `,_},y=new Set,R=[];for(let l=t.length-1;l>=0;l--)R.push({node:t[l],siblings:y});let S=0;for(;R.length>0;){let l=R.pop();if(l.close){f+=`}
327
- `;continue}let{node:x,siblings:T}=l,w=!!(x.isXform||x.positions.length===0),v=ft(T,we(x.name,w?`Group_${S}`:`Mesh_${S}`));S++;let h=x.children||[];if(w){let n=p(x.xrTraits,!1,x.invisible);f+=`def Xform "${v}"${n.header}
317
+ `),S+=`rel material:binding = </Root/Materials/${_}>
318
+ `,o.castShadow===!1&&i.length>0&&(S+=`bool primvars:doNotCastShadows = 1
319
+ `),S},L=new Set,D=[];for(let o=e.length-1;o>=0;o--)D.push({node:e[o],siblings:L});let O=0;for(;D.length>0;){let o=D.pop();if(o.close){T+=`}
320
+ `;continue}let{node:f,siblings:p}=o,m=!!(f.isXform||f.positions.length===0),y=lt(p,Pe(f.name,m?`Group_${O}`:`Mesh_${O}`));O++;let w=f.children||[];if(m){let x=d(f.xrTraits,!1,f.invisible);T+=`def Xform "${y}"${x.header}
328
321
  {
329
- ${n.body}${u(x)}${n.tail}`,R.push({close:!0});let b=new Set;for(let A=h.length-1;A>=0;A--)R.push({node:h[A],siblings:b})}else if(h.length>0){let n=p(x.xrTraits,!1,x.invisible),b=`${v}_mesh`;f+=`def Xform "${v}"${n.header}
322
+ ${x.body}${g(f)}${x.tail}`,D.push({close:!0});let z=new Set;for(let R=w.length-1;R>=0;R--)D.push({node:w[R],siblings:z})}else if(w.length>0){let x=d(f.xrTraits,!1,f.invisible),z=`${y}_mesh`;T+=`def Xform "${y}"${x.header}
330
323
  {
331
- ${n.body}${u(x)}${n.tail}`,f+=`def Mesh "${b}" (
324
+ ${x.body}${g(f)}${x.tail}`,T+=`def Mesh "${z}" (
332
325
  prepend apiSchemas = ["MaterialBindingAPI"]
333
326
  )
334
327
  {
335
- ${d(x)}}
336
- `,R.push({close:!0});let A=new Set([b]);for(let $=h.length-1;$>=0;$--)R.push({node:h[$],siblings:A})}else{let n=p(x.xrTraits,!0,x.invisible);f+=`def Mesh "${v}"${n.header}
328
+ ${I(f)}}
329
+ `,D.push({close:!0});let R=new Set([z]);for(let _=w.length-1;_>=0;_--)D.push({node:w[_],siblings:R})}else{let x=d(f.xrTraits,!0,f.invisible);T+=`def Mesh "${y}"${x.header}
337
330
  {
338
- ${n.body}${u(x)}${d(x)}${n.tail}}
339
- `}}return f+=`}
340
- }
341
- `,f}function vt(t,e){if(t&&typeof t.traverse=="function"){let a=yt(t,e);return Fe(a)}let i=Ae(t),r=Be(i);return Fe(r)}var Ie=null;function xt(t){if(!Ie){Ie=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;Ie[i]=r}}let e=4294967295;for(let i=0;i<t.length;i++)e=Ie[(e^t[i])&255]^e>>>8;return(e^4294967295)>>>0}function Mt(t){let e=[],i=0,r=[];for(let d of t){let y=Ne(d.filename),R=xt(d.data),S=d.data.length,l=30+y.length,x=(i+l)%64,T=x!==0?64-x:0,w=new Uint8Array(l+T),v=new DataView(w.buffer);v.setUint32(0,67324752,!0),v.setUint16(4,20,!0),v.setUint32(14,R,!0),v.setUint32(18,S,!0),v.setUint32(22,S,!0),v.setUint16(26,y.length,!0),v.setUint16(28,T,!0),w.set(y,30),e.push({offset:i,size:S,crc:R,filenameBytes:y,entry:d}),r.push(w,d.data),i+=w.length+d.data.length}let a=i;for(let d of e){let y=new Uint8Array(46+d.filenameBytes.length),R=new DataView(y.buffer);R.setUint32(0,33639248,!0),R.setUint16(4,20,!0),R.setUint16(6,20,!0),R.setUint32(16,d.crc,!0),R.setUint32(20,d.size,!0),R.setUint32(24,d.size,!0),R.setUint16(28,d.filenameBytes.length,!0),R.setUint32(42,d.offset,!0),y.set(d.filenameBytes,46),r.push(y),i+=y.length}let s=i-a,m=new Uint8Array(22),f=new DataView(m.buffer);f.setUint32(0,101010256,!0),f.setUint16(8,e.length,!0),f.setUint16(10,e.length,!0),f.setUint32(12,s,!0),f.setUint32(16,a,!0),r.push(m),i+=22;let p=new Uint8Array(i),u=0;for(let d of r)p.set(d,u),u+=d.length;return p}var Tt=t=>Mt([{filename:"model.usda",data:Ne(t)}]);function Kt(t){return Tt(vt(t))}function At(t){return Tt(Fe(Be(Ae(t))))}function wt(t){return t&&typeof t.toUSDZ=="function"?t.toUSDZ():At(t)}function qt(t){let e=wt(t);return new Blob([e],{type:"model/vnd.usdz+zip"})}
331
+ ${x.body}${g(f)}${I(f)}${x.tail}}
332
+ `}}if(T+=`}
333
+ `,i.length>0){T+=`def Scope "Lights"
334
+ {
335
+ `;let o=new Set;for(let f=0;f<i.length;f++){let p=i[f],m=lt(o,Pe(p.name,`Light_${f}`)),y=p.type==="directional"?"DistantLight":p.type==="spot"?"DiskLight":"SphereLight",w=p.type==="spot"?'["ShapingAPI", "ShadowAPI"]':'["ShadowAPI"]',[x,z,R]=p.color||[1,1,1],[_,C,S]=p.position||[0,5,5],N=-_,V=-C,b=-S;p.direction&&p.direction.length>=3&&(p.type==="directional"?(N=-p.direction[0],V=-p.direction[1],b=-p.direction[2]):(N=p.direction[0],V=p.direction[1],b=p.direction[2]));let[P,E,j,v]=Lt(N,V,b),$="",s=[];p.type!=="directional"&&(Math.abs(_)>1e-7||Math.abs(C)>1e-7||Math.abs(S)>1e-7)&&($+=`double3 xformOp:translate = ${we(_,C,S)}
336
+ `,s.push('"xformOp:translate"')),p.type!=="point"&&(1-Math.abs(v)>1e-7||Math.hypot(P,E,j)>1e-7)&&($+=`quatf xformOp:orient = ${Fe(v,P,E,j)}
337
+ `,s.push('"xformOp:orient"')),s.length>0&&($+=`uniform token[] xformOpOrder = [${s.join(", ")}]
338
+ `);let M="";if(p.type==="spot"){let u=(p.outerConeAngle??Math.PI/3)*180/Math.PI,A=(p.innerConeAngle??u*.8)*180/Math.PI,H=u>1e-4?Math.max(0,Math.min(1,1-A/u)):0;M=`float inputs:shaping:cone:angle = ${pe(u)}
339
+ float inputs:shaping:cone:softness = ${pe(H)}
340
+ `}T+=`def ${y} "${m}" (
341
+ prepend apiSchemas = ${w}
342
+ )
343
+ {
344
+ color3f inputs:color = ${we(x,z,R)}
345
+ float inputs:intensity = ${pe(p.intensity??1)}
346
+ bool inputs:shadow:enable = 1
347
+ ${M}${$}}
348
+ `}T+=`}
349
+ `}return T+=`}
350
+ `,T}function cn(e,t){if(e&&typeof e.traverse=="function"){let n=ht(e,t);return He(n)}let i=Ie(e),r=We(i);return He(r)}var ze=null;function _t(e){if(!ze){ze=new Uint32Array(256);for(let i=0;i<256;i++){let r=i;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;ze[i]=r}}let t=4294967295;for(let i=0;i<e.length;i++)t=ze[(t^e[i])&255]^t>>>8;return(t^4294967295)>>>0}function It(e){let t=[],i=0,r=[];for(let d of e){let g=je(d.filename),I=_t(d.data),L=d.data.length,D=30+g.length,O=(i+D)%64,o=O!==0?64-O:0;o>0&&o<4&&(o+=64);let f=new Uint8Array(D+o),p=new DataView(f.buffer);p.setUint32(0,67324752,!0),p.setUint16(4,20,!0),p.setUint32(14,I,!0),p.setUint32(18,L,!0),p.setUint32(22,L,!0),p.setUint16(26,g.length,!0),p.setUint16(28,o,!0),f.set(g,30),o>=4&&(p.setUint16(D,6534,!0),p.setUint16(D+2,o-4,!0)),t.push({offset:i,size:L,crc:I,filenameBytes:g,entry:d}),r.push(f,d.data),i+=f.length+d.data.length}let n=i;for(let d of t){let g=new Uint8Array(46+d.filenameBytes.length),I=new DataView(g.buffer);I.setUint32(0,33639248,!0),I.setUint16(4,20,!0),I.setUint16(6,20,!0),I.setUint32(16,d.crc,!0),I.setUint32(20,d.size,!0),I.setUint32(24,d.size,!0),I.setUint16(28,d.filenameBytes.length,!0),I.setUint32(42,d.offset,!0),g.set(d.filenameBytes,46),r.push(g),i+=g.length}let a=i-n,l=new Uint8Array(22),h=new DataView(l.buffer);h.setUint32(0,101010256,!0),h.setUint16(8,t.length,!0),h.setUint16(10,t.length,!0),h.setUint32(12,a,!0),h.setUint32(16,n,!0),r.push(l),i+=22;let c=new Uint8Array(i),T=0;for(let d of r)c.set(d,T),T+=d.length;return c}function Ft(e){let t=[{filename:"model.usda",data:je(He(e))}],i=new Set(["model.usda"]),r=[...e];for(;r.length>0;){let n=r.pop();for(let a of n.textures||[])a?.file&&a.data?.byteLength&&!i.has(a.file)&&(i.add(a.file),t.push({filename:a.file,data:a.data}));if(n.children)for(let a=n.children.length-1;a>=0;a--)r.push(n.children[a])}return It(t)}function ln(e){return Ft(ht(e))}function Nt(e){return Ft(We(Ie(e)))}function Ut(e){return e&&typeof e.toUSDZ=="function"?e.toUSDZ():Nt(e)}function mn(e){let t=Ut(e);return new Blob([t],{type:"model/vnd.usdz+zip"})}