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