three-live 1.2.1 → 1.2.3
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.
- package/README.md +6 -1
- package/dist/index.d.ts +66 -2
- package/dist/three-author-engine.js +85 -42
- package/dist/three-author.cjs +84 -42
- package/dist/three-author.d.ts +66 -2
- package/dist/three-author.js +84 -42
- package/dist/three-convert.cjs +84 -42
- package/dist/three-convert.d.ts +66 -2
- package/dist/three-convert.js +84 -42
- package/dist/three-live-animation.cjs +7 -7
- package/dist/three-live-animation.d.ts +66 -2
- package/dist/three-live-animation.js +7 -7
- package/dist/three-live-animation.min.js +7 -7
- package/dist/three-live-cad.cjs +18 -0
- package/dist/{three-live-extras.d.ts → three-live-cad.d.ts} +66 -2
- package/dist/three-live-cad.js +18 -0
- package/dist/three-live-cad.min.js +18 -0
- package/dist/three-live-element.cjs +48 -6
- package/dist/three-live-element.d.ts +66 -2
- package/dist/three-live-element.js +48 -6
- package/dist/three-live-full.cjs +176 -55
- package/dist/three-live-full.js +176 -55
- package/dist/three-live-full.min.js +176 -55
- package/dist/three-live-studio.cjs +120 -0
- package/dist/three-live-studio.d.ts +510 -0
- package/dist/three-live-studio.js +120 -0
- package/dist/three-live-studio.min.js +120 -0
- package/dist/three-live-viewer.cjs +48 -6
- package/dist/three-live-viewer.d.ts +66 -2
- package/dist/three-live-viewer.js +48 -6
- package/dist/three-live-viewer.min.js +48 -6
- package/dist/three-live.cjs +86 -44
- package/dist/three-live.js +86 -44
- package/dist/three-live.min.js +86 -44
- package/dist/three-view.cjs +48 -6
- package/dist/three-view.d.ts +66 -2
- package/dist/three-view.js +48 -6
- package/dist/three-xr.cjs +83 -41
- package/dist/three-xr.d.ts +66 -2
- package/dist/three-xr.js +83 -41
- package/package.json +10 -5
- package/dist/three-live-extras.cjs +0 -42
- package/dist/three-live-extras.js +0 -42
- package/dist/three-live-extras.min.js +0 -42
package/dist/three-xr.js
CHANGED
|
@@ -14,16 +14,31 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
function
|
|
17
|
+
function re(){let n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n}function ve(n,e,t,r,i){let s=1/Math.tan(e/2);n.fill(0),n[0]=s/t,n[5]=s,n[11]=-1;let a=1/(r-i);return n[10]=(i+r)*a,n[14]=2*i*r*a,n}function Me(n,e,t,r){let[i,s,a]=e,[c,o,l]=r,[u,d,f]=t,T=i-u,p=s-d,h=a-f,b=Math.hypot(T,p,h);b<=1e-5?(T=0,p=0,h=1):(T/=b,p/=b,h/=b);let R=o*h-l*p,A=l*T-c*h,v=c*p-o*T;b=Math.hypot(R,A,v),b<=1e-5?(R=0,A=0,v=0):(R/=b,A/=b,v/=b);let D=p*v-h*A,g=h*R-T*v,P=T*A-p*R;return b=Math.hypot(D,g,P),b<=1e-5?(D=0,g=0,P=0):(D/=b,g/=b,P/=b),n[0]=R,n[1]=D,n[2]=T,n[3]=0,n[4]=A,n[5]=g,n[6]=p,n[7]=0,n[8]=v,n[9]=P,n[10]=h,n[11]=0,n[12]=-(R*i+A*s+v*a),n[13]=-(D*i+g*s+P*a),n[14]=-(T*i+p*s+h*a),n[15]=1,n}function se(n,e,t){let r=e[0],i=e[1],s=e[2],a=e[3],c=e[4],o=e[5],l=e[6],u=e[7],d=e[8],f=e[9],T=e[10],p=e[11],h=e[12],b=e[13],R=e[14],A=e[15],v=t[0],D=t[1],g=t[2],P=t[3];return n[0]=v*r+D*c+g*d+P*h,n[1]=v*i+D*o+g*f+P*b,n[2]=v*s+D*l+g*T+P*R,n[3]=v*a+D*u+g*p+P*A,v=t[4],D=t[5],g=t[6],P=t[7],n[4]=v*r+D*c+g*d+P*h,n[5]=v*i+D*o+g*f+P*b,n[6]=v*s+D*l+g*T+P*R,n[7]=v*a+D*u+g*p+P*A,v=t[8],D=t[9],g=t[10],P=t[11],n[8]=v*r+D*c+g*d+P*h,n[9]=v*i+D*o+g*f+P*b,n[10]=v*s+D*l+g*T+P*R,n[11]=v*a+D*u+g*p+P*A,v=t[12],D=t[13],g=t[14],P=t[15],n[12]=v*r+D*c+g*d+P*h,n[13]=v*i+D*o+g*f+P*b,n[14]=v*s+D*l+g*T+P*R,n[15]=v*a+D*u+g*p+P*A,n}function ye(n,e,t,r){let i=e[0],s=e[1],a=e[2],c=e[3],o=i+i,l=s+s,u=a+a,d=i*o,f=i*l,T=i*u,p=s*l,h=s*u,b=a*u,R=c*o,A=c*l,v=c*u,D=r[0],g=r[1],P=r[2];return n[0]=(1-(p+b))*D,n[1]=(f+v)*D,n[2]=(T-A)*D,n[3]=0,n[4]=(f-v)*g,n[5]=(1-(d+b))*g,n[6]=(h+R)*g,n[7]=0,n[8]=(T+A)*P,n[9]=(h-R)*P,n[10]=(1-(d+p))*P,n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n}function me(n,e){let t=e[0],r=e[1],i=e[2],s=e[4],a=e[5],c=e[6],o=e[8],l=e[9],u=e[10],d=u*a-c*l,f=-u*s+c*o,T=l*s-a*o,p=t*d+r*f+i*T;return p&&(p=1/p,n[0]=d*p,n[1]=f*p,n[2]=T*p,n[3]=(-u*r+i*l)*p,n[4]=(u*t-i*o)*p,n[5]=(-l*t+r*o)*p,n[6]=(c*r-i*a)*p,n[7]=(-c*t+i*s)*p,n[8]=(a*t-r*s)*p),n}function Ge(n,e){let t=e[0],r=e[1],i=e[2],s=e[3],a=e[4],c=e[5],o=e[6],l=e[7],u=e[8],d=e[9],f=e[10],T=e[11],p=e[12],h=e[13],b=e[14],R=e[15],A=t*c-r*a,v=t*o-i*a,D=t*l-s*a,g=r*o-i*c,P=r*l-s*c,E=i*l-s*o,y=u*h-d*p,F=u*b-f*p,L=u*R-T*p,C=d*b-f*h,m=d*R-T*h,w=f*R-T*b,S=A*w-v*m+D*C+g*L-P*F+E*y;return S?(S=1/S,n[0]=(c*w-o*m+l*C)*S,n[1]=(i*m-r*w-s*C)*S,n[2]=(h*E-b*P+R*g)*S,n[3]=(f*P-d*E-T*g)*S,n[4]=(o*L-a*w-l*F)*S,n[5]=(t*w-i*L+s*F)*S,n[6]=(b*D-p*E-R*v)*S,n[7]=(u*E-f*D+T*v)*S,n[8]=(a*m-c*L+l*y)*S,n[9]=(r*L-t*m-s*y)*S,n[10]=(p*P-h*D+R*A)*S,n[11]=(d*D-u*P-T*A)*S,n[12]=(c*F-a*C-o*y)*S,n[13]=(t*C-r*F+i*y)*S,n[14]=(h*v-p*g-b*A)*S,n[15]=(u*g-d*v+f*A)*S,n):null}function Pe(n,e,t,r,i){let s=i[0]*e+i[4]*t+i[8]*r+i[12],a=i[1]*e+i[5]*t+i[9]*r+i[13],c=i[2]*e+i[6]*t+i[10]*r+i[14],o=i[3]*e+i[7]*t+i[11]*r+i[15],l=o!==0?1/o:1;n[0]=s*l,n[1]=a*l,n[2]=c*l}function ze(n,e,t,r,i,s,a,c,o,l,u,d,f,T,p,h,b=0){let R=l-a,A=u-c,v=d-o,D=f-a,g=T-c,P=p-o,E=i*P-s*g,y=s*D-r*P,F=r*g-i*D,L=R*E+A*y+v*F;if(L>-1e-7&&L<1e-7)return!1;let C=1/L,m=n-a,w=e-c,S=t-o,M=C*(m*E+w*y+S*F);if(M<-b||M>1+b)return!1;let k=w*v-S*A,_=S*R-m*v,K=m*A-w*R,U=C*(r*k+i*_+s*K);if(U<-b||M+U>1+b)return!1;let O=C*(D*k+g*_+P*K);if(O>1e-4&&O<h.distance){h.distance=O,h.point=[n+r*O,e+i*O,t+s*O];let B=A*P-v*g,q=v*D-R*P,Y=R*g-A*D,W=Math.hypot(B,q,Y)||1;return h.normal=[B/W,q/W,Y/W],!0}return!1}function Te(n,e){let t=Array.isArray(n?.nodes)?n.nodes.length:0,r=[];for(let u=0;u<t;u++)r.push(re());if(t===0)return r;let i=new Set;for(let u of n.nodes)if(Array.isArray(u.children))for(let d of u.children)i.add(d);let s=new Set,a=128,c=(u,d,f=0)=>{if(f>a||u<0||u>=t||s.has(u))return;s.add(u);let T=n.nodes[u];if(!T)return;let p=re();if(e&&e[u])p.set(e[u]);else if(T.matrix&&T.matrix.length===16)p.set(T.matrix);else{let b=T.translation||[0,0,0],R=T.rotation||[0,0,0,1],A=T.scale||[1,1,1];ye(p,R,b,A)}let h=r[u];if(d?se(h,d,p):h.set(p),Array.isArray(T.children))for(let b of T.children)typeof b=="number"&&c(b,h,f+1)},o=[],l=n.scenes&&n.scenes[n.scene!==void 0?n.scene:0];if(l&&Array.isArray(l.nodes))o.push(...l.nodes);else for(let u=0;u<t;u++)i.has(u)||o.push(u);for(let u of o)c(u,null);for(let u=0;u<t;u++)!i.has(u)&&!o.includes(u)&&c(u,null);return r}var Ae="__THREE_LIVE_REGISTRY__";function he(){let n=typeof globalThis<"u"?globalThis:{};if(!n[Ae]){let e={plugins:[],decoders:new Map};try{Object.defineProperty(n,Ae,{value:e,writable:!1,configurable:!1,enumerable:!1})}catch{n[Ae]=e}}return n[Ae]}var ae=he().plugins;function He(n){let e=he().plugins;e.some(t=>t.name===n.name)||e.push(n),n.onRegister?.()}function We(){return he().plugins}var gt={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function De(n,e,t,r){if(!t||t.bufferView===void 0)return null;let i=n.bufferViews?.[t.bufferView];if(!i)return null;let s=Number(t.count??0);if(!Number.isInteger(s)||s<=0)return null;let a=t.componentType??5126,c=gt[a];if(!c)throw new RangeError(`glTF accessor has unsupported componentType ${a}`);let o=c*r,l=i.byteStride&&i.byteStride>0?i.byteStride:o,u=(i.byteOffset||0)+(t.byteOffset||0);if(!Number.isInteger(u)||u<0||l<o||u+(s-1)*l+o>e.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${e.byteLength} bytes)`);if(a===5126&&l===o&&u%4===0)return new Float32Array(e,u,s*r);let d=new DataView(e),f=t.normalized===!0,T=new Float32Array(s*r);for(let p=0;p<s;p++){let h=u+p*l;for(let b=0;b<r;b++){let R=h+b*c,A;switch(a){case 5126:A=d.getFloat32(R,!0);break;case 5120:A=d.getInt8(R),f&&(A=Math.max(A/127,-1));break;case 5121:A=d.getUint8(R),f&&(A/=255);break;case 5122:A=d.getInt16(R,!0),f&&(A=Math.max(A/32767,-1));break;case 5123:A=d.getUint16(R,!0),f&&(A/=65535);break;default:A=d.getUint32(R,!0),f&&(A/=4294967295)}T[p*r+b]=A}}return T}function Xe(n,e){let t=Number(e.offset?.[0]??0)||0,r=Number(e.offset?.[1]??0)||0,i=Number(e.scale?.[0]??1),s=Number(e.scale?.[1]??1),a=Number(e.rotation??0)||0,c=Math.cos(a),o=Math.sin(a),l=(Number.isFinite(i)?i:1)*c,u=(Number.isFinite(i)?i:1)*o,d=-(Number.isFinite(s)?s:1)*o,f=(Number.isFinite(s)?s:1)*c;for(let T=0;T+1<n.length;T+=2){let p=n[T],h=n[T+1];n[T]=l*p+u*h+t,n[T+1]=d*p+f*h+r}}var Ke=["neutral","reinhard","none","aces","agx"];function Ie(n){let e=String(n??"").trim().toLowerCase();return Ke.includes(e)?e:"neutral"}function xt(n){return Ke.indexOf(Ie(n))}function vt(n){return new TextDecoder().decode(n)}var Ze=he().decoders;function Mt(n,e){Ze.set(n.toLowerCase(),e)}function pe(n){return Ze.get(n.toLowerCase())}function je(n){let e=ArrayBuffer.isView(n)?n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength):n,t=new DataView(e);if(e.byteLength<12)throw new Error(`Invalid GLB buffer size: ${e.byteLength} bytes`);let r=t.getUint32(0,!0);if(r!==1179937895){let f=t.getUint8(0);throw f===123||f===32||f===10||f===13?new Error("[three-live] Multi-file JSON .gltf is not supported for performance reasons. Please pack your asset into a single binary .glb file."):new Error(`Invalid GLB magic: 0x${r.toString(16)}`)}let i=t.getUint32(4,!0);if(i!==2)throw new Error(`Unsupported GLB version: ${i}`);let s=t.getUint32(8,!0),a=12,c=null,o=null;for(;a+8<=s&&a+8<=e.byteLength;){let f=t.getUint32(a,!0),T=t.getUint32(a+4,!0),p=a+8;if(p+f>e.byteLength)throw new Error(`Truncated GLB chunk: required ${p+f} bytes, buffer has ${e.byteLength}`);if(T===1313821514){let h=new Uint8Array(e,p,f),b=vt(h);c=JSON.parse(b,(R,A)=>R==="__proto__"||R==="constructor"||R==="prototype"?void 0:A)}else T===5130562&&(o=e.slice(p,p+f));a=p+f}if(!c)throw new Error("Missing JSON chunk in GLB");let l=c.extensionsRequired||[];if(l.includes("KHR_draco_mesh_compression")&&!pe("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");for(let f of["EXT_meshopt_compression","KHR_meshopt_compression"])if(l.includes(f)&&!pe("meshopt"))throw new Error(`Model requires ${f}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(l.includes("KHR_texture_basisu")&&!pe("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let u=o||new ArrayBuffer(0),d={gltf:c,bin:u,animations:[]};for(let f of ae)f.onParseGLB?.(d);return d}function Tt(n){return typeof n=="object"&&n!==null&&"gltf"in n&&typeof n.gltf=="object"&&n.gltf!==null&&"bin"in n&&(n.bin instanceof ArrayBuffer||ArrayBuffer.isView(n.bin))}function xe(n){if(Tt(n))return n;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return je(n);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var Qe=`#version 300 es
|
|
18
18
|
layout(location=0) in vec3 aPosition;
|
|
19
19
|
layout(location=1) in vec3 aNormal;
|
|
20
20
|
layout(location=2) in vec2 aUV;
|
|
21
21
|
uniform mat4 uMVP,uModel;
|
|
22
22
|
uniform mat3 uNormalMatrix;
|
|
23
23
|
uniform vec4 uUvTransform;
|
|
24
|
+
layout(location=8) in vec4 aInst0;
|
|
25
|
+
layout(location=9) in vec4 aInst1;
|
|
26
|
+
layout(location=10) in vec4 aInst2;
|
|
27
|
+
layout(location=11) in vec4 aInst3;
|
|
28
|
+
layout(location=12) in vec4 aInstColor;
|
|
29
|
+
uniform int uInstanced;
|
|
30
|
+
uniform mat4 uViewProj;
|
|
31
|
+
out vec4 vInstTint;
|
|
32
|
+
mat4 xrModel(){return uInstanced==1?uModel*mat4(aInst0,aInst1,aInst2,aInst3):uModel;}
|
|
33
|
+
mat4 xrMVP(){return uInstanced==1?uViewProj*xrModel():uMVP;}
|
|
34
|
+
mat3 xrNormalMatrix(){return uInstanced==1?transpose(inverse(mat3(xrModel()))):uNormalMatrix;}
|
|
35
|
+
#define uModel xrModel()
|
|
36
|
+
#define uMVP xrMVP()
|
|
37
|
+
#define uNormalMatrix xrNormalMatrix()
|
|
24
38
|
out vec3 vNormal,vWorldPos;
|
|
25
39
|
out vec2 vUV;
|
|
26
40
|
void main(){
|
|
41
|
+
vInstTint=uInstanced==1?aInstColor:vec4(1.0);
|
|
27
42
|
vec3 rawN=uNormalMatrix*aNormal;
|
|
28
43
|
vNormal=length(rawN)>1e-5?normalize(rawN):vec3(0.0);
|
|
29
44
|
vec4 world=uModel*vec4(aPosition,1.0);
|
|
@@ -32,12 +47,14 @@ vec2 scaleUV=uUvTransform.zw;
|
|
|
32
47
|
if(scaleUV.x==0.0&&scaleUV.y==0.0)scaleUV=vec2(1.0);
|
|
33
48
|
vUV=aUV*scaleUV+uUvTransform.xy;
|
|
34
49
|
gl_Position=uMVP*vec4(aPosition,1.0);
|
|
35
|
-
}`,
|
|
50
|
+
}`,At=`#version 300 es
|
|
36
51
|
precision highp float;
|
|
37
52
|
in vec3 vNormal,vWorldPos;
|
|
38
53
|
in vec2 vUV;
|
|
39
54
|
uniform vec4 uBaseColor;
|
|
40
|
-
|
|
55
|
+
in vec4 vInstTint;
|
|
56
|
+
#define uBaseColor (uBaseColor*vInstTint)
|
|
57
|
+
uniform float uMetallic,uRoughness,uEmissive,uEnvIntensity,uExposure;
|
|
41
58
|
uniform vec2 uClearcoat;
|
|
42
59
|
uniform vec3 uCameraPos,uAmbientColor;
|
|
43
60
|
uniform sampler2D uBaseColorTexture,uMetallicRoughnessTexture,uNormalTexture,uOcclusionTexture,uEnvironmentMap;
|
|
@@ -108,9 +125,33 @@ float g=1.0-1.0/(desaturation*(peak-newPeak)+1.0);
|
|
|
108
125
|
return mix(color,newPeak*vec3(1.0),g);
|
|
109
126
|
}
|
|
110
127
|
|
|
128
|
+
vec3 acesToneMapping(vec3 color){
|
|
129
|
+
color*=0.6;
|
|
130
|
+
return clamp((color*(2.51*color+0.03))/(color*(2.43*color+0.59)+0.14),0.0,1.0);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
vec3 agxToneMapping(vec3 color){
|
|
134
|
+
color=max(color,vec3(0.0));
|
|
135
|
+
vec3 inset=vec3(
|
|
136
|
+
0.84247906*color.r+0.0784336*color.g+0.07922375*color.b,
|
|
137
|
+
0.04232824*color.r+0.87846864*color.g+0.07916613*color.b,
|
|
138
|
+
0.04237565*color.r+0.0784336*color.g+0.87914297*color.b);
|
|
139
|
+
vec3 ev=clamp((log2(max(inset,vec3(1e-6)))+12.47393)/16.5,0.0,1.0);
|
|
140
|
+
vec3 x2=ev*ev;
|
|
141
|
+
vec3 x4=x2*x2;
|
|
142
|
+
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;
|
|
143
|
+
vec3 outset=vec3(
|
|
144
|
+
1.196879*s.r-0.09802088*s.g-0.09902974*s.b,
|
|
145
|
+
-0.05289685*s.r+1.15190313*s.g-0.09896118*s.b,
|
|
146
|
+
-0.05297164*s.r-0.09804345*s.g+1.15107367*s.b);
|
|
147
|
+
return clamp(pow(max(outset,vec3(0.0)),vec3(2.2)),0.0,1.0);
|
|
148
|
+
}
|
|
149
|
+
|
|
111
150
|
vec3 applyToneMapping(vec3 color,int mode){
|
|
112
151
|
if(mode==0)return neutralToneMapping(color);
|
|
113
152
|
if(mode==1)return color/(color+vec3(1.0));
|
|
153
|
+
if(mode==3)return acesToneMapping(color);
|
|
154
|
+
if(mode==4)return agxToneMapping(color);
|
|
114
155
|
return color;
|
|
115
156
|
}
|
|
116
157
|
|
|
@@ -194,28 +235,29 @@ if(uClearcoat.x>0.0){
|
|
|
194
235
|
vec3 ccF=F_SchlickRoughness(vec3(0.04),uClearcoat.y,NoV)*uClearcoat.x;
|
|
195
236
|
color=color*(vec3(1.0)-ccF)+getStudioRadiance(R,uClearcoat.y)*ccF*uEnvIntensity;
|
|
196
237
|
}
|
|
238
|
+
color*=uExposure;
|
|
197
239
|
color=applyToneMapping(color,uToneMapping);
|
|
198
240
|
float outAlpha=base.a;
|
|
199
241
|
/*XRD_O*/
|
|
200
242
|
fragColor=vec4(color,outAlpha);
|
|
201
|
-
}
|
|
243
|
+
}`;var wt=`#version 300 es
|
|
202
244
|
layout(location=0) in vec3 aPosition;
|
|
203
245
|
uniform mat4 uMVP;
|
|
204
|
-
void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,
|
|
246
|
+
void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,Rt=`#version 300 es
|
|
205
247
|
precision highp float;
|
|
206
248
|
uniform vec4 uColorId;
|
|
207
249
|
out vec4 fragColor;
|
|
208
|
-
void main(){fragColor=uColorId;}`;function ze(n,e,t){let i=n.createShader(e);if(n.shaderSource(i,t),n.compileShader(i),!n.getShaderParameter(i,35713)){let r=n.getShaderInfoLog(i);throw n.deleteShader(i),new Error(`Shader compile error: ${r}`)}return i}function Fe(n,e,t){let i=ze(n,35633,e),r=ze(n,35632,t),s=n.createProgram();if(n.attachShader(s,i),n.attachShader(s,r),n.linkProgram(s),!n.getProgramParameter(s,35714)){let c=n.getProgramInfoLog(s);throw n.deleteProgram(s),new Error(`Program link error: ${c}`)}return s}function Ce(n,e,t){let i={};for(let r of t)i[r]=n.getUniformLocation(e,r);return i}var Xe=["uMVP","uModel","uNormalMatrix","uUvTransform","uBaseColor","uMetallic","uRoughness","uClearcoat","uEmissive","uCameraPos","uBaseColorTexture","uHasTexture","uMetallicRoughnessTexture","uHasMetallicRoughnessTexture","uNormalTexture","uHasNormalTexture","uNormalScale","uOcclusionTexture","uHasOcclusionTexture","uOcclusionStrength","uToneMapping","uEnvironmentMap","uHasEnvironmentMap","uAmbientColor","uNumDirLights","uDirLightDir","uDirLightColor","uNumPointLights","uPointLightPos","uPointLightColor","uEnvIntensity","uViewportSize","uSectionPlane","uSectionEnabled"];function Ke(){let n=pe().xrDepthShader;return{fs:dt.replace("/*XRD_U*/",n?.uniformsGLSL||"").replace("/*XRD_O*/",n?.occlusionGLSL||""),uniforms:n?[...Xe,...n.uniformNames]:Xe}}function yt(n){if(typeof n!="string")return null;let e=n.trim();if(!e||/[\x00-\x1f\x7f]/.test(e))return null;let t=e.toLowerCase();return t.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(e)?e:null:t.startsWith("https://")||t.startsWith("blob:")?e:t.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(e)||/(^|[\\/])\.\.([\\/]|$)/.test(e)?null:e}function Le(n,e,t,i,r,s,c){if(i===void 0||!e.accessors?.[i])return null;let l=e.accessors[i],u=e.bufferViews[l.bufferView],a=(u.byteOffset||0)+(l.byteOffset||0),o=u.byteStride&&u.byteStride>s*4?u.byteStride>>2:s,f;if(o===s)f=new Float32Array(t,a,l.count*s);else{f=new Float32Array(l.count*s);let p=new Float32Array(t,u.byteOffset||0,Math.floor(u.byteLength/4)),m=(l.byteOffset||0)>>2;for(let x=0;x<l.count;x++){let b=m+x*o;for(let E=0;E<s;E++)f[x*s+E]=p[b+E]}}let d=n.createBuffer();return c.push(d),n.bindBuffer(34962,d),n.bufferData(34962,f,35044),n.enableVertexAttribArray(r),n.vertexAttribPointer(r,s,5126,!1,0,0),f}var Ft=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),Ze=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function We(n,e,t=Ze,i){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:r,bin:s}=e,c=[],l=we(r),u=[];if(Array.isArray(r.nodes))for(let v=0;v<r.nodes.length;v++){let y=r.nodes[v];y.mesh!==void 0&&r.meshes&&r.meshes[y.mesh]&&u.push({node:y,nodeIdx:v,meshIdx:y.mesh})}let a=u.length>0?u:(r.meshes||[]).map((v,y)=>({node:v,nodeIdx:-1,meshIdx:y})),o=[];if(Array.isArray(e.lights)&&e.lights.length>0)o.push(...e.lights);else if(r.extensions?.KHR_lights_punctual?.lights){let v=r.extensions.KHR_lights_punctual.lights;for(let y of v){let T=y.type==="directional"?"directional":y.type==="point"?"point":"ambient";o.push({type:T,color:y.color||[1,1,1],intensity:y.intensity!==void 0?y.intensity:1})}}if(o.length===0&&(o.push({type:"ambient",color:[1,1,1],intensity:.35}),o.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),a.length>t.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${t.maxMeshes}). Found: ${a.length}`);let f=[];if(r.textures&&r.images){if(r.textures.length>t.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${t.maxTextures}). Found: ${r.textures.length}`);for(let v=0;v<r.textures.length;v++){let y=r.textures[v],T=r.images[y.source];if(T){let F=n.createTexture();if(n.bindTexture(3553,F),n.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),n.texParameteri(3553,10242,10497),n.texParameteri(3553,10243,10497),n.texParameteri(3553,10241,9729),n.texParameteri(3553,10240,9729),T.bufferView!==void 0){let C=r.bufferViews[T.bufferView],w=s.slice(C.byteOffset||0,(C.byteOffset||0)+C.byteLength),D=new Blob([w],{type:T.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(D).then(B=>{n.bindTexture(3553,F),n.texImage2D(3553,0,6408,6408,5121,B),n.generateMipmap(3553),i?.()}).catch(()=>{})}else if(T.uri){let C=yt(T.uri);if(C){let w=new Image;w.crossOrigin="anonymous",w.referrerPolicy="no-referrer",w.onload=()=>{n.bindTexture(3553,F),n.texImage2D(3553,0,6408,6408,5121,w),n.generateMipmap(3553),i?.()},w.src=C}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",T.uri)}f.push(F)}else f.push(null)}}let d=[1/0,1/0,1/0],p=[-1/0,-1/0,-1/0],m=0,x=0;for(let v=0;v<a.length;v++){let y=a[v],T=r.meshes[y.meshIdx],F=y.nodeIdx>=0?l[y.nodeIdx]:Z(),C=new Float32Array(9);he(C,F);let w={name:y.node.name||T.name||`Mesh_${y.meshIdx}`,nodeIndex:y.nodeIdx,transform:F,normalMatrix:C,primitives:[],extras:y.node.extras||T.extras};for(let D of T.primitives||[]){if(D.extensions?.KHR_draco_mesh_compression){let O=ye("draco");O&&O.decodePrimitive(r,D,s)}let B=[],L=n.createVertexArray();n.bindVertexArray(L);let q=r.accessors[D.attributes.POSITION],z=Number(q?.count??0);if(!Number.isFinite(z)||z<0||m+z>t.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${t.maxVertices}).`);if(m+=z,q?.min&&q?.max)for(let O=0;O<3;O++){let ne=F[12+O],me=F[12+O];for(let de=0;de<3;de++){let xe=F[de*4+O]*q.min[de],Me=F[de*4+O]*q.max[de];ne+=xe<Me?xe:Me,me+=xe>Me?xe:Me}ne<d[O]&&(d[O]=ne),me>p[O]&&(p[O]=me)}let j=Le(n,r,s,D.attributes.POSITION,0,3,B);Le(n,r,s,D.attributes.NORMAL,1,3,B),Le(n,r,s,D.attributes.TEXCOORD_0,2,2,B);let H=0,$=5123,G=null;if(D.indices!==void 0){let O=r.accessors[D.indices],me=(r.bufferViews[O.bufferView].byteOffset||0)+(O.byteOffset||0);if(H=Number(O.count??0),!Number.isFinite(H)||H<0||x+H>t.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${t.maxIndices}).`);x+=H,$=O.componentType===5125?5125||5125:5123||5123;let de=n.createBuffer();B.push(de),n.bindBuffer(34963,de),O.componentType===5125?(G=new Uint32Array(s,me,O.count),n.bufferData(34963,G,35044)):(G=new Uint16Array(s,me,O.count),n.bufferData(34963,G,35044))}else H=q.count;let N={};for(let O of K)if(O.onBuildPrimitiveVAO){let ne=O.onBuildPrimitiveVAO(n,L,D,r,s);ne&&(N[O.name]=ne)}n.bindVertexArray(null);let W=r.materials&&D.material!==void 0?r.materials[D.material]:null,I=Ke(),S=Ye,U=I.fs,_=!1;for(let O of K)if(O.onResolveShader){let ne=O.onResolveShader(D,W,S,U);ne&&(S=ne.vs,U=ne.fs,_=!0)}let ee=_?Fe(n,S,U):null,re=ee?Ce(n,ee,I.uniforms):null,X=W?.pbrMetallicRoughness,ce=X?.baseColorFactor||[.8,.8,.8,1],ie=X?.metallicFactor??.1,te=X?.roughnessFactor??.5,k=W?.extensions?.KHR_materials_clearcoat,Q=k?k.clearcoatFactor??1:0,Y=Math.max(.04,k?.clearcoatRoughnessFactor??.04),ue=X?.baseColorTexture!==void 0&&f[X.baseColorTexture.index]?f[X.baseColorTexture.index]:null,ve=X?.metallicRoughnessTexture!==void 0&&f[X.metallicRoughnessTexture.index]?f[X.metallicRoughnessTexture.index]:null,se=W?.normalTexture!==void 0&&f[W.normalTexture.index]?f[W.normalTexture.index]:null,J=W?.normalTexture?.scale??1,fe=W?.occlusionTexture!==void 0&&f[W.occlusionTexture.index]?f[W.occlusionTexture.index]:null,ae=W?.occlusionTexture?.strength??1,le=!!(W?.extensions?.KHR_materials_transmission||N.materials?.isTransmissive);w.primitives.push({vao:L,indexCount:H,indexType:$,baseColor:ce,metallic:ie,roughness:te,clearcoat:Q,clearcoatRoughness:Y,positions:j,indices:G,texture:ue,metallicRoughnessTexture:ve,normalTexture:se,occlusionTexture:fe,normalScale:J,occlusionStrength:ae,buffers:B,materialIndex:D.material,pluginData:N,customProgram:ee,customUniforms:re,isTransmissive:le})}c.push(w)}isFinite(d[0])||(d=[-1,-1,-1]),isFinite(p[0])||(p=[1,1,1]);let b=[(d[0]+p[0])/2,(d[1]+p[1])/2,(d[2]+p[2])/2],E=p[0]-d[0],P=p[1]-d[1],A=p[2]-d[2],R=Math.max(Math.hypot(E,P,A)/2,.5),g=[d[0],d[1],d[2]],M=[p[0],p[1],p[2]],h=e.animations;if(!h){for(let v of K)if(v.onParseGLB?.(e),e.animations){h=e.animations;break}}return h||(h=[]),{meshes:c,bounds:{center:b,radius:R,min:g,max:M},lights:o,animations:h,worldMatrices:l}}var Ee=class{constructor(e,t,i){this.meshes=[];this.backdropMeshes=[];this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]};this.lights=[];this.modelRootMatrix=Z();this.clearColor=[0,0,0,0];this.envIntensity=1;this.shadowIntensity=0;this.shadowSoftness=.5;this.toneMapping="neutral";this.environmentTexture=null;this.animations=[];this.currentClip=null;this.animationTime=0;this.isPlayingAnimation=!1;this.autoplay=!1;this.animationName="";this.gltf=null;this.worldMatrices=[];this.initialNodeTransforms=[];this.projMatrix=Z();this.viewMatrix=Z();this.modelMatrix=Z();this.mvpMatrix=Z();this.normalMatrix=new Float32Array(9);this.initialTheta=.6;this.initialPhi=.35;this.initialDistance=null;this.customDistance=!1;this.distanceMode="auto";this.initialCustomTarget=null;this.customTarget=null;this.fov=Math.PI/4;this.minTheta=-1/0;this.maxTheta=1/0;this.minPhi=-Math.PI*.48;this.maxPhi=Math.PI*.48;this.minDistanceLimit=null;this.maxDistanceLimit=null;this.activePointers=new Map;this.isPanning=!1;this.targetTheta=.6;this.currTheta=.6;this.targetPhi=.35;this.currPhi=.35;this.targetDistance=3;this.currDistance=3;this.autoRotate=!1;this.autoRotateSpeed=Math.PI/6;this.autoRotateDelay=3e3;this.lastInteractionTime=-1/0;this.turntableRotation=0;this.isPointerDown=!1;this.interactive=!0;this.skyboxTexture=null;this.lastPointerX=0;this.lastPointerY=0;this.totalDragDist=0;this.selectedMeshName="";this.pickFbo=null;this.pickTexture=null;this.pickDepth=null;this.pickFboWidth=0;this.pickFboHeight=0;this.animFrameId=null;this.isVisible=!0;this.xrSessionActive=!1;this.lastTime=0;this.lastReportedTheta=-999;this.lastReportedPhi=-999;this.lastReportedZoom=-999;this.boundPointerDown=null;this.boundPointerMove=null;this.boundPointerUp=null;this.boundWheel=null;this.boundKeyDown=null;this.boundContextMenu=null;this.boundSetCamera=null;this.boundResetCamera=null;this.stereoSBS=!1;this.renderErrorReported=!1;this.xrDepthState={enabled:!1,texture:null,uvTransform:Z(),rawValueToMeters:.001,format:0};this.container=e;let r,s;if(t&&typeof t.getContext=="function"?(r=t,s=i):(s=t,r=s?.canvas),!r){let a=e.querySelector("canvas");a||(a=document.createElement("canvas"),a.style.width="100%",a.style.height="100%",a.style.display="block",a.style.touchAction="none",e.prepend(a)),r=a}this.canvas=r,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let c=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!c:c&&(this.autoRotate=!1),this.opts.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=this.opts.autoRotateSpeed),this.opts.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(this.opts.autoRotateDelay)||0)),this.opts.exposure!==void 0&&(this.envIntensity=Math.max(0,Number(this.opts.exposure))),this.opts.camera&&this.setInitialCamera(this.opts.camera.theta,this.opts.camera.phi,this.opts.camera.distance,this.opts.camera.zoom),this.opts.shadowIntensity!==void 0&&(this.shadowIntensity=Math.max(0,Math.min(1,Number(this.opts.shadowIntensity)||0))),this.opts.shadowSoftness!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(this.opts.shadowSoftness)||0))),this.opts.toneMapping!==void 0&&(this.toneMapping=this.opts.toneMapping),this.opts.autoplay!==void 0&&(this.autoplay=this.opts.autoplay),this.opts.animationName!==void 0&&(this.animationName=this.opts.animationName),this.opts.fieldOfView!==void 0&&(this.fov=this.opts.fieldOfView*Math.PI/180),this.opts.distanceMode!==void 0&&(this.distanceMode=this.opts.distanceMode),this.opts.cameraTarget!==void 0&&(this.setTarget(this.opts.cameraTarget[0],this.opts.cameraTarget[1],this.opts.cameraTarget[2]),this.initialCustomTarget=[...this.opts.cameraTarget]),(this.opts.minCameraOrbit||this.opts.maxCameraOrbit)&&this.setOrbitLimits({minTheta:this.opts.minCameraOrbit?.theta,maxTheta:this.opts.maxCameraOrbit?.theta,minPhi:this.opts.minCameraOrbit?.phi,maxPhi:this.opts.maxCameraOrbit?.phi,minDistance:this.opts.minCameraOrbit?.distance,maxDistance:this.opts.maxCameraOrbit?.distance});let l=r.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!l)throw new Error("WebGL2 not supported");this.gl=l;let u=Ke();this.renderProg=Fe(l,Ye,u.fs),this.pickProg=Fe(l,pt,bt),this.uRender=Ce(l,this.renderProg,u.uniforms),this.uPick=Ce(l,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo(),this.setupEvents(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(e,t){ht(e,t)}static getDecoder(e){return ye(e)}setupPickingFbo(){let e=this.gl;if(typeof e.createFramebuffer!="function")return;this.pickFbo=e.createFramebuffer(),this.pickTexture=e.createTexture(),this.pickDepth=e.createRenderbuffer();let t=Math.max(1,this.canvas.width),i=Math.max(1,this.canvas.height);this.pickFboWidth=t,this.pickFboHeight=i,e.bindTexture(3553,this.pickTexture),e.texImage2D(3553,0,6408,t,i,0,6408,5121,null),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728),e.bindRenderbuffer(36161,this.pickDepth),e.renderbufferStorage(36161,33189,t,i),e.bindFramebuffer(36160,this.pickFbo),e.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),e.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),e.bindFramebuffer(36160,null)}resizePickingFbo(e,t){if(!this.pickFbo)return;let i=this.gl,r=Math.max(1,e),s=Math.max(1,t);this.pickFboWidth=r,this.pickFboHeight=s,i.bindTexture(3553,this.pickTexture),i.texImage2D(3553,0,6408,r,s,0,6408,5121,null),i.bindRenderbuffer(36161,this.pickDepth),i.renderbufferStorage(36161,33189,r,s)}loadGLBData(e,t){let{meshes:i,bounds:r,lights:s,animations:c,worldMatrices:l}=We(this.gl,e,t,()=>this.render());if(this.disposeMeshGpuResources(),this.meshes=i,this.bounds=r,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=s,this.animations=c||[],this.worldMatrices=l||[],this.gltf=e.gltf,this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let a of e.gltf.nodes)this.initialNodeTransforms.push({t:a.translation?[a.translation[0],a.translation[1],a.translation[2]]:[0,0,0],r:a.rotation?[a.rotation[0],a.rotation[1],a.rotation[2],a.rotation[3]]:[0,0,0,1],s:a.scale?[a.scale[0],a.scale[1],a.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let a of K)a.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:r.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let u=e.exposure??e.environmentIntensity??e.gltf?.extras?.exposure??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.exposure??e.gltf?.asset?.extras?.environmentIntensity;u!==void 0&&(this.envIntensity=Math.max(0,Number(u))),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(e){this.loadGLBData(qe(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(ge(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let i=ge(e),{meshes:r}=We(this.gl,i,Ze,()=>this.render());if(t)for(let s of r)s.transform[12]+=t[0],s.transform[13]+=t[1],s.transform[14]+=t[2],he(s.normalMatrix,s.transform);this.backdropMeshes=r,this.update(0),this.render()}setClearColor(e,t,i,r=1){this.clearColor=[e,t,i,r]}updateMeshTransforms(e){for(let t=0;t<this.meshes.length;t++){let i=this.meshes[t],r;e instanceof Map?r=e.get(i.name)??e.get(t):Array.isArray(e)?r=e[t]:e&&typeof e=="object"&&(Object.prototype.hasOwnProperty.call(e,i.name)?r=e[i.name]:Object.prototype.hasOwnProperty.call(e,t)&&(r=e[t])),r&&r.length===16&&(i.transform.set(r),he(i.normalMatrix,i.transform))}}bindLights(e=this.uRender){let t=this.gl,i=[.28,.28,.28],r=[],s=[],c=[],l=[];for(let u of this.lights){let a=u.color||[1,1,1],o=u.intensity!==void 0?u.intensity:1;if(u.type==="ambient")i=[a[0]*o,a[1]*o,a[2]*o];else if(u.type==="directional"&&r.length<6){let f=u.direction||[.5,1,.8];r.push(f[0],f[1],f[2]),s.push(a[0]*o,a[1]*o,a[2]*o)}else if(u.type==="point"&&c.length<6){let f=u.position||[0,0,0];c.push(f[0],f[1],f[2]),l.push(a[0]*o,a[1]*o,a[2]*o)}}r.length===0&&(r.push(.5,1,.8),s.push(1,1,1)),t.uniform3fv(e.uAmbientColor,i),t.uniform1i(e.uNumDirLights,r.length/3),r.length>0&&(t.uniform3fv(e.uDirLightDir,r),t.uniform3fv(e.uDirLightColor,s)),t.uniform1i(e.uNumPointLights,c.length/3),c.length>0&&(t.uniform3fv(e.uPointLightPos,c),t.uniform3fv(e.uPointLightColor,l)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.envIntensity=Math.max(0,Number(e))}getExposure(){return this.envIntensity}setShadow(e,t){this.shadowIntensity=Math.max(0,Math.min(1,Number(e)||0)),t!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(t)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(e){this.toneMapping=e}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of K)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of K)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(o=>o.primitives.filter(f=>f.materialIndex===i||e.length===1&&f.materialIndex===void 0)),s=r[0],c=s?[...s.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],l=s?s.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,u=s?s.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,a={baseColorFactor:c,metallicFactor:l,roughnessFactor:u,setBaseColorFactor:o=>{let f=[o[0],o[1],o[2],o[3]??1];a.baseColorFactor=f,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=f);for(let d of r)d.baseColor=f;this.render()},setMetallicFactor:o=>{a.metallicFactor=o,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=o);for(let f of r)f.metallic=o;this.render()},setRoughnessFactor:o=>{a.roughnessFactor=o,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=o);for(let f of r)f.roughness=o;this.render()}};return{name:t.name||`Material_${i}`,pbrMetallicRoughness:a}})}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)}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 K)if(t.evaluateAnimation){t.evaluateAnimation(this,e);return}}setTarget(e,t,i){this.customTarget=[e,t,i],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(e){let t=Math.max(10,Math.min(90,e));this.fov=t*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(e){if(this.distanceMode=e,!this.customDistance){let t=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=t,this.targetDistance=t,this.currDistance=t,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(e){e.minTheta!==void 0&&(this.minTheta=e.minTheta*Math.PI/180),e.maxTheta!==void 0&&(this.maxTheta=e.maxTheta*Math.PI/180),e.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,e.minPhi*Math.PI/180)),e.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,e.maxPhi*Math.PI/180)),e.minDistance!==void 0&&(this.minDistanceLimit=e.minDistance),e.maxDistance!==void 0&&(this.maxDistanceLimit=e.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){return{minTheta:isFinite(this.minTheta)?this.minTheta*180/Math.PI:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*180/Math.PI:void 0,minPhi:this.minPhi*180/Math.PI,maxPhi:this.maxPhi*180/Math.PI,minDistance:this.minDistanceLimit!==null?this.minDistanceLimit:void 0,maxDistance:this.maxDistanceLimit!==null?this.maxDistanceLimit:void 0}}clampTheta(e){return Math.max(this.minTheta,Math.min(this.maxTheta,e))}clampPhi(e){return Math.max(this.minPhi,Math.min(this.maxPhi,e))}clampDistance(e){let t=this.minDistanceLimit!==null?this.minDistanceLimit:this.bounds?this.bounds.radius*.5:.1,i=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(t,Math.min(i,e))}setCamera(e,t,i,r){e!==void 0&&(this.targetTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.targetPhi=this.clampPhi(t*Math.PI/180)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(i)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/r))}setInitialCamera(e,t,i,r){if(e!==void 0&&(this.initialTheta=this.clampTheta(e*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),t!==void 0&&(this.initialPhi=this.clampPhi(t*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),i!==void 0&&i>0){let s=this.clampDistance(i);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else if(r!==void 0&&r>0){let s=this.clampDistance(this.bounds.radius*2.5/r);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else{this.customDistance=!1;let s=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=s,this.targetDistance=s,this.currDistance=s}this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.initialDistance!==null?this.targetDistance=this.clampDistance(this.initialDistance):this.targetDistance=this.clampDistance(this.bounds.radius*2.5),this.initialCustomTarget?this.customTarget=[...this.initialCustomTarget]:this.customTarget=null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(e,t){let i=Z();oe(i,this.projMatrix,this.viewMatrix);let[r,s,c]=e,l=t?t[0]:0,u=t?t[1]:0,a=t?t[2]:0,o=this.modelRootMatrix;o&&(r=o[0]*e[0]+o[4]*e[1]+o[8]*e[2]+o[12],s=o[1]*e[0]+o[5]*e[1]+o[9]*e[2]+o[13],c=o[2]*e[0]+o[6]*e[1]+o[10]*e[2]+o[14],t&&(l=o[0]*t[0]+o[4]*t[1]+o[8]*t[2],u=o[1]*t[0]+o[5]*t[1]+o[9]*t[2],a=o[2]*t[0]+o[6]*t[1]+o[10]*t[2]));let f=i[0]*r+i[4]*s+i[8]*c+i[12],d=i[1]*r+i[5]*s+i[9]*c+i[13],p=i[2]*r+i[6]*s+i[10]*c+i[14],m=i[3]*r+i[7]*s+i[11]*c+i[15];if(m<=1e-4)return{x:0,y:0,z:1,visible:!1};let x=f/m,b=d/m,E=p/m,P=this.canvas.getBoundingClientRect(),A=P.width||this.canvas.clientWidth||this.canvas.width||300,R=P.height||this.canvas.clientHeight||this.canvas.height||150,g=(x*.5+.5)*A,M=(-b*.5+.5)*R,h=x>=-1.1&&x<=1.1&&b>=-1.1&&b<=1.1&&E>=-1&&E<=1;if(h&&t){let v=this.customTarget||this.bounds.center,y=v[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),T=v[1]+this.currDistance*Math.sin(this.currPhi),F=v[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),C=[r-y,s-T,c-F];l*C[0]+u*C[1]+a*C[2]>.05&&(h=!1)}return{x:g,y:M,z:E,visible:h}}setSelectedMesh(e){this.selectedMeshName=e||""}setupEvents(){let e=this.canvas;this.boundContextMenu=t=>{t.preventDefault()},e.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=t=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.lastPointerX=t.clientX,this.lastPointerY=t.clientY,this.totalDragDist=0,this.activePointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.isPanning=t.button===2||t.shiftKey||this.activePointers.size===2,e.setPointerCapture(t.pointerId))},e.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=t=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let i=this.activePointers.get(t.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},r=t.clientX-i.x,s=t.clientY-i.y;if(this.activePointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.lastPointerX=t.clientX,this.lastPointerY=t.clientY,this.totalDragDist+=Math.hypot(r,s),this.isPanning||t.button===2||t.shiftKey||this.activePointers.size===2){let c=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],l=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],u=this.customTarget?[...this.customTarget]:[...this.bounds.center],a=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;u[0]+=(-r*c[0]+s*l[0])*a,u[1]+=(-r*c[1]+s*l[1])*a,u[2]+=(-r*c[2]+s*l[2])*a,this.customTarget=u}else this.targetTheta=this.clampTheta(this.targetTheta-r*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=t=>{this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.activePointers.delete(t.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(t.pointerId)}catch{}if(this.totalDragDist<5&&t.button===0){let i=e.getBoundingClientRect(),r=Math.floor((t.clientX-i.left)*(e.width/Math.max(i.width,1))),s=Math.floor((t.clientY-i.top)*(e.height/Math.max(i.height,1)));this.performMeshPick(r,s,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=t=>{if(!this.interactive)return;t.preventDefault(),this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let i=Math.exp(t.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*i)},e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=t=>{let i=t.detail||{};i.reset?this.resetCamera():this.setCamera(i.theta,i.phi,i.distance,i.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),e.tabIndex!==void 0&&e.tabIndex<0&&(e.tabIndex=0),e.getAttribute?.("role")||e.setAttribute?.("role","region"),e.getAttribute?.("aria-label")||e.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=t=>{if(!this.interactive)return;let i=typeof performance<"u"?performance.now():Date.now();switch(t.key){case"ArrowLeft":this.lastInteractionTime=i,this.targetTheta=this.clampTheta(this.targetTheta-.1),t.preventDefault();break;case"ArrowRight":this.lastInteractionTime=i,this.targetTheta=this.clampTheta(this.targetTheta+.1),t.preventDefault();break;case"ArrowUp":this.lastInteractionTime=i,this.targetPhi=this.clampPhi(this.targetPhi+.08),t.preventDefault();break;case"ArrowDown":this.lastInteractionTime=i,this.targetPhi=this.clampPhi(this.targetPhi-.08),t.preventDefault();break;case"+":case"=":{this.lastInteractionTime=i,this.targetDistance=this.clampDistance(this.targetDistance*.9),t.preventDefault();break}case"-":case"_":{this.lastInteractionTime=i,this.targetDistance=this.clampDistance(this.targetDistance*1.1),t.preventDefault();break}case"Home":this.lastInteractionTime=i,this.resetCamera(),t.preventDefault();break}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=this.canvas;this.boundContextMenu&&(e.removeEventListener("contextmenu",this.boundContextMenu),this.boundContextMenu=null),this.boundPointerDown&&(e.removeEventListener("pointerdown",this.boundPointerDown),this.boundPointerDown=null),this.boundPointerMove&&(e.removeEventListener("pointermove",this.boundPointerMove),this.boundPointerMove=null),this.boundPointerUp&&(e.removeEventListener("pointerup",this.boundPointerUp),this.boundPointerUp=null),this.boundWheel&&(e.removeEventListener("wheel",this.boundWheel),this.boundWheel=null),this.boundKeyDown&&(e.removeEventListener("keydown",this.boundKeyDown),this.boundKeyDown=null),this.boundSetCamera&&(this.container.removeEventListener("setCamera",this.boundSetCamera),this.boundSetCamera=null),this.boundResetCamera&&(this.container.removeEventListener("resetCamera",this.boundResetCamera),this.boundResetCamera=null)}raycastFromScreenPoint(e,t){let i=this.canvas,r=i.getBoundingClientRect(),s=i.width||300,c=i.height||300,l=r.width>0?Math.floor((e-r.left)*(s/r.width)):Math.floor(e),u=r.height>0?Math.floor((t-r.top)*(c/r.height)):Math.floor(t);return this.performMeshPick(l,u,!1)}performMeshPick(e,t,i=!0){if(this.meshes.length===0)return null;let r=this.gl,s=Math.max(1,this.canvas.width||300),c=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,s);let l=Z();oe(l,this.projMatrix,this.viewMatrix);let u=[],a=Math.max(0,Math.min(s-1,e)),o=Math.max(0,Math.min(c-1,c-1-t));if(this.pickFbo&&r&&!this.xrSessionActive){(this.pickFboWidth!==s||this.pickFboHeight!==c)&&this.resizePickingFbo(s,c),r.bindFramebuffer(36160,this.pickFbo),r.viewport(0,0,s,c),r.enable(2929),r.clearColor(0,0,0,0),r.clear(16384|256),r.useProgram(this.pickProg);for(let h=0;h<this.meshes.length;h++){let v=this.meshes[h];if(v.visible===!1||v.isPluginMesh)continue;let y=h+1,T=(y&255)/255,F=(y>>8&255)/255,C=(y>>16&255)/255;r.uniform4f(this.uPick.uColorId,T,F,C,1),oe(this.modelMatrix,this.modelRootMatrix,v.transform),oe(this.mvpMatrix,l,this.modelMatrix),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let w of v.primitives)r.bindVertexArray(w.vao),r.drawElements(4,w.indexCount,w.indexType,0)}let g=new Uint8Array(4);r.readPixels(a,o,1,1,6408,5121,g),r.bindFramebuffer(36160,null);let M=g[0]+(g[1]<<8)+(g[2]<<16);M>0&&M<=this.meshes.length&&(u=[this.meshes[M-1]])}u.length===0&&(u=this.meshes.filter(g=>g.visible!==!1));let f=null,d=1/0,p=[0,0,0],m=[0,1,0],x=this.customTarget||this.bounds.center,b=x[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),E=x[1]+this.currDistance*Math.sin(this.currPhi),P=x[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let g of u){oe(this.modelMatrix,this.modelRootMatrix,g.transform),oe(this.mvpMatrix,l,this.modelMatrix);let M=Z();if(!Oe(M,this.mvpMatrix))continue;let h=(a+.5)/s*2-1,v=(o+.5)/c*2-1,y=[0,0,0],T=[0,0,0];De(y,h,v,-1,M),De(T,h,v,1,M);let F=T[0]-y[0],C=T[1]-y[1],w=T[2]-y[2],D=Math.hypot(F,C,w)||1,B=F/D,L=C/D,q=w/D,z={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((H=>{for(let $ of g.primitives){if(!$.positions)continue;let G=$.positions,N=$.indices,W=Math.floor(N?N.length/3:G.length/9);for(let I=0;I<W;I++){let S=N?N[I*3]:I*3,U=N?N[I*3+1]:I*3+1,_=N?N[I*3+2]:I*3+2;Ve(y[0],y[1],y[2],B,L,q,G[S*3],G[S*3+1],G[S*3+2],G[U*3],G[U*3+1],G[U*3+2],G[_*3],G[_*3+1],G[_*3+2],z,H)}}})(1e-4),isFinite(z.distance)){let H=z.point[0],$=z.point[1],G=z.point[2],N=this.modelMatrix,W=N[0]*H+N[4]*$+N[8]*G+N[12],I=N[1]*H+N[5]*$+N[9]*G+N[13],S=N[2]*H+N[6]*$+N[10]*G+N[14],U=W-b,_=I-E,ee=S-P,re=Math.hypot(U,_,ee);if(re<d){he(this.normalMatrix,this.modelMatrix);let X=this.normalMatrix,ce=z.normal[0],ie=z.normal[1],te=z.normal[2],k=X[0]*ce+X[3]*ie+X[6]*te,Q=X[1]*ce+X[4]*ie+X[7]*te,Y=X[2]*ce+X[5]*ie+X[8]*te,ue=Math.hypot(k,Q,Y)||1;k/=ue,Q/=ue,Y/=ue,k*U+Q*_+Y*ee>0&&(k=-k,Q=-Q,Y=-Y),f=g,d=Math.round(re*1e3)/1e3,p=[Math.round(W*1e3)/1e3,Math.round(I*1e3)/1e3,Math.round(S*1e3)/1e3],m=[Math.round(k*1e3)/1e3,Math.round(Q*1e3)/1e3,Math.round(Y*1e3)/1e3]}}}if(!f)return null;let R={meshIndex:this.meshes.indexOf(f),meshName:f.name,nodeIndex:f.nodeIndex,distance:d,hitPoint:p,normal:m,screenX:e,screenY:t};if(i){for(let g of K)g.onMeshSelect?.(this,R);this.opts.onMeshClick&&this.opts.onMeshClick(R),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:R}))}return R}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let i=Math.max(1,Math.floor(t*.5)),r=e>=i,s=r?e-i:e,c=r?Math.max(1,t-i):i,l=(s+.5)/c*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);Te(this.projMatrix,this.fov,e,.1,t);let i=this.customTarget||this.bounds.center,r=i[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),s=i[1]+this.currDistance*Math.sin(this.currPhi),c=i[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);Re(this.viewMatrix,[r,s,c],i,[0,1,0]),oe(this.mvpMatrix,this.projMatrix,this.viewMatrix),he(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 K)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 K)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let e=t=>{if(this.animFrameId===null)return;let i=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(i),this.render()}catch(r){this.reportRenderError(r)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(e))};this.animFrameId=requestAnimationFrame(e)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(e){this.autoRotate=e}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(e){this.autoRotateSpeed=e}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(e){this.autoRotateDelay=Math.max(0,Number(e)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(e=0){this.turntableRotation=Number(e)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let e=Math.cos(this.turntableRotation),t=Math.sin(this.turntableRotation),i=this.bounds.center[0],r=this.bounds.center[2],s=this.modelRootMatrix;s[0]=e,s[1]=0,s[2]=-t,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=t,s[9]=0,s[10]=e,s[11]=0,s[12]=i-(e*i+t*r),s[13]=0,s[14]=r-(-t*i+e*r),s[15]=1}setVisible(e){this.isVisible=e}update(e){for(let c of K)c.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 c of K)c.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let i=Math.round((this.currTheta*180/Math.PI%360+360)%360),r=Math.round(this.currPhi*180/Math.PI),s=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(i-this.lastReportedTheta)>=1||Math.abs(r-this.lastReportedPhi)>=1||Math.abs(s-this.lastReportedZoom)>=.02){this.lastReportedTheta=i,this.lastReportedPhi=r,this.lastReportedZoom=s;let c={theta:i,phi:r,zoom:s,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(c),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:c}))}}renderXRView(e,t,i,r,s=!0,c=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let l=e?.transform?.inverse?.matrix||this.viewMatrix,u=e?.projectionMatrix||this.projMatrix,a=e?.transform?.position,o=a?[a.x,a.y,a.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):i&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:l,projMatrix:u,eyePos:o,viewport:r,eye:e?.eye||"none",clear:c>0?!1:e?.eye!=="right",isAR:s})}render(e){if(!e&&this.stereoSBS){let R=Math.max(2,this.canvas.width||2),g=Math.max(1,this.canvas.height||1),M=Math.max(1,Math.floor(R*.5)),h=Math.max(1,R-M),v=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),y=this.customTarget||this.bounds.center,T=y[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),F=y[1]+this.currDistance*Math.sin(this.currPhi),C=y[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),w=Math.cos(this.currTheta),D=-Math.sin(this.currTheta),B=.032,L=Z(),q=Z(),z=[T-w*B,F,C-D*B],j=[y[0]-w*B*.25,y[1],y[2]-D*B*.25];Te(L,this.fov,M/g,.1,v),Re(q,z,j,[0,1,0]);let H=Z(),$=Z(),G=[T+w*B,F,C+D*B],N=[y[0]+w*B*.25,y[1],y[2]+D*B*.25];Te(H,this.fov,h/g,.1,v),Re($,G,N,[0,1,0]),this.render({viewMatrix:q,projMatrix:L,eyePos:z,viewport:[0,0,M,g],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:$,projMatrix:H,eyePos:G,viewport:[M,0,h,g],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,R,g);return}let t=this.gl,i=0,r=0,s=this.canvas.width,c=this.canvas.height;e?.viewport?(i=e.viewport[0],r=e.viewport[1],s=e.viewport[2],c=e.viewport[3],t.viewport(i,r,s,c)):t.viewport(0,0,this.canvas.width,this.canvas.height),t.enable(2929),(!e||e.clear!==!1)&&(e?.isAR?t.clearColor(0,0,0,0):t.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),t.clear(16384|256));let l=Z(),u=e?.viewMatrix??this.viewMatrix;oe(l,e?.projMatrix??this.projMatrix,u);let a=pe().xrDepthShader,o=this.toneMapping==="reinhard"?1:this.toneMapping==="none"?2:0,f=this.customTarget||this.bounds.center,d=e?e.eyePos[0]:f[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),p=e?e.eyePos[1]:f[1]+this.currDistance*Math.sin(this.currPhi),m=e?e.eyePos[2]:f[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let R of K)R.onBeforeDrawScene?.(this,t,l,[d,p,m],o);let x=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&x===0)return;let b=e?.eye||"none",E=!1,P=x>0?[...this.backdropMeshes,...this.meshes]:this.meshes,A=R=>{for(let g=0;g<P.length;g++){let M=P[g];if(M.visible===!1)continue;let h=this.selectedMeshName!==""&&M.name===this.selectedMeshName;g<x||M.worldSpace===!0||M.name==="__xr_reticle__"?this.modelMatrix.set(M.transform):oe(this.modelMatrix,this.modelRootMatrix,M.transform),oe(this.mvpMatrix,l,this.modelMatrix),he(M.normalMatrix,this.modelMatrix);let v=M.extras?.xr?.stereo||M.userData?.xr?.stereo,y=0,T=0,F=1,C=1;v==="sbs"?(F=.5,y=b==="right"?.5:0):v==="ou"&&(C=.5,T=b==="right"?.5:0);for(let w of M.primitives){let D=!!w.isTransmissive;if(!R&&D){E=!0;continue}if(R&&!D)continue;let B=w.customProgram||this.renderProg,L=w.customUniforms||this.uRender;t.useProgram(B),t.uniform1i(L.uToneMapping,o),t.uniform1f(L.uEnvIntensity,this.envIntensity),t.uniform3f(L.uCameraPos,d,p,m),t.uniform1f(L.uEmissive,h?1:0),t.uniformMatrix4fv(L.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(L.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(L.uNormalMatrix,!1,M.normalMatrix),L.uUvTransform&&t.uniform4f(L.uUvTransform,y,T,F,C),L.uViewportSize&&t.uniform2f(L.uViewportSize,Math.max(1,s),Math.max(1,c)),a?.bind(t,L,this.xrDepthState,u,[i,r,Math.max(1,s),Math.max(1,c)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(L.uEnvironmentMap,4),t.uniform1i(L.uHasEnvironmentMap,1)):t.uniform1i(L.uHasEnvironmentMap,0),this.bindLights(L),L.uSectionEnabled&&t.uniform1i(L.uSectionEnabled,0);for(let q of K)q.onBeforeDrawPrimitive?.(t,B,w,M,this.worldMatrices||[],this.gltf);t.uniform4fv(L.uBaseColor,w.baseColor),t.uniform1f(L.uMetallic,w.metallic),t.uniform1f(L.uRoughness,w.roughness),L.uClearcoat&&t.uniform2f(L.uClearcoat,w.clearcoat??0,w.clearcoatRoughness??.04),w.texture?(t.activeTexture(33984),t.bindTexture(3553,w.texture),t.uniform1i(L.uBaseColorTexture,0),t.uniform1i(L.uHasTexture,1)):t.uniform1i(L.uHasTexture,0),w.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,w.metallicRoughnessTexture),t.uniform1i(L.uMetallicRoughnessTexture,1),t.uniform1i(L.uHasMetallicRoughnessTexture,1)):t.uniform1i(L.uHasMetallicRoughnessTexture,0),w.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,w.normalTexture),t.uniform1i(L.uNormalTexture,2),t.uniform1i(L.uHasNormalTexture,1),t.uniform1f(L.uNormalScale,w.normalScale)):t.uniform1i(L.uHasNormalTexture,0),w.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,w.occlusionTexture),t.uniform1i(L.uOcclusionTexture,3),t.uniform1i(L.uHasOcclusionTexture,1),t.uniform1f(L.uOcclusionStrength,w.occlusionStrength)):t.uniform1i(L.uHasOcclusionTexture,0),t.bindVertexArray(w.vao),t.drawElements(4,w.indexCount,w.indexType,0)}}};if(A(!1),E){for(let R of K)R.onBeforeTransmissivePass?.(t,this);A(!0)}for(let R of K)R.onAfterRender?.(t,this,l)}disposeMeshListGpuResources(e){let t=this.gl;for(let i of e)for(let r of i.primitives){if(r.vao&&t.deleteVertexArray(r.vao),r.buffers)for(let s of r.buffers)t.deleteBuffer(s);r.texture&&t.deleteTexture(r.texture),r.metallicRoughnessTexture&&t.deleteTexture(r.metallicRoughnessTexture),r.normalTexture&&t.deleteTexture(r.normalTexture),r.occlusionTexture&&t.deleteTexture(r.occlusionTexture),r.customProgram&&t.deleteProgram(r.customProgram)}}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes),this.meshes=[]}disposeGpuResources(){let e=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let t of K)t.onDestroy?.(e,this);this.environmentTexture&&(e.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&e.deleteProgram(this.renderProg),this.pickProg&&e.deleteProgram(this.pickProg),this.pickFbo&&e.deleteFramebuffer(this.pickFbo),this.pickTexture&&e.deleteTexture(this.pickTexture),this.pickDepth&&e.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};Ee.registerPlugin=Ge,Ee.getRegisteredPlugins=He;function Ue(n){return new TextEncoder().encode(n)}function gt(n,e){n.updateMatrixWorld(!0);let t=[];return n.traverse(i=>{if(i.geometry){let r=i.geometry,s=r.attributes.position;if(!s||s.count===0)return;let c=s.count,l=new Float32Array(c*3),u=i.matrixWorld.elements;for(let h=0;h<c;h++){let v=s.getX(h),y=s.getY(h),T=s.getZ(h);l[h*3]=u[0]*v+u[4]*y+u[8]*T+u[12],l[h*3+1]=u[1]*v+u[5]*y+u[9]*T+u[13],l[h*3+2]=u[2]*v+u[6]*y+u[10]*T+u[14]}let a;if(r.attributes.normal){let h=r.attributes.normal;a=new Float32Array(c*3);let v=new Float32Array(9);he(v,u);for(let y=0;y<c;y++){let T=h.getX(y),F=h.getY(y),C=h.getZ(y),w=v[0]*T+v[3]*F+v[6]*C,D=v[1]*T+v[4]*F+v[7]*C,B=v[2]*T+v[5]*F+v[8]*C,L=Math.hypot(w,D,B)||1;a[y*3]=w/L,a[y*3+1]=D/L,a[y*3+2]=B/L}}let o;if(r.attributes.uv){let h=r.attributes.uv;o=new Float32Array(c*2);for(let v=0;v<c;v++)o[v*2]=h.getX(v),o[v*2+1]=h.getY(v)}let f;if(r.index)f=r.index.array;else{f=c>65535?new Uint32Array(c):new Uint16Array(c);for(let h=0;h<c;h++)f[h]=h}let d="DefaultMaterial",p=[.8,.8,.8],m=.5,x=.1,b=0,E=0,P=1.5,A=1,R=[0,0,0];if(i.material){let h=i.material;d=h.name||`Material_${t.length}`,h.color&&(p=[h.color.r,h.color.g,h.color.b]),typeof h.roughness=="number"&&(m=h.roughness),typeof h.metalness=="number"&&(x=h.metalness),typeof h.clearcoat=="number"&&(b=h.clearcoat),typeof h.clearcoatRoughness=="number"&&(E=h.clearcoatRoughness),typeof h.ior=="number"&&(P=h.ior);let v=typeof h.opacity=="number"?h.opacity:1,y=typeof h.transmission=="number"?h.transmission:0;if(A=v*(1-y),h.emissive&&(h.emissive.r>0||h.emissive.g>0||h.emissive.b>0)){let T=h.emissiveIntensity??1;R=[h.emissive.r*T,h.emissive.g*T,h.emissive.b*T]}}let g,M=e?.animateCallback||e?.animateFn||(typeof n.userData?.animate=="function"?n.userData.animate:typeof n.__animateFn=="function"?n.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0);if(typeof M=="function"){let h=e?.duration??4,v=e?.fps??4,y=Math.max(2,Math.round(h*v)+1),T=[],F=[],C=[],w=[],D=[i.position.x,i.position.y,i.position.z],B=[i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w],L=[i.scale.x,i.scale.y,i.scale.z],q=!1;for(let z=0;z<y;z++){let j=z/(y-1)*h;T.push(j);try{M(j)}catch{}F.push([i.position.x,i.position.y,i.position.z]),C.push([i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w]),w.push([i.scale.x,i.scale.y,i.scale.z]),(Math.abs(i.position.x-D[0])>1e-4||Math.abs(i.position.y-D[1])>1e-4||Math.abs(i.position.z-D[2])>1e-4||Math.abs(i.quaternion.x-B[0])>1e-4||Math.abs(i.quaternion.y-B[1])>1e-4||Math.abs(i.quaternion.z-B[2])>1e-4||Math.abs(i.quaternion.w-B[3])>1e-4||Math.abs(i.scale.x-L[0])>1e-4)&&(q=!0)}i.position.set(D[0],D[1],D[2]),i.quaternion.set(B[0],B[1],B[2],B[3]),i.scale.set(L[0],L[1],L[2]),q&&(g={times:T,translations:F,rotations:C,scales:w})}t.push({name:i.name||`Mesh_${t.length}`,positions:l,indices:f,normals:a,uvs:o,materialName:d,color:p,roughness:m,metallic:x,clearcoat:b,clearcoatRoughness:E,ior:P,opacity:A,emissiveColor:R,xrTraits:i.userData?.xr,timeSamples:g})}}),t}function Je(n){let e=[],t=n.gltf,i=n.bin,r=i instanceof ArrayBuffer?i:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),s=t.accessors||[],c=t.bufferViews||[],l=t.materials||[],u=t.meshes||[],a=t.nodes||[];function o(p){let m=s[p];if(!m)throw new Error(`Accessor ${p} not found`);let x=c[m.bufferView||0],b=(x.byteOffset||0)+(m.byteOffset||0),E=x.byteLength||0,P=r.slice(b,b+E);return{acc:m,buffer:P}}let f=new Map;if(a.length>0){let p=we(t);for(let m=0;m<p.length;m++)f.set(m,p[m])}function d(p,m,x,b){let E=u[p];if(!E)return;let P=new Float32Array(9);he(P,m);for(let A=0;A<(E.primitives||[]).length;A++){let R=E.primitives[A],g=R.attributes?.POSITION;if(g===void 0)continue;let{acc:M,buffer:h}=o(g),v=new Float32Array(h,0,M.count*3),y=new Float32Array(v.length);for(let I=0;I<M.count;I++){let S=v[I*3],U=v[I*3+1],_=v[I*3+2];y[I*3]=m[0]*S+m[4]*U+m[8]*_+m[12],y[I*3+1]=m[1]*S+m[5]*U+m[9]*_+m[13],y[I*3+2]=m[2]*S+m[6]*U+m[10]*_+m[14]}let T,F=R.attributes?.NORMAL;if(F!==void 0){let{acc:I,buffer:S}=o(F),U=new Float32Array(S,0,I.count*3);T=new Float32Array(U.length);for(let _=0;_<I.count;_++){let ee=U[_*3],re=U[_*3+1],X=U[_*3+2],ce=P[0]*ee+P[3]*re+P[6]*X,ie=P[1]*ee+P[4]*re+P[7]*X,te=P[2]*ee+P[5]*re+P[8]*X,k=Math.hypot(ce,ie,te)||1;T[_*3]=ce/k,T[_*3+1]=ie/k,T[_*3+2]=te/k}}let C,w=R.attributes?.TEXCOORD_0;if(w!==void 0){let{acc:I,buffer:S}=o(w);C=new Float32Array(S,0,I.count*2)}let D;if(R.indices!==void 0){let{acc:I,buffer:S}=o(R.indices);I.componentType===5125?D=new Uint32Array(S,0,I.count):D=new Uint16Array(S,0,I.count);let U=M.count;for(let _ of D)if(_>=U)throw new Error(`SecurityError: Index buffer value (${_}) out of vertex bounds [0, ${U}).`)}else{let I=M.count;D=I>65535?new Uint32Array(I):new Uint16Array(I);for(let S=0;S<I;S++)D[S]=S}let B="DefaultMaterial",L=[.8,.8,.8],q=.5,z=.1,j=0,H=0,$=1.5,G=1,N=[0,0,0];if(R.material!==void 0&&l[R.material]){let I=l[R.material];B=I.name||`Material_${R.material}`;let S=I.pbrMetallicRoughness||{},U=1;Array.isArray(S.baseColorFactor)&&(L=[S.baseColorFactor[0],S.baseColorFactor[1],S.baseColorFactor[2]],typeof S.baseColorFactor[3]=="number"&&(U=S.baseColorFactor[3])),typeof S.roughnessFactor=="number"&&(q=S.roughnessFactor),typeof S.metallicFactor=="number"&&(z=S.metallicFactor),Array.isArray(I.emissiveFactor)&&I.emissiveFactor.length>=3&&(N=[I.emissiveFactor[0],I.emissiveFactor[1],I.emissiveFactor[2]]);let _=I.extensions||{};_.KHR_materials_clearcoat&&(j=_.KHR_materials_clearcoat.clearcoatFactor??0,H=_.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),_.KHR_materials_ior&&typeof _.KHR_materials_ior.ior=="number"&&($=_.KHR_materials_ior.ior);let ee=_.KHR_materials_transmission?.transmissionFactor??0;G=U*(1-ee)}let W=(E.primitives||[]).length>1?`${x}_p${A}`:x;e.push({name:W,positions:y,indices:D,normals:T,uvs:C,materialName:B,color:L,roughness:q,metallic:z,clearcoat:j,clearcoatRoughness:H,ior:$,opacity:G,emissiveColor:N,xrTraits:b?.xr||E.extras?.xr})}}if(a.length>0)for(let p=0;p<a.length;p++){let m=a[p];if(m.mesh!==void 0&&m.mesh<u.length){let x=f.get(p)||Z(),b=m.name||u[m.mesh].name||`Node_${p}`;d(m.mesh,x,b,m.extras)}}else{let p=Z();for(let m=0;m<u.length;m++){let x=u[m].name||`Mesh_${m}`;d(m,p,x,u[m].extras)}}return e}function Ie(n,e){if(!n||typeof n!="string")return e;let t=n.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(t)&&(t="_"+t),t||e}function je(n){return String(n??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function V(n){if(!Number.isFinite(n)||Math.abs(n)<1e-7)return"0";let e=Number(n.toFixed(5)).toString();return e.indexOf(".")===-1?`${e}.0`:e}function Qe(n){let e=n.length/3,t=new Array(e);for(let i=0;i<e;i++)t[i]=`(${V(n[i*3])}, ${V(n[i*3+1])}, ${V(n[i*3+2])})`;return t.join(", ")}function vt(n,e){let t=new Array(e);for(let i=0;i<e;i++)t[i]=`(${V(n[i*2])}, ${V(1-n[i*2+1])})`;return t.join(", ")}function xt(n){return Array.from(n).join(", ")}function _e(n){let e=new Map;for(let u of n){let a=Ie(u.materialName,"DefaultMaterial");e.has(a)||e.set(a,{color:u.color||[.8,.8,.8],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]})}let t=0,i=null;for(let u of n){if(u.timeSamples&&u.timeSamples.times.length>0){let a=u.timeSamples.times[u.timeSamples.times.length-1];a>t&&(t=a)}u.xrTraits?.anchor&&!i&&(i=u.xrTraits.anchor==="vertical"||u.xrTraits.anchor==="wall"?"vertical":"horizontal")}let r="";t>0&&(r=`startTimeCode = 0
|
|
209
|
-
endTimeCode = ${
|
|
250
|
+
void main(){fragColor=uColorId;}`;function $e(n,e,t){let r=n.createShader(e);if(n.shaderSource(r,t),n.compileShader(r),!n.getShaderParameter(r,35713)){let i=n.getShaderInfoLog(r);throw n.deleteShader(r),new Error(`Shader compile error: ${i}`)}return r}function _e(n,e,t){let r=$e(n,35633,e),i=$e(n,35632,t),s=n.createProgram();if(n.attachShader(s,r),n.attachShader(s,i),n.linkProgram(s),!n.getProgramParameter(s,35714)){let a=n.getProgramInfoLog(s);throw n.deleteProgram(s),new Error(`Program link error: ${a}`)}return s}function Ne(n,e,t){let r={};for(let i of t)r[i]=n.getUniformLocation(e,i);return r}var qe=["uMVP","uModel","uInstanced","uViewProj","uNormalMatrix","uUvTransform","uBaseColor","uMetallic","uRoughness","uClearcoat","uEmissive","uCameraPos","uBaseColorTexture","uHasTexture","uMetallicRoughnessTexture","uHasMetallicRoughnessTexture","uNormalTexture","uHasNormalTexture","uNormalScale","uOcclusionTexture","uHasOcclusionTexture","uOcclusionStrength","uToneMapping","uEnvironmentMap","uHasEnvironmentMap","uAmbientColor","uNumDirLights","uDirLightDir","uDirLightColor","uNumPointLights","uPointLightPos","uPointLightColor","uEnvIntensity","uExposure","uViewportSize","uSectionPlane","uSectionEnabled"];function Je(){let n=he().xrDepthShader;return{fs:At.replace("/*XRD_U*/",n?.uniformsGLSL||"").replace("/*XRD_O*/",n?.occlusionGLSL||""),uniforms:n?[...qe,...n.uniformNames]:qe}}function Et(n){if(typeof n!="string")return null;let e=n.trim();if(!e||/[\x00-\x1f\x7f]/.test(e))return null;let t=e.toLowerCase();return t.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(e)?e:null:t.startsWith("https://")||t.startsWith("blob:")?e:t.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(e)||/(^|[\\/])\.\.([\\/]|$)/.test(e)?null:e}function Fe(n,e,t,r,i,s,a,c){if(r===void 0||!e.accessors?.[r])return null;let o=De(e,t,e.accessors[r],s);if(!o)return null;c&&(o=o.slice(),Xe(o,c));let l=n.createBuffer();return a.push(l),n.bindBuffer(34962,l),n.bufferData(34962,o,35044),n.enableVertexAttribArray(i),n.vertexAttribPointer(i,s,5126,!1,0,0),o}function Ce(n){let e=Number(n);return Number.isFinite(e)?Math.max(0,e):1}function et(n,e,t){let r=Je(),i=Qe,s=r.fs,a=!1;for(let o of ae)if(o.onResolveShader){let l=o.onResolveShader(e,t,i,s);l&&(i=l.vs,s=l.fs,a=!0)}let c=a?_e(n,i,s):null;return{program:c,uniforms:c?Ne(n,c,r.uniforms):null}}function Lt(n,e,t){let r=e.instanceMatrices;if(!r||r.length<16||typeof n.vertexAttribDivisor!="function"||typeof n.drawElementsInstanced!="function")return!1;let i=r.length>>4,s=e.instanceColors,a=new Float32Array(i*20);for(let o=0;o<i;o++)a.set(r.subarray(o*16,o*16+16),o*20),a[o*20+16]=s?s[o*3]:1,a[o*20+17]=s?s[o*3+1]:1,a[o*20+18]=s?s[o*3+2]:1,a[o*20+19]=1;let c=n.createBuffer();t.push(c),n.bindBuffer(34962,c),n.bufferData(34962,a,35044);for(let o=0;o<5;o++)n.enableVertexAttribArray(8+o),n.vertexAttribPointer(8+o,4,5126,!1,80,o*16),n.vertexAttribDivisor(8+o,1);return!0}function St(n,e){let t=n.materials?.[e?.material];if(!t)return null;let r=[t.pbrMetallicRoughness?.baseColorTexture,t.pbrMetallicRoughness?.metallicRoughnessTexture,t.normalTexture,t.occlusionTexture,t.emissiveTexture];for(let i of r){let s=i?.extensions?.KHR_texture_transform;if(s&&typeof s=="object")return s}return null}var Xt=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),tt=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function we(n,e){e.indices?n.drawElements(4,e.indexCount,e.indexType,0):n.drawArrays(4,0,e.indexCount)}function nt(n,e){let t=n?.pbrMetallicRoughness,r=t?.baseColorFactor,i=n?.extensions?.KHR_materials_clearcoat,s=a=>a!==void 0&&e[a.index]?e[a.index]:null;return{baseColor:r?[r[0],r[1],r[2],r[3]??1]:[.8,.8,.8,1],metallic:t?.metallicFactor??.1,roughness:t?.roughnessFactor??.5,clearcoat:i?i.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,i?.clearcoatRoughnessFactor??.04),texture:s(t?.baseColorTexture),metallicRoughnessTexture:s(t?.metallicRoughnessTexture),normalTexture:s(n?.normalTexture),normalScale:n?.normalTexture?.scale??1,occlusionTexture:s(n?.occlusionTexture),occlusionStrength:n?.occlusionTexture?.strength??1,isTransmissive:(n?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function rt(n,e,t){let r=new Set,i=s=>{s&&!r.has(s)&&(r.add(s),n.deleteTexture(s))};for(let s of e)for(let a of s.primitives){if(a.vao&&n.deleteVertexArray(a.vao),a.buffers)for(let o of a.buffers)n.deleteBuffer(o);i(a.texture),i(a.metallicRoughnessTexture),i(a.normalTexture),i(a.occlusionTexture);let c=new Set;a.customProgram&&c.add(a.customProgram);for(let o of a.programCache?.values()??[])o.program&&c.add(o.program);for(let o of c)n.deleteProgram(o)}if(t)for(let s of t)i(s)}function Ye(n,e,t=tt,r){let i={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return Pt(n,e,t,r,i)}catch(s){let a=i.mesh&&!i.meshes.includes(i.mesh)?[...i.meshes,i.mesh]:i.meshes;rt(n,a,i.gpuTextures),i.vao&&n.deleteVertexArray(i.vao);for(let c of i.buffers)n.deleteBuffer(c);throw s}}function Pt(n,e,t,r,i){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:s}=e,a=pe("meshopt");a?.decodeBufferViews&&a.decodeBufferViews(s,e);let c=e.bin,o=[];i.meshes=o;let l=[],u=s.extensions?.KHR_materials_variants;u&&Array.isArray(u.variants)&&u.variants.forEach((m,w)=>{l.push(typeof m?.name=="string"&&m.name?m.name:`Variant_${w}`)});let d=Te(s),f=[];if(Array.isArray(s.nodes))for(let m=0;m<s.nodes.length;m++){let w=s.nodes[m];w.mesh!==void 0&&s.meshes&&s.meshes[w.mesh]&&f.push({node:w,nodeIdx:m,meshIdx:w.mesh})}let T=f.length>0?f:(s.meshes||[]).map((m,w)=>({node:m,nodeIdx:-1,meshIdx:w})),p=[];if(Array.isArray(e.lights)&&e.lights.length>0)p.push(...e.lights);else if(s.extensions?.KHR_lights_punctual?.lights){let m=s.extensions.KHR_lights_punctual.lights;for(let w of m){let S=w.type==="directional"?"directional":w.type==="point"?"point":"ambient";p.push({type:S,color:w.color||[1,1,1],intensity:w.intensity!==void 0?w.intensity:1})}}if(p.length===0&&(p.push({type:"ambient",color:[1,1,1],intensity:.35}),p.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),T.length>t.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${t.maxMeshes}). Found: ${T.length}`);let h=[];if(i.gpuTextures=h,s.textures&&s.images){if(s.textures.length>t.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${t.maxTextures}). Found: ${s.textures.length}`);for(let m=0;m<s.textures.length;m++){let w=s.textures[m],S=s.images[w.source];if(S){let M=n.createTexture();if(n.bindTexture(3553,M),n.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),n.texParameteri(3553,10242,10497),n.texParameteri(3553,10243,10497),n.texParameteri(3553,10241,9729),n.texParameteri(3553,10240,9729),S.bufferView!==void 0){let k=s.bufferViews[S.bufferView],_=c.slice(k.byteOffset||0,(k.byteOffset||0)+k.byteLength),K=new Blob([_],{type:S.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(K).then(U=>{n.bindTexture(3553,M),n.texImage2D(3553,0,6408,6408,5121,U),n.generateMipmap(3553),r?.()}).catch(()=>{})}else if(S.uri){let k=Et(S.uri);if(k){let _=new Image;_.crossOrigin="anonymous",_.referrerPolicy="no-referrer",_.onload=()=>{n.bindTexture(3553,M),n.texImage2D(3553,0,6408,6408,5121,_),n.generateMipmap(3553),r?.()},_.src=k}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",S.uri)}h.push(M)}else h.push(null)}}let b=[1/0,1/0,1/0],R=[-1/0,-1/0,-1/0],A=0,v=0;for(let m=0;m<T.length;m++){let w=T[m],S=s.meshes[w.meshIdx],M=w.nodeIdx>=0?d[w.nodeIdx]:re(),k=new Float32Array(9);me(k,M);let _={name:w.node.name||S.name||`Mesh_${w.meshIdx}`,nodeIndex:w.nodeIdx,transform:M,normalMatrix:k,primitives:[],extras:w.node.extras||S.extras};i.mesh=_;let K=w.node?.extensions?.EXT_mesh_gpu_instancing;if(K&&K.attributes&&typeof K.attributes=="object"){let U=K.attributes,O=U.TRANSLATION!==void 0?s.accessors?.[U.TRANSLATION]:null,B=U.ROTATION!==void 0?s.accessors?.[U.ROTATION]:null,q=U.SCALE!==void 0?s.accessors?.[U.SCALE]:null,Y=U._COLOR_0!==void 0?s.accessors?.[U._COLOR_0]:null,W=Number(O?.count??B?.count??q?.count??0);if(!Number.isFinite(W)||W<0||W>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${W}`);if(W>0){let j=(H,$)=>{if(!H||H.bufferView===void 0||!s.bufferViews?.[H.bufferView])return null;let G=H.componentType??5126,te=J=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${J})`),null);if(G!==5120&&G!==5121&&G!==5122&&G!==5123&&G!==5126)return te(`componentType ${G}`);if(!(Number(H.count)>=W))return te(`count ${H.count} < ${W}`);let V=null;try{V=De(s,c,{...H,count:W},$)}catch{return te("out of bounds")}return!V||!V.every(Number.isFinite)?te("non-finite value"):V},x=j(O,3),I=j(B,4),N=j(q,3),z=Y?.type==="VEC4"?4:3,ee=j(Y,z),ie=new Float32Array(W*16),oe=re();for(let H=0;H<W;H++){let $=x?[x[H*3],x[H*3+1],x[H*3+2]]:[0,0,0],G=I?[I[H*4],I[H*4+1],I[H*4+2],I[H*4+3]]:[0,0,0,1],te=N?[N[H*3],N[H*3+1],N[H*3+2]]:[1,1,1];ye(oe,G,$,te),ie.set(oe,H*16)}if(_.instanceMatrices=ie,ee){let H=new Float32Array(W*3);for(let $=0;$<W;$++)H[$*3]=ee[$*z],H[$*3+1]=ee[$*z+1],H[$*3+2]=ee[$*z+2];_.instanceColors=H}}}for(let U of S.primitives||[]){if(U.extensions?.KHR_draco_mesh_compression){let V=pe("draco");V&&V.decodePrimitive(s,U,c)}let O=[],B=n.createVertexArray();i.vao=B,i.buffers=O,n.bindVertexArray(B);let q=Lt(n,_,O),Y=s.accessors[U.attributes.POSITION],W=Number(Y?.count??0);if(!Number.isFinite(W)||W<0||A+W>t.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${t.maxVertices}).`);if(A+=W,Y?.min&&Y?.max){let V=J=>{for(let Q=0;Q<3;Q++){let Z=J[12+Q],ne=J[12+Q];for(let le=0;le<3;le++){let ce=J[le*4+Q]*Y.min[le],ue=J[le*4+Q]*Y.max[le];Z+=ce<ue?ce:ue,ne+=ce>ue?ce:ue}Z<b[Q]&&(b[Q]=Z),ne>R[Q]&&(R[Q]=ne)}};if(_.instanceMatrices&&_.instanceMatrices.length>=16){let J=_.instanceMatrices.length>>4,Q=re();for(let Z=0;Z<J;Z++){let ne=_.instanceMatrices.subarray(Z*16,Z*16+16);se(Q,M,ne),V(Q)}}else V(M)}let j=Fe(n,s,c,U.attributes.POSITION,0,3,O);Fe(n,s,c,U.attributes.NORMAL,1,3,O),Fe(n,s,c,U.attributes.TEXCOORD_0,2,2,O,St(s,U));let x=0,I=5123,N=null;if(U.indices!==void 0){let V=s.accessors[U.indices],Q=(s.bufferViews[V.bufferView].byteOffset||0)+(V.byteOffset||0);if(x=Number(V.count??0),!Number.isFinite(x)||x<0||v+x>t.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${t.maxIndices}).`);v+=x,I=V.componentType===5125?5125||5125:5123||5123;let Z=n.createBuffer();O.push(Z),n.bindBuffer(34963,Z),V.componentType===5125?(N=new Uint32Array(c,Q,V.count),n.bufferData(34963,N,35044)):V.componentType===5121?(N=Uint16Array.from(new Uint8Array(c,Q,V.count)),n.bufferData(34963,N,35044)):(N=Q%2===0?new Uint16Array(c,Q,V.count):new Uint16Array(c.slice(Q,Q+V.count*2)),n.bufferData(34963,N,35044))}else x=Y.count;let z={};for(let V of ae)if(V.onBuildPrimitiveVAO){let J=V.onBuildPrimitiveVAO(n,B,U,s,c);J&&(z[V.name]=J)}n.bindVertexArray(null);let ee=s.materials&&U.material!==void 0?s.materials[U.material]:null,{program:ie,uniforms:oe}=et(n,U,ee),H=nt(ee,h),$=!!(ee?.extensions?.KHR_materials_transmission||z.materials?.isTransmissive),G=U.extensions?.KHR_materials_variants?.mappings,te=Array.isArray(G)?G.filter(V=>V&&typeof V.material=="number"&&Array.isArray(V.variants)).map(V=>({material:V.material|0,variants:V.variants.map(J=>Number(J)|0)})):void 0;_.primitives.push({vao:B,instanced:q,indexCount:x,indexType:I,...H,positions:j,indices:N,buffers:O,materialIndex:U.material,defaultMaterialIndex:U.material,variantMappings:te,primitiveDef:U,programCache:new Map([[U.material??-1,{program:ie,uniforms:oe}]]),pluginData:z,customProgram:ie,customUniforms:oe,isTransmissive:$})}o.push(_)}isFinite(b[0])||(b=[-1,-1,-1]),isFinite(R[0])||(R=[1,1,1]);let D=[(b[0]+R[0])/2,(b[1]+R[1])/2,(b[2]+R[2])/2],g=R[0]-b[0],P=R[1]-b[1],E=R[2]-b[2],y=Math.max(Math.hypot(g,P,E)/2,.5),F=[b[0],b[1],b[2]],L=[R[0],R[1],R[2]],C=e.animations;if(!C){for(let m of ae)if(m.onParseGLB?.(e),e.animations){C=e.animations;break}}return C||(C=[]),{meshes:o,bounds:{center:D,radius:y,min:F,max:L},lights:p,animations:C,worldMatrices:d,gpuTextures:h,availableVariants:l}}function ge(n){let e=n.customTarget||n.bounds.center,t=n.currDistance*Math.cos(n.currPhi);return[e[0]+t*Math.sin(n.currTheta),e[1]+n.currDistance*Math.sin(n.currPhi),e[2]+t*Math.cos(n.currTheta)]}var Re=class{constructor(e,t,r){this.meshes=[];this.backdropMeshes=[];this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]};this.lights=[];this.modelRootMatrix=re();this.clearColor=[0,0,0,0];this.envIntensity=1;this.exposure=1;this.shadowIntensity=0;this.shadowSoftness=.5;this.toneMapping="neutral";this.environmentTexture=null;this.animations=[];this.currentClip=null;this.animationTime=0;this.isPlayingAnimation=!1;this.autoplay=!1;this.animationName="";this.gpuTextures=[];this.availableVariants=[];this.activeVariantName=null;this.gltf=null;this.worldMatrices=[];this.initialNodeTransforms=[];this.projMatrix=re();this.viewMatrix=re();this.activeViewMatrix=null;this.modelMatrix=re();this.mvpMatrix=re();this.normalMatrix=new Float32Array(9);this.initialTheta=.6;this.initialPhi=.35;this.initialDistance=null;this.customDistance=!1;this.distanceMode="auto";this.initialCustomTarget=null;this.customTarget=null;this.fov=Math.PI/4;this.minTheta=-1/0;this.maxTheta=1/0;this.minPhi=-Math.PI*.48;this.maxPhi=Math.PI*.48;this.minDistanceLimit=null;this.maxDistanceLimit=null;this.activePointers=new Map;this.isPanning=!1;this.targetTheta=.6;this.currTheta=.6;this.targetPhi=.35;this.currPhi=.35;this.targetDistance=3;this.currDistance=3;this.autoRotate=!1;this.autoRotateSpeed=Math.PI/6;this.autoRotateDelay=3e3;this.lastInteractionTime=-1/0;this.turntableRotation=0;this.isPointerDown=!1;this.interactive=!0;this.skyboxTexture=null;this.lastPointerX=0;this.lastPointerY=0;this.totalDragDist=0;this.selectedMeshName="";this.pickFbo=null;this.pickTexture=null;this.pickDepth=null;this.pickFboWidth=0;this.pickFboHeight=0;this.animFrameId=null;this.isVisible=!0;this.xrSessionActive=!1;this.lastTime=0;this.lastReportedTheta=-999;this.lastReportedPhi=-999;this.lastReportedZoom=-999;this.boundPointerDown=null;this.boundPointerMove=null;this.boundPointerUp=null;this.boundWheel=null;this.boundKeyDown=null;this.boundContextMenu=null;this.boundSetCamera=null;this.boundResetCamera=null;this.contextLost=!1;this.lastGlbData=null;this.boundContextLost=null;this.boundContextRestored=null;this.stereoSBS=!1;this.renderErrorReported=!1;this.xrDepthState={enabled:!1,texture:null,uvTransform:re(),rawValueToMeters:.001,format:0};this.container=e;let i,s;if(t&&typeof t.getContext=="function"?(i=t,s=r):(s=t,i=s?.canvas),!i){let o=e.querySelector("canvas");o||(o=document.createElement("canvas"),o.style.width="100%",o.style.height="100%",o.style.display="block",o.style.touchAction="none",e.prepend(o)),i=o}this.canvas=i,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!a:a&&(this.autoRotate=!1),this.opts.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=this.opts.autoRotateSpeed),this.opts.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(this.opts.autoRotateDelay)||0)),this.opts.exposure!==void 0&&(this.exposure=Ce(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=Ie(this.opts.toneMapping)),this.opts.autoplay!==void 0&&(this.autoplay=this.opts.autoplay),this.opts.animationName!==void 0&&(this.animationName=this.opts.animationName),this.opts.variantName!==void 0&&(this.activeVariantName=this.opts.variantName||null),this.opts.fieldOfView!==void 0&&(this.fov=this.opts.fieldOfView*Math.PI/180),this.opts.distanceMode!==void 0&&(this.distanceMode=this.opts.distanceMode),this.opts.cameraTarget!==void 0&&(this.setTarget(this.opts.cameraTarget[0],this.opts.cameraTarget[1],this.opts.cameraTarget[2]),this.initialCustomTarget=[...this.opts.cameraTarget]),(this.opts.minCameraOrbit||this.opts.maxCameraOrbit)&&this.setOrbitLimits({minTheta:this.opts.minCameraOrbit?.theta,maxTheta:this.opts.maxCameraOrbit?.theta,minPhi:this.opts.minCameraOrbit?.phi,maxPhi:this.opts.maxCameraOrbit?.phi,minDistance:this.opts.minCameraOrbit?.distance,maxDistance:this.opts.maxCameraOrbit?.distance});let c=i.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!c)throw new Error("WebGL2 not supported");this.gl=c,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(e,t){Mt(e,t)}static getDecoder(e){return pe(e)}setupContextLossHandling(){let e=this.canvas;typeof e?.addEventListener=="function"&&(this.boundContextLost=t=>{t.preventDefault?.(),this.contextLost=!0,this.stop()},this.boundContextRestored=()=>this.restoreContext(),e.addEventListener("webglcontextlost",this.boundContextLost),e.addEventListener("webglcontextrestored",this.boundContextRestored))}initGlState(){let e=this.gl,t=Je();this.renderProg=_e(e,Qe,t.fs),this.pickProg=_e(e,wt,Rt),this.uRender=Ne(e,this.renderProg,t.uniforms),this.uPick=Ne(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of ae)t.onContextRestored?.(e,this);this.meshes=[],this.gpuTextures=[],this.environmentTexture=null,this.lastGlbData&&this.loadGLBData(this.lastGlbData,this.lastLimits),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}setupPickingFbo(){let e=this.gl;if(typeof e.createFramebuffer!="function")return;this.pickFbo=e.createFramebuffer(),this.pickTexture=e.createTexture(),this.pickDepth=e.createRenderbuffer();let t=Math.max(1,this.canvas.width),r=Math.max(1,this.canvas.height);this.pickFboWidth=t,this.pickFboHeight=r,e.bindTexture(3553,this.pickTexture),e.texImage2D(3553,0,6408,t,r,0,6408,5121,null),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728),e.bindRenderbuffer(36161,this.pickDepth),e.renderbufferStorage(36161,33189,t,r),e.bindFramebuffer(36160,this.pickFbo),e.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),e.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),e.bindFramebuffer(36160,null)}resizePickingFbo(e,t){if(!this.pickFbo)return;let r=this.gl,i=Math.max(1,e),s=Math.max(1,t);this.pickFboWidth=i,this.pickFboHeight=s,r.bindTexture(3553,this.pickTexture),r.texImage2D(3553,0,6408,i,s,0,6408,5121,null),r.bindRenderbuffer(36161,this.pickDepth),r.renderbufferStorage(36161,33189,i,s)}loadGLBData(e,t){this.lastGlbData=e,this.lastLimits=t;let{meshes:r,bounds:i,lights:s,animations:a,worldMatrices:c,gpuTextures:o,availableVariants:l}=Ye(this.gl,e,t,()=>this.render());if(this.disposeMeshGpuResources(),this.meshes=r,this.bounds=i,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=s,this.animations=a||[],this.worldMatrices=c||[],this.gpuTextures=o||[],this.availableVariants=l||[],this.gltf=e.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let f of e.gltf.nodes)this.initialNodeTransforms.push({t:f.translation?[f.translation[0],f.translation[1],f.translation[2]]:[0,0,0],r:f.rotation?[f.rotation[0],f.rotation[1],f.rotation[2],f.rotation[3]]:[0,0,0,1],s:f.scale?[f.scale[0],f.scale[1],f.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let f of ae)f.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:i.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let u=e.exposure??e.gltf?.extras?.exposure??e.gltf?.asset?.extras?.exposure;u!==void 0&&(this.exposure=Ce(u));let d=e.environmentIntensity??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.environmentIntensity;d!==void 0&&(this.envIntensity=Math.max(0,Number(d)||0)),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(e){this.loadGLBData(je(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(xe(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=xe(e),{meshes:i}=Ye(this.gl,r,tt,()=>this.render());if(t)for(let s of i)s.transform[12]+=t[0],s.transform[13]+=t[1],s.transform[14]+=t[2],me(s.normalMatrix,s.transform);this.backdropMeshes=i,this.update(0),this.render()}setClearColor(e,t,r,i=1){this.clearColor=[e,t,r,i]}updateMeshTransforms(e){for(let t=0;t<this.meshes.length;t++){let r=this.meshes[t],i;e instanceof Map?i=e.get(r.name)??e.get(t):Array.isArray(e)?i=e[t]:e&&typeof e=="object"&&(Object.prototype.hasOwnProperty.call(e,r.name)?i=e[r.name]:Object.prototype.hasOwnProperty.call(e,t)&&(i=e[t])),i&&i.length===16&&(r.transform.set(i),me(r.normalMatrix,r.transform))}}bindLights(e=this.uRender){let t=this.gl,r=[.28,.28,.28],i=[],s=[],a=[],c=[];for(let o of this.lights){let l=o.color||[1,1,1],u=o.intensity!==void 0?o.intensity:1;if(o.type==="ambient")r=[l[0]*u,l[1]*u,l[2]*u];else if(o.type==="directional"&&i.length<6){let d=o.direction||[.5,1,.8];i.push(d[0],d[1],d[2]),s.push(l[0]*u,l[1]*u,l[2]*u)}else if(o.type==="point"&&a.length<6){let d=o.position||[0,0,0];a.push(d[0],d[1],d[2]),c.push(l[0]*u,l[1]*u,l[2]*u)}}i.length===0&&(i.push(.5,1,.8),s.push(1,1,1)),t.uniform3fv(e.uAmbientColor,r),t.uniform1i(e.uNumDirLights,i.length/3),i.length>0&&(t.uniform3fv(e.uDirLightDir,i),t.uniform3fv(e.uDirLightColor,s)),t.uniform1i(e.uNumPointLights,a.length/3),a.length>0&&(t.uniform3fv(e.uPointLightPos,a),t.uniform3fv(e.uPointLightColor,c)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=Ce(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=Ie(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of ae)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of ae)if(t.setSkyboxImage){await t.setSkyboxImage(this,e);return}}setInteractive(e){this.interactive=e}isInteractive(){return this.interactive}getCameraOrbit(){let e=this.currTheta,t=this.currPhi,r=this.currDistance;return{theta:e,phi:t,radius:r,toString(){return`${e.toFixed(4)}rad ${t.toFixed(4)}rad ${r.toFixed(4)}m`}}}getCameraTarget(){let e=this.customTarget||this.bounds.center;return{x:e[0],y:e[1],z:e[2],toString(){return`${e[0].toFixed(4)}m ${e[1].toFixed(4)}m ${e[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let e=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return e.map((t,r)=>{let i=this.meshes.flatMap(u=>u.primitives.filter(d=>d.materialIndex===r||e.length===1&&d.materialIndex===void 0)),s=i[0],a=s?[...s.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],c=s?s.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,o=s?s.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,l={baseColorFactor:a,metallicFactor:c,roughnessFactor:o,setBaseColorFactor:u=>{let d=[u[0],u[1],u[2],u[3]??1];l.baseColorFactor=d,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=d);for(let f of i)f.baseColor=d;this.render()},setMetallicFactor:u=>{l.metallicFactor=u,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=u);for(let d of i)d.metallic=u;this.render()},setRoughnessFactor:u=>{l.roughnessFactor=u,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=u);for(let d of i)d.roughness=u;this.render()}};return{name:t.name||`Material_${r}`,pbrMetallicRoughness:l}})}playAnimation(e){if(this.animations.length!==0){if(e){let t=this.animations.find(r=>r.name===e);t&&(this.currentClip=t)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(e=>e.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(e){let t=this.applyVariantMaterial(e);return t&&this.gl&&this.render(),t}applyVariantMaterial(e){let t=e===null||e==="",r=-1;if(t)this.activeVariantName=null;else{if(r=this.availableVariants.indexOf(e),r<0)return!1;this.activeVariantName=e}let i=this.gltf?.materials;if(!Array.isArray(i))return t;for(let s of this.meshes)for(let a of s.primitives){let c=a.defaultMaterialIndex;if(!t&&Array.isArray(a.variantMappings)){for(let l of a.variantMappings)if(Array.isArray(l.variants)&&l.variants.includes(r)){c=l.material;break}}let o=c!==void 0?i[c]:void 0;a.materialIndex=o?c:void 0,Object.assign(a,nt(o,this.gpuTextures)),this.applyPrimitiveProgram(a,a.materialIndex,o??null)}return!0}applyPrimitiveProgram(e,t,r){if(!this.gl||!e.primitiveDef)return;e.programCache??(e.programCache=new Map);let i=t??-1,s=e.programCache.get(i);s||(s=et(this.gl,{...e.primitiveDef,material:t},r),e.programCache.set(i,s)),e.customProgram=s.program,e.customUniforms=s.uniforms,e.pluginData&&(e.pluginData.materials=e.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(e){this.autoplay=e,e?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(e){this.animationName=e,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(e)}evaluateAnimation(e){for(let t of ae)if(t.evaluateAnimation){t.evaluateAnimation(this,e);return}}setTarget(e,t,r){this.customTarget=[e,t,r],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(e){let t=Math.max(10,Math.min(90,e));this.fov=t*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(e){if(this.distanceMode=e,!this.customDistance){let t=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=t,this.targetDistance=t,this.currDistance=t,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(e){e.minTheta!==void 0&&(this.minTheta=e.minTheta*Math.PI/180),e.maxTheta!==void 0&&(this.maxTheta=e.maxTheta*Math.PI/180),e.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,e.minPhi*Math.PI/180)),e.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,e.maxPhi*Math.PI/180)),e.minDistance!==void 0&&(this.minDistanceLimit=e.minDistance),e.maxDistance!==void 0&&(this.maxDistanceLimit=e.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){return{minTheta:isFinite(this.minTheta)?this.minTheta*180/Math.PI:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*180/Math.PI:void 0,minPhi:this.minPhi*180/Math.PI,maxPhi:this.maxPhi*180/Math.PI,minDistance:this.minDistanceLimit!==null?this.minDistanceLimit:void 0,maxDistance:this.maxDistanceLimit!==null?this.maxDistanceLimit:void 0}}clampTheta(e){return Math.max(this.minTheta,Math.min(this.maxTheta,e))}clampPhi(e){return Math.max(this.minPhi,Math.min(this.maxPhi,e))}clampDistance(e){let t=this.minDistanceLimit!==null?this.minDistanceLimit:this.bounds?this.bounds.radius*.5:.1,r=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(t,Math.min(r,e))}setCamera(e,t,r,i){e!==void 0&&(this.targetTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.targetPhi=this.clampPhi(t*Math.PI/180)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(r)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/i))}setInitialCamera(e,t,r,i){if(e!==void 0&&(this.initialTheta=this.clampTheta(e*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),t!==void 0&&(this.initialPhi=this.clampPhi(t*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),r!==void 0&&r>0){let s=this.clampDistance(r);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else if(i!==void 0&&i>0){let s=this.clampDistance(this.bounds.radius*2.5/i);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else{this.customDistance=!1;let s=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=s,this.targetDistance=s,this.currDistance=s}this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.initialDistance!==null?this.targetDistance=this.clampDistance(this.initialDistance):this.targetDistance=this.clampDistance(this.bounds.radius*2.5),this.initialCustomTarget?this.customTarget=[...this.initialCustomTarget]:this.customTarget=null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(e,t){let r=re();se(r,this.projMatrix,this.viewMatrix);let[i,s,a]=e,c=t?t[0]:0,o=t?t[1]:0,l=t?t[2]:0,u=this.modelRootMatrix;u&&(i=u[0]*e[0]+u[4]*e[1]+u[8]*e[2]+u[12],s=u[1]*e[0]+u[5]*e[1]+u[9]*e[2]+u[13],a=u[2]*e[0]+u[6]*e[1]+u[10]*e[2]+u[14],t&&(c=u[0]*t[0]+u[4]*t[1]+u[8]*t[2],o=u[1]*t[0]+u[5]*t[1]+u[9]*t[2],l=u[2]*t[0]+u[6]*t[1]+u[10]*t[2]));let d=r[0]*i+r[4]*s+r[8]*a+r[12],f=r[1]*i+r[5]*s+r[9]*a+r[13],T=r[2]*i+r[6]*s+r[10]*a+r[14],p=r[3]*i+r[7]*s+r[11]*a+r[15];if(p<=1e-4)return{x:0,y:0,z:1,visible:!1};let h=d/p,b=f/p,R=T/p,A=this.canvas.getBoundingClientRect(),v=A.width||this.canvas.clientWidth||this.canvas.width||300,D=A.height||this.canvas.clientHeight||this.canvas.height||150,g=(h*.5+.5)*v,P=(-b*.5+.5)*D,E=h>=-1.1&&h<=1.1&&b>=-1.1&&b<=1.1&&R>=-1&&R<=1;if(E&&t){let[y,F,L]=ge(this),C=[i-y,s-F,a-L];c*C[0]+o*C[1]+l*C[2]>.05&&(E=!1)}return{x:g,y:P,z:R,visible:E}}setSelectedMesh(e){this.selectedMeshName=e||""}getSelectedMesh(){return this.selectedMeshName}setupEvents(){let e=this.canvas;this.boundContextMenu=t=>{t.preventDefault()},e.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=t=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.lastPointerX=t.clientX,this.lastPointerY=t.clientY,this.totalDragDist=0,this.activePointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.isPanning=t.button===2||t.shiftKey||this.activePointers.size===2,e.setPointerCapture(t.pointerId))},e.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=t=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=this.activePointers.get(t.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},i=t.clientX-r.x,s=t.clientY-r.y;if(this.activePointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.lastPointerX=t.clientX,this.lastPointerY=t.clientY,this.totalDragDist+=Math.hypot(i,s),this.isPanning||t.button===2||t.shiftKey||this.activePointers.size===2){let a=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],c=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],o=this.customTarget?[...this.customTarget]:[...this.bounds.center],l=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;o[0]+=(-i*a[0]+s*c[0])*l,o[1]+=(-i*a[1]+s*c[1])*l,o[2]+=(-i*a[2]+s*c[2])*l,this.customTarget=o}else this.targetTheta=this.clampTheta(this.targetTheta-i*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=t=>{this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.activePointers.delete(t.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(t.pointerId)}catch{}if(this.totalDragDist<5&&t.button===0){let r=e.getBoundingClientRect(),i=Math.floor((t.clientX-r.left)*(e.width/Math.max(r.width,1))),s=Math.floor((t.clientY-r.top)*(e.height/Math.max(r.height,1)));this.performMeshPick(i,s,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=t=>{if(!this.interactive)return;t.preventDefault(),this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=Math.exp(t.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=t=>{let r=t.detail||{};r.reset?this.resetCamera():this.setCamera(r.theta,r.phi,r.distance,r.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),e.tabIndex!==void 0&&e.tabIndex<0&&(e.tabIndex=0),e.getAttribute?.("role")||e.setAttribute?.("role","region"),e.getAttribute?.("aria-label")||e.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=t=>{if(!this.interactive)return;let r=typeof performance<"u"?performance.now():Date.now();switch(t.key){case"ArrowLeft":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta-.1),t.preventDefault();break;case"ArrowRight":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta+.1),t.preventDefault();break;case"ArrowUp":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi+.08),t.preventDefault();break;case"ArrowDown":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi-.08),t.preventDefault();break;case"+":case"=":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*.9),t.preventDefault();break}case"-":case"_":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*1.1),t.preventDefault();break}case"Home":this.lastInteractionTime=r,this.resetCamera(),t.preventDefault();break}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=this.canvas;this.boundContextLost&&(e.removeEventListener("webglcontextlost",this.boundContextLost),this.boundContextLost=null),this.boundContextRestored&&(e.removeEventListener("webglcontextrestored",this.boundContextRestored),this.boundContextRestored=null),this.boundContextMenu&&(e.removeEventListener("contextmenu",this.boundContextMenu),this.boundContextMenu=null),this.boundPointerDown&&(e.removeEventListener("pointerdown",this.boundPointerDown),this.boundPointerDown=null),this.boundPointerMove&&(e.removeEventListener("pointermove",this.boundPointerMove),this.boundPointerMove=null),this.boundPointerUp&&(e.removeEventListener("pointerup",this.boundPointerUp),this.boundPointerUp=null),this.boundWheel&&(e.removeEventListener("wheel",this.boundWheel),this.boundWheel=null),this.boundKeyDown&&(e.removeEventListener("keydown",this.boundKeyDown),this.boundKeyDown=null),this.boundSetCamera&&(this.container.removeEventListener("setCamera",this.boundSetCamera),this.boundSetCamera=null),this.boundResetCamera&&(this.container.removeEventListener("resetCamera",this.boundResetCamera),this.boundResetCamera=null)}raycastFromScreenPoint(e,t){let r=this.canvas,i=r.getBoundingClientRect(),s=r.width||300,a=r.height||300,c=i.width>0?Math.floor((e-i.left)*(s/i.width)):Math.floor(e),o=i.height>0?Math.floor((t-i.top)*(a/i.height)):Math.floor(t);return this.performMeshPick(c,o,!1)}performMeshPick(e,t,r=!0){if(this.meshes.length===0)return null;let i=this.gl,s=Math.max(1,this.canvas.width||300),a=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,s);let c=re();se(c,this.projMatrix,this.viewMatrix);let o=[],l=Math.max(0,Math.min(s-1,e)),u=Math.max(0,Math.min(a-1,a-1-t));if(this.pickFbo&&i&&!this.xrSessionActive){(this.pickFboWidth!==s||this.pickFboHeight!==a)&&this.resizePickingFbo(s,a),i.bindFramebuffer(36160,this.pickFbo),i.viewport(0,0,s,a),i.enable(2929),i.clearColor(0,0,0,0),i.clear(16384|256),i.useProgram(this.pickProg);for(let E=0;E<this.meshes.length;E++){let y=this.meshes[E];if(y.visible===!1||y.isPluginMesh)continue;let F=E+1,L=(F&255)/255,C=(F>>8&255)/255,m=(F>>16&255)/255;i.uniform4f(this.uPick.uColorId,L,C,m,1),se(this.modelMatrix,this.modelRootMatrix,y.transform);let w=y.instanceMatrices;if(w&&w.length>=16){let S=w.length>>4,M=re();for(let k of y.primitives){i.bindVertexArray(k.vao);for(let _=0;_<S;_++)se(M,this.modelMatrix,w.subarray(_*16,_*16+16)),se(this.mvpMatrix,c,M),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),we(i,k)}}else{se(this.mvpMatrix,c,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let S of y.primitives)i.bindVertexArray(S.vao),we(i,S)}}let g=new Uint8Array(4);i.readPixels(l,u,1,1,6408,5121,g),i.bindFramebuffer(36160,null);let P=g[0]+(g[1]<<8)+(g[2]<<16);P>0&&P<=this.meshes.length&&(o=[this.meshes[P-1]])}o.length===0&&(o=this.meshes.filter(g=>g.visible!==!1));let d=null,f=1/0,T=[0,0,0],p=[0,1,0],[h,b,R]=ge(this),A=re();for(let g of o){se(A,this.modelRootMatrix,g.transform);let P=g.instanceMatrices,E=P&&P.length>=16?P.length>>4:1;for(let y=0;y<E;y++){P&&P.length>=16?se(this.modelMatrix,A,P.subarray(y*16,y*16+16)):this.modelMatrix.set(A),se(this.mvpMatrix,c,this.modelMatrix);let F=re();if(!Ge(F,this.mvpMatrix))continue;let L=(l+.5)/s*2-1,C=(u+.5)/a*2-1,m=[0,0,0],w=[0,0,0];Pe(m,L,C,-1,F),Pe(w,L,C,1,F);let S=w[0]-m[0],M=w[1]-m[1],k=w[2]-m[2],_=Math.hypot(S,M,k)||1,K=S/_,U=M/_,O=k/_,B={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((Y=>{for(let W of g.primitives){if(!W.positions)continue;let j=W.positions,x=W.indices,I=Math.floor(x?x.length/3:j.length/9);for(let N=0;N<I;N++){let z=x?x[N*3]:N*3,ee=x?x[N*3+1]:N*3+1,ie=x?x[N*3+2]:N*3+2;ze(m[0],m[1],m[2],K,U,O,j[z*3],j[z*3+1],j[z*3+2],j[ee*3],j[ee*3+1],j[ee*3+2],j[ie*3],j[ie*3+1],j[ie*3+2],B,Y)}}})(1e-4),isFinite(B.distance)){let Y=B.point[0],W=B.point[1],j=B.point[2],x=this.modelMatrix,I=x[0]*Y+x[4]*W+x[8]*j+x[12],N=x[1]*Y+x[5]*W+x[9]*j+x[13],z=x[2]*Y+x[6]*W+x[10]*j+x[14],ee=I-h,ie=N-b,oe=z-R,H=Math.hypot(ee,ie,oe);if(H<f){me(this.normalMatrix,this.modelMatrix);let $=this.normalMatrix,G=B.normal[0],te=B.normal[1],V=B.normal[2],J=$[0]*G+$[3]*te+$[6]*V,Q=$[1]*G+$[4]*te+$[7]*V,Z=$[2]*G+$[5]*te+$[8]*V,ne=Math.hypot(J,Q,Z)||1;J/=ne,Q/=ne,Z/=ne,J*ee+Q*ie+Z*oe>0&&(J=-J,Q=-Q,Z=-Z),d=g,f=Math.round(H*1e3)/1e3,T=[Math.round(I*1e3)/1e3,Math.round(N*1e3)/1e3,Math.round(z*1e3)/1e3],p=[Math.round(J*1e3)/1e3,Math.round(Q*1e3)/1e3,Math.round(Z*1e3)/1e3]}}}}if(!d)return null;let D={meshIndex:this.meshes.indexOf(d),meshName:d.name,nodeIndex:d.nodeIndex,distance:f,hitPoint:T,normal:p,screenX:e,screenY:t};if(r){for(let g of ae)g.onMeshSelect?.(this,D);this.opts.onMeshClick&&this.opts.onMeshClick(D),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:D}))}return D}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let r=Math.max(1,Math.floor(t*.5)),i=e>=r,s=i?e-r:e,a=i?Math.max(1,t-r):r,c=(s+.5)/a*2-1;return Math.floor((c*.5+1)*.5*t)}setStereoSBS(e){this.stereoSBS=!!e,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let e=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),t=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);ve(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center;Me(this.viewMatrix,ge(this),r,[0,1,0]),se(this.mvpMatrix,this.projMatrix,this.viewMatrix),me(this.normalMatrix,this.modelMatrix)}resize(){let e=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),t=this.canvas.getBoundingClientRect(),r=Math.max(1,Math.floor(t.width*e)),i=Math.max(1,Math.floor(t.height*e));this.canvas.width!==r||this.canvas.height!==i?(this.canvas.width=r,this.canvas.height=i,this.resizePickingFbo(r,i),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(e){let t=this.xrSessionActive;if(this.xrSessionActive=e,t&&!e){this.xrDepthState.enabled=!1;for(let r of ae)r.onXRSessionEnd?.(this);if(this.lastTime=typeof performance<"u"?performance.now():Date.now(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(r){this.reportRenderError(r)}}}reportRenderError(e){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",e))}stepXRUpdate(e){for(let t of ae)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let e=t=>{if(this.animFrameId===null)return;let r=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(r),this.render()}catch(i){this.reportRenderError(i)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(e))};this.animFrameId=requestAnimationFrame(e)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(e){this.autoRotate=e}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(e){this.autoRotateSpeed=e}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(e){this.autoRotateDelay=Math.max(0,Number(e)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(e=0){this.turntableRotation=Number(e)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let e=Math.cos(this.turntableRotation),t=Math.sin(this.turntableRotation),r=this.bounds.center[0],i=this.bounds.center[2],s=this.modelRootMatrix;s[0]=e,s[1]=0,s[2]=-t,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=t,s[9]=0,s[10]=e,s[11]=0,s[12]=r-(e*r+t*i),s[13]=0,s[14]=i-(-t*r+e*i),s[15]=1}setVisible(e){this.isVisible=e}update(e){for(let a of ae)a.onUpdate?.(this,e);let t=typeof performance<"u"?performance.now():Date.now();if(!this.isPointerDown&&this.autoRotate&&t-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*e,this.updateTurntableMatrix();for(let a of ae)a.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let r=Math.round((this.currTheta*180/Math.PI%360+360)%360),i=Math.round(this.currPhi*180/Math.PI),s=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(r-this.lastReportedTheta)>=1||Math.abs(i-this.lastReportedPhi)>=1||Math.abs(s-this.lastReportedZoom)>=.02){this.lastReportedTheta=r,this.lastReportedPhi=i,this.lastReportedZoom=s;let a={theta:r,phi:i,zoom:s,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(a),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:a}))}}renderXRView(e,t,r,i,s=!0,a=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let c=e?.transform?.inverse?.matrix||this.viewMatrix,o=e?.projectionMatrix||this.projMatrix,l=e?.transform?.position,u=l?[l.x,l.y,l.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):r&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:c,projMatrix:o,eyePos:u,viewport:i,eye:e?.eye||"none",clear:a>0?!1:e?.eye!=="right",isAR:s})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let v=Math.max(2,this.canvas.width||2),D=Math.max(1,this.canvas.height||1),g=Math.max(1,Math.floor(v*.5)),P=Math.max(1,v-g),E=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),y=this.customTarget||this.bounds.center,[F,L,C]=ge(this),m=Math.cos(this.currTheta),w=-Math.sin(this.currTheta),S=.032,M=re(),k=re(),_=[F-m*S,L,C-w*S],K=[y[0]-m*S*.25,y[1],y[2]-w*S*.25];ve(M,this.fov,g/D,.1,E),Me(k,_,K,[0,1,0]);let U=re(),O=re(),B=[F+m*S,L,C+w*S],q=[y[0]+m*S*.25,y[1],y[2]+w*S*.25];ve(U,this.fov,P/D,.1,E),Me(O,B,q,[0,1,0]),this.render({viewMatrix:k,projMatrix:M,eyePos:_,viewport:[0,0,g,D],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:O,projMatrix:U,eyePos:B,viewport:[g,0,P,D],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,v,D);return}let t=this.gl,r=0,i=0,s=this.canvas.width,a=this.canvas.height;e?.viewport?(r=e.viewport[0],i=e.viewport[1],s=e.viewport[2],a=e.viewport[3],t.viewport(r,i,s,a)):t.viewport(0,0,this.canvas.width,this.canvas.height),t.enable(2929),(!e||e.clear!==!1)&&(e?.isAR?t.clearColor(0,0,0,0):t.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),t.clear(16384|256));let c=re(),o=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=o,se(c,e?.projMatrix??this.projMatrix,o);let l=he().xrDepthShader,u=xt(this.toneMapping),[d,f,T]=e?e.eyePos:ge(this);for(let v of ae)v.onBeforeDrawScene?.(this,t,c,[d,f,T],u);let p=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&p===0)return;let h=e?.eye||"none",b=!1,R=p>0?[...this.backdropMeshes,...this.meshes]:this.meshes,A=v=>{for(let D=0;D<R.length;D++){let g=R[D];if(g.visible===!1)continue;let P=this.selectedMeshName!==""&&g.name===this.selectedMeshName;D<p||g.worldSpace===!0||g.name==="__xr_reticle__"?this.modelMatrix.set(g.transform):se(this.modelMatrix,this.modelRootMatrix,g.transform),se(this.mvpMatrix,c,this.modelMatrix),me(g.normalMatrix,this.modelMatrix);let E=g.extras?.xr?.stereo||g.userData?.xr?.stereo,y=0,F=0,L=1,C=1;E==="sbs"?(L=.5,y=h==="right"?.5:0):E==="ou"&&(C=.5,F=h==="right"?.5:0);for(let m of g.primitives){let w=!!m.isTransmissive;if(!v&&w){b=!0;continue}if(v&&!w)continue;let S=m.customProgram||this.renderProg,M=m.customUniforms||this.uRender;t.useProgram(S),t.uniform1i(M.uToneMapping,u),t.uniform1f(M.uEnvIntensity,this.envIntensity),M.uExposure&&t.uniform1f(M.uExposure,this.exposure),t.uniform3f(M.uCameraPos,d,f,T),t.uniform1f(M.uEmissive,P?1:0),t.uniformMatrix4fv(M.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(M.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(M.uNormalMatrix,!1,g.normalMatrix),M.uUvTransform&&t.uniform4f(M.uUvTransform,y,F,L,C),M.uViewportSize&&t.uniform2f(M.uViewportSize,Math.max(1,s),Math.max(1,a)),l?.bind(t,M,this.xrDepthState,o,[r,i,Math.max(1,s),Math.max(1,a)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(M.uEnvironmentMap,4),t.uniform1i(M.uHasEnvironmentMap,1)):t.uniform1i(M.uHasEnvironmentMap,0),this.bindLights(M),M.uSectionEnabled&&t.uniform1i(M.uSectionEnabled,0);for(let _ of ae)_.onBeforeDrawPrimitive?.(t,S,m,g,this.worldMatrices||[],this.gltf);t.uniform4fv(M.uBaseColor,m.baseColor),t.uniform1f(M.uMetallic,m.metallic),t.uniform1f(M.uRoughness,m.roughness),M.uClearcoat&&t.uniform2f(M.uClearcoat,m.clearcoat??0,m.clearcoatRoughness??.04),m.texture?(t.activeTexture(33984),t.bindTexture(3553,m.texture),t.uniform1i(M.uBaseColorTexture,0),t.uniform1i(M.uHasTexture,1)):t.uniform1i(M.uHasTexture,0),m.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,m.metallicRoughnessTexture),t.uniform1i(M.uMetallicRoughnessTexture,1),t.uniform1i(M.uHasMetallicRoughnessTexture,1)):t.uniform1i(M.uHasMetallicRoughnessTexture,0),m.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,m.normalTexture),t.uniform1i(M.uNormalTexture,2),t.uniform1i(M.uHasNormalTexture,1),t.uniform1f(M.uNormalScale,m.normalScale)):t.uniform1i(M.uHasNormalTexture,0),m.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,m.occlusionTexture),t.uniform1i(M.uOcclusionTexture,3),t.uniform1i(M.uHasOcclusionTexture,1),t.uniform1f(M.uOcclusionStrength,m.occlusionStrength)):t.uniform1i(M.uHasOcclusionTexture,0),t.bindVertexArray(m.vao);let k=g.instanceMatrices;if(k&&k.length>=16&&m.instanced&&M.uInstanced&&M.uViewProj){let _=k.length>>4;t.uniform1i(M.uInstanced,1),t.uniformMatrix4fv(M.uViewProj,!1,c),m.indices?t.drawElementsInstanced(4,m.indexCount,m.indexType,0,_):t.drawArraysInstanced(4,0,m.indexCount,_),t.uniform1i(M.uInstanced,0)}else if(k&&k.length>=16){let _=k.length>>4,K=g.instanceColors,U=re(),O=new Float32Array(9),B=[m.baseColor[0],m.baseColor[1],m.baseColor[2],m.baseColor[3]];for(let q=0;q<_;q++)se(U,this.modelMatrix,k.subarray(q*16,q*16+16)),se(this.mvpMatrix,c,U),me(O,U),t.uniformMatrix4fv(M.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(M.uModel,!1,U),t.uniformMatrix3fv(M.uNormalMatrix,!1,O),K&&(B[0]=m.baseColor[0]*K[q*3],B[1]=m.baseColor[1]*K[q*3+1],B[2]=m.baseColor[2]*K[q*3+2],B[3]=m.baseColor[3],t.uniform4fv(M.uBaseColor,B)),we(t,m)}else we(t,m)}}};if(A(!1),b){for(let v of ae)v.onBeforeTransmissivePass?.(t,this);A(!0)}for(let v of ae)v.onAfterRender?.(t,this,c)}disposeMeshListGpuResources(e,t){rt(this.gl,e,t)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let e=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let t of ae)t.onDestroy?.(e,this);this.environmentTexture&&(e.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&e.deleteProgram(this.renderProg),this.pickProg&&e.deleteProgram(this.pickProg),this.pickFbo&&e.deleteFramebuffer(this.pickFbo),this.pickTexture&&e.deleteTexture(this.pickTexture),this.pickDepth&&e.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};Re.registerPlugin=He,Re.getRegisteredPlugins=We;function Be(n){return new TextEncoder().encode(n)}function Dt(n,e){n.updateMatrixWorld(!0);let t=[];return n.traverse(r=>{if(r.geometry){let i=r.geometry,s=i.attributes.position;if(!s||s.count===0)return;let a=s.count,c=new Float32Array(a*3),o=r.matrixWorld.elements;for(let y=0;y<a;y++){let F=s.getX(y),L=s.getY(y),C=s.getZ(y);c[y*3]=o[0]*F+o[4]*L+o[8]*C+o[12],c[y*3+1]=o[1]*F+o[5]*L+o[9]*C+o[13],c[y*3+2]=o[2]*F+o[6]*L+o[10]*C+o[14]}let l;if(i.attributes.normal){let y=i.attributes.normal;l=new Float32Array(a*3);let F=new Float32Array(9);me(F,o);for(let L=0;L<a;L++){let C=y.getX(L),m=y.getY(L),w=y.getZ(L),S=F[0]*C+F[3]*m+F[6]*w,M=F[1]*C+F[4]*m+F[7]*w,k=F[2]*C+F[5]*m+F[8]*w,_=Math.hypot(S,M,k)||1;l[L*3]=S/_,l[L*3+1]=M/_,l[L*3+2]=k/_}}let u;if(i.attributes.uv){let y=i.attributes.uv;u=new Float32Array(a*2);for(let F=0;F<a;F++)u[F*2]=y.getX(F),u[F*2+1]=y.getY(F)}let d;if(i.index)d=i.index.array;else{d=a>65535?new Uint32Array(a):new Uint16Array(a);for(let y=0;y<a;y++)d[y]=y}let f="DefaultMaterial",T=[.8,.8,.8],p=.5,h=.1,b=0,R=0,A=1.5,v=1,D=[0,0,0];if(r.material){let y=r.material;f=y.name||`Material_${t.length}`,y.color&&(T=[y.color.r,y.color.g,y.color.b]),typeof y.roughness=="number"&&(p=y.roughness),typeof y.metalness=="number"&&(h=y.metalness),typeof y.clearcoat=="number"&&(b=y.clearcoat),typeof y.clearcoatRoughness=="number"&&(R=y.clearcoatRoughness),typeof y.ior=="number"&&(A=y.ior);let F=typeof y.opacity=="number"?y.opacity:1,L=typeof y.transmission=="number"?y.transmission:0;if(v=F*(1-L),y.emissive&&(y.emissive.r>0||y.emissive.g>0||y.emissive.b>0)){let C=y.emissiveIntensity??1;D=[y.emissive.r*C,y.emissive.g*C,y.emissive.b*C]}}let g,P=e?.animateCallback||e?.animateFn||(typeof n.userData?.animate=="function"?n.userData.animate:typeof n.__animateFn=="function"?n.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0);if(typeof P=="function"){let y=e?.duration??4,F=e?.fps??4,L=Math.max(2,Math.round(y*F)+1),C=[],m=[],w=[],S=[],M=[r.position.x,r.position.y,r.position.z],k=[r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w],_=[r.scale.x,r.scale.y,r.scale.z],K=!1;for(let U=0;U<L;U++){let O=U/(L-1)*y;C.push(O);try{P(O)}catch{}m.push([r.position.x,r.position.y,r.position.z]),w.push([r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w]),S.push([r.scale.x,r.scale.y,r.scale.z]),(Math.abs(r.position.x-M[0])>1e-4||Math.abs(r.position.y-M[1])>1e-4||Math.abs(r.position.z-M[2])>1e-4||Math.abs(r.quaternion.x-k[0])>1e-4||Math.abs(r.quaternion.y-k[1])>1e-4||Math.abs(r.quaternion.z-k[2])>1e-4||Math.abs(r.quaternion.w-k[3])>1e-4||Math.abs(r.scale.x-_[0])>1e-4)&&(K=!0)}r.position.set(M[0],M[1],M[2]),r.quaternion.set(k[0],k[1],k[2],k[3]),r.scale.set(_[0],_[1],_[2]),K&&(g={times:C,translations:m,rotations:w,scales:S})}let E=r;if(E.isInstancedMesh&&typeof E.count=="number"&&E.count>0&&E.instanceMatrix?.array){let y=Math.min(1e3,Math.floor(E.count)),F=E.instanceMatrix.array,L=E.instanceColor?.array,C=r.name||`Mesh_${t.length}`,m=new Float32Array(16),w=new Float32Array(9);for(let S=0;S<y;S++){let M=F.subarray(S*16,(S+1)*16);se(m,o,M);let k=new Float32Array(a*3);for(let O=0;O<a;O++){let B=s.getX(O),q=s.getY(O),Y=s.getZ(O);k[O*3]=m[0]*B+m[4]*q+m[8]*Y+m[12],k[O*3+1]=m[1]*B+m[5]*q+m[9]*Y+m[13],k[O*3+2]=m[2]*B+m[6]*q+m[10]*Y+m[14]}let _;if(i.attributes.normal){let O=i.attributes.normal;_=new Float32Array(a*3),me(w,m);for(let B=0;B<a;B++){let q=O.getX(B),Y=O.getY(B),W=O.getZ(B),j=w[0]*q+w[3]*Y+w[6]*W,x=w[1]*q+w[4]*Y+w[7]*W,I=w[2]*q+w[5]*Y+w[8]*W,N=Math.hypot(j,x,I)||1;_[B*3]=j/N,_[B*3+1]=x/N,_[B*3+2]=I/N}}let K=T,U=f;L&&L.length>=(S+1)*3&&(K=[T[0]*L[S*3],T[1]*L[S*3+1],T[2]*L[S*3+2]],U=`${f}_inst_${S}`),t.push({name:`${C}_${S}`,positions:k,indices:d,normals:_,uvs:u,materialName:U,color:K,roughness:p,metallic:h,clearcoat:b,clearcoatRoughness:R,ior:A,opacity:v,emissiveColor:D,xrTraits:r.userData?.xr})}return}t.push({name:r.name||`Mesh_${t.length}`,positions:c,indices:d,normals:l,uvs:u,materialName:f,color:T,roughness:p,metallic:h,clearcoat:b,clearcoatRoughness:R,ior:A,opacity:v,emissiveColor:D,xrTraits:r.userData?.xr,timeSamples:g})}}),t}function at(n){let e=[],t=n.gltf,r=he().decoders.get("meshopt");r&&typeof r.decodeBufferViews=="function"&&r.decodeBufferViews(t,n);let i=n.bin,s=i instanceof ArrayBuffer?i:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),a=t.accessors||[],c=t.bufferViews||[],o=t.materials||[],l=t.meshes||[],u=t.nodes||[];function d(p){let h=a[p];if(!h)throw new Error(`Accessor ${p} not found`);let b=c[h.bufferView||0],R=(b.byteOffset||0)+(h.byteOffset||0),A=b.byteLength||0,v=s.slice(R,R+A);return{acc:h,buffer:v}}let f=new Map;if(u.length>0){let p=Te(t);for(let h=0;h<p.length;h++)f.set(h,p[h])}function T(p,h,b,R){let A=l[p];if(!A)return;let v=new Float32Array(9);me(v,h);for(let D=0;D<(A.primitives||[]).length;D++){let g=A.primitives[D],P=g.attributes?.POSITION;if(P===void 0)continue;let{acc:E,buffer:y}=d(P),F=new Float32Array(y,0,E.count*3),L=new Float32Array(F.length);for(let x=0;x<E.count;x++){let I=F[x*3],N=F[x*3+1],z=F[x*3+2];L[x*3]=h[0]*I+h[4]*N+h[8]*z+h[12],L[x*3+1]=h[1]*I+h[5]*N+h[9]*z+h[13],L[x*3+2]=h[2]*I+h[6]*N+h[10]*z+h[14]}let C,m=g.attributes?.NORMAL;if(m!==void 0){let{acc:x,buffer:I}=d(m),N=new Float32Array(I,0,x.count*3);C=new Float32Array(N.length);for(let z=0;z<x.count;z++){let ee=N[z*3],ie=N[z*3+1],oe=N[z*3+2],H=v[0]*ee+v[3]*ie+v[6]*oe,$=v[1]*ee+v[4]*ie+v[7]*oe,G=v[2]*ee+v[5]*ie+v[8]*oe,te=Math.hypot(H,$,G)||1;C[z*3]=H/te,C[z*3+1]=$/te,C[z*3+2]=G/te}}let w,S=g.attributes?.TEXCOORD_0;if(S!==void 0){let{acc:x,buffer:I}=d(S);w=new Float32Array(I,0,x.count*2)}let M;if(g.indices!==void 0){let{acc:x,buffer:I}=d(g.indices);x.componentType===5125?M=new Uint32Array(I,0,x.count):M=new Uint16Array(I,0,x.count);let N=E.count;for(let z of M)if(z>=N)throw new Error(`SecurityError: Index buffer value (${z}) out of vertex bounds [0, ${N}).`)}else{let x=E.count;M=x>65535?new Uint32Array(x):new Uint16Array(x);for(let I=0;I<x;I++)M[I]=I}let k="DefaultMaterial",_=[.8,.8,.8],K=.5,U=.1,O=0,B=0,q=1.5,Y=1,W=[0,0,0];if(g.material!==void 0&&o[g.material]){let x=o[g.material];k=x.name||`Material_${g.material}`;let I=x.pbrMetallicRoughness||{},N=1;Array.isArray(I.baseColorFactor)&&(_=[I.baseColorFactor[0],I.baseColorFactor[1],I.baseColorFactor[2]],typeof I.baseColorFactor[3]=="number"&&(N=I.baseColorFactor[3])),typeof I.roughnessFactor=="number"&&(K=I.roughnessFactor),typeof I.metallicFactor=="number"&&(U=I.metallicFactor),Array.isArray(x.emissiveFactor)&&x.emissiveFactor.length>=3&&(W=[x.emissiveFactor[0],x.emissiveFactor[1],x.emissiveFactor[2]]);let z=x.extensions||{};z.KHR_materials_clearcoat&&(O=z.KHR_materials_clearcoat.clearcoatFactor??0,B=z.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),z.KHR_materials_ior&&typeof z.KHR_materials_ior.ior=="number"&&(q=z.KHR_materials_ior.ior);let ee=z.KHR_materials_transmission?.transmissionFactor??0;Y=N*(1-ee)}let j=(A.primitives||[]).length>1?`${b}_p${D}`:b;e.push({name:j,positions:L,indices:M,normals:C,uvs:w,materialName:k,color:_,roughness:K,metallic:U,clearcoat:O,clearcoatRoughness:B,ior:q,opacity:Y,emissiveColor:W,xrTraits:R?.xr||A.extras?.xr})}}if(u.length>0)for(let p=0;p<u.length;p++){let h=u[p];if(h.mesh!==void 0&&h.mesh<l.length){let b=f.get(p)||re(),R=h.name||l[h.mesh].name||`Node_${p}`,A=h.extensions?.EXT_mesh_gpu_instancing?.attributes;if(A&&typeof A=="object"){let v=A.TRANSLATION,D=A.ROTATION,g=A.SCALE,P=v!==void 0?(()=>{let{acc:L,buffer:C}=d(v);return new Float32Array(C,0,L.count*3)})():null,E=D!==void 0?(()=>{let{acc:L,buffer:C}=d(D);return new Float32Array(C,0,L.count*4)})():null,y=g!==void 0?(()=>{let{acc:L,buffer:C}=d(g);return new Float32Array(C,0,L.count*3)})():null,F=Math.min(1e3,P?P.length/3:E?E.length/4:y?y.length/3:0);if(F>0){let L=new Float32Array(16),C=new Float32Array(16);for(let m=0;m<F;m++){let w=P?[P[m*3],P[m*3+1],P[m*3+2]]:[0,0,0],S=E?[E[m*4],E[m*4+1],E[m*4+2],E[m*4+3]]:[0,0,0,1],M=y?[y[m*3],y[m*3+1],y[m*3+2]]:[1,1,1];ye(L,S,w,M),se(C,b,L),T(h.mesh,C,`${R}_${m}`,h.extras)}continue}}T(h.mesh,b,R,h.extras)}}else{let p=re();for(let h=0;h<l.length;h++){let b=l[h].name||`Mesh_${h}`;T(h,p,b,l[h].extras)}}return e}function Ue(n,e){if(!n||typeof n!="string")return e;let t=n.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(t)&&(t="_"+t),t||e}function it(n){return String(n??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function X(n){if(!Number.isFinite(n)||Math.abs(n)<1e-7)return"0";let e=Number(n.toFixed(5)).toString();return e.indexOf(".")===-1?`${e}.0`:e}function st(n){let e=n.length/3,t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${X(n[r*3])}, ${X(n[r*3+1])}, ${X(n[r*3+2])})`;return t.join(", ")}function Ft(n,e){let t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${X(n[r*2])}, ${X(1-n[r*2+1])})`;return t.join(", ")}function Ct(n){return Array.from(n).join(", ")}function ke(n){let e=new Map;for(let o of n){let l=Ue(o.materialName,"DefaultMaterial");e.has(l)||e.set(l,{color:o.color||[.8,.8,.8],roughness:o.roughness??.5,metallic:o.metallic??0,clearcoat:o.clearcoat??0,clearcoatRoughness:o.clearcoatRoughness??0,ior:o.ior??1.5,opacity:o.opacity??1,emissiveColor:o.emissiveColor||[0,0,0]})}let t=0,r=null;for(let o of n){if(o.timeSamples&&o.timeSamples.times.length>0){let l=o.timeSamples.times[o.timeSamples.times.length-1];l>t&&(t=l)}o.xrTraits?.anchor&&!r&&(r=o.xrTraits.anchor==="vertical"||o.xrTraits.anchor==="wall"?"vertical":"horizontal")}let i="";t>0&&(i=`startTimeCode = 0
|
|
251
|
+
endTimeCode = ${X(t)}
|
|
210
252
|
timeCodesPerSecond = 1.0
|
|
211
|
-
`);let s="";
|
|
212
|
-
uniform token preliminary:planeAnchoring:alignment = "${
|
|
213
|
-
`);let
|
|
253
|
+
`);let s="";r&&(s=`uniform token preliminary:anchoring:type = "plane"
|
|
254
|
+
uniform token preliminary:planeAnchoring:alignment = "${r}"
|
|
255
|
+
`);let a=`#usda 1.0
|
|
214
256
|
(
|
|
215
257
|
defaultPrim = "Root"
|
|
216
258
|
metersPerUnit = 1.0
|
|
217
259
|
upAxis = "Y"
|
|
218
|
-
${
|
|
260
|
+
${i})
|
|
219
261
|
|
|
220
262
|
def Xform "Root" (
|
|
221
263
|
kind = "component"
|
|
@@ -223,55 +265,55 @@ kind = "component"
|
|
|
223
265
|
{
|
|
224
266
|
${s}def Scope "Materials"
|
|
225
267
|
{
|
|
226
|
-
`;for(let[
|
|
227
|
-
`,b+=`float inputs:clearcoatRoughness = ${
|
|
228
|
-
`),
|
|
229
|
-
`),
|
|
230
|
-
`),(
|
|
231
|
-
`),
|
|
268
|
+
`;for(let[o,l]of e.entries()){let[u,d,f]=l.color,[T,p,h]=l.emissiveColor,b="";l.clearcoat>0&&(b+=`float inputs:clearcoat = ${X(l.clearcoat)}
|
|
269
|
+
`,b+=`float inputs:clearcoatRoughness = ${X(l.clearcoatRoughness)}
|
|
270
|
+
`),l.ior!==1.5&&(b+=`float inputs:ior = ${X(l.ior)}
|
|
271
|
+
`),l.opacity<1&&(b+=`float inputs:opacity = ${X(l.opacity)}
|
|
272
|
+
`),(T>0||p>0||h>0)&&(b+=`color3f inputs:emissiveColor = (${X(T)}, ${X(p)}, ${X(h)})
|
|
273
|
+
`),a+=`def Material "${o}"
|
|
232
274
|
{
|
|
233
275
|
def Shader "PBRShader"
|
|
234
276
|
{
|
|
235
277
|
uniform token info:id = "UsdPreviewSurface"
|
|
236
|
-
color3f inputs:diffuseColor = (${
|
|
237
|
-
float inputs:metallic = ${
|
|
238
|
-
float inputs:roughness = ${
|
|
278
|
+
color3f inputs:diffuseColor = (${X(u)}, ${X(d)}, ${X(f)})
|
|
279
|
+
float inputs:metallic = ${X(l.metallic)}
|
|
280
|
+
float inputs:roughness = ${X(l.roughness)}
|
|
239
281
|
${b}token outputs:surface
|
|
240
282
|
}
|
|
241
|
-
token outputs:surface.connect = </Root/Materials/${
|
|
283
|
+
token outputs:surface.connect = </Root/Materials/${o}/PBRShader.outputs:surface>
|
|
242
284
|
}
|
|
243
|
-
`}
|
|
285
|
+
`}a+=`}
|
|
244
286
|
def Scope "Meshes"
|
|
245
287
|
{
|
|
246
|
-
`;let
|
|
288
|
+
`;let c=new Set;for(let o=0;o<n.length;o++){let l=n[o],u=l.positions.length/3,d=1/0,f=1/0,T=1/0,p=-1/0,h=-1/0,b=-1/0;for(let E=0;E<u;E++){let y=l.positions[E*3],F=l.positions[E*3+1],L=l.positions[E*3+2];y<d&&(d=y),y>p&&(p=y),F<f&&(f=F),F>h&&(h=F),L<T&&(T=L),L>b&&(b=L)}isFinite(d)||(d=f=T=-1,p=h=b=1);let R=Math.floor(l.indices.length/3),A=Ue(l.materialName,"DefaultMaterial"),v=Ue(l.name,`Mesh_${o}`);c.has(v)&&(v=`${v}_${o}`),c.add(v);let D=R>0?R===1?"3":"3, ".repeat(R-1)+"3":"",g=l.xrTraits,P="";if(g){let E=[];g.physics&&g.physics!=="none"&&E.push('prepend apiSchemas = ["PhysicsBodyAPI", "PhysicsCollisionAPI"]');let y=he().xrTraitSerializer?.usdLines(g,it)??[];if(!y.length)for(let F of["grab","billboard","follow","anchor","physics"]){let L=F==="follow"&&typeof g.follow=="object"?g.follow.mode??"head":g[F];L!==void 0&&y.push(`string ${F} = "${it(L)}"`)}y.length>0&&E.push(`customData = {
|
|
247
289
|
dictionary xr = {
|
|
248
|
-
${
|
|
290
|
+
${y.join(`
|
|
249
291
|
`)}
|
|
250
292
|
}
|
|
251
|
-
}`),
|
|
252
|
-
${
|
|
293
|
+
}`),E.length>0&&(P=` (
|
|
294
|
+
${E.join(`
|
|
253
295
|
`)}
|
|
254
|
-
)`)}if(
|
|
296
|
+
)`)}if(a+=`def Mesh "${v}"${P}
|
|
255
297
|
{
|
|
256
|
-
`,g?.physics&&g.physics!=="none"){let
|
|
257
|
-
bool physics:kinematicEnabled = ${
|
|
298
|
+
`,g?.physics&&g.physics!=="none"){let E=g.physics==="static"?"true":"false";a+=`bool physics:rigidBodyEnabled = true
|
|
299
|
+
bool physics:kinematicEnabled = ${E}
|
|
258
300
|
bool physics:collisionEnabled = true
|
|
259
|
-
`}if(
|
|
260
|
-
quatf xformOp:orient.timeSamples = { ${
|
|
261
|
-
double3 xformOp:scale.timeSamples = { ${
|
|
301
|
+
`}if(l.timeSamples&&l.timeSamples.times.length>0){let E=l.timeSamples,y=E.times.map((C,m)=>{let w=E.translations?.[m]||[0,0,0];return`${X(C)}: (${X(w[0])}, ${X(w[1])}, ${X(w[2])})`}).join(", "),F=E.times.map((C,m)=>{let w=E.rotations?.[m]||[0,0,0,1];return`${X(C)}: (${X(w[3])}, ${X(w[0])}, ${X(w[1])}, ${X(w[2])})`}).join(", "),L=E.times.map((C,m)=>{let w=E.scales?.[m]||[1,1,1];return`${X(C)}: (${X(w[0])}, ${X(w[1])}, ${X(w[2])})`}).join(", ");a+=`double3 xformOp:translate.timeSamples = { ${y} }
|
|
302
|
+
quatf xformOp:orient.timeSamples = { ${F} }
|
|
303
|
+
double3 xformOp:scale.timeSamples = { ${L} }
|
|
262
304
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:orient", "xformOp:scale"]
|
|
263
|
-
`}
|
|
264
|
-
int[] faceVertexCounts = [${
|
|
265
|
-
int[] faceVertexIndices = [${
|
|
266
|
-
point3f[] points = [${
|
|
267
|
-
`,
|
|
305
|
+
`}a+=`float3[] extent = [(${X(d)}, ${X(f)}, ${X(T)}), (${X(p)}, ${X(h)}, ${X(b)})]
|
|
306
|
+
int[] faceVertexCounts = [${D}]
|
|
307
|
+
int[] faceVertexIndices = [${Ct(l.indices)}]
|
|
308
|
+
point3f[] points = [${st(l.positions)}]
|
|
309
|
+
`,l.normals&&l.normals.length===l.positions.length&&(a+=`normal3f[] normals = [${st(l.normals)}] (
|
|
268
310
|
interpolation = "vertex"
|
|
269
311
|
)
|
|
270
|
-
`),
|
|
312
|
+
`),l.uvs&&l.uvs.length===u*2&&(a+=`texCoord2f[] primvars:st = [${Ft(l.uvs,u)}] (
|
|
271
313
|
interpolation = "vertex"
|
|
272
314
|
)
|
|
273
|
-
`),
|
|
315
|
+
`),a+=`rel material:binding = </Root/Materials/${A}>
|
|
274
316
|
}
|
|
275
|
-
`}return
|
|
317
|
+
`}return a+=`}
|
|
276
318
|
}
|
|
277
|
-
`,c}function et(n,e){if(n&&typeof n.traverse=="function"){let r=gt(n,e);return _e(r)}let t=ge(n),i=Je(t);return _e(i)}var Se=null;function tt(n){if(!Se){Se=new Uint32Array(256);for(let t=0;t<256;t++){let i=t;for(let r=0;r<8;r++)i=i&1?3988292384^i>>>1:i>>>1;Se[t]=i}}let e=4294967295;for(let t=0;t<n.length;t++)e=Se[(e^n[t])&255]^e>>>8;return(e^4294967295)>>>0}function Be(n){let e=[],t=0,i=[];for(let o of n){let f=Ue(o.filename),d=tt(o.data),p=o.data.length,m=30+f.length,x=t+m,b=0,E=x%64;E!==0&&(b=64-E);let P=new Uint8Array(m+b),A=new DataView(P.buffer);A.setUint32(0,67324752,!0),A.setUint16(4,20,!0),A.setUint16(6,0,!0),A.setUint16(8,0,!0),A.setUint16(10,0,!0),A.setUint16(12,0,!0),A.setUint32(14,d,!0),A.setUint32(18,p,!0),A.setUint32(22,p,!0),A.setUint16(26,f.length,!0),A.setUint16(28,b,!0),P.set(f,30),b>0&&P.fill(0,30+f.length),e.push({offset:t,size:p,crc:d,filenameBytes:f,entry:o}),i.push(P),i.push(o.data),t+=P.length+o.data.length}let r=t;for(let o of e){let f=new Uint8Array(46+o.filenameBytes.length),d=new DataView(f.buffer);d.setUint32(0,33639248,!0),d.setUint16(4,20,!0),d.setUint16(6,20,!0),d.setUint16(8,0,!0),d.setUint16(10,0,!0),d.setUint16(12,0,!0),d.setUint16(14,0,!0),d.setUint32(16,o.crc,!0),d.setUint32(20,o.size,!0),d.setUint32(24,o.size,!0),d.setUint16(28,o.filenameBytes.length,!0),d.setUint16(30,0,!0),d.setUint16(32,0,!0),d.setUint16(34,0,!0),d.setUint16(36,0,!0),d.setUint32(38,0,!0),d.setUint32(42,o.offset,!0),f.set(o.filenameBytes,46),i.push(f),t+=f.length}let s=t-r,c=new Uint8Array(22),l=new DataView(c.buffer);l.setUint32(0,101010256,!0),l.setUint16(4,0,!0),l.setUint16(6,0,!0),l.setUint16(8,e.length,!0),l.setUint16(10,e.length,!0),l.setUint32(12,s,!0),l.setUint32(16,r,!0),l.setUint16(20,0,!0),i.push(c),t+=22;let u=new Uint8Array(t),a=0;for(let o of i)u.set(o,a),a+=o.length;return u}function Mt(n){let e=et(n),t=Ue(e);return Be([{filename:"model.usda",data:t}])}function nt(n){let e=ge(n),t=Je(e),i=_e(t),r=Ue(i);return Be([{filename:"model.usda",data:r}])}function it(n){return n&&typeof n.toUSDZ=="function"?n.toUSDZ():n&&typeof n.traverse=="function"?Mt(n):nt(n)}function rt(n){let e=it(n);return new Blob([e],{type:"model/vnd.usdz+zip"})}function ot(){if(typeof window>"u"||typeof navigator>"u")return!1;let n=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(n)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))return!1;let t=document.createElement("a");return t.relList!==void 0&&t.relList.supports!==void 0&&t.relList.supports("ar")}function ct(){if(typeof navigator>"u")return!1;let n=navigator.userAgent||"";return/android/i.test(n)}async function ut(){if(typeof navigator>"u")return!1;let n=navigator;if(!n.xr||typeof n.xr.isSessionSupported!="function")return!1;try{return await n.xr.isSessionSupported("immersive-ar")?!0:await n.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function Ot(){let n=[];return await ut()&&n.push("webxr"),ot()&&n.push("quick-look"),ct()&&n.push("scene-viewer"),n}async function Vt(){return(await lt()).bestMode}async function lt(){let[n,e,t]=await Promise.all([ut(),Promise.resolve(ot()),Promise.resolve(ct())]),i=[];e&&i.push("quick-look"),n&&i.push("webxr"),t&&i.push("scene-viewer");let r=null;return e?r="quick-look":n?r="webxr":t&&(r="scene-viewer"),{webxr:n,quickLook:e,sceneViewer:t,availableModes:i,bestMode:r}}function st(n,e={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let t,i=!1;if(typeof n=="string"){if(t=Rt(n),!t)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else t=URL.createObjectURL(n),i=!0;let r=[];if(e.allowScale===!1&&r.push("allowsContentScaling=0"),e.canonicalWebPageUrl){let l=Pe(e.canonicalWebPageUrl,!1);l&&r.push(`canonicalWebPageURL=${encodeURIComponent(l)}`)}e.checkoutTitle&&r.push(`checkoutTitle=${encodeURIComponent(e.checkoutTitle)}`),e.checkoutSubtitle&&r.push(`checkoutSubtitle=${encodeURIComponent(e.checkoutSubtitle)}`),e.price&&r.push(`price=${encodeURIComponent(e.price)}`),r.length>0&&(t+=`#${r.join("&")}`);let s=document.createElement("a");s.setAttribute("rel","ar"),s.setAttribute("href",t);let c=document.createElement("img");c.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),c.style.display="none",s.appendChild(c),document.body.appendChild(s),s.click(),setTimeout(()=>{document.body.removeChild(s),i&&URL.revokeObjectURL(t.split("#")[0])},3e3)}function Pe(n,e=!1){if(typeof n!="string")return"";let t=n.replace(/[\x00-\x1f\x7f]+/g,"").trim();if(!t)return"";if(/^[\\/]{2}/.test(t))throw new Error(`[XR-Live Security] Rejected protocol-relative URL in Scene Viewer intent: ${t.slice(0,32)}`);let i=t.toLowerCase();if(i.startsWith("https://")||i.startsWith("http://")||e&&i.startsWith("blob:")||!/^[a-z][a-z0-9+.-]*:/i.test(t))return t;throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Scene Viewer intent: ${t.slice(0,32)}`)}function Rt(n){try{return Pe(n,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(n||"").trim().slice(0,32)}`)}}function wt(n,e={}){let t=Pe(n,!0),i=e.mode||"ar_preferred",r=new URLSearchParams({file:t,mode:i,resizable:e.resizable!==!1?"true":"false",enable_vertical_placement:e.enableVerticalPlacement?"true":"false"});return e.title&&r.set("title",e.title),e.link&&r.set("link",Pe(e.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${r.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function At(n,e={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let t=wt(n,e);window.location.href=t}var be=null;function Et(n,e){let i=new Float32Array(144),r=new Float32Array(24*6),s=new Float32Array(24*4),c=new Uint16Array(24*6);for(let f=0;f<24;f++){let d=f/24*Math.PI*2,p=Math.cos(d),m=Math.sin(d),x=f*2,b=x+1,E=(f+1)%24*2;i[x*3]=p*.11,i[x*3+1]=.002,i[x*3+2]=m*.11,i[b*3]=p*.145,i[b*3+1]=.002,i[b*3+2]=m*.145,r[x*3+1]=r[b*3+1]=1,c.set([x,E,b,b,E,E+1],f*6)}let l=n.createVertexArray();n.bindVertexArray(l);let u=(f,d,p)=>{let m=n.createBuffer();return n.bindBuffer(34962,m),n.bufferData(34962,f,35044),n.enableVertexAttribArray(d),n.vertexAttribPointer(d,p,5126,!1,0,0),m},a=[u(i,0,3),u(r,1,3),u(s,2,2)],o=n.createBuffer();return a.push(o),n.bindBuffer(34963,o),n.bufferData(34963,c,35044),n.bindVertexArray(null),{name:"__xr_reticle__",nodeIndex:-1,worldSpace:!0,visible:!1,transform:new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),normalMatrix:new Float32Array([1,0,0,0,1,0,0,0,1]),primitives:[{vao:l,indexCount:c.length,indexType:5123,baseColor:e&&e.length>=3?[e[0],e[1],e[2],e[3]??.95]:[.22,.74,.97,.95],metallic:0,roughness:.2,positions:i,indices:c,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:a}]}}function at(n,e,t,i,r){let s=Math.cos(i),c=Math.sin(i),l=Math.max(.01,r);n.fill(0),n[0]=l*s,n[2]=-l*c,n[5]=l,n[8]=l*c,n[10]=l*s,n[12]=e[0]-l*(s*t[0]+c*t[2]),n[13]=e[1]-l*t[1],n[14]=e[2]-l*(-c*t[0]+s*t[2]),n[15]=1}var ke=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.");be&&be!==this&&be.isSessionActive()&&await be.stop().catch(()=>{});let i=navigator.xr,r=this.opts,s=t||e?.container,c=String(s?.tagName||"").toLowerCase()==="xr-live",l=e?.bounds,u=Number(l?.radius)||1,a=Array.isArray(l?.center)?l.center:[0,0,0],o=Array.isArray(l?.min)?l.min:[-.5,-.5,-.5],f=typeof navigator<"u"&&navigator.userAgent||"",d=/Android|iPhone|iPad|iPod/i.test(f)&&!/Quest|Oculus|Pico|Vision/i.test(f),p=c?r.arScale==="fixed"?1:d?.55:1:r.arScale==="fixed"?1:u>.45?.3/u:u<.05?.12/Math.max(u,.001):1,m=c?[0,-.25,0]:[a[0]||0,r.arPlacement==="wall"?a[1]:o[1]??0,a[2]||0],x="immersive-ar";try{await i.isSessionSupported("immersive-ar")||(x="immersive-vr")}catch{x="immersive-vr"}let b=s?.querySelector?.('[slot="ar-overlay"]')||null,E=!1,P=null,A=()=>{E&&b?.parentNode&&b.parentNode.removeChild(b),b=null,P=null,E=!1};if(x==="immersive-ar"){if(b)b.addEventListener?.("beforexrselect",S=>S.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let S=document.createElement("div");S.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",_=>_.preventDefault()),U.addEventListener("click",_=>{_.stopPropagation(),this.stop().catch(()=>{})}),P=document.createElement("div"),P.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",P.textContent="Move phone to detect a surface \u2022 Tap to place",S.appendChild(U),S.appendChild(P),document.body.appendChild(S),b=S,E=!0}}let R=new Set(r.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),g={requiredFeatures:r.requiredFeatures?[...r.requiredFeatures]:[],optionalFeatures:Array.from(R)};b&&(R.add("dom-overlay"),g.optionalFeatures=Array.from(R),g.domOverlay={root:b});for(let S of K)S.onConfigureXRSessionInit?.(s,g);Array.isArray(g.optionalFeatures)&&g.optionalFeatures.includes("dom-overlay")&&!g.domOverlay?.root&&(g.optionalFeatures=g.optionalFeatures.filter(S=>S!=="dom-overlay"));let M=S=>{let U=String(S?.name||"");return U==="NotAllowedError"||U==="SecurityError"};try{this.s=await i.requestSession(x,g)}catch(S){if(A(),M(S))throw r.onError?.(S),S;try{this.s=await i.requestSession(x,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(U){if(M(U))throw r.onError?.(U),U;try{this.s=await i.requestSession(x)}catch(_){throw r.onError?.(_),_}}}let h=this.s;be=this,this.placed=!1;let v=null,y=null,T=null,F=null,C=null,w=[0,-.25,-1.2],D=[0,-.25,-1.2],B=new Float32Array(16),L=new Float32Array(16),q=!1,z=1,j=0,H=!1,$=null,G=null,N=0,W=null,I=()=>{be===this&&(be=null),W?.(),W=null;try{y?.cancel?.()}catch{}if(y=null,T){let S=e?.meshes;if(Array.isArray(S)){let _=S.indexOf(T);_!==-1&&S.splice(_,1)}let U=e.getGLContext?.()||e?.gl;if(U)for(let _ of T.primitives||[]){U.deleteVertexArray?.(_.vao);for(let ee of _.buffers||[])U.deleteBuffer?.(ee)}T=null}e?.setXRSessionActive?.(!1),A(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=I,h.addEventListener("end",()=>{I(),r.onExit?.()}),h.addEventListener("select",()=>{if(!this.placed){let S=C||w;D=[S[0],S[1],S[2]],at(this.placedMat,D,m,j,p*z),this.placed=!0,T&&(T.visible=!1),P&&(P.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),r.onPlaced?.(this.placedMat)}});try{let S=e.getGLContext?.()||e?.gl;S&&typeof S.makeXRCompatible=="function"&&await S.makeXRCompatible();let U=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;S&&typeof U=="function"&&typeof h.updateRenderState=="function"&&h.updateRenderState({baseLayer:new U(h,S,{alpha:!0})});try{v=await h.requestReferenceSpace("local")}catch{try{v=await h.requestReferenceSpace("local-floor")}catch{v=await h.requestReferenceSpace("viewer")}}let _=await h.requestReferenceSpace("viewer").catch(()=>v);if(typeof h.requestHitTestSource=="function"&&_&&(y=await h.requestHitTestSource({space:_}).catch(()=>null)),x==="immersive-ar"&&S&&typeof S.createVertexArray=="function"&&Array.isArray(e.meshes)&&(T=Et(S,r.reticleColor),e.meshes.push(T)),typeof window<"u"&&typeof window.addEventListener=="function"){let re=k=>Math.hypot(k.touches[1].clientX-k.touches[0].clientX,k.touches[1].clientY-k.touches[0].clientY),X=k=>Math.atan2(k.touches[1].clientY-k.touches[0].clientY,k.touches[1].clientX-k.touches[0].clientX),ce=k=>{this.s&&(k.touches.length===1&&this.placed?H=!0:k.touches.length>=2&&(H=!1,$=re(k),G=X(k)))},ie=k=>{if(!this.s||k.touches.length<2)return;let Q=re(k),Y=X(k);if($&&$>4&&r.arScale!=="fixed"&&(z=Math.max(.15,Math.min(6,z*(Q/$)))),G!==null){let ue=Y-G;ue>Math.PI&&(ue-=Math.PI*2),ue<-Math.PI&&(ue+=Math.PI*2),j-=ue}$=Q,G=Y},te=k=>{(!k.touches||k.touches.length===0)&&(H=!1),(!k.touches||k.touches.length<2)&&($=null,G=null)};window.addEventListener("touchstart",ce,{passive:!0}),window.addEventListener("touchmove",ie,{passive:!0}),window.addEventListener("touchend",te,{passive:!0}),window.addEventListener("touchcancel",te,{passive:!0}),W=()=>{window.removeEventListener("touchstart",ce),window.removeEventListener("touchmove",ie),window.removeEventListener("touchend",te),window.removeEventListener("touchcancel",te)}}e.setXRSessionActive?.(!0);let ee=(re,X)=>{if(this.s!==h)return;h.requestAnimationFrame(ee);let ce=N>0?Math.min(Math.max((re-N)/1e3,0),.1):1/60;N=re,e?.stepXRUpdate?.(ce);let ie=X.getViewerPose(v);if(!ie)return;let te=ie.views?.[0];if(!q&&te?.transform){let se=te.transform.position,J=te.transform.matrix,fe=se?.x??(J?J[12]:0),ae=se?.y??(J?J[13]:0),le=se?.z??(J?J[14]:0),O=J?-J[8]:0,ne=J?-J[10]:-1,me=Math.hypot(O,ne);me>1e-4?(O/=me,ne/=me):(O=0,ne=-1),w=[fe+O*1.2,ae-.25,le+ne*1.2],j=Math.atan2(-O,-ne),q=!0}if(y&&typeof X.getHitTestResults=="function"&&(!this.placed||H)){let se=X.getHitTestResults(y)||[],J=!1;for(let fe of se){let ae=fe.getPose(v);if(ae?.transform?.matrix){let le=ae.transform.matrix,O=le[5];if(r.arPlacement==="wall"&&Math.abs(O)>.35||r.arPlacement==="floor"&&Math.abs(O)<.65)continue;F||(F=new Float32Array(16)),F.set(le),C=[le[12],le[13],le[14]],this.placed&&H&&(D=[le[12],le[13],le[14]]),T&&(T.visible=!this.placed||H,T.transform.set(le)),!this.placed&&P&&(P.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),r.onHit?.(F),J=!0;break}}!J&&T&&(T.visible=!1)}at(B,this.placed?D:C||w,m,j,p*z),this.placed&&this.placedMat.set(B);let k=e.xrRigMatrix;k instanceof Float32Array&&k.length===16?oe(L,k,B):L.set(B),e.modelRootMatrix&&e.modelRootMatrix.set(L);for(let se of K)se.onXRFrame?.(e,h,X,v);let Q=e.getGLContext?.()||e?.gl,Y=h.renderState?.baseLayer;Q&&Y&&Y.framebuffer!==void 0&&Q.bindFramebuffer(36160,Y.framebuffer);let ue=x==="immersive-ar",ve=ie.views||[];for(let se=0;se<ve.length;se++){let J=ve[se];if(typeof e.renderXRView=="function"){let fe;if(Y&&typeof Y.getViewport=="function"){let ae=Y.getViewport(J);ae&&ae.width>0&&ae.height>0&&(fe=[ae.x,ae.y,ae.width,ae.height])}else Y?.framebufferWidth>0&&Y?.framebufferHeight>0&&(fe=[0,0,Y.framebufferWidth,Y.framebufferHeight]);e.renderXRView(J,L,this.placed,fe,ue,se)}}Q&&Y&&Y.framebuffer&&Q.bindFramebuffer(36160,null)};h.requestAnimationFrame(ee)}catch(S){throw typeof h.end=="function"&&await h.end().catch(()=>{}),I(),r.onError?.(S),S}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function Gt(n){let e=await lt(),t=n.preferredModes||["quick-look","webxr","scene-viewer"],i=null;for(let l of t)if(e.availableModes.includes(l)){i=l;break}if(i||(i=e.bestMode),!i)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let r={...n.quickLookOptions,allowScale:n.arScale==="fixed"?!1:n.quickLookOptions?.allowScale},s={...n.sceneViewerOptions,resizable:n.arScale==="fixed"?!1:n.sceneViewerOptions?.resizable,enableVerticalPlacement:n.arPlacement==="wall"?!0:n.sceneViewerOptions?.enableVerticalPlacement},c={...n.webXROptions,arScale:n.arScale||n.webXROptions?.arScale,arPlacement:n.arPlacement||n.webXROptions?.arPlacement};try{if(i==="quick-look"){let l;if(n.model instanceof Blob&&n.model.type==="model/vnd.usdz+zip")l=n.model;else{if(typeof n.model=="string")return st(n.model,r),{mode:"quick-look",success:!0};l=rt(n.model)}return st(l,r),{mode:"quick-look",success:!0}}if(i==="scene-viewer"){let l=n.glbUrl||(typeof n.model=="string"?n.model:null);if(!l)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return At(l,s),{mode:"scene-viewer",success:!0}}if(i==="webxr"){if(!n.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let l=new ke(c);return await l.start(n.view,n.element),{mode:"webxr",success:!0,session:l}}}catch(l){return{mode:i,success:!1,error:l}}return{mode:i,success:!1,error:new Error(`Unhandled AR mode: ${i}`)}}export{ke as WebXRSessionManager,Gt as activateAR,Be as buildUSDZZip,tt as calculateCRC32,wt as createSceneViewerIntent,rt as createUSDZBlob,et as generateUSDA,it as generateUSDZ,lt as getARCapabilities,Ot as getAvailableARModes,Vt as getBestARMode,nt as glbToUSDZ,ot as isQuickLookSupported,ct as isSceneViewerSupported,ut as isWebXRSupported,st as launchQuickLook,At as launchSceneViewer};
|
|
319
|
+
`,a}function ot(n,e){if(n&&typeof n.traverse=="function"){let i=Dt(n,e);return ke(i)}let t=xe(n),r=at(t);return ke(r)}var Ee=null;function ct(n){if(!Ee){Ee=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let i=0;i<8;i++)r=r&1?3988292384^r>>>1:r>>>1;Ee[t]=r}}let e=4294967295;for(let t=0;t<n.length;t++)e=Ee[(e^n[t])&255]^e>>>8;return(e^4294967295)>>>0}function Ve(n){let e=[],t=0,r=[];for(let u of n){let d=Be(u.filename),f=ct(u.data),T=u.data.length,p=30+d.length,h=t+p,b=0,R=h%64;R!==0&&(b=64-R);let A=new Uint8Array(p+b),v=new DataView(A.buffer);v.setUint32(0,67324752,!0),v.setUint16(4,20,!0),v.setUint16(6,0,!0),v.setUint16(8,0,!0),v.setUint16(10,0,!0),v.setUint16(12,0,!0),v.setUint32(14,f,!0),v.setUint32(18,T,!0),v.setUint32(22,T,!0),v.setUint16(26,d.length,!0),v.setUint16(28,b,!0),A.set(d,30),b>0&&A.fill(0,30+d.length),e.push({offset:t,size:T,crc:f,filenameBytes:d,entry:u}),r.push(A),r.push(u.data),t+=A.length+u.data.length}let i=t;for(let u of e){let d=new Uint8Array(46+u.filenameBytes.length),f=new DataView(d.buffer);f.setUint32(0,33639248,!0),f.setUint16(4,20,!0),f.setUint16(6,20,!0),f.setUint16(8,0,!0),f.setUint16(10,0,!0),f.setUint16(12,0,!0),f.setUint16(14,0,!0),f.setUint32(16,u.crc,!0),f.setUint32(20,u.size,!0),f.setUint32(24,u.size,!0),f.setUint16(28,u.filenameBytes.length,!0),f.setUint16(30,0,!0),f.setUint16(32,0,!0),f.setUint16(34,0,!0),f.setUint16(36,0,!0),f.setUint32(38,0,!0),f.setUint32(42,u.offset,!0),d.set(u.filenameBytes,46),r.push(d),t+=d.length}let s=t-i,a=new Uint8Array(22),c=new DataView(a.buffer);c.setUint32(0,101010256,!0),c.setUint16(4,0,!0),c.setUint16(6,0,!0),c.setUint16(8,e.length,!0),c.setUint16(10,e.length,!0),c.setUint32(12,s,!0),c.setUint32(16,i,!0),c.setUint16(20,0,!0),r.push(a),t+=22;let o=new Uint8Array(t),l=0;for(let u of r)o.set(u,l),l+=u.length;return o}function It(n){let e=ot(n),t=Be(e);return Ve([{filename:"model.usda",data:t}])}function ut(n){let e=xe(n),t=at(e),r=ke(t),i=Be(r);return Ve([{filename:"model.usda",data:i}])}function lt(n){return n&&typeof n.toUSDZ=="function"?n.toUSDZ():n&&typeof n.traverse=="function"?It(n):ut(n)}function mt(n){let e=lt(n);return new Blob([e],{type:"model/vnd.usdz+zip"})}function dt(){if(typeof window>"u"||typeof navigator>"u")return!1;let n=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(n)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))return!1;let t=document.createElement("a");return t.relList!==void 0&&t.relList.supports!==void 0&&t.relList.supports("ar")}function pt(){if(typeof navigator>"u")return!1;let n=navigator.userAgent||"";return/android/i.test(n)}async function bt(){if(typeof navigator>"u")return!1;let n=navigator;if(!n.xr||typeof n.xr.isSessionSupported!="function")return!1;try{return await n.xr.isSessionSupported("immersive-ar")?!0:await n.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function Jt(){let n=[];return await bt()&&n.push("webxr"),dt()&&n.push("quick-look"),pt()&&n.push("scene-viewer"),n}async function en(){return(await yt()).bestMode}async function yt(){let[n,e,t]=await Promise.all([bt(),Promise.resolve(dt()),Promise.resolve(pt())]),r=[];e&&r.push("quick-look"),n&&r.push("webxr"),t&&r.push("scene-viewer");let i=null;return e?i="quick-look":n?i="webxr":t&&(i="scene-viewer"),{webxr:n,quickLook:e,sceneViewer:t,availableModes:r,bestMode:i}}function ht(n,e={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let t,r=!1;if(typeof n=="string"){if(t=Nt(n),!t)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else t=URL.createObjectURL(n),r=!0;let i=[];if(e.allowScale===!1&&i.push("allowsContentScaling=0"),e.canonicalWebPageUrl){let c=Le(e.canonicalWebPageUrl,!1);c&&i.push(`canonicalWebPageURL=${encodeURIComponent(c)}`)}e.checkoutTitle&&i.push(`checkoutTitle=${encodeURIComponent(e.checkoutTitle)}`),e.checkoutSubtitle&&i.push(`checkoutSubtitle=${encodeURIComponent(e.checkoutSubtitle)}`),e.price&&i.push(`price=${encodeURIComponent(e.price)}`),i.length>0&&(t+=`#${i.join("&")}`);let s=document.createElement("a");s.setAttribute("rel","ar"),s.setAttribute("href",t);let a=document.createElement("img");a.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),a.style.display="none",s.appendChild(a),document.body.appendChild(s),s.click(),setTimeout(()=>{document.body.removeChild(s),r&&URL.revokeObjectURL(t.split("#")[0])},3e3)}function Le(n,e=!1){if(typeof n!="string")return"";let t=n.replace(/[\x00-\x1f\x7f]+/g,"").trim();if(!t)return"";if(/^[\\/]{2}/.test(t))throw new Error(`[XR-Live Security] Rejected protocol-relative URL in Scene Viewer intent: ${t.slice(0,32)}`);let r=t.toLowerCase();if(r.startsWith("https://")||r.startsWith("http://")||e&&r.startsWith("blob:")||!/^[a-z][a-z0-9+.-]*:/i.test(t))return t;throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Scene Viewer intent: ${t.slice(0,32)}`)}function Nt(n){try{return Le(n,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(n||"").trim().slice(0,32)}`)}}function Ut(n,e={}){let t=Le(n,!0),r=e.mode||"ar_preferred",i=new URLSearchParams({file:t,mode:r,resizable:e.resizable!==!1?"true":"false",enable_vertical_placement:e.enableVerticalPlacement?"true":"false"});return e.title&&i.set("title",e.title),e.link&&i.set("link",Le(e.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${i.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function kt(n,e={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let t=Ut(n,e);window.location.href=t}var de=null;function Bt(n,e){let r=new Float32Array(144),i=new Float32Array(24*6),s=new Float32Array(24*4),a=new Uint16Array(24*6);for(let d=0;d<24;d++){let f=d/24*Math.PI*2,T=Math.cos(f),p=Math.sin(f),h=d*2,b=h+1,R=(d+1)%24*2;r[h*3]=T*.11,r[h*3+1]=.002,r[h*3+2]=p*.11,r[b*3]=T*.145,r[b*3+1]=.002,r[b*3+2]=p*.145,i[h*3+1]=i[b*3+1]=1,a.set([h,R,b,b,R,R+1],d*6)}let c=n.createVertexArray();n.bindVertexArray(c);let o=(d,f,T)=>{let p=n.createBuffer();return n.bindBuffer(34962,p),n.bufferData(34962,d,35044),n.enableVertexAttribArray(f),n.vertexAttribPointer(f,T,5126,!1,0,0),p},l=[o(r,0,3),o(i,1,3),o(s,2,2)],u=n.createBuffer();return l.push(u),n.bindBuffer(34963,u),n.bufferData(34963,a,35044),n.bindVertexArray(null),{name:"__xr_reticle__",nodeIndex:-1,worldSpace:!0,visible:!1,transform:new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),normalMatrix:new Float32Array([1,0,0,0,1,0,0,0,1]),primitives:[{vao:c,indexCount:a.length,indexType:5123,baseColor:e&&e.length>=3?[e[0],e[1],e[2],e[3]??.95]:[.22,.74,.97,.95],metallic:0,roughness:.2,positions:r,indices:a,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:l}]}}function ft(n,e,t,r,i){let s=Math.cos(r),a=Math.sin(r),c=Math.max(.01,i);n.fill(0),n[0]=c*s,n[2]=-c*a,n[5]=c,n[8]=c*a,n[10]=c*s,n[12]=e[0]-c*(s*t[0]+a*t[2]),n[13]=e[1]-c*t[1],n[14]=e[2]-c*(-a*t[0]+s*t[2]),n[15]=1}var Oe=class{constructor(e={}){this.s=null;this.placed=!1;this.placedMat=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);this.cleanFn=null;this.opts=e}isSessionActive(){return this.s!==null}hasPlacedModel(){return this.placed}getPlacedMatrix(){return this.placedMat}async start(e,t){if(typeof navigator>"u"||!navigator.xr)throw new Error("WebXR is not supported on this browser.");de&&de!==this&&de.isSessionActive()&&await de.stop().catch(()=>{});let r=navigator.xr,i=this.opts,s=t||e?.container,a=String(s?.tagName||"").toLowerCase()==="xr-live",c=e?.bounds,o=Number(c?.radius)||1,l=Array.isArray(c?.center)?c.center:[0,0,0],u=Array.isArray(c?.min)?c.min:[-.5,-.5,-.5],d=typeof navigator<"u"&&navigator.userAgent||"",f=/Android|iPhone|iPad|iPod/i.test(d)&&!/Quest|Oculus|Pico|Vision/i.test(d),T=a?i.arScale==="fixed"?1:f?.55:1:i.arScale==="fixed"?1:o>.45?.3/o:o<.05?.12/Math.max(o,.001):1,p=a?[0,-.25,0]:[l[0]||0,i.arPlacement==="wall"?l[1]:u[1]??0,l[2]||0],h="immersive-ar";try{await r.isSessionSupported("immersive-ar")||(h="immersive-vr")}catch{h="immersive-vr"}let b=s?.querySelector?.('[slot="ar-overlay"]')||null,R=!1,A=null,v=()=>{R&&b?.parentNode&&b.parentNode.removeChild(b),b=null,A=null,R=!1};if(h==="immersive-ar"){if(b)b.addEventListener?.("beforexrselect",x=>x.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let x=document.createElement("div");x.style.cssText="position:fixed;inset:0;pointer-events:none;background:transparent!important;z-index:2147483647;font-family:system-ui,sans-serif;user-select:none";let I=document.createElement("button");I.type="button",I.textContent="\u2715 Exit AR",I.style.cssText="position:absolute;top:max(16px,env(safe-area-inset-top,16px));right:16px;pointer-events:auto;padding:8px 14px;border-radius:99px;border:1px solid rgba(255,255,255,.3);background:rgba(15,23,42,.8);color:#f8fafc;font:600 13px system-ui,sans-serif",I.addEventListener("beforexrselect",N=>N.preventDefault()),I.addEventListener("click",N=>{N.stopPropagation(),this.stop().catch(()=>{})}),A=document.createElement("div"),A.style.cssText="position:absolute;bottom:max(28px,env(safe-area-inset-bottom,28px));left:50%;transform:translateX(-50%);padding:8px 15px;border-radius:99px;border:1px solid rgba(56,189,248,.4);background:rgba(15,23,42,.82);color:#f8fafc;font:500 12.5px system-ui,sans-serif;text-align:center;max-width:88vw",A.textContent="Move phone to detect a surface \u2022 Tap to place",x.appendChild(I),x.appendChild(A),document.body.appendChild(x),b=x,R=!0}}let D=new Set(i.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),g={requiredFeatures:i.requiredFeatures?[...i.requiredFeatures]:[],optionalFeatures:Array.from(D)};b&&(D.add("dom-overlay"),g.optionalFeatures=Array.from(D),g.domOverlay={root:b});for(let x of ae)x.onConfigureXRSessionInit?.(s,g);Array.isArray(g.optionalFeatures)&&g.optionalFeatures.includes("dom-overlay")&&!g.domOverlay?.root&&(g.optionalFeatures=g.optionalFeatures.filter(x=>x!=="dom-overlay"));let P=x=>{let I=String(x?.name||"");return I==="NotAllowedError"||I==="SecurityError"};try{this.s=await r.requestSession(h,g)}catch(x){if(v(),P(x))throw i.onError?.(x),x;try{this.s=await r.requestSession(h,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(I){if(P(I))throw i.onError?.(I),I;try{this.s=await r.requestSession(h)}catch(N){throw i.onError?.(N),N}}}let E=this.s;de=this,this.placed=!1;let y=null,F=null,L=null,C=null,m=null,w=[0,-.25,-1.2],S=[0,-.25,-1.2],M=new Float32Array(16),k=new Float32Array(16),_=!1,K=1,U=0,O=!1,B=null,q=null,Y=0,W=null,j=()=>{de===this&&(de=null),W?.(),W=null;try{F?.cancel?.()}catch{}if(F=null,L){let x=e?.meshes;if(Array.isArray(x)){let N=x.indexOf(L);N!==-1&&x.splice(N,1)}let I=e.getGLContext?.()||e?.gl;if(I)for(let N of L.primitives||[]){I.deleteVertexArray?.(N.vao);for(let z of N.buffers||[])I.deleteBuffer?.(z)}L=null}e?.setXRSessionActive?.(!1),v(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=j,E.addEventListener("end",()=>{j(),i.onExit?.()}),E.addEventListener("select",()=>{if(!this.placed){let x=m||w;S=[x[0],x[1],x[2]],ft(this.placedMat,S,p,U,T*K),this.placed=!0,L&&(L.visible=!1),A&&(A.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),i.onPlaced?.(this.placedMat)}});try{let x=e.getGLContext?.()||e?.gl;x&&typeof x.makeXRCompatible=="function"&&await x.makeXRCompatible();let I=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;x&&typeof I=="function"&&typeof E.updateRenderState=="function"&&E.updateRenderState({baseLayer:new I(E,x,{alpha:!0})});try{y=await E.requestReferenceSpace("local")}catch{try{y=await E.requestReferenceSpace("local-floor")}catch{y=await E.requestReferenceSpace("viewer")}}let N=await E.requestReferenceSpace("viewer").catch(()=>y);if(typeof E.requestHitTestSource=="function"&&N&&(F=await E.requestHitTestSource({space:N}).catch(()=>null)),h==="immersive-ar"&&x&&typeof x.createVertexArray=="function"&&Array.isArray(e.meshes)&&(L=Bt(x,i.reticleColor),e.meshes.push(L)),typeof window<"u"&&typeof window.addEventListener=="function"){let ee=G=>Math.hypot(G.touches[1].clientX-G.touches[0].clientX,G.touches[1].clientY-G.touches[0].clientY),ie=G=>Math.atan2(G.touches[1].clientY-G.touches[0].clientY,G.touches[1].clientX-G.touches[0].clientX),oe=G=>{this.s&&(G.touches.length===1&&this.placed?O=!0:G.touches.length>=2&&(O=!1,B=ee(G),q=ie(G)))},H=G=>{if(!this.s||G.touches.length<2)return;let te=ee(G),V=ie(G);if(B&&B>4&&i.arScale!=="fixed"&&(K=Math.max(.15,Math.min(6,K*(te/B)))),q!==null){let J=V-q;J>Math.PI&&(J-=Math.PI*2),J<-Math.PI&&(J+=Math.PI*2),U-=J}B=te,q=V},$=G=>{(!G.touches||G.touches.length===0)&&(O=!1),(!G.touches||G.touches.length<2)&&(B=null,q=null)};window.addEventListener("touchstart",oe,{passive:!0}),window.addEventListener("touchmove",H,{passive:!0}),window.addEventListener("touchend",$,{passive:!0}),window.addEventListener("touchcancel",$,{passive:!0}),W=()=>{window.removeEventListener("touchstart",oe),window.removeEventListener("touchmove",H),window.removeEventListener("touchend",$),window.removeEventListener("touchcancel",$)}}e.setXRSessionActive?.(!0);let z=(ee,ie)=>{if(this.s!==E)return;E.requestAnimationFrame(z);let oe=Y>0?Math.min(Math.max((ee-Y)/1e3,0),.1):1/60;Y=ee,e?.stepXRUpdate?.(oe);let H=ie.getViewerPose(y);if(!H)return;let $=H.views?.[0];if(!_&&$?.transform){let Z=$.transform.position,ne=$.transform.matrix,le=Z?.x??(ne?ne[12]:0),ce=Z?.y??(ne?ne[13]:0),ue=Z?.z??(ne?ne[14]:0),fe=ne?-ne[8]:0,be=ne?-ne[10]:-1,Se=Math.hypot(fe,be);Se>1e-4?(fe/=Se,be/=Se):(fe=0,be=-1),w=[le+fe*1.2,ce-.25,ue+be*1.2],U=Math.atan2(-fe,-be),_=!0}if(F&&typeof ie.getHitTestResults=="function"&&(!this.placed||O)){let Z=ie.getHitTestResults(F)||[],ne=!1;for(let le of Z){let ce=le.getPose(y);if(ce?.transform?.matrix){let ue=ce.transform.matrix,fe=ue[5];if(i.arPlacement==="wall"&&Math.abs(fe)>.35||i.arPlacement==="floor"&&Math.abs(fe)<.65)continue;C||(C=new Float32Array(16)),C.set(ue),m=[ue[12],ue[13],ue[14]],this.placed&&O&&(S=[ue[12],ue[13],ue[14]]),L&&(L.visible=!this.placed||O,L.transform.set(ue)),!this.placed&&A&&(A.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),i.onHit?.(C),ne=!0;break}}!ne&&L&&(L.visible=!1)}ft(M,this.placed?S:m||w,p,U,T*K),this.placed&&this.placedMat.set(M);let G=e.xrRigMatrix;G instanceof Float32Array&&G.length===16?se(k,G,M):k.set(M),e.modelRootMatrix&&e.modelRootMatrix.set(k);for(let Z of ae)Z.onXRFrame?.(e,E,ie,y);let te=e.getGLContext?.()||e?.gl,V=E.renderState?.baseLayer;te&&V&&V.framebuffer!==void 0&&te.bindFramebuffer(36160,V.framebuffer);let J=h==="immersive-ar",Q=H.views||[];for(let Z=0;Z<Q.length;Z++){let ne=Q[Z];if(typeof e.renderXRView=="function"){let le;if(V&&typeof V.getViewport=="function"){let ce=V.getViewport(ne);ce&&ce.width>0&&ce.height>0&&(le=[ce.x,ce.y,ce.width,ce.height])}else V?.framebufferWidth>0&&V?.framebufferHeight>0&&(le=[0,0,V.framebufferWidth,V.framebufferHeight]);e.renderXRView(ne,k,this.placed,le,J,Z)}}te&&V&&V.framebuffer&&te.bindFramebuffer(36160,null)};E.requestAnimationFrame(z)}catch(x){throw typeof E.end=="function"&&await E.end().catch(()=>{}),j(),i.onError?.(x),x}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function tn(n){let e=await yt(),t=n.preferredModes||["quick-look","webxr","scene-viewer"],r=null;for(let c of t)if(e.availableModes.includes(c)){r=c;break}if(r||(r=e.bestMode),!r)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let i={...n.quickLookOptions,allowScale:n.arScale==="fixed"?!1:n.quickLookOptions?.allowScale},s={...n.sceneViewerOptions,resizable:n.arScale==="fixed"?!1:n.sceneViewerOptions?.resizable,enableVerticalPlacement:n.arPlacement==="wall"?!0:n.sceneViewerOptions?.enableVerticalPlacement},a={...n.webXROptions,arScale:n.arScale||n.webXROptions?.arScale,arPlacement:n.arPlacement||n.webXROptions?.arPlacement};try{if(r==="quick-look"){let c;if(n.model instanceof Blob&&n.model.type==="model/vnd.usdz+zip")c=n.model;else{if(typeof n.model=="string")return ht(n.model,i),{mode:"quick-look",success:!0};c=mt(n.model)}return ht(c,i),{mode:"quick-look",success:!0}}if(r==="scene-viewer"){let c=n.glbUrl||(typeof n.model=="string"?n.model:null);if(!c)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return kt(c,s),{mode:"scene-viewer",success:!0}}if(r==="webxr"){if(!n.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let c=new Oe(a);return await c.start(n.view,n.element),{mode:"webxr",success:!0,session:c}}}catch(c){return{mode:r,success:!1,error:c}}return{mode:r,success:!1,error:new Error(`Unhandled AR mode: ${r}`)}}export{Oe as WebXRSessionManager,tn as activateAR,Ve as buildUSDZZip,ct as calculateCRC32,Ut as createSceneViewerIntent,mt as createUSDZBlob,ot as generateUSDA,lt as generateUSDZ,yt as getARCapabilities,Jt as getAvailableARModes,en as getBestARMode,ut as glbToUSDZ,dt as isQuickLookSupported,pt as isSceneViewerSupported,bt as isWebXRSupported,ht as launchQuickLook,kt as launchSceneViewer};
|