three-live 1.3.2 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -1
- package/dist/index.d.ts +190 -0
- package/dist/three-author-engine.js +171 -163
- package/dist/three-author.cjs +145 -163
- package/dist/three-author.d.ts +190 -0
- package/dist/three-author.js +145 -163
- package/dist/three-convert.cjs +142 -160
- package/dist/three-convert.d.ts +190 -0
- package/dist/three-convert.js +142 -160
- package/dist/three-live-ai.cjs +41 -0
- package/dist/three-live-ai.d.ts +759 -0
- package/dist/three-live-ai.js +41 -0
- package/dist/three-live-ai.min.js +41 -0
- package/dist/three-live-animation.cjs +6 -6
- package/dist/three-live-animation.d.ts +190 -0
- package/dist/three-live-animation.js +5 -5
- package/dist/three-live-animation.min.js +5 -5
- package/dist/three-live-cad.cjs +2 -2
- package/dist/three-live-cad.d.ts +190 -0
- package/dist/three-live-cad.js +2 -2
- package/dist/three-live-cad.min.js +2 -2
- package/dist/three-live-element.cjs +50 -85
- package/dist/three-live-element.d.ts +190 -0
- package/dist/three-live-element.js +50 -85
- package/dist/three-live-full.cjs +907 -189
- package/dist/three-live-full.js +907 -189
- package/dist/three-live-full.min.js +907 -189
- package/dist/three-live-procedural.cjs +16 -0
- package/dist/three-live-procedural.d.ts +759 -0
- package/dist/three-live-procedural.js +16 -0
- package/dist/three-live-procedural.min.js +16 -0
- package/dist/three-live-sandbox.html +11 -1
- package/dist/three-live-studio.cjs +72 -17
- package/dist/three-live-studio.d.ts +190 -0
- package/dist/three-live-studio.js +72 -17
- package/dist/three-live-studio.min.js +73 -18
- package/dist/three-live-tsl.cjs +103 -0
- package/dist/three-live-tsl.d.ts +759 -0
- package/dist/three-live-tsl.js +103 -0
- package/dist/three-live-tsl.min.js +103 -0
- package/dist/three-live-viewer.cjs +50 -85
- package/dist/three-live-viewer.d.ts +190 -0
- package/dist/three-live-viewer.js +50 -85
- package/dist/three-live-viewer.min.js +50 -85
- package/dist/three-live-webgpu.cjs +585 -0
- package/dist/three-live-webgpu.d.ts +759 -0
- package/dist/three-live-webgpu.js +585 -0
- package/dist/three-live-webgpu.min.js +585 -0
- package/dist/three-live.cjs +147 -165
- package/dist/three-live.js +147 -165
- package/dist/three-live.min.js +147 -165
- package/dist/three-view.cjs +49 -84
- package/dist/three-view.d.ts +190 -0
- package/dist/three-view.js +50 -85
- package/dist/three-xr.cjs +141 -159
- package/dist/three-xr.d.ts +190 -0
- package/dist/three-xr.js +140 -158
- package/package.json +21 -1
package/dist/three-live-full.cjs
CHANGED
|
@@ -13,8 +13,8 @@
|
|
|
13
13
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
|
-
*/var Mi=Object.defineProperty,Pa=Object.getOwnPropertyDescriptor,Na=Object.getOwnPropertyNames,ka=Object.prototype.hasOwnProperty,Oa=(e,t)=>{for(var r in t)Mi(e,r,{get:t[r],enumerable:!0})},Ua=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Na(t))!ka.call(e,n)&&n!==r&&Mi(e,n,{get:()=>t[n],enumerable:!(i=Pa(t,n))||i.enumerable});return e},Fa=e=>Ua(Mi({},"__esModule",{value:!0}),e),Co={};Oa(Co,{AmbientLight:()=>On,BoxGeometry:()=>Cn,BufferAttribute:()=>$e,BufferGeometry:()=>Be,Camera:()=>Fn,CapsuleGeometry:()=>qr,CatmullRomCurve3:()=>Cr,CircleGeometry:()=>Yr,Clock:()=>Hr,Color:()=>ut,ConeGeometry:()=>Sr,CubicBezierCurve3:()=>Ir,Curve3:()=>St,CylinderGeometry:()=>Dn,DataTexture:()=>Pr,DirectionalLight:()=>Br,DodecahedronGeometry:()=>Kr,EdgesGeometry:()=>Jr,Euler:()=>In,Float32BufferAttribute:()=>vr,Group:()=>Vr,HemisphereLight:()=>Hn,IKSolver:()=>$o,IcosahedronGeometry:()=>jr,InstancedMesh:()=>kn,InteractivityVM:()=>qn,LOD:()=>qo,LatheGeometry:()=>Pn,Light:()=>zt,Line:()=>Nt,LineBasicMaterial:()=>un,LineCurve3:()=>_r,LineDashedMaterial:()=>Zr,LineLoop:()=>ei,LineSegments:()=>ti,LodController:()=>xn,MAX_BSP_DEPTH:()=>Vo,MAX_CSG_TRIANGLES:()=>Fo,MAX_INSTANCES_PER_MESH:()=>Nn,MAX_SHAPE_POINTS:()=>zo,MAX_TEXT_GEOMETRY_CHARS:()=>Bo,Material:()=>et,MathUtils:()=>_s,Matrix3:()=>xr,Matrix4:()=>Pt,Mesh:()=>gt,MeshBasicMaterial:()=>kr,MeshLambertMaterial:()=>Or,MeshPhongMaterial:()=>Ur,MeshPhysicalMaterial:()=>Fr,MeshStandardMaterial:()=>Bt,Object3D:()=>lt,OctahedronGeometry:()=>Wr,PerspectiveCamera:()=>zr,PlaneGeometry:()=>Ar,PointLight:()=>Un,Points:()=>ni,PointsMaterial:()=>Gn,PolyhedronFallbackGeometry:()=>Dc,PolyhedronGeometry:()=>Et,QuadraticBezierCurve3:()=>Lr,Quaternion:()=>sn,RawShaderMaterial:()=>Bs,RectAreaLight:()=>Hs,RingGeometry:()=>zn,Scene:()=>Vn,SceneQuotaValidator:()=>yt,ShaderMaterial:()=>Bn,SphereGeometry:()=>wr,SpotLight:()=>ri,THREE:()=>Ht,TetrahedronGeometry:()=>$r,Texture:()=>an,TextureLoader:()=>Nr,ThreeLiveElement:()=>mt,ThreeView:()=>Ke,TorusGeometry:()=>Er,TorusKnotGeometry:()=>Rr,TubeGeometry:()=>Dr,Uint16BufferAttribute:()=>Mr,Uint32BufferAttribute:()=>Tr,Vector2:()=>rt,Vector3:()=>ge,Vector4:()=>gr,WebGLRenderer:()=>Gr,WireframeGeometry:()=>Qr,activateAR:()=>ci,applyMeshoptFilter:()=>Ao,authorScriptRunner:()=>ln,buildSandboxWorkerSource:()=>Wi,cadPlugin:()=>Ti,clearAuthorWarnings:()=>Vs,computeOutlineClipOffset:()=>Ra,contactShadowPlugin:()=>jn,createUSDZBlob:()=>on,crossFadeTo:()=>eo,decimateGeometry:()=>Ko,decodeMeshoptBuffer:()=>wo,decodeMeshoptGLB:()=>yi,defineModelViewer:()=>$s,encodeMeshoptBuffer:()=>Ta,environmentMapPlugin:()=>ho,evaluateKawaseBloom:()=>Ea,evaluateToneMapping:()=>is,exportSceneToCanvas3D:()=>Gi,exportSceneToGLB:()=>Hi,exportSceneToUSDZ:()=>Cs,extractMaterialVariants:()=>_o,extractPrimitiveVariantMappings:()=>_a,generateUSDZ:()=>En,getARCapabilities:()=>ai,getAllowClientScripts:()=>Ns,getAuthorWarnings:()=>Fs,getBestARMode:()=>Qs,getEnvironmentSH:()=>ta,getInteractivityVM:()=>hi,getLodController:()=>Yo,getSandboxEngineSrc:()=>Xi,getSandboxIframeSrc:()=>Ps,glbToUSDZ:()=>Sn,hotspotPlugin:()=>yo,ikPlugin:()=>Di,installCadExtension:()=>nr,installLodExtension:()=>gn,interactivityPlugin:()=>Mo,isAllowedSandboxEngineUrl:()=>cn,isQuickLookSupported:()=>co,isSceneViewerSupported:()=>uo,isWebXRSupported:()=>lo,keyframeAnimationPlugin:()=>to,lodPlugin:()=>Pi,materialsPlugin:()=>To,meshoptDecoder:()=>gi,meshoptPlugin:()=>So,morphPlugin:()=>no,noopProxy:()=>_n,parseAnimations:()=>Ji,parseHexRgb:()=>Eo,parseLod:()=>ar,parseSafeGltfPointer:()=>Kn,postprocessingPlugin:()=>Ro,quatFromUnitVectors:()=>or,registerMaterialShader:()=>ua,sampleChannel:()=>fn,sceneToCanvas3D:()=>rn,sceneToGLB:()=>Tn,sceneToUSDZ:()=>wn,selectLodLevelIndex:()=>sr,selectMaterialVariant:()=>La,sendInteractivityEvent:()=>vo,setAllowClientScripts:()=>Ac,setEnvironmentSH:()=>ui,setMorphTargetWeight:()=>Ks,setSandboxEngineSrc:()=>xc,setSandboxIframeSrc:()=>Mc,skinningPlugin:()=>io,solveFABRIK:()=>Ii,solveTwoBoneIK:()=>Li,threeAuthorPlugin:()=>Ln,threeMicroPlugin:()=>kc,toGLBData:()=>Lt,toTrustedWorkerScriptURL:()=>Ds,validateSandboxWorkerMessage:()=>ji,variantsPlugin:()=>Lo,warnUnsupported:()=>Gt,webxrPlugin:()=>Io}),module.exports=Fa(Co);function Uo(e,t,r){let i=[],n=new Map,s=[],l=[],o=[],a=new Map,u=p=>{let y=n.get(p);return y===void 0&&(y=i.length,i.push({op:p}),n.set(p,y)),y},h=p=>{let y=a.get(p);return y===void 0&&(y=o.length,o.push({id:p}),a.set(p,y)),y},m=(p,y={})=>s.push({declaration:u(p),...y})-1,c=(p,y,M)=>l.push({id:p,type:y,value:M})-1,d=p=>({node:p,socket:"value"}),f=r?.interactivity??r?.gltfExtensions?.KHR_interactivity;if(f&&typeof f=="object"){let p=Array.isArray(f.graphs)?f.graphs[f.graph??0]:f;if(p&&Array.isArray(p.nodes)){let y=Array.isArray(p.declarations)?p.declarations:[];for(let M of y)M?.op&&u(M.op);Array.isArray(p.variables)&&l.push(...p.variables);for(let M of p.events||[])M?.id&&h(M.id);for(let M of p.nodes){if(!M||typeof M!="object")continue;let P=M.op||(typeof M.declaration=="number"?y[M.declaration]?.op:"");s.push(P?{...M,declaration:u(P)}:{...M})}}}let g=(p,y,M="translation")=>M==="baseColorFactor"||M==="metallicFactor"||M==="roughnessFactor"?`/materials/${Math.max(0,y)}/pbrMetallicRoughness/${M}`:M==="emissiveFactor"||M==="alphaCutoff"?`/materials/${Math.max(0,y)}/${M}`:M==="visible"?`/nodes/${p}/extensions/KHR_node_visibility/visible`:`/nodes/${p}/${M}`,x=new Map;e.forEach((p,y)=>{typeof p?.name=="string"&&!x.has(p.name)&&x.set(p.name,y)});let b=(p,y)=>typeof p.target=="string"&&x.has(p.target)?x.get(p.target):typeof p.targetNode=="number"?p.targetNode:y,v=p=>{let y=e[p];return(typeof y?.mesh=="number"?t[y.mesh]?.primitives?.[0]?.material:0)??0};for(let p=0;p<e.length;p++){let y=e[p],M=y?.extras?.interactivity;if(!M||typeof M!="object")continue;let P=(typeof y.mesh=="number"?t[y.mesh]?.primitives?.[0]?.material:0)??0,F=T=>{let E=Array.isArray(T)?T:[T],S=[];for(let k=0;k<E.length;k++){let w=E[k];if(!w||typeof w!="object")continue;let ie=w.action||"interpolate",oe=typeof w.duration=="number"?w.duration:.35;if(ie==="toggleTransform"){let I=w.property==="rotation"||w.property==="scale"?w.property:"translation",H=I==="rotation"?y.rotation||[0,0,0,1]:I==="scale"?y.scale||[1,1,1]:y.translation||[0,0,0],N=`/nodes/${p}/${I}`,z=c(`__toggle_${p}_${k}`,"bool",!1),ue=m("variable/get",{configuration:{variable:z}}),ce=m("math/not",{values:{a:d(ue)}}),B=m("variable/set",{configuration:{variable:z},values:{value:d(ce)}}),$=m("pointer/interpolate",{configuration:{pointer:N},values:{value:{value:Array.isArray(w.to)?w.to:H},duration:{value:oe}}}),_=m("pointer/interpolate",{configuration:{pointer:N},values:{value:{value:Array.isArray(w.from)?w.from:H},duration:{value:oe}}});s[B].flows={out:{node:m("flow/branch",{values:{condition:d(ue)},flows:{true:{node:$},false:{node:_}}})}},S.push(B)}else if(ie==="interpolate"){let I=w.to??w.value;if(I===void 0)continue;let H={value:{value:I},duration:{value:oe}};w.from!==void 0&&(H.from={value:w.from}),S.push(m("pointer/interpolate",{configuration:{pointer:typeof w.pointer=="string"?w.pointer:g(b(w,p),v(b(w,p)),w.property)},values:H}))}else if(ie==="setProperty"){if(w.value===void 0)continue;S.push(m("pointer/set",{configuration:{pointer:typeof w.pointer=="string"?w.pointer:g(b(w,p),v(b(w,p)),w.property)},values:{value:{value:w.value}}}))}else if(ie==="toggleVisibility"){let I=b(w,p),H=c(`__vis_${I}_${k}`,"bool",!0),N=m("variable/get",{configuration:{variable:H}}),z=m("math/not",{values:{a:d(N)}}),ue=m("variable/set",{configuration:{variable:H},values:{value:d(z)}});s[ue].flows={out:{node:m("pointer/set",{configuration:{pointer:`/nodes/${I}/extensions/KHR_node_visibility/visible`},values:{value:d(N)}})}},S.push(ue)}else if(ie==="cycleMaterialColor"&&Array.isArray(w.colors)&&w.colors.length>0){let I=typeof w.duration=="number"?w.duration:.25,H=`/materials/${Math.max(0,P)}/pbrMetallicRoughness/baseColorFactor`,N=c(`__color_idx_${p}_${k}`,"int",0),z=m("variable/get",{configuration:{variable:N}}),ue=m("math/add",{values:{a:d(z),b:{value:1}}}),ce=m("math/rem",{values:{a:d(ue),b:{value:w.colors.length}}}),B=m("variable/set",{configuration:{variable:N},values:{value:d(ce)}}),$={};for(let _=0;_<w.colors.length;_++){let G=w.colors[_],j=Array.isArray(G)&&G.length>=3?[G[0],G[1],G[2],G[3]??1]:[1,1,1,1];$[String(_)]={node:I>0?m("pointer/interpolate",{configuration:{pointer:H},values:{value:{value:j},duration:{value:I}}}):m("pointer/set",{configuration:{pointer:H},values:{value:{value:j}}})}}s[B].flows={out:{node:m("flow/switch",{values:{selection:d(z)},flows:$})}},S.push(B)}else if(ie==="playAnimation")S.push(m("animation/start",{configuration:{animation:w.animation??w.clip??0}}));else if(ie==="stopAnimation")S.push(m("animation/stop"));else if(ie==="sendEvent"){let I={};for(let[H,N]of Object.entries(w.values||{}))I[H]={value:N};S.push(m("event/send",{configuration:{event:h(String(w.event??w.id??"custom"))},values:I}))}}if(!S.length)return null;if(S.length===1)return S[0];let O={};return S.forEach((k,w)=>{O[String(w)]={node:k}}),m("flow/sequence",{flows:O})},W=(T,E,S)=>{let O=F(E);O!==null&&m(T,{...S?{configuration:S}:{},flows:{out:{node:O}}})};if(M.onSelect&&W("pointer/onSelect",M.onSelect,{nodeIndex:p}),M.onHoverIn&&W("pointer/onHoverIn",M.onHoverIn,{nodeIndex:p}),M.onHoverOut&&W("pointer/onHoverOut",M.onHoverOut,{nodeIndex:p}),M.onStart&&W("event/onStart",M.onStart),M.onReceive&&typeof M.onReceive=="object")for(let[T,E]of Object.entries(M.onReceive))W("event/receive",E,{event:h(T)})}return s.length?{graphs:[{declarations:i,nodes:s,variables:l,events:o}],graph:0}:null}var Qn='SecurityError: Client-modified script compilation (Use Case 1) is disabled by default to satisfy strict CSP and Trusted Types requirements. Use script-src="..." or loadScriptFromSrc(url) for server-generated scripts (Use Case 2), or explicitly opt in via ThreeLiveElement.allowClientScripts = true (or the allow-client-scripts attribute).',Jn="Security Error: client-side scripts require allow-client-scripts opt-in.",er="__THREE_LIVE_REGISTRY__";function Ae(){let e=typeof globalThis<"u"?globalThis:{};if(!e[er]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(e,er,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{e[er]=t}}return e[er]}var Oe=Ae().plugins;function Qt(e){let t=Ae();t.workerExtensionInstallers||(t.workerExtensionInstallers=[]),t.workerExtensionInstallers.includes(e)||t.workerExtensionInstallers.push(e)}function Ve(e){let t=Ae().plugins;t.some(r=>r.name===e.name)||t.push(e),e.onRegister?.()}function tr(){return Ae().plugins}var Fo=8192,Vo=2048,Bo=128,zo=4096;function nr(e,t){if(!e||!e.BufferGeometry)return null;let r=e.Vector2,i=e.Vector3,n=e.Quaternion,s=e.Matrix4,l=e.Matrix3,o=e.Color,a=e.BufferAttribute,u=e.BufferGeometry,h=e.Material,m=e.MeshStandardMaterial,c=e.Mesh,d=8192,f=2048,g=128,x=4096,b=(R,A)=>{let L=R==null?NaN:Number(R);return Number.isFinite(L)?L:A};class v{constructor(A){this.currentPoint=new r(0,0),this.segments=[],Array.isArray(A)&&A.length>0&&this.fromPoints(A)}fromPoints(A){if(!A.length)return this;this.moveTo(A[0].x,A[0].y);for(let L=1;L<A.length;L++)this.lineTo(A[L].x,A[L].y);return this}moveTo(A,L){let C=Number(A)||0,U=Number(L)||0;return this.currentPoint.set(C,U),this.segments.push({type:"move",pts:[C,U]}),this}lineTo(A,L){let C=Number(A)||0,U=Number(L)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[this.currentPoint.x,this.currentPoint.y]}),this.currentPoint.set(C,U),this.segments.push({type:"line",pts:[C,U]}),this}quadraticCurveTo(A,L,C,U){let Q=this.currentPoint.x,X=this.currentPoint.y,Z=Number(A)||0,J=Number(L)||0,K=Number(C)||0,ae=Number(U)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[Q,X]}),this.currentPoint.set(K,ae),this.segments.push({type:"quad",pts:[Q,X,Z,J,K,ae]}),this}bezierCurveTo(A,L,C,U,Q,X){let Z=this.currentPoint.x,J=this.currentPoint.y,K=Number(A)||0,ae=Number(L)||0,ne=Number(C)||0,re=Number(U)||0,me=Number(Q)||0,fe=Number(X)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[Z,J]}),this.currentPoint.set(me,fe),this.segments.push({type:"cubic",pts:[Z,J,K,ae,ne,re,me,fe]}),this}absarc(A,L,C,U,Q,X=!1){return this.absellipse(A,L,C,C,U,Q,X,0)}arc(A,L,C,U,Q,X=!1){return this.absarc(this.currentPoint.x+(Number(A)||0),this.currentPoint.y+(Number(L)||0),C,U,Q,X)}absellipse(A,L,C,U,Q,X,Z=!1,J=0){let K=Number(A)||0,ae=Number(L)||0,ne=Math.max(0,Number(C)||0),re=Math.max(0,Number(U)||0),me=Number(Q)||0,fe=Number(X)||0,ye=Z?1:0,de=Number(J)||0;this.segments.push({type:"arc",pts:[K,ae,ne,re,me,fe,ye,de]});let pe=Math.cos(de),be=Math.sin(de),ve=ne*Math.cos(fe),xe=re*Math.sin(fe);return this.currentPoint.set(K+ve*pe-xe*be,ae+ve*be+xe*pe),this}ellipse(A,L,C,U,Q,X,Z=!1,J=0){return this.absellipse(this.currentPoint.x+(Number(A)||0),this.currentPoint.y+(Number(L)||0),C,U,Q,X,Z,J)}closePath(){if(this.segments.length>0){let A=this.segments[0],L=0,C=0;if(A.type==="arc"){let U=A.pts[0],Q=A.pts[1],X=A.pts[2],Z=A.pts[3],J=A.pts[4],K=A.pts[7],ae=Math.cos(K),ne=Math.sin(K),re=X*Math.cos(J),me=Z*Math.sin(J);L=U+re*ae-me*ne,C=Q+re*ne+me*ae}else L=A.pts[0],C=A.pts[1];Math.hypot(this.currentPoint.x-L,this.currentPoint.y-C)>1e-6&&this.lineTo(L,C)}return this}getPoints(A=12){let L=Math.max(1,Math.min(128,Math.floor(Number(A)||12))),C=[],U=(Q,X)=>{if(C.length>0){let Z=C[C.length-1];if(Math.hypot(Z.x-Q,Z.y-X)<1e-6)return}C.push(new r(Q,X))};for(let Q of this.segments){let X=Q.pts;if(Q.type==="move"||Q.type==="line")U(X[0],X[1]);else if(Q.type==="quad"){let Z=X[0],J=X[1],K=X[2],ae=X[3],ne=X[4],re=X[5];U(Z,J);for(let me=1;me<=L;me++){let fe=me/L,ye=1-fe;U(ye*ye*Z+2*ye*fe*K+fe*fe*ne,ye*ye*J+2*ye*fe*ae+fe*fe*re)}}else if(Q.type==="cubic"){let Z=X[0],J=X[1],K=X[2],ae=X[3],ne=X[4],re=X[5],me=X[6],fe=X[7];U(Z,J);for(let ye=1;ye<=L;ye++){let de=ye/L,pe=1-de,be=pe*pe,ve=de*de;U(be*pe*Z+3*be*de*K+3*pe*ve*ne+ve*de*me,be*pe*J+3*be*de*ae+3*pe*ve*re+ve*de*fe)}}else if(Q.type==="arc"){let Z=X[0],J=X[1],K=X[2],ae=X[3],ne=X[4],re=X[5],me=X[6]!==0,fe=X[7],ye=Math.PI*2,de=re-ne,pe=Math.abs(de)<1e-9;for(;de<0;)de+=ye;for(;de>ye;)de-=ye;de<1e-9&&(de=pe?0:ye),me&&!pe&&(de=de===ye?-ye:de-ye);let be=Math.cos(fe),ve=Math.sin(fe),xe=Math.max(2,L);for(let Ee=0;Ee<=xe;Ee++){let Te=Ee/xe,Pe=ne+Te*de,Ce=K*Math.cos(Pe),ke=ae*Math.sin(Pe);U(Z+Ce*be-ke*ve,J+Ce*ve+ke*be)}}}if(C.length>2){let Q=C[0],X=C[C.length-1];Math.hypot(Q.x-X.x,Q.y-X.y)<1e-6&&C.pop()}return C}getSpacedPoints(A=12){return this.getPoints(A)}clone(){let A=new this.constructor;return A.currentPoint.copy(this.currentPoint),A.segments=this.segments.map(L=>({type:L.type,pts:[...L.pts]})),Array.isArray(this.holes)&&(A.holes=this.holes.map(L=>L.clone())),A}}class p extends v{constructor(A){super(A),this.holes=[]}extractPoints(A=12){return{shape:this.getPoints(A),holes:this.holes.map(L=>L.getPoints(A))}}}function y(R){let A=0,L=R.length;for(let C=0,U=L-1;C<L;U=C++)A+=R[U].x*R[C].y-R[C].x*R[U].y;return A*.5}function M(R,A,L,C,U,Q,X,Z){let J=X-L,K=Z-C,ae=U-L,ne=Q-C,re=R-L,me=A-C,fe=J*J+K*K,ye=J*ae+K*ne,de=J*re+K*me,pe=ae*ae+ne*ne,be=ae*re+ne*me,ve=fe*pe-ye*ye;if(Math.abs(ve)<1e-12)return!1;let xe=1/ve,Ee=(pe*de-ye*be)*xe,Te=(fe*be-ye*de)*xe;return Ee>=-1e-7&&Te>=-1e-7&&Ee+Te<=1+1e-7}function P(R,A){let L=R.slice();y(L)<0&&L.reverse();let C=L.map(J=>new r(J.x,J.y)),U=L.map((J,K)=>K),Q=[];for(let J of A){if(!J||J.length<3)continue;let K=J.slice();y(K)>0&&K.reverse();let ae=[],ne=-1/0,re=0;for(let me=0;me<K.length;me++){let fe=K[me],ye=C.length;C.push(new r(fe.x,fe.y)),ae.push(ye),fe.x>ne&&(ne=fe.x,re=me)}Q.push({pts:K,indices:ae,maxX:ne,maxIdx:re})}Q.sort((J,K)=>K.maxX-J.maxX);let X=(J,K,ae)=>(K.x-J.x)*(ae.y-J.y)-(K.y-J.y)*(ae.x-J.x),Z=(J,K,ae)=>{for(let ne=0;ne<ae.length;ne++){let re=ae[ne],me=ae[(ne+1)%ae.length];if(X(J,K,re)*X(J,K,me)<0&&X(re,me,J)*X(re,me,K)<0)return!0}return!1};for(let J of Q){let K=J.pts[J.maxIdx],ae=K.x,ne=U.length,re=U.map(pe=>C[pe]),me=pe=>Math.hypot(re[pe].x-ae,re[pe].y-K.y),fe=re.map((pe,be)=>be).sort((pe,be)=>+(re[pe].x<ae)-+(re[be].x<ae)||me(pe)-me(be)),ye=fe[0];for(let pe of fe){let be=re[pe],ve=re[(pe+ne-1)%ne],xe=re[(pe+1)%ne],Ee=X(be,xe,K)>=0,Te=X(ve,be,K)>=0;if((X(ve,be,xe)>=0?Ee&&Te:Ee||Te)&&!Z(K,be,re)&&!Q.some(Pe=>Z(K,be,Pe.pts))){ye=pe;break}}let de=[];for(let pe=0;pe<=ye;pe++)de.push(U[pe]);for(let pe=0;pe<=J.indices.length;pe++){let be=J.indices[(J.maxIdx+pe)%J.indices.length];de.push(be)}for(let pe=ye;pe<U.length;pe++)de.push(U[pe]);U=de}return{merged:U.map(J=>C[J]),mergedIndices:U,allVertices:C}}function F(R,A){let L=[],C=R.slice();if(C.length<3)return L;let U=C.length*C.length+64,Q=0;for(;C.length>2&&U-- >0;){let X=C.length,Z=C[(Q+X-1)%X],J=C[Q%X],K=C[(Q+1)%X],ae=A[Z],ne=A[J],re=A[K];if((ne.x-ae.x)*(re.y-ae.y)-(ne.y-ae.y)*(re.x-ae.x)>1e-9){let me=!0,fe=Math.min(ae.x,ne.x,re.x)-1e-7,ye=Math.max(ae.x,ne.x,re.x)+1e-7,de=Math.min(ae.y,ne.y,re.y)-1e-7,pe=Math.max(ae.y,ne.y,re.y)+1e-7;for(let be=0;be<X;be++){let ve=C[be];if(ve===Z||ve===J||ve===K)continue;let xe=A[ve];if(xe.x>=fe&&xe.x<=ye&&xe.y>=de&&xe.y<=pe&&M(xe.x,xe.y,ae.x,ae.y,ne.x,ne.y,re.x,re.y)&&(xe.x-ae.x)*(xe.x-ae.x)+(xe.y-ae.y)*(xe.y-ae.y)>=1e-12&&(xe.x-ne.x)*(xe.x-ne.x)+(xe.y-ne.y)*(xe.y-ne.y)>=1e-12&&(xe.x-re.x)*(xe.x-re.x)+(xe.y-re.y)*(xe.y-re.y)>=1e-12){me=!1;break}}if(me){L.push([Z,J,K]),C.splice(Q%X,1),Q=Math.max(0,Q%X-1);continue}}Q++,Q>=X*2&&(L.push([Z,J,K]),C.splice((Q-1)%X,1),Q=0)}return L}function W(R,A){let L=R instanceof p?R.extractPoints(A):{shape:R.getPoints(A),holes:[]},C=L.shape.length;for(let U of L.holes)C+=U.length;if(C>x)throw new RangeError(`SecurityError: shape point count (${C}) exceeds MAX_SHAPE_POINTS (${x})`);return L}function T(R){let A=1/0,L=1/0,C=-1/0,U=-1/0;for(let Q of R)Q.x<A&&(A=Q.x),Q.y<L&&(L=Q.y),Q.x>C&&(C=Q.x),Q.y>U&&(U=Q.y);return[A,L,Math.max(1e-6,C-A),Math.max(1e-6,U-L)]}class E extends u{constructor(A=new p,L=12){super();let C=Array.isArray(A)?A:[A],U=[],Q=[],X=[],Z=[];for(let J of C){if(!(J instanceof v))continue;let K=W(J,L);if(K.shape.length<3)continue;let{mergedIndices:ae,allVertices:ne}=P(K.shape,K.holes),re=F(ae,ne),me=U.length/3,[fe,ye,de,pe]=T(ne);for(let be of ne)U.push(be.x,be.y,0),Q.push(0,0,1),X.push((be.x-fe)/de,(be.y-ye)/pe);for(let[be,ve,xe]of re)Z.push(me+be,me+ve,me+xe)}S(this,U,Q,X,Z)}}function S(R,A,L,C,U){return R.setAttribute("position",new a(A,3)),R.setAttribute("normal",new a(L,3)),R.setAttribute("uv",new a(C,2)),R.setIndex(U),R}function O(R){let A=R.length,L=[];for(let C=0;C<A;C++){let U=R[(C+A-1)%A],Q=R[C],X=R[(C+1)%A],Z=Q.x-U.x,J=Q.y-U.y,K=Math.hypot(Z,J)||1;Z/=K,J/=K;let ae=X.x-Q.x,ne=X.y-Q.y,re=Math.hypot(ae,ne)||1;ae/=re,ne/=re;let me=J,fe=-Z,ye=ne,de=-ae,pe=me+ye,be=fe+de,ve=Math.hypot(pe,be);if(ve>1e-6){pe/=ve,be/=ve;let xe=Math.max(.35,pe*me+be*fe);L.push(new r(pe/xe,be/xe))}else L.push(new r(me,fe))}return L}class k extends u{constructor(A=new p,L={}){super();let C=Array.isArray(A)?A:[A],U=Math.max(1,Math.min(64,Math.floor(b(L.curveSegments,12)))),Q=b(L.depth??L.amount,1),X=Math.max(1,Math.min(32,Math.floor(b(L.steps,1)))),Z=!!(L.bevelEnabled??!1),J=Z?Math.max(0,b(L.bevelThickness,.06)):0,K=Z?Math.max(0,b(L.bevelSize,J*.8)):0,ae=Z?b(L.bevelOffset,0):0,ne=Z?Math.max(1,Math.min(8,Math.floor(b(L.bevelSegments,2)))):0,re=[],me=[],fe=[],ye=[];for(let de of C){if(!(de instanceof v))continue;let pe=W(de,U);if(pe.shape.length<3)continue;let be=pe.shape.slice();y(be)<0&&be.reverse();let ve=[];for(let _e of pe.holes){if(_e.length<3)continue;let Le=_e.slice();y(Le)>0&&Le.reverse(),ve.push(Le)}let{mergedIndices:xe,allVertices:Ee}=P(be,ve),Te=F(xe,Ee),Pe=[be,...ve],Ce=[];for(let _e of Pe){let Le=O(_e);for(let qe of Le)Ce.push(qe)}let[ke,tt,Ze,pt]=T(Ee);for(let[_e,Le]of[[-J,-1],[Q+J,1]]){let qe=re.length/3;for(let We=0;We<Ee.length;We++){let Ue=Ee[We],He=Ce[We]??new r(0,0),st=Ue.x+He.x*ae,Je=Ue.y+He.y*ae;re.push(st,Je,_e),me.push(0,0,Le),fe.push((st-ke)/Ze,(Je-tt)/pt)}for(let[We,Ue,He]of Te)ye.push(qe+We,qe+(Le<0?He:Ue),qe+(Le<0?Ue:He))}let Fe=[];if(Z&&ne>0)for(let _e=0;_e<ne;_e++){let Le=_e/ne*Math.PI/2;Fe.push({z:-J*Math.cos(Le),expand:ae+K*Math.sin(Le)})}for(let _e=0;_e<=X;_e++){let Le=_e/X;Fe.push({z:Le*Q,expand:ae+K})}if(Z&&ne>0)for(let _e=1;_e<=ne;_e++){let Le=_e/ne*Math.PI/2;Fe.push({z:Q+J*Math.sin(Le),expand:ae+K*Math.cos(Le)})}let at=0;for(let _e of Pe){let Le=_e.length;for(let qe=0;qe<Fe.length-1;qe++){let We=Fe[qe],Ue=Fe[qe+1];for(let He=0;He<Le;He++){let st=(He+1)%Le,Je=_e[He],ot=_e[st],ht=Ce[at+He],ct=Ce[at+st],dt=Je.x+ht.x*We.expand,Mt=Je.y+ht.y*We.expand,jt=ot.x+ct.x*We.expand,qt=ot.y+ct.y*We.expand,qi=ot.x+ct.x*Ue.expand,Yi=ot.y+ct.y*Ue.expand,Ut=Je.x+ht.x*Ue.expand,Ot=Je.y+ht.y*Ue.expand,Wt=jt-dt,kt=qt-Mt,sl=Ut-dt,al=Ot-Mt,bn=Ue.z-We.z,Kt=kt*bn,Yt=-Wt*bn,Zt=Wt*al-kt*sl,pn=Math.hypot(Kt,Yt,Zt)||1;Kt/=pn,Yt/=pn,Zt/=pn;let vi=re.length/3;re.push(dt,Mt,We.z,jt,qt,We.z,qi,Yi,Ue.z,Ut,Ot,Ue.z),me.push(Kt,Yt,Zt,Kt,Yt,Zt,Kt,Yt,Zt,Kt,Yt,Zt);let Ca=He/Le,Da=(He+1)/Le,so=qe/(Fe.length-1),Po=(qe+1)/(Fe.length-1);fe.push(Ca,so,Da,so,Da,Po,Ca,Po),ye.push(vi,vi+1,vi+2,vi,vi+2,vi+3)}}at+=Le}}S(this,re,me,fe,ye)}}function w(R){return{x:R.x,y:R.y,z:R.z,nx:R.nx,ny:R.ny,nz:R.nz,u:R.u,v:R.v}}function ie(R){return{x:R.x,y:R.y,z:R.z,nx:-R.nx,ny:-R.ny,nz:-R.nz,u:R.u,v:R.v}}function oe(R,A,L){let C=R.nx+(A.nx-R.nx)*L,U=R.ny+(A.ny-R.ny)*L,Q=R.nz+(A.nz-R.nz)*L,X=Math.hypot(C,U,Q)||1;return{x:R.x+(A.x-R.x)*L,y:R.y+(A.y-R.y)*L,z:R.z+(A.z-R.z)*L,nx:C/X,ny:U/X,nz:Q/X,u:R.u+(A.u-R.u)*L,v:R.v+(A.v-R.v)*L}}function I(R){if(R.length<3)return null;let A=R[0],L=R[1],C=R[2],U=L.x-A.x,Q=L.y-A.y,X=L.z-A.z,Z=C.x-A.x,J=C.y-A.y,K=C.z-A.z,ae=Q*K-X*J,ne=X*Z-U*K,re=U*J-Q*Z,me=Math.hypot(ae,ne,re);if(me<1e-9)return null;ae/=me,ne/=me,re/=me;let fe=ae*A.x+ne*A.y+re*A.z;return{vertices:R,nx:ae,ny:ne,nz:re,w:fe}}function H(R){R.vertices.reverse();for(let A=0;A<R.vertices.length;A++)R.vertices[A]=ie(R.vertices[A]);R.nx=-R.nx,R.ny=-R.ny,R.nz=-R.nz,R.w=-R.w}let N=1e-5,z=0,ue=1,ce=2,B=3;function $(R,A,L,C,U,Q,X,Z,J){let K=0,ae=[];for(let ne=0;ne<U.vertices.length;ne++){let re=U.vertices[ne],me=R*re.x+A*re.y+L*re.z-C,fe=me<-N?ce:me>N?ue:z;K|=fe,ae.push(fe)}switch(K){case z:{R*U.nx+A*U.ny+L*U.nz>0?Q.push(U):X.push(U);break}case ue:Z.push(U);break;case ce:J.push(U);break;case B:{let ne=[],re=[],me=U.vertices.length;for(let be=0;be<me;be++){let ve=(be+1)%me,xe=ae[be],Ee=ae[ve],Te=U.vertices[be],Pe=U.vertices[ve];if(xe!==ce&&ne.push(Te),xe!==ue&&re.push(xe!==ce?w(Te):Te),(xe|Ee)===B){let Ce=Pe.x-Te.x,ke=Pe.y-Te.y,tt=Pe.z-Te.z,Ze=R*Ce+A*ke+L*tt,pt=Math.abs(Ze)>1e-12?(C-(R*Te.x+A*Te.y+L*Te.z))/Ze:.5,Fe=oe(Te,Pe,Math.max(0,Math.min(1,pt)));ne.push(Fe),re.push(w(Fe))}}let{nx:fe,ny:ye,nz:de,w:pe}=U;ne.length>=3&&Z.push({vertices:ne,nx:fe,ny:ye,nz:de,w:pe}),re.length>=3&&J.push({vertices:re,nx:fe,ny:ye,nz:de,w:pe});break}default:break}}class _{constructor(A,L=0){this.nx=0,this.ny=0,this.nz=0,this.w=0,this.hasPlane=!1,this.polygons=[],this.front=null,this.back=null,A&&A.length>0&&this.build(A,L)}invert(){for(let L=0;L<this.polygons.length;L++)H(this.polygons[L]);this.nx=-this.nx,this.ny=-this.ny,this.nz=-this.nz,this.w=-this.w,this.front&&this.front.invert(),this.back&&this.back.invert();let A=this.front;this.front=this.back,this.back=A}clipPolygons(A,L=0){if(!this.hasPlane||A.length===0)return A.slice();if(L>=f)throw new RangeError(`SecurityError: CSG BSP depth exceeds MAX_BSP_DEPTH (${f})`);let C=[],U=[];for(let Q=0;Q<A.length;Q++)$(this.nx,this.ny,this.nz,this.w,A[Q],C,U,C,U);return this.front&&C.length>0&&(C=this.front.clipPolygons(C,L+1)),this.back?U=U.length>0?this.back.clipPolygons(U,L+1):[]:U=[],C.concat(U)}clipTo(A,L=0){this.polygons.length>0&&(this.polygons=A.clipPolygons(this.polygons,0)),L<f&&(this.front&&this.front.clipTo(A,L+1),this.back&&this.back.clipTo(A,L+1))}allPolygons(A=[]){for(let L=0;L<this.polygons.length;L++)A.push(this.polygons[L]);return this.front&&this.front.allPolygons(A),this.back&&this.back.allPolygons(A),A}build(A,L=0){if(!A.length)return;if(!this.hasPlane){let Q=A[A.length>>1];this.nx=Q.nx,this.ny=Q.ny,this.nz=Q.nz,this.w=Q.w,this.hasPlane=!0}if(L>=f)throw new RangeError(`SecurityError: CSG BSP depth exceeds MAX_BSP_DEPTH (${f})`);let C=[],U=[];for(let Q=0;Q<A.length;Q++)$(this.nx,this.ny,this.nz,this.w,A[Q],this.polygons,this.polygons,C,U);C.length>0&&(this.front||(this.front=new _),this.front.build(C,L+1)),U.length>0&&(this.back||(this.back=new _),this.back.build(U,L+1))}}function G(R,A){if(!A&&R._csgPolygons)return R._csgPolygons;let L=R.attributes.position;if(!L||L.count===0)return[];let C=R.attributes.normal,U=R.attributes.uv,Q=R.index?R.index.array:null,X=Math.floor(Q?Q.length/3:L.count/3);if(X>d)throw new RangeError(`SecurityError: CSG input triangle count (${X}) exceeds MAX_CSG_TRIANGLES (${d})`);let Z=A?A.elements:null,J=Z?Z[0]*(Z[5]*Z[10]-Z[9]*Z[6])-Z[4]*(Z[1]*Z[10]-Z[9]*Z[2])+Z[8]*(Z[1]*Z[6]-Z[5]*Z[2])<0:!1,K=Z?new l().getNormalMatrix(A).elements:null,ae=re=>{let me=L.getX(re),fe=L.getY(re),ye=L.getZ(re),de=C?C.getX(re):NaN,pe=C?C.getY(re):NaN,be=C?C.getZ(re):NaN;if(Z&&K){let Ee=Z[0]*me+Z[4]*fe+Z[8]*ye+Z[12],Te=Z[1]*me+Z[5]*fe+Z[9]*ye+Z[13],Pe=Z[2]*me+Z[6]*fe+Z[10]*ye+Z[14];me=Ee,fe=Te,ye=Pe;let Ce=K[0]*de+K[3]*pe+K[6]*be,ke=K[1]*de+K[4]*pe+K[7]*be,tt=K[2]*de+K[5]*pe+K[8]*be,Ze=Math.hypot(Ce,ke,tt)||1;de=Ce/Ze,pe=ke/Ze,be=tt/Ze}let ve=U?U.getX(re):0,xe=U?U.getY(re):0;return{x:me,y:fe,z:ye,nx:de,ny:pe,nz:be,u:ve,v:xe}},ne=[];for(let re=0;re<X;re++){let me=Q?Q[re*3]:re*3,fe=Q?Q[re*3+1]:re*3+1,ye=Q?Q[re*3+2]:re*3+2,de=I(J?[ae(me),ae(ye),ae(fe)]:[ae(me),ae(fe),ae(ye)]);de&&ne.push(de)}return ne}function j(R){let A=[],L=[],C=[],U=[];for(let X of R){let Z=X.vertices;if(Z.length<3)continue;let J=A.length/3;for(let K of Z)A.push(K.x,K.y,K.z),Number.isFinite(K.nx)&&K.nx*K.nx+K.ny*K.ny+K.nz*K.nz>.5?L.push(K.nx,K.ny,K.nz):L.push(X.nx,X.ny,X.nz),C.push(K.u,K.v);for(let K=1;K<Z.length-1;K++)U.push(J,J+K,J+K+1)}let Q=S(new u,A,L,C,U);return Q._csgPolygons=R,Q}function q(R,A,L){if(R.length+A.length>d)throw new RangeError(`SecurityError: Combined CSG triangle count (${R.length+A.length}) exceeds MAX_CSG_TRIANGLES (${d})`);if(R.length===0)return L==="union"?A:[];if(A.length===0)return L==="intersect"?[]:R;let C=1/0,U=1/0,Q=1/0,X=-1/0,Z=-1/0,J=-1/0;for(let me=0;me<A.length;me++){let fe=A[me].vertices;for(let ye=0;ye<fe.length;ye++){let de=fe[ye];de.x<C&&(C=de.x),de.y<U&&(U=de.y),de.z<Q&&(Q=de.z),de.x>X&&(X=de.x),de.y>Z&&(Z=de.y),de.z>J&&(J=de.z)}}C-=1e-4,U-=1e-4,Q-=1e-4,X+=1e-4,Z+=1e-4,J+=1e-4;let K=[],ae=[];for(let me=0;me<R.length;me++){let fe=R[me],ye=fe.vertices,de=1/0,pe=1/0,be=1/0,ve=-1/0,xe=-1/0,Ee=-1/0;for(let Te=0;Te<ye.length;Te++){let Pe=ye[Te];Pe.x<de&&(de=Pe.x),Pe.y<pe&&(pe=Pe.y),Pe.z<be&&(be=Pe.z),Pe.x>ve&&(ve=Pe.x),Pe.y>xe&&(xe=Pe.y),Pe.z>Ee&&(Ee=Pe.z)}ve<C||de>X||xe<U||pe>Z||Ee<Q||be>J?ae.push(fe):K.push(fe)}if(K.length===0)return L==="union"?R.concat(A):L==="subtract"?R:[];let ne=new _(K),re=new _(A);return L==="union"?(ne.clipTo(re),re.clipTo(ne),re.invert(),re.clipTo(ne),re.invert(),ne.build(re.allPolygons()),ae.concat(ne.allPolygons())):L==="subtract"?(ne.invert(),ne.clipTo(re),re.clipTo(ne),re.invert(),re.clipTo(ne),re.invert(),ne.build(re.allPolygons()),ne.invert(),ae.concat(ne.allPolygons())):(ne.invert(),re.clipTo(ne),re.invert(),ne.clipTo(re),re.clipTo(ne),ne.build(re.allPolygons()),ne.invert(),ne.allPolygons())}function D(R,A,L,C=null,U=null){let Q=G(R,C),X=G(A,U);return j(q(Q,X,L))}function Y(R,A,L){let C=R instanceof c||!!R?.isMesh,U=A instanceof c||!!A?.isMesh,Q=C?R.geometry:R,X=U?A.geometry:A,Z=null;if(U)if(A.updateMatrix(),C){R.updateMatrix();let ne=new s().makeScale(1/(R.scale.x||1),1/(R.scale.y||1),1/(R.scale.z||1)),re=Math.hypot(R.quaternion.x,R.quaternion.y,R.quaternion.z,R.quaternion.w)||1,me=new s().compose(new i(0,0,0),new n(-R.quaternion.x/re,-R.quaternion.y/re,-R.quaternion.z/re,R.quaternion.w/re),new i(1,1,1)),fe=new s().makeTranslation(-R.position.x,-R.position.y,-R.position.z);Z=ne.multiply(me).multiply(fe).multiply(A.matrix)}else Z=A.matrix;let J=D(Q,X,L,null,Z),K=C?R.material:new m,ae=new c(J,K);return C&&(ae.position.copy(R.position),ae.quaternion.copy(R.quaternion),ae.scale.copy(R.scale),ae.name=R.name),ae}let te={toGeometry:D,subtract(R,A){return Y(R,A,"subtract")},union(R,A){return Y(R,A,"union")},intersect(R,A){return Y(R,A,"intersect")}},se={0:[[[.15,0],[.85,0],[.85,1],[.15,1],[.15,0]]],1:[[[.3,.8],[.5,1],[.5,0]],[[.2,0],[.8,0]]],2:[[[.15,.8],[.3,1],[.7,1],[.85,.8],[.85,.55],[.15,0],[.85,0]]],3:[[[.15,.85],[.3,1],[.75,1],[.85,.75],[.5,.5],[.85,.25],[.75,0],[.3,0],[.15,.15]]],4:[[[.7,0],[.7,1],[.15,.35],[.9,.35]]],5:[[[.85,1],[.2,1],[.15,.55],[.75,.55],[.85,.3],[.75,0],[.2,0]]],6:[[[.8,.9],[.5,1],[.15,.7],[.15,.15],[.5,0],[.85,.2],[.85,.45],[.5,.55],[.15,.45]]],7:[[[.15,1],[.85,1],[.35,0]]],8:[[[.2,.5],[.15,.75],[.3,1],[.7,1],[.85,.75],[.8,.5],[.2,.5],[.15,.2],[.3,0],[.7,0],[.85,.2],[.8,.5]]],9:[[[.85,.55],[.5,.45],[.15,.55],[.15,.85],[.5,1],[.85,.85],[.85,.2],[.5,0],[.2,.1]]],A:[[[.1,0],[.5,1],[.9,0]],[[.25,.35],[.75,.35]]],B:[[[.15,0],[.15,1],[.7,1],[.85,.75],[.7,.5],[.15,.5]],[[.7,.5],[.85,.25],[.7,0],[.15,0]]],C:[[[.85,.8],[.65,1],[.3,1],[.15,.75],[.15,.25],[.3,0],[.65,0],[.85,.2]]],D:[[[.15,0],[.15,1],[.65,1],[.85,.75],[.85,.25],[.65,0],[.15,0]]],E:[[[.85,1],[.15,1],[.15,0],[.85,0]],[[.15,.5],[.7,.5]]],F:[[[.85,1],[.15,1],[.15,0]],[[.15,.5],[.7,.5]]],G:[[[.85,.8],[.65,1],[.3,1],[.15,.75],[.15,.25],[.3,0],[.85,0],[.85,.45],[.55,.45]]],H:[[[.15,0],[.15,1]],[[.85,0],[.85,1]],[[.15,.5],[.85,.5]]],I:[[[.25,1],[.75,1]],[[.5,1],[.5,0]],[[.25,0],[.75,0]]],J:[[[.8,1],[.8,.25],[.6,0],[.3,0],[.15,.25]]],K:[[[.15,0],[.15,1]],[[.85,1],[.15,.45],[.85,0]]],L:[[[.15,1],[.15,0],[.85,0]]],M:[[[.1,0],[.1,1],[.5,.35],[.9,1],[.9,0]]],N:[[[.15,0],[.15,1],[.85,0],[.85,1]]],O:[[[.3,0],[.7,0],[.85,.25],[.85,.75],[.7,1],[.3,1],[.15,.75],[.15,.25],[.3,0]]],P:[[[.15,0],[.15,1],[.7,1],[.85,.75],[.7,.5],[.15,.5]]],Q:[[[.3,0],[.7,0],[.85,.25],[.85,.75],[.7,1],[.3,1],[.15,.75],[.15,.25],[.3,0]],[[.55,.3],[.9,-.05]]],R:[[[.15,0],[.15,1],[.7,1],[.85,.75],[.7,.5],[.15,.5]],[[.55,.5],[.85,0]]],S:[[[.85,.85],[.65,1],[.3,1],[.15,.75],[.85,.25],[.7,0],[.3,0],[.15,.15]]],T:[[[.1,1],[.9,1]],[[.5,1],[.5,0]]],U:[[[.15,1],[.15,.25],[.35,0],[.65,0],[.85,.25],[.85,1]]],V:[[[.1,1],[.5,0],[.9,1]]],W:[[[.05,1],[.25,0],[.5,.65],[.75,0],[.95,1]]],X:[[[.15,1],[.85,0]],[[.85,1],[.15,0]]],Y:[[[.15,1],[.5,.5],[.85,1]],[[.5,.5],[.5,0]]],Z:[[[.15,1],[.85,1],[.15,0],[.85,0]]],".":[[[.45,0],[.55,0],[.55,.12],[.45,.12],[.45,0]]],",":[[[.5,.15],[.4,-.1]]],":":[[[.45,.1],[.55,.1]],[[.45,.7],[.55,.7]]],"-":[[[.2,.5],[.8,.5]]],"+":[[[.2,.5],[.8,.5]],[[.5,.2],[.5,.8]]],"=":[[[.2,.35],[.8,.35]],[[.2,.65],[.8,.65]]],"/":[[[.2,0],[.8,1]]],"!":[[[.5,1],[.5,.28]],[[.5,.1],[.5,0]]],"?":[[[.2,.8],[.35,1],[.7,1],[.85,.75],[.5,.45],[.5,.28]],[[.5,.1],[.5,0]]],"(":[[[.65,1],[.35,.65],[.35,.35],[.65,0]]],")":[[[.35,1],[.65,.65],[.65,.35],[.35,0]]],"%":[[[.2,0],[.8,1]],[[.2,.8],[.35,.8],[.35,.95],[.2,.95],[.2,.8]],[[.65,.05],[.8,.05],[.8,.2],[.65,.2],[.65,.05]]],"#":[[[.32,0],[.32,1]],[[.68,0],[.68,1]],[[.12,.35],[.88,.35]],[[.12,.65],[.88,.65]]],$:[[[.8,.8],[.6,.92],[.3,.92],[.18,.72],[.82,.28],[.7,.08],[.4,.08],[.2,.2]],[[.5,1],[.5,0]]],_:[[[.1,0],[.9,0]]],"[":[[[.65,1],[.3,1],[.3,0],[.65,0]]],"]":[[[.35,1],[.7,1],[.7,0],[.35,0]]],"<":[[[.75,.85],[.25,.5],[.75,.15]]],">":[[[.25,.85],[.75,.5],[.25,.15]]],"*":[[[.5,.2],[.5,.8]],[[.2,.35],[.8,.65]],[[.2,.65],[.8,.35]]],"\\":[[[.2,1],[.8,0]]]};class le extends u{constructor(A="",L={}){super();let C=String(A??"").slice(0,g),U=Math.max(.005,Math.min(100,b(L.size,.2))),Q=!!(L.bevelEnabled??!1),X=Q?Math.max(0,Math.min(2,b(L.bevelThickness,U*.04))):0,Z=Q?Math.max(0,Math.min(2,b(L.bevelSize,U*.03))):0,J=Math.max(.001,Math.min(20,b(L.depth??L.height,U*.2)))+X*2,K=U*.085+Z,ae=U*.68,ne=U*.82,re=[],me=[],fe=[],ye=[],de=(ve,xe,Ee,Te,Pe,Ce,ke)=>{let tt=Ee-ve,Ze=Te-xe,pt=Math.hypot(tt,Ze),Fe=1,at=0;pt>1e-6&&(Fe=tt/pt,at=Ze/pt);let _e=-at*Pe,Le=Fe*Pe,qe=Fe*Pe*.6,We=at*Pe*.6,Ue=ve-qe+_e,He=xe-We+Le,st=ve-qe-_e,Je=xe-We-Le,ot=Ee+qe-_e,ht=Te+We-Le,ct=Ee+qe+_e,dt=Te+We+Le,Mt=(jt,qt,qi,Yi,Ut,Ot,Wt)=>{let kt=re.length/3;re.push(jt[0],jt[1],jt[2],qt[0],qt[1],qt[2],qi[0],qi[1],qi[2],Yi[0],Yi[1],Yi[2]),me.push(Ut,Ot,Wt,Ut,Ot,Wt,Ut,Ot,Wt,Ut,Ot,Wt),fe.push(0,0,1,0,1,1,0,1),ye.push(kt,kt+1,kt+2,kt,kt+2,kt+3)};Mt([Ue,He,ke],[st,Je,ke],[ot,ht,ke],[ct,dt,ke],0,0,1),Mt([st,Je,Ce],[Ue,He,Ce],[ct,dt,Ce],[ot,ht,Ce],0,0,-1),Mt([Ue,He,Ce],[st,Je,Ce],[st,Je,ke],[Ue,He,ke],-Fe,-at,0),Mt([ot,ht,Ce],[ct,dt,Ce],[ct,dt,ke],[ot,ht,ke],Fe,at,0),Mt([st,Je,Ce],[ot,ht,Ce],[ot,ht,ke],[st,Je,ke],at,-Fe,0),Mt([ct,dt,Ce],[Ue,He,Ce],[Ue,He,ke],[ct,dt,ke],-at,Fe,0)},pe=0,be=0;for(let ve=0;ve<C.length;ve++){let xe=C[ve];if(xe===`
|
|
17
|
-
`){pe=0,be-=U*1.35;continue}if(xe===" "||xe===" "){pe+=ne*(xe===" "?.75:3);continue}if(xe==="\r")continue;let Ee=xe.toUpperCase(),Te=xe!==Ee&&xe>="a"&&xe<="z",Pe=se[Ee]??se["?"],Ce=Te?U*.76:U,ke=Te?ae*.88:ae;for(let tt of Pe)for(let Ze=0;Ze<tt.length-1;Ze++){let pt=tt[Ze],Fe=tt[Ze+1];de(pe+pt[0]*ke,be+pt[1]*Ce,pe+Fe[0]*ke,be+Fe[1]*Ce,K,-J*.5,J*.5)}pe+=Te?ne*.88:ne}S(this,re,me,fe,ye),L.center!==!1?this.center():this.computeBoundingBox()}}function V(R){if(!R)return;let A=R,L=R.userData?.xr?.text??R.userData?.xr?.label??R.userData?.xr?.title??R.userData?.xr?.caption??R.userData?.xr?.spatialLabel;if(L!=null&&L!==!1){let U=A.geometry?.attributes?.position;if((!U||U.count===0)&&R.userData._textApplied!==!0){let Q="",X=.08,Z=.015,J;if(typeof L=="string"||typeof L=="number")Q=String(L);else if(typeof L=="object"){let K=L;Q=String(K.text??K.value??""),K.size!==void 0&&(X=Number(K.size)||.08),(K.depth!==void 0||K.height!==void 0)&&(Z=Number(K.depth??K.height)||X*.2),(typeof K.color=="string"||typeof K.color=="number")&&(J=K.color)}Q.trim().length>0&&(A.geometry=new le(Q,{size:X,depth:Z}),R.userData._textApplied=!0,A.material instanceof h?J!==void 0&&R.userData._autoTextColorApplied!==!0&&(A.material.color=new o(J),R.userData._autoTextColorApplied=!0):A.material=new m({color:J??16317180}))}}let C=R.userData?.csg;if(C&&typeof C=="object"&&R.userData._csgApplied!==!0&&A.geometry instanceof u&&A.geometry.attributes.position?.count>0){R.userData._csgApplied=!0;let U=Array.isArray(C)?C:[C],Q=A.geometry;for(let X of U){if(!X||typeof X!="object")continue;let Z=X,J=String(Z.op??Z.operation??"subtract"),K=J==="union"||J==="intersect"?J:"subtract",ae=Z.target??Z.mesh??Z.geometry;if(ae instanceof c||ae instanceof u)try{let ne=K==="union"?te.union(A,ae):K==="intersect"?te.intersect(A,ae):te.subtract(A,ae);A.geometry!==Q&&A.geometry.dispose?.(),A.geometry=ne.geometry}catch(ne){typeof console<"u"&&console.warn("[three-live] userData.csg skipped:",ne)}}}}let ee={Path:v,Shape:p,ShapeGeometry:E,ExtrudeGeometry:k,TextGeometry:le,CSG:te,MAX_CSG_TRIANGLES:d,MAX_BSP_DEPTH:f,MAX_TEXT_GEOMETRY_CHARS:g,MAX_SHAPE_POINTS:x,materializeDeclarativeGeometry:V};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,ee),t._cadMaterialize=V,t.materializeDeclarativeGeometry=R=>{t._cadMaterialize?.(R),t._lodMaterialize?.(R)}),ee}var Ti={name:"cad",onRegister(){Qt(nr);let e=Ae(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t&&nr(t,e)}};function Se(){let e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function rr(e,t,r,i,n){let s=1/Math.tan(t/2);e.fill(0),e[0]=s/r,e[5]=s,e[11]=-1;let l=1/(i-n);return e[10]=(n+i)*l,e[14]=2*n*i*l,e}function Jt(e,t,r,i){let[n,s,l]=t,[o,a,u]=i,[h,m,c]=r,d=n-h,f=s-m,g=l-c,x=Math.hypot(d,f,g);x<=1e-5?(d=0,f=0,g=1):(d/=x,f/=x,g/=x);let b=a*g-u*f,v=u*d-o*g,p=o*f-a*d;x=Math.hypot(b,v,p),x<=1e-5?(b=0,v=0,p=0):(b/=x,v/=x,p/=x);let y=f*p-g*v,M=g*b-d*p,P=d*v-f*b;return x=Math.hypot(y,M,P),x<=1e-5?(y=0,M=0,P=0):(y/=x,M/=x,P/=x),e[0]=b,e[1]=y,e[2]=d,e[3]=0,e[4]=v,e[5]=M,e[6]=f,e[7]=0,e[8]=p,e[9]=P,e[10]=g,e[11]=0,e[12]=-(b*n+v*s+p*l),e[13]=-(y*n+M*s+P*l),e[14]=-(d*n+f*s+g*l),e[15]=1,e}function Ie(e,t,r){let i=t[0],n=t[1],s=t[2],l=t[3],o=t[4],a=t[5],u=t[6],h=t[7],m=t[8],c=t[9],d=t[10],f=t[11],g=t[12],x=t[13],b=t[14],v=t[15],p=r[0],y=r[1],M=r[2],P=r[3];return e[0]=p*i+y*o+M*m+P*g,e[1]=p*n+y*a+M*c+P*x,e[2]=p*s+y*u+M*d+P*b,e[3]=p*l+y*h+M*f+P*v,p=r[4],y=r[5],M=r[6],P=r[7],e[4]=p*i+y*o+M*m+P*g,e[5]=p*n+y*a+M*c+P*x,e[6]=p*s+y*u+M*d+P*b,e[7]=p*l+y*h+M*f+P*v,p=r[8],y=r[9],M=r[10],P=r[11],e[8]=p*i+y*o+M*m+P*g,e[9]=p*n+y*a+M*c+P*x,e[10]=p*s+y*u+M*d+P*b,e[11]=p*l+y*h+M*f+P*v,p=r[12],y=r[13],M=r[14],P=r[15],e[12]=p*i+y*o+M*m+P*g,e[13]=p*n+y*a+M*c+P*x,e[14]=p*s+y*u+M*d+P*b,e[15]=p*l+y*h+M*f+P*v,e}function Tt(e,t,r,i){let n=t[0],s=t[1],l=t[2],o=t[3],a=n+n,u=s+s,h=l+l,m=n*a,c=n*u,d=n*h,f=s*u,g=s*h,x=l*h,b=o*a,v=o*u,p=o*h,y=i[0],M=i[1],P=i[2];return e[0]=(1-(f+x))*y,e[1]=(c+p)*y,e[2]=(d-v)*y,e[3]=0,e[4]=(c-p)*M,e[5]=(1-(m+x))*M,e[6]=(g+b)*M,e[7]=0,e[8]=(d+v)*P,e[9]=(g-b)*P,e[10]=(1-(m+f))*P,e[11]=0,e[12]=r[0],e[13]=r[1],e[14]=r[2],e[15]=1,e}function Xe(e,t,r=0){let i=t[0],n=t[1],s=t[2],l=t[4],o=t[5],a=t[6],u=t[8],h=t[9],m=t[10],c=m*o-a*h,d=-m*l+a*u,f=h*l-o*u,g=i*c+n*d+s*f;return!g||r>0&&(!Number.isFinite(g)||Math.abs(g)<=r)||(g=1/g,e[0]=c*g,e[1]=d*g,e[2]=f*g,e[3]=(-m*n+s*h)*g,e[4]=(m*i-s*u)*g,e[5]=(-h*i+n*u)*g,e[6]=(a*n-s*o)*g,e[7]=(-a*i+s*l)*g,e[8]=(o*i-n*l)*g),e}function en(e,t){let r=t[0],i=t[1],n=t[2],s=t[3],l=t[4],o=t[5],a=t[6],u=t[7],h=t[8],m=t[9],c=t[10],d=t[11],f=t[12],g=t[13],x=t[14],b=t[15],v=r*o-i*l,p=r*a-n*l,y=r*u-s*l,M=i*a-n*o,P=i*u-s*o,F=n*u-s*a,W=h*g-m*f,T=h*x-c*f,E=h*b-d*f,S=m*x-c*g,O=m*b-d*g,k=c*b-d*x,w=v*k-p*O+y*S+M*E-P*T+F*W;return w?(w=1/w,e[0]=(o*k-a*O+u*S)*w,e[1]=(n*O-i*k-s*S)*w,e[2]=(g*F-x*P+b*M)*w,e[3]=(c*P-m*F-d*M)*w,e[4]=(a*E-l*k-u*T)*w,e[5]=(r*k-n*E+s*T)*w,e[6]=(x*y-f*F-b*p)*w,e[7]=(h*F-c*y+d*p)*w,e[8]=(l*O-o*E+u*W)*w,e[9]=(i*E-r*O-s*W)*w,e[10]=(f*P-g*y+b*v)*w,e[11]=(m*y-h*P-d*v)*w,e[12]=(o*T-l*S-a*W)*w,e[13]=(r*S-i*T+n*W)*w,e[14]=(g*p-f*M-x*v)*w,e[15]=(h*M-m*p+c*v)*w,e):null}function Ai(e,t,r,i,n){let s=n[0]*t+n[4]*r+n[8]*i+n[12],l=n[1]*t+n[5]*r+n[9]*i+n[13],o=n[2]*t+n[6]*r+n[10]*i+n[14],a=n[3]*t+n[7]*r+n[11]*i+n[15],u=a!==0?1/a:1;e[0]=s*u,e[1]=l*u,e[2]=o*u}function Go(e,t,r,i,n,s,l,o,a,u,h,m,c,d,f,g,x=0){let b=u-l,v=h-o,p=m-a,y=c-l,M=d-o,P=f-a,F=n*P-s*M,W=s*y-i*P,T=i*M-n*y,E=b*F+v*W+p*T;if(E>-1e-7&&E<1e-7)return!1;let S=1/E,O=e-l,k=t-o,w=r-a,ie=S*(O*F+k*W+w*T);if(ie<-x||ie>1+x)return!1;let oe=k*p-w*v,I=w*b-O*p,H=O*v-k*b,N=S*(i*oe+n*I+s*H);if(N<-x||ie+N>1+x)return!1;let z=S*(y*oe+M*I+P*H);if(z>1e-4&&z<g.distance){g.distance=z,g.point=[e+i*z,t+n*z,r+s*z];let ue=v*P-p*M,ce=p*y-b*P,B=b*M-v*y,$=Math.hypot(ue,ce,B)||1;return g.normal=[ue/$,ce/$,B/$],!0}return!1}function Ft(e,t){let r=Array.isArray(e?.nodes)?e.nodes.length:0,i=[];for(let h=0;h<r;h++)i.push(Se());if(r===0)return i;let n=new Set;for(let h of e.nodes)if(Array.isArray(h.children))for(let m of h.children)n.add(m);let s=new Set,l=128,o=(h,m,c=0)=>{if(c>l||h<0||h>=r||s.has(h))return;s.add(h);let d=e.nodes[h];if(!d)return;let f=Se();if(t&&t[h])f.set(t[h]);else if(d.matrix&&d.matrix.length===16)f.set(d.matrix);else{let x=d.translation||[0,0,0],b=d.rotation||[0,0,0,1],v=d.scale||[1,1,1];Tt(f,b,x,v)}let g=i[h];if(m?Ie(g,m,f):g.set(f),Array.isArray(d.children))for(let x of d.children)typeof x=="number"&&o(x,g,c+1)},a=[],u=e.scenes&&e.scenes[e.scene!==void 0?e.scene:0];if(u&&Array.isArray(u.nodes))a.push(...u.nodes);else for(let h=0;h<r;h++)n.has(h)||a.push(h);for(let h of a)o(h,null);for(let h=0;h<r;h++)!n.has(h)&&!a.includes(h)&&o(h,null);return i}function Ei(e,t){function r(a,u,h,m){let c=typeof a=="number"?a:Number(a);return Number.isFinite(c)?Math.max(u,Math.min(h,c)):m}function i(a,u){let h=a[0]*u[0]+a[1]*u[1]+a[2]*u[2]+1;if(h<1e-6){if(Math.abs(a[0])>Math.abs(a[2])){let x=Math.hypot(a[1],a[0])||1;return[-a[1]/x,a[0]/x,0,0]}let g=Math.hypot(a[2],a[1])||1;return[0,-a[2]/g,a[1]/g,0]}let m=a[1]*u[2]-a[2]*u[1],c=a[2]*u[0]-a[0]*u[2],d=a[0]*u[1]-a[1]*u[0],f=Math.hypot(m,c,d,h)||1;return[m/f,c/f,d/f,h/f]}function n(a,u,h,m,c){let d=u[0]-a[0],f=u[1]-a[1],g=u[2]-a[2],x=Math.hypot(d,f,g),b=h[0]-u[0],v=h[1]-u[1],p=h[2]-u[2],y=Math.hypot(b,v,p);if(x<1e-6||y<1e-6)return{rootPos:[a[0],a[1],a[2]],midPos:[u[0],u[1],u[2]],effectorPos:[h[0],h[1],h[2]],rootRotation:[0,0,0,1],midRotation:[0,0,0,1]};let M=[d/x,f/x,g/x],P=[b/y,v/y,p/y],F=m[0]-a[0],W=m[1]-a[1],T=m[2]-a[2],E=Math.hypot(F,W,T),S=E>1e-6?[F/E,W/E,T/E]:M,O=Math.abs(x-y)+1e-5,k=Math.max(O,x+y-1e-5),w=Math.max(O,Math.min(k,E>1e-6?E:O)),ie=r((x*x+w*w-y*y)/(2*x*w),-1,1,1),oe=Math.sqrt(Math.max(0,1-ie*ie)),I=c?c[0]-a[0]:d,H=c?c[1]-a[1]:f,N=c?c[2]-a[2]:g,z=I*S[0]+H*S[1]+N*S[2],ue=I-S[0]*z,ce=H-S[1]*z,B=N-S[2]*z,$=Math.hypot(ue,ce,B);if($<=1e-6){let ee=Math.abs(S[1])<.99?0:1,R=Math.abs(S[1])<.99?1:0,A=0;ue=S[1]*A-S[2]*R,ce=S[2]*ee-S[0]*A,B=S[0]*R-S[1]*ee,$=Math.hypot(ue,ce,B)||1}let _=[ue/$,ce/$,B/$],G=[a[0]+S[0]*(x*ie)+_[0]*(x*oe),a[1]+S[1]*(x*ie)+_[1]*(x*oe),a[2]+S[2]*(x*ie)+_[2]*(x*oe)],j=[a[0]+S[0]*w,a[1]+S[1]*w,a[2]+S[2]*w],q=j[0]-G[0],D=j[1]-G[1],Y=j[2]-G[2],te=Math.hypot(q,D,Y),se=te>1e-6?[q/te,D/te,Y/te]:S,le=[G[0]+se[0]*y,G[1]+se[1]*y,G[2]+se[2]*y],V=[(G[0]-a[0])/x,(G[1]-a[1])/x,(G[2]-a[2])/x];return{rootPos:[a[0],a[1],a[2]],midPos:G,effectorPos:le,rootRotation:i(M,V),midRotation:i(P,se)}}function s(a,u,h=8,m=.001){let c=a.length;if(c<2)return{positions:a.map(E=>[E[0],E[1],E[2]]),rotations:[],iterations:0};let d=a.map(E=>[E[0],E[1],E[2]]),f=[],g=[],x=0;for(let E=0;E<c-1;E++){let S=d[E+1][0]-d[E][0],O=d[E+1][1]-d[E][1],k=d[E+1][2]-d[E][2],w=Math.hypot(S,O,k);f.push(w),x+=w,g.push(w>1e-6?[S/w,O/w,k/w]:[0,1,0])}let b=[d[0][0],d[0][1],d[0][2]],v=Math.round(r(h,1,32,8)),p=r(m,1e-5,.1,.001),y=u[0]-b[0],M=u[1]-b[1],P=u[2]-b[2],F=Math.hypot(y,M,P),W=0;if(F>=x&&x>1e-6){let E=F>1e-6?[y/F,M/F,P/F]:g[0];d[0]=[b[0],b[1],b[2]];for(let S=0;S<c-1;S++){let O=f[S];d[S+1]=[d[S][0]+E[0]*O,d[S][1]+E[1]*O,d[S][2]+E[2]*O]}W=1}else for(let E=1;E<=v;E++){let S=d[c-1];if(Math.hypot(S[0]-u[0],S[1]-u[1],S[2]-u[2])<=p)break;W=E;let O=(k,w,ie,oe,I)=>{let H=w[0]-k[0],N=w[1]-k[1],z=w[2]-k[2],ue=Math.hypot(H,N,z);if(ue>1e-6){let ce=ie/ue;return[k[0]+H*ce,k[1]+N*ce,k[2]+z*ce]}return[k[0]+oe[0]*ie*I,k[1]+oe[1]*ie*I,k[2]+oe[2]*ie*I]};d[c-1]=[u[0],u[1],u[2]];for(let k=c-2;k>=0;k--)d[k]=O(d[k+1],d[k],f[k],g[k],-1);d[0]=[b[0],b[1],b[2]];for(let k=0;k<c-1;k++)d[k+1]=O(d[k],d[k+1],f[k],g[k],1)}let T=[];for(let E=0;E<c-1;E++){let S=d[E+1][0]-d[E][0],O=d[E+1][1]-d[E][1],k=d[E+1][2]-d[E][2],w=Math.hypot(S,O,k),ie=w>1e-6?[S/w,O/w,k/w]:g[E];T.push(i(g[E],ie))}return{positions:d,rotations:T,iterations:W}}function l(a){if(!a||typeof a!="object"||Array.isArray(a))return null;let u=a;if(u.enabled===!1)return null;let h=p=>{if(typeof p!="string")return;let y=p.trim().slice(0,64);return/^[A-Za-z0-9_.:-]+$/.test(y)?y:void 0},m=p=>Array.isArray(p)&&p.length===3&&p.every(y=>typeof y=="number"&&Number.isFinite(y))?[r(p[0],-1e3,1e3,0),r(p[1],-1e3,1e3,0),r(p[2],-1e3,1e3,0)]:void 0,c=h(u.root),d=h(u.effector);if(!c||!d)return null;let f=h(u.mid),g=m(u.target)??h(u.target);if(!g)return null;let x=u.pole??u.poleTarget,b=m(x)??h(x),v=u.solver==="fabrik"?"fabrik":u.solver==="two-bone"||f?"two-bone":"fabrik";return{root:c,...f?{mid:f}:{},effector:d,target:g,...b?{pole:b}:{},solver:v,iterations:Math.round(r(u.iterations,1,32,8)),tolerance:r(u.tolerance,1e-5,.1,.001),weight:r(u.weight,0,1,1)}}let o=Object.freeze({solveTwoBone:n,solveFABRIK:s,parseIKTrait:l});return t&&typeof t=="object"&&(t.authorNamespace=t.authorNamespace||{},t.authorNamespace.IKSolver=o),{clampNum:r,parseIKTrait:l,quatFromUnitVectors:i,solveTwoBoneIK:n,solveFABRIK:s,IKSolver:o}}var tn=Ei(),Xo=tn.clampNum,Va=tn.parseIKTrait,or=tn.quatFromUnitVectors,Li=tn.solveTwoBoneIK,Ii=tn.solveFABRIK,$o=tn.IKSolver;function Ri(e){let t=e?.transform??e?.modelMatrix;return t&&t.length>=16?[t[12]||0,t[13]||0,t[14]||0]:[0,0,0]}function Ba(e,t){let r=e?.transform??e?.modelMatrix;!r||r.length<16||(r[12]=t[0],r[13]=t[1],r[14]=t[2])}function za(e,t,r,i,n){let s=Xo(n,0,1,1),l=t[0]+(r[0]-t[0])*s,o=t[1]+(r[1]-t[1])*s,a=t[2]+(r[2]-t[2])*s,u=l-e[0],h=o-e[1],m=a-e[2],c=Math.hypot(u,h,m);if(c>1e-6&&i>1e-6){let b=i/c;return[e[0]+u*b,e[1]+h*b,e[2]+m*b]}let d=r[0]-e[0],f=r[1]-e[1],g=r[2]-e[2],x=Math.hypot(d,f,g);if(x>1e-6&&i>1e-6){let b=i/x;return[e[0]+d*b,e[1]+f*b,e[2]+g*b]}return[l,o,a]}function Ga(e,t){let r=e?.modelRootMatrix;if(!r||r.length!==16)return t;let i=new Float32Array(16);return en(i,r instanceof Float32Array?r:Float32Array.from(r))?[i[0]*t[0]+i[4]*t[1]+i[8]*t[2]+i[12],i[1]*t[0]+i[5]*t[1]+i[9]*t[2]+i[13],i[2]*t[0]+i[6]*t[1]+i[10]*t[2]+i[14]]:t}function wi(e,t){e.__ikWarned||(e.__ikWarned=new Set);let r=e.__ikWarned;r.has(t)||(r.add(t),console.warn(`[three-live] ik: joint '${t}' on '${e?.name??""}' not found among scene nodes or meshes.`))}function _i(e,t,r){if(Array.isArray(e))return[e[0],e[1],e[2]];let i=t.get(e);if(i)return Ri(i);let n;if(e==="head"?n=r?.headPose?.position??r?.headPose??r?.cameraPosition:e==="hand-left"?n=r?.handPoses?.left?.position??r?.handPoses?.left??r?.hands?.left?.position??r?.hands?.left:e==="hand-right"&&(n=r?.handPoses?.right?.position??r?.handPoses?.right??r?.hands?.right?.position??r?.hands?.right),(Array.isArray(n)||ArrayBuffer.isView(n))&&n.length>=3){let s=n;return Ga(r,[s[0],s[1],s[2]])}return null}function Si(e,t){return[e[3]*t[0]+e[0]*t[3]+e[1]*t[2]-e[2]*t[1],e[3]*t[1]-e[0]*t[2]+e[1]*t[3]+e[2]*t[0],e[3]*t[2]+e[0]*t[1]-e[1]*t[0]+e[2]*t[3],e[3]*t[3]-e[0]*t[0]-e[1]*t[1]-e[2]*t[2]]}function Ha(e){return[-e[0],-e[1],-e[2],e[3]]}function Ci(e){let t=Math.hypot(e[0],e[1],e[2],e[3]);return t>1e-12?[e[0]/t,e[1]/t,e[2]/t,e[3]/t]:[0,0,0,1]}function Xa(e,t){if(t>=1)return e;if(t<=0)return[0,0,0,1];let[r,i,n,s]=e;s<0&&(r=-r,i=-i,n=-n,s=-s);let l=Math.acos(Math.min(1,s)),o=Math.sin(l);if(o<1e-9)return[0,0,0,1];let a=Math.sin(l*t)/o;return Ci([r*a,i*a,n*a,Math.cos(l*t)])}function $a(e){let t=Math.hypot(e[0],e[1],e[2])||1,r=Math.hypot(e[4],e[5],e[6])||1,i=Math.hypot(e[8],e[9],e[10])||1,n=e[0]/t,s=e[1]/t,l=e[2]/t,o=e[4]/r,a=e[5]/r,u=e[6]/r,h=e[8]/i,m=e[9]/i,c=e[10]/i,d=n+a+c,f;if(d>0){let g=Math.sqrt(d+1)*2;f=[(u-m)/g,(h-l)/g,(s-o)/g,.25*g]}else if(n>a&&n>c){let g=Math.sqrt(1+n-a-c)*2;f=[.25*g,(o+s)/g,(h+l)/g,(u-m)/g]}else if(a>c){let g=Math.sqrt(1+a-n-c)*2;f=[(o+s)/g,.25*g,(m+u)/g,(h-l)/g]}else{let g=Math.sqrt(1+c-n-a)*2;f=[(h+l)/g,(m+u)/g,.25*g,(s-o)/g]}return Ci(f)}function Wa(e,t,r){let[i,n,s,l]=r,o=1-2*(n*n+s*s),a=2*(i*n-s*l),u=2*(i*s+n*l),h=2*(i*n+s*l),m=1-2*(i*i+s*s),c=2*(n*s-i*l),d=2*(i*s-n*l),f=2*(n*s+i*l),g=1-2*(i*i+n*n);for(let x=0;x<3;x++){let b=t[x*4],v=t[x*4+1],p=t[x*4+2];e[x*4]=o*b+a*v+u*p,e[x*4+1]=h*b+m*v+c*p,e[x*4+2]=d*b+f*v+g*p}}function ir(e,t){let r=t[0]-e[0],i=t[1]-e[1],n=t[2]-e[2],s=Math.hypot(r,i,n);return s>1e-9?[r/s,i/s,n/s]:null}function Wo(e){e?.normalMatrix&&e?.transform&&Xe(e.normalMatrix,e.transform)}var Ho=new WeakMap;function ja(e){let t=Ho.get(e);return t||(t=new Int32Array(e.nodes.length).fill(-1),e.nodes.forEach((r,i)=>{for(let n of Array.isArray(r?.children)?r.children:[])typeof n=="number"&&n>=0&&n<t.length&&(t[n]=i)}),Ho.set(e,t)),t}function Ka(e,t,r){let i=e?.gltf,n=i?.nodes;if(!Array.isArray(n)||n.length===0)return!1;let s=new Map;n.forEach((T,E)=>{typeof T?.name=="string"&&T.name&&!s.has(T.name)&&s.set(T.name,E)});let l=(t.mid?[t.root,t.mid,t.effector]:[t.root,t.effector]).map(T=>s.get(T));if(l.some(T=>T===void 0))return!1;let o=l,a=ja(i);for(let T=1;T<o.length;T++){let E=a[o[T]],S=0;for(;E>=0&&E!==o[T-1]&&S++<256;)E=a[E];if(E!==o[T-1])return!1}let u=o[0],h=e.initialNodeTransforms,m=new Map,c=[],d=[u];for(;d.length&&c.length<4096;){let T=d.pop();if(m.has(T))continue;let E=h?.[T],S=n[T];m.set(T,{t:E?[E.t[0],E.t[1],E.t[2]]:S?.translation?[...S.translation]:[0,0,0],r:E?[E.r[0],E.r[1],E.r[2],E.r[3]]:S?.rotation?[...S.rotation]:[0,0,0,1],s:E?[E.s[0],E.s[1],E.s[2]]:S?.scale?[...S.scale]:[1,1,1]}),c.push(T);for(let O of Array.isArray(S?.children)?S.children:[])typeof O=="number"&&d.push(O)}let f=a[u],g=f>=0&&e.worldMatrices?.[f]?.length===16?Float32Array.from(e.worldMatrices[f]):Se(),x=new Map,b=()=>{let T=(E,S)=>{let O=m.get(E);if(!O)return;let k=Se();Tt(k,O.r,O.t,O.s);let w=Se();Ie(w,S,k),x.set(E,w);for(let ie of Array.isArray(n[E]?.children)?n[E].children:[])typeof ie=="number"&&T(ie,w)};T(u,g)},v=T=>{let E=x.get(T);return[E[12],E[13],E[14]]};b();let p=o.map(v),y=T=>{if(typeof T=="string"&&!r.has(T)){let E=s.get(T),S=E!==void 0?x.get(E)??e.worldMatrices?.[E]:void 0;if(S&&S.length===16)return[S[12],S[13],S[14]]}return _i(T,r,e)},M=y(t.target);if(!M)return!0;let P=t.pole?y(t.pole)??void 0:void 0,F=jo(p,t,M,P),W=Xo(t.weight,0,1,1);for(let T=0;T<o.length-1;T++){let E=ir(v(o[T]),v(o[T+1])),S=ir(F[T],F[T+1]);if(!E||!S)continue;let O=Xa(or(E,S),W),k=o[T],w=a[k],ie=w===f||w<0?g:x.get(w)??g,oe=$a(ie),I=m.get(k);I.r=Ci(Si(Ha(oe),Si(O,Si(oe,I.r)))),b()}if(Array.isArray(e.worldMatrices))for(let[T,E]of x)e.worldMatrices[T]?.set&&e.worldMatrices[T].set(E);for(let T of e.meshes??[]){let E=x.get(T?.nodeIndex);E&&T.transform?.set&&(T.transform.set(E),Wo(T))}return!0}function jo(e,t,r,i){if(t.solver==="two-bone"&&e.length===3){let n=Li(e[0],e[1],e[2],r,i);return[e[0],n.midPos,n.effectorPos]}return Ii(e,r,t.iterations,t.tolerance).positions}function qa(e,t,r){let i=e.__ikRestOffsets,n=e.__ikRestMats;if(!(!i||!n))for(let s=0;s<t.length-1;s++){let l=t[s]?.transform??t[s]?.modelMatrix,o=n[s],a=ir([0,0,0],i[s]),u=ir(r[s],r[s+1]);!l||l.length<16||!o||o.length<16||!a||!u||(Wa(l,o,or(a,u)),Wo(t[s]))}}var Di={name:"ik",onRegister(){let e=Ae();Qt(Ei),Ei(e.threeNamespace,e)},onUpdate(e){let t=e?.meshes;if(!Array.isArray(t)||t.length===0)return;let r=null;for(let i of t){let n=i?.userData?.xr?.ik??i?.extras?.xr?.ik??i?.extensions?.ANDROID_xr_scenecore?.ik;if(!n)continue;let s=Va(n);if(!s||s.weight<=0)continue;if(!r){r=new Map;for(let p of t)p&&typeof p.name=="string"&&p.name&&r.set(p.name,p)}if(Ka(e,s,r))continue;let l=r.get(s.root),o=r.get(s.effector),a=s.mid?r.get(s.mid):void 0;if(l||wi(i,s.root),o||wi(i,s.effector),s.mid&&!a&&wi(i,s.mid),!l||!o)continue;let u=_i(s.target,r,e);if(!u)continue;let h=s.pole?_i(s.pole,r,e)??void 0:void 0,m=a?[l,a,o]:[l,o],c=m.map(p=>p.name||"").join(">");if(!i.__ikRestOffsets||i.__ikRestKey!==c){let p=m.map(Ri),y=[];for(let M=0;M<p.length-1;M++)y.push([p[M+1][0]-p[M][0],p[M+1][1]-p[M][1],p[M+1][2]-p[M][2]]);i.__ikRestOffsets=y,i.__ikRestKey=c,i.__ikRestMats=m.map(M=>Array.from(M.transform??M.modelMatrix??[]))}let d=i.__ikRestOffsets,f=[Ri(l)],g=[];for(let p=0;p<d.length;p++){let y=f[p],M=d[p];f.push([y[0]+M[0],y[1]+M[1],y[2]+M[2]]),g.push(Math.hypot(M[0],M[1],M[2]))}let x=jo(f,s,u,h),b=f[0],v=[f[0]];for(let p=1;p<m.length;p++){let y=d[p-1],M=[b[0]+y[0],b[1]+y[1],b[2]+y[2]],P=[b[0]+(x[p][0]-x[p-1][0]),b[1]+(x[p][1]-x[p-1][1]),b[2]+(x[p][2]-x[p-1][2])],F=za(b,M,P,g[p-1],s.weight);Ba(m[p],F),b=F,v.push(F)}qa(i,m,v)}}};function gn(e,t){let r=(h,m,c,d)=>{let f=typeof h=="number"?h:Number(h);return Number.isFinite(f)?Math.max(m,Math.min(c,f)):d};function i(h,m,c=0,d=.05,f){if(!h||!h.length)return-1;let g=h[0]>0?[0,...h]:h,x=Number.isFinite(m)?Math.max(0,m):0,b=Number.isFinite(d)?Math.max(0,Math.min(.5,d)):.05;if(typeof f=="number"&&Number.isFinite(f)&&f>0){let y=c===-1?f*(1-b):f*(1+b);if(x>y)return-1}let v=0;for(let y=g.length-1;y>=1;y--)if(x>=g[y]){v=y;break}if(c<0||c>=g.length||c===v)return v;if(v>c){let y=c;for(let M=c+1;M<=v&&x>=g[M]*(1+b);M++)y=M;return y}let p=c;for(let y=c;y>v&&x<g[y]*(1-b);y--)p=y-1;return p}function n(h){if(!h)return null;let m=h===!0?{distances:[4,10],ratios:[.5,.25]}:Array.isArray(h)?{distances:h}:typeof h=="object"?h:null;if(!m||m.enabled===!1)return null;let c=r(m.hysteresis,0,.5,.05),d=[],f;if(Array.isArray(m.levels)&&m.levels.length>0){let v=m.levels.slice(0,8);for(let y=0;y<v.length;y++){let M=v[y];if(!M||typeof M!="object"||Array.isArray(M))continue;let P=M,F=r(P.distance,0,1e4,y===0?0:y*4),W=typeof P.hysteresis=="number"?r(P.hysteresis,0,.5,c):void 0,T=typeof P.ratio=="number"?r(P.ratio,.05,1,.5):void 0,E=typeof P.childIndex=="number"&&Number.isFinite(P.childIndex)?Math.max(0,Math.round(P.childIndex)):void 0,S=typeof P.node=="string"&&/^[A-Za-z0-9_.:-]+$/.test(P.node.trim())?P.node.trim().slice(0,64):void 0;d.push({distance:F,...W!==void 0?{hysteresis:W}:{},...T!==void 0?{ratio:T}:{},...E!==void 0?{childIndex:E}:{},...S?{node:S}:{}})}d.sort((y,M)=>y.distance-M.distance),d.length>0&&d[0].distance>0&&d.unshift({distance:0,childIndex:0});let p=0;d=d.slice(0,8).map((y,M)=>{let P=M===0?0:Math.max(p,y.distance);return p=P,{...y,distance:P,childIndex:y.childIndex??M}})}if(Array.isArray(m.ratios)&&m.ratios.length>0){let v=[];for(let p of m.ratios.slice(0,7))typeof p=="number"&&v.push(r(p,.05,1,.5));v.length>0&&(f=v)}if(d.length===0){let v=Array.isArray(m.distances)?m.distances:[],p=[];for(let M of v.slice(0,8))typeof M=="number"&&p.push(r(M,0,1e4,4));if(p.length===0&&f&&f.length>0)for(let M=0;M<f.length;M++)p.push((M+1)*4);if(p.length===0&&m.cullDistance===void 0)return null;p.length===0||p[0]>0?p.unshift(0):f&&f.length===p.length&&f[0]===1&&(f=f.slice(1));let y=0;for(let M=0;M<Math.min(8,p.length);M++){let P=M===0?0:Math.max(y,p[M]);y=P;let F=M>0&&f?f[M-1]:void 0;d.push({distance:P,childIndex:M,...F!==void 0?{ratio:F}:{}})}}else if(!f){let v=[];for(let p=1;p<d.length;p++)typeof d[p].ratio=="number"&&v.push(d[p].ratio);v.length>0&&(f=v)}let g=d.map(v=>v.distance),x=g[g.length-1]??0,b=m.cullDistance!==void 0&&m.cullDistance!==null&&m.cullDistance!==!1?r(m.cullDistance,Math.max(1,x),1e4,100):void 0;return{levels:d,distances:g,...f?{ratios:f}:{},hysteresis:c,...b!==void 0?{cullDistance:b}:{}}}function s(h,m){let c=h?.attributes?.position;if(!c||!c.array||c.count<3)return h;let d=r(m,.05,1,.5),f=c.array,g=c.count,x=h.attributes?.normal?.array,b=h.attributes?.uv?.array,v=h.index?.array,p=Math.floor((v?v.length:g)/3);if(p<1)return h;let y=Math.max(1,Math.min(p,Math.round(p*d))),M=1/0,P=1/0,F=1/0,W=-1/0,T=-1/0,E=-1/0;for(let $=0;$<g;$++){let _=f[$*3],G=f[$*3+1],j=f[$*3+2];_<M&&(M=_),G<P&&(P=G),j<F&&(F=j),_>W&&(W=_),G>T&&(T=G),j>E&&(E=j)}let S=Math.max(1e-5,W-M),O=Math.max(1e-5,T-P),k=Math.max(1e-5,E-F),w=Math.max(S,O,k),ie=$=>{let _=Math.max(1,Math.round(S/w*$)),G=Math.max(1,Math.round(O/w*$)),j=Math.max(1,Math.round(k/w*$)),q=new Map,D=new Int32Array(g),Y=[],te=[],se=[],le=[];for(let C=0;C<g;C++){let U=f[C*3],Q=f[C*3+1],X=f[C*3+2],Z=Math.min(_-1,Math.max(0,Math.floor((U-M)/S*_))),J=Math.min(G-1,Math.max(0,Math.floor((Q-P)/O*G))),K=Math.min(j-1,Math.max(0,Math.floor((X-F)/k*j))),ae=Z+J*_+K*_*G,ne=q.get(ae);ne===void 0?(ne=le.length,q.set(ae,ne),Y.push(U,Q,X),x&&te.push(x[C*3],x[C*3+1],x[C*3+2]),b&&se.push(b[C*2],b[C*2+1]),le.push(1)):(Y[ne*3]+=U,Y[ne*3+1]+=Q,Y[ne*3+2]+=X,x&&(te[ne*3]+=x[C*3],te[ne*3+1]+=x[C*3+1],te[ne*3+2]+=x[C*3+2]),le[ne]++),D[C]=ne}let V=[],ee=new Set;for(let C=0;C<p;C++){let U=v?v[C*3]:C*3,Q=v?v[C*3+1]:C*3+1,X=v?v[C*3+2]:C*3+2,Z=D[U],J=D[Q],K=D[X];if(Z===J||J===K||K===Z)continue;let ae=Math.min(Z,J,K),ne=Math.max(Z,J,K),re=Z+J+K-ae-ne,me=`${ae}_${re}_${ne}`;ee.has(me)||(ee.add(me),V.push(Z,J,K))}let R=le.length,A=new Float32Array(R*3),L=x?new Float32Array(R*3):null;for(let C=0;C<R;C++){let U=1/le[C];if(A[C*3]=Y[C*3]*U,A[C*3+1]=Y[C*3+1]*U,A[C*3+2]=Y[C*3+2]*U,L){let Q=te[C*3],X=te[C*3+1],Z=te[C*3+2],J=Math.hypot(Q,X,Z)||1;L[C*3]=Q/J,L[C*3+1]=X/J,L[C*3+2]=Z/J}}return{pos:A,norm:L,uv:b?new Float32Array(se):null,tris:V,triCount:V.length/3,vertCount:R}},oe=Math.max(2,Math.round(Math.sqrt(y/4))),I=ie(oe);if(I.triCount>y*1.25&&oe>2){let $=Math.max(2,Math.round(oe*Math.sqrt(y/I.triCount)));if($!==oe){let _=ie($);_.triCount>=Math.min(4,y)&&(I=_)}}else if(I.triCount<Math.min(4,y)){let $=ie(Math.max(oe*2,8));$.triCount>I.triCount&&(I=$)}let H=I.tris;if(d<1&&I.triCount>y){let $=[],_=I.triCount/y;for(let G=0;G<y;G++){let j=Math.min(I.triCount-1,Math.floor(G*_));$.push(I.tris[j*3],I.tris[j*3+1],I.tris[j*3+2])}H=$}if(H.length<3){H=[];for(let $=0;$<y*3;$++)H.push(v?v[$]:$);I={pos:f.slice(),norm:x?x.slice():null,uv:b?b.slice():null,tris:H,triCount:y,vertCount:g}}let N=e??t?.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0),z=N?.BufferGeometry??h.constructor,ue=N?.BufferAttribute??c.constructor,ce=new z;ce.setAttribute("position",new ue(I.pos,3)),I.norm&&ce.setAttribute("normal",new ue(I.norm,3)),I.uv&&ce.setAttribute("uv",new ue(I.uv,2));let B=I.vertCount>65535?new Uint32Array(H):new Uint16Array(H);return typeof ce.setIndex=="function"?ce.setIndex(new ue(B,1)):ce.index=new ue(B,1),ce}let l=e?.Object3D??t?.threeNamespace?.Object3D??class{constructor(){this.name="",this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0},this.quaternion={x:0,y:0,z:0,w:1},this.scale={x:1,y:1,z:1},this.visible=!0,this.parent=null,this.children=[],this.userData={}}add(...h){for(let m of h)m&&(m.parent=this,this.children.push(m));return this}};class o extends l{constructor(){super(),this.isLOD=!0,this.type="LOD",this.autoUpdate=!0,this.levels=[],this._currentLevel=0}addLevel(m,c=0,d=.05){if(!m)return this;let f=Math.max(0,Number.isFinite(Number(c))?Number(c):0),g=r(d,0,.5,.05),x=this.levels.length;for(let p=0;p<this.levels.length;p++)if(f<this.levels[p].distance){x=p;break}this.levels.splice(x,0,{object:m,distance:f,hysteresis:g}),this.add(m);let b=this.levels.map(p=>p.object),v=this.children.filter(p=>!b.includes(p));this.children=[...b,...v];for(let p=0;p<this.levels.length;p++)this.levels[p].object.visible=p===this._currentLevel;return this.syncUserDataTrait(),this}getCurrentLevel(){return this._currentLevel}getObjectForDistance(m){if(!this.levels.length)return null;let c=i(this.levels.map(d=>d.distance),m,this._currentLevel,this.levels[0]?.hysteresis??.05,this.userData?.xr?.lod?.cullDistance);return c>=0&&c<this.levels.length?this.levels[c].object:null}update(m){if(this.levels.length===0||!m)return;let c=m.position??{x:0,y:0,z:0},d=this.position??{x:0,y:0,z:0},f=Math.hypot((Number(c.x)||0)-(Number(d.x)||0),(Number(c.y)||0)-(Number(d.y)||0),(Number(c.z)||0)-(Number(d.z)||0)),g=i(this.levels.map(x=>x.distance),f,this._currentLevel,this.levels[0]?.hysteresis??.05,this.userData?.xr?.lod?.cullDistance);this._currentLevel=g;for(let x=0;x<this.levels.length;x++)this.levels[x].object.visible=x===g}syncUserDataTrait(){this.userData=this.userData||{},this.userData.xr=this.userData.xr||{};let m=this.userData.xr.lod?.cullDistance;this.userData.xr.lod={levels:this.levels.map((c,d)=>({distance:c.distance,hysteresis:c.hysteresis,childIndex:d,...c.object?.name?{node:c.object.name}:{}})),distances:this.levels.map(c=>c.distance),hysteresis:this.levels[0]?.hysteresis??.05,...m!==void 0?{cullDistance:m}:{}}}}function a(h){if(!h||h._lodMaterialized||!h.userData?.xr?.lod||h.isLOD||Array.isArray(h.children)&&h.children.length>0)return;let m=h.geometry?.attributes?.position;if(!m||!m.array||m.count<3)return;let c=n(h.userData.xr.lod);if(!c||c.levels.length<2)return;h._lodMaterialized=!0;let d=h.geometry;h._lodOriginalGeometry=d;let f=e??t?.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0),g=f?.Mesh??h.constructor,x=f?.BufferGeometry??d.constructor,b=typeof h.name=="string"&&h.name.trim()?h.name.trim():"Mesh",v=new g(d,h.material);v.name=`${b}_LOD0`,v.visible=!0,v.castShadow=!!h.castShadow,v.receiveShadow=!!h.receiveShadow,h.add(v);for(let p=1;p<c.levels.length;p++){let y=c.levels[p].ratio??c.ratios?.[p-1]??Math.max(.05,Math.pow(.5,p)),M=s(d,y),P=new g(M,h.material);P.name=`${b}_LOD${p}`,P.visible=!1,P.castShadow=!!h.castShadow,P.receiveShadow=!!h.receiveShadow,h.add(P)}h.geometry=new x,h.userData.xr.lod={...c,levels:c.levels.map((p,y)=>({...p,childIndex:y,node:`${b}_LOD${y}`}))}}let u={LOD:o,decimateGeometry:s,selectLodLevelIndex:i,parseLod:n,materializeLodGeometry:a};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,{LOD:o,decimateGeometry:s}),t._lodMaterialize=a,t.materializeDeclarativeGeometry=h=>{t._cadMaterialize?.(h),t._lodMaterialize?.(h)}),u}var vn=gn(),Ko=vn.decimateGeometry,sr=vn.selectLodLevelIndex,ar=vn.parseLod,Pu=vn.materializeLodGeometry,qo=vn.LOD,yn=new WeakMap;function Yo(e){return e&&typeof e=="object"?yn.get(e):void 0}var xn=class{constructor(e,t){this.groups=[],this.viewer=e,this.gltf=t,this.rebuild()}rebuild(){this.groups.length=0;let e=this.gltf?.nodes;if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let i of this.viewer?.meshes??[])if(typeof i?.nodeIndex=="number"&&i.nodeIndex>=0){let n=t.get(i.nodeIndex);n||(n=[],t.set(i.nodeIndex,n)),n.push(i)}let r=i=>{let n=[],s=new Set,l=[i];for(;l.length>0;){let o=l.pop();if(s.has(o)||o<0||o>=e.length)continue;s.add(o);let a=t.get(o);a&&n.push(...a);let u=e[o]?.children;if(Array.isArray(u))for(let h=u.length-1;h>=0;h--)typeof u[h]=="number"&&l.push(u[h])}return n};for(let i=0;i<e.length;i++){let n=e[i];if(!n||typeof n!="object")continue;let s=n.extras?.xr?.lod??n.extensions?.ANDROID_xr_scenecore?.lod??n.extensions?.MOZ_hubs_components?.lod,l=Array.isArray(n.extensions?.MSFT_lod?.ids)?n.extensions.MSFT_lod.ids.filter(d=>typeof d=="number"&&Number.isInteger(d)&&d>=0&&d<e.length):[],o=ar(s);if(!o&&l.length>0&&(o=ar({distances:l.map((d,f)=>f*4)})),!o)continue;let a=l.length>0?l:Array.isArray(n.children)?n.children.filter(d=>typeof d=="number"&&Number.isInteger(d)&&d>=0&&d<e.length):[],u=[],h=[];if(a.length>0){let d=Math.min(a.length,o.levels.length);for(let f=0;f<d;f++){let g=a[f];u.push(g),h.push(r(g))}}else{let d=t.get(i)??[];if(d.length===0)continue;u.push(i),h.push(d)}let m=o.distances.slice(0,h.length);m.length===0&&m.push(0);let c={nodeIndex:i,name:typeof n.name=="string"?n.name:`LOD_${i}`,distances:m,hysteresis:o.hysteresis,...o.cullDistance!==void 0?{cullDistance:o.cullDistance}:{},childNodeIndices:u,levelMeshes:h,activeLevelIndex:0,lastDistance:0};this.applyGroupVisibility(c,0),this.groups.push(c)}}getGroups(){return this.groups}getActiveLevel(e){let t=this.findGroup(e);return t?t.activeLevelIndex:null}forceLodLevel(e,t){let r=this.findGroup(e);if(!r)return;if(t==null){r.forcedLevelIndex=null;let n=sr(r.distances,r.lastDistance,r.activeLevelIndex,r.hysteresis,r.cullDistance);r.activeLevelIndex=n,this.applyGroupVisibility(r,n);return}let i=t<0?-1:Math.min(Math.max(0,Math.trunc(t)),r.levelMeshes.length-1);r.forcedLevelIndex=i,r.activeLevelIndex=i,this.applyGroupVisibility(r,i)}findGroup(e){return typeof e=="number"?this.groups.find(t=>t.nodeIndex===e)??this.groups[e]:this.groups.find(t=>t.name===e)}update(e){if(this.groups.length===0)return;let t=this.viewer?.worldMatrices,r=this.viewer?.modelRootMatrix;for(let i of this.groups){let n=Array.isArray(t)&&i.nodeIndex<t.length?t[i.nodeIndex]:null,s=n&&n[12]||0,l=n&&n[13]||0,o=n&&n[14]||0,a=r?r[0]*s+r[4]*l+r[8]*o+r[12]:s,u=r?r[1]*s+r[5]*l+r[9]*o+r[13]:l,h=r?r[2]*s+r[6]*l+r[10]*o+r[14]:o,m=Math.hypot((e[0]||0)-a,(e[1]||0)-u,(e[2]||0)-h);if(i.lastDistance=m,i.forcedLevelIndex!==void 0&&i.forcedLevelIndex!==null){i.activeLevelIndex!==i.forcedLevelIndex&&(i.activeLevelIndex=i.forcedLevelIndex,this.applyGroupVisibility(i,i.forcedLevelIndex));continue}let c=sr(i.distances,m,i.activeLevelIndex,i.hysteresis,i.cullDistance);c!==i.activeLevelIndex&&(i.activeLevelIndex=c,this.applyGroupVisibility(i,c))}}applyGroupVisibility(e,t){let r=this.gltf?.nodes;for(let i=0;i<e.levelMeshes.length;i++){let n=i===t;for(let o of e.levelMeshes[i])o.visible=n;let s=e.childNodeIndices[i],l=Array.isArray(r)?r[s]:null;l&&typeof l=="object"&&(l.visible=n,l.extensions=l.extensions||{},l.extensions.KHR_node_visibility={visible:n})}}},Pi={name:"lod",onRegister(){Qt(gn);let e=Ae(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);gn(t,e)},onLoadModel(e,t){!e||typeof e!="object"||yn.set(e,new xn(e,t))},onUpdate(e){let t=yn.get(e);if(!t||typeof e?.getCameraOrbit!="function")return;let r=e.getCameraOrbit(),i=typeof e.getCameraTarget=="function"?e.getCameraTarget():{x:0,y:0,z:0},n=r?.radius??3,s=r?.phi??0,l=r?.theta??0,o=Math.cos(s),a=(i.x||0)+n*o*Math.sin(l),u=(i.y||0)+n*Math.sin(s),h=(i.z||0)+n*o*Math.cos(l);t.update([a,u,h])},onBeforeDrawScene(e,t,r,i){let n=yn.get(e);n&&n.update(i)},onDestroy(e,t){t&&typeof t=="object"&&yn.delete(t)}},Ya={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function bt(e,t,r,i){if(!r||r.bufferView===void 0)return null;let n=e.bufferViews?.[r.bufferView];if(!n)return null;let s=Number(r.count??0);if(!Number.isInteger(s)||s<=0)return null;let l=r.componentType??5126,o=Ya[l];if(!o)throw new RangeError(`glTF accessor has unsupported componentType ${l}`);let a=o*i,u=n.byteStride&&n.byteStride>0?n.byteStride:a,h=(n.byteOffset||0)+(r.byteOffset||0);if(!Number.isInteger(h)||h<0||u<a||h+(s-1)*u+a>t.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${t.byteLength} bytes)`);if(l===5126&&u===a&&h%4===0)return new Float32Array(t,h,s*i);let m=new DataView(t),c=r.normalized===!0,d=new Float32Array(s*i);for(let f=0;f<s;f++){let g=h+f*u;for(let x=0;x<i;x++){let b=g+x*o,v;switch(l){case 5126:v=m.getFloat32(b,!0);break;case 5120:v=m.getInt8(b),c&&(v=Math.max(v/127,-1));break;case 5121:v=m.getUint8(b),c&&(v/=255);break;case 5122:v=m.getInt16(b,!0),c&&(v=Math.max(v/32767,-1));break;case 5123:v=m.getUint16(b,!0),c&&(v/=65535);break;default:v=m.getUint32(b,!0),c&&(v/=4294967295)}d[f*i+x]=v}}return d}function Zo(e,t){let r=Number(t.offset?.[0]??0)||0,i=Number(t.offset?.[1]??0)||0,n=Number(t.scale?.[0]??1),s=Number(t.scale?.[1]??1),l=Number(t.rotation??0)||0,o=Math.cos(l),a=Math.sin(l),u=(Number.isFinite(n)?n:1)*o,h=(Number.isFinite(n)?n:1)*a,m=-(Number.isFinite(s)?s:1)*a,c=(Number.isFinite(s)?s:1)*o;for(let d=0;d+1<e.length;d+=2){let f=e[d],g=e[d+1];e[d]=u*f+h*g+r,e[d+1]=m*f+c*g+i}}function _t(e,t,r,i=!0){let n=[],s=null;try{for(let[l,o]of[[35633,t],[35632,r]]){let a=e.createShader(l);if(!a){if(i)throw new Error("Shader allocation failed");return null}if(n.push(a),e.shaderSource(a,o),e.compileShader(a),e.getShaderParameter&&!e.getShaderParameter(a,35713)){if(i)throw new Error(`Shader compile error: ${e.getShaderInfoLog(a)}`);return null}}if(s=e.createProgram(),!s){if(i)throw new Error("Program allocation failed");return null}for(let l of n)e.attachShader(s,l);if(e.linkProgram(s),e.getProgramParameter&&!e.getProgramParameter(s,35714)){let l=i?e.getProgramInfoLog(s):null;if(e.deleteProgram?.(s),s=null,i)throw new Error(`Program link error: ${l}`);return null}return s}finally{for(let l of n)s&&e.detachShader?.(s,l),e.deleteShader?.(l)}}var es=["neutral","reinhard","none","aces","agx"];function Vt(e){let t=String(e??"").trim().toLowerCase();return es.includes(t)?t:"neutral"}function Za(e){return es.indexOf(Vt(e))}function Qa(e){return new TextDecoder().decode(e)}var ts=Ae().decoders;function Ja(e,t){ts.set(e.toLowerCase(),t)}function nn(e){return ts.get(e.toLowerCase())}function ns(e){let t=ArrayBuffer.isView(e)?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):e,r=new DataView(t);if(t.byteLength<12)throw new Error(`Invalid GLB buffer size: ${t.byteLength} bytes`);let i=r.getUint32(0,!0);if(i!==1179937895){let c=r.getUint8(0);throw c===123||c===32||c===10||c===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${i.toString(16)}`)}let n=r.getUint32(4,!0);if(n!==2)throw new Error(`Unsupported GLB version: ${n}`);let s=r.getUint32(8,!0),l=12,o=null,a=null;for(;l+8<=s&&l+8<=t.byteLength;){let c=r.getUint32(l,!0),d=r.getUint32(l+4,!0),f=l+8;if(f+c>t.byteLength)throw new Error(`Truncated GLB chunk: required ${f+c} bytes, buffer has ${t.byteLength}`);if(d===1313821514){let g=new Uint8Array(t,f,c),x=Qa(g);o=JSON.parse(x,(b,v)=>b==="__proto__"||b==="constructor"||b==="prototype"?void 0:v)}else d===5130562&&(a=t.slice(f,f+c));l=f+c}if(!o)throw new Error("Missing JSON chunk in GLB");let u=o.extensionsRequired||[];if(u.includes("KHR_draco_mesh_compression")&&!nn("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");for(let c of["EXT_meshopt_compression","KHR_meshopt_compression"])if(u.includes(c)&&!nn("meshopt"))throw new Error(`Model requires ${c}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(u.includes("KHR_texture_basisu")&&!nn("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let h=a||new ArrayBuffer(0),m={gltf:o,bin:h,animations:[]};for(let c of Oe)c.onParseGLB?.(m);return m}function ec(e){return typeof e=="object"&&e!==null&&"gltf"in e&&typeof e.gltf=="object"&&e.gltf!==null&&"bin"in e&&(e.bin instanceof ArrayBuffer||ArrayBuffer.isView(e.bin))}function Lt(e){if(ec(e))return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return ns(e);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var rs=`#version 300 es
|
|
16
|
+
*/var Ec=Object.defineProperty,Kh=Object.getOwnPropertyDescriptor,Jh=Object.getOwnPropertyNames,Qh=Object.prototype.hasOwnProperty,Zh=(e,t)=>{for(var r in t)Ec(e,r,{get:t[r],enumerable:!0})},ep=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Jh(t))!Qh.call(e,n)&&n!==r&&Ec(e,n,{get:()=>t[n],enumerable:!(i=Kh(t,n))||i.enumerable});return e},tp=e=>ep(Ec({},"__esModule",{value:!0}),e),Qu={};Zh(Qu,{AIVoiceSession:()=>ki,AmbientLight:()=>mi,BoxGeometry:()=>ai,BufferAttribute:()=>Vt,BufferGeometry:()=>Nt,Camera:()=>pi,CapsuleGeometry:()=>ia,CatmullRomCurve3:()=>zs,CircleGeometry:()=>sa,Clock:()=>Zs,Color:()=>Bn,ConeGeometry:()=>Ds,CubicBezierCurve3:()=>Os,Curve3:()=>ar,CylinderGeometry:()=>ci,DataTexture:()=>Gs,DirectionalLight:()=>Ks,DodecahedronGeometry:()=>oa,EdgesGeometry:()=>la,Euler:()=>si,Float32BufferAttribute:()=>Ls,Group:()=>Ys,HemisphereLight:()=>vi,IKSolver:()=>wd,IMAGE_SYSTEM_PROMPT:()=>Tl,IcosahedronGeometry:()=>ra,InstancedMesh:()=>di,InteractivityVM:()=>Bi,LOD:()=>Td,LatheGeometry:()=>li,Light:()=>cr,LightShadow:()=>fi,Line:()=>kr,LineBasicMaterial:()=>io,LineCurve3:()=>Fs,LineDashedMaterial:()=>aa,LineLoop:()=>ua,LineSegments:()=>da,LodController:()=>Go,MAX_BSP_DEPTH:()=>hd,MAX_CSG_TRIANGLES:()=>md,MAX_INSTANCES_PER_MESH:()=>ui,MAX_SHADOW_LIGHTS:()=>Ao,MAX_SHAPE_POINTS:()=>bd,MAX_TEXT_GEOMETRY_CHARS:()=>pd,MAX_TSL_NODES:()=>Xd,MAX_TSL_UNIFORMS:()=>eo,Material:()=>vn,MathUtils:()=>cf,Matrix3:()=>Rs,Matrix4:()=>_r,Mesh:()=>qn,MeshBasicMaterial:()=>Hs,MeshLambertMaterial:()=>Ws,MeshPhongMaterial:()=>Xs,MeshPhysicalMaterial:()=>qs,MeshStandardMaterial:()=>Fr,Object3D:()=>Fn,OctahedronGeometry:()=>na,PART_STRIDE_BYTES:()=>Yi,PART_STRIDE_WORDS:()=>qi,PerspectiveCamera:()=>Js,PlaneGeometry:()=>Cs,PointLight:()=>hi,Points:()=>fa,PointsMaterial:()=>xi,PolyhedronFallbackGeometry:()=>l0,PolyhedronGeometry:()=>lr,QuadraticBezierCurve3:()=>Vs,Quaternion:()=>no,RawShaderMaterial:()=>vf,RectAreaLight:()=>ha,RingGeometry:()=>gi,SCENE_PBR_WGSL:()=>Ji,SCENE_PICK_WGSL:()=>fc,SCENE_SHADOW_WGSL:()=>dc,SCENE_UNIFORM_BYTES:()=>jr,SHADOW_MAP_TEXTURE_UNIT:()=>Cu,Scene:()=>bi,SceneQuotaValidator:()=>Xn,ShaderMaterial:()=>yi,SphereGeometry:()=>Ns,SpotLight:()=>ma,TEXTURE_PROMPT_SUFFIX:()=>Bl,THREE:()=>Vr,TSL_EXTENSION_NAME:()=>Br,TSL_TIME_PERIOD_SEC:()=>Wn,TSL_WGSL_UNIFORM_BYTES:()=>rh,TetrahedronGeometry:()=>ta,Texture:()=>ro,TextureLoader:()=>js,ThreeLiveElement:()=>kn,ThreeView:()=>Ht,TorusGeometry:()=>Us,TorusKnotGeometry:()=>Bs,TubeGeometry:()=>$s,Uint16BufferAttribute:()=>Ps,Uint32BufferAttribute:()=>Is,VERTEX_STRIDE_BYTES:()=>Hr,VERTEX_STRIDE_FLOATS:()=>Eo,Vector2:()=>tn,Vector3:()=>Ze,Vector4:()=>ks,WebGLRenderer:()=>Qs,WebGPUSceneAccelerator:()=>Zi,WireframeGeometry:()=>ca,acquireSceneWebGPUDevice:()=>qr,activateAR:()=>Xa,aiPlugin:()=>Ga,applyMeshoptFilter:()=>_u,authorScriptRunner:()=>so,browserImageCodec:()=>Ei,buildImageMessages:()=>El,buildImageUserText:()=>_l,buildSandboxWorkerSource:()=>sl,buildSelectIndex:()=>wi,cadPlugin:()=>kc,clearAuthorWarnings:()=>xf,compileFromImage:()=>Ra,compileTslToGlsl:()=>ws,compileTslToWgsl:()=>cc,computeOutlineClipOffset:()=>jm,computeWorldSceneBounds:()=>Du,connectVoice:()=>Ri,contactShadowPlugin:()=>Di,createAIChatProvider:()=>Ql,createAIImageProvider:()=>Fl,createUSDZBlob:()=>Zr,createWebSpeechRecognizer:()=>Kl,crossFadeTo:()=>ou,decimateGeometry:()=>Ad,decodeMeshoptBuffer:()=>Eu,decodeMeshoptGLB:()=>nc,defineModelViewer:()=>Af,describeEditResult:()=>$a,describeSelection:()=>Si,describeVoiceSelection:()=>bo,detectImageMime:()=>Rl,doesMeshCastShadow:()=>Gr,doesMeshReceiveShadow:()=>$i,editScene:()=>Zl,encodeMeshoptBuffer:()=>Vm,environmentMapPlugin:()=>yu,evaluateKawaseBloom:()=>Gm,evaluateToneMapping:()=>Id,exportSceneToCanvas3D:()=>nl,exportSceneToGLB:()=>rl,exportSceneToUSDZ:()=>df,extractMaterialVariants:()=>Ou,extractPrimitiveVariantMappings:()=>Zm,extractScript:()=>Ai,fitDirectionalShadowMatrix:()=>Uu,fitSpotShadowMatrix:()=>sc,fmtShaderFloat:()=>Un,formatSpatialPriors:()=>Ea,geminiLiveAdapter:()=>Yl,generateUSDZ:()=>Qo,getARCapabilities:()=>Wa,getAllowClientScripts:()=>hf,getAuthorWarnings:()=>gf,getBestARMode:()=>pm,getEnvironmentSH:()=>gm,getInteractivityVM:()=>Za,getLodController:()=>_d,getSandboxEngineSrc:()=>ol,getSandboxIframeSrc:()=>mf,getSelection:()=>nn,getShadowMapStats:()=>Km,getWebGPUSceneAccelerator:()=>Ro,glbToUSDZ:()=>Jo,hideSelectionChips:()=>mo,hotspotPlugin:()=>vu,ikPlugin:()=>Fc,imageRepairMessage:()=>kl,indexedDbTextureCache:()=>$l,installCadExtension:()=>cs,installLodExtension:()=>$o,installProceduralExtension:()=>ms,installTslExtension:()=>Zo,interactivityPlugin:()=>Au,isAllowedImageUrl:()=>On,isAllowedSandboxEngineUrl:()=>oo,isQuickLookSupported:()=>fu,isSceneViewerSupported:()=>mu,isWebXRSupported:()=>hu,keyframeAnimationPlugin:()=>iu,lodPlugin:()=>Vc,matchSelection:()=>va,materialsPlugin:()=>Tu,meshoptDecoder:()=>rc,meshoptPlugin:()=>ku,morphPlugin:()=>su,noopProxy:()=>oi,normalizeImageInput:()=>ka,normalizeRendererPreference:()=>Ju,normalizeShadowMapsMode:()=>Nu,packUniformVec4:()=>ei,parseAnimations:()=>ru,parseHexRgb:()=>Ru,parseLod:()=>fs,parseSafeGltfPointer:()=>Ui,parseSelectReply:()=>Al,parseTexturePack:()=>Ol,parseVoiceCommand:()=>wa,postprocessingPlugin:()=>Lu,prepareAlbedo:()=>Vl,proceduralPlugin:()=>Oc,quatFromUnitVectors:()=>us,realtimeAdapter:()=>ql,registerMaterialShader:()=>_m,remapClipDepthToZeroOne:()=>Xi,resetSceneWebGPUDevice:()=>_h,resolveActiveShadowLights:()=>Gi,resolveSceneRenderBackend:()=>xc,resolveSelection:()=>Ma,resolveSelectionWithModel:()=>Aa,sampleChannel:()=>go,sceneSelectEntries:()=>uo,sceneToCanvas3D:()=>Qr,sceneToGLB:()=>qo,sceneToUSDZ:()=>Ko,selectByVoice:()=>yo,selectCamera:()=>Sa,selectLodLevelIndex:()=>ds,selectMaterialVariant:()=>eh,selectMessages:()=>Ml,selectNamesByVoice:()=>Jl,sendInteractivityEvent:()=>Mu,serializeTexturePack:()=>zl,serializeTslToUsda:()=>Ss,setAllowClientScripts:()=>e0,setEnvironmentSH:()=>qa,setMaterialUniform:()=>ju,setMorphTargetWeight:()=>dm,setSandboxEngineSrc:()=>Kp,setSandboxIframeSrc:()=>Qp,setSceneWebGPUDeviceForTests:()=>Th,setSelectOnTap:()=>Pi,setSelection:()=>rn,shadowMapsPlugin:()=>Vu,showSelectionChips:()=>Va,skinningPlugin:()=>cu,solveFABRIK:()=>Uc,solveTwoBoneIK:()=>Dc,speakableName:()=>za,startVoiceEdit:()=>Li,textureRequests:()=>Na,threeAuthorPlugin:()=>ii,threeMicroPlugin:()=>f0,toGLBData:()=>wr,toTrustedWorkerScriptURL:()=>ff,tslPlugin:()=>uc,tslSafeMod:()=>vs,tslTypeArity:()=>Wt,tslTypeFromArity:()=>Kc,undoEdit:()=>eu,validateSandboxWorkerMessage:()=>al,validateTslGraph:()=>Sr,variantsPlugin:()=>zu,warnUnsupported:()=>Er,webgpuScenePlugin:()=>wc,webxrPlugin:()=>$u,writeSceneUniforms:()=>Ki}),module.exports=tp(Qu);function fd(e,t,r){let i=[],n=new Map,a=[],s=[],o=[],l=new Map,c=b=>{let w=n.get(b);return w===void 0&&(w=i.length,i.push({op:b}),n.set(b,w)),w},f=b=>{let w=l.get(b);return w===void 0&&(w=o.length,o.push({id:b}),l.set(b,w)),w},m=(b,w={})=>a.push({declaration:c(b),...w})-1,h=(b,w,S)=>s.push({id:b,type:w,value:S})-1,p=b=>({node:b,socket:"value"}),g=r?.interactivity??r?.gltfExtensions?.KHR_interactivity;if(g&&typeof g=="object"){let b=Array.isArray(g.graphs)?g.graphs[g.graph??0]:g;if(b&&Array.isArray(b.nodes)){let w=Array.isArray(b.declarations)?b.declarations:[];for(let S of w)S?.op&&c(S.op);Array.isArray(b.variables)&&s.push(...b.variables);for(let S of b.events||[])S?.id&&f(S.id);for(let S of b.nodes){if(!S||typeof S!="object")continue;let E=S.op||(typeof S.declaration=="number"?w[S.declaration]?.op:"");a.push(E?{...S,declaration:c(E)}:{...S})}}}let x=(b,w,S="translation")=>S==="baseColorFactor"||S==="metallicFactor"||S==="roughnessFactor"?`/materials/${Math.max(0,w)}/pbrMetallicRoughness/${S}`:S==="emissiveFactor"||S==="alphaCutoff"?`/materials/${Math.max(0,w)}/${S}`:S==="visible"?`/nodes/${b}/extensions/KHR_node_visibility/visible`:`/nodes/${b}/${S}`,v=new Map;e.forEach((b,w)=>{typeof b?.name=="string"&&!v.has(b.name)&&v.set(b.name,w)});let y=(b,w)=>typeof b.target=="string"&&v.has(b.target)?v.get(b.target):typeof b.targetNode=="number"?b.targetNode:w,A=b=>{let w=e[b];return(typeof w?.mesh=="number"?t[w.mesh]?.primitives?.[0]?.material:0)??0};for(let b=0;b<e.length;b++){let w=e[b],S=w?.extras?.interactivity;if(!S||typeof S!="object")continue;let E=(typeof w.mesh=="number"?t[w.mesh]?.primitives?.[0]?.material:0)??0,N=_=>{let P=Array.isArray(_)?_:[_],R=[];for(let F=0;F<P.length;F++){let V=P[F];if(!V||typeof V!="object")continue;let Y=V.action||"interpolate",J=typeof V.duration=="number"?V.duration:.35;if(Y==="toggleTransform"){let re=V.property==="rotation"||V.property==="scale"?V.property:"translation",Q=re==="rotation"?w.rotation||[0,0,0,1]:re==="scale"?w.scale||[1,1,1]:w.translation||[0,0,0],ee=`/nodes/${b}/${re}`,k=h(`__toggle_${b}_${F}`,"bool",!1),G=m("variable/get",{configuration:{variable:k}}),q=m("math/not",{values:{a:p(G)}}),H=m("variable/set",{configuration:{variable:k},values:{value:p(q)}}),te=m("pointer/interpolate",{configuration:{pointer:ee},values:{value:{value:Array.isArray(V.to)?V.to:Q},duration:{value:J}}}),Z=m("pointer/interpolate",{configuration:{pointer:ee},values:{value:{value:Array.isArray(V.from)?V.from:Q},duration:{value:J}}});a[H].flows={out:{node:m("flow/branch",{values:{condition:p(G)},flows:{true:{node:te},false:{node:Z}}})}},R.push(H)}else if(Y==="interpolate"){let re=V.to??V.value;if(re===void 0)continue;let Q={value:{value:re},duration:{value:J}};V.from!==void 0&&(Q.from={value:V.from}),R.push(m("pointer/interpolate",{configuration:{pointer:typeof V.pointer=="string"?V.pointer:x(y(V,b),A(y(V,b)),V.property)},values:Q}))}else if(Y==="setProperty"){if(V.value===void 0)continue;R.push(m("pointer/set",{configuration:{pointer:typeof V.pointer=="string"?V.pointer:x(y(V,b),A(y(V,b)),V.property)},values:{value:{value:V.value}}}))}else if(Y==="toggleVisibility"){let re=y(V,b),Q=h(`__vis_${re}_${F}`,"bool",!0),ee=m("variable/get",{configuration:{variable:Q}}),k=m("math/not",{values:{a:p(ee)}}),G=m("variable/set",{configuration:{variable:Q},values:{value:p(k)}});a[G].flows={out:{node:m("pointer/set",{configuration:{pointer:`/nodes/${re}/extensions/KHR_node_visibility/visible`},values:{value:p(ee)}})}},R.push(G)}else if(Y==="cycleMaterialColor"&&Array.isArray(V.colors)&&V.colors.length>0){let re=typeof V.duration=="number"?V.duration:.25,Q=`/materials/${Math.max(0,E)}/pbrMetallicRoughness/baseColorFactor`,ee=h(`__color_idx_${b}_${F}`,"int",0),k=m("variable/get",{configuration:{variable:ee}}),G=m("math/add",{values:{a:p(k),b:{value:1}}}),q=m("math/rem",{values:{a:p(G),b:{value:V.colors.length}}}),H=m("variable/set",{configuration:{variable:ee},values:{value:p(q)}}),te={};for(let Z=0;Z<V.colors.length;Z++){let ae=V.colors[Z],ie=Array.isArray(ae)&&ae.length>=3?[ae[0],ae[1],ae[2],ae[3]??1]:[1,1,1,1];te[String(Z)]={node:re>0?m("pointer/interpolate",{configuration:{pointer:Q},values:{value:{value:ie},duration:{value:re}}}):m("pointer/set",{configuration:{pointer:Q},values:{value:{value:ie}}})}}a[H].flows={out:{node:m("flow/switch",{values:{selection:p(k)},flows:te})}},R.push(H)}else if(Y==="playAnimation")R.push(m("animation/start",{configuration:{animation:V.animation??V.clip??0}}));else if(Y==="stopAnimation")R.push(m("animation/stop"));else if(Y==="sendEvent"){let re={};for(let[Q,ee]of Object.entries(V.values||{}))re[Q]={value:ee};R.push(m("event/send",{configuration:{event:f(String(V.event??V.id??"custom"))},values:re}))}}if(!R.length)return null;if(R.length===1)return R[0];let $={};return R.forEach((F,V)=>{$[String(V)]={node:F}}),m("flow/sequence",{flows:$})},C=(_,P,R)=>{let $=N(P);$!==null&&m(_,{...R?{configuration:R}:{},flows:{out:{node:$}}})};if(S.onSelect&&C("pointer/onSelect",S.onSelect,{nodeIndex:b}),S.onHoverIn&&C("pointer/onHoverIn",S.onHoverIn,{nodeIndex:b}),S.onHoverOut&&C("pointer/onHoverOut",S.onHoverOut,{nodeIndex:b}),S.onStart&&C("event/onStart",S.onStart),S.onReceive&&typeof S.onReceive=="object")for(let[_,P]of Object.entries(S.onReceive))C("event/receive",P,{event:f(_)})}return a.length?{graphs:[{declarations:i,nodes:a,variables:s,events:o}],graph:0}:null}var os='SecurityError: Client-modified script compilation (Use Case 1) is disabled by default to satisfy strict CSP and Trusted Types requirements. Use script-src="..." or loadScriptFromSrc(url) for server-generated scripts (Use Case 2), or explicitly opt in via ThreeLiveElement.allowClientScripts = true (or the allow-client-scripts attribute).',is="Security Error: client-side scripts require allow-client-scripts opt-in.",ss="__THREE_LIVE_REGISTRY__";function He(){let e=typeof globalThis<"u"?globalThis:{};if(!e[ss]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(e,ss,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{e[ss]=t}}return e[ss]}var kt=He().plugins;function jn(e){let t=He();t.workerExtensionInstallers||(t.workerExtensionInstallers=[]),t.workerExtensionInstallers.includes(e)||t.workerExtensionInstallers.push(e)}function gt(e){let t=He().plugins;t.some(r=>r.name===e.name)||t.push(e),e.onRegister?.()}function as(){return He().plugins}var md=8192,hd=2048,pd=128,bd=4096;function cs(e,t){if(!e||!e.BufferGeometry)return null;let r=e.Vector2,i=e.Vector3,n=e.Quaternion,a=e.Matrix4,s=e.Matrix3,o=e.Color,l=e.BufferAttribute,c=e.BufferGeometry,f=e.Material,m=e.MeshStandardMaterial,h=e.Mesh,p=8192,g=2048,x=128,v=4096,y=(W,D)=>{let z=W==null?NaN:Number(W);return Number.isFinite(z)?z:D};class A{constructor(D){this.currentPoint=new r(0,0),this.segments=[],Array.isArray(D)&&D.length>0&&this.fromPoints(D)}fromPoints(D){if(!D.length)return this;this.moveTo(D[0].x,D[0].y);for(let z=1;z<D.length;z++)this.lineTo(D[z].x,D[z].y);return this}moveTo(D,z){let O=Number(D)||0,X=Number(z)||0;return this.currentPoint.set(O,X),this.segments.push({type:"move",pts:[O,X]}),this}lineTo(D,z){let O=Number(D)||0,X=Number(z)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[this.currentPoint.x,this.currentPoint.y]}),this.currentPoint.set(O,X),this.segments.push({type:"line",pts:[O,X]}),this}quadraticCurveTo(D,z,O,X){let se=this.currentPoint.x,ce=this.currentPoint.y,pe=Number(D)||0,xe=Number(z)||0,he=Number(O)||0,Ne=Number(X)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[se,ce]}),this.currentPoint.set(he,Ne),this.segments.push({type:"quad",pts:[se,ce,pe,xe,he,Ne]}),this}bezierCurveTo(D,z,O,X,se,ce){let pe=this.currentPoint.x,xe=this.currentPoint.y,he=Number(D)||0,Ne=Number(z)||0,ge=Number(O)||0,Ae=Number(X)||0,Ee=Number(se)||0,De=Number(ce)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[pe,xe]}),this.currentPoint.set(Ee,De),this.segments.push({type:"cubic",pts:[pe,xe,he,Ne,ge,Ae,Ee,De]}),this}absarc(D,z,O,X,se,ce=!1){return this.absellipse(D,z,O,O,X,se,ce,0)}arc(D,z,O,X,se,ce=!1){return this.absarc(this.currentPoint.x+(Number(D)||0),this.currentPoint.y+(Number(z)||0),O,X,se,ce)}absellipse(D,z,O,X,se,ce,pe=!1,xe=0){let he=Number(D)||0,Ne=Number(z)||0,ge=Math.max(0,Number(O)||0),Ae=Math.max(0,Number(X)||0),Ee=Number(se)||0,De=Number(ce)||0,ke=pe?1:0,ze=Number(xe)||0;this.segments.push({type:"arc",pts:[he,Ne,ge,Ae,Ee,De,ke,ze]});let Be=Math.cos(ze),Ue=Math.sin(ze),We=ge*Math.cos(De),Ge=Ae*Math.sin(De);return this.currentPoint.set(he+We*Be-Ge*Ue,Ne+We*Ue+Ge*Be),this}ellipse(D,z,O,X,se,ce,pe=!1,xe=0){return this.absellipse(this.currentPoint.x+(Number(D)||0),this.currentPoint.y+(Number(z)||0),O,X,se,ce,pe,xe)}add(D){if(D&&typeof D.getPoints=="function"){this.segments.push({type:"curve",pts:[],curve:D});let z=D.getPoint?.(1);z&&this.currentPoint.set(Number(z.x)||0,Number(z.y)||0)}return this}splineThru(D){if(!Array.isArray(D)||D.length===0)return this;let z=e.SplineCurve||t?.authorNamespace?.SplineCurve;if(z)return this.add(new z([this.currentPoint.clone(),...D]));for(let O of D)O&&this.lineTo(Number(O.x)||0,Number(O.y)||0);return this}closePath(){if(this.segments.length>0){let D=this.segments[0],z=0,O=0;if(D.type==="curve"&&D.curve?.getPoint){let X=D.curve.getPoint(0);z=Number(X?.x)||0,O=Number(X?.y)||0}else if(D.type==="arc"){let X=D.pts[0],se=D.pts[1],ce=D.pts[2],pe=D.pts[3],xe=D.pts[4],he=D.pts[7],Ne=Math.cos(he),ge=Math.sin(he),Ae=ce*Math.cos(xe),Ee=pe*Math.sin(xe);z=X+Ae*Ne-Ee*ge,O=se+Ae*ge+Ee*Ne}else z=D.pts[0],O=D.pts[1];Math.hypot(this.currentPoint.x-z,this.currentPoint.y-O)>1e-6&&this.lineTo(z,O)}return this}getPoints(D=12){let z=Math.max(1,Math.min(128,Math.floor(Number(D)||12))),O=[],X=(se,ce)=>{if(O.length>0){let pe=O[O.length-1];if(Math.hypot(pe.x-se,pe.y-ce)<1e-6)return}O.push(new r(se,ce))};for(let se of this.segments){let ce=se.pts;if(se.type==="move"||se.type==="line")X(ce[0],ce[1]);else if(se.type==="quad"){let pe=ce[0],xe=ce[1],he=ce[2],Ne=ce[3],ge=ce[4],Ae=ce[5];X(pe,xe);for(let Ee=1;Ee<=z;Ee++){let De=Ee/z,ke=1-De;X(ke*ke*pe+2*ke*De*he+De*De*ge,ke*ke*xe+2*ke*De*Ne+De*De*Ae)}}else if(se.type==="cubic"){let pe=ce[0],xe=ce[1],he=ce[2],Ne=ce[3],ge=ce[4],Ae=ce[5],Ee=ce[6],De=ce[7];X(pe,xe);for(let ke=1;ke<=z;ke++){let ze=ke/z,Be=1-ze,Ue=Be*Be,We=ze*ze;X(Ue*Be*pe+3*Ue*ze*he+3*Be*We*ge+We*ze*Ee,Ue*Be*xe+3*Ue*ze*Ne+3*Be*We*Ae+We*ze*De)}}else if(se.type==="arc"){let pe=ce[0],xe=ce[1],he=ce[2],Ne=ce[3],ge=ce[4],Ae=ce[5],Ee=ce[6]!==0,De=ce[7],ke=Math.PI*2,ze=Ae-ge,Be=Math.abs(ze)<1e-9;for(;ze<0;)ze+=ke;for(;ze>ke;)ze-=ke;ze<1e-9&&(ze=Be?0:ke),Ee&&!Be&&(ze=ze===ke?-ke:ze-ke);let Ue=Math.cos(De),We=Math.sin(De),Ge=Math.max(2,z);for(let ut=0;ut<=Ge;ut++){let nt=ut/Ge,st=ge+nt*ze,ft=he*Math.cos(st),Qe=Ne*Math.sin(st);X(pe+ft*Ue-Qe*We,xe+ft*We+Qe*Ue)}}else if(se.type==="curve"&&se.curve?.getPoints)for(let pe of se.curve.getPoints(z))pe&&X(Number(pe.x)||0,Number(pe.y)||0)}if(O.length>2){let se=O[0],ce=O[O.length-1];Math.hypot(se.x-ce.x,se.y-ce.y)<1e-6&&O.pop()}return O}getSpacedPoints(D=12){return this.getPoints(D)}clone(){let D=new this.constructor;return D.currentPoint.copy(this.currentPoint),D.segments=this.segments.map(z=>({type:z.type,pts:[...z.pts],...z.curve?{curve:z.curve.clone?z.curve.clone():z.curve}:{}})),Array.isArray(this.holes)&&(D.holes=this.holes.map(z=>z.clone())),D}}class b extends A{constructor(D){super(D),this.holes=[]}extractPoints(D=12){return{shape:this.getPoints(D),holes:this.holes.map(z=>z.getPoints(D))}}}function w(W){let D=0,z=W.length;for(let O=0,X=z-1;O<z;X=O++)D+=W[X].x*W[O].y-W[O].x*W[X].y;return D*.5}function S(W,D,z,O,X,se,ce,pe){let xe=ce-z,he=pe-O,Ne=X-z,ge=se-O,Ae=W-z,Ee=D-O,De=xe*xe+he*he,ke=xe*Ne+he*ge,ze=xe*Ae+he*Ee,Be=Ne*Ne+ge*ge,Ue=Ne*Ae+ge*Ee,We=De*Be-ke*ke;if(Math.abs(We)<1e-12)return!1;let Ge=1/We,ut=(Be*ze-ke*Ue)*Ge,nt=(De*Ue-ke*ze)*Ge;return ut>=-1e-7&&nt>=-1e-7&&ut+nt<=1+1e-7}function E(W,D){let z=W.slice();w(z)<0&&z.reverse();let O=z.map(xe=>new r(xe.x,xe.y)),X=z.map((xe,he)=>he),se=[];for(let xe of D){if(!xe||xe.length<3)continue;let he=xe.slice();w(he)>0&&he.reverse();let Ne=[],ge=-1/0,Ae=0;for(let Ee=0;Ee<he.length;Ee++){let De=he[Ee],ke=O.length;O.push(new r(De.x,De.y)),Ne.push(ke),De.x>ge&&(ge=De.x,Ae=Ee)}se.push({pts:he,indices:Ne,maxX:ge,maxIdx:Ae})}se.sort((xe,he)=>he.maxX-xe.maxX);let ce=(xe,he,Ne)=>(he.x-xe.x)*(Ne.y-xe.y)-(he.y-xe.y)*(Ne.x-xe.x),pe=(xe,he,Ne)=>{for(let ge=0;ge<Ne.length;ge++){let Ae=Ne[ge],Ee=Ne[(ge+1)%Ne.length];if(ce(xe,he,Ae)*ce(xe,he,Ee)<0&&ce(Ae,Ee,xe)*ce(Ae,Ee,he)<0)return!0}return!1};for(let xe of se){let he=xe.pts[xe.maxIdx],Ne=he.x,ge=X.length,Ae=X.map(Be=>O[Be]),Ee=Be=>Math.hypot(Ae[Be].x-Ne,Ae[Be].y-he.y),De=Ae.map((Be,Ue)=>Ue).sort((Be,Ue)=>+(Ae[Be].x<Ne)-+(Ae[Ue].x<Ne)||Ee(Be)-Ee(Ue)),ke=De[0];for(let Be of De){let Ue=Ae[Be],We=Ae[(Be+ge-1)%ge],Ge=Ae[(Be+1)%ge],ut=ce(Ue,Ge,he)>=0,nt=ce(We,Ue,he)>=0;if((ce(We,Ue,Ge)>=0?ut&&nt:ut||nt)&&!pe(he,Ue,Ae)&&!se.some(st=>pe(he,Ue,st.pts))){ke=Be;break}}let ze=[];for(let Be=0;Be<=ke;Be++)ze.push(X[Be]);for(let Be=0;Be<=xe.indices.length;Be++){let Ue=xe.indices[(xe.maxIdx+Be)%xe.indices.length];ze.push(Ue)}for(let Be=ke;Be<X.length;Be++)ze.push(X[Be]);X=ze}return{merged:X.map(xe=>O[xe]),mergedIndices:X,allVertices:O}}function N(W,D){let z=[],O=W.slice();if(O.length<3)return z;let X=O.length*O.length+64,se=0;for(;O.length>2&&X-- >0;){let ce=O.length,pe=O[(se+ce-1)%ce],xe=O[se%ce],he=O[(se+1)%ce],Ne=D[pe],ge=D[xe],Ae=D[he];if((ge.x-Ne.x)*(Ae.y-Ne.y)-(ge.y-Ne.y)*(Ae.x-Ne.x)>1e-9){let Ee=!0,De=Math.min(Ne.x,ge.x,Ae.x)-1e-7,ke=Math.max(Ne.x,ge.x,Ae.x)+1e-7,ze=Math.min(Ne.y,ge.y,Ae.y)-1e-7,Be=Math.max(Ne.y,ge.y,Ae.y)+1e-7;for(let Ue=0;Ue<ce;Ue++){let We=O[Ue];if(We===pe||We===xe||We===he)continue;let Ge=D[We];if(Ge.x>=De&&Ge.x<=ke&&Ge.y>=ze&&Ge.y<=Be&&S(Ge.x,Ge.y,Ne.x,Ne.y,ge.x,ge.y,Ae.x,Ae.y)&&(Ge.x-Ne.x)*(Ge.x-Ne.x)+(Ge.y-Ne.y)*(Ge.y-Ne.y)>=1e-12&&(Ge.x-ge.x)*(Ge.x-ge.x)+(Ge.y-ge.y)*(Ge.y-ge.y)>=1e-12&&(Ge.x-Ae.x)*(Ge.x-Ae.x)+(Ge.y-Ae.y)*(Ge.y-Ae.y)>=1e-12){Ee=!1;break}}if(Ee){z.push([pe,xe,he]),O.splice(se%ce,1),se=Math.max(0,se%ce-1);continue}}se++,se>=ce*2&&(z.push([pe,xe,he]),O.splice((se-1)%ce,1),se=0)}return z}function C(W,D){let z=W instanceof b?W.extractPoints(D):{shape:W.getPoints(D),holes:[]},O=z.shape.length;for(let X of z.holes)O+=X.length;if(O>v)throw new RangeError(`SecurityError: shape point count (${O}) exceeds MAX_SHAPE_POINTS (${v})`);return z}function _(W){let D=1/0,z=1/0,O=-1/0,X=-1/0;for(let se of W)se.x<D&&(D=se.x),se.y<z&&(z=se.y),se.x>O&&(O=se.x),se.y>X&&(X=se.y);return[D,z,Math.max(1e-6,O-D),Math.max(1e-6,X-z)]}class P extends c{constructor(D=new b,z=12){super();let O=Array.isArray(D)?D:[D],X=[],se=[],ce=[],pe=[];for(let xe of O){if(!(xe instanceof A))continue;let he=C(xe,z);if(he.shape.length<3)continue;let{mergedIndices:Ne,allVertices:ge}=E(he.shape,he.holes),Ae=N(Ne,ge),Ee=X.length/3,[De,ke,ze,Be]=_(ge);for(let Ue of ge)X.push(Ue.x,Ue.y,0),se.push(0,0,1),ce.push((Ue.x-De)/ze,(Ue.y-ke)/Be);for(let[Ue,We,Ge]of Ae)pe.push(Ee+Ue,Ee+We,Ee+Ge)}R(this,X,se,ce,pe)}}function R(W,D,z,O,X){return W.setAttribute("position",new l(D,3)),W.setAttribute("normal",new l(z,3)),W.setAttribute("uv",new l(O,2)),W.setIndex(X),W}function $(W){let D=W.length,z=[];for(let O=0;O<D;O++){let X=W[(O+D-1)%D],se=W[O],ce=W[(O+1)%D],pe=se.x-X.x,xe=se.y-X.y,he=Math.hypot(pe,xe)||1;pe/=he,xe/=he;let Ne=ce.x-se.x,ge=ce.y-se.y,Ae=Math.hypot(Ne,ge)||1;Ne/=Ae,ge/=Ae;let Ee=xe,De=-pe,ke=ge,ze=-Ne,Be=Ee+ke,Ue=De+ze,We=Math.hypot(Be,Ue);if(We>1e-6){Be/=We,Ue/=We;let Ge=Math.max(.35,Be*Ee+Ue*De);z.push(new r(Be/Ge,Ue/Ge))}else z.push(new r(Ee,De))}return z}class F extends c{constructor(D=new b,z={}){super();let O=Array.isArray(D)?D:[D],X=Math.max(1,Math.min(64,Math.floor(y(z.curveSegments,12)))),se=y(z.depth??z.amount,1),ce=Math.max(1,Math.min(32,Math.floor(y(z.steps,1)))),pe=!!(z.bevelEnabled??!1),xe=pe?Math.max(0,y(z.bevelThickness,.06)):0,he=pe?Math.max(0,y(z.bevelSize,xe*.8)):0,Ne=pe?y(z.bevelOffset,0):0,ge=pe?Math.max(1,Math.min(8,Math.floor(y(z.bevelSegments,2)))):0,Ae=[],Ee=[],De=[],ke=[];for(let ze of O){if(!(ze instanceof A))continue;let Be=C(ze,X);if(Be.shape.length<3)continue;let Ue=Be.shape.slice();w(Ue)<0&&Ue.reverse();let We=[];for(let Pe of Be.holes){if(Pe.length<3)continue;let ot=Pe.slice();w(ot)>0&&ot.reverse(),We.push(ot)}let{mergedIndices:Ge,allVertices:ut}=E(Ue,We),nt=N(Ge,ut),st=[Ue,...We],ft=[];for(let Pe of st){let ot=$(Pe);for(let wt of ot)ft.push(wt)}let[Qe,It,Dt,yr]=_(ut);for(let[Pe,ot]of[[-xe,-1],[se+xe,1]]){let wt=Ae.length/3;for(let St=0;St<ut.length;St++){let Pt=ut[St],Lt=ft[St]??new r(0,0),Zt=Pt.x+Lt.x*Ne,Ot=Pt.y+Lt.y*Ne;Ae.push(Zt,Ot,Pe),Ee.push(0,0,ot),De.push((Zt-Qe)/Dt,(Ot-It)/yr)}for(let[St,Pt,Lt]of nt)ke.push(wt+St,wt+(ot<0?Lt:Pt),wt+(ot<0?Pt:Lt))}let Mt=[];if(pe&&ge>0)for(let Pe=0;Pe<ge;Pe++){let ot=Pe/ge*Math.PI/2;Mt.push({z:-xe*Math.cos(ot),expand:Ne+he*Math.sin(ot)})}for(let Pe=0;Pe<=ce;Pe++){let ot=Pe/ce;Mt.push({z:ot*se,expand:Ne+he})}if(pe&&ge>0)for(let Pe=1;Pe<=ge;Pe++){let ot=Pe/ge*Math.PI/2;Mt.push({z:se+xe*Math.sin(ot),expand:Ne+he*Math.cos(ot)})}let jt=0;for(let Pe of st){let ot=Pe.length;for(let wt=0;wt<Mt.length-1;wt++){let St=Mt[wt],Pt=Mt[wt+1];for(let Lt=0;Lt<ot;Lt++){let Zt=(Lt+1)%ot,Ot=Pe[Lt],Jt=Pe[Zt],er=ft[jt+Lt],tr=ft[jt+Zt],Nr=Ot.x+er.x*St.expand,on=Ot.y+er.y*St.expand,Tn=Jt.x+tr.x*St.expand,rr=Jt.y+tr.y*St.expand,nr=Jt.x+tr.x*Pt.expand,$n=Jt.y+tr.y*Pt.expand,wn=Ot.x+er.x*Pt.expand,cn=Ot.y+er.y*Pt.expand,Cr=Tn-Nr,Kt=rr-on,ul=wn-Nr,ts=cn-on,In=Pt.z-St.z,pn=Kt*In,dn=-Cr*In,gn=Cr*ts-Kt*ul,Pn=Math.hypot(pn,dn,gn)||1;pn/=Pn,dn/=Pn,gn/=Pn;let Ir=Ae.length/3;Ae.push(Nr,on,St.z,Tn,rr,St.z,nr,$n,Pt.z,wn,cn,Pt.z),Ee.push(pn,dn,gn,pn,dn,gn,pn,dn,gn,pn,dn,gn);let rs=Lt/ot,Bo=(Lt+1)/ot,hn=wt/(Mt.length-1),Yr=(wt+1)/(Mt.length-1);De.push(rs,hn,Bo,hn,Bo,Yr,rs,Yr),ke.push(Ir,Ir+1,Ir+2,Ir,Ir+2,Ir+3)}}jt+=ot}}R(this,Ae,Ee,De,ke)}}function V(W){return{x:W.x,y:W.y,z:W.z,nx:W.nx,ny:W.ny,nz:W.nz,u:W.u,v:W.v}}function Y(W){return{x:W.x,y:W.y,z:W.z,nx:-W.nx,ny:-W.ny,nz:-W.nz,u:W.u,v:W.v}}function J(W,D,z){let O=W.nx+(D.nx-W.nx)*z,X=W.ny+(D.ny-W.ny)*z,se=W.nz+(D.nz-W.nz)*z,ce=Math.hypot(O,X,se)||1;return{x:W.x+(D.x-W.x)*z,y:W.y+(D.y-W.y)*z,z:W.z+(D.z-W.z)*z,nx:O/ce,ny:X/ce,nz:se/ce,u:W.u+(D.u-W.u)*z,v:W.v+(D.v-W.v)*z}}function re(W){if(W.length<3)return null;let D=W[0],z=W[1],O=W[2],X=z.x-D.x,se=z.y-D.y,ce=z.z-D.z,pe=O.x-D.x,xe=O.y-D.y,he=O.z-D.z,Ne=se*he-ce*xe,ge=ce*pe-X*he,Ae=X*xe-se*pe,Ee=Math.hypot(Ne,ge,Ae);if(Ee<1e-9)return null;Ne/=Ee,ge/=Ee,Ae/=Ee;let De=Ne*D.x+ge*D.y+Ae*D.z;return{vertices:W,nx:Ne,ny:ge,nz:Ae,w:De}}function Q(W){W.vertices.reverse();for(let D=0;D<W.vertices.length;D++)W.vertices[D]=Y(W.vertices[D]);W.nx=-W.nx,W.ny=-W.ny,W.nz=-W.nz,W.w=-W.w}let ee=1e-5,k=0,G=1,q=2,H=3;function te(W,D,z,O,X,se,ce,pe,xe){let he=0,Ne=[];for(let ge=0;ge<X.vertices.length;ge++){let Ae=X.vertices[ge],Ee=W*Ae.x+D*Ae.y+z*Ae.z-O,De=Ee<-ee?q:Ee>ee?G:k;he|=De,Ne.push(De)}switch(he){case k:{W*X.nx+D*X.ny+z*X.nz>0?se.push(X):ce.push(X);break}case G:pe.push(X);break;case q:xe.push(X);break;case H:{let ge=[],Ae=[],Ee=X.vertices.length;for(let Ue=0;Ue<Ee;Ue++){let We=(Ue+1)%Ee,Ge=Ne[Ue],ut=Ne[We],nt=X.vertices[Ue],st=X.vertices[We];if(Ge!==q&&ge.push(nt),Ge!==G&&Ae.push(Ge!==q?V(nt):nt),(Ge|ut)===H){let ft=st.x-nt.x,Qe=st.y-nt.y,It=st.z-nt.z,Dt=W*ft+D*Qe+z*It,yr=Math.abs(Dt)>1e-12?(O-(W*nt.x+D*nt.y+z*nt.z))/Dt:.5,Mt=J(nt,st,Math.max(0,Math.min(1,yr)));ge.push(Mt),Ae.push(V(Mt))}}let{nx:De,ny:ke,nz:ze,w:Be}=X;ge.length>=3&&pe.push({vertices:ge,nx:De,ny:ke,nz:ze,w:Be}),Ae.length>=3&&xe.push({vertices:Ae,nx:De,ny:ke,nz:ze,w:Be});break}default:break}}class Z{constructor(D,z=0){this.nx=0,this.ny=0,this.nz=0,this.w=0,this.hasPlane=!1,this.polygons=[],this.front=null,this.back=null,D&&D.length>0&&this.build(D,z)}invert(){for(let z=0;z<this.polygons.length;z++)Q(this.polygons[z]);this.nx=-this.nx,this.ny=-this.ny,this.nz=-this.nz,this.w=-this.w,this.front&&this.front.invert(),this.back&&this.back.invert();let D=this.front;this.front=this.back,this.back=D}clipPolygons(D,z=0){if(!this.hasPlane||D.length===0)return D.slice();if(z>=g)throw new RangeError(`SecurityError: CSG BSP depth exceeds MAX_BSP_DEPTH (${g})`);let O=[],X=[];for(let se=0;se<D.length;se++)te(this.nx,this.ny,this.nz,this.w,D[se],O,X,O,X);return this.front&&O.length>0&&(O=this.front.clipPolygons(O,z+1)),this.back?X=X.length>0?this.back.clipPolygons(X,z+1):[]:X=[],O.concat(X)}clipTo(D,z=0){this.polygons.length>0&&(this.polygons=D.clipPolygons(this.polygons,0)),z<g&&(this.front&&this.front.clipTo(D,z+1),this.back&&this.back.clipTo(D,z+1))}allPolygons(D=[]){for(let z=0;z<this.polygons.length;z++)D.push(this.polygons[z]);return this.front&&this.front.allPolygons(D),this.back&&this.back.allPolygons(D),D}build(D,z=0){if(!D.length)return;if(!this.hasPlane){let se=D[D.length>>1];this.nx=se.nx,this.ny=se.ny,this.nz=se.nz,this.w=se.w,this.hasPlane=!0}if(z>=g)throw new RangeError(`SecurityError: CSG BSP depth exceeds MAX_BSP_DEPTH (${g})`);let O=[],X=[];for(let se=0;se<D.length;se++)te(this.nx,this.ny,this.nz,this.w,D[se],this.polygons,this.polygons,O,X);O.length>0&&(this.front||(this.front=new Z),this.front.build(O,z+1)),X.length>0&&(this.back||(this.back=new Z),this.back.build(X,z+1))}}function ae(W,D){if(!D&&W._csgPolygons)return W._csgPolygons;let z=W.attributes.position;if(!z||z.count===0)return[];let O=W.attributes.normal,X=W.attributes.uv,se=W.index?W.index.array:null,ce=Math.floor(se?se.length/3:z.count/3);if(ce>p)throw new RangeError(`SecurityError: CSG input triangle count (${ce}) exceeds MAX_CSG_TRIANGLES (${p})`);let pe=D?D.elements:null,xe=pe?pe[0]*(pe[5]*pe[10]-pe[9]*pe[6])-pe[4]*(pe[1]*pe[10]-pe[9]*pe[2])+pe[8]*(pe[1]*pe[6]-pe[5]*pe[2])<0:!1,he=pe?new s().getNormalMatrix(D).elements:null,Ne=Ae=>{let Ee=z.getX(Ae),De=z.getY(Ae),ke=z.getZ(Ae),ze=O?O.getX(Ae):NaN,Be=O?O.getY(Ae):NaN,Ue=O?O.getZ(Ae):NaN;if(pe&&he){let ut=pe[0]*Ee+pe[4]*De+pe[8]*ke+pe[12],nt=pe[1]*Ee+pe[5]*De+pe[9]*ke+pe[13],st=pe[2]*Ee+pe[6]*De+pe[10]*ke+pe[14];Ee=ut,De=nt,ke=st;let ft=he[0]*ze+he[3]*Be+he[6]*Ue,Qe=he[1]*ze+he[4]*Be+he[7]*Ue,It=he[2]*ze+he[5]*Be+he[8]*Ue,Dt=Math.hypot(ft,Qe,It)||1;ze=ft/Dt,Be=Qe/Dt,Ue=It/Dt}let We=X?X.getX(Ae):0,Ge=X?X.getY(Ae):0;return{x:Ee,y:De,z:ke,nx:ze,ny:Be,nz:Ue,u:We,v:Ge}},ge=[];for(let Ae=0;Ae<ce;Ae++){let Ee=se?se[Ae*3]:Ae*3,De=se?se[Ae*3+1]:Ae*3+1,ke=se?se[Ae*3+2]:Ae*3+2,ze=re(xe?[Ne(Ee),Ne(ke),Ne(De)]:[Ne(Ee),Ne(De),Ne(ke)]);ze&&ge.push(ze)}return ge}function ie(W){let D=[],z=[],O=[],X=[];for(let ce of W){let pe=ce.vertices;if(pe.length<3)continue;let xe=D.length/3;for(let he of pe)D.push(he.x,he.y,he.z),Number.isFinite(he.nx)&&he.nx*he.nx+he.ny*he.ny+he.nz*he.nz>.5?z.push(he.nx,he.ny,he.nz):z.push(ce.nx,ce.ny,ce.nz),O.push(he.u,he.v);for(let he=1;he<pe.length-1;he++)X.push(xe,xe+he,xe+he+1)}let se=R(new c,D,z,O,X);return se._csgPolygons=W,se}function de(W,D,z){if(W.length+D.length>p)throw new RangeError(`SecurityError: Combined CSG triangle count (${W.length+D.length}) exceeds MAX_CSG_TRIANGLES (${p})`);if(W.length===0)return z==="union"?D:[];if(D.length===0)return z==="intersect"?[]:W;let O=1/0,X=1/0,se=1/0,ce=-1/0,pe=-1/0,xe=-1/0;for(let Ee=0;Ee<D.length;Ee++){let De=D[Ee].vertices;for(let ke=0;ke<De.length;ke++){let ze=De[ke];ze.x<O&&(O=ze.x),ze.y<X&&(X=ze.y),ze.z<se&&(se=ze.z),ze.x>ce&&(ce=ze.x),ze.y>pe&&(pe=ze.y),ze.z>xe&&(xe=ze.z)}}O-=1e-4,X-=1e-4,se-=1e-4,ce+=1e-4,pe+=1e-4,xe+=1e-4;let he=[],Ne=[];for(let Ee=0;Ee<W.length;Ee++){let De=W[Ee],ke=De.vertices,ze=1/0,Be=1/0,Ue=1/0,We=-1/0,Ge=-1/0,ut=-1/0;for(let nt=0;nt<ke.length;nt++){let st=ke[nt];st.x<ze&&(ze=st.x),st.y<Be&&(Be=st.y),st.z<Ue&&(Ue=st.z),st.x>We&&(We=st.x),st.y>Ge&&(Ge=st.y),st.z>ut&&(ut=st.z)}We<O||ze>ce||Ge<X||Be>pe||ut<se||Ue>xe?Ne.push(De):he.push(De)}if(he.length===0)return z==="union"?W.concat(D):z==="subtract"?W:[];let ge=new Z(he),Ae=new Z(D);return z==="union"?(ge.clipTo(Ae),Ae.clipTo(ge),Ae.invert(),Ae.clipTo(ge),Ae.invert(),ge.build(Ae.allPolygons()),Ne.concat(ge.allPolygons())):z==="subtract"?(ge.invert(),ge.clipTo(Ae),Ae.clipTo(ge),Ae.invert(),Ae.clipTo(ge),Ae.invert(),ge.build(Ae.allPolygons()),ge.invert(),Ne.concat(ge.allPolygons())):(ge.invert(),Ae.clipTo(ge),Ae.invert(),ge.clipTo(Ae),Ae.clipTo(ge),ge.build(Ae.allPolygons()),ge.invert(),ge.allPolygons())}function me(W,D,z,O=null,X=null){let se=ae(W,O),ce=ae(D,X);return ie(de(se,ce,z))}function Se(W,D,z){let O=W instanceof h||!!W?.isMesh,X=D instanceof h||!!D?.isMesh,se=O?W.geometry:W,ce=X?D.geometry:D,pe=null;if(X)if(D.updateMatrix(),O){W.updateMatrix();let ge=new a().makeScale(1/(W.scale.x||1),1/(W.scale.y||1),1/(W.scale.z||1)),Ae=Math.hypot(W.quaternion.x,W.quaternion.y,W.quaternion.z,W.quaternion.w)||1,Ee=new a().compose(new i(0,0,0),new n(-W.quaternion.x/Ae,-W.quaternion.y/Ae,-W.quaternion.z/Ae,W.quaternion.w/Ae),new i(1,1,1)),De=new a().makeTranslation(-W.position.x,-W.position.y,-W.position.z);pe=ge.multiply(Ee).multiply(De).multiply(D.matrix)}else pe=D.matrix;let xe=me(se,ce,z,null,pe),he=O?W.material:new m,Ne=new h(xe,he);return O&&(Ne.position.copy(W.position),Ne.quaternion.copy(W.quaternion),Ne.scale.copy(W.scale),Ne.name=W.name),Ne}let Fe={toGeometry:me,subtract(W,D){return Se(W,D,"subtract")},union(W,D){return Se(W,D,"union")},intersect(W,D){return Se(W,D,"intersect")}},_e={0:[[[.15,0],[.85,0],[.85,1],[.15,1],[.15,0]]],1:[[[.3,.8],[.5,1],[.5,0]],[[.2,0],[.8,0]]],2:[[[.15,.8],[.3,1],[.7,1],[.85,.8],[.85,.55],[.15,0],[.85,0]]],3:[[[.15,.85],[.3,1],[.75,1],[.85,.75],[.5,.5],[.85,.25],[.75,0],[.3,0],[.15,.15]]],4:[[[.7,0],[.7,1],[.15,.35],[.9,.35]]],5:[[[.85,1],[.2,1],[.15,.55],[.75,.55],[.85,.3],[.75,0],[.2,0]]],6:[[[.8,.9],[.5,1],[.15,.7],[.15,.15],[.5,0],[.85,.2],[.85,.45],[.5,.55],[.15,.45]]],7:[[[.15,1],[.85,1],[.35,0]]],8:[[[.2,.5],[.15,.75],[.3,1],[.7,1],[.85,.75],[.8,.5],[.2,.5],[.15,.2],[.3,0],[.7,0],[.85,.2],[.8,.5]]],9:[[[.85,.55],[.5,.45],[.15,.55],[.15,.85],[.5,1],[.85,.85],[.85,.2],[.5,0],[.2,.1]]],A:[[[.1,0],[.5,1],[.9,0]],[[.25,.35],[.75,.35]]],B:[[[.15,0],[.15,1],[.7,1],[.85,.75],[.7,.5],[.15,.5]],[[.7,.5],[.85,.25],[.7,0],[.15,0]]],C:[[[.85,.8],[.65,1],[.3,1],[.15,.75],[.15,.25],[.3,0],[.65,0],[.85,.2]]],D:[[[.15,0],[.15,1],[.65,1],[.85,.75],[.85,.25],[.65,0],[.15,0]]],E:[[[.85,1],[.15,1],[.15,0],[.85,0]],[[.15,.5],[.7,.5]]],F:[[[.85,1],[.15,1],[.15,0]],[[.15,.5],[.7,.5]]],G:[[[.85,.8],[.65,1],[.3,1],[.15,.75],[.15,.25],[.3,0],[.85,0],[.85,.45],[.55,.45]]],H:[[[.15,0],[.15,1]],[[.85,0],[.85,1]],[[.15,.5],[.85,.5]]],I:[[[.25,1],[.75,1]],[[.5,1],[.5,0]],[[.25,0],[.75,0]]],J:[[[.8,1],[.8,.25],[.6,0],[.3,0],[.15,.25]]],K:[[[.15,0],[.15,1]],[[.85,1],[.15,.45],[.85,0]]],L:[[[.15,1],[.15,0],[.85,0]]],M:[[[.1,0],[.1,1],[.5,.35],[.9,1],[.9,0]]],N:[[[.15,0],[.15,1],[.85,0],[.85,1]]],O:[[[.3,0],[.7,0],[.85,.25],[.85,.75],[.7,1],[.3,1],[.15,.75],[.15,.25],[.3,0]]],P:[[[.15,0],[.15,1],[.7,1],[.85,.75],[.7,.5],[.15,.5]]],Q:[[[.3,0],[.7,0],[.85,.25],[.85,.75],[.7,1],[.3,1],[.15,.75],[.15,.25],[.3,0]],[[.55,.3],[.9,-.05]]],R:[[[.15,0],[.15,1],[.7,1],[.85,.75],[.7,.5],[.15,.5]],[[.55,.5],[.85,0]]],S:[[[.85,.85],[.65,1],[.3,1],[.15,.75],[.85,.25],[.7,0],[.3,0],[.15,.15]]],T:[[[.1,1],[.9,1]],[[.5,1],[.5,0]]],U:[[[.15,1],[.15,.25],[.35,0],[.65,0],[.85,.25],[.85,1]]],V:[[[.1,1],[.5,0],[.9,1]]],W:[[[.05,1],[.25,0],[.5,.65],[.75,0],[.95,1]]],X:[[[.15,1],[.85,0]],[[.85,1],[.15,0]]],Y:[[[.15,1],[.5,.5],[.85,1]],[[.5,.5],[.5,0]]],Z:[[[.15,1],[.85,1],[.15,0],[.85,0]]],".":[[[.45,0],[.55,0],[.55,.12],[.45,.12],[.45,0]]],",":[[[.5,.15],[.4,-.1]]],":":[[[.45,.1],[.55,.1]],[[.45,.7],[.55,.7]]],"-":[[[.2,.5],[.8,.5]]],"+":[[[.2,.5],[.8,.5]],[[.5,.2],[.5,.8]]],"=":[[[.2,.35],[.8,.35]],[[.2,.65],[.8,.65]]],"/":[[[.2,0],[.8,1]]],"!":[[[.5,1],[.5,.28]],[[.5,.1],[.5,0]]],"?":[[[.2,.8],[.35,1],[.7,1],[.85,.75],[.5,.45],[.5,.28]],[[.5,.1],[.5,0]]],"(":[[[.65,1],[.35,.65],[.35,.35],[.65,0]]],")":[[[.35,1],[.65,.65],[.65,.35],[.35,0]]],"%":[[[.2,0],[.8,1]],[[.2,.8],[.35,.8],[.35,.95],[.2,.95],[.2,.8]],[[.65,.05],[.8,.05],[.8,.2],[.65,.2],[.65,.05]]],"#":[[[.32,0],[.32,1]],[[.68,0],[.68,1]],[[.12,.35],[.88,.35]],[[.12,.65],[.88,.65]]],$:[[[.8,.8],[.6,.92],[.3,.92],[.18,.72],[.82,.28],[.7,.08],[.4,.08],[.2,.2]],[[.5,1],[.5,0]]],_:[[[.1,0],[.9,0]]],"[":[[[.65,1],[.3,1],[.3,0],[.65,0]]],"]":[[[.35,1],[.7,1],[.7,0],[.35,0]]],"<":[[[.75,.85],[.25,.5],[.75,.15]]],">":[[[.25,.85],[.75,.5],[.25,.15]]],"*":[[[.5,.2],[.5,.8]],[[.2,.35],[.8,.65]],[[.2,.65],[.8,.35]]],"\\":[[[.2,1],[.8,0]]]};class Le extends c{constructor(D="",z={}){super();let O=String(D??"").slice(0,x),X=Math.max(.005,Math.min(100,y(z.size,.2))),se=!!(z.bevelEnabled??!1),ce=se?Math.max(0,Math.min(2,y(z.bevelThickness,X*.04))):0,pe=se?Math.max(0,Math.min(2,y(z.bevelSize,X*.03))):0,xe=Math.max(.001,Math.min(20,y(z.depth??z.height,X*.2)))+ce*2,he=X*.085+pe,Ne=X*.68,ge=X*.82,Ae=[],Ee=[],De=[],ke=[],ze=(We,Ge,ut,nt,st,ft,Qe)=>{let It=ut-We,Dt=nt-Ge,yr=Math.hypot(It,Dt),Mt=1,jt=0;yr>1e-6&&(Mt=It/yr,jt=Dt/yr);let Pe=-jt*st,ot=Mt*st,wt=Mt*st*.6,St=jt*st*.6,Pt=We-wt+Pe,Lt=Ge-St+ot,Zt=We-wt-Pe,Ot=Ge-St-ot,Jt=ut+wt-Pe,er=nt+St-ot,tr=ut+wt+Pe,Nr=nt+St+ot,on=(Tn,rr,nr,$n,wn,cn,Cr)=>{let Kt=Ae.length/3;Ae.push(Tn[0],Tn[1],Tn[2],rr[0],rr[1],rr[2],nr[0],nr[1],nr[2],$n[0],$n[1],$n[2]),Ee.push(wn,cn,Cr,wn,cn,Cr,wn,cn,Cr,wn,cn,Cr),De.push(0,0,1,0,1,1,0,1),ke.push(Kt,Kt+1,Kt+2,Kt,Kt+2,Kt+3)};on([Pt,Lt,Qe],[Zt,Ot,Qe],[Jt,er,Qe],[tr,Nr,Qe],0,0,1),on([Zt,Ot,ft],[Pt,Lt,ft],[tr,Nr,ft],[Jt,er,ft],0,0,-1),on([Pt,Lt,ft],[Zt,Ot,ft],[Zt,Ot,Qe],[Pt,Lt,Qe],-Mt,-jt,0),on([Jt,er,ft],[tr,Nr,ft],[tr,Nr,Qe],[Jt,er,Qe],Mt,jt,0),on([Zt,Ot,ft],[Jt,er,ft],[Jt,er,Qe],[Zt,Ot,Qe],jt,-Mt,0),on([tr,Nr,ft],[Pt,Lt,ft],[Pt,Lt,Qe],[tr,Nr,Qe],-jt,Mt,0)},Be=0,Ue=0;for(let We=0;We<O.length;We++){let Ge=O[We];if(Ge===`
|
|
17
|
+
`){Be=0,Ue-=X*1.35;continue}if(Ge===" "||Ge===" "){Be+=ge*(Ge===" "?.75:3);continue}if(Ge==="\r")continue;let ut=Ge.toUpperCase(),nt=Ge!==ut&&Ge>="a"&&Ge<="z",st=_e[ut]??_e["?"],ft=nt?X*.76:X,Qe=nt?Ne*.88:Ne;for(let It of st)for(let Dt=0;Dt<It.length-1;Dt++){let yr=It[Dt],Mt=It[Dt+1];ze(Be+yr[0]*Qe,Ue+yr[1]*ft,Be+Mt[0]*Qe,Ue+Mt[1]*ft,he,-xe*.5,xe*.5)}Be+=nt?ge*.88:ge}R(this,Ae,Ee,De,ke),z.center!==!1?this.center():this.computeBoundingBox()}}function ne(W){if(!W)return;let D=W,z=W.userData?.xr?.text??W.userData?.xr?.label??W.userData?.xr?.title??W.userData?.xr?.caption??W.userData?.xr?.spatialLabel;if(z!=null&&z!==!1){let X=D.geometry?.attributes?.position;if((!X||X.count===0)&&W.userData._textApplied!==!0){let se="",ce=.08,pe=.015,xe;if(typeof z=="string"||typeof z=="number")se=String(z);else if(typeof z=="object"){let he=z;se=String(he.text??he.value??""),he.size!==void 0&&(ce=Number(he.size)||.08),(he.depth!==void 0||he.height!==void 0)&&(pe=Number(he.depth??he.height)||ce*.2),(typeof he.color=="string"||typeof he.color=="number")&&(xe=he.color)}se.trim().length>0&&(D.geometry=new Le(se,{size:ce,depth:pe}),W.userData._textApplied=!0,D.material instanceof f?xe!==void 0&&W.userData._autoTextColorApplied!==!0&&(D.material.color=new o(xe),W.userData._autoTextColorApplied=!0):D.material=new m({color:xe??16317180}))}}let O=W.userData?.csg;if(O&&typeof O=="object"&&W.userData._csgApplied!==!0&&D.geometry instanceof c&&D.geometry.attributes.position?.count>0){W.userData._csgApplied=!0;let X=Array.isArray(O)?O:[O],se=D.geometry;for(let ce of X){if(!ce||typeof ce!="object")continue;let pe=ce,xe=String(pe.op??pe.operation??"subtract"),he=xe==="union"||xe==="intersect"?xe:"subtract",Ne=pe.target??pe.mesh??pe.geometry;if(Ne instanceof h||Ne instanceof c)try{let ge=he==="union"?Fe.union(D,Ne):he==="intersect"?Fe.intersect(D,Ne):Fe.subtract(D,Ne);D.geometry!==se&&D.geometry.dispose?.(),D.geometry=ge.geometry}catch(ge){typeof console<"u"&&console.warn("[three-live] userData.csg skipped:",ge)}}}}let Re={Path:A,Shape:b,ShapeGeometry:P,ExtrudeGeometry:F,TextGeometry:Le,CSG:Fe,MAX_CSG_TRIANGLES:p,MAX_BSP_DEPTH:g,MAX_TEXT_GEOMETRY_CHARS:x,MAX_SHAPE_POINTS:v,materializeDeclarativeGeometry:ne};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,Re),t._cadMaterialize=ne,t.materializeDeclarativeGeometry=W=>{t._cadMaterialize?.(W),t._lodMaterialize?.(W),t._procMaterialize?.(W)}),Re}var kc={name:"cad",onRegister(){jn(cs);let e=He(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t&&cs(t,e)}};function rt(){let e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function Oo(e,t,r,i,n){let a=1/Math.tan(t/2);e.fill(0),e[0]=a/r,e[5]=a,e[11]=-1;let s=1/(i-n);return e[10]=(n+i)*s,e[14]=2*n*i*s,e}function yd(e,t,r,i,n,a,s){let o=1/(t-r),l=1/(i-n),c=1/(a-s);return e.fill(0),e[0]=-2*o,e[5]=-2*l,e[10]=2*c,e[12]=(t+r)*o,e[13]=(n+i)*l,e[14]=(s+a)*c,e[15]=1,e}function xr(e,t,r,i){let[n,a,s]=t,[o,l,c]=i,[f,m,h]=r,p=n-f,g=a-m,x=s-h,v=Math.hypot(p,g,x);v<=1e-5?(p=0,g=0,x=1):(p/=v,g/=v,x/=v);let y=l*x-c*g,A=c*p-o*x,b=o*g-l*p;v=Math.hypot(y,A,b),v<=1e-5?(y=0,A=0,b=0):(y/=v,A/=v,b/=v);let w=g*b-x*A,S=x*y-p*b,E=p*A-g*y;return v=Math.hypot(w,S,E),v<=1e-5?(w=0,S=0,E=0):(w/=v,S/=v,E/=v),e[0]=y,e[1]=w,e[2]=p,e[3]=0,e[4]=A,e[5]=S,e[6]=g,e[7]=0,e[8]=b,e[9]=E,e[10]=x,e[11]=0,e[12]=-(y*n+A*a+b*s),e[13]=-(w*n+S*a+E*s),e[14]=-(p*n+g*a+x*s),e[15]=1,e}function at(e,t,r){let i=t[0],n=t[1],a=t[2],s=t[3],o=t[4],l=t[5],c=t[6],f=t[7],m=t[8],h=t[9],p=t[10],g=t[11],x=t[12],v=t[13],y=t[14],A=t[15],b=r[0],w=r[1],S=r[2],E=r[3];return e[0]=b*i+w*o+S*m+E*x,e[1]=b*n+w*l+S*h+E*v,e[2]=b*a+w*c+S*p+E*y,e[3]=b*s+w*f+S*g+E*A,b=r[4],w=r[5],S=r[6],E=r[7],e[4]=b*i+w*o+S*m+E*x,e[5]=b*n+w*l+S*h+E*v,e[6]=b*a+w*c+S*p+E*y,e[7]=b*s+w*f+S*g+E*A,b=r[8],w=r[9],S=r[10],E=r[11],e[8]=b*i+w*o+S*m+E*x,e[9]=b*n+w*l+S*h+E*v,e[10]=b*a+w*c+S*p+E*y,e[11]=b*s+w*f+S*g+E*A,b=r[12],w=r[13],S=r[14],E=r[15],e[12]=b*i+w*o+S*m+E*x,e[13]=b*n+w*l+S*h+E*v,e[14]=b*a+w*c+S*p+E*y,e[15]=b*s+w*f+S*g+E*A,e}function or(e,t,r,i){let n=t[0],a=t[1],s=t[2],o=t[3],l=n+n,c=a+a,f=s+s,m=n*l,h=n*c,p=n*f,g=a*c,x=a*f,v=s*f,y=o*l,A=o*c,b=o*f,w=i[0],S=i[1],E=i[2];return e[0]=(1-(g+v))*w,e[1]=(h+b)*w,e[2]=(p-A)*w,e[3]=0,e[4]=(h-b)*S,e[5]=(1-(m+v))*S,e[6]=(x+y)*S,e[7]=0,e[8]=(p+A)*E,e[9]=(x-y)*E,e[10]=(1-(m+g))*E,e[11]=0,e[12]=r[0],e[13]=r[1],e[14]=r[2],e[15]=1,e}function Bt(e,t,r=0){let i=t[0],n=t[1],a=t[2],s=t[4],o=t[5],l=t[6],c=t[8],f=t[9],m=t[10],h=m*o-l*f,p=-m*s+l*c,g=f*s-o*c,x=i*h+n*p+a*g;return!x||r>0&&(!Number.isFinite(x)||Math.abs(x)<=r)||(x=1/x,e[0]=h*x,e[1]=p*x,e[2]=g*x,e[3]=(-m*n+a*f)*x,e[4]=(m*i-a*c)*x,e[5]=(-f*i+n*c)*x,e[6]=(l*n-a*o)*x,e[7]=(-l*i+a*s)*x,e[8]=(o*i-n*s)*x),e}function Kr(e,t){let r=t[0],i=t[1],n=t[2],a=t[3],s=t[4],o=t[5],l=t[6],c=t[7],f=t[8],m=t[9],h=t[10],p=t[11],g=t[12],x=t[13],v=t[14],y=t[15],A=r*o-i*s,b=r*l-n*s,w=r*c-a*s,S=i*l-n*o,E=i*c-a*o,N=n*c-a*l,C=f*x-m*g,_=f*v-h*g,P=f*y-p*g,R=m*v-h*x,$=m*y-p*x,F=h*y-p*v,V=A*F-b*$+w*R+S*P-E*_+N*C;return V?(V=1/V,e[0]=(o*F-l*$+c*R)*V,e[1]=(n*$-i*F-a*R)*V,e[2]=(x*N-v*E+y*S)*V,e[3]=(h*E-m*N-p*S)*V,e[4]=(l*P-s*F-c*_)*V,e[5]=(r*F-n*P+a*_)*V,e[6]=(v*w-g*N-y*b)*V,e[7]=(f*N-h*w+p*b)*V,e[8]=(s*$-o*P+c*C)*V,e[9]=(i*P-r*$-a*C)*V,e[10]=(g*E-x*w+y*A)*V,e[11]=(m*w-f*E-p*A)*V,e[12]=(o*_-s*R-l*C)*V,e[13]=(r*R-i*_+n*C)*V,e[14]=(x*b-g*S-v*A)*V,e[15]=(f*S-m*b+h*A)*V,e):null}function Rc(e,t,r,i,n){let a=n[0]*t+n[4]*r+n[8]*i+n[12],s=n[1]*t+n[5]*r+n[9]*i+n[13],o=n[2]*t+n[6]*r+n[10]*i+n[14],l=n[3]*t+n[7]*r+n[11]*i+n[15],c=l!==0?1/l:1;e[0]=a*c,e[1]=s*c,e[2]=o*c}function gd(e,t,r,i,n,a,s,o,l,c,f,m,h,p,g,x,v=0){let y=c-s,A=f-o,b=m-l,w=h-s,S=p-o,E=g-l,N=n*E-a*S,C=a*w-i*E,_=i*S-n*w,P=y*N+A*C+b*_;if(P>-1e-7&&P<1e-7)return!1;let R=1/P,$=e-s,F=t-o,V=r-l,Y=R*($*N+F*C+V*_);if(Y<-v||Y>1+v)return!1;let J=F*b-V*A,re=V*y-$*b,Q=$*A-F*y,ee=R*(i*J+n*re+a*Q);if(ee<-v||Y+ee>1+v)return!1;let k=R*(w*J+S*re+E*Q);if(k>1e-4&&k<x.distance){x.distance=k,x.point=[e+i*k,t+n*k,r+a*k];let G=A*E-b*S,q=b*w-y*E,H=y*S-A*w,te=Math.hypot(G,q,H)||1;return x.normal=[G/te,q/te,H/te],!0}return!1}function vr(e,t){let r=Array.isArray(e?.nodes)?e.nodes.length:0,i=[];for(let f=0;f<r;f++)i.push(rt());if(r===0)return i;let n=new Set;for(let f of e.nodes)if(Array.isArray(f.children))for(let m of f.children)n.add(m);let a=new Set,s=128,o=(f,m,h=0)=>{if(h>s||f<0||f>=r||a.has(f))return;a.add(f);let p=e.nodes[f];if(!p)return;let g=rt();if(t&&t[f])g.set(t[f]);else if(p.matrix&&p.matrix.length===16)g.set(p.matrix);else{let v=p.translation||[0,0,0],y=p.rotation||[0,0,0,1],A=p.scale||[1,1,1];or(g,y,v,A)}let x=i[f];if(m?at(x,m,g):x.set(g),Array.isArray(p.children))for(let v of p.children)typeof v=="number"&&o(v,x,h+1)},l=[],c=e.scenes&&e.scenes[e.scene!==void 0?e.scene:0];if(c&&Array.isArray(c.nodes))l.push(...c.nodes);else for(let f=0;f<r;f++)n.has(f)||l.push(f);for(let f of l)o(f,null);for(let f=0;f<r;f++)!n.has(f)&&!l.includes(f)&&o(f,null);return i}function Ic(e,t){function r(l,c,f,m){let h=typeof l=="number"?l:Number(l);return Number.isFinite(h)?Math.max(c,Math.min(f,h)):m}function i(l,c){let f=l[0]*c[0]+l[1]*c[1]+l[2]*c[2]+1;if(f<1e-6){if(Math.abs(l[0])>Math.abs(l[2])){let v=Math.hypot(l[1],l[0])||1;return[-l[1]/v,l[0]/v,0,0]}let x=Math.hypot(l[2],l[1])||1;return[0,-l[2]/x,l[1]/x,0]}let m=l[1]*c[2]-l[2]*c[1],h=l[2]*c[0]-l[0]*c[2],p=l[0]*c[1]-l[1]*c[0],g=Math.hypot(m,h,p,f)||1;return[m/g,h/g,p/g,f/g]}function n(l,c,f,m,h){let p=c[0]-l[0],g=c[1]-l[1],x=c[2]-l[2],v=Math.hypot(p,g,x),y=f[0]-c[0],A=f[1]-c[1],b=f[2]-c[2],w=Math.hypot(y,A,b);if(v<1e-6||w<1e-6)return{rootPos:[l[0],l[1],l[2]],midPos:[c[0],c[1],c[2]],effectorPos:[f[0],f[1],f[2]],rootRotation:[0,0,0,1],midRotation:[0,0,0,1]};let S=[p/v,g/v,x/v],E=[y/w,A/w,b/w],N=m[0]-l[0],C=m[1]-l[1],_=m[2]-l[2],P=Math.hypot(N,C,_),R=P>1e-6?[N/P,C/P,_/P]:S,$=Math.abs(v-w)+1e-5,F=Math.max($,v+w-1e-5),V=Math.max($,Math.min(F,P>1e-6?P:$)),Y=r((v*v+V*V-w*w)/(2*v*V),-1,1,1),J=Math.sqrt(Math.max(0,1-Y*Y)),re=h?h[0]-l[0]:p,Q=h?h[1]-l[1]:g,ee=h?h[2]-l[2]:x,k=re*R[0]+Q*R[1]+ee*R[2],G=re-R[0]*k,q=Q-R[1]*k,H=ee-R[2]*k,te=Math.hypot(G,q,H);if(te<=1e-6){let Re=Math.abs(R[1])<.99?0:1,W=Math.abs(R[1])<.99?1:0,D=0;G=R[1]*D-R[2]*W,q=R[2]*Re-R[0]*D,H=R[0]*W-R[1]*Re,te=Math.hypot(G,q,H)||1}let Z=[G/te,q/te,H/te],ae=[l[0]+R[0]*(v*Y)+Z[0]*(v*J),l[1]+R[1]*(v*Y)+Z[1]*(v*J),l[2]+R[2]*(v*Y)+Z[2]*(v*J)],ie=[l[0]+R[0]*V,l[1]+R[1]*V,l[2]+R[2]*V],de=ie[0]-ae[0],me=ie[1]-ae[1],Se=ie[2]-ae[2],Fe=Math.hypot(de,me,Se),_e=Fe>1e-6?[de/Fe,me/Fe,Se/Fe]:R,Le=[ae[0]+_e[0]*w,ae[1]+_e[1]*w,ae[2]+_e[2]*w],ne=[(ae[0]-l[0])/v,(ae[1]-l[1])/v,(ae[2]-l[2])/v];return{rootPos:[l[0],l[1],l[2]],midPos:ae,effectorPos:Le,rootRotation:i(S,ne),midRotation:i(E,_e)}}function a(l,c,f=8,m=.001){let h=l.length;if(h<2)return{positions:l.map(P=>[P[0],P[1],P[2]]),rotations:[],iterations:0};let p=l.map(P=>[P[0],P[1],P[2]]),g=[],x=[],v=0;for(let P=0;P<h-1;P++){let R=p[P+1][0]-p[P][0],$=p[P+1][1]-p[P][1],F=p[P+1][2]-p[P][2],V=Math.hypot(R,$,F);g.push(V),v+=V,x.push(V>1e-6?[R/V,$/V,F/V]:[0,1,0])}let y=[p[0][0],p[0][1],p[0][2]],A=Math.round(r(f,1,32,8)),b=r(m,1e-5,.1,.001),w=c[0]-y[0],S=c[1]-y[1],E=c[2]-y[2],N=Math.hypot(w,S,E),C=0;if(N>=v&&v>1e-6){let P=N>1e-6?[w/N,S/N,E/N]:x[0];p[0]=[y[0],y[1],y[2]];for(let R=0;R<h-1;R++){let $=g[R];p[R+1]=[p[R][0]+P[0]*$,p[R][1]+P[1]*$,p[R][2]+P[2]*$]}C=1}else for(let P=1;P<=A;P++){let R=p[h-1];if(Math.hypot(R[0]-c[0],R[1]-c[1],R[2]-c[2])<=b)break;C=P;let $=(F,V,Y,J,re)=>{let Q=V[0]-F[0],ee=V[1]-F[1],k=V[2]-F[2],G=Math.hypot(Q,ee,k);if(G>1e-6){let q=Y/G;return[F[0]+Q*q,F[1]+ee*q,F[2]+k*q]}return[F[0]+J[0]*Y*re,F[1]+J[1]*Y*re,F[2]+J[2]*Y*re]};p[h-1]=[c[0],c[1],c[2]];for(let F=h-2;F>=0;F--)p[F]=$(p[F+1],p[F],g[F],x[F],-1);p[0]=[y[0],y[1],y[2]];for(let F=0;F<h-1;F++)p[F+1]=$(p[F],p[F+1],g[F],x[F],1)}let _=[];for(let P=0;P<h-1;P++){let R=p[P+1][0]-p[P][0],$=p[P+1][1]-p[P][1],F=p[P+1][2]-p[P][2],V=Math.hypot(R,$,F),Y=V>1e-6?[R/V,$/V,F/V]:x[P];_.push(i(x[P],Y))}return{positions:p,rotations:_,iterations:C}}function s(l){if(!l||typeof l!="object"||Array.isArray(l))return null;let c=l;if(c.enabled===!1)return null;let f=b=>{if(typeof b!="string")return;let w=b.trim().slice(0,64);return/^[A-Za-z0-9_.:-]+$/.test(w)?w:void 0},m=b=>Array.isArray(b)&&b.length===3&&b.every(w=>typeof w=="number"&&Number.isFinite(w))?[r(b[0],-1e3,1e3,0),r(b[1],-1e3,1e3,0),r(b[2],-1e3,1e3,0)]:void 0,h=f(c.root),p=f(c.effector);if(!h||!p)return null;let g=f(c.mid),x=m(c.target)??f(c.target);if(!x)return null;let v=c.pole??c.poleTarget,y=m(v)??f(v),A=c.solver==="fabrik"?"fabrik":c.solver==="two-bone"||g?"two-bone":"fabrik";return{root:h,...g?{mid:g}:{},effector:p,target:x,...y?{pole:y}:{},solver:A,iterations:Math.round(r(c.iterations,1,32,8)),tolerance:r(c.tolerance,1e-5,.1,.001),weight:r(c.weight,0,1,1)}}let o=Object.freeze({solveTwoBone:n,solveFABRIK:a,parseIKTrait:s});return t&&typeof t=="object"&&(t.authorNamespace=t.authorNamespace||{},t.authorNamespace.IKSolver=o),{clampNum:r,parseIKTrait:s,quatFromUnitVectors:i,solveTwoBoneIK:n,solveFABRIK:a,IKSolver:o}}var Jr=Ic(),vd=Jr.clampNum,np=Jr.parseIKTrait,us=Jr.quatFromUnitVectors,Dc=Jr.solveTwoBoneIK,Uc=Jr.solveFABRIK,wd=Jr.IKSolver;function Cc(e){let t=e?.transform??e?.modelMatrix;return t&&t.length>=16?[t[12]||0,t[13]||0,t[14]||0]:[0,0,0]}function rp(e,t){let r=e?.transform??e?.modelMatrix;!r||r.length<16||(r[12]=t[0],r[13]=t[1],r[14]=t[2])}function op(e,t,r,i,n){let a=vd(n,0,1,1),s=t[0]+(r[0]-t[0])*a,o=t[1]+(r[1]-t[1])*a,l=t[2]+(r[2]-t[2])*a,c=s-e[0],f=o-e[1],m=l-e[2],h=Math.hypot(c,f,m);if(h>1e-6&&i>1e-6){let y=i/h;return[e[0]+c*y,e[1]+f*y,e[2]+m*y]}let p=r[0]-e[0],g=r[1]-e[1],x=r[2]-e[2],v=Math.hypot(p,g,x);if(v>1e-6&&i>1e-6){let y=i/v;return[e[0]+p*y,e[1]+g*y,e[2]+x*y]}return[s,o,l]}function ip(e,t){let r=e?.modelRootMatrix;if(!r||r.length!==16)return t;let i=new Float32Array(16);return Kr(i,r instanceof Float32Array?r:Float32Array.from(r))?[i[0]*t[0]+i[4]*t[1]+i[8]*t[2]+i[12],i[1]*t[0]+i[5]*t[1]+i[9]*t[2]+i[13],i[2]*t[0]+i[6]*t[1]+i[10]*t[2]+i[14]]:t}function Lc(e,t){e.__ikWarned||(e.__ikWarned=new Set);let r=e.__ikWarned;r.has(t)||(r.add(t),console.warn(`[three-live] ik: joint '${t}' on '${e?.name??""}' not found among scene nodes or meshes.`))}function Nc(e,t,r){if(Array.isArray(e))return[e[0],e[1],e[2]];let i=t.get(e);if(i)return Cc(i);let n;if(e==="head"?n=r?.headPose?.position??r?.headPose??r?.cameraPosition:e==="hand-left"?n=r?.handPoses?.left?.position??r?.handPoses?.left??r?.hands?.left?.position??r?.hands?.left:e==="hand-right"&&(n=r?.handPoses?.right?.position??r?.handPoses?.right??r?.hands?.right?.position??r?.hands?.right),(Array.isArray(n)||ArrayBuffer.isView(n))&&n.length>=3){let a=n;return ip(r,[a[0],a[1],a[2]])}return null}function Pc(e,t){return[e[3]*t[0]+e[0]*t[3]+e[1]*t[2]-e[2]*t[1],e[3]*t[1]-e[0]*t[2]+e[1]*t[3]+e[2]*t[0],e[3]*t[2]+e[0]*t[1]-e[1]*t[0]+e[2]*t[3],e[3]*t[3]-e[0]*t[0]-e[1]*t[1]-e[2]*t[2]]}function sp(e){return[-e[0],-e[1],-e[2],e[3]]}function Bc(e){let t=Math.hypot(e[0],e[1],e[2],e[3]);return t>1e-12?[e[0]/t,e[1]/t,e[2]/t,e[3]/t]:[0,0,0,1]}function ap(e,t){if(t>=1)return e;if(t<=0)return[0,0,0,1];let[r,i,n,a]=e;a<0&&(r=-r,i=-i,n=-n,a=-a);let s=Math.acos(Math.min(1,a)),o=Math.sin(s);if(o<1e-9)return[0,0,0,1];let l=Math.sin(s*t)/o;return Bc([r*l,i*l,n*l,Math.cos(s*t)])}function cp(e){let t=Math.hypot(e[0],e[1],e[2])||1,r=Math.hypot(e[4],e[5],e[6])||1,i=Math.hypot(e[8],e[9],e[10])||1,n=e[0]/t,a=e[1]/t,s=e[2]/t,o=e[4]/r,l=e[5]/r,c=e[6]/r,f=e[8]/i,m=e[9]/i,h=e[10]/i,p=n+l+h,g;if(p>0){let x=Math.sqrt(p+1)*2;g=[(c-m)/x,(f-s)/x,(a-o)/x,.25*x]}else if(n>l&&n>h){let x=Math.sqrt(1+n-l-h)*2;g=[.25*x,(o+a)/x,(f+s)/x,(c-m)/x]}else if(l>h){let x=Math.sqrt(1+l-n-h)*2;g=[(o+a)/x,.25*x,(m+c)/x,(f-s)/x]}else{let x=Math.sqrt(1+h-n-l)*2;g=[(f+s)/x,(m+c)/x,.25*x,(a-o)/x]}return Bc(g)}function lp(e,t,r){let[i,n,a,s]=r,o=1-2*(n*n+a*a),l=2*(i*n-a*s),c=2*(i*a+n*s),f=2*(i*n+a*s),m=1-2*(i*i+a*a),h=2*(n*a-i*s),p=2*(i*a-n*s),g=2*(n*a+i*s),x=1-2*(i*i+n*n);for(let v=0;v<3;v++){let y=t[v*4],A=t[v*4+1],b=t[v*4+2];e[v*4]=o*y+l*A+c*b,e[v*4+1]=f*y+m*A+h*b,e[v*4+2]=p*y+g*A+x*b}}function ls(e,t){let r=t[0]-e[0],i=t[1]-e[1],n=t[2]-e[2],a=Math.hypot(r,i,n);return a>1e-9?[r/a,i/a,n/a]:null}function Sd(e){e?.normalMatrix&&e?.transform&&Bt(e.normalMatrix,e.transform)}var xd=new WeakMap;function up(e){let t=xd.get(e);return t||(t=new Int32Array(e.nodes.length).fill(-1),e.nodes.forEach((r,i)=>{for(let n of Array.isArray(r?.children)?r.children:[])typeof n=="number"&&n>=0&&n<t.length&&(t[n]=i)}),xd.set(e,t)),t}function dp(e,t,r){let i=e?.gltf,n=i?.nodes;if(!Array.isArray(n)||n.length===0)return!1;let a=new Map;n.forEach((_,P)=>{typeof _?.name=="string"&&_.name&&!a.has(_.name)&&a.set(_.name,P)});let s=(t.mid?[t.root,t.mid,t.effector]:[t.root,t.effector]).map(_=>a.get(_));if(s.some(_=>_===void 0))return!1;let o=s,l=up(i);for(let _=1;_<o.length;_++){let P=l[o[_]],R=0;for(;P>=0&&P!==o[_-1]&&R++<256;)P=l[P];if(P!==o[_-1])return!1}let c=o[0],f=e.initialNodeTransforms,m=new Map,h=[],p=[c];for(;p.length&&h.length<4096;){let _=p.pop();if(m.has(_))continue;let P=f?.[_],R=n[_];m.set(_,{t:P?[P.t[0],P.t[1],P.t[2]]:R?.translation?[...R.translation]:[0,0,0],r:P?[P.r[0],P.r[1],P.r[2],P.r[3]]:R?.rotation?[...R.rotation]:[0,0,0,1],s:P?[P.s[0],P.s[1],P.s[2]]:R?.scale?[...R.scale]:[1,1,1]}),h.push(_);for(let $ of Array.isArray(R?.children)?R.children:[])typeof $=="number"&&p.push($)}let g=l[c],x=g>=0&&e.worldMatrices?.[g]?.length===16?Float32Array.from(e.worldMatrices[g]):rt(),v=new Map,y=()=>{let _=(P,R)=>{let $=m.get(P);if(!$)return;let F=rt();or(F,$.r,$.t,$.s);let V=rt();at(V,R,F),v.set(P,V);for(let Y of Array.isArray(n[P]?.children)?n[P].children:[])typeof Y=="number"&&_(Y,V)};_(c,x)},A=_=>{let P=v.get(_);return[P[12],P[13],P[14]]};y();let b=o.map(A),w=_=>{if(typeof _=="string"&&!r.has(_)){let P=a.get(_),R=P!==void 0?v.get(P)??e.worldMatrices?.[P]:void 0;if(R&&R.length===16)return[R[12],R[13],R[14]]}return Nc(_,r,e)},S=w(t.target);if(!S)return!0;let E=t.pole?w(t.pole)??void 0:void 0,N=Md(b,t,S,E),C=vd(t.weight,0,1,1);for(let _=0;_<o.length-1;_++){let P=ls(A(o[_]),A(o[_+1])),R=ls(N[_],N[_+1]);if(!P||!R)continue;let $=ap(us(P,R),C),F=o[_],V=l[F],Y=V===g||V<0?x:v.get(V)??x,J=cp(Y),re=m.get(F);re.r=Bc(Pc(sp(J),Pc($,Pc(J,re.r)))),y()}if(Array.isArray(e.worldMatrices))for(let[_,P]of v)e.worldMatrices[_]?.set&&e.worldMatrices[_].set(P);for(let _ of e.meshes??[]){let P=v.get(_?.nodeIndex);P&&_.transform?.set&&(_.transform.set(P),Sd(_))}return!0}function Md(e,t,r,i){if(t.solver==="two-bone"&&e.length===3){let n=Dc(e[0],e[1],e[2],r,i);return[e[0],n.midPos,n.effectorPos]}return Uc(e,r,t.iterations,t.tolerance).positions}function fp(e,t,r){let i=e.__ikRestOffsets,n=e.__ikRestMats;if(!(!i||!n))for(let a=0;a<t.length-1;a++){let s=t[a]?.transform??t[a]?.modelMatrix,o=n[a],l=ls([0,0,0],i[a]),c=ls(r[a],r[a+1]);!s||s.length<16||!o||o.length<16||!l||!c||(lp(s,o,us(l,c)),Sd(t[a]))}}var Fc={name:"ik",onRegister(){let e=He();jn(Ic),Ic(e.threeNamespace,e)},onUpdate(e){let t=e?.meshes;if(!Array.isArray(t)||t.length===0)return;let r=null;for(let i of t){let n=i?.userData?.xr?.ik??i?.extras?.xr?.ik??i?.extensions?.ANDROID_xr_scenecore?.ik;if(!n)continue;let a=np(n);if(!a||a.weight<=0)continue;if(!r){r=new Map;for(let b of t)b&&typeof b.name=="string"&&b.name&&r.set(b.name,b)}if(dp(e,a,r))continue;let s=r.get(a.root),o=r.get(a.effector),l=a.mid?r.get(a.mid):void 0;if(s||Lc(i,a.root),o||Lc(i,a.effector),a.mid&&!l&&Lc(i,a.mid),!s||!o)continue;let c=Nc(a.target,r,e);if(!c)continue;let f=a.pole?Nc(a.pole,r,e)??void 0:void 0,m=l?[s,l,o]:[s,o],h=m.map(b=>b.name||"").join(">");if(!i.__ikRestOffsets||i.__ikRestKey!==h){let b=m.map(Cc),w=[];for(let S=0;S<b.length-1;S++)w.push([b[S+1][0]-b[S][0],b[S+1][1]-b[S][1],b[S+1][2]-b[S][2]]);i.__ikRestOffsets=w,i.__ikRestKey=h,i.__ikRestMats=m.map(S=>Array.from(S.transform??S.modelMatrix??[]))}let p=i.__ikRestOffsets,g=[Cc(s)],x=[];for(let b=0;b<p.length;b++){let w=g[b],S=p[b];g.push([w[0]+S[0],w[1]+S[1],w[2]+S[2]]),x.push(Math.hypot(S[0],S[1],S[2]))}let v=Md(g,a,c,f),y=g[0],A=[g[0]];for(let b=1;b<m.length;b++){let w=p[b-1],S=[y[0]+w[0],y[1]+w[1],y[2]+w[2]],E=[y[0]+(v[b][0]-v[b-1][0]),y[1]+(v[b][1]-v[b-1][1]),y[2]+(v[b][2]-v[b-1][2])],N=op(y,S,E,x[b-1],a.weight);rp(m[b],N),y=N,A.push(N)}fp(i,m,A)}}};function $o(e,t){let r=(f,m,h,p)=>{let g=typeof f=="number"?f:Number(f);return Number.isFinite(g)?Math.max(m,Math.min(h,g)):p};function i(f,m,h=0,p=.05,g){if(!f||!f.length)return-1;let x=f[0]>0?[0,...f]:f,v=Number.isFinite(m)?Math.max(0,m):0,y=Number.isFinite(p)?Math.max(0,Math.min(.5,p)):.05;if(typeof g=="number"&&Number.isFinite(g)&&g>0){let w=h===-1?g*(1-y):g*(1+y);if(v>w)return-1}let A=0;for(let w=x.length-1;w>=1;w--)if(v>=x[w]){A=w;break}if(h<0||h>=x.length||h===A)return A;if(A>h){let w=h;for(let S=h+1;S<=A&&v>=x[S]*(1+y);S++)w=S;return w}let b=h;for(let w=h;w>A&&v<x[w]*(1-y);w--)b=w-1;return b}function n(f){if(!f)return null;let m=f===!0?{distances:[4,10],ratios:[.5,.25]}:Array.isArray(f)?{distances:f}:typeof f=="object"?f:null;if(!m||m.enabled===!1)return null;let h=r(m.hysteresis,0,.5,.05),p=[],g;if(Array.isArray(m.levels)&&m.levels.length>0){let A=m.levels.slice(0,8);for(let w=0;w<A.length;w++){let S=A[w];if(!S||typeof S!="object"||Array.isArray(S))continue;let E=S,N=r(E.distance,0,1e4,w===0?0:w*4),C=typeof E.hysteresis=="number"?r(E.hysteresis,0,.5,h):void 0,_=typeof E.ratio=="number"?r(E.ratio,.05,1,.5):void 0,P=typeof E.childIndex=="number"&&Number.isFinite(E.childIndex)?Math.max(0,Math.round(E.childIndex)):void 0,R=typeof E.node=="string"&&/^[A-Za-z0-9_.:-]+$/.test(E.node.trim())?E.node.trim().slice(0,64):void 0;p.push({distance:N,...C!==void 0?{hysteresis:C}:{},..._!==void 0?{ratio:_}:{},...P!==void 0?{childIndex:P}:{},...R?{node:R}:{}})}p.sort((w,S)=>w.distance-S.distance),p.length>0&&p[0].distance>0&&p.unshift({distance:0,childIndex:0});let b=0;p=p.slice(0,8).map((w,S)=>{let E=S===0?0:Math.max(b,w.distance);return b=E,{...w,distance:E,childIndex:w.childIndex??S}})}if(Array.isArray(m.ratios)&&m.ratios.length>0){let A=[];for(let b of m.ratios.slice(0,7))typeof b=="number"&&A.push(r(b,.05,1,.5));A.length>0&&(g=A)}if(p.length===0){let A=Array.isArray(m.distances)?m.distances:[],b=[];for(let S of A.slice(0,8))typeof S=="number"&&b.push(r(S,0,1e4,4));if(b.length===0&&g&&g.length>0)for(let S=0;S<g.length;S++)b.push((S+1)*4);if(b.length===0&&m.cullDistance===void 0)return null;b.length===0||b[0]>0?b.unshift(0):g&&g.length===b.length&&g[0]===1&&(g=g.slice(1));let w=0;for(let S=0;S<Math.min(8,b.length);S++){let E=S===0?0:Math.max(w,b[S]);w=E;let N=S>0&&g?g[S-1]:void 0;p.push({distance:E,childIndex:S,...N!==void 0?{ratio:N}:{}})}}else if(!g){let A=[];for(let b=1;b<p.length;b++)typeof p[b].ratio=="number"&&A.push(p[b].ratio);A.length>0&&(g=A)}let x=p.map(A=>A.distance),v=x[x.length-1]??0,y=m.cullDistance!==void 0&&m.cullDistance!==null&&m.cullDistance!==!1?r(m.cullDistance,Math.max(1,v),1e4,100):void 0;return{levels:p,distances:x,...g?{ratios:g}:{},hysteresis:h,...y!==void 0?{cullDistance:y}:{}}}function a(f,m){let h=f?.attributes?.position;if(!h||!h.array||h.count<3)return f;let p=r(m,.05,1,.5),g=h.array,x=h.count,v=f.attributes?.normal?.array,y=f.attributes?.uv?.array,A=f.index?.array,b=Math.floor((A?A.length:x)/3);if(b<1)return f;let w=Math.max(1,Math.min(b,Math.round(b*p))),S=1/0,E=1/0,N=1/0,C=-1/0,_=-1/0,P=-1/0;for(let te=0;te<x;te++){let Z=g[te*3],ae=g[te*3+1],ie=g[te*3+2];Z<S&&(S=Z),ae<E&&(E=ae),ie<N&&(N=ie),Z>C&&(C=Z),ae>_&&(_=ae),ie>P&&(P=ie)}let R=Math.max(1e-5,C-S),$=Math.max(1e-5,_-E),F=Math.max(1e-5,P-N),V=Math.max(R,$,F),Y=te=>{let Z=Math.max(1,Math.round(R/V*te)),ae=Math.max(1,Math.round($/V*te)),ie=Math.max(1,Math.round(F/V*te)),de=new Map,me=new Int32Array(x),Se=[],Fe=[],_e=[],Le=[];for(let O=0;O<x;O++){let X=g[O*3],se=g[O*3+1],ce=g[O*3+2],pe=Math.min(Z-1,Math.max(0,Math.floor((X-S)/R*Z))),xe=Math.min(ae-1,Math.max(0,Math.floor((se-E)/$*ae))),he=Math.min(ie-1,Math.max(0,Math.floor((ce-N)/F*ie))),Ne=pe+xe*Z+he*Z*ae,ge=de.get(Ne);ge===void 0?(ge=Le.length,de.set(Ne,ge),Se.push(X,se,ce),v&&Fe.push(v[O*3],v[O*3+1],v[O*3+2]),y&&_e.push(y[O*2],y[O*2+1]),Le.push(1)):(Se[ge*3]+=X,Se[ge*3+1]+=se,Se[ge*3+2]+=ce,v&&(Fe[ge*3]+=v[O*3],Fe[ge*3+1]+=v[O*3+1],Fe[ge*3+2]+=v[O*3+2]),Le[ge]++),me[O]=ge}let ne=[],Re=new Set;for(let O=0;O<b;O++){let X=A?A[O*3]:O*3,se=A?A[O*3+1]:O*3+1,ce=A?A[O*3+2]:O*3+2,pe=me[X],xe=me[se],he=me[ce];if(pe===xe||xe===he||he===pe)continue;let Ne=Math.min(pe,xe,he),ge=Math.max(pe,xe,he),Ae=pe+xe+he-Ne-ge,Ee=`${Ne}_${Ae}_${ge}`;Re.has(Ee)||(Re.add(Ee),ne.push(pe,xe,he))}let W=Le.length,D=new Float32Array(W*3),z=v?new Float32Array(W*3):null;for(let O=0;O<W;O++){let X=1/Le[O];if(D[O*3]=Se[O*3]*X,D[O*3+1]=Se[O*3+1]*X,D[O*3+2]=Se[O*3+2]*X,z){let se=Fe[O*3],ce=Fe[O*3+1],pe=Fe[O*3+2],xe=Math.hypot(se,ce,pe)||1;z[O*3]=se/xe,z[O*3+1]=ce/xe,z[O*3+2]=pe/xe}}return{pos:D,norm:z,uv:y?new Float32Array(_e):null,tris:ne,triCount:ne.length/3,vertCount:W}},J=Math.max(2,Math.round(Math.sqrt(w/4))),re=Y(J);if(re.triCount>w*1.25&&J>2){let te=Math.max(2,Math.round(J*Math.sqrt(w/re.triCount)));if(te!==J){let Z=Y(te);Z.triCount>=Math.min(4,w)&&(re=Z)}}else if(re.triCount<Math.min(4,w)){let te=Y(Math.max(J*2,8));te.triCount>re.triCount&&(re=te)}let Q=re.tris;if(p<1&&re.triCount>w){let te=[],Z=re.triCount/w;for(let ae=0;ae<w;ae++){let ie=Math.min(re.triCount-1,Math.floor(ae*Z));te.push(re.tris[ie*3],re.tris[ie*3+1],re.tris[ie*3+2])}Q=te}if(Q.length<3){Q=[];for(let te=0;te<w*3;te++)Q.push(A?A[te]:te);re={pos:g.slice(),norm:v?v.slice():null,uv:y?y.slice():null,tris:Q,triCount:w,vertCount:x}}let ee=e??t?.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0),k=ee?.BufferGeometry??f.constructor,G=ee?.BufferAttribute??h.constructor,q=new k;q.setAttribute("position",new G(re.pos,3)),re.norm&&q.setAttribute("normal",new G(re.norm,3)),re.uv&&q.setAttribute("uv",new G(re.uv,2));let H=re.vertCount>65535?new Uint32Array(Q):new Uint16Array(Q);return typeof q.setIndex=="function"?q.setIndex(new G(H,1)):q.index=new G(H,1),q}let s=e?.Object3D??t?.threeNamespace?.Object3D??class{constructor(){this.name="",this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0},this.quaternion={x:0,y:0,z:0,w:1},this.scale={x:1,y:1,z:1},this.visible=!0,this.parent=null,this.children=[],this.userData={}}add(...f){for(let m of f)m&&(m.parent=this,this.children.push(m));return this}};class o extends s{constructor(){super(),this.isLOD=!0,this.type="LOD",this.autoUpdate=!0,this.levels=[],this._currentLevel=0}addLevel(m,h=0,p=.05){if(!m)return this;let g=Math.max(0,Number.isFinite(Number(h))?Number(h):0),x=r(p,0,.5,.05),v=this.levels.length;for(let b=0;b<this.levels.length;b++)if(g<this.levels[b].distance){v=b;break}this.levels.splice(v,0,{object:m,distance:g,hysteresis:x}),this.add(m);let y=this.levels.map(b=>b.object),A=this.children.filter(b=>!y.includes(b));this.children=[...y,...A];for(let b=0;b<this.levels.length;b++)this.levels[b].object.visible=b===this._currentLevel;return this.syncUserDataTrait(),this}getCurrentLevel(){return this._currentLevel}getObjectForDistance(m){if(!this.levels.length)return null;let h=i(this.levels.map(p=>p.distance),m,this._currentLevel,this.levels[0]?.hysteresis??.05,this.userData?.xr?.lod?.cullDistance);return h>=0&&h<this.levels.length?this.levels[h].object:null}update(m){if(this.levels.length===0||!m)return;let h=m.position??{x:0,y:0,z:0},p=this.position??{x:0,y:0,z:0},g=Math.hypot((Number(h.x)||0)-(Number(p.x)||0),(Number(h.y)||0)-(Number(p.y)||0),(Number(h.z)||0)-(Number(p.z)||0)),x=i(this.levels.map(v=>v.distance),g,this._currentLevel,this.levels[0]?.hysteresis??.05,this.userData?.xr?.lod?.cullDistance);this._currentLevel=x;for(let v=0;v<this.levels.length;v++)this.levels[v].object.visible=v===x}syncUserDataTrait(){this.userData=this.userData||{},this.userData.xr=this.userData.xr||{};let m=this.userData.xr.lod?.cullDistance;this.userData.xr.lod={levels:this.levels.map((h,p)=>({distance:h.distance,hysteresis:h.hysteresis,childIndex:p,...h.object?.name?{node:h.object.name}:{}})),distances:this.levels.map(h=>h.distance),hysteresis:this.levels[0]?.hysteresis??.05,...m!==void 0?{cullDistance:m}:{}}}}function l(f){if(!f||f._lodMaterialized||!f.userData?.xr?.lod||f.isLOD||Array.isArray(f.children)&&f.children.length>0)return;let m=f.geometry?.attributes?.position;if(!m||!m.array||m.count<3)return;let h=n(f.userData.xr.lod);if(!h||h.levels.length<2)return;f._lodMaterialized=!0;let p=f.geometry;f._lodOriginalGeometry=p;let g=e??t?.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0),x=g?.Mesh??f.constructor,v=g?.BufferGeometry??p.constructor,y=typeof f.name=="string"&&f.name.trim()?f.name.trim():"Mesh",A=new x(p,f.material);A.name=`${y}_LOD0`,A.visible=!0,A.castShadow=!!f.castShadow,A.receiveShadow=!!f.receiveShadow,f.add(A);for(let b=1;b<h.levels.length;b++){let w=h.levels[b].ratio??h.ratios?.[b-1]??Math.max(.05,Math.pow(.5,b)),S=a(p,w),E=new x(S,f.material);E.name=`${y}_LOD${b}`,E.visible=!1,E.castShadow=!!f.castShadow,E.receiveShadow=!!f.receiveShadow,f.add(E)}f.geometry=new v,f.userData.xr.lod={...h,levels:h.levels.map((b,w)=>({...b,childIndex:w,node:`${y}_LOD${w}`}))}}let c={LOD:o,decimateGeometry:a,selectLodLevelIndex:i,parseLod:n,materializeLodGeometry:l};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,{LOD:o,decimateGeometry:a}),t._lodMaterialize=l,t.materializeDeclarativeGeometry=f=>{t._cadMaterialize?.(f),t._lodMaterialize?.(f),t._procMaterialize?.(f)}),c}var jo=$o(),Ad=jo.decimateGeometry,ds=jo.selectLodLevelIndex,fs=jo.parseLod,Jy=jo.materializeLodGeometry,Td=jo.LOD,zo=new WeakMap;function _d(e){return e&&typeof e=="object"?zo.get(e):void 0}var Go=class{constructor(e,t){this.groups=[],this.viewer=e,this.gltf=t,this.rebuild()}rebuild(){this.groups.length=0;let e=this.gltf?.nodes;if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let i of this.viewer?.meshes??[])if(typeof i?.nodeIndex=="number"&&i.nodeIndex>=0){let n=t.get(i.nodeIndex);n||(n=[],t.set(i.nodeIndex,n)),n.push(i)}let r=i=>{let n=[],a=new Set,s=[i];for(;s.length>0;){let o=s.pop();if(a.has(o)||o<0||o>=e.length)continue;a.add(o);let l=t.get(o);l&&n.push(...l);let c=e[o]?.children;if(Array.isArray(c))for(let f=c.length-1;f>=0;f--)typeof c[f]=="number"&&s.push(c[f])}return n};for(let i=0;i<e.length;i++){let n=e[i];if(!n||typeof n!="object")continue;let a=n.extras?.xr?.lod??n.extensions?.ANDROID_xr_scenecore?.lod??n.extensions?.MOZ_hubs_components?.lod,s=Array.isArray(n.extensions?.MSFT_lod?.ids)?n.extensions.MSFT_lod.ids.filter(p=>typeof p=="number"&&Number.isInteger(p)&&p>=0&&p<e.length):[],o=fs(a);if(!o&&s.length>0&&(o=fs({distances:s.map((p,g)=>g*4)})),!o)continue;let l=s.length>0?s:Array.isArray(n.children)?n.children.filter(p=>typeof p=="number"&&Number.isInteger(p)&&p>=0&&p<e.length):[],c=[],f=[];if(l.length>0){let p=Math.min(l.length,o.levels.length);for(let g=0;g<p;g++){let x=l[g];c.push(x),f.push(r(x))}}else{let p=t.get(i)??[];if(p.length===0)continue;c.push(i),f.push(p)}let m=o.distances.slice(0,f.length);m.length===0&&m.push(0);let h={nodeIndex:i,name:typeof n.name=="string"?n.name:`LOD_${i}`,distances:m,hysteresis:o.hysteresis,...o.cullDistance!==void 0?{cullDistance:o.cullDistance}:{},childNodeIndices:c,levelMeshes:f,activeLevelIndex:0,lastDistance:0};this.applyGroupVisibility(h,0),this.groups.push(h)}}getGroups(){return this.groups}getActiveLevel(e){let t=this.findGroup(e);return t?t.activeLevelIndex:null}forceLodLevel(e,t){let r=this.findGroup(e);if(!r)return;if(t==null){r.forcedLevelIndex=null;let n=ds(r.distances,r.lastDistance,r.activeLevelIndex,r.hysteresis,r.cullDistance);r.activeLevelIndex=n,this.applyGroupVisibility(r,n);return}let i=t<0?-1:Math.min(Math.max(0,Math.trunc(t)),r.levelMeshes.length-1);r.forcedLevelIndex=i,r.activeLevelIndex=i,this.applyGroupVisibility(r,i)}findGroup(e){return typeof e=="number"?this.groups.find(t=>t.nodeIndex===e)??this.groups[e]:this.groups.find(t=>t.name===e)}update(e){if(this.groups.length===0)return;let t=this.viewer?.worldMatrices,r=this.viewer?.modelRootMatrix;for(let i of this.groups){let n=Array.isArray(t)&&i.nodeIndex<t.length?t[i.nodeIndex]:null,a=n&&n[12]||0,s=n&&n[13]||0,o=n&&n[14]||0,l=r?r[0]*a+r[4]*s+r[8]*o+r[12]:a,c=r?r[1]*a+r[5]*s+r[9]*o+r[13]:s,f=r?r[2]*a+r[6]*s+r[10]*o+r[14]:o,m=Math.hypot((e[0]||0)-l,(e[1]||0)-c,(e[2]||0)-f);if(i.lastDistance=m,i.forcedLevelIndex!==void 0&&i.forcedLevelIndex!==null){i.activeLevelIndex!==i.forcedLevelIndex&&(i.activeLevelIndex=i.forcedLevelIndex,this.applyGroupVisibility(i,i.forcedLevelIndex));continue}let h=ds(i.distances,m,i.activeLevelIndex,i.hysteresis,i.cullDistance);h!==i.activeLevelIndex&&(i.activeLevelIndex=h,this.applyGroupVisibility(i,h))}}applyGroupVisibility(e,t){let r=this.gltf?.nodes;for(let i=0;i<e.levelMeshes.length;i++){let n=i===t;for(let o of e.levelMeshes[i])o.visible=n;let a=e.childNodeIndices[i],s=Array.isArray(r)?r[a]:null;s&&typeof s=="object"&&(s.visible=n,s.extensions=s.extensions||{},s.extensions.KHR_node_visibility={visible:n})}}},Vc={name:"lod",onRegister(){jn($o);let e=He(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);$o(t,e)},onLoadModel(e,t){!e||typeof e!="object"||zo.set(e,new Go(e,t))},onUpdate(e){let t=zo.get(e);if(!t||typeof e?.getCameraOrbit!="function")return;let r=e.getCameraOrbit(),i=typeof e.getCameraTarget=="function"?e.getCameraTarget():{x:0,y:0,z:0},n=r?.radius??3,a=r?.phi??0,s=r?.theta??0,o=Math.cos(a),l=(i.x||0)+n*o*Math.sin(s),c=(i.y||0)+n*Math.sin(a),f=(i.z||0)+n*o*Math.cos(s);t.update([l,c,f])},onBeforeDrawScene(e,t,r,i){let n=zo.get(e);n&&n.update(i)},onDestroy(e,t){t&&typeof t=="object"&&zo.delete(t)}};function ms(e,t){if(!e||!e.Vector3||!e.BufferGeometry)return null;let r=e.Vector3,i=e.Matrix4,n=e.BufferGeometry;if(typeof r.prototype.distanceToSquared!="function"&&(r.prototype.distanceToSquared=function(T){let u=this.x-Number(T?.x??0),d=this.y-Number(T?.y??0),M=this.z-Number(T?.z??0);return u*u+d*d+M*M}),typeof r.prototype.addScalar!="function"&&(r.prototype.addScalar=function(T){let u=Number(T)||0;return this.set(this.x+u,this.y+u,this.z+u)}),typeof r.prototype.applyQuaternion!="function"&&(r.prototype.applyQuaternion=function(T){let u=this.x,d=this.y,M=this.z,L=Number(T?.x)||0,I=Number(T?.y)||0,B=Number(T?.z)||0,U=T?.w===void 0?1:Number(T.w)||0,j=2*(I*M-B*d),K=2*(B*u-L*M),ue=2*(L*d-I*u);return this.set(u+U*j+(I*ue-B*K),d+U*K+(B*j-L*ue),M+U*ue+(L*K-I*j))}),typeof r.prototype.min!="function"&&(r.prototype.min=function(T){return this.set(Math.min(this.x,T.x),Math.min(this.y,T.y),Math.min(this.z,T.z))}),typeof r.prototype.max!="function"&&(r.prototype.max=function(T){return this.set(Math.max(this.x,T.x),Math.max(this.y,T.y),Math.max(this.z,T.z))}),typeof r.prototype.clamp!="function"&&(r.prototype.clamp=function(T,u){return this.set(Math.max(T.x,Math.min(u.x,this.x)),Math.max(T.y,Math.min(u.y,this.y)),Math.max(T.z,Math.min(u.z,this.z)))}),typeof r.prototype.clampScalar!="function"&&(r.prototype.clampScalar=function(T,u){return this.set(Math.max(T,Math.min(u,this.x)),Math.max(T,Math.min(u,this.y)),Math.max(T,Math.min(u,this.z)))}),typeof r.prototype.negate!="function"&&(r.prototype.negate=function(){return this.multiplyScalar(-1)}),typeof r.prototype.equals!="function"&&(r.prototype.equals=function(T){return!!T&&T.x===this.x&&T.y===this.y&&T.z===this.z}),i&&typeof i.prototype.getMaxScaleOnAxis!="function"&&(i.prototype.getMaxScaleOnAxis=function(){let T=this.elements;return Math.sqrt(Math.max(T[0]*T[0]+T[1]*T[1]+T[2]*T[2],T[4]*T[4]+T[5]*T[5]+T[6]*T[6],T[8]*T[8]+T[9]*T[9]+T[10]*T[10]))}),e.MathUtils&&typeof e.MathUtils=="object"){let T=1234567;try{typeof e.MathUtils.seededRandom!="function"&&(e.MathUtils.seededRandom=u=>{u!==void 0&&(T=Number.isFinite(u)?u|0:0);let d=T=T+1831565813|0;return d=Math.imul(d^d>>>15,d|1),d^=d+Math.imul(d^d>>>7,d|61),((d^d>>>14)>>>0)/4294967296}),typeof e.MathUtils.randInt!="function"&&(e.MathUtils.randInt=(u,d)=>u+Math.floor(Math.random()*(d-u+1))),typeof e.MathUtils.randFloatSpread!="function"&&(e.MathUtils.randFloatSpread=u=>u*(.5-Math.random()))}catch{}}class a{constructor(u,d){this.isBox3=!0,this.min=u!=null?new r(u.x,u.y,u.z):new r(1/0,1/0,1/0),this.max=d!=null?new r(d.x,d.y,d.z):new r(-1/0,-1/0,-1/0)}set(u,d){return this.min.copy(u),this.max.copy(d),this}makeEmpty(){return this.min.set(1/0,1/0,1/0),this.max.set(-1/0,-1/0,-1/0),this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}clone(){return new a(this.min,this.max)}copy(u){return u?(this.min.copy(u.min),this.max.copy(u.max),this):this}expandByPoint(u){if(!u)return this;let d=Number(u.x),M=Number(u.y),L=u.z===void 0?0:Number(u.z);return!Number.isFinite(d)||!Number.isFinite(M)||!Number.isFinite(L)?this:(d<this.min.x&&(this.min.x=d),M<this.min.y&&(this.min.y=M),L<this.min.z&&(this.min.z=L),d>this.max.x&&(this.max.x=d),M>this.max.y&&(this.max.y=M),L>this.max.z&&(this.max.z=L),this)}expandByVector(u){if(this.isEmpty()||!u)return this;let d=Number(u.x),M=Number(u.y),L=Number(u.z);return!Number.isFinite(d)||!Number.isFinite(M)||!Number.isFinite(L)?this:(this.min.set(this.min.x-d,this.min.y-M,this.min.z-L),this.max.set(this.max.x+d,this.max.y+M,this.max.z+L),this.isEmpty()&&this.makeEmpty(),this)}expandByScalar(u){let d=Number(u);return this.isEmpty()||!Number.isFinite(d)?this:(this.min.set(this.min.x-d,this.min.y-d,this.min.z-d),this.max.set(this.max.x+d,this.max.y+d,this.max.z+d),this.isEmpty()&&this.makeEmpty(),this)}setFromArray(u){if(this.makeEmpty(),!u)return this;for(let d=0,M=u.length-2;d<M;d+=3)this.expandByPoint({x:u[d],y:u[d+1],z:u[d+2]});return this}setFromBufferAttribute(u){if(this.makeEmpty(),!u||typeof u.count!="number")return this;for(let d=0;d<u.count;d++)this.expandByPoint({x:u.getX(d),y:u.getY(d),z:u.getZ(d)});return this}setFromPoints(u){if(this.makeEmpty(),Array.isArray(u))for(let d of u)this.expandByPoint(d);return this}setFromCenterAndSize(u,d){if(!u||!d)return this;let M=Math.abs(Number(d.x)||0)*.5,L=Math.abs(Number(d.y)||0)*.5,I=Math.abs(Number(d.z)||0)*.5,B=Number(u.x)||0,U=Number(u.y)||0,j=Number(u.z)||0;return this.min.set(B-M,U-L,j-I),this.max.set(B+M,U+L,j+I),this}setFromObject(u,d){return this.makeEmpty().expandByObject(u,!!d)}expandByObject(u,d){return s(this,u,!!d),this}getCenter(u=new r){return this.isEmpty()?u.set(0,0,0):u.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(u=new r){return this.isEmpty()?u.set(0,0,0):u.subVectors(this.max,this.min)}getParameter(u,d=new r){let M=this.max.x-this.min.x,L=this.max.y-this.min.y,I=this.max.z-this.min.z;return d.set(M!==0?(u.x-this.min.x)/M:0,L!==0?(u.y-this.min.y)/L:0,I!==0?(u.z-this.min.z)/I:0)}containsPoint(u){return!!u&&!this.isEmpty()&&u.x>=this.min.x&&u.x<=this.max.x&&u.y>=this.min.y&&u.y<=this.max.y&&u.z>=this.min.z&&u.z<=this.max.z}containsBox(u){return!!u&&this.min.x<=u.min.x&&u.max.x<=this.max.x&&this.min.y<=u.min.y&&u.max.y<=this.max.y&&this.min.z<=u.min.z&&u.max.z<=this.max.z}intersectsBox(u){return!!u&&u.max.x>=this.min.x&&u.min.x<=this.max.x&&u.max.y>=this.min.y&&u.min.y<=this.max.y&&u.max.z>=this.min.z&&u.min.z<=this.max.z}intersectsSphere(u){return!u||this.isEmpty()||u.isEmpty()?!1:this.clampPoint(u.center,new r).distanceToSquared(u.center)<=u.radius*u.radius}intersectsPlane(u){if(!u?.normal||this.isEmpty())return!1;let d=u.normal.x,M=u.normal.y,L=u.normal.z,I=Number(u.constant)||0,B=(d>0?d*this.min.x:d*this.max.x)+(M>0?M*this.min.y:M*this.max.y)+(L>0?L*this.min.z:L*this.max.z),U=(d>0?d*this.max.x:d*this.min.x)+(M>0?M*this.max.y:M*this.min.y)+(L>0?L*this.max.z:L*this.min.z);return B<=-I&&U>=-I}clampPoint(u,d=new r){return this.isEmpty()?d.copy(u):d.copy(u).clamp(this.min,this.max)}distanceToPoint(u){return this.isEmpty()?1/0:this.clampPoint(u,new r).distanceTo(u)}getBoundingSphere(u=new o){return this.isEmpty()?u.makeEmpty():(this.getCenter(u.center),u.radius=this.getSize(new r).length()*.5,u)}intersect(u){return u?(this.min.max(u.min),this.max.min(u.max),this.isEmpty()&&this.makeEmpty(),this):this}union(u){return!u||u.isEmpty()?this:this.isEmpty()?this.copy(u):(this.min.min(u.min),this.max.max(u.max),this)}applyMatrix4(u){if(this.isEmpty()||!u)return this;let d=this.min.x,M=this.min.y,L=this.min.z,I=this.max.x,B=this.max.y,U=this.max.z,j=new r;this.makeEmpty();for(let K=0;K<8;K++)j.set(K&1?I:d,K&2?B:M,K&4?U:L).applyMatrix4(u),this.expandByPoint(j);return this}translate(u){return this.isEmpty()||!u?this:(this.min.add(u),this.max.add(u),this)}equals(u){return!!u&&u.min.equals(this.min)&&u.max.equals(this.max)}}function s(T,u,d){if(!u)return;u.updateMatrixWorld?.(!0);let M=new r,L=new a,I=new i,B=new i,U=new Set,j=new Map,K=(le,oe)=>{let fe=le?.attributes?.position;if(!(!fe||!(fe.count>0)))if(d)for(let ye=0;ye<fe.count;ye++)M.set(fe.getX(ye),fe.getY(ye),fe.getZ(ye)).applyMatrix4(oe),T.expandByPoint(M);else{let ye=j.get(le);ye||(ye=new a().setFromBufferAttribute(fe),j.set(le,ye)),ye.isEmpty()||T.union(L.copy(ye).applyMatrix4(oe))}},ue=le=>{if(!le||typeof le!="object"||U.has(le)||(U.add(le),t?.materializeDeclarativeGeometry?.(le),le.isBoxHelper&&le!==u))return;(le.isSprite||le.isBox3Helper)&&le._bakeAuthorGeometry?.();let oe=le._sourceGeo||le.geometry;if(oe&&oe.attributes?.position&&le.matrixWorld)if(le.isInstancedMesh&&typeof le.getMatrixAt=="function"){let fe=Math.floor((le.instanceMatrix?.array?.length??0)/16),ye=Math.min(Math.max(0,Math.floor(Number(le.count)||0)),fe);for(let ve=0;ve<ye;ve++)le.getMatrixAt(ve,I),B.multiplyMatrices(le.matrixWorld,I),K(oe,B)}else K(oe,le.matrixWorld);if(Array.isArray(le.children))for(let fe of le.children)ue(fe)};ue(u)}class o{constructor(u,d=-1){this.isSphere=!0,this.center=u!=null?new r(u.x,u.y,u.z):new r;let M=Number(d);this.radius=Number.isFinite(M)?M:-1}set(u,d){u&&this.center.copy(u);let M=Number(d);return this.radius=Number.isFinite(M)?M:-1,this}setFromPoints(u,d){if(!Array.isArray(u)||u.length===0)return this.makeEmpty();if(d)this.center.copy(d);else{let B=new a().setFromPoints(u);if(B.isEmpty())return this.makeEmpty();B.getCenter(this.center)}let M=0,L=!1,I=new r;for(let B of u){let U=Number(B?.x),j=Number(B?.y),K=B?.z===void 0?0:Number(B.z);Number.isFinite(U)&&Number.isFinite(j)&&Number.isFinite(K)&&(L=!0,M=Math.max(M,this.center.distanceToSquared(I.set(U,j,K))))}return L?(this.radius=Math.sqrt(M),this):this.makeEmpty()}copy(u){return u?(this.center.copy(u.center),this.radius=u.radius,this):this}clone(){return new o(this.center,this.radius)}isEmpty(){return!(this.radius>=0)||!Number.isFinite(this.radius)}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(u){return!!u&&!this.isEmpty()&&u.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(u){return this.isEmpty()?1/0:u.distanceTo(this.center)-this.radius}intersectsSphere(u){if(!u||this.isEmpty()||u.isEmpty())return!1;let d=this.radius+u.radius;return u.center.distanceToSquared(this.center)<=d*d}intersectsBox(u){return!!u&&u.intersectsSphere(this)}intersectsPlane(u){if(!u?.normal||this.isEmpty())return!1;let d=u.normal.dot(this.center)+(Number(u.constant)||0);return Math.abs(d)<=this.radius}clampPoint(u,d=new r){return d.copy(u),this.isEmpty()||this.center.distanceToSquared(u)>this.radius*this.radius&&d.sub(this.center).normalize().multiplyScalar(this.radius).add(this.center),d}getBoundingBox(u=new a){return this.isEmpty()?u.makeEmpty():(u.set(this.center,this.center),u.expandByScalar(this.radius),u)}applyMatrix4(u){if(this.isEmpty()||!u)return this;let d=u.getMaxScaleOnAxis();return Number.isFinite(d)?(this.center.applyMatrix4(u),this.radius*=d,this):this.makeEmpty()}translate(u){return!this.isEmpty()&&u&&this.center.add(u),this}expandByPoint(u){if(!u||!Number.isFinite(u.x)||!Number.isFinite(u.y)||!Number.isFinite(u.z))return this;if(this.isEmpty())return this.center.copy(u),this.radius=0,this;let d=this.center.distanceToSquared(u);if(d>this.radius*this.radius){let M=Math.sqrt(d),L=(this.radius+M)*.5;this.center.addScaledVector(new r().subVectors(u,this.center),(M-this.radius)/(2*M)),this.radius=L}return this}union(u){if(!u||u.isEmpty())return this;if(this.isEmpty())return this.copy(u);if(this.center.equals(u.center))return this.radius=Math.max(this.radius,u.radius),this;let d=new r().subVectors(u.center,this.center),M=d.length();if(M+u.radius<=this.radius)return this;if(M+this.radius<=u.radius)return this.copy(u);let L=(this.radius+M+u.radius)*.5;return this.center.addScaledVector(d,(L-this.radius)/M),this.radius=L,this}equals(u){return!!u&&u.center.equals(this.center)&&u.radius===this.radius}}n.prototype.computeBoundingSphere=function(){(!this.boundingSphere||!this.boundingSphere.isSphere)&&(this.boundingSphere=new o);let T=this.attributes?.position;if(!T||!(T.count>0))return this.boundingSphere.makeEmpty();let u=new a().setFromBufferAttribute(T);if(u.isEmpty())return this.boundingSphere.makeEmpty();let d=u.getCenter(this.boundingSphere.center),M=0,L=new r;for(let I=0;I<T.count;I++){let B=T.getX(I),U=T.getY(I),j=T.getZ(I);Number.isFinite(B)&&Number.isFinite(U)&&Number.isFinite(j)&&(M=Math.max(M,d.distanceToSquared(L.set(B,U,j))))}return this.boundingSphere.radius=Math.sqrt(M),this.boundingSphere},n.prototype.computeBoundingBox=function(){(!this.boundingBox||!this.boundingBox.isBox3)&&(this.boundingBox=new a);let T=this.attributes?.position;return T&&T.count>0?this.boundingBox.setFromBufferAttribute(T):this.boundingBox.makeEmpty(),this.boundingSphere&&this.computeBoundingSphere(),this.boundingBox};let l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=512,f=2048,m=16384,h=256,p="AAAAAAAAAF8AAAAHAAcAFH8UfxQkKn8qEiMTCGRiNklVIlAABQMAAAAcIkEAAEEiHAAUCD4IFAgIPggIAFAwAAAICAgICABgYAAAIBAIBAI+UUlFPgBCf0AAQmFRSUYhQUVLMRgUEn8QJ0VFRTk8SklJMAFxCQUDNklJSTYGSUkpHgA2NgAAAFY2AAAIFCJBABQUFBQUAEEiFAgCAVEJBjJJeUE+fhEREX5/SUlJNj5BQUEif0FBIhx/SUlJQX8JCQkBPkFJSXp/CAgIfwBBf0EAIEBBPwF/CBQiQX9AQEBAfwIMAn9/BAgQfz5BQUE+fwkJCQY+QVEhXn8JGSlGRklJSTEBAX8BAT9AQEA/HyBAIB8/QDhAP2MUCBRjBwhwCAdhUUlFQwB/QUEAAgQIECAAQUF/AAQCAQIEQEBAQEAAAQIEACBUVFR4f0hERDg4REREIDhEREh/OFRUVBgIfgkBAgxSUlI+fwgEBHgARH1AACBARD0AfxAoRAAAQX9AAHwEGAR4fAgEBHg4REREOHwUFBQICBQUGHx8CAQECEhUVFQgBD9EQCA8QEAgfBwgQCAcPEAwQDxEKBAoRAxQUFA8RGRUTEQACDZBAAAAfwAAAEE2CAAIBAgQCA==",g=new Int16Array(128).fill(-1);for(let T=0;T<64;T++)g[l.charCodeAt(T)]=T;let x=(()=>{let T=new Uint8Array(475),u=0,d=0,M=0;for(let L=0;L<p.length&&M<475;L++){let I=p.charCodeAt(L);if(I===61)break;let B=I<128?g[I]:-1;B<0||(u=u<<6|B,d+=6,d>=8&&(d-=8,T[M++]=u>>d&255))}return T})(),v=(()=>{let T=new Uint32Array(256);for(let u=0;u<256;u++){let d=u;for(let M=0;M<8;M++)d=d&1?3988292384^d>>>1:d>>>1;T[u]=d>>>0}return T})(),y=T=>{let u=4294967295;for(let d=0;d<T.length;d++)u=v[(u^T[d])&255]^u>>>8;return(u^4294967295)>>>0},A=(()=>{let T=new Float32Array(256);for(let u=0;u<256;u++){let d=u/255;T[u]=d<=.04045?d/12.92:Math.pow((d+.055)/1.055,2.4)}return T})(),b=typeof globalThis<"u"?globalThis.__three_live_native_encode_rgba_png__:void 0,w={};for(let T of"black:000000,white:ffffff,red:ff0000,lime:00ff00,green:008000,blue:0000ff,yellow:ffff00,cyan:00ffff,aqua:00ffff,magenta:ff00ff,fuchsia:ff00ff,silver:c0c0c0,gray:808080,grey:808080,darkgray:a9a9a9,darkgrey:a9a9a9,dimgray:696969,dimgrey:696969,lightgray:d3d3d3,lightgrey:d3d3d3,slategray:708090,slategrey:708090,darkslategray:2f4f4f,darkslategrey:2f4f4f,maroon:800000,olive:808000,purple:800080,teal:008080,navy:000080,orange:ffa500,orangered:ff4500,gold:ffd700,coral:ff7f50,salmon:fa8072,tomato:ff6347,crimson:dc143c,pink:ffc0cb,hotpink:ff69b4,deeppink:ff1493,indigo:4b0082,violet:ee82ee,plum:dda0dd,orchid:da70d6,brown:a52a2a,saddlebrown:8b4513,sienna:a0522d,chocolate:d2691e,peru:cd853f,tan:d2b48c,wheat:f5deb3,beige:f5f5dc,ivory:fffff0,linen:faf0e6,snow:fffafa,khaki:f0e68c,skyblue:87ceeb,deepskyblue:00bfff,dodgerblue:1e90ff,royalblue:4169e1,steelblue:4682b4,turquoise:40e0d0,aquamarine:7fffd4,chartreuse:7fff00,forestgreen:228b22,seagreen:2e8b57".split(",")){let[u,d]=T.split(":");w[u]=parseInt(d,16)}let S=T=>T>0?T<255?T+.5|0:255:0,E=T=>{let u=T.trim();return u.endsWith("%")?S(parseFloat(u)*255/100):S(parseFloat(u))},N=T=>{if(!T)return 255;let u=T.trim();if(!u)return 255;let d=u.endsWith("%")?parseFloat(u)/100:parseFloat(u);return Number.isFinite(d)?S(Math.max(0,Math.min(1,d))*255):255},C=(T,u=[0,0,0,255])=>{if(typeof T!="string")return u;let d=T.trim().toLowerCase();if(!d)return u;if(d==="transparent")return[0,0,0,0];if(d.charCodeAt(0)===35){let ve=d.slice(1);if(ve.length===3||ve.length===4){let we=parseInt(ve[0]+ve[0],16),Te=parseInt(ve[1]+ve[1],16),Me=parseInt(ve[2]+ve[2],16),be=ve.length===4?parseInt(ve[3]+ve[3],16):255;if(Number.isFinite(we+Te+Me+be))return[we,Te,Me,be]}else if(ve.length===6||ve.length===8){let we=parseInt(ve.slice(0,2),16),Te=parseInt(ve.slice(2,4),16),Me=parseInt(ve.slice(4,6),16),be=ve.length===8?parseInt(ve.slice(6,8),16):255;if(Number.isFinite(we+Te+Me+be))return[we,Te,Me,be]}return u}let M=w[d];if(M!==void 0)return[M>>16&255,M>>8&255,M&255,255];let L=/^(rgba?|hsla?)\(([^)]+)\)$/.exec(d);if(!L)return u;let I=L[1],B=L[2].replace(/\//g," ").split(/[\s,]+/).filter(Boolean);if(B.length<3)return u;if(I.startsWith("rgb"))return[E(B[0]),E(B[1]),E(B[2]),N(B[3])];let U=parseFloat(B[0]);if(!Number.isFinite(U))return u;B[0].endsWith("turn")?U*=360:B[0].endsWith("rad")&&(U=U*180/Math.PI);let j=(U%360+360)%360/360,K=Math.max(0,Math.min(1,(parseFloat(B[1])||0)/100)),ue=Math.max(0,Math.min(1,(parseFloat(B[2])||0)/100)),le=N(B[3]);if(K===0){let ve=S(ue*255);return[ve,ve,ve,le]}let oe=ue<.5?ue*(1+K):ue+K-ue*K,fe=2*ue-oe,ye=ve=>{let we=ve;return we<0&&(we+=1),we>1&&(we-=1),we<1/6?fe+(oe-fe)*6*we:we<1/2?oe:we<2/3?fe+(oe-fe)*(2/3-we)*6:fe};return[S(ye(j+1/3)*255),S(ye(j)*255),S(ye(j-1/3)*255),le]},_=(T,u,d,M,L,I=c)=>{if(!T||u<=0||d<=0||T.length<u*d*4)return{uri:"",avgColor:[1,1,1,1]};if(typeof b=="function"){let je=b(T,u,d,M,L,I);if(Array.isArray(je)&&typeof je[0]=="string")return{uri:je[0],avgColor:[je[1],je[2],je[3],je[4]]}}let B=u>I||d>I?I/Math.max(u,d):1,U=Math.max(1,Math.round(u*B)),j=Math.max(1,Math.round(d*B)),K=1+U*4,ue=j*K,le=2+Math.max(1,Math.ceil(ue/65535))*5+ue+4,oe=new Uint8Array(57+le),fe=new DataView(oe.buffer);fe.setUint32(0,2303741511),fe.setUint32(4,218765834),fe.setUint32(8,13),fe.setUint32(12,1229472850),fe.setUint32(16,U),fe.setUint32(20,j),oe[24]=8,oe[25]=6,fe.setUint32(29,y(oe.subarray(12,29))),fe.setUint32(33,le),fe.setUint32(37,1229209940),oe[41]=120,oe[42]=1;let ye=new Uint8Array(ue),ve=0,we=1,Te=0,Me=0,be=0,Ce=0,Ie=0,Ve=U===u&&j===d;for(let je=0;je<j;je++){ye[ve++]=0,Te=(Te+we)%65521;let Xe=M?j-1-je:je,it=Ve?Xe:Math.floor(Xe*d/j),bt=Ve?Xe+1:Math.max(it+1,Math.floor((Xe+1)*d/j));for(let pt=0;pt<U;pt++){let lt=0,xt=0,Tt=0,dt=0;if(Ve){let yt=(it*u+pt)*4;lt=T[yt]|0,xt=T[yt+1]|0,Tt=T[yt+2]|0,dt=T[yt+3]|0}else{let yt=Math.floor(pt*u/U),zt=Math.max(yt+1,Math.floor((pt+1)*u/U)),Et=0;for(let Ut=it;Ut<bt&&Ut<d;Ut++)for(let $t=yt;$t<zt&&$t<u;$t++){let Yt=(Ut*u+$t)*4;lt+=T[Yt]|0,xt+=T[Yt+1]|0,Tt+=T[Yt+2]|0,dt+=T[Yt+3]|0,Et++}Et>1&&(lt=lt/Et+.5|0,xt=xt/Et+.5|0,Tt=Tt/Et+.5|0,dt=dt/Et+.5|0)}ye[ve++]=lt,we+=lt,Te+=we,ye[ve++]=xt,we+=xt,Te+=we,ye[ve++]=Tt,we+=Tt,Te+=we,ye[ve++]=dt,we+=dt,Te+=we,Me+=L?lt/255:A[lt],be+=L?xt/255:A[xt],Ce+=L?Tt/255:A[Tt],Ie+=dt/255}we%=65521,Te%=65521}let Oe=43,qe=ue,Ke=0;for(;qe>0||Ke===0;){let je=Math.min(65535,qe),Xe=qe-je===0?1:0;if(oe[Oe++]=Xe,fe.setUint16(Oe,je,!0),fe.setUint16(Oe+2,~je&65535,!0),Oe+=4,je>0&&(oe.set(ye.subarray(Ke,Ke+je),Oe),Oe+=je,Ke+=je,qe-=je),Xe)break}fe.setUint32(Oe,(Te<<16|we)>>>0),Oe+=4,fe.setUint32(Oe,y(oe.subarray(37,Oe))),Oe+=4,fe.setUint32(Oe,0),fe.setUint32(Oe+4,1229278788),fe.setUint32(Oe+8,2923585666);let et=Math.max(1,U*j),Ye=[Me/et,be/et,Ce/et,Ie/et],tt=["data:image/png;base64,"];for(let je=0;je<oe.length;je+=3){let Xe=oe[je]<<16|(oe[je+1]??0)<<8|(oe[je+2]??0);tt.push(l[Xe>>18&63]+l[Xe>>12&63]+(je+1<oe.length?l[Xe>>6&63]:"=")+(je+2<oe.length?l[Xe&63]:"="))}return{uri:tt.join(""),avgColor:Ye}},P=(T,u,d,M)=>(T&255|(u&255)<<8|(d&255)<<16|(M&255)<<24)>>>0,R=T=>{if(T._lut)return T._lut;let u=new Uint32Array(256),d=T.s;if(d.length===1){let M=d[0].c;u.fill(P(M[0],M[1],M[2],M[3]))}else if(d.length>1){let M=0;for(let L=0;L<256;L++){let I=L/255;if(I<=d[0].o){let B=d[0].c;u[L]=P(B[0],B[1],B[2],B[3])}else if(I>=d[d.length-1].o){let B=d[d.length-1].c;u[L]=P(B[0],B[1],B[2],B[3])}else{for(;M<d.length-2&&I>d[M+1].o;)M++;let B=d[M],U=d[M+1],j=U.o-B.o,K=j>1e-9?(I-B.o)/j:0;u[L]=P(B.c[0]+(U.c[0]-B.c[0])*K+.5|0,B.c[1]+(U.c[1]-B.c[1])*K+.5|0,B.c[2]+(U.c[2]-B.c[2])*K+.5|0,B.c[3]+(U.c[3]-B.c[3])*K+.5|0)}}}return T._lut=u,u},$=(T,u,d)=>{if(T.s.length===0)return 0;let M=R(T),L=0;if(T.rad){let B=T.x1-T.x0,U=T.y1-T.y0,j=T.r1-T.r0,K=u-T.x0,ue=d-T.y0,le=B*B+U*U-j*j,oe=-2*(K*B+ue*U+T.r0*j),fe=K*K+ue*ue-T.r0*T.r0;if(Math.abs(le)<1e-9)L=Math.abs(oe)>1e-9?-fe/oe:0;else{let ye=Math.sqrt(Math.max(0,oe*oe-4*le*fe)),ve=(-oe+ye)/(2*le),we=(-oe-ye)/(2*le);L=T.r0+ve*j>=0?ve:T.r0+we*j>=0?we:Math.max(ve,we)}}else{let B=T.x1-T.x0,U=T.y1-T.y0,j=B*B+U*U;if(j<=1e-12)return M[255];L=((u-T.x0)*B+(d-T.y0)*U)/j}let I=L<=0?0:L>=1?255:L*255+.5|0;return M[I]};class F{constructor(u,d,M,L,I,B,U){this._g=1,this.rad=u,this.x0=Number(d)||0,this.y0=Number(M)||0,this.r0=Math.max(0,Number(L)||0),this.x1=Number(I)||0,this.y1=Number(B)||0,this.r1=Math.max(0,Number(U)||0),this.s=[],this._lut=null}addColorStop(u,d){let M=Math.max(0,Math.min(1,Number(u)||0));this.s.push({o:M,c:C(d,[0,0,0,255]),i:this.s.length}),this.s.sort((L,I)=>L.o-I.o||L.i-I.i),this._lut=null}}class V{constructor(u,d,M,L){this._g=2,this.d=u,this.w=Math.max(1,d|0),this.h=Math.max(1,M|0);let I=(L||"repeat").toLowerCase();this.rx=I==="repeat"||I==="repeat-x",this.ry=I==="repeat"||I==="repeat-y"}}let Y=(T,u,d)=>{let M=Math.floor(u),L=Math.floor(d);if(T.rx)M=(M%T.w+T.w)%T.w;else if(M<0||M>=T.w)return 0;if(T.ry)L=(L%T.h+T.h)%T.h;else if(L<0||L>=T.h)return 0;let I=(L*T.w+M)*4;return P(T.d[I],T.d[I+1],T.d[I+2],T.d[I+3])},J=T=>T>=32&&T<=126?T:T===176?39:T===8226||T===183?42:T===8211||T===8212||T===8722?45:T===215?120:T===8216||T===8217?39:T===8220||T===8221?34:63,re=new Array(190),Q=(T,u)=>{let d=(T-32)*2+(u?1:0),M=re[d];if(M)return M;let L=new Uint8Array(63),I=(T-32)*5;for(let U=0;U<5;U++){let j=x[I+U]??0;for(let K=0;K<7;K++)j>>K&1&&(L[(K+1)*7+(U+1)]=1)}let B=new Uint8Array(140);for(let U=0;U<7;U++)for(let j=0;j<5;j++){let K=(U+1)*7+(j+1),ue=L[K],le=L[K-7],oe=L[K+1],fe=L[K-1],ye=L[K+7],ve=U*2,we=j*2;B[ve*10+we]=fe===le&&fe!==ye&&le!==oe?le:ue,B[ve*10+we+1]=le===oe&&le!==fe&&oe!==ye?oe:ue,B[(ve+1)*10+we]=ye===fe&&ye!==oe&&fe!==le?fe:ue,B[(ve+1)*10+we+1]=oe===ye&&oe!==le&&ye!==fe?ye:ue}if(u)for(let U=0;U<14;U++)for(let j=9;j>=1;j--)B[U*10+j-1]&&(B[U*10+j]=1);return re[d]=B,B},ee=T=>{let u=String(T||"10px sans-serif"),d=/\b(bold|bolder|[6-9]00)\b/i.test(u),M=/(\d+(?:\.\d+)?)\s*(px|pt|em|rem)\b/i.exec(u);if(!M)return{sizePx:10,bold:d};let L=parseFloat(M[1]),I=M[2].toLowerCase();return I==="pt"?L*=4/3:(I==="em"||I==="rem")&&(L*=16),{sizePx:Number.isFinite(L)&&L>0?Math.min(1024,L):10,bold:d}},k=T=>{T.fillStyle="#000000",T.strokeStyle="#000000",T.globalAlpha=1,T.globalCompositeOperation="source-over",T.lineWidth=1,T.lineCap="butt",T.lineJoin="miter",T.lineDashOffset=0,T.font="10px sans-serif",T.textAlign="start",T.textBaseline="alphabetic",T.shadowColor="rgba(0, 0, 0, 0)",T.shadowBlur=0,T.shadowOffsetX=0,T.shadowOffsetY=0,T._m=[1,0,0,1,0,0],T._dash=[],T._clip=null,T._stack=[],T._subs=[],T._cur=null,T._pts=0},G=(T,u,d)=>{let M=T._m;return[(M[0]*u+M[2]*d+M[4])*T.canvas._sx,(M[1]*u+M[3]*d+M[5])*T.canvas._sy]},q=T=>{let u=T.canvas._sx>0?1/T.canvas._sx:1,d=T.canvas._sy>0?1/T.canvas._sy:1,M=T._m,L=M[0]*M[3]-M[1]*M[2];if(Math.abs(L)<1e-12)return[0,0,0,0,0,0];let I=1/L;return[M[3]*u*I,-M[2]*d*I,(-M[3]*M[4]+M[2]*M[5])*I,-M[1]*u*I,M[0]*d*I,(M[1]*M[4]-M[0]*M[5])*I]},H=(T,u,d)=>{let[M,L,I,B,U,j]=q(T);return[M*u+L*d+I,B*u+U*d+j]},te=T=>{let u=String(T.globalCompositeOperation||"source-over").toLowerCase();return u==="source-over"?0:u==="copy"?1:u==="destination-out"?2:u==="lighter"||u==="add"?3:u==="multiply"?4:u==="screen"?5:0},Z=(T,u,d)=>{T._pts>=m||!T._cur||(T._cur.pts.push([u,d]),T._pts++)},ae=(T,u)=>{let d=Number(T.globalAlpha),M=Number.isFinite(d)?Math.max(0,Math.min(1,d)):1,L=Math.round(M*256);if(typeof u=="string"){let U=C(u,[0,0,0,255]),j=P(U[0],U[1],U[2],U[3]*L+128>>8);return()=>j}let I=u?u._g:0;if(I===1||I===2){let[U,j,K,ue,le,oe]=q(T);return(fe,ye)=>{let ve=U*fe+j*ye+K,we=ue*fe+le*ye+oe,Te=I===1?$(u,ve,we):Y(u,ve,we);if(L>=256)return Te;let Me=(Te>>>24)*L+128>>8&255;return(Te&16777215|Me<<24)>>>0}}let B=P(0,0,0,255*L+128>>8);return()=>B},ie=(T,u,d,M,L)=>{let I=T.canvas._bw,B=T.canvas._bh;if(d<0||d>=I||M<0||M>=B)return;let U=M*I+d;if(T._clip&&!T._clip[U])return;let j=T.canvas._data,K=U*4,ue=L&255,le=L>>>8&255,oe=L>>>16&255,fe=L>>>24;if(u===1){j[K]=ue,j[K+1]=le,j[K+2]=oe,j[K+3]=fe;return}if(fe<=0)return;if(fe>=255&&u===0){j[K]=ue,j[K+1]=le,j[K+2]=oe,j[K+3]=255;return}if(u===2){j[K+3]=(j[K+3]*(255-fe)+127)/255|0,j[K+3]===0&&(j[K]=j[K+1]=j[K+2]=0);return}if(u===3){j[K]=Math.min(255,j[K]+((ue*fe+127)/255|0)),j[K+1]=Math.min(255,j[K+1]+((le*fe+127)/255|0)),j[K+2]=Math.min(255,j[K+2]+((oe*fe+127)/255|0)),j[K+3]=Math.min(255,j[K+3]+fe);return}let ye=j[K+3],ve=fe/255,we=ye/255,Te=ve+we*(1-ve);if(Te<=1e-6){j[K]=j[K+1]=j[K+2]=j[K+3]=0;return}let Me=ue,be=le,Ce=oe;u===4&&ye>0?(Me=(Me*j[K]+127)/255,be=(be*j[K+1]+127)/255,Ce=(Ce*j[K+2]+127)/255):u===5&&ye>0&&(Me=255-(255-Me)*(255-j[K])/255,be=255-(255-be)*(255-j[K+1])/255,Ce=255-(255-Ce)*(255-j[K+2])/255),j[K]=S((Me*ve+j[K]*we*(1-ve))/Te),j[K+1]=S((be*ve+j[K+1]*we*(1-ve))/Te),j[K+2]=S((Ce*ve+j[K+2]*we*(1-ve))/Te),j[K+3]=S(Te*255)},de=(T,u,d,M)=>{if(T.canvas.width<=0||T.canvas.height<=0)return;let L=T.canvas._bw,I=T.canvas._bh,B=[],U=I,j=-1;for(let ye of u){let ve=ye.pts,we=ve.length;if(!(we<2))for(let Te=0;Te<we;Te++){let[Me,be]=ve[Te],[Ce,Ie]=ve[(Te+1)%we];if(be===Ie)continue;let Ve=Math.min(be,Ie),Oe=Math.max(be,Ie);B.push([Ve,Oe,Ie>be?Me:Ce,(Ie>be?Ce-Me:Me-Ce)/(Oe-Ve),Ie>be?1:-1]),Ve<U&&(U=Ve),Oe>j&&(j=Oe)}}if(B.length===0)return;let K=Math.max(0,Math.floor(U)),ue=Math.min(I-1,Math.ceil(j)),le=d==="evenodd",oe=(ye,ve,we)=>{for(let Te=ve;Te<=we;Te++)M(Te,ye)},fe=[];for(let ye=K;ye<=ue;ye++){let ve=ye+.5;fe.length=0;for(let we=0;we<B.length;we++){let Te=B[we];Te[0]<=ve&&Te[1]>ve&&fe.push([Te[2]+(ve-Te[0])*Te[3],Te[4]])}if(!(fe.length<2))if(fe.sort((we,Te)=>we[0]-Te[0]),le)for(let we=0;we+1<fe.length;we+=2)oe(ye,Math.max(0,Math.ceil(fe[we][0]-.5)),Math.min(L-1,Math.floor(fe[we+1][0]-.5)));else{let we=0,Te=0;for(let Me=0;Me<fe.length;Me++){let be=we;we+=fe[Me][1],be===0&&we!==0?Te=fe[Me][0]:be!==0&&we===0&&oe(ye,Math.max(0,Math.ceil(Te-.5)),Math.min(L-1,Math.floor(fe[Me][0]-.5)))}}}},me=(T,u,d,M,L,I)=>{if(!Number.isFinite(d+M)||T.canvas.width<=0||T.canvas.height<=0)return;let B=String(u??"").slice(0,1024);if(!B)return;let U=Array.from(B),{sizePx:j,bold:K}=ee(T.font),ue=j,le=j*(K?.54:.5),oe=j*(K?.64:.6),fe=U.length*oe-j*.1,ye=1;if(L!==void 0&&Number.isFinite(L)){if(L<=0)return;fe>L&&fe>0&&(ye=L/fe)}let ve=fe*ye,we=d;T.textAlign==="center"?we-=ve*.5:(T.textAlign==="right"||T.textAlign==="end")&&(we-=ve);let Te=M,Me=T.textBaseline;Me==="middle"?Te-=ue*.5:Me==="bottom"||Me==="ideographic"?Te-=ue:Me==="alphabetic"?Te-=ue*.82:Me==="hanging"&&(Te-=ue*.08);let be=ae(T,I?T.strokeStyle:T.fillStyle),Ce=te(T),[Ie,Ve,Oe,qe,Ke,et]=q(T),Ye=T.canvas._bw,tt=T.canvas._bh,je=new Uint8Array(Ye*tt),Xe=le*ye;if(Xe<=1e-6||ue<=1e-6)return;let it=1/Xe,bt=1/ue;for(let pt=0;pt<U.length;pt++){let lt=J(U[pt].codePointAt(0)??32);if(lt===32)continue;let xt=we+pt*oe*ye,Tt=Q(lt,K),dt=G(T,xt,Te),yt=G(T,xt+Xe,Te),zt=G(T,xt+Xe,Te+ue),Et=G(T,xt,Te+ue),Ut=Math.max(0,Math.floor(Math.min(dt[0],yt[0],zt[0],Et[0]))),$t=Math.min(Ye-1,Math.ceil(Math.max(dt[0],yt[0],zt[0],Et[0]))),Yt=Math.max(0,Math.floor(Math.min(dt[1],yt[1],zt[1],Et[1]))),gr=Math.min(tt-1,Math.ceil(Math.max(dt[1],yt[1],zt[1],Et[1])));for(let mn=Yt;mn<=gr;mn++){let en=mn+.5;for(let Mn=Ut;Mn<=$t;Mn++){let es=mn*Ye+Mn;if(je[es])continue;let Gn=Mn+.5,Po=Ie*Gn+Ve*en+Oe,No=qe*Gn+Ke*en+et,Sn=(Po-xt)*it,An=(No-Te)*bt;if(Sn<0||Sn>=1||An<0||An>=1)continue;let an=Math.min(9,Sn*10|0),sn=Math.min(13,An*14|0);Tt[sn*10+an]===1&&(I&&an>0&&an<9&&sn>0&&sn<13&&Tt[sn*10+an-1]&&Tt[sn*10+an+1]&&Tt[(sn-1)*10+an]&&Tt[(sn+1)*10+an]||(je[es]=1,ie(T,Ce,Mn,mn,be(Gn,en))))}}}T.canvas._ver++};class Se{constructor(u){this.canvas=u,k(this)}save(){this._stack.length>=h||this._stack.push([this._m.slice(),this.fillStyle,this.strokeStyle,this.globalAlpha,this.globalCompositeOperation,this.lineWidth,this.lineCap,this.lineJoin,this._dash.slice(),this.lineDashOffset,this.font,this.textAlign,this.textBaseline,this.shadowColor,this.shadowBlur,this.shadowOffsetX,this.shadowOffsetY,this._clip?new Uint8Array(this._clip):null])}restore(){let u=this._stack.pop();u&&([this._m,this.fillStyle,this.strokeStyle,this.globalAlpha,this.globalCompositeOperation,this.lineWidth,this.lineCap,this.lineJoin,this._dash,this.lineDashOffset,this.font,this.textAlign,this.textBaseline,this.shadowColor,this.shadowBlur,this.shadowOffsetX,this.shadowOffsetY,this._clip]=u)}setLineDash(u){if(!Array.isArray(u))return;let d=[];for(let M=0;M<Math.min(64,u.length);M++){let L=Number(u[M]);if(!Number.isFinite(L)||L<0)return;d.push(L)}this._dash=d.length%2===1?[...d,...d]:d}getLineDash(){return[...this._dash]}resetTransform(){this._m=[1,0,0,1,0,0]}setTransform(u,d,M,L,I,B){if(u&&typeof u=="object"){this.setTransform(u.a??1,u.b??0,u.c??0,u.d??1,u.e??0,u.f??0);return}let U=Number(u??1),j=Number(d??0),K=Number(M??0),ue=Number(L??1),le=Number(I??0),oe=Number(B??0);Number.isFinite(U+j+K+ue+le+oe)&&(this._m=[U,j,K,ue,le,oe])}getTransform(){let u=this._m;return{a:u[0],b:u[1],c:u[2],d:u[3],e:u[4],f:u[5]}}transform(u,d,M,L,I,B){if(!Number.isFinite(u+d+M+L+I+B))return;let U=this._m;this._m=[U[0]*u+U[2]*d,U[1]*u+U[3]*d,U[0]*M+U[2]*L,U[1]*M+U[3]*L,U[0]*I+U[2]*B+U[4],U[1]*I+U[3]*B+U[5]]}translate(u,d){this.transform(1,0,0,1,u,d)}rotate(u){if(!Number.isFinite(u))return;let d=Math.cos(u),M=Math.sin(u);this.transform(d,M,-M,d,0,0)}scale(u,d){this.transform(u,0,0,d,0,0)}createLinearGradient(u,d,M,L){return new F(!1,u,d,0,M,L,0)}createRadialGradient(u,d,M,L,I,B){return new F(!0,u,d,M,L,I,B)}createPattern(u,d="repeat"){let M=Le(u);return M?new V(M.data,M.width,M.height,d):null}beginPath(){this._subs.length=0,this._cur=null,this._pts=0}closePath(){if(this._cur&&this._cur.pts.length>0){this._cur.closed=!0;let u=this._cur.pts[0];this._cur={pts:[[u[0],u[1]]],closed:!1},this._subs.push(this._cur)}}moveTo(u,d){Number.isFinite(u+d)&&(this._cur={pts:[G(this,u,d)],closed:!1},this._subs.push(this._cur),this._pts++)}lineTo(u,d){if(!Number.isFinite(u+d))return;if(!this._cur||this._cur.pts.length===0){this.moveTo(u,d);return}let M=G(this,u,d);Z(this,M[0],M[1])}rect(u,d,M,L){Number.isFinite(u+d+M+L)&&(this.moveTo(u,d),this.lineTo(u+M,d),this.lineTo(u+M,d+L),this.lineTo(u,d+L),this.closePath())}roundRect(u,d,M,L,I){if(!Number.isFinite(u+d+M+L))return;M<0&&(u+=M,M=-M),L<0&&(d+=L,L=-L);let B=Array.isArray(I)?I:I!==void 0?[I]:[0],U=fe=>{let ye=Number(fe&&typeof fe=="object"?fe.x??0:fe??0);return Number.isFinite(ye)?Math.max(0,ye):0},j=U(B[0]),K=U(B[1]??B[0]),ue=U(B[2]??B[0]),le=U(B[3]??B[1]??B[0]),oe=Math.min(1,M/Math.max(1e-6,j+K),M/Math.max(1e-6,le+ue),L/Math.max(1e-6,j+le),L/Math.max(1e-6,K+ue));if(j*=oe,K*=oe,ue*=oe,le*=oe,j+K+ue+le<=1e-4){this.rect(u,d,M,L);return}this.moveTo(u+j,d),this.lineTo(u+M-K,d),K>0&&this.arc(u+M-K,d+K,K,-Math.PI/2,0),this.lineTo(u+M,d+L-ue),ue>0&&this.arc(u+M-ue,d+L-ue,ue,0,Math.PI/2),this.lineTo(u+le,d+L),le>0&&this.arc(u+le,d+L-le,le,Math.PI/2,Math.PI),this.lineTo(u,d+j),j>0&&this.arc(u+j,d+j,j,Math.PI,Math.PI*3/2),this.closePath()}quadraticCurveTo(u,d,M,L){if(!Number.isFinite(u+d+M+L))return;(!this._cur||this._cur.pts.length===0)&&this.moveTo(u,d);let I=this._cur.pts,[B,U]=I[I.length-1],[j,K]=G(this,u,d),[ue,le]=G(this,M,L),oe=Math.max(4,Math.min(64,Math.ceil((Math.hypot(j-B,K-U)+Math.hypot(ue-j,le-K))*.5)));for(let fe=1;fe<=oe;fe++){let ye=fe/oe,ve=1-ye;Z(this,ve*ve*B+2*ve*ye*j+ye*ye*ue,ve*ve*U+2*ve*ye*K+ye*ye*le)}}bezierCurveTo(u,d,M,L,I,B){if(!Number.isFinite(u+d+M+L+I+B))return;(!this._cur||this._cur.pts.length===0)&&this.moveTo(u,d);let U=this._cur.pts,[j,K]=U[U.length-1],[ue,le]=G(this,u,d),[oe,fe]=G(this,M,L),[ye,ve]=G(this,I,B),we=Math.max(6,Math.min(64,Math.ceil((Math.hypot(ue-j,le-K)+Math.hypot(oe-ue,fe-le)+Math.hypot(ye-oe,ve-fe))*.4)));for(let Te=1;Te<=we;Te++){let Me=Te/we,be=1-Me,Ce=be*be,Ie=Me*Me;Z(this,Ce*be*j+3*Ce*Me*ue+3*be*Ie*oe+Ie*Me*ye,Ce*be*K+3*Ce*Me*le+3*be*Ie*fe+Ie*Me*ve)}}ellipse(u,d,M,L,I=0,B=0,U=Math.PI*2,j=!1){if(!Number.isFinite(u+d+M+L+I+B+U))return;let K=Math.max(0,M),ue=Math.max(0,L),le=Math.PI*2,oe=U-B;if(!j)oe>=le?oe=le:oe<0&&(oe=(oe%le+le)%le);else if(oe<=-le)oe=-le;else if(oe>0){let Te=oe%le;oe=Te===0?0:Te-le}let fe=Math.cos(I),ye=Math.sin(I),ve=Math.hypot(this._m[0]*this.canvas._sx,this._m[1]*this.canvas._sy,this._m[2]*this.canvas._sx,this._m[3]*this.canvas._sy),we=Math.max(8,Math.min(96,Math.ceil(Math.abs(oe)*Math.max(1,K,ue)*ve/3)));for(let Te=0;Te<=we;Te++){let Me=B+oe*Te/we,be=K*Math.cos(Me),Ce=ue*Math.sin(Me),Ie=u+be*fe-Ce*ye,Ve=d+be*ye+Ce*fe;Te===0&&(!this._cur||this._cur.pts.length===0)?this.moveTo(Ie,Ve):this.lineTo(Ie,Ve)}}arc(u,d,M,L,I,B=!1){this.ellipse(u,d,M,M,0,L,I,B)}arcTo(u,d,M,L,I){if(!Number.isFinite(u+d+M+L+I))return;let B=Math.max(0,I);if(!this._cur||this._cur.pts.length===0){this.moveTo(u,d);return}if(B<=1e-6){this.lineTo(u,d);return}let U=this._cur.pts,[j,K]=U[U.length-1],[ue,le]=H(this,j,K),oe=ue-u,fe=le-d,ye=M-u,ve=L-d,we=Math.hypot(oe,fe),Te=Math.hypot(ye,ve);if(we<1e-6||Te<1e-6){this.lineTo(u,d);return}let Me=oe/we,be=fe/we,Ce=ye/Te,Ie=ve/Te,Ve=Me*Ie-be*Ce;if(Math.abs(Ve)<1e-6){this.lineTo(u,d);return}let Oe=Math.acos(Math.max(-1,Math.min(1,Me*Ce+be*Ie)))*.5,qe=B/Math.tan(Oe),Ke=Me+Ce,et=be+Ie,Ye=Math.hypot(Ke,et)||1,tt=B/Math.sin(Oe),je=u+Ke/Ye*tt,Xe=d+et/Ye*tt;this.arc(je,Xe,B,Math.atan2(d+be*qe-Xe,u+Me*qe-je),Math.atan2(d+Ie*qe-Xe,u+Ce*qe-je),Ve>0)}fill(u){if(this.canvas.width<=0||this.canvas.height<=0)return;let d=ae(this,this.fillStyle),M=te(this);de(this,this._subs,typeof u=="string"?u:"nonzero",(L,I)=>ie(this,M,L,I,d(L+.5,I+.5))),this.canvas._ver++}clip(u){let d=this.canvas._bw,M=this.canvas._bh,L=new Uint8Array(d*M);if(de(this,this._subs,typeof u=="string"?u:"nonzero",(I,B)=>{L[B*d+I]=1}),this._clip)for(let I=0;I<L.length;I++)L[I]&=this._clip[I];this._clip=L}stroke(){if(this.canvas.width<=0||this.canvas.height<=0)return;let u=this._m,d=(Math.hypot(u[0]*this.canvas._sx,u[1]*this.canvas._sy)+Math.hypot(u[2]*this.canvas._sx,u[3]*this.canvas._sy))*.5,M=Number(this.lineWidth),L=Number.isFinite(M)&&M>0?M:1,I=Math.max(.5,L*d*.5),B=I*I,U=this.lineCap,j=this.canvas._bw,K=this.canvas._bh,ue=ae(this,this.strokeStyle),le=te(this),oe=new Uint8Array(j*K),fe=0,ye=[];for(let Me=0;Me<this._dash.length;Me++){let be=this._dash[Me]*d;ye.push(be),fe+=be}let ve=(Me,be,Ce,Ie,Ve,Oe)=>{let qe=Me,Ke=be,et=Ce,Ye=Ie,tt=et-qe,je=Ye-Ke,Xe=Math.hypot(tt,je);if(U==="square"&&Xe>1e-6){let dt=tt/Xe*I,yt=je/Xe*I;Ve&&(qe-=dt,Ke-=yt),Oe&&(et+=dt,Ye+=yt),tt=et-qe,je=Ye-Ke}let it=tt*tt+je*je,bt=I+.5,pt=Math.max(0,Math.floor(Math.min(qe,et)-bt)),lt=Math.min(j-1,Math.ceil(Math.max(qe,et)+bt)),xt=Math.max(0,Math.floor(Math.min(Ke,Ye)-bt)),Tt=Math.min(K-1,Math.ceil(Math.max(Ke,Ye)+bt));for(let dt=xt;dt<=Tt;dt++){let yt=dt+.5;for(let zt=pt;zt<=lt;zt++){let Et=dt*j+zt;if(oe[Et])continue;let Ut=zt+.5,$t=it>1e-9?((Ut-qe)*tt+(yt-Ke)*je)/it:0;if(U==="butt"&&($t<0&&Ve||$t>1&&Oe))continue;$t=Math.max(0,Math.min(1,$t));let Yt=qe+$t*tt,gr=Ke+$t*je;(Ut-Yt)*(Ut-Yt)+(yt-gr)*(yt-gr)<=B&&(oe[Et]=1,ie(this,le,zt,dt,ue(Ut,yt)))}}},we=Number(this.lineDashOffset),Te=Number.isFinite(we)?we:0;for(let Me of this._subs){let be=Me.pts,Ce=be.length;if(Ce<2)continue;let Ie=Me.closed?Ce:Ce-1,Ve=fe>1e-6?(Te*d%fe+fe)%fe:0;for(let Oe=0;Oe<Ie;Oe++){let[qe,Ke]=be[Oe],[et,Ye]=be[(Oe+1)%Ce];if(fe<=1e-6)ve(qe,Ke,et,Ye,!Me.closed&&Oe===0,!Me.closed&&Oe===Ie-1);else{let tt=Math.hypot(et-qe,Ye-Ke);if(tt<=1e-6)continue;let je=0;for(;je<tt;){let Xe=Ve,it=0;for(;it<ye.length&&Xe>=ye[it];)Xe-=ye[it],it++;let bt=Math.min(tt-je,it<ye.length?Math.max(.25,ye[it]-Xe):tt-je);if(it%2===0){let pt=je/tt,lt=(je+bt)/tt;ve(qe+(et-qe)*pt,Ke+(Ye-Ke)*pt,qe+(et-qe)*lt,Ke+(Ye-Ke)*lt,!0,!0)}je+=bt,Ve=(Ve+bt)%fe}}}}this.canvas._ver++}clearRect(u,d,M,L){if(!Number.isFinite(u+d+M+L)||this.canvas.width<=0||this.canvas.height<=0)return;let I=this._m;if(I[0]===1&&I[1]===0&&I[2]===0&&I[3]===1&&I[4]===0&&I[5]===0&&!this._clip&&u<=0&&d<=0&&u+M>=this.canvas.width&&d+L>=this.canvas.height){this.canvas._data.fill(0),this.canvas._ver++;return}let B=this.canvas._data,U=this.canvas._bw,j=this._clip;de(this,[{pts:[G(this,u,d),G(this,u+M,d),G(this,u+M,d+L),G(this,u,d+L)],closed:!0}],"nonzero",(K,ue)=>{let le=ue*U+K;if(j&&!j[le])return;let oe=le*4;B[oe]=B[oe+1]=B[oe+2]=B[oe+3]=0}),this.canvas._ver++}fillRect(u,d,M,L){if(!Number.isFinite(u+d+M+L)||M===0||L===0||this.canvas.width<=0||this.canvas.height<=0)return;let I=ae(this,this.fillStyle),B=te(this),U=this._m;if(U[1]===0&&U[2]===0){let j=this.canvas._bw,K=this.canvas._bh,ue=(U[0]*u+U[4])*this.canvas._sx,le=(U[0]*(u+M)+U[4])*this.canvas._sx,oe=(U[3]*d+U[5])*this.canvas._sy,fe=(U[3]*(d+L)+U[5])*this.canvas._sy,ye=Math.max(0,Math.ceil(Math.min(ue,le)-.5)),ve=Math.min(j-1,Math.ceil(Math.max(ue,le)-.5)-1),we=Math.max(0,Math.ceil(Math.min(oe,fe)-.5)),Te=Math.min(K-1,Math.ceil(Math.max(oe,fe)-.5)-1);if(ye<=ve&&we<=Te){if(!this._clip&&typeof this.fillStyle=="string"){let be=I(0,0),Ce=be>>>24;if(B===0&&Ce>=255||B===1){let Ie=new Uint32Array(new Uint8Array([be&255,be>>>8&255,be>>>16&255,Ce]).buffer)[0],Ve=this.canvas._data,Oe=new Uint32Array(Ve.buffer,Ve.byteOffset,j*K);if(ye===0&&ve===j-1)Oe.fill(Ie,we*j,(Te+1)*j);else for(let qe=we;qe<=Te;qe++)Oe.fill(Ie,qe*j+ye,qe*j+ve+1);this.canvas._ver++;return}}let Me=be=>{let Ce=be+.5;for(let Ie=ye;Ie<=ve;Ie++)ie(this,B,Ie,be,I(Ie+.5,Ce))};for(let be=we;be<=Te;be++)Me(be)}this.canvas._ver++;return}de(this,[{pts:[G(this,u,d),G(this,u+M,d),G(this,u+M,d+L),G(this,u,d+L)],closed:!0}],"nonzero",(j,K)=>ie(this,B,j,K,I(j+.5,K+.5))),this.canvas._ver++}strokeRect(u,d,M,L){if(!Number.isFinite(u+d+M+L)||M===0&&L===0)return;let I=this._subs,B=this._cur,U=this._pts;this._subs=[],this._cur=null,this._pts=0,this.rect(u,d,M,L),this.stroke(),this._subs=I,this._cur=B,this._pts=U}measureText(u){let{sizePx:d,bold:M}=ee(this.font),L=Array.from(String(u??"")).length;return{width:L>0?L*d*(M?.64:.6)-d*.1:0,actualBoundingBoxAscent:d*.8,actualBoundingBoxDescent:d*.2,fontBoundingBoxAscent:d*.85,fontBoundingBoxDescent:d*.2}}fillText(u,d,M,L){me(this,u,d,M,L,!1)}strokeText(u,d,M,L){me(this,u,d,M,L,!0)}createImageData(u,d){let M=u&&typeof u=="object",L=Math.max(1,Math.min(f,Math.floor(Math.abs(Number(M?u.width:u))||1))),I=Math.max(1,Math.min(f,Math.floor(Math.abs(Number(M?u.height:d))||1)));return{data:new Uint8ClampedArray(L*I*4),width:L,height:I}}getImageData(u,d,M,L){let I=Math.floor(Number(u)||0),B=Math.floor(Number(d)||0),U=Math.floor(Number(M)||0),j=Math.floor(Number(L)||0);U<0&&(I+=U,U=-U),j<0&&(B+=j,j=-j),U=Math.max(1,Math.min(f,U)),j=Math.max(1,Math.min(f,j));let K=new Uint8ClampedArray(U*j*4);if(this.canvas.width<=0||this.canvas.height<=0)return{data:K,width:U,height:j};let ue=this.canvas._bw,le=this.canvas._bh,oe=this.canvas._sx,fe=this.canvas._sy,ye=this.canvas._data;for(let ve=0;ve<j;ve++){let we=B+ve;if(we<0||we>=this.canvas.height)continue;let Te=Math.min(le-1,Math.floor((we+.5)*fe));for(let Me=0;Me<U;Me++){let be=I+Me;if(be<0||be>=this.canvas.width)continue;let Ce=(Te*ue+Math.min(ue-1,Math.floor((be+.5)*oe)))*4,Ie=(ve*U+Me)*4;K[Ie]=ye[Ce],K[Ie+1]=ye[Ce+1],K[Ie+2]=ye[Ce+2],K[Ie+3]=ye[Ce+3]}}return{data:K,width:U,height:j}}putImageData(u,d,M,L=0,I=0,B,U){if(!u?.data||this.canvas.width<=0||this.canvas.height<=0)return;let j=Math.floor(Number(u.width)||0),K=Math.floor(Number(u.height)||0);if(j<=0||K<=0)return;let ue=Math.floor(Number(L)||0),le=Math.floor(Number(I)||0),oe=B!==void 0?Math.floor(Number(B)):j,fe=U!==void 0?Math.floor(Number(U)):K;oe<0&&(ue+=oe,oe=-oe),fe<0&&(le+=fe,fe=-fe);let ye=Math.max(0,ue),ve=Math.max(0,le),we=Math.min(j,ue+oe),Te=Math.min(K,le+fe);if(ye>=we||ve>=Te)return;let Me=Math.floor(Number(d)||0),be=Math.floor(Number(M)||0),Ce=this.canvas._bw,Ie=this.canvas._bh,Ve=1/this.canvas._sx,Oe=1/this.canvas._sy,qe=this.canvas._data,Ke=u.data,et=Math.max(0,Math.floor((Me+ye)*this.canvas._sx)),Ye=Math.min(Ce-1,Math.ceil((Me+we)*this.canvas._sx)-1),tt=Math.max(0,Math.floor((be+ve)*this.canvas._sy)),je=Math.min(Ie-1,Math.ceil((be+Te)*this.canvas._sy)-1);for(let Xe=tt;Xe<=je;Xe++){let it=Math.floor((Xe+.5)*Oe)-be;if(!(it<ve||it>=Te))for(let bt=et;bt<=Ye;bt++){let pt=Math.floor((bt+.5)*Ve)-Me;if(pt<ye||pt>=we)continue;let lt=(it*j+pt)*4,xt=(Xe*Ce+bt)*4;qe[xt]=Ke[lt]|0,qe[xt+1]=Ke[lt+1]|0,qe[xt+2]=Ke[lt+2]|0,qe[xt+3]=Ke[lt+3]|0}}this.canvas._ver++}drawImage(u,...d){let M=Le(u);if(!M||M.width<=0||M.height<=0||this.canvas.width<=0||this.canvas.height<=0)return;let L=Number(u?.width)>0?Number(u.width):M.width,I=Number(u?.height)>0?Number(u.height):M.height,B=0,U=0,j=L,K=I,ue=0,le=0,oe=L,fe=I;if(d.length>=8)[B,U,j,K,ue,le,oe,fe]=d;else if(d.length>=4)[ue,le,oe,fe]=d;else if(d.length>=2)[ue,le]=d;else return;if(!Number.isFinite(B+U+j+K+ue+le+oe+fe)||j===0||K===0||oe===0||fe===0)return;let ye=Number(this.globalAlpha),ve=Number.isFinite(ye)?Math.max(0,Math.min(1,ye)):1,we=Math.round(ve*256),Te=te(this),[Me,be,Ce,Ie,Ve,Oe]=q(this),qe=1/oe,Ke=1/fe,et=M.width/L,Ye=M.height/I;de(this,[{pts:[G(this,ue,le),G(this,ue+oe,le),G(this,ue+oe,le+fe),G(this,ue,le+fe)],closed:!0}],"nonzero",(tt,je)=>{let Xe=tt+.5,it=je+.5,bt=Me*Xe+be*it+Ce,pt=Ie*Xe+Ve*it+Oe,lt=(bt-ue)*qe,xt=(pt-le)*Ke;if(lt<0||lt>=1||xt<0||xt>=1)return;let Tt=Math.floor((B+lt*j)*et),dt=Math.floor((U+xt*K)*Ye);if(Tt<0||Tt>=M.width||dt<0||dt>=M.height)return;let yt=(dt*M.width+Tt)*4;ie(this,Te,tt,je,P(M.data[yt],M.data[yt+1],M.data[yt+2],M.data[yt+3]*we+128>>8))}),this.canvas._ver++}}let Fe=(T,u,d)=>{let M=Math.floor(Number(u)),L=Math.floor(Number(d));T._w=Number.isFinite(M)&&M>=0?M:0,T._h=Number.isFinite(L)&&L>=0?L:0,T._bw=T._w>0?Math.min(c,T._w):1,T._bh=T._h>0?Math.min(c,T._h):1,T._sx=T._w>0?T._bw/T._w:1,T._sy=T._h>0?T._bh/T._h:1,T._data=new Uint8ClampedArray(T._bw*T._bh*4),T._ctx2d&&k(T._ctx2d),T._ver++};class _e{constructor(u=300,d=150){this._vc=!0,this._ver=1,this._ctx2d=null,this.style={},Fe(this,u,d)}get width(){return this._w}set width(u){Fe(this,u,this._h)}get height(){return this._h}set height(u){Fe(this,this._w,u)}getContext(u){return String(u).toLowerCase()!=="2d"?null:this._ctx2d??(this._ctx2d=new Se(this))}toDataURL(){return this._w<=0||this._h<=0||this._w>f||this._h>f?"":_(this._data,this._bw,this._bh,!1,!1).uri}addEventListener(){}removeEventListener(){}getBoundingClientRect(){return{left:0,top:0,width:this._w,height:this._h,right:this._w,bottom:this._h}}}function Le(T){if(!T||typeof T!="object")return null;let u=T._vc?T:T.canvas?._vc?T.canvas:T.image?._vc?T.image:null;if(u)return{data:u._data,width:u._bw,height:u._bh,logicalW:u._w,logicalH:u._h,ver:u._ver};let d=T.image&&typeof T.image=="object"?T.image:T;if(d.data&&typeof d.data.length=="number"&&Number(d.width)>0&&Number(d.height)>0){let M=Math.floor(Number(d.width)),L=Math.floor(Number(d.height));return{data:d.data instanceof Uint8ClampedArray?d.data:new Uint8ClampedArray(d.data),width:M,height:L,logicalW:M,logicalH:L,ver:-1}}if(typeof d.getContext=="function"){let M=Math.floor(Number(d.width)||0),L=Math.floor(Number(d.height)||0);if(M>0&&L>0&&M<=f&&L<=f)try{let I=d.getContext("2d")?.getImageData?.(0,0,M,L);if(I?.data)return{data:I.data instanceof Uint8ClampedArray?I.data:new Uint8ClampedArray(I.data),width:M,height:L,logicalW:M,logicalH:L,ver:-1}}catch{}}return null}let ne=e.Texture??class{constructor(T=""){this.source=T,this.isTexture=!0,this.image=null,this.width=0,this.height=0}dispose(){}},Re=T=>{let u=Le(T.image);if(!u){T.width=Number(T.image?.width??0)||0,T.height=Number(T.image?.height??0)||0,T._cs="";return}if(T.width=u.logicalW,T.height=u.logicalH,u.logicalW<=0||u.logicalH<=0||u.logicalW>f||u.logicalH>f){T._cs="";return}let d=`${u.ver>=0?u.ver:T._fs}|${u.logicalW}x${u.logicalH}|${T.flipY?1:0}|${T.colorSpace}`;if(d===T._bk&&T._cs)return;T._bk=d;let M=_(u.data,u.width,u.height,T.flipY,T.colorSpace==="srgb-linear",Math.min(f,Number(T._pngDim)||c));T._cs=M.uri,T._ca=M.avgColor};class W extends ne{constructor(u=null,d,M=1001,L=1001,I=1006,B=1008,U=1023,j=1009,K=1,ue="srgb"){super(""),delete this.source,this.isCanvasTexture=!0,this.isDataTexture=!0,this.image=u,this.width=Number(u?.width??0)||0,this.height=Number(u?.height??0)||0,this.wrapS=Number(M)||1001,this.wrapT=Number(L)||1001,this.magFilter=Number(I)||1006,this.minFilter=Number(B)||1008,this.format=Number(U)||1023,this.type=Number(j)||1009,this.flipY=!0,this.generateMipmaps=!0,this.unpackAlignment=4,this.colorSpace=ue||"srgb",this._bk="",this._cs="",this._ca=[1,1,1,1],this._ms="",this._fs=1}get needsUpdate(){return!1}set needsUpdate(u){u&&(this._ms="",this._fs++,this.width=Number(this.image?.width??0)||0,this.height=Number(this.image?.height??0)||0)}get source(){return this._ms?this._ms:(Re(this),this._cs)}set source(u){this._ms=typeof u=="string"?u:""}get avgColor(){return this._ms||Re(this),this._ca}set avgColor(u){Array.isArray(u)&&u.length===4&&(this._ca=[u[0],u[1],u[2],u[3]])}}try{Object.freeze(F.prototype),Object.freeze(V.prototype),Object.freeze(Se.prototype),Object.freeze(_e.prototype)}catch{}let D=(T=300,u=150)=>new _e(T,u);try{let T=typeof globalThis<"u"?globalThis:typeof self<"u"?self:void 0;if(T&&typeof T.HTMLCanvasElement>"u"){let u=d=>String(d).toLowerCase()==="canvas"?new _e(300,150):{style:{},getContext:()=>null,addEventListener:()=>{},removeEventListener:()=>{},appendChild:()=>{},removeChild:()=>{},setAttribute:()=>{}};if(typeof T.document>"u"||T.document===null){let d=Object.freeze({appendChild:()=>{},removeChild:()=>{},style:{}}),M=Object.freeze({style:{}});T.document=Object.freeze({__threeLiveVirtualCanvas:!0,createElement:u,createTextNode:()=>({}),querySelectorAll:()=>[],querySelector:()=>null,getElementById:()=>null,head:d,body:d,documentElement:M,addEventListener:()=>{},removeEventListener:()=>{}})}else if(typeof T.document=="object"&&!T.document.__threeLiveVirtualCanvas){let d=typeof T.document.createElement=="function"?T.document.createElement.bind(T.document):null;try{T.document.__threeLiveVirtualCanvas=!0,T.document.createElement=M=>String(M).toLowerCase()==="canvas"?new _e(300,150):d?d(M):u(M)}catch{}}}}catch{}let z=new Uint8Array([151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180]),O=new Uint8Array(512);for(let T=0;T<256;T++)O[T]=z[T],O[T+256]=z[T];let X=T=>T*T*T*(T*(T*6-15)+10),se=(T,u,d)=>u+T*(d-u),ce=(T,u,d,M)=>{let L=T&15,I=L<8?u:d,B=L<4?d:L===12||L===14?u:M;return((L&1)===0?I:-I)+((L&2)===0?B:-B)};class pe{noise(u,d,M=0){let L=Number(u),I=Number(d),B=Number(M);if(!Number.isFinite(L)||!Number.isFinite(I)||!Number.isFinite(B))return 0;let U=Math.floor(L),j=Math.floor(I),K=Math.floor(B),ue=U&255,le=j&255,oe=K&255;L-=U,I-=j,B-=K;let fe=L-1,ye=I-1,ve=B-1,we=X(L),Te=X(I),Me=X(B),be=O[ue]+le,Ce=O[be]+oe,Ie=O[be+1]+oe,Ve=O[ue+1]+le,Oe=O[Ve]+oe,qe=O[Ve+1]+oe;return se(Me,se(Te,se(we,ce(O[Ce],L,I,B),ce(O[Oe],fe,I,B)),se(we,ce(O[Ie],L,ye,B),ce(O[qe],fe,ye,B))),se(Te,se(we,ce(O[Ce+1],L,I,ve),ce(O[Oe+1],fe,I,ve)),se(we,ce(O[Ie+1],L,ye,ve),ce(O[qe+1],fe,ye,ve))))}}Object.freeze(pe.prototype);let xe=new Int8Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0,1,0,1,-1,0,1,1,0,-1,-1,0,-1,0,1,1,0,-1,1,0,1,-1,0,-1,-1]),he=new Int8Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]),Ne=.5*(Math.sqrt(3)-1),ge=(3-Math.sqrt(3))/6,Ae=1/3,Ee=1/6,De=(Math.sqrt(5)-1)/4,ke=(5-Math.sqrt(5))/20,ze=(T,u,d)=>xe[T]*u+xe[T+1]*d,Be=(T,u,d,M)=>xe[T]*u+xe[T+1]*d+xe[T+2]*M,Ue=(T,u,d,M,L)=>he[T]*u+he[T+1]*d+he[T+2]*M+he[T+3]*L;function We(T){let u=T===void 0?Math:T;if(typeof u=="function")return u;if(typeof u=="number"){let d=Number.isFinite(u)?u|0:0;return()=>{let M=d=d+1831565813|0;return M=Math.imul(M^M>>>15,M|1),M^=M+Math.imul(M^M>>>7,M|61),((M^M>>>14)>>>0)/4294967296}}return u&&typeof u=="object"&&typeof u.random=="function"?()=>u.random():Math.random}class Ge{constructor(u){let d=We(u),M=new Uint8Array(256);for(let B=0;B<256;B++){let U=Number(d()),j=Number.isFinite(U)?(U%1+1)%1:0;M[B]=Math.floor(j*256)&255}let L=new Uint8Array(512),I=new Uint8Array(512);for(let B=0;B<512;B++){let U=M[B&255];L[B]=U,I[B]=U%12}this.p=M,this.perm=L,this.permMod12=I}noise(u,d){let M=Number(u),L=Number(d);if(!Number.isFinite(M)||!Number.isFinite(L))return 0;let I=this.perm,B=this.permMod12,U=(M+L)*Ne,j=Math.floor(M+U),K=Math.floor(L+U),ue=(j+K)*ge,le=j-ue,oe=K-ue,fe=M-le,ye=L-oe,ve=fe>ye?1:0,we=fe>ye?0:1,Te=fe-ve+ge,Me=ye-we+ge,be=fe-1+2*ge,Ce=ye-1+2*ge,Ie=j&255,Ve=K&255,Oe=B[Ie+I[Ve]]*3,qe=B[Ie+ve+I[Ve+we]]*3,Ke=B[Ie+1+I[Ve+1]]*3,et=0,Ye=.5-fe*fe-ye*ye;Ye>=0&&(Ye*=Ye,et=Ye*Ye*ze(Oe,fe,ye));let tt=0,je=.5-Te*Te-Me*Me;je>=0&&(je*=je,tt=je*je*ze(qe,Te,Me));let Xe=0,it=.5-be*be-Ce*Ce;return it>=0&&(it*=it,Xe=it*it*ze(Ke,be,Ce)),70*(et+tt+Xe)}noise3d(u,d,M){let L=Number(u),I=Number(d),B=Number(M);if(!Number.isFinite(L)||!Number.isFinite(I)||!Number.isFinite(B))return 0;let U=this.perm,j=this.permMod12,K=(L+I+B)*Ae,ue=Math.floor(L+K),le=Math.floor(I+K),oe=Math.floor(B+K),fe=(ue+le+oe)*Ee,ye=L-(ue-fe),ve=I-(le-fe),we=B-(oe-fe),Te,Me,be,Ce,Ie,Ve;ye>=ve?ve>=we?(Te=1,Me=0,be=0,Ce=1,Ie=1,Ve=0):ye>=we?(Te=1,Me=0,be=0,Ce=1,Ie=0,Ve=1):(Te=0,Me=0,be=1,Ce=1,Ie=0,Ve=1):ve<we?(Te=0,Me=0,be=1,Ce=0,Ie=1,Ve=1):ye<we?(Te=0,Me=1,be=0,Ce=0,Ie=1,Ve=1):(Te=0,Me=1,be=0,Ce=1,Ie=1,Ve=0);let Oe=ye-Te+Ee,qe=ve-Me+Ee,Ke=we-be+Ee,et=ye-Ce+2*Ee,Ye=ve-Ie+2*Ee,tt=we-Ve+2*Ee,je=ye-1+3*Ee,Xe=ve-1+3*Ee,it=we-1+3*Ee,bt=ue&255,pt=le&255,lt=oe&255,xt=j[bt+U[pt+U[lt]]]*3,Tt=j[bt+Te+U[pt+Me+U[lt+be]]]*3,dt=j[bt+Ce+U[pt+Ie+U[lt+Ve]]]*3,yt=j[bt+1+U[pt+1+U[lt+1]]]*3,zt=0,Et=.6-ye*ye-ve*ve-we*we;Et>=0&&(Et*=Et,zt=Et*Et*Be(xt,ye,ve,we));let Ut=0,$t=.6-Oe*Oe-qe*qe-Ke*Ke;$t>=0&&($t*=$t,Ut=$t*$t*Be(Tt,Oe,qe,Ke));let Yt=0,gr=.6-et*et-Ye*Ye-tt*tt;gr>=0&&(gr*=gr,Yt=gr*gr*Be(dt,et,Ye,tt));let mn=0,en=.6-je*je-Xe*Xe-it*it;return en>=0&&(en*=en,mn=en*en*Be(yt,je,Xe,it)),32*(zt+Ut+Yt+mn)}noise4d(u,d,M,L){let I=Number(u),B=Number(d),U=Number(M),j=Number(L);if(!Number.isFinite(I)||!Number.isFinite(B)||!Number.isFinite(U)||!Number.isFinite(j))return 0;let K=this.perm,ue=(I+B+U+j)*De,le=Math.floor(I+ue),oe=Math.floor(B+ue),fe=Math.floor(U+ue),ye=Math.floor(j+ue),ve=(le+oe+fe+ye)*ke,we=I-(le-ve),Te=B-(oe-ve),Me=U-(fe-ve),be=j-(ye-ve),Ce=(we>Te?1:0)+(we>Me?1:0)+(we>be?1:0),Ie=(we<=Te?1:0)+(Te>Me?1:0)+(Te>be?1:0),Ve=(we<=Me?1:0)+(Te<=Me?1:0)+(Me>be?1:0),Oe=(we<=be?1:0)+(Te<=be?1:0)+(Me<=be?1:0),qe=Ce>=3?1:0,Ke=Ie>=3?1:0,et=Ve>=3?1:0,Ye=Oe>=3?1:0,tt=Ce>=2?1:0,je=Ie>=2?1:0,Xe=Ve>=2?1:0,it=Oe>=2?1:0,bt=Ce>=1?1:0,pt=Ie>=1?1:0,lt=Ve>=1?1:0,xt=Oe>=1?1:0,Tt=we-qe+ke,dt=Te-Ke+ke,yt=Me-et+ke,zt=be-Ye+ke,Et=we-tt+2*ke,Ut=Te-je+2*ke,$t=Me-Xe+2*ke,Yt=be-it+2*ke,gr=we-bt+3*ke,mn=Te-pt+3*ke,en=Me-lt+3*ke,Mn=be-xt+3*ke,es=we-1+4*ke,Gn=Te-1+4*ke,Po=Me-1+4*ke,No=be-1+4*ke,Sn=le&255,An=oe&255,an=fe&255,sn=ye&255,ld=(K[Sn+K[An+K[an+K[sn]]]]&31)*4,ud=(K[Sn+qe+K[An+Ke+K[an+et+K[sn+Ye]]]]&31)*4,cd=(K[Sn+tt+K[An+je+K[an+Xe+K[sn+it]]]]&31)*4,dd=(K[Sn+bt+K[An+pt+K[an+lt+K[sn+xt]]]]&31)*4,e1=(K[Sn+1+K[An+1+K[an+1+K[sn+1]]]]&31)*4,wh=0,Co=.6-we*we-Te*Te-Me*Me-be*be;Co>=0&&(Co*=Co,wh=Co*Co*Ue(ld,we,Te,Me,be));let Sh=0,Lo=.6-Tt*Tt-dt*dt-yt*yt-zt*zt;Lo>=0&&(Lo*=Lo,Sh=Lo*Lo*Ue(ud,Tt,dt,yt,zt));let Nh=0,Io=.6-Et*Et-Ut*Ut-$t*$t-Yt*Yt;Io>=0&&(Io*=Io,Nh=Io*Io*Ue(cd,Et,Ut,$t,Yt));let Ch=0,Do=.6-gr*gr-mn*mn-en*en-Mn*Mn;Do>=0&&(Do*=Do,Ch=Do*Do*Ue(dd,gr,mn,en,Mn));let $h=0,Fo=.6-es*es-Gn*Gn-Po*Po-No*No;return Fo>=0&&(Fo*=Fo,$h=Fo*Fo*Ue(e1,es,Gn,Po,No)),27*(wh+Sh+Nh+Ch+$h)}noise2D(u,d){return this.noise(u,d)}noise3D(u,d,M){return this.noise3d(u,d,M)}noise4D(u,d,M,L){return this.noise4d(u,d,M,L)}}Object.freeze(Ge.prototype);let ut=T=>{if(!T||typeof T!="object")return null;let u=T,d=u.image,M=Le(d??u);if(M&&d?._vc)return{buf:M.data,w:M.width,h:M.height,ch:4,isFloat:!1,flipY:!!u.flipY};let L=d?.data,I=Number(d?.width??u.width)|0,B=Number(d?.height??u.height)|0;if(!L||!(I>0&&B>0)||!L.length)return null;let U=I*B,j=u.format,K=j===1021||j===1024||j===1028||L.length===U?1:j===1025||j===1030||L.length===U*2?2:j===1022||L.length===U*3?3:4;return{buf:L,w:I,h:B,ch:K,isFloat:u.type===1015||u.type===1016||L instanceof Float32Array||L instanceof Float64Array,flipY:!!u.flipY}},nt=(T,u,d,M)=>{let L=Math.min(T.w-1,Math.max(0,u*T.w|0)),I=Math.min(T.h-1,Math.max(0,d*T.h|0)),B=T.flipY?T.h-1-I:I,U=Number(T.buf[(B*T.w+L)*T.ch+Math.min(M,T.ch-1)]??0);if(!Number.isFinite(U))return 0;let j=T.isFloat&&U<=1?U*255:U;return j>0?j<255?j+.5|0:255:0},st=e.MeshStandardMaterial?.prototype&&(Object.getPrototypeOf(e.MeshStandardMaterial.prototype)||e.MeshStandardMaterial.prototype);st&&typeof st._packPbr!="function"&&(st._packPbr=function(){let T;if((this.roughnessMap||this.metalnessMap)&&this.roughnessMap!==this.metalnessMap){let M=ut(this.roughnessMap),L=ut(this.metalnessMap);if(M||L){let I=Math.min(128,Math.max(M?.w??1,L?.w??1)),B=Math.min(128,Math.max(M?.h??1,L?.h??1)),U=new Uint8ClampedArray(I*B*4);for(let j=0;j<B;j++){let K=(j+.5)/B;for(let ue=0;ue<I;ue++){let le=(ue+.5)/I,oe=(j*I+ue)*4;U[oe]=255,U[oe+1]=M?nt(M,le,K,1):255,U[oe+2]=L?nt(L,le,K,2):255,U[oe+3]=255}}T=_(U,I,B,!1,!0,128).uri}}let u,d;if(!this.normalMap&&this.bumpMap){let M=ut(this.bumpMap);if(M){let L=Number.isFinite(this.bumpScale)?this.bumpScale:1,I=Math.min(128,M.w),B=Math.min(128,M.h),U=new Uint8ClampedArray(I*B*4),j=(K,ue)=>nt(M,((K%I+I)%I+.5)/I,((ue%B+B)%B+.5)/B,0)/255;for(let K=0;K<B;K++)for(let ue=0;ue<I;ue++){let le=(j(ue+1,K)-j(ue-1,K))*L*2,oe=(j(ue,K+1)-j(ue,K-1))*L*2,fe=1/Math.hypot(le,oe,1),ye=(K*I+ue)*4;U[ye]=(-le*fe*.5+.5)*255+.5|0,U[ye+1]=(oe*fe*.5+.5)*255+.5|0,U[ye+2]=(fe*.5+.5)*255+.5|0,U[ye+3]=255}u=_(U,I,B,!1,!0,128).uri,d=1}}return{mrUri:T,normUri:u,normScale:d}});let ft=0,Qe=e.Vector2,It=e.PlaneGeometry,Dt=e.Mesh,yr=e.Material;class Mt extends yr{constructor(u={}){super({roughness:.85,metalness:0,side:2,transparent:u.transparent??!0,...u}),this.isSpriteMaterial=!0;let d=Number(u.rotation);this.rotation=Number.isFinite(d)?d:0,this.sizeAttenuation=u.sizeAttenuation!==!1,u.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.35,this.map&&!this.emissiveMap&&(this.emissiveMap=this.map))}clone(){return new Mt({...this,emissive:this._em?this.emissive:void 0})}}class jt extends Dt{constructor(u){super(new It(1,1),u instanceof yr?u:new Mt(u||{})),this.isSprite=!0,this.center=new Qe(.5,.5),this.userData={xr:{billboard:"spherical"}}}_cloneCustom(){let u=new jt(this.material);return u.center.copy(this.center),u._autoNamed=!!this._autoNamed,u._noBillboard=!!this._noBillboard,u}_bakeAuthorGeometry(){this._bakedOwner!==this?((!this.name||this._autoNamed)&&(this.name=`Sprite_${++ft}`,this._autoNamed=!0),this._bakedOwner=this):this.name||(this.name=`Sprite_${++ft}`,this._autoNamed=!0);let u=this.userData?.xr?.billboard;u===!1||u===null?(this._noBillboard=!0,delete this.userData.xr.billboard,Object.keys(this.userData.xr).length===0&&delete this.userData.xr):((typeof u=="string"||u===!0)&&(this._noBillboard=!1),this._noBillboard||(!this.userData||typeof this.userData!="object"?this.userData={xr:{billboard:"spherical"}}:!this.userData.xr||typeof this.userData.xr!="object"?this.userData.xr={billboard:"spherical"}:this.userData.xr.billboard===void 0&&(this.userData.xr.billboard="spherical")));let d=Number.isFinite(this.center?.x)?this.center.x:.5,M=Number.isFinite(this.center?.y)?this.center.y:.5,L=Number(this.material?.rotation),I=Number.isFinite(L)?L:0,B=`${d},${M},${I}`;if(this._bakedKey!==B&&(this._bakedKey!==void 0||d!==.5||M!==.5||I!==0)){let U=new It(1,1),j=U.attributes.position?.array,K=.5-d,ue=.5-M,le=Math.cos(I),oe=Math.sin(I);if(j){for(let fe=0;fe<j.length;fe+=3){let ye=j[fe]+K,ve=j[fe+1]+ue;j[fe]=ye*le-ve*oe,j[fe+1]=ye*oe+ve*le}U.boundingBox=null,U.boundingSphere=null}U.__baked=!0,this._bakedKey=B,this.geometry=U}}}if(Object.freeze(Mt.prototype),Object.freeze(jt.prototype),Qe?.prototype){let T=Qe.prototype,u=(d,M)=>{typeof T[d]!="function"&&(T[d]=M)};u("length",function(){return Math.hypot(this.x,this.y)}),u("normalize",function(){return this.divideScalar(Math.hypot(this.x,this.y)||1)}),u("distanceTo",function(d){return Math.hypot(this.x-(d?.x||0),this.y-(d?.y||0))}),u("dot",function(d){return this.x*(d?.x||0)+this.y*(d?.y||0)}),u("lerp",function(d,M){let L=Number(M)||0;return this.set(this.x+((d?.x||0)-this.x)*L,this.y+((d?.y||0)-this.y)*L)}),u("lerpVectors",function(d,M,L){let I=Number(L)||0,B=d?.x||0,U=d?.y||0;return this.set(B+((M?.x||0)-B)*I,U+((M?.y||0)-U)*I)}),u("equals",function(d){return!!d&&d.x===this.x&&d.y===this.y})}let Pe=(T,u=0)=>{let d=Number(T);return Number.isFinite(d)?d:u},ot=T=>Math.max(0,Math.min(1,Pe(T,0))),wt=T=>new Qe(Pe(T?.x),Pe(T?.y));class St{constructor(u="Curve"){this.type=u,this.arcLengthDivisions=200,this._lenCache=null}getPoint(u,d=new Qe){return d.set(0,0)}getPointAt(u,d){return this.getPoint(this.getUtoTMapping(u),d)}getPoints(u=5){let d=Math.max(1,Math.min(1024,Math.floor(Pe(u,5)))),M=[];for(let L=0;L<=d;L++)M.push(this.getPoint(L/d));return M}getSpacedPoints(u=5){let d=Math.max(1,Math.min(1024,Math.floor(Pe(u,5)))),M=[];for(let L=0;L<=d;L++)M.push(this.getPointAt(L/d));return M}getLength(){let u=this.getLengths();return u[u.length-1]||0}getLengths(u=this.arcLengthDivisions){let d=Math.max(1,Math.min(2048,Math.floor(Pe(u,200))));if(this._lenCache&&this._lenCache.length===d+1)return this._lenCache;let M=[0],L=0,I=this.getPoint(0);for(let B=1;B<=d;B++){let U=this.getPoint(B/d);L+=Math.hypot(Pe(U.x)-Pe(I.x),Pe(U.y)-Pe(I.y),Pe(U.z)-Pe(I.z)),M.push(L),I=U}return d===this.arcLengthDivisions&&(this._lenCache=M),M}updateArcLengths(){this._lenCache=null,this.getLengths()}getUtoTMapping(u,d){let M=this.getLengths(),L=M.length,I=M[L-1]||0;if(I<=0||L<2)return ot(u);let B=d!==void 0&&Number.isFinite(Number(d))?Math.max(0,Math.min(I,Number(d))):ot(u)*I,U=0,j=L-1;for(;U<=j;){let oe=U+j>>1,fe=M[oe]-B;if(fe<0)U=oe+1;else if(fe>0)j=oe-1;else return oe/(L-1)}let K=Math.max(0,U-1),ue=M[K],le=(M[K+1]??I)-ue;return(K+(le>1e-12?(B-ue)/le:0))/(L-1)}getTangent(u,d){let M=ot(u),L=this.getPoint(Math.max(0,M-1e-4)),I=this.getPoint(Math.min(1,M+1e-4)),B=Pe(I.x)-Pe(L.x),U=Pe(I.y)-Pe(L.y);if("z"in L||d?.isVector3){let K=Pe(I.z)-Pe(L.z),ue=Math.hypot(B,U,K)||1;return(d||new r).set(B/ue,U/ue,K/ue)}let j=Math.hypot(B,U)||1;return(d||new Qe).set(B/j,U/j)}getTangentAt(u,d){return this.getTangent(this.getUtoTMapping(u),d)}clone(){return new this.constructor().copy(this)}copy(u){if(!u||typeof u!="object")return this;let d=u,M=this;for(let L of Object.keys(d)){if(L==="type"||L.startsWith("is"))continue;if(L.startsWith("_")){M[L]=null;continue}let I=d[L];Array.isArray(I)?M[L]=I.map(B=>B?.clone?B.clone():B&&typeof B=="object"&&"x"in B?wt(B):B):I?.clone?M[L]=I.clone():I&&typeof I=="object"&&"x"in I?M[L]=wt(I):M[L]=I}return this}}class Pt extends St{constructor(u,d){super("LineCurve"),this.isLineCurve=!0,this.v1=wt(u),this.v2=wt(d)}getPoint(u,d=new Qe){let M=Pe(u,0),L=Pe(this.v1.x),I=Pe(this.v1.y);return M===1?d.set(Pe(this.v2.x),Pe(this.v2.y)):d.set(L+(Pe(this.v2.x)-L)*M,I+(Pe(this.v2.y)-I)*M)}getPointAt(u,d=new Qe){return this.getPoint(ot(u),d)}}class Lt extends St{constructor(u,d,M){super("QuadraticBezierCurve"),this.isQuadraticBezierCurve=!0,this.v0=wt(u),this.v1=wt(d),this.v2=wt(M)}getPoint(u,d=new Qe){let M=ot(u),L=1-M;return d.set(L*L*Pe(this.v0.x)+2*L*M*Pe(this.v1.x)+M*M*Pe(this.v2.x),L*L*Pe(this.v0.y)+2*L*M*Pe(this.v1.y)+M*M*Pe(this.v2.y))}}class Zt extends St{constructor(u,d,M,L){super("CubicBezierCurve"),this.isCubicBezierCurve=!0,this.v0=wt(u),this.v1=wt(d),this.v2=wt(M),this.v3=wt(L)}getPoint(u,d=new Qe){let M=ot(u),L=1-M,I=L*L,B=M*M;return d.set(I*L*Pe(this.v0.x)+3*I*M*Pe(this.v1.x)+3*L*B*Pe(this.v2.x)+B*M*Pe(this.v3.x),I*L*Pe(this.v0.y)+3*I*M*Pe(this.v1.y)+3*L*B*Pe(this.v2.y)+B*M*Pe(this.v3.y))}}class Ot extends St{constructor(u=[]){super("SplineCurve"),this.isSplineCurve=!0,this.points=Array.isArray(u)?u:[]}getPoint(u,d=new Qe){let M=this.points,L=Array.isArray(M)?M.length:0;if(L===0)return d.set(0,0);if(L===1)return d.set(Pe(M[0]?.x),Pe(M[0]?.y));let I=(L-1)*ot(u),B=Math.floor(I),U=I-B;B>=L-1&&(B=L-2,U=1);let j=M[B===0?0:B-1],K=M[B],ue=M[B+1],le=M[B>L-3?L-1:B+2],oe=U*U,fe=oe*U,ye=(ve,we,Te,Me)=>.5*(2*we+(Te-ve)*U+(2*ve-5*we+4*Te-Me)*oe+(3*we-ve-3*Te+Me)*fe);return d.set(ye(Pe(j?.x),Pe(K?.x),Pe(ue?.x),Pe(le?.x)),ye(Pe(j?.y),Pe(K?.y),Pe(ue?.y),Pe(le?.y)))}}class Jt extends St{constructor(u=0,d=0,M=1,L=1,I=0,B=Math.PI*2,U=!1,j=0){super("EllipseCurve"),this.isEllipseCurve=!0,this.aX=Pe(u,0),this.aY=Pe(d,0),this.xRadius=Pe(M,1),this.yRadius=Pe(L,1),this.aStartAngle=Pe(I,0),this.aEndAngle=Pe(B,Math.PI*2),this.aClockwise=!!U,this.aRotation=Pe(j,0)}getPoint(u,d=new Qe){let M=Math.PI*2,L=Pe(this.aStartAngle,0),I=Pe(this.aEndAngle,M)-L;Math.abs(I)>=1e-9?(I=(I%M+M)%M,I<1e-9&&(I=M),this.aClockwise&&(I=I===M?-M:I-M)):I=0;let B=L+ot(u)*I,U=Pe(this.xRadius,1)*Math.cos(B),j=Pe(this.yRadius,1)*Math.sin(B),K=Pe(this.aRotation,0),ue=Math.cos(K),le=Math.sin(K);return d.set(this.aX+U*ue-j*le,this.aY+U*le+j*ue)}}class er extends Jt{constructor(u=0,d=0,M=1,L=0,I=Math.PI*2,B=!1){super(u,d,M,M,L,I,B,0),this.type="ArcCurve",this.isArcCurve=!0}}class tr extends St{constructor(){super("CurvePath"),this.isCurvePath=!0,this.curves=[],this.autoClose=!1,this._curveLens=null}add(u){return u&&typeof u.getPoint=="function"&&(this.curves.push(u),this._curveLens=null,this._lenCache=null),this}closePath(){if(this.curves.length===0)return this;let u=this.curves[0].getPoint(0),d=this.curves[this.curves.length-1].getPoint(1),M=!!(u&&("z"in u||u.isVector3));if(Math.hypot(Pe(u?.x)-Pe(d?.x),Pe(u?.y)-Pe(d?.y),M?Pe(u?.z)-Pe(d?.z):0)>1e-6){let L=e.LineCurve3;this.add(M&&L?new L(d,u):new Pt(d,u))}return this}getCurveLengths(){if(this._curveLens&&this._curveLens.length===this.curves.length)return this._curveLens;let u=[],d=0;for(let M of this.curves){let L=0;if(typeof M?.getLength=="function")L=Pe(M.getLength(),0);else if(typeof M?.getPoints=="function"){let I=M.getPoints(32);for(let B=1;B<I.length;B++)L+=Math.hypot(Pe(I[B]?.x)-Pe(I[B-1]?.x),Pe(I[B]?.y)-Pe(I[B-1]?.y),Pe(I[B]?.z)-Pe(I[B-1]?.z))}d+=L,u.push(d)}return this._curveLens=u,u}getLength(){let u=this.getCurveLengths();return u[u.length-1]||0}updateArcLengths(){this._curveLens=null,this._lenCache=null;for(let u of this.curves)u?.updateArcLengths?.();this.getCurveLengths()}getPoint(u,d){if(this.curves.length===0)return(d||new Qe).set(0,0);let M=this.getCurveLengths(),L=M[M.length-1]||0;if(L<=1e-12)return this.curves[0].getPoint(0,d);let I=ot(u)*L;for(let B=0;B<M.length;B++)if(I<=M[B]||B===M.length-1){let U=B>0?M[B-1]:0,j=M[B]-U,K=j>1e-12?(I-U)/j:0,ue=this.curves[B];return typeof ue.getPointAt=="function"?ue.getPointAt(K,d):ue.getPoint(K,d)}return this.curves[this.curves.length-1].getPoint(1,d)}getPoints(u=12){let d=Math.max(1,Math.min(1024,Math.floor(Pe(u,12)))),M=[],L=null;for(let I of this.curves){let B=I?.isEllipseCurve?d*2:I?.isLineCurve||I instanceof(e.LineCurve3||Function)?1:I?.isSplineCurve&&Array.isArray(I.points)?d*Math.max(1,I.points.length):d;for(let U of I.getPoints(Math.min(1024,B)))L&&Math.hypot(Pe(L.x)-Pe(U.x),Pe(L.y)-Pe(U.y),Pe(L.z)-Pe(U.z))<1e-6||(M.push(U),L=U)}if(this.autoClose&&M.length>1){let I=M[0];Math.hypot(Pe(L.x)-Pe(I.x),Pe(L.y)-Pe(I.y),Pe(L.z)-Pe(I.z))>1e-6&&M.push(I.clone?I.clone():I)}return M}getSpacedPoints(u=40){let d=Math.max(1,Math.min(1024,Math.floor(Pe(u,40)))),M=[];for(let L=0;L<=d;L++)M.push(this.getPoint(L/d));return this.autoClose&&M.length>0&&M.push(M[0].clone?M[0].clone():M[0]),M}}let Nr=e.BufferAttribute,on=e.Object3D,Tn=e.Line,rr=e.LineSegments,nr=e.LineBasicMaterial,$n=e.MeshBasicMaterial,wn=e.ConeGeometry,cn=e.Color,Cr=(T,u,d,M)=>{T.name=u.name,T.position.copy(u.position),T.quaternion.copy(u.quaternion),T.scale.copy(u.scale),T.visible=u.visible,T.castShadow=u.castShadow,T.receiveShadow=u.receiveShadow;try{T.userData=JSON.parse(JSON.stringify(u.userData||{}))}catch{T.userData={...u.userData||{}}}if(M&&Array.isArray(u.children))for(let L=d;L<u.children.length;L++)T.add(u.children[L].clone(!0));return T},Kt=T=>{let u=new n;return u.setAttribute("position",new Nr(new Float32Array(T),3)),u.__isSegmentPairs=!0,u},ul=[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,3,7,2,6],ts=(T,u,d,M,L,I)=>{if(!Number.isFinite(T+u+d+M+L+I)||M<T||L<u||I<d)return new n;let B=[];for(let U of ul)B.push(U&1?M:T,U&2?L:u,U&4?I:d);return Kt(B)};class In extends rr{constructor(u=10,d=10,M=4473924,L=8947848){let I=Math.max(1e-4,Math.abs(Pe(u,10))),B=Math.max(1,Math.min(256,Math.floor(Pe(d,10)))),U=new cn(M??4473924),j=new cn(L??8947848),K=I*.5,ue=I/B,le=B%2===0&&U.getHex()!==j.getHex()?B>>1:-1,oe=[],fe=[];for(let ye=0,ve=-K;ye<=B;ye++,ve+=ue)(ye===le?fe:oe).push(-K,0,ve,K,0,ve,ve,0,-K,ve,0,K);if(super(Kt(oe.length?oe:fe),new nr({color:oe.length?j:U})),this.type="GridHelper",this.isGridHelper=!0,this._size=I,this._divisions=B,this._internalKids=0,fe.length&&oe.length){let ye=new rr(Kt(fe),new nr({color:U}));this._centerLines=ye,this._internalKids=1,this.add(ye)}}_bakeAuthorGeometry(){this._centerLines?.material&&this.material&&(this._centerLines.material.transparent=this.material.transparent,this._centerLines.material.opacity=this.material.opacity),super._bakeAuthorGeometry()}clone(u=!0){let d=new In(this._size,this._divisions,this._centerLines?this._centerLines.material.color:this.material.color,this.material.color);return d.material.transparent=this.material.transparent,d.material.opacity=this.material.opacity,Cr(d,this,this._internalKids,u)}dispose(){}}class pn extends rr{constructor(u=1){let d=Math.max(1e-4,Math.abs(Pe(u,1)));super(Kt([0,0,0,d,0,0]),new nr({color:16724736})),this.type="AxesHelper",this.isAxesHelper=!0,this._size=d,this._yAxis=new rr(Kt([0,0,0,0,d,0]),new nr({color:3407616})),this._zAxis=new rr(Kt([0,0,0,0,0,d]),new nr({color:35071})),this.add(this._yAxis),this.add(this._zAxis)}setColors(u,d,M){return this.material.color.set(u),this._yAxis.material.color.set(d),this._zAxis.material.color.set(M),this}_bakeAuthorGeometry(){for(let u of[this._yAxis,this._zAxis])u?.material&&this.material&&(u.material.transparent=this.material.transparent,u.material.opacity=this.material.opacity);super._bakeAuthorGeometry()}clone(u=!0){let d=new pn(this._size).setColors(this.material.color,this._yAxis.material.color,this._zAxis.material.color);return d.material.transparent=this.material.transparent,d.material.opacity=this.material.opacity,Cr(d,this,2,u)}dispose(){}}class dn extends on{constructor(u=new r(0,0,1),d=new r(0,0,0),M=1,L=16776960,I,B){super(),this.type="ArrowHelper",this.isArrowHelper=!0,this.position.set(Pe(d?.x),Pe(d?.y),Pe(d?.z));let U=new n;U.setAttribute("position",new Nr(new Float32Array([0,0,0,0,1,0]),3)),this.line=new Tn(U,new nr({color:L})),this.cone=new Dt(new wn(.5,1,8).translate(0,-.5,0),new $n({color:L})),this.add(this.line),this.add(this.cone),this.setDirection(u).setLength(M,I,B)}setDirection(u){let d=Pe(u?.x,0),M=Pe(u?.y,0),L=Pe(u?.z,1),I=Math.hypot(d,M,L),B=I>1e-9?d/I:0,U=I>1e-9?M/I:1,j=I>1e-9?L/I:0;return U>.99999?this.quaternion.set(0,0,0,1):U<-.99999?this.quaternion.set(1,0,0,0):this.quaternion.setFromAxisAngle(new r(j,0,-B).normalize(),Math.acos(Math.max(-1,Math.min(1,U)))),this}setLength(u,d,M){let L=Math.max(1e-4,Math.abs(Pe(u,1))),I=d!==void 0&&Number.isFinite(Number(d))?Math.max(1e-4,Math.abs(Number(d))):.2*L,B=M!==void 0&&Number.isFinite(Number(M))?Math.max(1e-4,Math.abs(Number(M))):.2*I;return this.line.scale.set(1,Math.max(1e-4,L-I),1),this.line.updateMatrix?.(),this.cone.scale.set(B,I,B),this.cone.position.set(0,L,0),this.cone.updateMatrix?.(),this}setColor(u){return this.line.material.color.set(u),this.cone.material.color.set(u),this}clone(u=!0){let d=new dn;return d.line.scale.copy(this.line.scale),d.cone.scale.copy(this.cone.scale),d.cone.position.copy(this.cone.position),d.setColor(this.cone.material.color),d.line.material.transparent=this.line.material.transparent,d.line.material.opacity=this.line.material.opacity,d.cone.material.transparent=this.cone.material.transparent,d.cone.material.opacity=this.cone.material.opacity,Cr(d,this,2,u)}dispose(){}}class gn extends rr{constructor(u=new a,d=16776960){let M=u instanceof a?u:new a(u?.min,u?.max);super(M.isEmpty()?new n:ts(M.min.x,M.min.y,M.min.z,M.max.x,M.max.y,M.max.z),new nr({color:d})),this.type="Box3Helper",this.isBox3Helper=!0,this.box=M}_bakeAuthorGeometry(){let u=this.box,d=!u||u.isEmpty()?new n:ts(u.min.x,u.min.y,u.min.z,u.max.x,u.max.y,u.max.z);this._sourceGeo=d,this.geometry=d,super._bakeAuthorGeometry()}clone(u=!0){let d=new gn(this.box.clone(),this.material.color);return d.material.transparent=this.material.transparent,d.material.opacity=this.material.opacity,Cr(d,this,0,u)}dispose(){}}class Pn extends rr{constructor(u,d=16776960){super(new n,new nr({color:d})),this.type="BoxHelper",this.isBoxHelper=!0,this.object=u,u&&this.update()}update(u){u!==void 0&&(this.object=u);let d=new a;this.object&&this.object!==this&&d.setFromObject(this.object);let M=d.isEmpty()?new n:ts(d.min.x,d.min.y,d.min.z,d.max.x,d.max.y,d.max.z);return this.position.set(0,0,0),this.quaternion.set(0,0,0,1),this.scale.set(1,1,1),this._sourceGeo=M,this.geometry=M,this}setFromObject(u){return this.update(u)}_bakeAuthorGeometry(){this.update(),super._bakeAuthorGeometry()}clone(u=!0){let d=new Pn(this.object,this.material.color);return d.material.transparent=this.material.transparent,d.material.opacity=this.material.opacity,Cr(d,this,0,u)}dispose(){}}for(let T of[St,Pt,Lt,Zt,Ot,Jt,er,tr,In,pn,dn,gn,Pn])Object.freeze(T.prototype);let Ir=["checkerboard","grid","wood","marble","brushedMetal","carbonFiber","concrete","brick","fabric","leather","rust"],rs=[[8,3359061,14870768,.6],[8,16317180,6583435,.7],[10,9132587,0,.6],[3,15857145,4674921,.25],[1,12106946,0,.32],[8,2040616,0,.35],[4,10265519,0,.9],[8,10107694,13157048,.85],[32,3890060,0,.9],[12,5913128,0,.6],[4,9124378,9080985,.9]],Bo=(T,u,d)=>{let M=Math.imul(T,668265261)^Math.imul(u,374761393)^Math.imul(d,2654435769);return M^=M>>>15,M=Math.imul(M,2246822507),M^=M>>>13,M=Math.imul(M,3266489909),M^=M>>>16,M>>>0},hn=(T,u,d)=>Bo(T,u,d)/4294967296,Yr=(T,u)=>(T%u+u)%u,Sc=(T,u,d,M,L)=>{let I=Math.floor(T),B=Math.floor(u),U=T-I,j=u-B,K=Yr(I,d),ue=Yr(B,M),le=(K+1)%d,oe=(ue+1)%M,fe=U*U*(3-2*U),ye=j*j*(3-2*j),ve=hn(K,ue,L),we=hn(le,ue,L),Te=hn(K,oe,L),Me=hn(le,oe,L);return ve+(we-ve)*fe+(Te-ve)*ye+(ve-we-Te+Me)*fe*ye},yn=(T,u,d,M,L,I)=>{let B=0,U=.5,j=0,K=1;for(let ue=0;ue<L;ue++){let le=d*K,oe=M*K;B+=U*Sc(T*le,u*oe,le,oe,I+ue>>>0),j+=U,U*=.5,K*=2}return B/j},dl=T=>T-Math.floor(T),uu=T=>Math.abs(dl(T)*2-1),ns=(T,u,d)=>{let M=(d-T)/(u-T);return M<0?M=0:M>1&&(M=1),M*M*(3-2*M)},fn=(T,u,d)=>T+(u-T)*d,bn=T=>T<=0?0:T>=1?255:Math.floor(T*255+.5),qh=(T,u,d,M,L,I,B,U,j,K,ue)=>{let le=Me=>[L[0]*Me,L[1]*Me,L[2]*Me],oe=(Me,be,Ce)=>[fn(Me[0],be[0],Ce),fn(Me[1],be[1],Ce),fn(Me[2],be[2],Ce)];if(T===0){let Me=Yr(Math.floor(U*d)+Math.floor(j*d),2)===1?I:L;return[Me[0],Me[1],Me[2],.5,B,0]}if(T===1){let Me=dl(U*d),be=dl(j*d),Ce=Math.max(.035,d/u),Ie=1-ns(Ce*.5,Ce,Math.min(Me,1-Me,be,1-be));return[...oe(L,I,Ie),.3+.4*Ie,B,0]}if(T===2){let Me=yn(U,j,4,4,4,M),be=uu(j*d+Me*1.5),Ce=yn(U,j,2,96,2,M+7>>>0),Ie=be*.7+Ce*.3;return[...le(fn(.55,1,Ie)),Ie,B+(1-Ie)*.15,0]}if(T===3){let Me=yn(U,j,3,3,5,M),be=uu((U+j)*d+Me*2.5),Ce=be*be,Ie=Ce*Ce,Ve=Ie*Ie,Oe=.92+.08*Me,qe=oe(L,I,Ve*.85);return[qe[0]*Oe,qe[1]*Oe,qe[2]*Oe,.5-Ve*.2,B+Ve*.1,0]}if(T===4){let Me=yn(U,j,2,192*d,2,M),be=hn(K,ue,M+3>>>0);return[...le(.85+.12*Me+.03*be),.35+Me*.3,B+(Me-.5)*.12,1]}if(T===5){let Me=d*2,be=U*Me,Ce=j*Me,Ie=be-Math.floor(be),Ve=Ce-Math.floor(Ce),Oe=Yr(Math.floor(be)+Math.floor(Ce),2)===0,qe=Oe?Ve*2-1:Ie*2-1,Ke=1-qe*qe,et=.08*uu(Oe?Ve*8:Ie*8),Ye=.6+.4*Ke;return[L[0]*Ye+et,L[1]*Ye+et,L[2]*Ye+et,Ke*.8,B+.1*(1-Ke),0]}if(T===6){let Me=yn(U,j,d,d,5,M),be=hn(K,ue,M+31>>>0),Ce=d*16,Ie=ns(.82,.9,Sc(U*Ce,j*Ce,Ce,Ce,M+17>>>0));return[...le((.82+.25*Me+.06*(be-.5))*(1-.35*Ie)),.5+.25*(Me-.5)-.3*Ie,B-.05*Me,0]}if(T===7){let Me=Math.floor(d/2),be=j*d,Ce=Math.floor(be),Ie=be-Ce,Ve=U*Me+(Yr(Ce,2)===1?.5:0),Oe=Math.floor(Ve),qe=Ve-Oe,Ke=Math.min(Math.min(qe,1-qe)*2,Math.min(Ie,1-Ie)),et=Math.max(.06,1.5*d/u),Ye=1-ns(et*.5,et,Ke),tt=hn(Yr(Oe,Me),Yr(Ce,d),M),je=yn(U,j,d,d,3,M+5>>>0),Xe=.8+.25*tt+.15*(je-.5),it=.9+.1*je;return[fn(L[0]*Xe,I[0]*it,Ye),fn(L[1]*Xe,I[1]*it,Ye),fn(L[2]*Xe,I[2]*it,Ye),(1-Ye)*(.75+.1*je)+Ye*.2,fn(B,.95,Ye),0]}if(T===8){let Me=U*d,be=j*d,Ce=(Me-Math.floor(Me))*2-1,Ie=(be-Math.floor(be))*2-1,Ve=Yr(Math.floor(Me)+Math.floor(be),2)===0?1-Ce*Ce:1-Ie*Ie,Oe=yn(U,j,4,4,2,M);return[...le((.75+.25*Ve)*(.95+.1*(Oe-.5))),Ve,B,0]}if(T===9){let Me=U*d,be=j*d,Ce=Math.floor(Me),Ie=Math.floor(be),Ve=1e9,Oe=1e9;for(let et=-1;et<=1;et++)for(let Ye=-1;Ye<=1;Ye++){let tt=Ce+Ye,je=Ie+et,Xe=Yr(tt,d),it=Yr(je,d),bt=tt+hn(Xe,it,M)-Me,pt=je+hn(Xe,it,M+1>>>0)-be,lt=bt*bt+pt*pt;lt<Ve?(Oe=Ve,Ve=lt):lt<Oe&&(Oe=lt)}let qe=1-ns(0,.12,Math.sqrt(Oe)-Math.sqrt(Ve)),Ke=yn(U,j,4,4,3,M+3>>>0);return[...le((.85+.2*(Ke-.5))*(1-.3*qe)),.6-.4*qe+.1*(Ke-.5),B+.15*qe,0]}let fe=yn(U,j,d,d,5,M),ye=ns(.45,.6,fe),ve=yn(U,j,d*8,d*8,3,M+9>>>0),we=.9+.1*ve,Te=.7+.5*ve;return[fn(I[0]*we,L[0]*Te,ye),fn(I[1]*we,L[1]*Te,ye),fn(I[2]*we,L[2]*Te,ye),.4+.4*ye*ve+.1*ye,fn(.35,B,ye),1-ye]},Wh=(T,u,d,M,L,I,B,U)=>{let j=globalThis.__three_live_native_material_preset__;if(typeof j=="function"){let oe=j(T,u,d,M,...L,...I,B,U);if(Array.isArray(oe)&&oe.length===3)return oe}let K=new Uint8Array(u*u*4),ue=new Uint8Array(u*u*4),le=new Float64Array(u*u);for(let oe=0;oe<u;oe++){let fe=(oe+.5)/u;for(let ye=0;ye<u;ye++){let ve=qh(T,u,d,M,L,I,B,(ye+.5)/u,fe,ye,oe),we=(oe*u+ye)*4;K[we]=bn(ve[0]),K[we+1]=bn(ve[1]),K[we+2]=bn(ve[2]),K[we+3]=255,ue[we]=255,ue[we+1]=bn(ve[4]),ue[we+2]=bn(ve[5]),ue[we+3]=255,le[oe*u+ye]=ve[3]}}return[K,Ac(le,u,U),ue]},Ac=(T,u,d)=>{let M=new Uint8Array(u*u*4),L=d*u*.0625;for(let I=0;I<u;I++){let B=(I+u-1)%u,U=(I+1)%u;for(let j=0;j<u;j++){let K=-(T[I*u+(j+1)%u]-T[I*u+(j+u-1)%u])*L,ue=(T[U*u+j]-T[B*u+j])*L,le=1/Math.sqrt(K*K+ue*ue+1),oe=(I*u+j)*4;M[oe]=bn(K*le*.5+.5),M[oe+1]=bn(ue*le*.5+.5),M[oe+2]=bn(le*.5+.5),M[oe+3]=255}}return M},Tc=(T,u)=>{let d=u;try{T!=null&&(d=new cn(T).getHex())}catch{}return[(d>>16&255)/255,(d>>8&255)/255,(d&255)/255]},Vo=new Map,Zu=(T,u={})=>{let d=Ir.indexOf(T);if(d<0)throw new TypeError(`THREE.ProceduralTexture: unknown preset '${T}' (use ${Ir.join(", ")})`);let M=u&&typeof u=="object"?u:{},L=rs[d],I=Math.max(1,Math.min(256,Math.round(Pe(M.scale,L[0]))));(d===0||d===7||d===8)&&I%2===1&&I++;let B=Math.max(16,Math.min(512,Math.round(Pe(M.size,256)))),U=Math.round(Math.abs(Pe(M.seed,1)))>>>0,j=Tc(M.color,L[1]),K=Tc(M.color2,L[2]||L[1]),ue=ot(Pe(M.roughness,L[3])),le=Math.max(0,Math.min(8,Pe(M.normalStrength,1))),oe=[d,B,I,U,...j,...K,ue,le].join(","),fe=Vo.get(oe);if(fe)return{...fe};let[ye,ve,we]=Wh(d,B,I,U,j,K,ue,le),Te=(Ce,Ie)=>{let Ve=new _e(B,B);Ve._data.set(Ce),Ve._ver++;let Oe=new W(Ve);return Oe.flipY=!1,Oe.colorSpace=Ie,Oe.name=`${T}_${Ie==="srgb"?"albedo":Ce===ve?"normal":"orm"}`,Oe},Me=Te(we,"srgb-linear"),be={map:Te(ye,"srgb")};return le>0&&(be.normalMap=Te(ve,"srgb-linear")),be.roughnessMap=Me,be.metalnessMap=Me,Vo.size>=64&&Vo.clear(),Vo.set(oe,be),{...be}},Mc={presets:Object.freeze(Ir.slice()),create:(T,u)=>Zu(String(T),u)};for(let T of Ir)Mc[T]=u=>Zu(T,u);Object.freeze(Mc);let Xh=500,Yh=T=>{if(typeof T!="string")return null;let u="",d=!1;for(let M=0;M<T.length;M++){let L=T.charCodeAt(M);if(L<=32||L===127){d=u.length>0;continue}d&&(u+=" ",d=!1),u+=T[M]}return u.length===0||u.length>Xh?null:u},ed=T=>{let u=typeof T=="number"?T:NaN;return Number.isFinite(u)?u<=384?256:u<=768?512:1024:512},ch=T=>T>512&&T%2===0?T/2:T,td=(T,u)=>{let d=u/2,M=new Uint8Array(d*d*4);for(let L=0;L<d;L++)for(let I=0;I<d;I++){let B=(2*L*u+2*I)*4,U=B+u*4,j=(L*d+I)*4;for(let K=0;K<4;K++)M[j+K]=T[B+K]+T[B+4+K]+T[U+K]+T[U+4+K]+2>>2}return M},rd=T=>{let u=typeof T=="number"?T:NaN,d=Number.isFinite(u)?Math.abs(u):1;return Math.floor(d+.5)%4294967296},id=T=>{let u=[];for(let d=0;d<T.length;d++){let M=T.charCodeAt(d);if(M>=55296&&M<=56319&&d+1<T.length){let L=T.charCodeAt(d+1);L>=56320&&L<=57343?(M=65536+(M-55296<<10)+(L-56320),d++):M=65533}else M>=55296&&M<=57343&&(M=65533);M<128?u.push(M):M<2048?u.push(192|M>>6,128|M&63):M<65536?u.push(224|M>>12,128|M>>6&63,128|M&63):u.push(240|M>>18,128|M>>12&63,128|M>>6&63,128|M&63)}return u},nd=(T,u,d)=>{let M=id(`three-live-texture1${T}${u}${d}`),L=3421674724,I=2216829733;for(let B of M){I=(I^B)>>>0;let U=I&65535,j=I>>>16,K=U*435,ue=j*435+(K>>>16),le=(ue&65535)<<16|K&65535,oe=Math.floor(ue/65536);L=Math.imul(L,435)+oe+(I<<8>>>0)>>>0,I=le>>>0}return L.toString(16).padStart(8,"0")+I.toString(16).padStart(8,"0")},gh=T=>{let u=Yh(T?.prompt);if(u===null)return null;let d=ed(T?.size),M=rd(T?.seed);return{prompt:u,size:d,seed:M,key:nd(u,d,M)}},_c=(T,u,d,M,L)=>{if(ch(u)!==u)return _c(td(T,u),u/2,d,M,L);let I=new Float64Array(u*u);for(let be=0;be<u*u;be++){let Ce=be*4;I[be]=2126*T[Ce]+7152*T[Ce+1]+722*T[Ce+2]}let B=Math.min(4,Math.floor((u-1)/2)),U=new Float64Array(u*u);for(let be=0;be<u;be++)for(let Ce=0;Ce<u;Ce++){let Ie=0;for(let Ve=0;Ve<=2*B;Ve++)Ie+=I[be*u+(Ce+u+Ve-B)%u];U[be*u+Ce]=Ie}let j=(2*B+1)*(2*B+1),K=new Float64Array(u*u),ue=1/0,le=-1/0;for(let be=0;be<u;be++)for(let Ce=0;Ce<u;Ce++){let Ie=0;for(let Oe=0;Oe<=2*B;Oe++)Ie+=U[(be+u+Oe-B)%u*u+Ce];let Ve=j*I[be*u+Ce]-Ie;K[be*u+Ce]=Ve,Ve<ue&&(ue=Ve),Ve>le&&(le=Ve)}let oe=le-ue,fe=new Float64Array(u*u);for(let be=0;be<u*u;be++)fe[be]=oe===0?.5:(K[be]-ue)/oe;let ye=Number.isFinite(d)?Math.max(0,Math.min(8,d)):1,ve=Ac(fe,u,ye),we=Number.isFinite(M)?Math.max(0,Math.min(1,M)):0,Te=bn(Number.isFinite(L)?Math.max(0,Math.min(1,L)):0),Me=new Uint8Array(u*u*4);for(let be=0;be<u*u;be++){let Ce=be*4;Me[Ce]=255,Me[Ce+1]=bn(we+.35*(.5-fe[be])),Me[Ce+2]=Te,Me[Ce+3]=255}return[ve,Me]},Uo=new Map,yh=new WeakMap,ad=0,sd=(T,u)=>{let d=gh(T);if(!d)return null;let{prompt:M,size:L,seed:I,key:B}=d,U=ot(Pe(T.roughness,u>=0?rs[u][3]:.8)),j=ot(Pe(T.metalness,0)),K=Math.max(0,Math.min(8,Pe(T.normalStrength,1))),ue=globalThis,le=ue.__three_live_native_texture_pack__,oe=ue.__three_live_texture_pack__,fe=0;if(typeof le=="function"){let Ie=ue.__three_live_native_texture_pack_token__;fe=typeof Ie=="function"&&Number(Ie())||0}else oe&&typeof oe=="object"&&(fe=yh.get(oe)??0,fe||yh.set(oe,fe=++ad));let ye=[fe,B,K,U,j].join(","),ve=fe?Uo.get(ye):void 0;if(ve)return{...ve};let we=null;if(typeof le=="function"){let Ie=le(M,L,I,K,U,j);Array.isArray(Ie)&&Ie.length===3&&(we=Ie)}else{let Ie=oe&&typeof oe=="object"&&Object.prototype.hasOwnProperty.call(oe,B)?oe[B]:null;Ie&&Ie.size===L&&Ie.rgba instanceof Uint8Array&&Ie.rgba.length===L*L*4&&(we=[Ie.rgba,..._c(Ie.rgba,L,K,U,j)])}if(!we)return null;let Te=(Ie,Ve,Oe,qe)=>{let Ke=new W({data:new Uint8ClampedArray(Ie.buffer,Ie.byteOffset,Ve*Ve*4),width:Ve,height:Ve});return Ke.flipY=!1,Ke.colorSpace=Oe,Ke.name=`ai_${B}_${qe}`,Ke._pngDim=Ve,Ke},Me=ch(L),be=Te(we[2],Me,"srgb-linear","orm"),Ce={map:Te(we[0],L,"srgb","albedo")};return K>0&&(Ce.normalMap=Te(we[1],Me,"srgb-linear","normal")),Ce.roughnessMap=be,Ce.metalnessMap=be,fe&&(Uo.size>=32&&Uo.clear(),Uo.set(ye,Ce)),{...Ce}},xh=new Set,od=T=>{let u=T?.userData?.xr?.material,d=T?.material;if(u==null||!d||typeof d!="object"||Array.isArray(d))return;let M=typeof u=="string"?{preset:u}:typeof u=="object"?u:null,L=String(M?.preset??M?.type??""),I=Ir.indexOf(L),B=!!M&&M.prompt!==void 0&&M.prompt!==null,U=B?sd(M,I):null;if(!M||I<0&&!U){!(B&&L==="")&&!xh.has(L)&&(xh.add(L),console.warn(`[three-live] userData.xr.material: unknown preset '${L}' (use ${Ir.join(", ")}).`));return}d._presetTint===void 0&&(d._presetTint=d.color?.getHex?.()??16777215);let j="";try{j=JSON.stringify([M,d._presetTint])}catch{j=L}if(d._presetKey===j)return;if(d._presetOwner&&d._presetOwner!==T){let le=Object.assign(Object.create(Object.getPrototypeOf(d)),d);le.color=new cn(d._presetTint);for(let oe of["_presetKey","_presetMaps","_presetOwner"])le[oe]=void 0;for(let oe of["map","normalMap","roughnessMap","metalnessMap"])d._presetMaps?.[oe]&&le[oe]===d._presetMaps[oe]&&(le[oe]=null);T.material=d=le}let K=U??Zu(L,{...M,color:M.color??(d._presetTint===16777215?void 0:d._presetTint)}),ue=d._presetMaps||{};for(let le of["map","normalMap","roughnessMap","metalnessMap"])(!d[le]||d[le]===ue[le])&&(d[le]=K[le]??null,ue[le]=K[le]??null);ue.map===d.map&&d.color?.set?.(16777215),ue.roughnessMap===d.roughnessMap&&(d.roughness=1),ue.metalnessMap===d.metalnessMap&&(d.metalness=1),d._presetMaps=ue,d._presetKey=j,d._presetOwner=T},vh={Box3:a,Sphere:o,CanvasTexture:W,ImprovedNoise:pe,SimplexNoise:Ge,SpriteMaterial:Mt,Sprite:jt,LineCurve:Pt,QuadraticBezierCurve:Lt,CubicBezierCurve:Zt,SplineCurve:Ot,EllipseCurve:Jt,ArcCurve:er,CurvePath:tr,GridHelper:In,AxesHelper:pn,ArrowHelper:dn,Box3Helper:gn,BoxHelper:Pn,ProceduralTexture:Mc};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,vh),t.createCanvas=D,t._procMaterialize=od,t.canonicalTextureSpec=gh,t.deriveTextureMaps=_c,t.encodeRgbaPngDataUri=(T,u,d)=>_(T,u,d,!1,!1,f).uri,t.materializeDeclarativeGeometry=T=>{t._cadMaterialize?.(T),t._lodMaterialize?.(T),t._procMaterialize?.(T)}),vh}var Oc={name:"procedural",onRegister(){jn(ms);let e=He(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t&&ms(t,e)}};function zc(e){if(typeof e!="function")return null;let t=new Uint32Array(256);for(let h=0;h<256;h++){let p=h;for(let g=0;g<8;g++)p=p&1?3988292384^p>>>1:p>>>1;t[h]=p>>>0}let r=(h,p,g)=>{let x=4294967295;for(let v=p;v<g;v++)x=t[(x^h[v])&255]^x>>>8;return(x^4294967295)>>>0},i=(h,p)=>(h[p]<<24|h[p+1]<<16|h[p+2]<<8|h[p+3])>>>0,n=(h,p,g)=>{h[p]=g>>>24,h[p+1]=g>>>16&255,h[p+2]=g>>>8&255,h[p+3]=g&255},a=h=>{let p=new e("deflate"),g=p.writable.getWriter();g.write(h).catch(()=>{}),g.close().catch(()=>{});let x=p.readable.getReader(),v=[],y=0,A=()=>x.read().then(b=>{if(b.done){let w=new Uint8Array(y),S=0;for(let E=0;E<v.length;E++)w.set(v[E],S),S+=v[E].length;return w}return b.value&&(v.push(b.value),y+=b.value.length),A()});return A()},s=h=>{if(h.length<45||i(h,0)!==2303741511||i(h,12)!==1229472850)return null;let p=i(h,16),g=i(h,20);if(h[24]!==8||h[25]!==6||h[28]!==0||!p||!g||p>4096||g>4096)return null;let x=1+p*4,v=new Uint8Array(x*g),y=0,A=33,b=-2,w=0,S=[],E=!1;for(;A+8<=h.length&&!E;){let N=i(h,A),C=i(h,A+4),_=A+8,P=_+N;if(P+4>h.length)return null;if(C===1229209940)for(let R=_;R<P&&!E;){if(b<0)b++,R++;else if(w>0){let $=Math.min(w,P-R);if(y+$>v.length)return null;v.set(h.subarray(R,R+$),y),y+=$,R+=$,w-=$,w===0&&S[0]&1&&(E=!0)}else{if(S.push(h[R++]),S.length===1&&S[0]>>1&3)return null;if(S.length===5){let $=S[1]|S[2]<<8;if(($^(S[3]|S[4]<<8))!==65535)return null;w=$,$===0&&(S[0]&1&&(E=!0),S=[])}}w===0&&S.length===5&&(S=[])}else if(C===1229278788)break;A=P+4}if(y!==v.length)return null;for(let N=0;N<g;N++)if(v[N*x]!==0)return null;return{w:p,h:g,raw:v}},o=(h,p,g)=>{let x=p*4,v=x+1,y=new Uint8Array(h.length),A=new Uint8Array(x),b=new Uint8Array(x);for(let w=0;w<g;w++){let S=w*v+1,E=S-v,N=0,C=1/0;for(let _=0;_<5;_++){if(_===3||(_===2||_===4)&&w===0)continue;let P=0;for(let R=0;R<x;R++){let $=R>=4?h[S+R-4]:0,F=w>0?h[E+R]:0,V=0;if(_===1)V=$;else if(_===2)V=F;else if(_===4){let J=R>=4&&w>0?h[E+R-4]:0,re=$+F-J,Q=Math.abs(re-$),ee=Math.abs(re-F),k=Math.abs(re-J);V=Q<=ee&&Q<=k?$:ee<=k?F:J}let Y=h[S+R]-V&255;A[R]=Y,P+=Y<128?Y:256-Y}P<C&&(C=P,N=_,b.set(A))}y[w*v]=N,y.set(b,S)}return y},l=h=>{let p=null;try{p=s(h)}catch{p=null}if(!p)return Promise.resolve(h);let{w:g,h:x,raw:v}=p;return a(o(v,g,x)).then(y=>{let A=45+y.length+12;if(A>=h.length)return h;let b=new Uint8Array(A);b.set(h.subarray(0,33),0),n(b,33,y.length),n(b,37,1229209940),b.set(y,41),n(b,41+y.length,r(b,37,41+y.length));let w=45+y.length;return n(b,w,0),n(b,w+4,1229278788),n(b,w+8,2923585666),b},()=>h)},c=new Int16Array(128).fill(-1),f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(let h=0;h<64;h++)c[f.charCodeAt(h)]=h;let m=h=>{let p=h.length;for(;p>0&&h.charCodeAt(p-1)===61;)p--;let g=new Uint8Array(Math.floor(p*3/4)),x=0,v=0,y=0;for(let A=0;A<p;A++){let b=h.charCodeAt(A),w=b<128?c[b]:-1;if(w<0)return null;x=(x<<6|w)&16777215,v+=6,v>=8&&(v-=8,g[y++]=x>>v&255)}return y===g.length?g:null};return{png:l,glb:h=>{let p=(R,$)=>(R[$]|R[$+1]<<8|R[$+2]<<16|R[$+3]<<24)>>>0,g=(R,$,F)=>{R[$]=F&255,R[$+1]=F>>>8&255,R[$+2]=F>>>16&255,R[$+3]=F>>>24},x,v=new Uint8Array(0);try{if(h.length<20||p(h,0)!==1179937895)return Promise.resolve(h);let R=Math.min(h.length,p(h,8)),$=p(h,12);if(p(h,16)!==1313821514||20+$>R)return Promise.resolve(h);x=JSON.parse(new TextDecoder().decode(h.subarray(20,20+$)));let F=20+$;if(F+8<=R){let V=p(h,F);if(p(h,F+4)!==5130562||F+8+V>R)return Promise.resolve(h);v=h.subarray(F+8,F+8+V)}}catch{return Promise.resolve(h)}if(!x||typeof x!="object")return Promise.resolve(h);let y=Array.isArray(x.bufferViews)?x.bufferViews:[],A=Array.isArray(x.images)?x.images:[],b=[],w=[],S=[],E="data:image/png;base64,";for(let R=0;R<A.length;R++){let $=A[R];if(!$||typeof $!="object")continue;let F=y[$.bufferView];if(typeof $.uri=="string"&&$.uri.indexOf(E)===0){let V=m($.uri.slice(E.length));V&&(w.push(R),S.push(V))}else $.mimeType==="image/png"&&F&&(F.buffer||0)===0&&b.indexOf($.bufferView)<0&&b.push($.bufferView)}if(!b.length&&!w.length)return Promise.resolve(h);let N=[];for(let R=0;R<y.length;R++)N.push(R);N.sort((R,$)=>(y[R].byteOffset||0)-(y[$].byteOffset||0));let C=0;for(let R=0;R<N.length;R++){let $=y[N[R]],F=$.byteOffset||0;if(typeof $.byteLength!="number"||($.buffer||0)!==0||F<C||F+$.byteLength>v.length)return Promise.resolve(h);C=F+$.byteLength}let _=R=>{let $=y[R].byteOffset||0;return v.subarray($,$+y[R].byteLength)},P=[];for(let R=0;R<b.length;R++)P.push(l(_(b[R])));for(let R=0;R<S.length;R++)P.push(l(S[R]));return Promise.all(P).then(R=>{let $=[];for(let k=0;k<y.length;k++){let G=b.indexOf(k);$.push(G>=0?R[G]:_(k))}let F=0;for(let k=0;k<N.length;k++)F=(F+3&-4)+$[N[k]].length;for(let k=0;k<w.length;k++)F=(F+3&-4)+R[b.length+k].length;let V=F+3&-4,Y=new Uint8Array(V),J=0;for(let k=0;k<N.length;k++){let G=N[k];J=J+3&-4,Y.set($[G],J),y[G].byteOffset=J,y[G].byteLength=$[G].length,J+=$[G].length}for(let k=0;k<w.length;k++){let G=R[b.length+k];J=J+3&-4,Y.set(G,J);let q=A[w[k]];delete q.uri,q.mimeType="image/png",q.bufferView=y.length,y.push({buffer:0,byteOffset:J,byteLength:G.length}),J+=G.length}x.bufferViews=y,!Array.isArray(x.buffers)||!x.buffers.length?x.buffers=[{byteLength:V}]:x.buffers[0].byteLength=V;let re=new TextEncoder().encode(JSON.stringify(x)),Q=re.length+3&-4;if(Q!==re.length){let k=new Uint8Array(Q).fill(32);k.set(re),re=k}let ee=new Uint8Array(20+Q+8+V);return g(ee,0,1179937895),g(ee,4,2),g(ee,8,ee.length),g(ee,12,Q),g(ee,16,1313821514),ee.set(re,20),g(ee,20+Q,V),g(ee,24+Q,5130562),ee.set(Y,28+Q),ee.length<h.length?ee:h})}}}var mp={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function Hn(e,t,r,i){if(!r||r.bufferView===void 0)return null;let n=e.bufferViews?.[r.bufferView];if(!n)return null;let a=Number(r.count??0);if(!Number.isInteger(a)||a<=0)return null;let s=r.componentType??5126,o=mp[s];if(!o)throw new RangeError(`glTF accessor has unsupported componentType ${s}`);let l=o*i,c=n.byteStride&&n.byteStride>0?n.byteStride:l,f=(n.byteOffset||0)+(r.byteOffset||0);if(!Number.isInteger(f)||f<0||c<l||f+(a-1)*c+l>t.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${t.byteLength} bytes)`);if(s===5126&&c===l&&f%4===0)return new Float32Array(t,f,a*i);let m=new DataView(t),h=r.normalized===!0,p=new Float32Array(a*i);for(let g=0;g<a;g++){let x=f+g*c;for(let v=0;v<i;v++){let y=x+v*o,A;switch(s){case 5126:A=m.getFloat32(y,!0);break;case 5120:A=m.getInt8(y),h&&(A=Math.max(A/127,-1));break;case 5121:A=m.getUint8(y),h&&(A/=255);break;case 5122:A=m.getInt16(y,!0),h&&(A=Math.max(A/32767,-1));break;case 5123:A=m.getUint16(y,!0),h&&(A/=65535);break;default:A=m.getUint32(y,!0),h&&(A/=4294967295)}p[g*i+v]=A}}return p}function Ed(e,t){let r=Number(t.offset?.[0]??0)||0,i=Number(t.offset?.[1]??0)||0,n=Number(t.scale?.[0]??1),a=Number(t.scale?.[1]??1),s=Number(t.rotation??0)||0,o=Math.cos(s),l=Math.sin(s),c=(Number.isFinite(n)?n:1)*o,f=(Number.isFinite(n)?n:1)*l,m=-(Number.isFinite(a)?a:1)*l,h=(Number.isFinite(a)?a:1)*o;for(let p=0;p+1<e.length;p+=2){let g=e[p],x=e[p+1];e[p]=c*g+f*x+r,e[p+1]=m*g+h*x+i}}function ir(e,t,r,i=!0){let n=[],a=null;try{for(let[s,o]of[[35633,t],[35632,r]]){let l=e.createShader(s);if(!l){if(i)throw new Error("Shader allocation failed");return null}if(n.push(l),e.shaderSource(l,o),e.compileShader(l),e.getShaderParameter&&!e.getShaderParameter(l,35713)){if(i)throw new Error(`Shader compile error: ${e.getShaderInfoLog(l)}`);return null}}if(a=e.createProgram(),!a){if(i)throw new Error("Program allocation failed");return null}for(let s of n)e.attachShader(a,s);if(e.linkProgram(a),e.getProgramParameter&&!e.getProgramParameter(a,35714)){let s=i?e.getProgramInfoLog(a):null;if(e.deleteProgram?.(a),a=null,i)throw new Error(`Program link error: ${s}`);return null}return a}finally{for(let s of n)a&&e.detachShader?.(a,s),e.deleteShader?.(s)}}var Rd=["neutral","reinhard","none","aces","agx"];function Dr(e){let t=String(e??"").trim().toLowerCase();return Rd.includes(t)?t:"neutral"}function hp(e){return Rd.indexOf(Dr(e))}function pp(e){return new TextDecoder().decode(e)}var Ld=He().decoders;function bp(e,t){Ld.set(e.toLowerCase(),t)}function ys(e){return Ld.get(e.toLowerCase())}function Pd(e){let t=ArrayBuffer.isView(e)?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):e,r=new DataView(t);if(t.byteLength<12)throw new Error(`Invalid GLB buffer size: ${t.byteLength} bytes`);let i=r.getUint32(0,!0);if(i!==1179937895){let h=r.getUint8(0);throw h===123||h===32||h===10||h===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${i.toString(16)}`)}let n=r.getUint32(4,!0);if(n!==2)throw new Error(`Unsupported GLB version: ${n}`);let a=r.getUint32(8,!0),s=12,o=null,l=null;for(;s+8<=a&&s+8<=t.byteLength;){let h=r.getUint32(s,!0),p=r.getUint32(s+4,!0),g=s+8;if(g+h>t.byteLength)throw new Error(`Truncated GLB chunk: required ${g+h} bytes, buffer has ${t.byteLength}`);if(p===1313821514){let x=new Uint8Array(t,g,h),v=pp(x);o=JSON.parse(v,(y,A)=>y==="__proto__"||y==="constructor"||y==="prototype"?void 0:A)}else p===5130562&&(l=t.slice(g,g+h));s=g+h}if(!o)throw new Error("Missing JSON chunk in GLB");let c=o.extensionsRequired||[];for(let[h,p]of[["KHR_draco_mesh_compression","draco"],["EXT_meshopt_compression","meshopt"],["KHR_meshopt_compression","meshopt"],["KHR_texture_basisu","ktx2"]])if(c.includes(h)&&!ys(p))throw new Error(`Model requires ${h}. Register a decoder via ThreeLiveElement.registerDecoder('${p}', decoder).`);let f=l||new ArrayBuffer(0),m={gltf:o,bin:f,animations:[],animationsParsed:!1};for(let h of kt)h.onParseGLB?.(m);return m}function Wc(e,t=vr(e)){let r=e?.extensions?.KHR_lights_punctual?.lights;if(!Array.isArray(r))return[];let i=[],n=new Set,a=(s,o,l,c)=>{let f=s.type,m=f==="directional"||f==="point"||f==="spot"?f:"ambient",h=o?o[8]:-.5,p=o?o[9]:-1,g=o?o[10]:-.8,x=Math.hypot(h,p,g)||1,v=s.extras?.shadow??l,y=s.name||c,A={type:m,color:s.color||[1,1,1],intensity:s.intensity??1};y&&(A.name=y),o&&(A.position=[o[12],o[13],o[14]]),m==="directional"&&o?A.direction=[h/x,p/x,g/x]:(m==="spot"&&(A.direction=o?[-h/x,-p/x,-g/x]:[0,-1,0],A.innerConeAngle=s.spot?.innerConeAngle??0,A.outerConeAngle=s.spot?.outerConeAngle??Math.PI/4),A.range=s.range),v&&(A.shadow=v),i.push(A)};return(e.nodes||[]).forEach((s,o)=>{let l=s?.extensions?.KHR_lights_punctual?.light;typeof l=="number"&&r[l]&&(n.add(l),a(r[l],t[o],s.extras?.shadow,s.name))}),r.forEach((s,o)=>{n.has(o)||a(s)}),i}function yp(e){return typeof e=="object"&&e!==null&&"gltf"in e&&typeof e.gltf=="object"&&e.gltf!==null&&"bin"in e&&(e.bin instanceof ArrayBuffer||ArrayBuffer.isView(e.bin))}function wr(e){if(yp(e))return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Pd(e);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var jc=`#version 300 es
|
|
18
18
|
layout(location=0) in vec3 aPos;
|
|
19
19
|
layout(location=3) in vec3 aOff;
|
|
20
20
|
layout(location=1) in vec3 aNormal;
|
|
@@ -49,7 +49,7 @@ vec2 scaleUV=uUvTransform.zw;
|
|
|
49
49
|
if(scaleUV.x==0.0&&scaleUV.y==0.0)scaleUV=vec2(1.0);
|
|
50
50
|
vUV=aUV*scaleUV+uUvTransform.xy;
|
|
51
51
|
gl_Position=uMVP*vec4(aPosition,1.0);
|
|
52
|
-
}`,
|
|
52
|
+
}`,gp=`#version 300 es
|
|
53
53
|
precision highp float;
|
|
54
54
|
in vec3 vNormal,vWorldPos;
|
|
55
55
|
in vec2 vUV;
|
|
@@ -58,117 +58,81 @@ in vec4 vInstTint;
|
|
|
58
58
|
#define uBaseColor (uBaseColor*vInstTint)
|
|
59
59
|
uniform float uMetallic,uRoughness,uEmissive,uEnvIntensity,uExposure;
|
|
60
60
|
uniform vec2 uClearcoat;
|
|
61
|
-
uniform vec3 uCameraPos,uAmbientColor;
|
|
62
|
-
uniform
|
|
63
|
-
uniform
|
|
61
|
+
uniform vec3 uCameraPos,uAmbientColor,uEmissiveFactor;
|
|
62
|
+
uniform mat3 uHemi;
|
|
63
|
+
uniform sampler2D uBaseColorTexture,uMetallicRoughnessTexture,uNormalTexture,uOcclusionTexture,uEnvironmentMap,uEmissiveTexture;
|
|
64
|
+
uniform int uHasTexture,uHasMetallicRoughnessTexture,uHasNormalTexture,uHasOcclusionTexture,uHasEnvironmentMap,uHasEmissiveTexture;
|
|
64
65
|
uniform float uNormalScale,uOcclusionStrength;
|
|
65
|
-
/*XRD_U*/
|
|
66
|
+
/*XRD_U*//*SHD_U*/
|
|
66
67
|
uniform vec2 uViewportSize;
|
|
67
68
|
uniform vec4 uSectionPlane;
|
|
68
69
|
uniform int uToneMapping,uNumDirLights,uNumPointLights,uSectionEnabled;
|
|
69
70
|
uniform vec3 uDirLightDir[2],uDirLightColor[2],uPointLightPos[2],uPointLightColor[2],uPointLightSpotDir[2];
|
|
70
71
|
uniform vec2 uPointLightSpotCone[2];
|
|
71
72
|
out vec4 fragColor;
|
|
72
|
-
|
|
73
73
|
vec2 envBRDF(float r,float n){
|
|
74
|
-
vec4 c0=vec4(-1.0,-0.0275,-0.572,0.022),c1=vec4(1.0,0.0425,1.04,-0.04);
|
|
75
|
-
vec4 rv=r*c0+c1;
|
|
74
|
+
vec4 c0=vec4(-1.0,-0.0275,-0.572,0.022),c1=vec4(1.0,0.0425,1.04,-0.04),rv=r*c0+c1;
|
|
76
75
|
float a=min(rv.x*rv.x,exp2(-9.28*n))*rv.x+rv.y;
|
|
77
76
|
return vec2(-1.04,1.04)*a+rv.zw;
|
|
78
77
|
}
|
|
79
|
-
|
|
80
78
|
vec3 F_SchlickRoughness(vec3 F0,float r,float n){
|
|
81
79
|
return F0+(max(vec3(1.0-r),F0)-F0)*pow(clamp(1.0-n,0.0,1.0),5.0);
|
|
82
80
|
}
|
|
83
|
-
|
|
84
81
|
vec3 getStudioRadiance(vec3 R,float r){
|
|
85
|
-
vec3 kd=normalize(vec3(0.0,1.0,0.35));
|
|
82
|
+
vec3 kd=normalize(vec3(0.0,1.0,0.35)),fd=normalize(vec3(-0.85,0.45,-0.35));
|
|
86
83
|
float ki=pow(max(dot(R,kd),0.0),mix(96.0,1.5,r))*mix(2.4,0.5,r);
|
|
87
|
-
vec3 fd=normalize(vec3(-0.85,0.45,-0.35));
|
|
88
84
|
float fi=pow(max(dot(R,fd),0.0),mix(36.0,1.2,r))*mix(1.3,0.35,r);
|
|
89
85
|
float ri=pow(clamp(1.0-abs(R.y),0.0,1.0),3.5)*mix(0.55,0.22,r);
|
|
90
|
-
|
|
91
|
-
return ag+vec3(1.0,0.98,0.94)*ki+vec3(0.85,0.92,1.0)*fi+vec3(0.65,0.72,0.85)*ri;
|
|
86
|
+
return mix(vec3(0.06,0.06,0.08),vec3(0.48,0.50,0.55),R.y*0.5+0.5)+vec3(1.0,0.98,0.94)*ki+vec3(0.85,0.92,1.0)*fi+vec3(0.65,0.72,0.85)*ri;
|
|
92
87
|
}
|
|
93
|
-
|
|
94
|
-
vec3
|
|
95
|
-
vec3
|
|
96
|
-
|
|
97
|
-
vec3
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
vec2 duv2=dFdy(uv);
|
|
101
|
-
vec3 dp2perp=cross(dp2,N);
|
|
102
|
-
vec3 dp1perp=cross(N,dp1);
|
|
103
|
-
vec3 T=dp2perp*duv1.x+dp1perp*duv2.x;
|
|
104
|
-
vec3 B=dp2perp*duv1.y+dp1perp*duv2.y;
|
|
105
|
-
float invmax=inversesqrt(max(dot(T,T),dot(B,B)));
|
|
106
|
-
return normalize(mat3(T*invmax,B*invmax,N)*normalize(mapNormal));
|
|
88
|
+
vec3 perturbNormal(vec3 N,vec3 V,vec2 uv,sampler2D m,float s){
|
|
89
|
+
vec3 q=texture(m,uv).xyz*2.0-1.0;q.xy*=s;
|
|
90
|
+
vec3 p1=dFdx(vWorldPos),p2=dFdy(vWorldPos),c2=cross(p2,N),c1=cross(N,p1);
|
|
91
|
+
vec2 u1=dFdx(uv),u2=dFdy(uv);
|
|
92
|
+
vec3 T=c2*u1.x+c1*u2.x,B=c2*u1.y+c1*u2.y;
|
|
93
|
+
float k=inversesqrt(max(dot(T,T),dot(B,B)));
|
|
94
|
+
return normalize(mat3(T*k,B*k,N)*normalize(q));
|
|
107
95
|
}
|
|
108
|
-
|
|
109
96
|
vec2 equirectangularUV(vec3 dir){
|
|
110
97
|
vec3 d=normalize(dir);
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
vec3
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
0.84247906*color.r+0.0784336*color.g+0.07922375*color.b,
|
|
140
|
-
0.04232824*color.r+0.87846864*color.g+0.07916613*color.b,
|
|
141
|
-
0.04237565*color.r+0.0784336*color.g+0.87914297*color.b);
|
|
142
|
-
vec3 ev=clamp((log2(max(inset,vec3(1e-6)))+12.47393)/16.5,0.0,1.0);
|
|
143
|
-
vec3 x2=ev*ev;
|
|
144
|
-
vec3 x4=x2*x2;
|
|
145
|
-
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;
|
|
146
|
-
vec3 outset=vec3(
|
|
147
|
-
1.196879*s.r-0.09802088*s.g-0.09902974*s.b,
|
|
148
|
-
-0.05289685*s.r+1.15190313*s.g-0.09896118*s.b,
|
|
149
|
-
-0.05297164*s.r-0.09804345*s.g+1.15107367*s.b);
|
|
150
|
-
return clamp(pow(max(outset,vec3(0.0)),vec3(2.2)),0.0,1.0);
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
vec3 applyToneMapping(vec3 color,int mode){
|
|
154
|
-
if(mode==0)return neutralToneMapping(color);
|
|
155
|
-
if(mode==1)return color/(color+vec3(1.0));
|
|
156
|
-
if(mode==3)return acesToneMapping(color);
|
|
157
|
-
if(mode==4)return agxToneMapping(color);
|
|
158
|
-
return color;
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
vec3 evalLight(vec3 L,vec3 V,vec3 N,vec3 base,float specExp,float specWeight){
|
|
162
|
-
float NoH=max(dot(N,normalize(L+V)),0.0);
|
|
163
|
-
return base*max(dot(N,L),0.0)*0.75+vec3(pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35);
|
|
98
|
+
return vec2(atan(d.z,d.x)*0.15915494309+0.5,0.5-asin(clamp(d.y,-1.0,1.0))*0.31830988618);
|
|
99
|
+
}
|
|
100
|
+
vec3 neutralToneMapping(vec3 c){
|
|
101
|
+
float x=min(c.r,min(c.g,c.b));
|
|
102
|
+
c-=x<0.08?x-6.25*x*x:0.04;
|
|
103
|
+
float p=max(c.r,max(c.g,c.b));
|
|
104
|
+
if(p<0.76)return c;
|
|
105
|
+
float n=1.0-0.0576/(p-0.52);
|
|
106
|
+
c*=n/p;
|
|
107
|
+
return mix(c,vec3(n),1.0-1.0/(0.15*(p-n)+1.0));
|
|
108
|
+
}
|
|
109
|
+
vec3 acesToneMapping(vec3 c){
|
|
110
|
+
c*=0.6;return clamp((c*(2.51*c+0.03))/(c*(2.43*c+0.59)+0.14),0.0,1.0);
|
|
111
|
+
}
|
|
112
|
+
vec3 agxToneMapping(vec3 c){
|
|
113
|
+
c=max(c,vec3(0.0));
|
|
114
|
+
vec3 i=mat3(0.84247906,0.04232824,0.04237565,0.0784336,0.87846864,0.0784336,0.07922375,0.07916613,0.87914297)*c;
|
|
115
|
+
vec3 e=clamp((log2(max(i,vec3(1e-6)))+12.47393)/16.5,0.0,1.0),x2=e*e,x4=x2*x2;
|
|
116
|
+
vec3 s=15.5*x4*x2-40.14*x4*e+31.96*x4-6.868*x2*e+0.4298*x2+0.1191*e-0.00232;
|
|
117
|
+
vec3 o=mat3(1.196879,-0.05289685,-0.05297164,-0.09802088,1.15190313,-0.09804345,-0.09902974,-0.09896118,1.15107367)*s;
|
|
118
|
+
return clamp(pow(max(o,vec3(0.0)),vec3(2.2)),0.0,1.0);
|
|
119
|
+
}
|
|
120
|
+
vec3 applyToneMapping(vec3 c,int m){
|
|
121
|
+
return m==0?neutralToneMapping(c):m==1?c/(c+vec3(1.0)):m==3?acesToneMapping(c):m==4?agxToneMapping(c):c;
|
|
122
|
+
}
|
|
123
|
+
vec3 evalLight(vec3 L,vec3 V,vec3 N,vec3 b,float e,float w){
|
|
124
|
+
float h=max(dot(N,normalize(L+V)),0.0);
|
|
125
|
+
return b*max(dot(N,L),0.0)*0.75+vec3(pow(h,e)*w+uClearcoat.x*pow(h,mix(64.0,512.0,1.0-uClearcoat.y))*0.35);
|
|
164
126
|
}
|
|
165
127
|
|
|
166
128
|
void main(){
|
|
167
129
|
if(uSectionEnabled==1&&dot(vWorldPos,uSectionPlane.xyz)>uSectionPlane.w)discard;
|
|
168
130
|
vec4 base=uBaseColor;
|
|
169
131
|
if(uHasTexture==1)base*=texture(uBaseColorTexture,vUV);
|
|
132
|
+
if(base.a<0.004)discard;
|
|
133
|
+
vec3 em=uHasEmissiveTexture==1?uEmissiveFactor*texture(uEmissiveTexture,vUV).rgb:uEmissiveFactor;
|
|
170
134
|
if(length(vNormal)<1e-4&&uHasTexture==1){
|
|
171
|
-
vec3 unlit=base.rgb+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
|
|
135
|
+
vec3 unlit=base.rgb+em+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
|
|
172
136
|
fragColor=vec4(unlit,base.a);
|
|
173
137
|
return;
|
|
174
138
|
}
|
|
@@ -200,7 +164,7 @@ float specWeight=mix(0.22*gloss,1.0,metallic);
|
|
|
200
164
|
vec3 directLight=vec3(0.0);
|
|
201
165
|
for(int i=0;i<2;i++){
|
|
202
166
|
if(i>=uNumDirLights)break;
|
|
203
|
-
directLight+=evalLight(normalize(uDirLightDir[i]),V,N,base.rgb,specExp,specWeight)*uDirLightColor[i]
|
|
167
|
+
directLight+=evalLight(normalize(uDirLightDir[i]),V,N,base.rgb,specExp,specWeight)*uDirLightColor[i]/*SHD_D*/;
|
|
204
168
|
}
|
|
205
169
|
for(int i=0;i<2;i++){
|
|
206
170
|
if(i>=uNumPointLights)break;
|
|
@@ -209,7 +173,7 @@ float dist=length(toLight);
|
|
|
209
173
|
vec3 L=toLight/max(dist,0.0001);
|
|
210
174
|
float spotAtt=clamp((dot(-L,uPointLightSpotDir[i])-uPointLightSpotCone[i].y)/max(uPointLightSpotCone[i].x-uPointLightSpotCone[i].y,0.0001),0.0,1.0);
|
|
211
175
|
spotAtt*=spotAtt;
|
|
212
|
-
directLight+=evalLight(L,V,N,base.rgb,specExp,specWeight)*uPointLightColor[i]*spotAtt/(1.0+0.09*dist+0.032*dist*dist)
|
|
176
|
+
directLight+=evalLight(L,V,N,base.rgb,specExp,specWeight)*uPointLightColor[i]*spotAtt/(1.0+0.09*dist+0.032*dist*dist)/*SHD_P*/;
|
|
213
177
|
}
|
|
214
178
|
|
|
215
179
|
vec3 R=reflect(-V,N);
|
|
@@ -229,8 +193,9 @@ envDiffuse=mix(vec3(0.10,0.10,0.12),vec3(0.52,0.54,0.58),N.y*0.5+0.5);
|
|
|
229
193
|
}
|
|
230
194
|
|
|
231
195
|
vec3 kD=(vec3(1.0)-F)*(1.0-metallic);
|
|
196
|
+
directLight+=kD*base.rgb*mix(uHemi[1],uHemi[0],dot(N,uHemi[2])*0.5+0.5)*occ;
|
|
232
197
|
vec3 diffuseIBL=kD*base.rgb*(uAmbientColor+envDiffuse*0.5)*occ;
|
|
233
|
-
vec3 color=directLight+(diffuseIBL+specularIBL)*uEnvIntensity+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
|
|
198
|
+
vec3 color=directLight+(diffuseIBL+specularIBL)*uEnvIntensity+em+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
|
|
234
199
|
if(uClearcoat.x>0.0){
|
|
235
200
|
vec3 ccF=F_SchlickRoughness(vec3(0.04),uClearcoat.y,NoV)*uClearcoat.x;
|
|
236
201
|
color=color*(vec3(1.0)-ccF)+getStudioRadiance(R,uClearcoat.y)*ccF*uEnvIntensity;
|
|
@@ -240,24 +205,24 @@ color=applyToneMapping(color,uToneMapping);
|
|
|
240
205
|
float outAlpha=base.a;
|
|
241
206
|
/*XRD_O*/
|
|
242
207
|
fragColor=vec4(color,outAlpha);
|
|
243
|
-
}`;function
|
|
208
|
+
}`;function Id(e,t,r=1){t=Dr(t);let i=Number.isFinite(r)?Math.max(0,r):1,[n,a,s]=[0,1,2].map(x=>Math.max(0,(Number(e[x])||0)*i)),o=x=>Math.max(0,Math.min(1,x)),l=x=>[x(n),x(a),x(s)];if(t==="none")return l(o);if(t==="reinhard")return l(x=>x/(x+1));if(t==="aces")return l(x=>{let v=x*.6;return o(v*(2.51*v+.03)/(v*(2.43*v+.59)+.14))});if(t==="agx"){let[x,v,y]=[.84247906*n+.0784336*a+.07922375*s,.04232824*n+.87846864*a+.07916613*s,.04237565*n+.0784336*a+.87914297*s].map(A=>{let b=o((Math.log2(Math.max(A,1e-6))+12.47393)/16.5),w=b*b,S=w*w;return 15.5*S*w-40.14*S*b+31.96*S-6.868*w*b+.4298*w+.1191*b-.00232});return[1.196879*x-.09802088*v-.09902974*y,-.05289685*x+1.15190313*v-.09896118*y,-.05297164*x-.09804345*v+1.15107367*y].map(A=>o(Math.pow(Math.max(A,0),2.2)))}let c=Math.min(n,a,s),f=c<.08?c-6.25*c*c:.04;[n,a,s]=l(x=>x-f);let m=Math.max(n,a,s);if(m<.76)return l(o);let h=1-.0576/(m-.52),p=h/m,g=1-1/(.15*(m-h)+1);return l(x=>o(x*p+(h-x*p)*g))}var xp=`#version 300 es
|
|
244
209
|
layout(location=0) in vec3 aPosition;
|
|
245
210
|
uniform mat4 uMVP;
|
|
246
|
-
void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,
|
|
211
|
+
void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,vp=`#version 300 es
|
|
247
212
|
precision highp float;
|
|
248
213
|
uniform vec4 uColorId;
|
|
249
214
|
out vec4 fragColor;
|
|
250
|
-
void main(){fragColor=uColorId;}`;function Oi(e,t,r){let i={};for(let n of r)i[n]=e.getUniformLocation(t,n);return i}var Qo=["uMVP","uModel","uInstanced","uViewProj","uNormalMatrix","uUvTransform","uBaseColor","uMetallic","uRoughness","uClearcoat","uEmissive","uCameraPos","uBaseColorTexture","uHasTexture","uMetallicRoughnessTexture","uHasMetallicRoughnessTexture","uNormalTexture","uHasNormalTexture","uNormalScale","uOcclusionTexture","uHasOcclusionTexture","uOcclusionStrength","uToneMapping","uEnvironmentMap","uHasEnvironmentMap","uAmbientColor","uNumDirLights","uDirLightDir","uDirLightColor","uNumPointLights","uPointLightPos","uPointLightColor","uPointLightSpotDir","uPointLightSpotCone","uEnvIntensity","uExposure","uViewportSize","uSectionPlane","uSectionEnabled"];function os(){let e=Ae().xrDepthShader;return{fs:tc.replace("/*XRD_U*/",e?.uniformsGLSL||"").replace("/*XRD_O*/",e?.occlusionGLSL||""),uniforms:e?[...Qo,...e.uniformNames]:Qo}}function ic(e){if(typeof e!="string")return null;let t=e.trim();if(!t||/[\x00-\x1f\x7f]/.test(t))return null;let r=t.toLowerCase();return r.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(t)?t:null:r.startsWith("https://")||r.startsWith("blob:")?t:r.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(t)||/(^|[\\/])\.\.([\\/]|$)/.test(t)?null:t}function Ni(e,t,r,i,n,s,l,o){if(i===void 0||!t.accessors?.[i])return null;let a=bt(t,r,t.accessors[i],s);if(!a)return null;o&&(a=a.slice(),Zo(a,o));let u=e.createBuffer();return l.push(u),e.bindBuffer(34962,u),e.bufferData(34962,a,35044),e.enableVertexAttribArray(n),e.vertexAttribPointer(n,s,5126,!1,0,0),a}function ki(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,t):1}function ss(e,t,r){let i=os(),n=rs,s=i.fs,l=!1;for(let a of Oe)if(a.onResolveShader){let u=a.onResolveShader(t,r,n,s);u&&(n=u.vs,s=u.fs,l=!0)}let o=l?_t(e,n,s):null;return{program:o,uniforms:o?Oi(e,o,i.uniforms):null}}function oc(e,t,r){let i=t.instanceMatrices;if(!i||i.length<16||typeof e.vertexAttribDivisor!="function"||typeof e.drawElementsInstanced!="function")return!1;let n=i.length>>4,s=t.instanceColors,l=new Float32Array(n*20);for(let a=0;a<n;a++)l.set(i.subarray(a*16,a*16+16),a*20),l[a*20+16]=s?s[a*3]:1,l[a*20+17]=s?s[a*3+1]:1,l[a*20+18]=s?s[a*3+2]:1,l[a*20+19]=1;let o=e.createBuffer();r.push(o),e.bindBuffer(34962,o),e.bufferData(34962,l,35044);for(let a=0;a<5;a++)e.enableVertexAttribArray(8+a),e.vertexAttribPointer(8+a,4,5126,!1,80,a*16),e.vertexAttribDivisor(8+a,1);return!0}function sc(e,t){let r=e.materials?.[t?.material];if(!r)return null;let i=[r.pbrMetallicRoughness?.baseColorTexture,r.pbrMetallicRoughness?.metallicRoughnessTexture,r.normalTexture,r.occlusionTexture,r.emissiveTexture];for(let n of i){let s=n?.extensions?.KHR_texture_transform;if(s&&typeof s=="object")return s}return null}var as=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),cs=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function cr(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}function us(e,t){let r=e?.pbrMetallicRoughness,i=r?.baseColorFactor,n=e?.extensions?.KHR_materials_clearcoat,s=l=>l!==void 0&&t[l.index]?t[l.index]:null;return{baseColor:i?[i[0],i[1],i[2],i[3]??1]:[.8,.8,.8,1],metallic:r?.metallicFactor??.1,roughness:r?.roughnessFactor??.5,clearcoat:n?n.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,n?.clearcoatRoughnessFactor??.04),texture:s(r?.baseColorTexture),metallicRoughnessTexture:s(r?.metallicRoughnessTexture),normalTexture:s(e?.normalTexture),normalScale:e?.normalTexture?.scale??1,occlusionTexture:s(e?.occlusionTexture),occlusionStrength:e?.occlusionTexture?.strength??1,isTransmissive:(e?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function ls(e,t,r){let i=new Set,n=s=>{s&&!i.has(s)&&(i.add(s),e.deleteTexture(s))};for(let s of t)for(let l of s.primitives){if(l.vao&&e.deleteVertexArray(l.vao),l.buffers)for(let a of l.buffers)e.deleteBuffer(a);n(l.texture),n(l.metallicRoughnessTexture),n(l.normalTexture),n(l.occlusionTexture);let o=new Set;l.customProgram&&o.add(l.customProgram);for(let a of l.programCache?.values()??[])a.program&&o.add(a.program);for(let a of o)e.deleteProgram(a)}if(r)for(let s of r)n(s)}function Jo(e,t,r=cs,i){let n={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return ac(e,t,r,i,n)}catch(s){let l=n.mesh&&!n.meshes.includes(n.mesh)?[...n.meshes,n.mesh]:n.meshes;ls(e,l,n.gpuTextures),n.vao&&e.deleteVertexArray(n.vao);for(let o of n.buffers)e.deleteBuffer(o);throw s}}function ac(e,t,r,i,n){if(!t||!t.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:s}=t,l=nn("meshopt");l?.decodeBufferViews&&l.decodeBufferViews(s,t);let o=t.bin,a=[];n.meshes=a;let u=[],h=s.extensions?.KHR_materials_variants;h&&Array.isArray(h.variants)&&h.variants.forEach((k,w)=>{u.push(typeof k?.name=="string"&&k.name?k.name:`Variant_${w}`)});let m=Ft(s),c=[];if(Array.isArray(s.nodes))for(let k=0;k<s.nodes.length;k++){let w=s.nodes[k];w.mesh!==void 0&&s.meshes&&s.meshes[w.mesh]&&c.push({node:w,nodeIdx:k,meshIdx:w.mesh})}let d=c.length>0?c:(s.meshes||[]).map((k,w)=>({node:k,nodeIdx:-1,meshIdx:w})),f=[],g=Array.isArray(t.lights)&&t.lights.length>0?t.lights:Array.isArray(s.asset?.extras?.lights)&&s.asset.extras.lights.length>0?s.asset.extras.lights:null;if(g)for(let k of g)f.push({...k,type:k.type||k.light_type||"point",innerConeAngle:k.innerConeAngle??k.inner_cone_angle,outerConeAngle:k.outerConeAngle??k.outer_cone_angle});else if(s.extensions?.KHR_lights_punctual?.lights){let k=s.extensions.KHR_lights_punctual.lights;for(let w of k){let ie=w.type==="directional"?"directional":w.type==="point"?"point":w.type==="spot"?"spot":"ambient";f.push({type:ie,color:w.color||[1,1,1],intensity:w.intensity!==void 0?w.intensity:1})}}if(f.length===0&&(f.push({type:"ambient",color:[1,1,1],intensity:.35}),f.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),d.length>r.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${r.maxMeshes}). Found: ${d.length}`);let x=[];if(n.gpuTextures=x,s.textures&&s.images){if(s.textures.length>r.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${r.maxTextures}). Found: ${s.textures.length}`);for(let k=0;k<s.textures.length;k++){let w=s.textures[k],ie=s.images[w.source];if(ie){let oe=e.createTexture();e.bindTexture(3553,oe),e.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),e.texParameteri(3553,10242,10497),e.texParameteri(3553,10243,10497),e.texParameteri(3553,10241,9729),e.texParameteri(3553,10240,9729);let I=H=>{e.bindTexture(3553,oe),e.texImage2D(3553,0,6408,6408,5121,H),e.generateMipmap(3553),i?.()};if(ie.bufferView!==void 0){let H=s.bufferViews[ie.bufferView],N=H.byteOffset||0,z=new Blob([o.slice(N,N+H.byteLength)],{type:ie.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(z).then(I).catch(()=>{})}else if(ie.uri){let H=ic(ie.uri);if(H){let N=new Image;N.crossOrigin="anonymous",N.referrerPolicy="no-referrer",N.onload=()=>I(N),N.src=H}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",ie.uri)}x.push(oe)}else x.push(null)}}let b=[1/0,1/0,1/0],v=[-1/0,-1/0,-1/0],p=0,y=0;for(let k=0;k<d.length;k++){let w=d[k],ie=s.meshes[w.meshIdx],oe=w.nodeIdx>=0?m[w.nodeIdx]:Se(),I=new Float32Array(9);Xe(I,oe);let H={name:w.node.name||ie.name||`Mesh_${w.meshIdx}`,nodeIndex:w.nodeIdx,transform:oe,normalMatrix:I,primitives:[],extras:w.node.extras||ie.extras,...w.node?.visible===!1||w.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{}};n.mesh=H;let N=w.node?.extensions?.EXT_mesh_gpu_instancing;if(N&&N.attributes&&typeof N.attributes=="object"){let z=N.attributes,ue=z.TRANSLATION!==void 0?s.accessors?.[z.TRANSLATION]:null,ce=z.ROTATION!==void 0?s.accessors?.[z.ROTATION]:null,B=z.SCALE!==void 0?s.accessors?.[z.SCALE]:null,$=z._COLOR_0!==void 0?s.accessors?.[z._COLOR_0]:null,_=Number(ue?.count??ce?.count??B?.count??0);if(!Number.isFinite(_)||_<0||_>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${_}`);if(_>0){let G=(V,ee)=>{if(!V||V.bufferView===void 0||!s.bufferViews?.[V.bufferView])return null;let R=V.componentType??5126,A=C=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${C})`),null);if(R!==5120&&R!==5121&&R!==5122&&R!==5123&&R!==5126)return A(`componentType ${R}`);if(!(Number(V.count)>=_))return A(`count ${V.count} < ${_}`);let L=null;try{L=bt(s,o,{...V,count:_},ee)}catch{return A("out of bounds")}return!L||!L.every(Number.isFinite)?A("non-finite value"):L},j=G(ue,3),q=G(ce,4),D=G(B,3),Y=$?.type==="VEC4"?4:3,te=G($,Y),se=new Float32Array(_*16),le=Se();for(let V=0;V<_;V++){let ee=j?[j[V*3],j[V*3+1],j[V*3+2]]:[0,0,0],R=q?[q[V*4],q[V*4+1],q[V*4+2],q[V*4+3]]:[0,0,0,1],A=D?[D[V*3],D[V*3+1],D[V*3+2]]:[1,1,1];Tt(le,R,ee,A),se.set(le,V*16)}if(H.instanceMatrices=se,te){let V=new Float32Array(_*3);for(let ee=0;ee<_;ee++)V[ee*3]=te[ee*Y],V[ee*3+1]=te[ee*Y+1],V[ee*3+2]=te[ee*Y+2];H.instanceColors=V}}}for(let z of ie.primitives||[]){if(z.extensions?.KHR_draco_mesh_compression){let L=nn("draco");L&&L.decodePrimitive(s,z,o)}let ue=[],ce=e.createVertexArray();n.vao=ce,n.buffers=ue,e.bindVertexArray(ce);let B=oc(e,H,ue),$=s.accessors[z.attributes.POSITION],_=Number($?.count??0);if(!Number.isFinite(_)||_<0||p+_>r.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${r.maxVertices}).`);if(p+=_,$?.min&&$?.max){let L=C=>{for(let U=0;U<3;U++){let Q=C[12+U],X=C[12+U];for(let Z=0;Z<3;Z++){let J=C[Z*4+U]*$.min[Z],K=C[Z*4+U]*$.max[Z];Q+=J<K?J:K,X+=J>K?J:K}Q<b[U]&&(b[U]=Q),X>v[U]&&(v[U]=X)}};if(H.instanceMatrices&&H.instanceMatrices.length>=16){let C=H.instanceMatrices.length>>4,U=Se();for(let Q=0;Q<C;Q++){let X=H.instanceMatrices.subarray(Q*16,Q*16+16);Ie(U,oe,X),L(U)}}else L(oe)}let G=Ni(e,s,o,z.attributes.POSITION,0,3,ue);Ni(e,s,o,z.attributes.NORMAL,1,3,ue),Ni(e,s,o,z.attributes.TEXCOORD_0,2,2,ue,sc(s,z));let j=0,q=5123,D=null;if(z.indices!==void 0){let L=s.accessors[z.indices],C=(s.bufferViews[L.bufferView].byteOffset||0)+(L.byteOffset||0);if(j=Number(L.count??0),!Number.isFinite(j)||j<0||y+j>r.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${r.maxIndices}).`);y+=j,q=L.componentType===5125?5125:5123;let U=e.createBuffer();ue.push(U),e.bindBuffer(34963,U),L.componentType===5125?D=new Uint32Array(o,C,L.count):L.componentType===5121?D=Uint16Array.from(new Uint8Array(o,C,L.count)):D=C%2===0?new Uint16Array(o,C,L.count):new Uint16Array(o.slice(C,C+L.count*2)),e.bufferData(34963,D,35044)}else j=$.count;let Y={};for(let L of Oe)if(L.onBuildPrimitiveVAO){let C=L.onBuildPrimitiveVAO(e,ce,z,s,o);C&&(Y[L.name]=C)}e.bindVertexArray(null);let te=s.materials&&z.material!==void 0?s.materials[z.material]:null,{program:se,uniforms:le}=ss(e,z,te),V=us(te,x),ee=!!(te?.extensions?.KHR_materials_transmission||Y.materials?.isTransmissive),R=z.extensions?.KHR_materials_variants?.mappings,A=Array.isArray(R)?R.filter(L=>L&&typeof L.material=="number"&&Array.isArray(L.variants)).map(L=>({material:L.material|0,variants:L.variants.map(C=>Number(C)|0)})):void 0;H.primitives.push({vao:ce,instanced:B,indexCount:j,indexType:q,...V,positions:G,indices:D,buffers:ue,materialIndex:z.material,defaultMaterialIndex:z.material,variantMappings:A,primitiveDef:z,programCache:new Map([[z.material??-1,{program:se,uniforms:le}]]),pluginData:Y,customProgram:se,customUniforms:le,isTransmissive:ee})}a.push(H)}isFinite(b[0])||(b=[-1,-1,-1]),isFinite(v[0])||(v=[1,1,1]);let M=[(b[0]+v[0])/2,(b[1]+v[1])/2,(b[2]+v[2])/2],P=v[0]-b[0],F=v[1]-b[1],W=v[2]-b[2],T=Math.max(Math.hypot(P,F,W)/2,.5),E=[b[0],b[1],b[2]],S=[v[0],v[1],v[2]],O=t.animations;if(!O){for(let k of Oe)if(k.onParseGLB?.(t),t.animations){O=t.animations;break}}return O||(O=[]),{meshes:a,bounds:{center:M,radius:T,min:E,max:S},lights:f,animations:O,worldMatrices:m,gpuTextures:x,availableVariants:u}}function Mn(e){let t=e.customTarget||e.bounds.center,r=e.currDistance*Math.cos(e.currPhi);return[t[0]+r*Math.sin(e.currTheta),t[1]+e.currDistance*Math.sin(e.currPhi),t[2]+r*Math.cos(e.currTheta)]}var Ke=class{constructor(e,t,r){this.supportsInstanceOffsets=!0,this.meshes=[],this.backdropMeshes=[],this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]},this.lights=[],this.modelRootMatrix=Se(),this.clearColor=[0,0,0,0],this.envIntensity=1,this.exposure=1,this.shadowIntensity=0,this.shadowSoftness=.5,this.toneMapping="neutral",this.environmentTexture=null,this.animations=[],this.currentClip=null,this.animationTime=0,this.isPlayingAnimation=!1,this.autoplay=!1,this.animationName="",this.gpuTextures=[],this.availableVariants=[],this.activeVariantName=null,this.gltf=null,this.worldMatrices=[],this.initialNodeTransforms=[],this.projMatrix=Se(),this.viewMatrix=Se(),this.activeViewMatrix=null,this.modelMatrix=Se(),this.mvpMatrix=Se(),this.normalMatrix=new Float32Array(9),this.initialTheta=.6,this.initialPhi=.35,this.initialDistance=null,this.customDistance=!1,this.distanceMode="auto",this.initialCustomTarget=null,this.customTarget=null,this.fov=Math.PI/4,this.minTheta=-1/0,this.maxTheta=1/0,this.minPhi=-Math.PI*.48,this.maxPhi=Math.PI*.48,this.minDistanceLimit=null,this.maxDistanceLimit=null,this.activePointers=new Map,this.isPanning=!1,this.targetTheta=.6,this.currTheta=.6,this.targetPhi=.35,this.currPhi=.35,this.targetDistance=3,this.currDistance=3,this.autoRotate=!1,this.autoRotateSpeed=Math.PI/6,this.autoRotateDelay=3e3,this.lastInteractionTime=-1/0,this.turntableRotation=0,this.isPointerDown=!1,this.interactive=!0,this.skyboxTexture=null,this.lastPointerX=0,this.lastPointerY=0,this.totalDragDist=0,this.selectedMeshName="",this.pickFbo=null,this.pickTexture=null,this.pickDepth=null,this.pickFboWidth=0,this.pickFboHeight=0,this.animFrameId=null,this.isVisible=!0,this.xrSessionActive=!1,this.lastTime=0,this.lastReportedTheta=-999,this.lastReportedPhi=-999,this.lastReportedZoom=-999,this.boundPointerDown=null,this.boundPointerMove=null,this.boundPointerUp=null,this.boundWheel=null,this.boundKeyDown=null,this.boundContextMenu=null,this.boundSetCamera=null,this.boundResetCamera=null,this.contextLost=!1,this.lastGlbData=null,this.boundContextLost=null,this.boundContextRestored=null,this.stereoSBS=!1,this.renderErrorReported=!1,this.xrDepthState={enabled:!1,texture:null,uvTransform:Se(),rawValueToMeters:.001,format:0},this.container=e;let i,n;if(t&&typeof t.getContext=="function"?(i=t,n=r):(n=t,i=n?.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=n||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!s:s&&(this.autoRotate=!1),this.opts.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=this.opts.autoRotateSpeed),this.opts.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(this.opts.autoRotateDelay)||0)),this.opts.exposure!==void 0&&(this.exposure=ki(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=Vt(this.opts.toneMapping)),this.opts.autoplay!==void 0&&(this.autoplay=this.opts.autoplay),this.opts.animationName!==void 0&&(this.animationName=this.opts.animationName),this.opts.variantName!==void 0&&(this.activeVariantName=this.opts.variantName||null),this.opts.fieldOfView!==void 0&&(this.fov=this.opts.fieldOfView*Math.PI/180),this.opts.distanceMode!==void 0&&(this.distanceMode=this.opts.distanceMode),this.opts.cameraTarget!==void 0&&(this.setTarget(this.opts.cameraTarget[0],this.opts.cameraTarget[1],this.opts.cameraTarget[2]),this.initialCustomTarget=[...this.opts.cameraTarget]),(this.opts.minCameraOrbit||this.opts.maxCameraOrbit)&&this.setOrbitLimits({minTheta:this.opts.minCameraOrbit?.theta,maxTheta:this.opts.maxCameraOrbit?.theta,minPhi:this.opts.minCameraOrbit?.phi,maxPhi:this.opts.maxCameraOrbit?.phi,minDistance:this.opts.minCameraOrbit?.distance,maxDistance:this.opts.maxCameraOrbit?.distance});let l=i.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!l)throw new Error("WebGL2 not supported");this.gl=l,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(e,t){Ja(e,t)}static getDecoder(e){return nn(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=os();this.renderProg=_t(e,rs,t.fs),this.pickProg=_t(e,nc,rc),this.uRender=Oi(e,this.renderProg,t.uniforms),this.uPick=Oi(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of Oe)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),n=Math.max(1,t);this.pickFboWidth=i,this.pickFboHeight=n,r.bindTexture(3553,this.pickTexture),r.texImage2D(3553,0,6408,i,n,0,6408,5121,null),r.bindRenderbuffer(36161,this.pickDepth),r.renderbufferStorage(36161,33189,i,n)}loadGLBData(e,t){let{meshes:r,bounds:i,lights:n,animations:s,worldMatrices:l,gpuTextures:o,availableVariants:a}=Jo(this.gl,e,t,()=>this.render());if(this.lastGlbData=e,this.lastLimits=t,this.disposeMeshGpuResources(),this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.meshes=r,this.bounds=i,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=n,this.animations=s||[],this.worldMatrices=l||[],this.gpuTextures=o||[],this.availableVariants=a||[],this.gltf=e.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let m of e.gltf.nodes)this.initialNodeTransforms.push({t:m.translation?[m.translation[0],m.translation[1],m.translation[2]]:[0,0,0],r:m.rotation?[m.rotation[0],m.rotation[1],m.rotation[2],m.rotation[3]]:[0,0,0,1],s:m.scale?[m.scale[0],m.scale[1],m.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let m of Oe)m.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:i.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let u=e.exposure??e.gltf?.extras?.exposure??e.gltf?.asset?.extras?.exposure;u!==void 0&&(this.exposure=ki(u));let h=e.environmentIntensity??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.environmentIntensity;h!==void 0&&(this.envIntensity=Math.max(0,Number(h)||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(ns(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let e of Oe)e.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(Lt(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=Lt(e),{meshes:i}=Jo(this.gl,r,cs,()=>this.render());if(t)for(let n of i)n.transform[12]+=t[0],n.transform[13]+=t[1],n.transform[14]+=t[2],Xe(n.normalMatrix,n.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),Xe(r.normalMatrix,r.transform))}}bindLights(e=this.uRender){let t=this.gl,r=[.28,.28,.28],i=[],n=[],s=[],l=[],o=[],a=[];for(let u of this.lights){let h=u.color||[1,1,1],m=u.intensity!==void 0?u.intensity:1;if(u.type==="ambient")r=[h[0]*m,h[1]*m,h[2]*m];else if(u.type==="directional"&&i.length<6){let c=u.direction||[.5,1,.8];i.push(c[0],c[1],c[2]),n.push(h[0]*m,h[1]*m,h[2]*m)}else if((u.type==="point"||u.type==="spot")&&s.length<6){let c=u.position||[0,0,0];if(s.push(c[0],c[1],c[2]),l.push(h[0]*m,h[1]*m,h[2]*m),u.type==="spot"){let d=u.direction||[0,-1,0],f=Math.max(.01,Math.min(Math.PI/2,u.outerConeAngle??Math.PI/3)),g=Math.max(0,Math.min(f-1e-4,u.innerConeAngle??0));o.push(d[0],d[1],d[2]),a.push(Math.cos(g),Math.cos(f))}else o.push(0,-1,0),a.push(-2,-3)}}i.length===0&&(i.push(.5,1,.8),n.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,n)),t.uniform1i(e.uNumPointLights,s.length/3),s.length>0&&(t.uniform3fv(e.uPointLightPos,s),t.uniform3fv(e.uPointLightColor,l),e.uPointLightSpotDir&&t.uniform3fv(e.uPointLightSpotDir,o),e.uPointLightSpotCone&&t.uniform2fv(e.uPointLightSpotCone,a)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=ki(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=Vt(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of Oe)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of Oe)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(h=>h.materialIndex===r||e.length===1&&h.materialIndex===void 0)),n=i[0],s=n?[...n.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],l=n?n.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,o=n?n.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,a={baseColorFactor:s,metallicFactor:l,roughnessFactor:o,setBaseColorFactor:u=>{let h=[u[0],u[1],u[2],u[3]??1];a.baseColorFactor=h,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=h);for(let m of i)m.baseColor=h;this.render()},setMetallicFactor:u=>{a.metallicFactor=u,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=u);for(let h of i)h.metallic=u;this.render()},setRoughnessFactor:u=>{a.roughnessFactor=u,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=u);for(let h of i)h.roughness=u;this.render()}};return{name:t.name||`Material_${r}`,pbrMetallicRoughness:a}})}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 n of this.meshes)for(let s of n.primitives){let l=s.defaultMaterialIndex;if(!t&&Array.isArray(s.variantMappings)){for(let a of s.variantMappings)if(Array.isArray(a.variants)&&a.variants.includes(r)){l=a.material;break}}let o=l!==void 0?i[l]:void 0;s.materialIndex=o?l:void 0,Object.assign(s,us(o,this.gpuTextures)),this.applyPrimitiveProgram(s,s.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,n=e.programCache.get(i);n||(n=ss(this.gl,{...e.primitiveDef,material:t},r),e.programCache.set(i,n)),e.customProgram=n.program,e.customUniforms=n.uniforms,e.pluginData&&(e.pluginData.materials=e.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(e){this.autoplay=e,e?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(e){this.animationName=e,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(e)}evaluateAnimation(e){for(let t of Oe)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 n=this.clampDistance(r);this.initialDistance=n,this.customDistance=!0,this.targetDistance=n,this.currDistance=n}else if(i!==void 0&&i>0){let n=this.clampDistance(this.bounds.radius*2.5/i);this.initialDistance=n,this.customDistance=!0,this.targetDistance=n,this.currDistance=n}else{this.customDistance=!1;let n=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=n,this.targetDistance=n,this.currDistance=n}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=Se();Ie(r,this.projMatrix,this.viewMatrix);let[i,n,s]=e,l=t?t[0]:0,o=t?t[1]:0,a=t?t[2]:0,u=this.modelRootMatrix;u&&(i=u[0]*e[0]+u[4]*e[1]+u[8]*e[2]+u[12],n=u[1]*e[0]+u[5]*e[1]+u[9]*e[2]+u[13],s=u[2]*e[0]+u[6]*e[1]+u[10]*e[2]+u[14],t&&(l=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],a=u[2]*t[0]+u[6]*t[1]+u[10]*t[2]));let h=r[0]*i+r[4]*n+r[8]*s+r[12],m=r[1]*i+r[5]*n+r[9]*s+r[13],c=r[2]*i+r[6]*n+r[10]*s+r[14],d=r[3]*i+r[7]*n+r[11]*s+r[15];if(d<=1e-4)return{x:0,y:0,z:1,visible:!1};let f=h/d,g=m/d,x=c/d,b=this.canvas.getBoundingClientRect(),v=b.width||this.canvas.clientWidth||this.canvas.width||300,p=b.height||this.canvas.clientHeight||this.canvas.height||150,y=(f*.5+.5)*v,M=(-g*.5+.5)*p,P=f>=-1.1&&f<=1.1&&g>=-1.1&&g<=1.1&&x>=-1&&x<=1;if(P&&t){let[F,W,T]=Mn(this),E=[i-F,n-W,s-T];l*E[0]+o*E[1]+a*E[2]>.05&&(P=!1)}return{x:y,y:M,z:x,visible:P}}setSelectedMesh(e){this.selectedMeshName=e||""}getSelectedMesh(){return this.selectedMeshName}setupEvents(){let e=this.canvas,t=()=>typeof performance<"u"?performance.now():Date.now();this.boundContextMenu=r=>{r.preventDefault()},e.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=r=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=t(),this.lastPointerX=r.clientX,this.lastPointerY=r.clientY,this.totalDragDist=0,this.activePointers.set(r.pointerId,{x:r.clientX,y:r.clientY}),this.isPanning=r.button===2||r.shiftKey||this.activePointers.size===2,e.setPointerCapture(r.pointerId))},e.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=r=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=t();let i=this.activePointers.get(r.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},n=r.clientX-i.x,s=r.clientY-i.y;if(this.activePointers.set(r.pointerId,{x:r.clientX,y:r.clientY}),this.lastPointerX=r.clientX,this.lastPointerY=r.clientY,this.totalDragDist+=Math.hypot(n,s),this.isPanning||r.button===2||r.shiftKey||this.activePointers.size===2){let l=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],o=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],a=this.customTarget?[...this.customTarget]:[...this.bounds.center],u=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;a[0]+=(-n*l[0]+s*o[0])*u,a[1]+=(-n*l[1]+s*o[1])*u,a[2]+=(-n*l[2]+s*o[2])*u,this.customTarget=a}else this.targetTheta=this.clampTheta(this.targetTheta-n*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=r=>{this.lastInteractionTime=t(),this.activePointers.delete(r.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(r.pointerId)}catch{}if(this.totalDragDist<5&&r.button===0){let i=e.getBoundingClientRect(),n=Math.floor((r.clientX-i.left)*(e.width/Math.max(i.width,1))),s=Math.floor((r.clientY-i.top)*(e.height/Math.max(i.height,1)));this.performMeshPick(n,s,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=r=>{if(!this.interactive)return;r.preventDefault(),this.lastInteractionTime=t();let i=Math.exp(r.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*i)},e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=r=>{let i=r.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=r=>{if(this.interactive){switch(r.key){case"ArrowLeft":this.targetTheta=this.clampTheta(this.targetTheta-.1);break;case"ArrowRight":this.targetTheta=this.clampTheta(this.targetTheta+.1);break;case"ArrowUp":this.targetPhi=this.clampPhi(this.targetPhi+.08);break;case"ArrowDown":this.targetPhi=this.clampPhi(this.targetPhi-.08);break;case"+":case"=":this.targetDistance=this.clampDistance(this.targetDistance*.9);break;case"-":case"_":this.targetDistance=this.clampDistance(this.targetDistance*1.1);break;case"Home":this.resetCamera();break;default:return}this.lastInteractionTime=t(),r.preventDefault()}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=(r,i,n)=>{this[n]&&(r.removeEventListener(i,this[n]),this[n]=null)},t=this.canvas;e(t,"webglcontextlost","boundContextLost"),e(t,"webglcontextrestored","boundContextRestored"),e(t,"contextmenu","boundContextMenu"),e(t,"pointerdown","boundPointerDown"),e(t,"pointermove","boundPointerMove"),e(t,"pointerup","boundPointerUp"),e(t,"wheel","boundWheel"),e(t,"keydown","boundKeyDown"),e(this.container,"setCamera","boundSetCamera"),e(this.container,"resetCamera","boundResetCamera")}raycastFromScreenPoint(e,t){let r=this.canvas,i=r.getBoundingClientRect(),n=r.width||300,s=r.height||300,l=i.width>0?Math.floor((e-i.left)*(n/i.width)):Math.floor(e),o=i.height>0?Math.floor((t-i.top)*(s/i.height)):Math.floor(t);return this.performMeshPick(l,o,!1)}performMeshPick(e,t,r=!0){if(this.meshes.length===0)return null;let i=this.gl,n=Math.max(1,this.canvas.width||300),s=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,n);let l=Se();Ie(l,this.projMatrix,this.viewMatrix);let o=[],a=Math.max(0,Math.min(n-1,e)),u=Math.max(0,Math.min(s-1,s-1-t));if(this.pickFbo&&i&&!this.xrSessionActive){(this.pickFboWidth!==n||this.pickFboHeight!==s)&&this.resizePickingFbo(n,s),i.bindFramebuffer(36160,this.pickFbo),i.viewport(0,0,n,s),i.enable(2929),i.clearColor(0,0,0,0),i.clear(16640),i.useProgram(this.pickProg);for(let M=0;M<this.meshes.length;M++){let P=this.meshes[M];if(P.visible===!1||P.isPluginMesh)continue;let F=M+1,W=(F&255)/255,T=(F>>8&255)/255,E=(F>>16&255)/255;i.uniform4f(this.uPick.uColorId,W,T,E,1),Ie(this.modelMatrix,this.modelRootMatrix,P.transform);let S=P.instanceMatrices;if(S&&S.length>=16){let O=S.length>>4,k=Se();for(let w of P.primitives){i.bindVertexArray(w.vao);for(let ie=0;ie<O;ie++)Ie(k,this.modelMatrix,S.subarray(ie*16,ie*16+16)),Ie(this.mvpMatrix,l,k),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),cr(i,w)}}else{Ie(this.mvpMatrix,l,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let O of P.primitives)i.bindVertexArray(O.vao),cr(i,O)}}let p=new Uint8Array(4);i.readPixels(a,u,1,1,6408,5121,p),i.bindFramebuffer(36160,null);let y=p[0]+(p[1]<<8)+(p[2]<<16);y>0&&y<=this.meshes.length&&(o=[this.meshes[y-1]])}o.length===0&&(o=this.meshes.filter(p=>p.visible!==!1));let h=null,m=1/0,c=[0,0,0],d=[0,1,0],[f,g,x]=Mn(this),b=Se();for(let p of o){Ie(b,this.modelRootMatrix,p.transform);let y=p.instanceMatrices,M=y&&y.length>=16?y.length>>4:1;for(let P=0;P<M;P++){y&&y.length>=16?Ie(this.modelMatrix,b,y.subarray(P*16,P*16+16)):this.modelMatrix.set(b),Ie(this.mvpMatrix,l,this.modelMatrix);let F=Se();if(!en(F,this.mvpMatrix))continue;let W=(a+.5)/n*2-1,T=(u+.5)/s*2-1,E=[0,0,0],S=[0,0,0];Ai(E,W,T,-1,F),Ai(S,W,T,1,F);let O=S[0]-E[0],k=S[1]-E[1],w=S[2]-E[2],ie=Math.hypot(O,k,w)||1,oe=O/ie,I=k/ie,H=w/ie,N={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((z=>{for(let ue of p.primitives){if(!ue.positions)continue;let ce=ue.positions,B=ue.indices,$=Math.floor(B?B.length/3:ce.length/9);for(let _=0;_<$;_++){let G=B?B[_*3]:_*3,j=B?B[_*3+1]:_*3+1,q=B?B[_*3+2]:_*3+2;Go(E[0],E[1],E[2],oe,I,H,ce[G*3],ce[G*3+1],ce[G*3+2],ce[j*3],ce[j*3+1],ce[j*3+2],ce[q*3],ce[q*3+1],ce[q*3+2],N,z)}}})(1e-4),isFinite(N.distance)){let z=N.point[0],ue=N.point[1],ce=N.point[2],B=this.modelMatrix,$=B[0]*z+B[4]*ue+B[8]*ce+B[12],_=B[1]*z+B[5]*ue+B[9]*ce+B[13],G=B[2]*z+B[6]*ue+B[10]*ce+B[14],j=$-f,q=_-g,D=G-x,Y=Math.hypot(j,q,D);if(Y<m){Xe(this.normalMatrix,this.modelMatrix);let te=this.normalMatrix,se=N.normal[0],le=N.normal[1],V=N.normal[2],ee=te[0]*se+te[3]*le+te[6]*V,R=te[1]*se+te[4]*le+te[7]*V,A=te[2]*se+te[5]*le+te[8]*V,L=Math.hypot(ee,R,A)||1;ee/=L,R/=L,A/=L,ee*j+R*q+A*D>0&&(ee=-ee,R=-R,A=-A),h=p,m=Math.round(Y*1e3)/1e3,c=[Math.round($*1e3)/1e3,Math.round(_*1e3)/1e3,Math.round(G*1e3)/1e3],d=[Math.round(ee*1e3)/1e3,Math.round(R*1e3)/1e3,Math.round(A*1e3)/1e3]}}}}if(!h)return null;let v={meshIndex:this.meshes.indexOf(h),meshName:h.name,nodeIndex:h.nodeIndex,distance:m,hitPoint:c,normal:d,screenX:e,screenY:t};if(r){for(let p of Oe)p.onMeshSelect?.(this,v);this.opts.onMeshClick&&this.opts.onMeshClick(v),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:v}))}return v}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let r=Math.max(1,Math.floor(t*.5)),i=e>=r,n=i?e-r:e,s=i?Math.max(1,t-r):r,l=(n+.5)/s*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);rr(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center;Jt(this.viewMatrix,Mn(this),r,[0,1,0]),Ie(this.mvpMatrix,this.projMatrix,this.viewMatrix),Xe(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 Oe)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 Oe)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],n=this.modelRootMatrix;n[0]=e,n[1]=0,n[2]=-t,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=t,n[9]=0,n[10]=e,n[11]=0,n[12]=r-(e*r+t*i),n[13]=0,n[14]=i-(-t*r+e*i),n[15]=1}setVisible(e){this.isVisible=e}update(e){for(let s of Oe)s.onUpdate?.(this,e);let t=typeof performance<"u"?performance.now():Date.now();if(!this.isPointerDown&&this.autoRotate&&t-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*e,this.updateTurntableMatrix();for(let s of Oe)s.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let r=Math.round((this.currTheta*180/Math.PI%360+360)%360),i=Math.round(this.currPhi*180/Math.PI),n=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(n-this.lastReportedZoom)>=.02){this.lastReportedTheta=r,this.lastReportedPhi=i,this.lastReportedZoom=n;let s={theta:r,phi:i,zoom:n,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(s),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:s}))}}renderXRView(e,t,r,i,n=!0,s=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let l=e?.transform?.inverse?.matrix||this.viewMatrix,o=e?.projectionMatrix||this.projMatrix,a=e?.transform?.position,u=a?[a.x,a.y,a.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):r&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:l,projMatrix:o,eyePos:u,viewport:i,eye:e?.eye||"none",clear:s>0?!1:e?.eye!=="right",isAR:n})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let v=Math.max(2,this.canvas.width||2),p=Math.max(1,this.canvas.height||1),y=Math.max(1,Math.floor(v*.5)),M=Math.max(1,v-y),P=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),F=this.customTarget||this.bounds.center,[W,T,E]=Mn(this),S=Math.cos(this.currTheta),O=-Math.sin(this.currTheta),k=.032,w=Se(),ie=Se(),oe=[W-S*k,T,E-O*k],I=[F[0]-S*k*.25,F[1],F[2]-O*k*.25];rr(w,this.fov,y/p,.1,P),Jt(ie,oe,I,[0,1,0]);let H=Se(),N=Se(),z=[W+S*k,T,E+O*k],ue=[F[0]+S*k*.25,F[1],F[2]+O*k*.25];rr(H,this.fov,M/p,.1,P),Jt(N,z,ue,[0,1,0]),this.render({viewMatrix:ie,projMatrix:w,eyePos:oe,viewport:[0,0,y,p],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:N,projMatrix:H,eyePos:z,viewport:[y,0,M,p],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,v,p);return}let t=this.gl,r=0,i=0,n=this.canvas.width,s=this.canvas.height;e?.viewport?(r=e.viewport[0],i=e.viewport[1],n=e.viewport[2],s=e.viewport[3],t.viewport(r,i,n,s)):t.viewport(0,0,this.canvas.width,this.canvas.height),t.enable(2929),(!e||e.clear!==!1)&&(e?.isAR?t.clearColor(0,0,0,0):t.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),t.clear(16640));let l=Se(),o=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=o,Ie(l,e?.projMatrix??this.projMatrix,o);let a=Ae().xrDepthShader,u=Za(this.toneMapping),[h,m,c]=e?e.eyePos:Mn(this);for(let v of Oe)v.onBeforeDrawScene?.(this,t,l,[h,m,c],u);let d=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&d===0)return;let f=e?.eye||"none",g=!1,x=d>0?[...this.backdropMeshes,...this.meshes]:this.meshes,b=v=>{for(let p=0;p<x.length;p++){let y=x[p];if(y.visible===!1)continue;let M=this.selectedMeshName!==""&&y.name===this.selectedMeshName;p<d||y.worldSpace===!0||y.name==="__xr_reticle__"?this.modelMatrix.set(y.transform):Ie(this.modelMatrix,this.modelRootMatrix,y.transform),Ie(this.mvpMatrix,l,this.modelMatrix),Xe(y.normalMatrix,this.modelMatrix);let P=y.extras?.xr?.stereo||y.userData?.xr?.stereo,F=0,W=0,T=1,E=1;P==="sbs"?(T=.5,F=f==="right"?.5:0):P==="ou"&&(E=.5,W=f==="right"?.5:0);for(let S of y.primitives){let O=!!S.isTransmissive;if(!v&&O){g=!0;continue}if(v&&!O)continue;let k=S.customProgram||this.renderProg,w=S.customUniforms||this.uRender;t.useProgram(k),t.vertexAttrib3f(3,0,0,0),w.uInstanced&&t.uniform1i(w.uInstanced,0),t.uniform1i(w.uToneMapping,u),t.uniform1f(w.uEnvIntensity,this.envIntensity),w.uExposure&&t.uniform1f(w.uExposure,this.exposure),t.uniform3f(w.uCameraPos,h,m,c),t.uniform1f(w.uEmissive,M?1:0),t.uniformMatrix4fv(w.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(w.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(w.uNormalMatrix,!1,y.normalMatrix),w.uUvTransform&&t.uniform4f(w.uUvTransform,F,W,T,E),w.uViewportSize&&t.uniform2f(w.uViewportSize,Math.max(1,n),Math.max(1,s)),a?.bind(t,w,this.xrDepthState,o,[r,i,Math.max(1,n),Math.max(1,s)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(w.uEnvironmentMap,4),t.uniform1i(w.uHasEnvironmentMap,1)):t.uniform1i(w.uHasEnvironmentMap,0),this.bindLights(w),w.uSectionEnabled&&t.uniform1i(w.uSectionEnabled,0);for(let oe of Oe)oe.onBeforeDrawPrimitive?.(t,k,S,y,this.worldMatrices||[],this.gltf);t.uniform4fv(w.uBaseColor,S.baseColor),t.uniform1f(w.uMetallic,S.metallic),t.uniform1f(w.uRoughness,S.roughness),w.uClearcoat&&t.uniform2f(w.uClearcoat,S.clearcoat??0,S.clearcoatRoughness??.04),S.texture?(t.activeTexture(33984),t.bindTexture(3553,S.texture),t.uniform1i(w.uBaseColorTexture,0),t.uniform1i(w.uHasTexture,1)):t.uniform1i(w.uHasTexture,0),S.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,S.metallicRoughnessTexture),t.uniform1i(w.uMetallicRoughnessTexture,1),t.uniform1i(w.uHasMetallicRoughnessTexture,1)):t.uniform1i(w.uHasMetallicRoughnessTexture,0),S.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,S.normalTexture),t.uniform1i(w.uNormalTexture,2),t.uniform1i(w.uHasNormalTexture,1),t.uniform1f(w.uNormalScale,S.normalScale)):t.uniform1i(w.uHasNormalTexture,0),S.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,S.occlusionTexture),t.uniform1i(w.uOcclusionTexture,3),t.uniform1i(w.uHasOcclusionTexture,1),t.uniform1f(w.uOcclusionStrength,S.occlusionStrength)):t.uniform1i(w.uHasOcclusionTexture,0),t.bindVertexArray(S.vao);let ie=y.instanceMatrices;if(S.instanceCount!==void 0)t.drawElementsInstanced(4,S.indexCount,S.indexType,0,S.instanceCount);else if(ie&&ie.length>=16&&S.instanced&&w.uInstanced&&w.uViewProj){let oe=ie.length>>4;t.uniform1i(w.uInstanced,1),t.uniformMatrix4fv(w.uViewProj,!1,l),S.indices?t.drawElementsInstanced(4,S.indexCount,S.indexType,0,oe):t.drawArraysInstanced(4,0,S.indexCount,oe),t.uniform1i(w.uInstanced,0)}else if(ie&&ie.length>=16){let oe=ie.length>>4,I=y.instanceColors,H=Se(),N=new Float32Array(9),z=[S.baseColor[0],S.baseColor[1],S.baseColor[2],S.baseColor[3]];for(let ue=0;ue<oe;ue++)Ie(H,this.modelMatrix,ie.subarray(ue*16,ue*16+16)),Ie(this.mvpMatrix,l,H),Xe(N,H),t.uniformMatrix4fv(w.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(w.uModel,!1,H),t.uniformMatrix3fv(w.uNormalMatrix,!1,N),I&&(z[0]=S.baseColor[0]*I[ue*3],z[1]=S.baseColor[1]*I[ue*3+1],z[2]=S.baseColor[2]*I[ue*3+2],z[3]=S.baseColor[3],t.uniform4fv(w.uBaseColor,z)),cr(t,S)}else cr(t,S)}}};if(b(!1),g){for(let v of Oe)v.onBeforeTransmissivePass?.(t,this);b(!0)}for(let v of Oe)v.onAfterRender?.(t,this,l,e?.eye??"none",[r,i,n,s],e?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(e,t){ls(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 Oe)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()}};Ke.registerPlugin=Ve,Ke.getRegisteredPlugins=tr;function cc(e){return e+3&-4}var Me=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t;function fs(e,t){let r=t,i=1;for(;e.has(r);)r=`${t}_${i++}`;return e.add(r),r}function ds(e,t=0){let[r,i,n,,s,l,o,,a,u,h,,m,c,d]=Array.from({length:15},(N,z)=>Me(e[t+z],z%5===0?1:0)),f=Math.hypot(r,i,n),g=Math.hypot(s,l,o),x=Math.hypot(a,u,h);r*(l*h-u*o)-s*(i*h-u*n)+a*(i*o-l*n)<0&&(f=-f);let b=Math.abs(f)>1e-8?1/f:0,v=Math.abs(g)>1e-8?1/g:0,p=Math.abs(x)>1e-8?1/x:0,y=r*b,M=i*b,P=n*b,F=s*v,W=l*v,T=o*v,E=a*p,S=u*p,O=h*p,k=y+W+O,w=0,ie=0,oe=0,I=1;if(k>0){let N=.5/Math.sqrt(k+1);I=.25/N,w=(T-S)*N,ie=(E-P)*N,oe=(M-F)*N}else if(y>W&&y>O){let N=2*Math.sqrt(Math.max(0,1+y-W-O));N>1e-8&&(I=(T-S)/N,w=.25*N,ie=(F+M)/N,oe=(E+P)/N)}else if(W>O){let N=2*Math.sqrt(Math.max(0,1+W-y-O));N>1e-8&&(I=(E-P)/N,w=(F+M)/N,ie=.25*N,oe=(T+S)/N)}else{let N=2*Math.sqrt(Math.max(0,1+O-y-W));N>1e-8&&(I=(M-F)/N,w=(E+P)/N,ie=(T+S)/N,oe=.25*N)}let H=Math.hypot(w,ie,oe,I);return H>1e-8&&Number.isFinite(H)?(w/=H,ie/=H,oe/=H,I/=H):(w=0,ie=0,oe=0,I=1),{t:[m,c,d],r:[w,ie,oe,I],s:[f,g,x]}}function uc(e){let t={};return e.grab&&(t.interactable={mode:typeof e.grab=="string"?e.grab:"2-hand"},t.movable={scaleInZ:!!e.scale,minScale:typeof e.scale=="object"?e.scale.min??.1:.1,maxScale:typeof e.scale=="object"?e.scale.max??10:10}),e.billboard&&(t.billboard={mode:typeof e.billboard=="string"?e.billboard:"capsule"}),e.follow&&(t.follow={target:typeof e.follow=="object"?e.follow.mode??"head":e.follow}),e.anchor&&(t.anchor={plane:e.anchor}),e.physics&&e.physics!=="none"&&(t.rigidbody={type:e.physics}),t}var It=(e,t,r,i)=>typeof e=="number"&&Number.isFinite(e)?Math.max(t,Math.min(r,e)):i;function hs(e){let t=e?.audioEmitter??e?.spatialAudio??(typeof e?.audio=="object"&&e.audio&&("preset"in e.audio||"distanceModel"in e.audio||"coneInnerAngle"in e.audio||"maxDistance"in e.audio||"volume"in e.audio)?e.audio:typeof e?.audio=="string"&&/^(hum|reactor|wind|beacon|geiger|chimeLoop|machinery|water)$/.test(e.audio)?{preset:e.audio}:void 0);if(!t||typeof t=="object"&&t.enabled===!1)return null;let r=typeof t=="string"?{preset:t}:t,i=typeof r.src=="string"&&!/[\x00-\x20\\%]|^\s*(javascript|data|file|http):/i.test(r.src)?r.src:void 0,n=typeof r.preset=="string"?r.preset:void 0;return!i&&!n?null:{ae:r,src:i,preset:n,volume:It(r.volume,0,2,.6),loop:typeof r.loop=="boolean"?r.loop:!0,isGlobal:r.type==="global"||r.positional===!1}}function rn(e,t){return ps(e,t)[0]}function ps(e,t){e.updateMatrixWorld(!0);let r=[],i=0,n=[],s=[],l=[],o=[],a=new Set,u=[],h=[],m=new Map,c=[],d=[],f=[],g=new Map,x=[],b=[];function v(I){let H=m.get(I);if(H!==void 0)return H;H=h.length,m.set(I,H);let N=I,z=N.color?.r??1,ue=N.color?.g??1,ce=N.color?.b??1,B=N.opacity??1,$={baseColorFactor:[z,ue,ce,B],metallicFactor:N.metalness??0,roughnessFactor:N.roughness??.5},_={},G=ee=>{if(!ee)return;let R=(typeof ee=="string"?ee:typeof ee.source=="string"?ee.source:typeof ee.image=="string"?ee.image:"").trim();if(!R||/[\x00-\x1f\x7f\\]|\.\./.test(R)||!(/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(R)||!R.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(R)))return;let A=g.get(R);if(A===void 0){let L=c.length;c.push({uri:R}),d.length===0&&d.push({magFilter:9729,minFilter:9987,wrapS:10497,wrapT:10497}),A=f.length,f.push({sampler:0,source:L}),g.set(R,A)}return{index:A}},j=G(N.map);j&&($.baseColorTexture=j);let q=G(N.roughnessMap||N.metalnessMap);q&&($.metallicRoughnessTexture=q);let D=N.map?.avgColor;Array.isArray(D)&&D.length>=3&&(_.avgColor=[D[0],D[1],D[2]]);let Y=G(N.normalMap),te=G(N.emissiveMap),se=G(N.aoMap),le={name:N.name||"",pbrMetallicRoughness:$,doubleSided:N.side===2||!!N.doubleSided,...Y?{normalTexture:Y}:{},...te?{emissiveTexture:te}:{},...se?{occlusionTexture:se}:{},...Object.keys(_).length>0?{extras:_}:{}};if(N.emissive&&(N.emissive.r>0||N.emissive.g>0||N.emissive.b>0)){let ee=N.emissiveIntensity??1;le.emissiveFactor=[N.emissive.r*ee,N.emissive.g*ee,N.emissive.b*ee]}let V={};return N.clearcoat&&N.clearcoat>0&&(V.KHR_materials_clearcoat={clearcoatFactor:N.clearcoat,clearcoatRoughnessFactor:N.clearcoatRoughness||0}),N.sheen&&N.sheen>0&&(V.KHR_materials_sheen={sheenColorFactor:N.sheenColor?[N.sheenColor.r,N.sheenColor.g,N.sheenColor.b]:[1,1,1],sheenRoughnessFactor:N.sheenRoughness||0}),N.transmission&&N.transmission>0&&(V.KHR_materials_transmission={transmissionFactor:N.transmission}),N.thickness&&N.thickness>0&&(V.KHR_materials_volume={thicknessFactor:N.thickness,attenuationDistance:N.attenuationDistance??1/0,attenuationColor:N.attenuationColor?[N.attenuationColor.r,N.attenuationColor.g,N.attenuationColor.b]:[1,1,1]}),N.ior!==void 0&&N.ior!==1.5&&(V.KHR_materials_ior={ior:N.ior}),N.dispersion&&N.dispersion>0&&(V.KHR_materials_dispersion={dispersion:N.dispersion}),N.iridescence&&N.iridescence>0&&(V.KHR_materials_iridescence={iridescenceFactor:N.iridescence,iridescenceIor:N.iridescenceIOR??1.3}),Object.keys(V).length>0&&(le.extensions=V),h.push(le),H}function p(I,H){let N=new Uint8Array(I.buffer,I.byteOffset,I.byteLength),z=cc(N.byteLength),ue=new Uint8Array(z);ue.set(N),r.push(ue);let ce=n.length;return n.push({buffer:0,byteOffset:i,byteLength:N.byteLength,target:H}),i+=z,ce}function y(I,H,N,z,ue,ce,B){let $=p(I,N),_=s.length,G={bufferView:$,byteOffset:0,componentType:z,count:ue,type:H};return ce&&(G.min=ce),B&&(G.max=B),s.push(G),_}e.traverse(I=>{if(I.isLight||I.color&&I.intensity!==void 0){let H=I.matrixWorld?.elements,N=Me(H?H[12]:I.position?.x,0),z=Me(H?H[13]:I.position?.y,0),ue=Me(H?H[14]:I.position?.z,0),ce=I.target,B=ce?.parent?ce?.matrixWorld?.elements:void 0,$=Me(B?B[12]:ce?.position?.x,0),_=Me(B?B[13]:ce?.position?.y,0),G=Me(B?B[14]:ce?.position?.z,0),j=$-N,q=_-z,D=G-ue,Y=Math.hypot(j,q,D),te=Math.max(.01,Math.min(Math.PI/2,Me(I.angle,Math.PI/3))),se=Math.max(0,Math.min(1,Me(I.penumbra,0)));b.push({type:I.type,color:[I.color.r,I.color.g,I.color.b],intensity:I.intensity,position:[N,z,ue],...I.type==="spot"?{direction:Y>1e-6?[j/Y,q/Y,D/Y]:[0,-1,0],outerConeAngle:te,innerConeAngle:Math.max(0,te*(1-se)),range:Math.max(0,Me(I.distance,0))}:I.type==="point"?{range:Math.max(0,Me(I.distance,0))}:{}})}});let M=[],P=new Set([e]),F=[];if(Array.isArray(e.children))for(let I=e.children.length-1;I>=0;I--)F.push({obj:e.children[I],parentKids:M});for(;F.length>0;){let{obj:I,parentKids:H}=F.pop();if(!I||typeof I!="object"||P.has(I))continue;P.add(I),I._bakeAuthorGeometry?.(),Ae().materializeDeclarativeGeometry?.(I);let N=!!(I.userData&&(I.userData.xr&&typeof I.userData.xr=="object"&&Object.keys(I.userData.xr).length>0||I.userData.interactivity&&typeof I.userData.interactivity=="object"&&Object.keys(I.userData.interactivity).length>0)),z={name:I.name||(N?`Node_${o.length}`:"")},ue=Me(I.position?.x,0),ce=Me(I.position?.y,0),B=Me(I.position?.z,0),$=Me(I.quaternion?.x,0),_=Me(I.quaternion?.y,0),G=Me(I.quaternion?.z,0),j=Me(I.quaternion?.w,1),q=Me(I.scale?.x,1),D=Me(I.scale?.y,1),Y=Me(I.scale?.z,1);if((ue||ce||B)&&(z.translation=[ue,ce,B]),($||_||G||j!==1)&&(z.rotation=[$,_,G,j]),(q!==1||D!==1||Y!==1)&&(z.scale=[q,D,Y]),I.visible===!1&&(z.extensions={...z.extensions||{},KHR_node_visibility:{visible:!1}},a.add("KHR_node_visibility")),I.userData&&Object.keys(I.userData).length>0&&(z.extras=JSON.parse(JSON.stringify(I.userData,(le,V)=>{if(!(le==="__proto__"||le==="prototype"||le==="constructor"))return typeof V=="function"?void 0:V})),I.userData.xr)){let le=uc(I.userData.xr);z.extensions={...z.extensions||{},MOZ_hubs_components:le,ANDROID_xr_scenecore:le},Ae().xrTraitSerializer?.gltfNode(z,I.userData.xr),a.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(I.geometry){let le=I.geometry,V=le.attributes.position;if(V&&V.count>0){let ee=[1/0,1/0,1/0],R=[-1/0,-1/0,-1/0];for(let X=0;X<V.count;X++){let Z=V.getX(X),J=V.getY(X),K=V.getZ(X);Z<ee[0]&&(ee[0]=Z),Z>R[0]&&(R[0]=Z),J<ee[1]&&(ee[1]=J),J>R[1]&&(R[1]=J),K<ee[2]&&(ee[2]=K),K>R[2]&&(R[2]=K)}let A={attributes:{POSITION:y(V.array,"VEC3",34962,5126,V.count,ee,R)}};if(le.attributes.normal&&(A.attributes.NORMAL=y(le.attributes.normal.array,"VEC3",34962,5126,le.attributes.normal.count)),le.attributes.uv&&(A.attributes.TEXCOORD_0=y(le.attributes.uv.array,"VEC2",34962,5126,le.attributes.uv.count)),le.index){let X=le.index.array instanceof Uint32Array;A.indices=y(le.index.array,"SCALAR",34963,X?5125:5123,le.index.count)}let L=Array.isArray(I.material)?I.material[0]:I.material;L&&(A.material=v(L));let C=I.userData?.variants;if(C&&typeof C=="object"){let X=new Map;for(let Z of Object.keys(C)){if(!Z||Z==="__proto__"||Z==="constructor"||Z==="prototype")continue;let J=C[Z];if(!J||typeof J!="object")continue;let K=x.indexOf(Z);if(K===-1&&x.length<256&&(K=x.length,x.push(Z)),K===-1)continue;let ae=v(J),ne=X.get(ae);ne||(ne=[],X.set(ae,ne)),ne.push(K)}if(X.size>0){let Z=[];for(let[J,K]of X.entries())Z.push({material:J,variants:K});A.extensions={...A.extensions||{},KHR_materials_variants:{mappings:Z}},a.add("KHR_materials_variants")}}let U=I;if(U.isInstancedMesh&&typeof U.count=="number"&&U.count>0&&U.instanceMatrix?.array){let X=Math.min(1e4,Math.floor(U.count)),Z=U.instanceMatrix.array,J=new Float32Array(X*3),K=new Float32Array(X*4),ae=new Float32Array(X*3);for(let re=0;re<X;re++){let{t:me,r:fe,s:ye}=ds(Z,re*16);J[re*3]=me[0],J[re*3+1]=me[1],J[re*3+2]=me[2],K[re*4]=fe[0],K[re*4+1]=fe[1],K[re*4+2]=fe[2],K[re*4+3]=fe[3],ae[re*3]=ye[0],ae[re*3+1]=ye[1],ae[re*3+2]=ye[2]}let ne={TRANSLATION:y(J,"VEC3",0,5126,X),ROTATION:y(K,"VEC4",0,5126,X),SCALE:y(ae,"VEC3",0,5126,X)};if(U.instanceColor?.array&&U.instanceColor.array.length>=X*3){let re=new Float32Array(U.instanceColor.array.subarray(0,X*3));ne._COLOR_0=y(re,"VEC3",0,5126,X)}z.extensions={...z.extensions||{},EXT_mesh_gpu_instancing:{attributes:ne}},a.add("EXT_mesh_gpu_instancing")}let Q=l.length;l.push({primitives:[A],name:I.name,...z.extras?{extras:z.extras}:{}}),z.mesh=Q}}let te=o.length;o.push(z),u.push(I),H.push(te);let se=I.children;if(Array.isArray(se)&&se.length>0){let le=[];z.children=le;for(let V=se.length-1;V>=0;V--)F.push({obj:se[V],parentKids:le})}}for(let I=0;I<o.length;I++){let H=o[I];H.children&&H.children.length===0?delete H.children:H.children&&H.children.length>0&&(H.extras?.xr?.lod||H.extensions?.ANDROID_xr_scenecore?.lod||u[I]?.isLOD)&&(H.extensions={...H.extensions||{},MSFT_lod:{ids:[...H.children]}},a.add("MSFT_lod"))}let W=t?.animateCallback||t?.animateFn||(typeof e.userData?.animate=="function"?e.userData.animate:typeof e.__animateFn=="function"?e.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0),T=[];if(typeof W=="function"&&u.length>0){let I=t?.duration??4,H=t?.fps??15,N=Math.max(2,Math.round(I*H)+1),z=new Float32Array(N),ue=u.map(D=>[Me(D.position?.x,0),Me(D.position?.y,0),Me(D.position?.z,0),Me(D.quaternion?.x,0),Me(D.quaternion?.y,0),Me(D.quaternion?.z,0),Me(D.quaternion?.w,1),Me(D.scale?.x,1),Me(D.scale?.y,1),Me(D.scale?.z,1)]),ce=u.map(()=>new Float32Array(N*3)),B=u.map(()=>new Float32Array(N*4)),$=u.map(()=>new Float32Array(N*3));for(let D=0;D<N;D++){let Y=D/(N-1)*I;z[D]=Y;try{W(Y)}catch{}for(let te=0;te<u.length;te++){let se=u[te];ce[te][D*3]=Me(se.position?.x,0),ce[te][D*3+1]=Me(se.position?.y,0),ce[te][D*3+2]=Me(se.position?.z,0);let le=Me(se.quaternion?.x,0),V=Me(se.quaternion?.y,0),ee=Me(se.quaternion?.z,0),R=Me(se.quaternion?.w,1),A=Math.hypot(le,V,ee,R)||1;if(le/=A,V/=A,ee/=A,R/=A,D>0){let L=(D-1)*4,C=B[te];C[L]*le+C[L+1]*V+C[L+2]*ee+C[L+3]*R<0&&(le=-le,V=-V,ee=-ee,R=-R)}B[te][D*4]=le,B[te][D*4+1]=V,B[te][D*4+2]=ee,B[te][D*4+3]=R,$[te][D*3]=Me(se.scale?.x,1),$[te][D*3+1]=Me(se.scale?.y,1),$[te][D*3+2]=Me(se.scale?.z,1)}}for(let D=0;D<u.length;D++){let Y=u[D],te=ue[D];Y.position?.set(te[0],te[1],te[2]),Y.quaternion?.set(te[3],te[4],te[5],te[6]),Y.scale?.set(te[7],te[8],te[9])}e.updateMatrixWorld(!0);let _=null,G=()=>(_===null&&(_=y(z,"SCALAR",0,5126,N,[0],[I])),_),j=[],q=[];for(let D=0;D<u.length;D++){let Y=ue[D],te=(le,V,ee)=>le.some((R,A)=>Math.abs(R-Y[ee+A%V])>1e-4),se=(le,V,ee,R)=>{le&&q.push({sampler:j.push({input:G(),interpolation:"LINEAR",output:y(V,ee,0,5126,N)})-1,target:{node:D,path:R}})};se(te(ce[D],3,0),ce[D],"VEC3","translation"),se(te(B[D],4,3),B[D],"VEC4","rotation"),se(te($[D],3,7),$[D],"VEC3","scale")}q.length>0&&T.push({name:"ProceduralLoop",samplers:j,channels:q})}let E=Uo(o,l,e.userData),S=[],O=[],k=[];for(let I=0;I<o.length;I++){let H=o[I],N=hs(H.extras?.xr);if(!N)continue;let{ae:z,src:ue,preset:ce,volume:B,loop:$,isGlobal:_}=N,G=H.name||`Node_${I}`,j=O.length;O.push({name:`${G}_source`,gain:B,loop:$,autoPlay:typeof z.autoplay=="boolean"?z.autoplay:!0,...ue!==void 0?{audio:S.push({uri:ue})-1}:{},...ce?{extras:{preset:ce,pitch:It(z.pitch,.25,4,1)}}:{}});let q=k.length,D=It(z.refDistance,.05,100,1),Y=It(z.coneInnerAngle,0,360,360),te=It(z.coneOuterAngle,Y,360,360);k.push({name:`${G}_emitter`,type:_?"global":"positional",gain:B,sources:[j],..._?{}:{positional:{distanceModel:z.distanceModel==="linear"||z.distanceModel==="exponential"?z.distanceModel:"inverse",refDistance:D,maxDistance:It(z.maxDistance,D,500,Math.max(D,25)),rolloffFactor:It(z.rolloffFactor,0,10,1),coneInnerAngle:+(Y*Math.PI/180).toFixed(6),coneOuterAngle:+(te*Math.PI/180).toFixed(6),coneOuterGain:It(z.coneOuterGain,0,1,0)}}}),H.extensions={...H.extensions||{},KHR_audio_emitter:{emitter:q}},a.add("KHR_audio_emitter")}let w={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:e.environmentIntensity}},scenes:[{nodes:M}],scene:0,nodes:o,meshes:l,materials:h,...c.length>0?{images:c}:{},...d.length>0?{samplers:d}:{},...f.length>0?{textures:f}:{},accessors:s,bufferViews:n,buffers:[{byteLength:i}],...T.length>0?{animations:T}:{},...E||a.size>0?{extensionsUsed:[...E?["KHR_interactivity"]:[],...a]}:{},...E||x.length>0||k.length>0?{extensions:{...E?{KHR_interactivity:E}:{},...x.length>0?{KHR_materials_variants:{variants:x.map(I=>({name:I}))}}:{},...k.length>0?{KHR_audio_emitter:{...S.length>0?{audio:S}:{},sources:O,emitters:k}}:{}}}:{}},ie=new Uint8Array(i),oe=0;for(let I of r)ie.set(I,oe),oe+=I.byteLength;return[{gltf:w,bin:ie.buffer,lights:b,environmentIntensity:e.environmentIntensity},u]}function Ui(e){return new TextEncoder().encode(e)}function Tn(e,t){let{gltf:r,bin:i}=rn(e,t),n=JSON.stringify(r),s=Ui(n),l=(4-s.byteLength%4)%4,o=s.byteLength+l,a=20+o+8+i.byteLength,u=new Uint8Array(a),h=new DataView(u.buffer);h.setUint32(0,1179937895,!0),h.setUint32(4,2,!0),h.setUint32(8,a,!0),h.setUint32(12,o,!0),h.setUint32(16,1313821514,!0),u.set(s,20);for(let c=0;c<l;c++)u[20+s.byteLength+c]=32;let m=20+o;return h.setUint32(m,i.byteLength,!0),h.setUint32(m+4,5130562,!0),u.set(new Uint8Array(i),m+8),u}function lc(e,t){let[r,i]=ps(e,t);return bs(r,i)}function bs(e,t){let r=[],i=e.gltf,n=Ae().decoders.get("meshopt");n&&typeof n.decodeBufferViews=="function"&&n.decodeBufferViews(i,e);let s=e.bin,l=s instanceof ArrayBuffer?s:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),o=i.accessors||[],a=i.bufferViews||[],u=i.materials||[],h=i.meshes||[],m=i.nodes||[],c=i.textures||[],d=i.images||[],f=i.samplers||[],g=new Set,x=u.map((P,F)=>fs(g,fr(P?.name,`Material_${F}`))),b=new Map;function v(P){let F=/^data:image\/(png|jpe?g)(?:;[^,]*)?;base64,([A-Za-z0-9+/=\s]+)$/i.exec(P);if(!F)return null;let W=F[2].replace(/\s+/g,""),T=W.endsWith("==")?2:W.endsWith("=")?1:0,E=new Uint8Array((W.length*3>>2)-T),S=k=>{let w=W.charCodeAt(k);return w>96?w-71:w>64?w-65:w>47?w+4:w===43?62:w===47?63:0},O=0;for(let k=0;k<W.length;k+=4){let w=S(k)<<18|S(k+1)<<12|S(k+2)<<6|S(k+3);E[O++]=w>>16&255,O<E.length&&(E[O++]=w>>8&255),O<E.length&&(E[O++]=w&255)}return E}function p(P,F,W){let T=P?.index;if(typeof T!="number")return;let E=c[T],S=E?.source;if(typeof S!="number"||!d[S])return;let O=b.get(S);if(O===void 0){O=null;let ie=d[S],oe=null;if(typeof ie.bufferView=="number"){let I=a[ie.bufferView],H=I?.byteOffset||0,N=I?.byteLength||0;I&&N>0&&H>=0&&H+N<=l.byteLength&&(oe=new Uint8Array(l,H,N))}else typeof ie.uri=="string"&&(oe=v(ie.uri));if(oe&&oe.byteLength>0){let I=oe[0]===255&&oe[1]===216&&oe[2]===255||!(oe[0]===137&&oe[1]===80)&&/jpe?g/i.test(ie.mimeType||ie.uri||"");O={file:`texture_${S}.${I?"jpg":"png"}`,data:oe}}b.set(S,O)}if(!O)return;let k=typeof E.sampler=="number"?f[E.sampler]:void 0,w=ie=>ie===33071?"clamp":ie===33648?"mirror":"repeat";return{file:O.file,data:O.data,wrapS:w(k?.wrapS),wrapT:w(k?.wrapT),...F?{scale:F}:{},...W?{bias:W}:{}}}function y(P){let F=o[P];if(!F)throw new Error(`Accessor ${P} not found`);let W=a[F.bufferView||0],T=(W.byteOffset||0)+(F.byteOffset||0),E=W.byteLength||0;return{acc:F,buffer:l.slice(T,T+E)}}function M(P,F,W,T){let E=[],S=h[P];if(!S)return E;let O=S.primitives||[];for(let k=0;k<O.length;k++){let w=O[k],ie=w.attributes?.POSITION;if(ie===void 0)continue;let{acc:oe,buffer:I}=y(ie),H=new Float32Array(I,0,oe.count*3),N,z=w.attributes?.NORMAL;if(z!==void 0){let{acc:V,buffer:ee}=y(z),R=new Float32Array(ee,0,V.count*3);N=new Float32Array(R.length);for(let A=0;A<V.count;A++){let L=R[A*3],C=R[A*3+1],U=R[A*3+2],Q=Math.hypot(L,C,U)||1;N[A*3]=L/Q,N[A*3+1]=C/Q,N[A*3+2]=U/Q}}let ue,ce=w.attributes?.TEXCOORD_0;if(ce!==void 0){let{acc:V,buffer:ee}=y(ce);ue=new Float32Array(ee,0,V.count*2)}let B;if(w.indices!==void 0){let{acc:V,buffer:ee}=y(w.indices);B=V.componentType===5125?new Uint32Array(ee,0,V.count):new Uint16Array(ee,0,V.count);let R=oe.count;for(let A of B)if(A>=R)throw new Error(`SecurityError: Index buffer value (${A}) out of vertex bounds [0, ${R}).`)}else{let V=oe.count;B=V>65535?new Uint32Array(V):new Uint16Array(V);for(let ee=0;ee<V;ee++)B[ee]=ee}let $="DefaultMaterial",_=[1,1,1],G=.5,j=0,q=0,D=0,Y=1.5,te=1,se=[0,0,0],le;if(w.material!==void 0&&u[w.material]){let V=u[w.material];$=x[w.material]||`Material_${w.material}`;let ee=V.pbrMetallicRoughness||{},R=(me,fe)=>Array.isArray(me)&&me.length>=3?[me[0],me[1],me[2]]:fe;_=R(ee.baseColorFactor,[1,1,1]);let A=Array.isArray(ee.baseColorFactor)&&typeof ee.baseColorFactor[3]=="number"?ee.baseColorFactor[3]:1,L=_[0]!==1||_[1]!==1||_[2]!==1||A!==1,C=p(ee.baseColorTexture,L?[_[0],_[1],_[2],A]:void 0),U=V.extras?.avgColor;!C&&Array.isArray(U)&&U.length>=3&&(_=[_[0]*U[0],_[1]*U[1],_[2]*U[2]]),typeof ee.roughnessFactor=="number"&&(G=ee.roughnessFactor),typeof ee.metallicFactor=="number"&&(j=ee.metallicFactor);let Q=typeof ee.roughnessFactor=="number"?ee.roughnessFactor:1,X=typeof ee.metallicFactor=="number"?ee.metallicFactor:1,Z=p(ee.metallicRoughnessTexture,Q!==1||X!==1?[1,Q,X,1]:void 0);se=R(V.emissiveFactor,[0,0,0]);let J=(se[0]>0||se[1]>0||se[2]>0)&&(se[0]!==1||se[1]!==1||se[2]!==1)?[se[0],se[1],se[2],1]:void 0,K=p(V.emissiveTexture,J),ae=p(V.normalTexture,[2,2,2,1],[-1,-1,-1,0]),ne=p(V.occlusionTexture);(C||Z||ae||K||ne)&&(le=[C,Z,ae,K,ne]);let re=V.extensions||{};re.KHR_materials_clearcoat&&(q=re.KHR_materials_clearcoat.clearcoatFactor??0,D=re.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),typeof re.KHR_materials_ior?.ior=="number"&&(Y=re.KHR_materials_ior.ior),te=A*(1-(re.KHR_materials_transmission?.transmissionFactor??0))}E.push({name:O.length>1?`${F}_p${k}`:F,positions:H,indices:B,normals:N,uvs:ue,materialName:$,color:_,roughness:G,metallic:j,clearcoat:q,clearcoatRoughness:D,ior:Y,opacity:te,emissiveColor:se,...le?{textures:le}:{},xrTraits:W||S.extras?.xr,...T?{invisible:!0}:{}})}return E}if(m.length>0){let P=new Float32Array(0),F=new Uint16Array(0),W=(H,N)=>{if(H===void 0)return null;let{acc:z,buffer:ue}=y(H);return new Float32Array(ue,0,z.count*N)},T=(H,N)=>Array.isArray(H)&&H.length>=3?[Me(H[0],N),Me(H[1],N),Me(H[2],N)]:[N,N,N],E=(H,N,z)=>H&&H.length>=(N+1)*3?[H[N*3],H[N*3+1],H[N*3+2]]:z,S=(H,N,z)=>H&&H.length>=(N+1)*4?[H[N*4],H[N*4+1],H[N*4+2],H[N*4+3]]:z,O=new Map,k=i.animations?.[0];if(k&&Array.isArray(k.channels)&&Array.isArray(k.samplers))for(let H of k.channels){let N=k.samplers[H?.sampler],z=H?.target?.node,ue=H?.target?.path;if(!N||typeof z!="number"||N.input===void 0)continue;let ce=O.get(z);ce||(ce={input:N.input},O.set(z,ce)),ue==="translation"?ce.t=N.output:ue==="rotation"?ce.r=N.output:ue==="scale"&&(ce.s=N.output)}let w=i.scenes?.[i.scene??0]?.nodes??[];if(!Array.isArray(w)||w.length===0){let H=new Set;for(let N of m)if(Array.isArray(N?.children))for(let z of N.children)H.add(z);w=[];for(let N=0;N<m.length;N++)H.has(N)||w.push(N);w.length===0&&(w=[0])}let ie=new Set,oe=[],I=(H,N)=>{if(Array.isArray(H))for(let z=H.length-1;z>=0;z--)oe.push({idx:H[z],out:N})};for(I(w,r);oe.length>0;){let{idx:H,out:N}=oe.pop();if(typeof H!="number"||H<0||H>=m.length||ie.has(H))continue;ie.add(H);let z=m[H];if(!z)continue;let ue=[0,0,0],ce=[0,0,0,1],B=[1,1,1];if(Array.isArray(z.matrix)&&z.matrix.length===16){let te=ds(z.matrix);ue=te.t,ce=te.r,B=te.s}else ue=T(z.translation,0),Array.isArray(z.rotation)&&z.rotation.length>=4&&(ce=[Me(z.rotation[0],0),Me(z.rotation[1],0),Me(z.rotation[2],0),Me(z.rotation[3],1)]),B=T(z.scale,1);let $,_=O.get(H);if(_){let te=W(_.input,1);if(te&&te.length>0){let se=W(_.t,3),le=W(_.r,4),V=W(_.s,3),ee=Array.from(te),R=[],A=[],L=[];for(let C=0;C<te.length;C++)R.push(E(se,C,ue)),A.push(S(le,C,ce)),L.push(E(V,C,B));$={times:ee,translations:R,rotations:A,scales:L}}}let G=Array.isArray(z.children)?z.children:[],j=typeof z.mesh=="number"&&z.mesh>=0&&z.mesh<h.length,q=t?.[H]?.userData?.xr??z.extras?.xr;if(!j&&G.length===0&&(z.camera!==void 0||z.extensions?.KHR_lights_punctual||!z.name&&!z.extras&&!q&&!$))continue;let D=(te,se,le)=>({name:te,positions:P,indices:F,isXform:!0,xrTraits:q,timeSamples:$,translation:ue,rotation:ce,scale:B,children:se,...le?{invisible:!0}:{}}),Y=z.visible===!1||z.extensions?.KHR_node_visibility?.visible===!1||t?.[H]?.visible===!1;if(j){let te=z.name||h[z.mesh]?.name||`Mesh_${H}`,se=M(z.mesh,te,q,Y),le=z.extensions?.EXT_mesh_gpu_instancing?.attributes;if(le&&typeof le=="object"&&se.length>0){let V=W(le.TRANSLATION,3),ee=W(le.ROTATION,4),R=W(le.SCALE,3),A=W(le._COLOR_0,3),L=Math.min(1e3,V?V.length/3:ee?ee.length/4:R?R.length/3:0);if(L>0){let C=[];for(let U=0;U<L;U++){let Q=E(V,U,[0,0,0]),X=S(ee,U,[0,0,0,1]),Z=E(R,U,[1,1,1]);for(let J of se){let K=J.color||[.8,.8,.8],ae=A&&A.length>=(U+1)*3;C.push({...J,name:`${J.name}_${U}`,materialName:ae?`${J.materialName}_inst_${U}`:J.materialName,color:ae?[K[0]*A[U*3],K[1]*A[U*3+1],K[2]*A[U*3+2]]:J.color,translation:Q,rotation:X,scale:Z})}}I(G,C),N.push(D(te,C,Y));continue}}if(se.length===1)se[0].translation=ue,se[0].rotation=ce,se[0].scale=B,se[0].timeSamples=$,G.length>0&&(se[0].children=[],I(G,se[0].children)),N.push(se[0]);else{let V=[...se];I(G,V),N.push(D(te,V,Y))}}else{let te=[];I(G,te),N.push(D(z.name||`Group_${H}`,te,Y))}}}else for(let P=0;P<h.length;P++){let F=h[P].name||`Mesh_${P}`;r.push(...M(P,F,h[P].extras?.xr))}return r}function fr(e,t){if(!e||typeof e!="string")return t;let r=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(r)&&(r="_"+r),r||t}function ur(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function je(e){if(!Number.isFinite(e)||Math.abs(e)<1e-7)return"0";let t=Number(e.toFixed(5)).toString();return t.indexOf(".")===-1?`${t}.0`:t}var At=(e,t,r)=>`(${je(e)}, ${je(t)}, ${je(r)})`,lr=(e,t,r,i)=>`(${je(e)}, ${je(t)}, ${je(r)}, ${je(i)})`;function ms(e){let t=e.length/3,r=new Array(t);for(let i=0;i<t;i++)r[i]=At(e[i*3],e[i*3+1],e[i*3+2]);return r.join(", ")}function mc(e,t){let r=new Array(t);for(let i=0;i<t;i++)r[i]=`(${je(e[i*2])}, ${je(1-e[i*2+1])})`;return r.join(", ")}function fc(e){return Array.from(e).join(", ")}function dc(e){let t=new Map,r=0,i=null,n=[...e];for(;n.length>0;){let f=n.pop();if(!f.isXform&&f.positions&&f.positions.length>0){let g=fr(f.materialName,"DefaultMaterial");t.has(g)||t.set(g,{color:f.color||[1,1,1],roughness:f.roughness??.5,metallic:f.metallic??0,clearcoat:f.clearcoat??0,clearcoatRoughness:f.clearcoatRoughness??0,ior:f.ior??1.5,opacity:f.opacity??1,emissiveColor:f.emissiveColor||[0,0,0],textures:f.textures})}if(f.timeSamples&&f.timeSamples.times.length>0){let g=f.timeSamples.times[f.timeSamples.times.length-1];g>r&&(r=g)}if(f.xrTraits?.anchor&&!i&&(i=f.xrTraits.anchor==="vertical"||f.xrTraits.anchor==="wall"?"vertical":"horizontal"),f.children)for(let g=f.children.length-1;g>=0;g--)n.push(f.children[g])}let s="";r>0&&(s=`startTimeCode = 0
|
|
251
|
-
endTimeCode = ${
|
|
215
|
+
void main(){fragColor=uColorId;}`;function bs(e,t,r){let i={};for(let n of r)i[n]=e.getUniformLocation(t,n);return i}var wp="uMVP uModel uInstanced uViewProj uNormalMatrix uUvTransform uBaseColor uMetallic uRoughness uClearcoat uEmissive uCameraPos uBaseColorTexture uHasTexture uMetallicRoughnessTexture uHasMetallicRoughnessTexture uNormalTexture uHasNormalTexture uNormalScale uOcclusionTexture uHasOcclusionTexture uOcclusionStrength uEmissiveFactor uEmissiveTexture uHasEmissiveTexture uToneMapping uEnvironmentMap uHasEnvironmentMap uAmbientColor uHemi uNumDirLights uDirLightDir uDirLightColor uNumPointLights uPointLightPos uPointLightColor uPointLightSpotDir uPointLightSpotCone uEnvIntensity uExposure uViewportSize uSectionPlane uSectionEnabled".split(" ");function Hc(){let e=He(),t=e.xrDepthShader,r=e.shadowMapShader;return{fs:gp.replace("/*XRD_U*/",t?.uniformsGLSL||"").replace("/*XRD_O*/",t?.occlusionGLSL||"").replace("/*SHD_U*/",r?.uniformsGLSL||"").replace("/*SHD_D*/",r?.dirGLSL||"").replace("/*SHD_P*/",r?.ptGLSL||""),uniforms:[...wp,...t?.uniformNames||[],...r?.uniformNames||[]]}}function Sp(e){if(typeof e!="string")return null;let t=e.trim();if(!t||/[\x00-\x1f\x7f]/.test(t))return null;let r=t.toLowerCase();return r.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(t)?t:null:r.startsWith("https://")||r.startsWith("blob:")?t:r.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(t)||/(^|[\\/])\.\.([\\/]|$)/.test(t)?null:t}function $c(e,t,r,i,n,a,s,o){if(i===void 0||!t.accessors?.[i])return null;let l=Hn(t,r,t.accessors[i],a);if(!l)return null;o&&(l=l.slice(),Ed(l,o));let c=e.createBuffer();return s.push(c),e.bindBuffer(34962,c),e.bufferData(34962,l,35044),e.enableVertexAttribArray(n),e.vertexAttribPointer(n,a,5126,!1,0,0),l}function Gc(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,t):1}function Cd(e,t,r){let i=Hc(),n=jc,a=i.fs,s=!1;for(let l of kt)if(l.onResolveShader){let c=l.onResolveShader(t,r,n,a);c&&(n=c.vs,a=c.fs,s=!0)}let o=s?ir(e,n,a):null;return{program:o,uniforms:o?bs(e,o,i.uniforms):null}}function Mp(e,t,r){let i=t.instanceMatrices;if(!i||i.length<16||typeof e.vertexAttribDivisor!="function"||typeof e.drawElementsInstanced!="function")return!1;let n=i.length>>4,a=t.instanceColors,s=new Float32Array(n*20);for(let l=0;l<n;l++)s.set(i.subarray(l*16,l*16+16),l*20),s[l*20+16]=a?a[l*3]:1,s[l*20+17]=a?a[l*3+1]:1,s[l*20+18]=a?a[l*3+2]:1,s[l*20+19]=1;let o=e.createBuffer();r.push(o),e.bindBuffer(34962,o),e.bufferData(34962,s,35044);for(let l=0;l<5;l++)e.enableVertexAttribArray(8+l),e.vertexAttribPointer(8+l,4,5126,!1,80,l*16),e.vertexAttribDivisor(8+l,1);return!0}function Ap(e,t){let r=e.materials?.[t?.material];if(!r)return null;let i=[r.pbrMetallicRoughness?.baseColorTexture,r.pbrMetallicRoughness?.metallicRoughnessTexture,r.normalTexture,r.occlusionTexture,r.emissiveTexture];for(let n of i){let a=n?.extensions?.KHR_texture_transform;if(a&&typeof a=="object")return a}return null}var Nd=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),Dd=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function hs(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}function Ud(e,t){let r=e?.pbrMetallicRoughness,i=r?.baseColorFactor,n=e?.emissiveFactor,a=e?.extensions?.KHR_materials_clearcoat,s=o=>o!==void 0&&t[o.index]?t[o.index]:null;return{baseColor:i?[i[0],i[1],i[2],i[3]??1]:[.8,.8,.8,1],metallic:r?.metallicFactor??.1,roughness:r?.roughnessFactor??.5,clearcoat:a?a.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,a?.clearcoatRoughnessFactor??.04),texture:s(r?.baseColorTexture),metallicRoughnessTexture:s(r?.metallicRoughnessTexture),normalTexture:s(e?.normalTexture),normalScale:e?.normalTexture?.scale??1,occlusionTexture:s(e?.occlusionTexture),occlusionStrength:e?.occlusionTexture?.strength??1,emissiveTexture:s(e?.emissiveTexture),emissiveFactor:Array.isArray(n)&&n.length>=3?[n[0],n[1],n[2]]:[0,0,0],isTransmissive:(e?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function Bd(e,t,r){let i=new Set,n=a=>{a&&!i.has(a)&&(i.add(a),e.deleteTexture(a))};for(let a of t)for(let s of a.primitives){if(s.vao&&e.deleteVertexArray(s.vao),s.buffers)for(let l of s.buffers)e.deleteBuffer(l);for(let l of[s.texture,s.metallicRoughnessTexture,s.normalTexture,s.occlusionTexture,s.emissiveTexture])n(l);let o=new Set;s.customProgram&&o.add(s.customProgram);for(let l of s.programCache?.values()??[])l.program&&o.add(l.program);for(let l of o)e.deleteProgram(l)}if(r)for(let a of r)n(a)}function kd(e,t,r=Dd,i){let n={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return Tp(e,t,r,i,n)}catch(a){let s=n.mesh&&!n.meshes.includes(n.mesh)?[...n.meshes,n.mesh]:n.meshes;Bd(e,s,n.gpuTextures),n.vao&&e.deleteVertexArray(n.vao);for(let o of n.buffers)e.deleteBuffer(o);throw a}}function Tp(e,t,r,i,n){if(!t||!t.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:a}=t,s=ys("meshopt");s?.decodeBufferViews&&s.decodeBufferViews(a,t);let o=t.bin,l=[];n.meshes=l;let c=[],f=a.extensions?.KHR_materials_variants;f&&Array.isArray(f.variants)&&f.variants.forEach((P,R)=>{c.push(typeof P?.name=="string"&&P.name?P.name:`Variant_${R}`)});let m=vr(a),h=[];if(Array.isArray(a.nodes))for(let P=0;P<a.nodes.length;P++){let R=a.nodes[P];R.mesh!==void 0&&a.meshes&&a.meshes[R.mesh]&&h.push({node:R,nodeIdx:P,meshIdx:R.mesh})}let p=h.length>0?h:(a.meshes||[]).map((P,R)=>({node:P,nodeIdx:-1,meshIdx:R})),g=[],x=Array.isArray(t.lights)&&t.lights.length>0?t.lights:Array.isArray(a.asset?.extras?.lights)&&a.asset.extras.lights.length>0?a.asset.extras.lights:null;if(x)for(let P of x)g.push({...P,type:P.type||P.light_type||"point",groundColor:P.groundColor??P.ground_color,innerConeAngle:P.innerConeAngle??P.inner_cone_angle,outerConeAngle:P.outerConeAngle??P.outer_cone_angle});else a.extensions?.KHR_lights_punctual?.lights&&g.push(...Wc(a,m));if(g.length===0&&(g.push({type:"ambient",color:[1,1,1],intensity:.35}),g.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),p.length>r.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${r.maxMeshes}). Found: ${p.length}`);let v=[];if(n.gpuTextures=v,a.textures&&a.images){if(a.textures.length>r.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${r.maxTextures}). Found: ${a.textures.length}`);for(let P=0;P<a.textures.length;P++){let R=a.textures[P],$=a.images[R.source];if($){let F=e.createTexture();e.bindTexture(3553,F),e.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255]));for(let[Y,J]of[[10242,10497],[10243,10497],[10241,9729],[10240,9729]])e.texParameteri(3553,Y,J);let V=Y=>{F.__gpuImageSource=Y,e.bindTexture(3553,F),e.texImage2D(3553,0,6408,6408,5121,Y),e.generateMipmap(3553),i?.()};if($.bufferView!==void 0){let Y=a.bufferViews[$.bufferView],J=Y.byteOffset||0,re=new Blob([o.slice(J,J+Y.byteLength)],{type:$.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(re).then(V).catch(()=>{})}else if($.uri){let Y=Sp($.uri);if(Y){let J=new Image;J.crossOrigin="anonymous",J.referrerPolicy="no-referrer",J.onload=()=>V(J),J.src=Y}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",$.uri)}v.push(F)}else v.push(null)}}let y=[1/0,1/0,1/0],A=[-1/0,-1/0,-1/0],b=0,w=0;for(let P=0;P<p.length;P++){let R=p[P],$=a.meshes[R.meshIdx],F=R.nodeIdx>=0?m[R.nodeIdx]:rt(),V=new Float32Array(9);Bt(V,F);let Y=R.node?.extras?.shadow,J={name:R.node.name||$.name||`Mesh_${R.meshIdx}`,nodeIndex:R.nodeIdx,transform:F,normalMatrix:V,primitives:[],extras:R.node.extras||$.extras,...R.node?.visible===!1||R.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{},...typeof Y?.cast=="boolean"?{castShadow:Y.cast}:{},...typeof Y?.receive=="boolean"?{receiveShadow:Y.receive}:{}};n.mesh=J;let re=R.node?.extensions?.EXT_mesh_gpu_instancing;if(re&&re.attributes&&typeof re.attributes=="object"){let Q=re.attributes,ee=Q.TRANSLATION!==void 0?a.accessors?.[Q.TRANSLATION]:null,k=Q.ROTATION!==void 0?a.accessors?.[Q.ROTATION]:null,G=Q.SCALE!==void 0?a.accessors?.[Q.SCALE]:null,q=Q._COLOR_0!==void 0?a.accessors?.[Q._COLOR_0]:null,H=Number(ee?.count??k?.count??G?.count??0);if(!Number.isFinite(H)||H<0||H>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${H}`);if(H>0){let te=(_e,Le)=>{if(!_e||_e.bufferView===void 0||!a.bufferViews?.[_e.bufferView])return null;let ne=_e.componentType??5126,Re=D=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${D})`),null);if(ne!==5120&&ne!==5121&&ne!==5122&&ne!==5123&&ne!==5126)return Re(`componentType ${ne}`);if(!(Number(_e.count)>=H))return Re(`count ${_e.count} < ${H}`);let W=null;try{W=Hn(a,o,{..._e,count:H},Le)}catch{return Re("out of bounds")}return!W||!W.every(Number.isFinite)?Re("non-finite value"):W},Z=te(ee,3),ae=te(k,4),ie=te(G,3),de=q?.type==="VEC4"?4:3,me=te(q,de),Se=new Float32Array(H*16),Fe=rt();for(let _e=0;_e<H;_e++){let Le=_e*3,ne=_e*4;or(Fe,ae?[ae[ne],ae[ne+1],ae[ne+2],ae[ne+3]]:[0,0,0,1],Z?[Z[Le],Z[Le+1],Z[Le+2]]:[0,0,0],ie?[ie[Le],ie[Le+1],ie[Le+2]]:[1,1,1]),Se.set(Fe,_e*16)}if(J.instanceMatrices=Se,me){let _e=new Float32Array(H*3);for(let Le=0;Le<H;Le++)_e[Le*3]=me[Le*de],_e[Le*3+1]=me[Le*de+1],_e[Le*3+2]=me[Le*de+2];J.instanceColors=_e}}}for(let Q of $.primitives||[]){if(Q.extensions?.KHR_draco_mesh_compression){let z=ys("draco");z&&z.decodePrimitive(a,Q,o)}let ee=[],k=e.createVertexArray();n.vao=k,n.buffers=ee,e.bindVertexArray(k);let G=Mp(e,J,ee),q=a.accessors[Q.attributes.POSITION],H=Number(q?.count??0);if(!Number.isFinite(H)||H<0||b+H>r.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${r.maxVertices}).`);if(b+=H,q?.min&&q?.max){let z=O=>{for(let X=0;X<3;X++){let se=O[12+X],ce=se;for(let pe=0;pe<3;pe++){let xe=O[pe*4+X]*q.min[pe],he=O[pe*4+X]*q.max[pe];se+=xe<he?xe:he,ce+=xe>he?xe:he}se<y[X]&&(y[X]=se),ce>A[X]&&(A[X]=ce)}};if(J.instanceMatrices&&J.instanceMatrices.length>=16){let O=J.instanceMatrices.length>>4,X=rt();for(let se=0;se<O;se++)at(X,F,J.instanceMatrices.subarray(se*16,se*16+16)),z(X)}else z(F)}let te=$c(e,a,o,Q.attributes.POSITION,0,3,ee),Z=$c(e,a,o,Q.attributes.NORMAL,1,3,ee),ae=$c(e,a,o,Q.attributes.TEXCOORD_0,2,2,ee,Ap(a,Q)),ie=0,de=5123,me=null;if(Q.indices!==void 0){let z=a.accessors[Q.indices],O=(a.bufferViews[z.bufferView].byteOffset||0)+(z.byteOffset||0);if(ie=Number(z.count??0),!Number.isFinite(ie)||ie<0||w+ie>r.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${r.maxIndices}).`);w+=ie,de=z.componentType===5125?5125:5123;let X=e.createBuffer();ee.push(X),e.bindBuffer(34963,X),z.componentType===5125?me=new Uint32Array(o,O,z.count):z.componentType===5121?me=Uint16Array.from(new Uint8Array(o,O,z.count)):me=O%2===0?new Uint16Array(o,O,z.count):new Uint16Array(o.slice(O,O+z.count*2)),e.bufferData(34963,me,35044)}else ie=q.count;let Se={};for(let z of kt)if(z.onBuildPrimitiveVAO){let O=z.onBuildPrimitiveVAO(e,k,Q,a,o);O&&(Se[z.name]=O)}e.bindVertexArray(null);let Fe=a.materials&&Q.material!==void 0?a.materials[Q.material]:null,{program:_e,uniforms:Le}=Cd(e,Q,Fe),ne=Ud(Fe,v),Re=!!(Fe?.extensions?.KHR_materials_transmission||Se.materials?.isTransmissive),W=Q.extensions?.KHR_materials_variants?.mappings,D=Array.isArray(W)?W.filter(z=>z&&typeof z.material=="number"&&Array.isArray(z.variants)).map(z=>({material:z.material|0,variants:z.variants.map(O=>Number(O)|0)})):void 0;J.primitives.push({vao:k,instanced:G,indexCount:ie,indexType:de,...ne,positions:te,normals:Z,uvs:ae,indices:me,buffers:ee,materialIndex:Q.material,defaultMaterialIndex:Q.material,variantMappings:D,primitiveDef:Q,programCache:new Map([[Q.material??-1,{program:_e,uniforms:Le}]]),pluginData:Se,customProgram:_e,customUniforms:Le,isTransmissive:Re})}l.push(J)}isFinite(y[0])||(y=[-1,-1,-1]),isFinite(A[0])||(A=[1,1,1]);let S=[(y[0]+A[0])/2,(y[1]+A[1])/2,(y[2]+A[2])/2],E=Math.max(Math.hypot(A[0]-y[0],A[1]-y[1],A[2]-y[2])/2,.5),N=[...y],C=[...A],_=t.animations;if(t.animationsParsed===!1||!_){for(let P of kt)if(P.onParseGLB?.(t),t.animations){_=t.animations;break}}return _||(_=[]),{meshes:l,bounds:{center:S,radius:E,min:N,max:C},lights:g,animations:_,worldMatrices:m,gpuTextures:v,availableVariants:c}}function ps(){return typeof performance<"u"?performance.now():Date.now()}function Ho(e){let t=e.customTarget||e.bounds.center,r=e.currDistance*Math.cos(e.currPhi);return[t[0]+r*Math.sin(e.currTheta),t[1]+e.currDistance*Math.sin(e.currPhi),t[2]+r*Math.cos(e.currTheta)]}var Ht=class{constructor(e,t,r){this.supportsInstanceOffsets=!0,this.meshes=[],this.backdropMeshes=[],this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]},this.lights=[],this.modelRootMatrix=rt(),this.clearColor=[0,0,0,0],this.envIntensity=1,this.exposure=1,this.shadowIntensity=0,this.shadowSoftness=.5,this.toneMapping="neutral",this.environmentTexture=null,this.environmentSource=null,this.animations=[],this.currentClip=null,this.animationTime=0,this.isPlayingAnimation=!1,this.autoplay=!1,this.animationName="",this.gpuTextures=[],this.availableVariants=[],this.activeVariantName=null,this.gltf=null,this.worldMatrices=[],this.initialNodeTransforms=[],this.projMatrix=rt(),this.viewMatrix=rt(),this.activeViewMatrix=null,this.modelMatrix=rt(),this.mvpMatrix=rt(),this.normalMatrix=new Float32Array(9),this.initialTheta=.6,this.initialPhi=.35,this.initialDistance=null,this.customDistance=!1,this.distanceMode="auto",this.initialCustomTarget=null,this.customTarget=null,this.fov=Math.PI/4,this.minTheta=-1/0,this.maxTheta=1/0,this.minPhi=-Math.PI*.48,this.maxPhi=Math.PI*.48,this.minDistanceLimit=null,this.maxDistanceLimit=null,this.activePointers=new Map,this.isPanning=!1,this.targetTheta=.6,this.currTheta=.6,this.targetPhi=.35,this.currPhi=.35,this.targetDistance=3,this.currDistance=3,this.autoRotate=!1,this.autoRotateSpeed=Math.PI/6,this.autoRotateDelay=3e3,this.lastInteractionTime=-1/0,this.turntableRotation=0,this.isPointerDown=!1,this.interactive=!0,this.skyboxTexture=null,this.lastPointerX=0,this.lastPointerY=0,this.totalDragDist=0,this.selectedMeshNames=new Set,this.pickFbo=null,this.pickTexture=null,this.pickDepth=null,this.pickFboWidth=0,this.pickFboHeight=0,this.animFrameId=null,this.isVisible=!0,this.xrSessionActive=!1,this.lastTime=0,this.lastReportedTheta=-999,this.lastReportedPhi=-999,this.lastReportedZoom=-999,this.boundPointerDown=null,this.boundPointerMove=null,this.boundPointerUp=null,this.boundWheel=null,this.boundKeyDown=null,this.boundContextMenu=null,this.boundSetCamera=null,this.boundResetCamera=null,this.contextLost=!1,this.lastGlbData=null,this.boundContextLost=null,this.boundContextRestored=null,this.stereoSBS=!1,this.renderErrorReported=!1,this.xrDepthState={enabled:!1,texture:null,uvTransform:rt(),rawValueToMeters:.001,format:0},this.container=e;let i,n;if(t&&typeof t.getContext=="function"?(i=t,n=r):(n=t,i=n?.canvas),!i){let l=e.querySelector("canvas");l||(l=document.createElement("canvas"),l.style.cssText="width:100%;height:100%;display:block;touch-action:none",e.prepend(l)),i=l}this.canvas=i;let a=this.opts=n||{};a.clearColor&&(this.clearColor=a.clearColor);let s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;a.autoRotate!==void 0?this.autoRotate=a.autoRotate&&!s:s&&(this.autoRotate=!1),a.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=a.autoRotateSpeed),a.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(a.autoRotateDelay)||0)),a.exposure!==void 0&&(this.exposure=Gc(a.exposure)),a.camera&&this.setInitialCamera(a.camera.theta,a.camera.phi,a.camera.distance,a.camera.zoom),(a.shadowIntensity!==void 0||a.shadowSoftness!==void 0)&&this.setShadow(a.shadowIntensity??0,a.shadowSoftness),a.shadowMaps!==void 0&&(this.shadowMaps=a.shadowMaps),a.toneMapping!==void 0&&(this.toneMapping=Dr(a.toneMapping)),a.autoplay!==void 0&&(this.autoplay=a.autoplay),a.animationName!==void 0&&(this.animationName=a.animationName),a.variantName!==void 0&&(this.activeVariantName=a.variantName||null),a.fieldOfView!==void 0&&(this.fov=a.fieldOfView*Math.PI/180),a.distanceMode!==void 0&&(this.distanceMode=a.distanceMode),a.cameraTarget!==void 0&&(this.setTarget(a.cameraTarget[0],a.cameraTarget[1],a.cameraTarget[2]),this.initialCustomTarget=[...a.cameraTarget]),(a.minCameraOrbit||a.maxCameraOrbit)&&this.setOrbitLimits({minTheta:a.minCameraOrbit?.theta,maxTheta:a.maxCameraOrbit?.theta,minPhi:a.minCameraOrbit?.phi,maxPhi:a.maxCameraOrbit?.phi,minDistance:a.minCameraOrbit?.distance,maxDistance:a.maxCameraOrbit?.distance});let o=i.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!o)throw new Error("WebGL2 not supported");this.gl=o,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),a.environmentImage&&this.setEnvironmentImage(a.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&a.autoStart!==!1&&this.start()}static registerDecoder(e,t){bp(e,t)}static getDecoder(e){return ys(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=Hc();this.renderProg=ir(e,jc,t.fs),this.pickProg=ir(e,xp,vp),this.uRender=bs(e,this.renderProg,t.uniforms),this.uPick=bs(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}recompileRenderProgram(){if(this.contextLost)return;let e=this.gl,t=Hc();this.renderProg&&e.deleteProgram(this.renderProg),this.renderProg=ir(e,jc,t.fs),this.uRender=bs(e,this.renderProg,t.uniforms);for(let r of this.meshes)for(let i of r.primitives)i.customProgram&&(e.deleteProgram(i.customProgram),i.programCache?.clear(),this.applyPrimitiveProgram(i,i.materialIndex,this.gltf?.materials?.[i.materialIndex??-1]??null))}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of kt)t.onContextRestored?.(e,this);this.meshes=[],this.gpuTextures=[],this.environmentTexture=null,this.lastGlbData&&this.loadGLBData(this.lastGlbData,this.lastLimits),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}setupPickingFbo(){let e=this.gl;typeof e.createFramebuffer=="function"&&(this.pickFbo=e.createFramebuffer(),this.pickTexture=e.createTexture(),this.pickDepth=e.createRenderbuffer(),this.resizePickingFbo(this.canvas.width,this.canvas.height),e.bindFramebuffer(36160,this.pickFbo),e.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),e.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),e.bindFramebuffer(36160,null))}resizePickingFbo(e,t){if(!this.pickFbo)return;let r=this.gl,i=Math.max(1,e),n=Math.max(1,t);this.pickFboWidth=i,this.pickFboHeight=n,r.bindTexture(3553,this.pickTexture),r.texImage2D(3553,0,6408,i,n,0,6408,5121,null),r.texParameteri(3553,10241,9728),r.texParameteri(3553,10240,9728),r.bindRenderbuffer(36161,this.pickDepth),r.renderbufferStorage(36161,33189,i,n)}loadGLBData(e,t){let{meshes:r,bounds:i,lights:n,animations:a,worldMatrices:s,gpuTextures:o,availableVariants:l}=kd(this.gl,e,t,()=>this.render());this.lastGlbData=e,this.lastLimits=t,this.disposeMeshGpuResources(),this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.meshes=r,this.bounds=i,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=n,this.animations=a||[],this.worldMatrices=s||[],this.gpuTextures=o||[],this.availableVariants=l||[],this.gltf=e.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=(e.gltf?.nodes||[]).map(m=>({t:[m.translation?.[0]??0,m.translation?.[1]??0,m.translation?.[2]??0],r:[m.rotation?.[0]??0,m.rotation?.[1]??0,m.rotation?.[2]??0,m.rotation?.[3]??1],s:[m.scale?.[0]??1,m.scale?.[1]??1,m.scale?.[2]??1]})),this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let m of kt)m.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:i.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let c=e.exposure??e.gltf?.extras?.exposure??e.gltf?.asset?.extras?.exposure;c!==void 0&&(this.exposure=Gc(c));let f=e.environmentIntensity??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.environmentIntensity;f!==void 0&&(this.envIntensity=Math.max(0,Number(f)||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(Pd(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let e of kt)e.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(wr(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=wr(e),{meshes:i}=kd(this.gl,r,Dd,()=>this.render());if(t)for(let n of i)n.transform[12]+=t[0],n.transform[13]+=t[1],n.transform[14]+=t[2],Bt(n.normalMatrix,n.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?e.get(r.name)??e.get(t):Array.isArray(e)?e[t]:e&&typeof e=="object"?Object.prototype.hasOwnProperty.call(e,r.name)?e[r.name]:Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0:void 0;i&&i.length===16&&(r.transform.set(i),Bt(r.normalMatrix,r.transform))}}bindLights(e=this.uRender){let t=this.gl,r=[.28,.28,.28],i=[0,0,0,0,0,0,0,1,0],n=!1,a=[],s=[],o=[],l=[],c=[],f=[];for(let m of this.lights){let h=m.color||[1,1,1],p=m.intensity!==void 0?m.intensity:1;if(m.type==="ambient")r=[h[0]*p,h[1]*p,h[2]*p];else if(m.type==="hemisphere"){n=!0;let g=m.groundColor||[.2,.2,.2],x=p*.65;for(let A=0;A<3;A++)i[A]+=h[A]*x,i[A+3]+=g[A]*x;let v=m.position||[0,1,0],y=Math.hypot(v[0],v[1],v[2]);y>1e-5&&(i[6]=v[0]/y,i[7]=v[1]/y,i[8]=v[2]/y)}else if(m.type==="directional"&&a.length<6){let g=m.direction||[.5,1,.8];a.push(g[0],g[1],g[2]),s.push(h[0]*p,h[1]*p,h[2]*p)}else if((m.type==="point"||m.type==="spot")&&o.length<6){let g=m.position||[0,0,0];if(o.push(g[0],g[1],g[2]),l.push(h[0]*p,h[1]*p,h[2]*p),m.type==="spot"){let x=m.direction||[0,-1,0],v=Math.max(.01,Math.min(Math.PI/2,m.outerConeAngle??Math.PI/3)),y=Math.max(0,Math.min(v-1e-4,m.innerConeAngle??0));c.push(x[0],x[1],x[2]),f.push(Math.cos(y),Math.cos(v))}else c.push(0,-1,0),f.push(-2,-3)}}a.length===0&&!n&&(a.push(.5,1,.8),s.push(1,1,1)),t.uniform3fv(e.uAmbientColor,r),e.uHemi&&t.uniformMatrix3fv(e.uHemi,!1,i),t.uniform1i(e.uNumDirLights,a.length/3),a.length>0&&(t.uniform3fv(e.uDirLightDir,a),t.uniform3fv(e.uDirLightColor,s)),t.uniform1i(e.uNumPointLights,o.length/3),o.length>0&&(t.uniform3fv(e.uPointLightPos,o),t.uniform3fv(e.uPointLightColor,l),e.uPointLightSpotDir&&t.uniform3fv(e.uPointLightSpotDir,c),e.uPointLightSpotCone&&t.uniform2fv(e.uPointLightSpotCone,f)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=Gc(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=Dr(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){this.environmentSource=e&&typeof e=="object"?e:null;for(let t of kt)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e),this.render();return}this.render()}async setSkyboxImage(e){for(let t of kt)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(f=>f.primitives.filter(m=>m.materialIndex===r||e.length===1&&m.materialIndex===void 0)),n=i[0],a=n?[...n.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],s=n?n.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,o=n?n.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,l=(f,m,h)=>{c[f]=h,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness[f]=h);for(let p of i)p[m]=h;this.render()},c={baseColorFactor:a,metallicFactor:s,roughnessFactor:o,setBaseColorFactor:f=>l("baseColorFactor","baseColor",[f[0],f[1],f[2],f[3]??1]),setMetallicFactor:f=>l("metallicFactor","metallic",f),setRoughnessFactor:f=>l("roughnessFactor","roughness",f)};return{name:t.name||`Material_${r}`,pbrMetallicRoughness:c}})}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 n of this.meshes)for(let a of n.primitives){let s=a.defaultMaterialIndex;if(!t&&Array.isArray(a.variantMappings)){for(let l of a.variantMappings)if(Array.isArray(l.variants)&&l.variants.includes(r)){s=l.material;break}}let o=s!==void 0?i[s]:void 0;a.materialIndex=o?s:void 0,Object.assign(a,Ud(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,n=e.programCache.get(i);n||(n=Cd(this.gl,{...e.primitiveDef,material:t},r),e.programCache.set(i,n)),e.customProgram=n.program,e.customUniforms=n.uniforms,e.pluginData&&(e.pluginData.materials=e.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(e){this.autoplay=e,e?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(e){this.animationName=e,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(e)}evaluateAnimation(e){for(let t of kt)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){let t=Math.PI/180,r=Math.PI*.48;e.minTheta!==void 0&&(this.minTheta=e.minTheta*t),e.maxTheta!==void 0&&(this.maxTheta=e.maxTheta*t),e.minPhi!==void 0&&(this.minPhi=Math.max(-r,e.minPhi*t)),e.maxPhi!==void 0&&(this.maxPhi=Math.min(r,e.maxPhi*t)),e.minDistance!==void 0&&(this.minDistanceLimit=e.minDistance),e.maxDistance!==void 0&&(this.maxDistanceLimit=e.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){let e=180/Math.PI;return{minTheta:isFinite(this.minTheta)?this.minTheta*e:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*e:void 0,minPhi:this.minPhi*e,maxPhi:this.maxPhi*e,minDistance:this.minDistanceLimit??void 0,maxDistance:this.maxDistanceLimit??void 0}}clampTheta(e){return Math.max(this.minTheta,Math.min(this.maxTheta,e))}clampPhi(e){return Math.max(this.minPhi,Math.min(this.maxPhi,e))}clampDistance(e){let t=this.bounds?.radius;return Math.max(this.minDistanceLimit??(t?t*.5:.1),Math.min(this.maxDistanceLimit??(t?t*8:100),e))}setCamera(e,t,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){e!==void 0&&(this.initialTheta=this.targetTheta=this.currTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.initialPhi=this.targetPhi=this.currPhi=this.clampPhi(t*Math.PI/180));let n=r!==void 0&&r>0?r:i!==void 0&&i>0?this.bounds.radius*2.5/i:null;this.customDistance=n!==null,this.initialDistance=this.targetDistance=this.currDistance=this.clampDistance(n??(this.distanceMode==="absolute"?3:this.bounds.radius*2.5)),this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.targetDistance=this.clampDistance(this.initialDistance??this.bounds.radius*2.5),this.customTarget=this.initialCustomTarget?[...this.initialCustomTarget]:null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(e,t){let r=rt();at(r,this.projMatrix,this.viewMatrix);let i=(C,_,P=1)=>[C[0]*_[0]+C[4]*_[1]+C[8]*_[2]+C[12]*P,C[1]*_[0]+C[5]*_[1]+C[9]*_[2]+C[13]*P,C[2]*_[0]+C[6]*_[1]+C[10]*_[2]+C[14]*P,C[3]*_[0]+C[7]*_[1]+C[11]*_[2]+C[15]*P],n=this.modelRootMatrix,[a,s,o]=n?i(n,e):e,[l,c,f]=t?n?i(n,t,0):t:[0,0,0],[m,h,p,g]=i(r,[a,s,o]);if(g<=1e-4)return{x:0,y:0,z:1,visible:!1};let x=m/g,v=h/g,y=p/g,A=this.canvas.getBoundingClientRect(),b=A.width||this.canvas.clientWidth||this.canvas.width||300,w=A.height||this.canvas.clientHeight||this.canvas.height||150,S=(x*.5+.5)*b,E=(-v*.5+.5)*w,N=x>=-1.1&&x<=1.1&&v>=-1.1&&v<=1.1&&y>=-1&&y<=1;if(N&&t){let[C,_,P]=Ho(this),R=[a-C,s-_,o-P];l*R[0]+c*R[1]+f*R[2]>.05&&(N=!1)}return{x:S,y:E,z:y,visible:N}}setSelectedMesh(e){this.setSelectedMeshes([e])}setSelectedMeshes(e){this.selectedMeshNames=new Set(e.filter(Boolean))}getSelectedMesh(){return[...this.selectedMeshNames][0]||""}setupEvents(){let e=this.canvas,t=ps;this.boundContextMenu=r=>{r.preventDefault()},e.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=r=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=t(),this.lastPointerX=r.clientX,this.lastPointerY=r.clientY,this.totalDragDist=0,this.activePointers.set(r.pointerId,{x:r.clientX,y:r.clientY}),this.isPanning=r.button===2||r.shiftKey||this.activePointers.size===2,e.setPointerCapture(r.pointerId))},e.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=r=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=t();let i=this.activePointers.get(r.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},n=r.clientX-i.x,a=r.clientY-i.y;if(this.activePointers.set(r.pointerId,{x:r.clientX,y:r.clientY}),this.lastPointerX=r.clientX,this.lastPointerY=r.clientY,this.totalDragDist+=Math.hypot(n,a),this.isPanning||r.button===2||r.shiftKey||this.activePointers.size===2){let s=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],o=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],l=this.customTarget?[...this.customTarget]:[...this.bounds.center],c=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;l[0]+=(-n*s[0]+a*o[0])*c,l[1]+=(-n*s[1]+a*o[1])*c,l[2]+=(-n*s[2]+a*o[2])*c,this.customTarget=l}else this.targetTheta=this.clampTheta(this.targetTheta-n*.008),this.targetPhi=this.clampPhi(this.targetPhi+a*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=r=>{this.lastInteractionTime=t(),this.activePointers.delete(r.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(r.pointerId)}catch{}if(this.totalDragDist<5&&r.button===0){let i=e.getBoundingClientRect(),n=Math.floor((r.clientX-i.left)*(e.width/Math.max(i.width,1))),a=Math.floor((r.clientY-i.top)*(e.height/Math.max(i.height,1)));this.performMeshPick(n,a,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=r=>{if(!this.interactive)return;r.preventDefault(),this.lastInteractionTime=t();let i=Math.exp(r.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*i)},e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=r=>{let i=r.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=r=>{if(this.interactive){switch(r.key){case"ArrowLeft":this.targetTheta=this.clampTheta(this.targetTheta-.1);break;case"ArrowRight":this.targetTheta=this.clampTheta(this.targetTheta+.1);break;case"ArrowUp":this.targetPhi=this.clampPhi(this.targetPhi+.08);break;case"ArrowDown":this.targetPhi=this.clampPhi(this.targetPhi-.08);break;case"+":case"=":this.targetDistance=this.clampDistance(this.targetDistance*.9);break;case"-":case"_":this.targetDistance=this.clampDistance(this.targetDistance*1.1);break;case"Home":this.resetCamera();break;default:return}this.lastInteractionTime=t(),r.preventDefault()}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=(r,i,n)=>{this[n]&&(r.removeEventListener(i,this[n]),this[n]=null)},t=this.canvas;for(let[r,i]of[["webglcontextlost","boundContextLost"],["webglcontextrestored","boundContextRestored"],["contextmenu","boundContextMenu"],["pointerdown","boundPointerDown"],["pointermove","boundPointerMove"],["pointerup","boundPointerUp"],["wheel","boundWheel"],["keydown","boundKeyDown"]])e(t,r,i);e(this.container,"setCamera","boundSetCamera"),e(this.container,"resetCamera","boundResetCamera")}raycastFromScreenPoint(e,t){let r=this.canvas,i=r.getBoundingClientRect(),n=r.width||300,a=r.height||300,s=i.width>0?Math.floor((e-i.left)*(n/i.width)):Math.floor(e),o=i.height>0?Math.floor((t-i.top)*(a/i.height)):Math.floor(t);return this.performMeshPick(s,o,!1)}performMeshPick(e,t,r=!0){if(this.meshes.length===0)return null;let i=this.gl,n=Math.max(1,this.canvas.width||300),a=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,n);let s=rt();at(s,this.projMatrix,this.viewMatrix);let o=[],l=Math.max(0,Math.min(n-1,e)),c=Math.max(0,Math.min(a-1,a-1-t));if(this.pickFbo&&i&&!this.xrSessionActive){(this.pickFboWidth!==n||this.pickFboHeight!==a)&&this.resizePickingFbo(n,a),i.bindFramebuffer(36160,this.pickFbo),i.viewport(0,0,n,a),i.enable(2929),i.clearColor(0,0,0,0),i.clear(16640),i.useProgram(this.pickProg);for(let S=0;S<this.meshes.length;S++){let E=this.meshes[S];if(E.visible===!1||E.isPluginMesh)continue;let N=S+1,C=(N&255)/255,_=(N>>8&255)/255,P=(N>>16&255)/255;i.uniform4f(this.uPick.uColorId,C,_,P,1),at(this.modelMatrix,this.modelRootMatrix,E.transform);let R=E.instanceMatrices;if(R&&R.length>=16){let $=R.length>>4,F=rt();for(let V of E.primitives){i.bindVertexArray(V.vao);for(let Y=0;Y<$;Y++)at(F,this.modelMatrix,R.subarray(Y*16,Y*16+16)),at(this.mvpMatrix,s,F),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),hs(i,V)}}else{at(this.mvpMatrix,s,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let $ of E.primitives)i.bindVertexArray($.vao),hs(i,$)}}let b=new Uint8Array(4);i.readPixels(l,c,1,1,6408,5121,b),i.bindFramebuffer(36160,null);let w=b[0]+(b[1]<<8)+(b[2]<<16);w>0&&w<=this.meshes.length&&(o=[this.meshes[w-1]])}o.length===0&&(o=this.meshes.filter(b=>b.visible!==!1));let f=null,m=1/0,h=[0,0,0],p=[0,1,0],[g,x,v]=Ho(this),y=rt();for(let b of o){at(y,this.modelRootMatrix,b.transform);let w=b.instanceMatrices,S=w&&w.length>=16?w.length>>4:1;for(let E=0;E<S;E++){w&&w.length>=16?at(this.modelMatrix,y,w.subarray(E*16,E*16+16)):this.modelMatrix.set(y),at(this.mvpMatrix,s,this.modelMatrix);let N=rt();if(!Kr(N,this.mvpMatrix))continue;let C=(l+.5)/n*2-1,_=(c+.5)/a*2-1,P=[0,0,0],R=[0,0,0];Rc(P,C,_,-1,N),Rc(R,C,_,1,N);let $=R[0]-P[0],F=R[1]-P[1],V=R[2]-P[2],Y=Math.hypot($,F,V)||1,J=$/Y,re=F/Y,Q=V/Y,ee={distance:1/0,point:[0,0,0],normal:[0,1,0]};for(let k of b.primitives){if(!k.positions)continue;let G=k.positions,q=k.indices,H=Math.floor(q?q.length/3:G.length/9);for(let te=0;te<H;te++){let Z=(q?q[te*3]:te*3)*3,ae=(q?q[te*3+1]:te*3+1)*3,ie=(q?q[te*3+2]:te*3+2)*3;gd(P[0],P[1],P[2],J,re,Q,G[Z],G[Z+1],G[Z+2],G[ae],G[ae+1],G[ae+2],G[ie],G[ie+1],G[ie+2],ee,1e-4)}}if(isFinite(ee.distance)){let k=ee.point[0],G=ee.point[1],q=ee.point[2],H=this.modelMatrix,te=H[0]*k+H[4]*G+H[8]*q+H[12],Z=H[1]*k+H[5]*G+H[9]*q+H[13],ae=H[2]*k+H[6]*G+H[10]*q+H[14],ie=te-g,de=Z-x,me=ae-v,Se=Math.hypot(ie,de,me);if(Se<m){Bt(this.normalMatrix,this.modelMatrix);let Fe=this.normalMatrix,_e=ee.normal[0],Le=ee.normal[1],ne=ee.normal[2],Re=Fe[0]*_e+Fe[3]*Le+Fe[6]*ne,W=Fe[1]*_e+Fe[4]*Le+Fe[7]*ne,D=Fe[2]*_e+Fe[5]*Le+Fe[8]*ne,z=Math.hypot(Re,W,D)||1;Re/=z,W/=z,D/=z,Re*ie+W*de+D*me>0&&(Re=-Re,W=-W,D=-D);let O=X=>Math.round(X*1e3)/1e3;f=b,m=O(Se),h=[O(te),O(Z),O(ae)],p=[O(Re),O(W),O(D)]}}}}if(!f)return null;let A={meshIndex:this.meshes.indexOf(f),meshName:f.name,nodeIndex:f.nodeIndex,distance:m,hitPoint:h,normal:p,screenX:e,screenY:t};if(r){for(let b of kt)b.onMeshSelect?.(this,A);this.opts.onMeshClick&&this.opts.onMeshClick(A),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:A}))}return A}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let r=Math.max(1,Math.floor(t*.5)),i=e>=r,n=i?e-r:e,a=i?Math.max(1,t-r):r,s=(n+.5)/a*2-1;return Math.floor((s*.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);Oo(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center;xr(this.viewMatrix,Ho(this),r,[0,1,0]),at(this.mvpMatrix,this.projMatrix,this.viewMatrix),Bt(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 kt)r.onXRSessionEnd?.(this);if(this.lastTime=ps(),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 kt)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=ps();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,,i]=this.bounds.center;this.modelRootMatrix.set([e,0,-t,0,0,1,0,0,t,0,e,0,r-(e*r+t*i),0,i-(-t*r+e*i),1])}setVisible(e){this.isVisible=e}update(e){for(let a of kt)a.onUpdate?.(this,e);let t=ps();if(!this.isPointerDown&&this.autoRotate&&t-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*e,this.updateTurntableMatrix();for(let a of kt)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),n=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(n-this.lastReportedZoom)>=.02){this.lastReportedTheta=r,this.lastReportedPhi=i,this.lastReportedZoom=n;let a={theta:r,phi:i,zoom:n,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(a),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:a}))}}renderXRView(e,t,r,i,n=!0,a=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let s=e?.transform?.inverse?.matrix||this.viewMatrix,o=e?.projectionMatrix||this.projMatrix,l=e?.transform?.position,c=l?[l.x,l.y,l.z]:[0,1.6,0];t&&this.modelRootMatrix.set(t),this.render({viewMatrix:s,projMatrix:o,eyePos:c,viewport:i,eye:e?.eye||"none",clear:a>0?!1:e?.eye!=="right",isAR:n})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let E=Math.max(2,this.canvas.width||2),N=Math.max(1,this.canvas.height||1),C=Math.max(1,Math.floor(E*.5)),_=Math.max(1,E-C),P=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),R=this.customTarget||this.bounds.center,[$,F,V]=Ho(this),Y=Math.cos(this.currTheta),J=-Math.sin(this.currTheta),re=.032;for(let Q of[-1,1]){let ee=rt(),k=rt(),G=Q<0?C:_,q=[$+Q*Y*re,F,V+Q*J*re];Oo(ee,this.fov,G/N,.1,P),xr(k,q,[R[0]+Q*Y*re*.25,R[1],R[2]+Q*J*re*.25],[0,1,0]),this.render({viewMatrix:k,projMatrix:ee,eyePos:q,viewport:[Q<0?0:C,0,G,N],eye:Q<0?"left":"right",clear:Q<0,isAR:!1})}this.gl.viewport(0,0,E,N);return}let t=this.gl,[r,i,n,a]=e?.viewport||[0,0,this.canvas.width,this.canvas.height];if(t.viewport(r,i,n,a),t.enable(2929),!e||e.clear!==!1){let E=e?.isAR?[0,0,0,0]:this.clearColor;t.clearColor(E[0],E[1],E[2],E[3]),t.clear(16640)}let s=rt(),o=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=o;let l=e?.projMatrix??this.projMatrix;at(s,l,o);let c=He(),f=c.xrDepthShader,m=hp(this.toneMapping),[h,p,g]=e?e.eyePos:Ho(this);for(let E of kt)E.onBeforeDrawScene?.(this,t,s,[h,p,g],m);let x=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&x===0){c.gpuSceneAccelerator?.hideLayer?.(this);return}let v=e?.eye||"none",y=!e||e.clear!==!1;if(!this.xrSessionActive&&c.gpuSceneAccelerator?.renderScene(this,s,l,o,[h,p,g],m,[r,i,n,a],v,y,!!e?.isAR)){y&&!this.skyboxTexture&&(t.clearColor(0,0,0,0),t.clear(16384));for(let E of kt)E.name.includes("webgpu")&&E.onAfterRender?.(t,this,s,v,[r,i,n,a],l);return}let A=!1,b=x>0?[...this.backdropMeshes,...this.meshes]:this.meshes,w=(E,N,C,_)=>{N?(t.activeTexture(33984+E),t.bindTexture(3553,N),t.uniform1i(C,E),t.uniform1i(_,1)):t.uniform1i(_,0)},S=E=>{for(let N=0;N<b.length;N++){let C=b[N];if(C.visible===!1)continue;let _=this.selectedMeshNames.has(C.name);if(N<x||C.worldSpace===!0||C.name==="__xr_reticle__")this.modelMatrix.set(C.transform);else{at(this.modelMatrix,this.modelRootMatrix,C.transform);let Y=!e&&(C.extras?.xr?.billboard??C.userData?.xr?.billboard);if(Y){let J=this.modelMatrix,re=Math.hypot(J[0],J[1],J[2])||1,Q=Math.hypot(J[4],J[5],J[6])||1,ee=Math.hypot(J[8],J[9],J[10])||1,k=Y==="y"||Y==="cylindrical"||Y==="capsule",G=h-J[12],q=g-J[14],H=Math.hypot(G,q),te=H>1e-5?G/H:0,Z=H>1e-5?q/H:1;J.set(k?[Z*re,0,-te*re,0,0,Q,0,0,te*ee,0,Z*ee]:[o[0]*re,o[4]*re,o[8]*re,0,o[1]*Q,o[5]*Q,o[9]*Q,0,o[2]*ee,o[6]*ee,o[10]*ee])}}at(this.mvpMatrix,s,this.modelMatrix),Bt(C.normalMatrix,this.modelMatrix);let P=C.extras?.xr?.stereo||C.userData?.xr?.stereo,R=0,$=0,F=1,V=1;P==="sbs"?(F=.5,R=v==="right"?.5:0):P==="ou"&&(V=.5,$=v==="right"?.5:0);for(let Y of C.primitives){let J=!!Y.isTransmissive;if(!E&&J){A=!0;continue}if(E&&!J)continue;let re=Y.customProgram||this.renderProg,Q=Y.customUniforms||this.uRender;t.useProgram(re),t.vertexAttrib3f(3,0,0,0),Q.uInstanced&&t.uniform1i(Q.uInstanced,0),t.uniform1i(Q.uToneMapping,m),t.uniform1f(Q.uEnvIntensity,this.envIntensity),Q.uExposure&&t.uniform1f(Q.uExposure,this.exposure),t.uniform3f(Q.uCameraPos,h,p,g),t.uniform1f(Q.uEmissive,_?1:0),t.uniformMatrix4fv(Q.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(Q.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(Q.uNormalMatrix,!1,C.normalMatrix),Q.uUvTransform&&t.uniform4f(Q.uUvTransform,R,$,F,V),Q.uViewportSize&&t.uniform2f(Q.uViewportSize,Math.max(1,n),Math.max(1,a)),f?.bind(t,Q,this.xrDepthState,o,[r,i,Math.max(1,n),Math.max(1,a)]),c.shadowMapShader?.bind(t,Q,this,C),w(4,this.environmentTexture,Q.uEnvironmentMap,Q.uHasEnvironmentMap),this.bindLights(Q),Q.uSectionEnabled&&t.uniform1i(Q.uSectionEnabled,0);for(let k of kt)k.onBeforeDrawPrimitive?.(t,re,Y,C,this.worldMatrices||[],this.gltf);t.uniform4fv(Q.uBaseColor,Y.baseColor),t.uniform1f(Q.uMetallic,Y.metallic),t.uniform1f(Q.uRoughness,Y.roughness),Q.uClearcoat&&t.uniform2f(Q.uClearcoat,Y.clearcoat??0,Y.clearcoatRoughness??.04),w(0,Y.texture,Q.uBaseColorTexture,Q.uHasTexture),w(1,Y.metallicRoughnessTexture,Q.uMetallicRoughnessTexture,Q.uHasMetallicRoughnessTexture),w(2,Y.normalTexture,Q.uNormalTexture,Q.uHasNormalTexture),Y.normalTexture&&t.uniform1f(Q.uNormalScale,Y.normalScale),w(3,Y.occlusionTexture,Q.uOcclusionTexture,Q.uHasOcclusionTexture),Y.occlusionTexture&&t.uniform1f(Q.uOcclusionStrength,Y.occlusionStrength),t.uniform3fv(Q.uEmissiveFactor,Y.emissiveFactor),w(8,Y.emissiveTexture,Q.uEmissiveTexture,Q.uHasEmissiveTexture),t.bindVertexArray(Y.vao);let ee=C.instanceMatrices;if(Y.instanceCount!==void 0)t.drawElementsInstanced(4,Y.indexCount,Y.indexType,0,Y.instanceCount);else if(ee&&ee.length>=16&&Y.instanced&&Q.uInstanced&&Q.uViewProj){let k=ee.length>>4;t.uniform1i(Q.uInstanced,1),t.uniformMatrix4fv(Q.uViewProj,!1,s),Y.indices?t.drawElementsInstanced(4,Y.indexCount,Y.indexType,0,k):t.drawArraysInstanced(4,0,Y.indexCount,k),t.uniform1i(Q.uInstanced,0)}else if(ee&&ee.length>=16){let k=ee.length>>4,G=C.instanceColors,q=rt(),H=new Float32Array(9);for(let te=0;te<k;te++){if(at(q,this.modelMatrix,ee.subarray(te*16,te*16+16)),at(this.mvpMatrix,s,q),Bt(H,q),t.uniformMatrix4fv(Q.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(Q.uModel,!1,q),t.uniformMatrix3fv(Q.uNormalMatrix,!1,H),G){let Z=Y.baseColor,ae=te*3;t.uniform4fv(Q.uBaseColor,[Z[0]*G[ae],Z[1]*G[ae+1],Z[2]*G[ae+2],Z[3]])}hs(t,Y)}}else hs(t,Y)}}};if(S(!1),A){for(let E of kt)E.onBeforeTransmissivePass?.(t,this);S(!0)}for(let E of kt)E.onAfterRender?.(t,this,s,v,[r,i,n,a],l)}disposeMeshListGpuResources(e,t){Bd(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 kt)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()}};Ht.registerPlugin=gt,Ht.getRegisteredPlugins=as;function _p(e){return e+3&-4}var Je=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t;function Xc(e,t){let r=t,i=1;for(;e.has(r);)r=`${t}_${i++}`;return e.add(r),r}function Vd(e,t,r){let i=Math.hypot(e,t,r)||1,n=e/i,a=t/i,s=-(r/i);if(s<-.999999)return[0,1,0,0];let o=Math.sqrt((1+s)*2);return[a/o,-n/o,0,o*.5]}function Od(e,t=0){let[r,i,n,,a,s,o,,l,c,f,,m,h,p]=Array.from({length:15},(ee,k)=>Je(e[t+k],k%5===0?1:0)),g=Math.hypot(r,i,n),x=Math.hypot(a,s,o),v=Math.hypot(l,c,f);r*(s*f-c*o)-a*(i*f-c*n)+l*(i*o-s*n)<0&&(g=-g);let y=Math.abs(g)>1e-8?1/g:0,A=Math.abs(x)>1e-8?1/x:0,b=Math.abs(v)>1e-8?1/v:0,w=r*y,S=i*y,E=n*y,N=a*A,C=s*A,_=o*A,P=l*b,R=c*b,$=f*b,F=w+C+$,V=0,Y=0,J=0,re=1;if(F>0){let ee=.5/Math.sqrt(F+1);re=.25/ee,V=(_-R)*ee,Y=(P-E)*ee,J=(S-N)*ee}else if(w>C&&w>$){let ee=2*Math.sqrt(Math.max(0,1+w-C-$));ee>1e-8&&(re=(_-R)/ee,V=.25*ee,Y=(N+S)/ee,J=(P+E)/ee)}else if(C>$){let ee=2*Math.sqrt(Math.max(0,1+C-w-$));ee>1e-8&&(re=(P-E)/ee,V=(N+S)/ee,Y=.25*ee,J=(_+R)/ee)}else{let ee=2*Math.sqrt(Math.max(0,1+$-w-C));ee>1e-8&&(re=(S-N)/ee,V=(P+E)/ee,Y=(_+R)/ee,J=.25*ee)}let Q=Math.hypot(V,Y,J,re);return Q>1e-8&&Number.isFinite(Q)?(V/=Q,Y/=Q,J/=Q,re/=Q):(V=0,Y=0,J=0,re=1),{t:[m,h,p],r:[V,Y,J,re],s:[g,x,v]}}function Ep(e){let t={};return e.grab&&(t.interactable={mode:typeof e.grab=="string"?e.grab:"2-hand"},t.movable={scaleInZ:!!e.scale,minScale:typeof e.scale=="object"?e.scale.min??.1:.1,maxScale:typeof e.scale=="object"?e.scale.max??10:10}),e.billboard&&(t.billboard={mode:typeof e.billboard=="string"?e.billboard:"capsule"}),e.follow&&(t.follow={target:typeof e.follow=="object"?e.follow.mode??"head":e.follow}),e.anchor&&(t.anchor={plane:e.anchor}),e.physics&&e.physics!=="none"&&(t.rigidbody={type:e.physics}),t}var Nn=(e,t,r,i)=>typeof e=="number"&&Number.isFinite(e)?Math.max(t,Math.min(r,e)):i;function zd(e){let t=e?.audioEmitter??e?.spatialAudio??(typeof e?.audio=="object"&&e.audio&&("preset"in e.audio||"distanceModel"in e.audio||"coneInnerAngle"in e.audio||"maxDistance"in e.audio||"volume"in e.audio)?e.audio:typeof e?.audio=="string"&&/^(hum|reactor|wind|beacon|geiger|chimeLoop|machinery|water)$/.test(e.audio)?{preset:e.audio}:void 0);if(!t||typeof t=="object"&&t.enabled===!1)return null;let r=typeof t=="string"?{preset:t}:t,i=typeof r.src=="string"&&!/[\x00-\x20\\%]|^\s*(javascript|data|file|http):/i.test(r.src)?r.src:void 0,n=typeof r.preset=="string"?r.preset:void 0;return!i&&!n?null:{ae:r,src:i,preset:n,volume:Nn(r.volume,0,2,.6),loop:typeof r.loop=="boolean"?r.loop:!0,isGlobal:r.type==="global"||r.positional===!1}}function kp(e){let t=e?.material,r=t?._presetMaps?.map;if(!r||r!==t.map)return null;let i=/^ai_([0-9a-f]{16})_albedo$/.exec(String(r.name??""));return i?i[1]:null}function Qr(e,t){return $d(e,t)[0]}function $d(e,t){e.updateMatrixWorld(!0);let r=[],i=0,n=[],a=[],s=[],o=[],l=new Set,c=[],f=[],m=new Map,h=[],p=[],g=[],x=new Map,v=[],y=[],A=[],b=!1;function w(k){let G=m.get(k);if(G!==void 0)return G;G=f.length,m.set(k,G);let q=k,H=q.color?.r??1,te=q.color?.g??1,Z=q.color?.b??1,ae=q.opacity??1,ie={baseColorFactor:[H,te,Z,ae],metallicFactor:q.metalness??0,roughnessFactor:q.roughness??.5},de={},me=he=>{if(!he)return;let Ne=(typeof he=="string"?he:typeof he.source=="string"?he.source:typeof he.image=="string"?he.image:"").trim();if(!Ne||/[\x00-\x1f\x7f\\]|\.\./.test(Ne)||!(/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(Ne)||!Ne.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(Ne)))return;let ge=x.get(Ne);if(ge===void 0){let Ae=h.length;h.push({uri:Ne}),p.length===0&&p.push({magFilter:9729,minFilter:9987,wrapS:10497,wrapT:10497}),ge=g.length,g.push({sampler:0,source:Ae}),x.set(Ne,ge)}return{index:ge}},Se=q._packPbr?.(),Fe=me(q.map);Fe&&(ie.baseColorTexture=Fe);let _e=me(Se?.mrUri||q.roughnessMap||q.metalnessMap);_e&&(ie.metallicRoughnessTexture=_e);let Le=q.map?.avgColor;Array.isArray(Le)&&Le.length>=3&&(de.avgColor=[Le[0],Le[1],Le[2]]);let ne=me(Se?.normUri||q.normalMap),Re=q.normalScale,W=Se?.normUri?Se.normScale??1:typeof Re=="number"?Math.max(0,Je(Re,1)):Re?Math.max(0,(Je(Re.x,1)+Je(Re.y,1))*.5):1;ne&&W!==1&&(ne.scale=W);let D=me(q.emissiveMap),z=me(q.aoMap),O=Math.max(0,Math.min(1,Je(q.aoMapIntensity,1)));z&&O!==1&&(z.strength=O);let X={name:q.name||"",pbrMetallicRoughness:ie,doubleSided:q.side===2||!!q.doubleSided,...ae<1||q.transparent?{alphaMode:"BLEND"}:{},...ne?{normalTexture:ne}:{},...D?{emissiveTexture:D}:{},...z?{occlusionTexture:z}:{},...Object.keys(de).length>0?{extras:de}:{}},se=Math.max(0,Je(q.emissiveIntensity,1)),ce=q.emissive&&(q.emissive.r>0||q.emissive.g>0||q.emissive.b>0);(ce||D&&!q._em&&se>0)&&(X.emissiveFactor=ce?[q.emissive.r*se,q.emissive.g*se,q.emissive.b*se]:[se,se,se]);let pe={};q.clearcoat&&q.clearcoat>0&&(pe.KHR_materials_clearcoat={clearcoatFactor:q.clearcoat,clearcoatRoughnessFactor:q.clearcoatRoughness||0}),q.sheen&&q.sheen>0&&(pe.KHR_materials_sheen={sheenColorFactor:q.sheenColor?[q.sheenColor.r,q.sheenColor.g,q.sheenColor.b]:[1,1,1],sheenRoughnessFactor:q.sheenRoughness||0}),q.transmission&&q.transmission>0&&(pe.KHR_materials_transmission={transmissionFactor:q.transmission}),q.thickness&&q.thickness>0&&(pe.KHR_materials_volume={thicknessFactor:q.thickness,attenuationDistance:q.attenuationDistance??1/0,attenuationColor:q.attenuationColor?[q.attenuationColor.r,q.attenuationColor.g,q.attenuationColor.b]:[1,1,1]}),q.ior!==void 0&&q.ior!==1.5&&(pe.KHR_materials_ior={ior:q.ior}),q.dispersion&&q.dispersion>0&&(pe.KHR_materials_dispersion={dispersion:q.dispersion}),q.iridescence&&q.iridescence>0&&(pe.KHR_materials_iridescence={iridescenceFactor:q.iridescence,iridescenceIor:q.iridescenceIOR??1.3});let xe=q._serializeTslGraph?.();return xe&&(pe.GOOGLE_material_tsl=xe,l.add("GOOGLE_material_tsl")),Object.keys(pe).length>0&&(X.extensions=pe),f.push(X),G}function S(k,G){let q=new Uint8Array(k.buffer,k.byteOffset,k.byteLength),H=_p(q.byteLength),te=new Uint8Array(H);te.set(q),r.push(te);let Z=n.length;return n.push({buffer:0,byteOffset:i,byteLength:q.byteLength,target:G}),i+=H,Z}function E(k,G,q,H,te,Z,ae){let ie=S(k,q),de=a.length,me={bufferView:ie,byteOffset:0,componentType:H,count:te,type:G};return Z&&(me.min=Z),ae&&(me.max=ae),a.push(me),de}let N=[],C=[],_=new Set([e]),P=[];if(Array.isArray(e.children))for(let k=e.children.length-1;k>=0;k--)P.push({obj:e.children[k],parentKids:C});for(;P.length>0;){let{obj:k,parentKids:G}=P.pop();if(!k||typeof k!="object"||_.has(k))continue;_.add(k),k._bakeAuthorGeometry?.(),He().materializeDeclarativeGeometry?.(k);let q=!!(k.userData&&(k.userData.xr&&typeof k.userData.xr=="object"&&Object.keys(k.userData.xr).length>0||k.userData.interactivity&&typeof k.userData.interactivity=="object"&&Object.keys(k.userData.interactivity).length>0)),H={name:k.name||(q?`Node_${o.length}`:"")},te=Je(k.position?.x,0),Z=Je(k.position?.y,0),ae=Je(k.position?.z,0),ie=Je(k.quaternion?.x,0),de=Je(k.quaternion?.y,0),me=Je(k.quaternion?.z,0),Se=Je(k.quaternion?.w,1),Fe=Je(k.scale?.x,1),_e=Je(k.scale?.y,1),Le=Je(k.scale?.z,1);if((te||Z||ae)&&(H.translation=[te,Z,ae]),(ie||de||me||Se!==1)&&(H.rotation=[ie,de,me,Se]),(Fe!==1||_e!==1||Le!==1)&&(H.scale=[Fe,_e,Le]),k.visible===!1&&(H.extensions={...H.extensions||{},KHR_node_visibility:{visible:!1}},l.add("KHR_node_visibility")),k.userData&&Object.keys(k.userData).length>0&&(H.extras=JSON.parse(JSON.stringify(k.userData,(z,O)=>{if(!(z==="__proto__"||z==="prototype"||z==="constructor"))return typeof O=="function"?void 0:O})),k.userData.xr)){let z=Ep(k.userData.xr);H.extensions={...H.extensions||{},MOZ_hubs_components:z,ANDROID_xr_scenecore:z},He().xrTraitSerializer?.gltfNode(H,k.userData.xr);let O=kp(k),X=H.extras?.xr?.material;O&&X&&typeof X=="object"&&!Array.isArray(X)&&(X.textureKey=O),l.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}let ne=k,Re=ne.isLight||ne.color&&ne.intensity!==void 0;if(!Re&&(ne._castShdSet||ne._recvShdSet||k.castShadow||k.receiveShadow)&&(H.extras={...H.extras||{},shadow:{cast:!!k.castShadow,receive:ne._recvShdSet?!!k.receiveShadow:!!(k.receiveShadow||k.castShadow)}}),Re){let z=ne.matrixWorld?.elements,O=Je(z?z[12]:k.position?.x,0),X=Je(z?z[13]:k.position?.y,0),se=Je(z?z[14]:k.position?.z,0),ce=ne.target,pe=ce?.parent?ce?.matrixWorld?.elements:void 0,xe=Je(pe?pe[12]:ce?.position?.x,0),he=Je(pe?pe[13]:ce?.position?.y,0),Ne=Je(pe?pe[14]:ce?.position?.z,0),ge=xe-O,Ae=he-X,Ee=Ne-se,De=Math.hypot(ge,Ae,Ee),ke=Math.max(.01,Math.min(Math.PI/2,Je(ne.angle,Math.PI/3))),ze=Math.max(0,Math.min(1,Je(ne.penumbra,0))),Be=Math.max(0,ke*(1-ze)),Ue=Math.max(0,Je(ne.distance,0)),We=k.type==="directional"||k.type==="spot"||k.type==="point",Ge;if(k.castShadow&&We){let Qe=ne.shadow,It=Math.max(256,Math.min(2048,Math.round(Je(Qe?.mapSize?.x??Qe?.mapSize?.width,1024))));Ge={cast:!0,mapSize:It<=384?256:It<=768?512:It<=1536?1024:2048,bias:Nn(Qe?.bias,-.05,.05,-5e-4),normalBias:Nn(Qe?.normalBias,0,.2,.015),radius:Nn(Qe?.radius,0,8,1.5)},b=!0}let ut=O-xe,nt=X-he,st=se-Ne,ft=Math.hypot(ut,nt,st);y.push({type:k.type,color:[k.color.r,k.color.g,k.color.b],intensity:k.intensity,position:k.type==="directional"?[ut,nt,st]:[O,X,se],...k.type==="directional"?{direction:ft>1e-6?[ut/ft,nt/ft,st/ft]:[0,1,0]}:k.type==="spot"?{direction:De>1e-6?[ge/De,Ae/De,Ee/De]:[0,-1,0],outerConeAngle:ke,innerConeAngle:Be,range:Ue}:k.type==="point"?{range:Ue}:k.type==="hemisphere"&&ne.groundColor?{groundColor:[ne.groundColor.r,ne.groundColor.g,ne.groundColor.b]}:{},...Ge?{shadow:Ge}:{}}),We&&N.push({node:H,obj:k,px:O,py:X,pz:se,tx:xe,ty:he,tz:Ne,dx:ge,dy:Ae,dz:Ee,dLen:De,outerAngle:ke,innerAngle:Be,range:Ue,shadowSpec:Ge})}if(k.geometry){let z=k.geometry,O=z.attributes.position;if(O&&O.count>0){let X=[1/0,1/0,1/0],se=[-1/0,-1/0,-1/0];for(let ge=0;ge<O.count;ge++){let Ae=O.getX(ge),Ee=O.getY(ge),De=O.getZ(ge);Ae<X[0]&&(X[0]=Ae),Ae>se[0]&&(se[0]=Ae),Ee<X[1]&&(X[1]=Ee),Ee>se[1]&&(se[1]=Ee),De<X[2]&&(X[2]=De),De>se[2]&&(se[2]=De)}let ce={attributes:{POSITION:E(O.array,"VEC3",34962,5126,O.count,X,se)}};if(z.attributes.normal&&(ce.attributes.NORMAL=E(z.attributes.normal.array,"VEC3",34962,5126,z.attributes.normal.count)),z.attributes.uv&&(ce.attributes.TEXCOORD_0=E(z.attributes.uv.array,"VEC2",34962,5126,z.attributes.uv.count)),z.index){let ge=z.index.array instanceof Uint32Array;ce.indices=E(z.index.array,"SCALAR",34963,ge?5125:5123,z.index.count)}let pe=Array.isArray(k.material)?k.material[0]:k.material;pe&&(ce.material=w(pe));let xe=k.userData?.variants;if(xe&&typeof xe=="object"){let ge=new Map;for(let Ae of Object.keys(xe)){if(!Ae||Ae==="__proto__"||Ae==="constructor"||Ae==="prototype")continue;let Ee=xe[Ae];if(!Ee||typeof Ee!="object")continue;let De=v.indexOf(Ae);if(De===-1&&v.length<256&&(De=v.length,v.push(Ae)),De===-1)continue;let ke=w(Ee),ze=ge.get(ke);ze||(ze=[],ge.set(ke,ze)),ze.push(De)}if(ge.size>0){let Ae=[];for(let[Ee,De]of ge.entries())Ae.push({material:Ee,variants:De});ce.extensions={...ce.extensions||{},KHR_materials_variants:{mappings:Ae}},l.add("KHR_materials_variants")}}let he=k;if(he.isInstancedMesh&&typeof he.count=="number"&&he.count>0&&he.instanceMatrix?.array){let ge=Math.min(1e4,Math.floor(he.count)),Ae=he.instanceMatrix.array,Ee=new Float32Array(ge*3),De=new Float32Array(ge*4),ke=new Float32Array(ge*3);for(let Be=0;Be<ge;Be++){let{t:Ue,r:We,s:Ge}=Od(Ae,Be*16);Ee[Be*3]=Ue[0],Ee[Be*3+1]=Ue[1],Ee[Be*3+2]=Ue[2],De[Be*4]=We[0],De[Be*4+1]=We[1],De[Be*4+2]=We[2],De[Be*4+3]=We[3],ke[Be*3]=Ge[0],ke[Be*3+1]=Ge[1],ke[Be*3+2]=Ge[2]}let ze={TRANSLATION:E(Ee,"VEC3",0,5126,ge),ROTATION:E(De,"VEC4",0,5126,ge),SCALE:E(ke,"VEC3",0,5126,ge)};if(he.instanceColor?.array&&he.instanceColor.array.length>=ge*3){let Be=new Float32Array(he.instanceColor.array.subarray(0,ge*3));ze._COLOR_0=E(Be,"VEC3",0,5126,ge)}H.extensions={...H.extensions||{},EXT_mesh_gpu_instancing:{attributes:ze}},l.add("EXT_mesh_gpu_instancing")}let Ne=s.length;s.push({primitives:[ce],name:k.name,...H.extras?{extras:H.extras}:{}}),H.mesh=Ne}}let W=o.length;o.push(H),c.push(k),G.push(W);let D=k.children;if(Array.isArray(D)&&D.length>0){let z=[];H.children=z;for(let O=D.length-1;O>=0;O--)P.push({obj:D[O],parentKids:z})}}if(b)for(let k of N){let G=A.length;if(A.push({name:k.obj.name||`Light_${G}`,type:k.obj.type,color:[k.obj.color.r,k.obj.color.g,k.obj.color.b],intensity:k.obj.intensity,...k.range>0&&(k.obj.type==="point"||k.obj.type==="spot")?{range:k.range}:{},...k.obj.type==="spot"?{spot:{innerConeAngle:k.innerAngle,outerConeAngle:k.outerAngle}}:{},...k.shadowSpec?{extras:{shadow:k.shadowSpec}}:{}}),k.node.extensions={...k.node.extensions||{},KHR_lights_punctual:{light:G}},l.add("KHR_lights_punctual"),k.obj.type==="directional"||k.obj.type==="spot"){let q=k.dLen>1e-6?k.dx/k.dLen:0,H=k.dLen>1e-6?k.dy/k.dLen:-1,te=k.dLen>1e-6?k.dz/k.dLen:0;k.node.rotation=Vd(q,H,te),k.obj.type==="directional"&&(k.tx||k.ty||k.tz)&&(k.node.translation=[k.px-k.tx,k.py-k.ty,k.pz-k.tz])}}for(let k=0;k<o.length;k++){let G=o[k];G.children&&G.children.length===0?delete G.children:G.children&&G.children.length>0&&(G.extras?.xr?.lod||G.extensions?.ANDROID_xr_scenecore?.lod||c[k]?.isLOD)&&(G.extensions={...G.extensions||{},MSFT_lod:{ids:[...G.children]}},l.add("MSFT_lod"))}let R=t?.animateCallback||t?.animateFn||(typeof e.userData?.animate=="function"?e.userData.animate:typeof e.__animateFn=="function"?e.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0),$=[];if(typeof R=="function"&&c.length>0){let k=t?.duration??4,G=t?.fps??15,q=Math.max(2,Math.round(k*G)+1),H=new Float32Array(q),te=c.map(_e=>[Je(_e.position?.x,0),Je(_e.position?.y,0),Je(_e.position?.z,0),Je(_e.quaternion?.x,0),Je(_e.quaternion?.y,0),Je(_e.quaternion?.z,0),Je(_e.quaternion?.w,1),Je(_e.scale?.x,1),Je(_e.scale?.y,1),Je(_e.scale?.z,1)]),Z=c.map(()=>new Float32Array(q*3)),ae=c.map(()=>new Float32Array(q*4)),ie=c.map(()=>new Float32Array(q*3));for(let _e=0;_e<q;_e++){let Le=_e/(q-1)*k;H[_e]=Le;try{R(Le)}catch{}for(let ne=0;ne<c.length;ne++){let Re=c[ne];Z[ne][_e*3]=Je(Re.position?.x,0),Z[ne][_e*3+1]=Je(Re.position?.y,0),Z[ne][_e*3+2]=Je(Re.position?.z,0);let W=Je(Re.quaternion?.x,0),D=Je(Re.quaternion?.y,0),z=Je(Re.quaternion?.z,0),O=Je(Re.quaternion?.w,1),X=Math.hypot(W,D,z,O)||1;if(W/=X,D/=X,z/=X,O/=X,_e>0){let se=(_e-1)*4,ce=ae[ne];ce[se]*W+ce[se+1]*D+ce[se+2]*z+ce[se+3]*O<0&&(W=-W,D=-D,z=-z,O=-O)}ae[ne][_e*4]=W,ae[ne][_e*4+1]=D,ae[ne][_e*4+2]=z,ae[ne][_e*4+3]=O,ie[ne][_e*3]=Je(Re.scale?.x,1),ie[ne][_e*3+1]=Je(Re.scale?.y,1),ie[ne][_e*3+2]=Je(Re.scale?.z,1)}}for(let _e=0;_e<c.length;_e++){let Le=c[_e],ne=te[_e];Le.position?.set(ne[0],ne[1],ne[2]),Le.quaternion?.set(ne[3],ne[4],ne[5],ne[6]),Le.scale?.set(ne[7],ne[8],ne[9])}e.updateMatrixWorld(!0);let de=null,me=()=>(de===null&&(de=E(H,"SCALAR",0,5126,q,[0],[k])),de),Se=[],Fe=[];for(let _e=0;_e<c.length;_e++){let Le=te[_e],ne=(W,D,z)=>W.some((O,X)=>Math.abs(O-Le[z+X%D])>1e-4),Re=(W,D,z,O)=>{W&&Fe.push({sampler:Se.push({input:me(),interpolation:"LINEAR",output:E(D,z,0,5126,q)})-1,target:{node:_e,path:O}})};Re(ne(Z[_e],3,0),Z[_e],"VEC3","translation"),Re(ne(ae[_e],4,3),ae[_e],"VEC4","rotation"),Re(ne(ie[_e],3,7),ie[_e],"VEC3","scale")}Fe.length>0&&$.push({name:"ProceduralLoop",samplers:Se,channels:Fe})}let F=fd(o,s,e.userData),V=[],Y=[],J=[];for(let k=0;k<o.length;k++){let G=o[k],q=zd(G.extras?.xr);if(!q)continue;let{ae:H,src:te,preset:Z,volume:ae,loop:ie,isGlobal:de}=q,me=G.name||`Node_${k}`,Se=Y.length;Y.push({name:`${me}_source`,gain:ae,loop:ie,autoPlay:typeof H.autoplay=="boolean"?H.autoplay:!0,...te!==void 0?{audio:V.push({uri:te})-1}:{},...Z?{extras:{preset:Z,pitch:Nn(H.pitch,.25,4,1)}}:{}});let Fe=J.length,_e=Nn(H.refDistance,.05,100,1),Le=Nn(H.coneInnerAngle,0,360,360),ne=Nn(H.coneOuterAngle,Le,360,360);J.push({name:`${me}_emitter`,type:de?"global":"positional",gain:ae,sources:[Se],...de?{}:{positional:{distanceModel:H.distanceModel==="linear"||H.distanceModel==="exponential"?H.distanceModel:"inverse",refDistance:_e,maxDistance:Nn(H.maxDistance,_e,500,Math.max(_e,25)),rolloffFactor:Nn(H.rolloffFactor,0,10,1),coneInnerAngle:+(Le*Math.PI/180).toFixed(6),coneOuterAngle:+(ne*Math.PI/180).toFixed(6),coneOuterGain:Nn(H.coneOuterGain,0,1,0)}}}),G.extensions={...G.extensions||{},KHR_audio_emitter:{emitter:Fe}},l.add("KHR_audio_emitter")}let re={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:e.environmentIntensity,...y.length>0?{lights:y}:{}}},scenes:[{nodes:C}],scene:0,nodes:o,meshes:s,materials:f,...h.length>0?{images:h}:{},...p.length>0?{samplers:p}:{},...g.length>0?{textures:g}:{},accessors:a,bufferViews:n,buffers:[{byteLength:i}],...$.length>0?{animations:$}:{},...F||l.size>0?{extensionsUsed:[...F?["KHR_interactivity"]:[],...l]}:{},...F||v.length>0||J.length>0||A.length>0?{extensions:{...F?{KHR_interactivity:F}:{},...v.length>0?{KHR_materials_variants:{variants:v.map(k=>({name:k}))}}:{},...J.length>0?{KHR_audio_emitter:{...V.length>0?{audio:V}:{},sources:Y,emitters:J}}:{},...A.length>0?{KHR_lights_punctual:{lights:A}}:{}}}:{}},Q=new Uint8Array(i),ee=0;for(let k of r)Q.set(k,ee),ee+=k.byteLength;return[{gltf:re,bin:Q.buffer,lights:y,environmentIntensity:e.environmentIntensity},c]}function qc(e){return new TextEncoder().encode(e)}function qo(e,t){let{gltf:r,bin:i}=Qr(e,t),n=JSON.stringify(r),a=qc(n),s=(4-a.byteLength%4)%4,o=a.byteLength+s,l=20+o+8+i.byteLength,c=new Uint8Array(l),f=new DataView(c.buffer);f.setUint32(0,1179937895,!0),f.setUint32(4,2,!0),f.setUint32(8,l,!0),f.setUint32(12,o,!0),f.setUint32(16,1313821514,!0),c.set(a,20);for(let h=0;h<s;h++)c[20+a.byteLength+h]=32;let m=20+o;return f.setUint32(m,i.byteLength,!0),f.setUint32(m+4,5130562,!0),c.set(new Uint8Array(i),m+8),c}function Rp(e,t){let[r,i]=$d(e,t);return Gd(r,i)}function Gd(e,t){let r=[],i=e.gltf,n=He().decoders.get("meshopt");n&&typeof n.decodeBufferViews=="function"&&n.decodeBufferViews(i,e);let a=e.bin,s=a instanceof ArrayBuffer?a:a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),o=i.accessors||[],l=i.bufferViews||[],c=i.materials||[],f=i.meshes||[],m=i.nodes||[],h=i.textures||[],p=i.images||[],g=i.samplers||[],x=new Set,v=c.map((C,_)=>Xc(x,Xo(C?.name,`Material_${_}`))),y=new Map;function A(C){let _=/^data:image\/(png|jpe?g)(?:;[^,]*)?;base64,([A-Za-z0-9+/=\s]+)$/i.exec(C);if(!_)return null;let P=_[2].replace(/\s+/g,""),R=P.endsWith("==")?2:P.endsWith("=")?1:0,$=new Uint8Array((P.length*3>>2)-R),F=Y=>{let J=P.charCodeAt(Y);return J>96?J-71:J>64?J-65:J>47?J+4:J===43?62:J===47?63:0},V=0;for(let Y=0;Y<P.length;Y+=4){let J=F(Y)<<18|F(Y+1)<<12|F(Y+2)<<6|F(Y+3);$[V++]=J>>16&255,V<$.length&&($[V++]=J>>8&255),V<$.length&&($[V++]=J&255)}return $}function b(C,_,P){let R=C?.index;if(typeof R!="number")return;let $=h[R],F=$?.source;if(typeof F!="number"||!p[F])return;let V=y.get(F);if(V===void 0){V=null;let re=p[F],Q=null;if(typeof re.bufferView=="number"){let ee=l[re.bufferView],k=ee?.byteOffset||0,G=ee?.byteLength||0;ee&&G>0&&k>=0&&k+G<=s.byteLength&&(Q=new Uint8Array(s,k,G))}else typeof re.uri=="string"&&(Q=A(re.uri));if(Q&&Q.byteLength>0){let ee=Q[0]===255&&Q[1]===216&&Q[2]===255||!(Q[0]===137&&Q[1]===80)&&/jpe?g/i.test(re.mimeType||re.uri||"");V={file:`texture_${F}.${ee?"jpg":"png"}`,data:Q}}y.set(F,V)}if(!V)return;let Y=typeof $.sampler=="number"?g[$.sampler]:void 0,J=re=>re===33071?"clamp":re===33648?"mirror":"repeat";return{file:V.file,data:V.data,wrapS:J(Y?.wrapS),wrapT:J(Y?.wrapT),..._?{scale:_}:{},...P?{bias:P}:{}}}function w(C){let _=o[C];if(!_)throw new Error(`Accessor ${C} not found`);let P=l[_.bufferView||0],R=(P.byteOffset||0)+(_.byteOffset||0),$=P.byteLength||0;return{acc:_,buffer:s.slice(R,R+$)}}function S(C,_,P,R){let $=[],F=f[C];if(!F)return $;let V=F.primitives||[];for(let Y=0;Y<V.length;Y++){let J=V[Y],re=J.attributes?.POSITION;if(re===void 0)continue;let{acc:Q,buffer:ee}=w(re),k=new Float32Array(ee,0,Q.count*3),G,q=J.attributes?.NORMAL;if(q!==void 0){let{acc:D,buffer:z}=w(q),O=new Float32Array(z,0,D.count*3);G=new Float32Array(O.length);for(let X=0;X<D.count;X++){let se=O[X*3],ce=O[X*3+1],pe=O[X*3+2],xe=Math.hypot(se,ce,pe)||1;G[X*3]=se/xe,G[X*3+1]=ce/xe,G[X*3+2]=pe/xe}}let H,te=J.attributes?.TEXCOORD_0;if(te!==void 0){let{acc:D,buffer:z}=w(te);H=new Float32Array(z,0,D.count*2)}let Z;if(J.indices!==void 0){let{acc:D,buffer:z}=w(J.indices);Z=D.componentType===5125?new Uint32Array(z,0,D.count):new Uint16Array(z,0,D.count);let O=Q.count;for(let X of Z)if(X>=O)throw new Error(`SecurityError: Index buffer value (${X}) out of vertex bounds [0, ${O}).`)}else{let D=Q.count;Z=D>65535?new Uint32Array(D):new Uint16Array(D);for(let z=0;z<D;z++)Z[z]=z}let ae="DefaultMaterial",ie=[1,1,1],de=.5,me=0,Se=0,Fe=0,_e=1.5,Le=1,ne=[0,0,0],Re,W={};if(J.material!==void 0&&c[J.material]){let D=c[J.material];ae=v[J.material]||`Material_${J.material}`;let z=D.pbrMetallicRoughness||{},O=(Be,Ue)=>Array.isArray(Be)&&Be.length>=3?[Be[0],Be[1],Be[2]]:Ue;ie=O(z.baseColorFactor,[1,1,1]);let X=Array.isArray(z.baseColorFactor)&&typeof z.baseColorFactor[3]=="number"?z.baseColorFactor[3]:1,se=ie[0]!==1||ie[1]!==1||ie[2]!==1||X!==1,ce=b(z.baseColorTexture,se?[ie[0],ie[1],ie[2],X]:void 0),pe=D.extras?.avgColor;!ce&&Array.isArray(pe)&&pe.length>=3&&(ie=[ie[0]*pe[0],ie[1]*pe[1],ie[2]*pe[2]]),typeof z.roughnessFactor=="number"&&(de=z.roughnessFactor),typeof z.metallicFactor=="number"&&(me=z.metallicFactor);let xe=typeof z.roughnessFactor=="number"?z.roughnessFactor:1,he=typeof z.metallicFactor=="number"?z.metallicFactor:1,Ne=b(z.metallicRoughnessTexture,xe!==1||he!==1?[1,xe,he,1]:void 0);ne=O(D.emissiveFactor,[0,0,0]);let ge=(ne[0]>0||ne[1]>0||ne[2]>0)&&(ne[0]!==1||ne[1]!==1||ne[2]!==1)?[ne[0],ne[1],ne[2],1]:void 0,Ae=b(D.emissiveTexture,ge),Ee=typeof D.normalTexture?.scale=="number"?D.normalTexture.scale:1,De=b(D.normalTexture,[2*Ee,2*Ee,2,1],[-Ee,-Ee,-1,0]),ke=typeof D.occlusionTexture?.strength=="number"?D.occlusionTexture.strength:1,ze=ke!==1?b(D.occlusionTexture,[ke,ke,ke,1],[1-ke,1-ke,1-ke,0]):b(D.occlusionTexture);(ce||Ne||De||Ae||ze)&&(Re=[ce,Ne,De,Ae,ze]),W=D.extensions||{},W.KHR_materials_clearcoat&&(Se=W.KHR_materials_clearcoat.clearcoatFactor??0,Fe=W.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),typeof W.KHR_materials_ior?.ior=="number"&&(_e=W.KHR_materials_ior.ior),Le=X*(1-(W.KHR_materials_transmission?.transmissionFactor??0))}$.push({name:V.length>1?`${_}_p${Y}`:_,positions:k,indices:Z,normals:G,uvs:H,materialName:ae,color:ie,roughness:de,metallic:me,clearcoat:Se,clearcoatRoughness:Fe,ior:_e,opacity:Le,emissiveColor:ne,...Re?{textures:Re}:{},...W.GOOGLE_material_tsl?{tslGraph:W.GOOGLE_material_tsl}:{},xrTraits:P||F.extras?.xr,...R?{invisible:!0}:{}})}return $}if(m.length>0){let C=new Float32Array(0),_=new Uint16Array(0),P=(k,G)=>{if(k===void 0)return null;let{acc:q,buffer:H}=w(k);return new Float32Array(H,0,q.count*G)},R=(k,G)=>Array.isArray(k)&&k.length>=3?[Je(k[0],G),Je(k[1],G),Je(k[2],G)]:[G,G,G],$=(k,G,q)=>k&&k.length>=(G+1)*3?[k[G*3],k[G*3+1],k[G*3+2]]:q,F=(k,G,q)=>k&&k.length>=(G+1)*4?[k[G*4],k[G*4+1],k[G*4+2],k[G*4+3]]:q,V=new Map,Y=i.animations?.[0];if(Y&&Array.isArray(Y.channels)&&Array.isArray(Y.samplers))for(let k of Y.channels){let G=Y.samplers[k?.sampler],q=k?.target?.node,H=k?.target?.path;if(!G||typeof q!="number"||G.input===void 0)continue;let te=V.get(q);te||(te={input:G.input},V.set(q,te)),H==="translation"?te.t=G.output:H==="rotation"?te.r=G.output:H==="scale"&&(te.s=G.output)}let J=i.scenes?.[i.scene??0]?.nodes??[];if(!Array.isArray(J)||J.length===0){let k=new Set;for(let G of m)if(Array.isArray(G?.children))for(let q of G.children)k.add(q);J=[];for(let G=0;G<m.length;G++)k.has(G)||J.push(G);J.length===0&&(J=[0])}let re=new Set,Q=[],ee=(k,G)=>{if(Array.isArray(k))for(let q=k.length-1;q>=0;q--)Q.push({idx:k[q],out:G})};for(ee(J,r);Q.length>0;){let{idx:k,out:G}=Q.pop();if(typeof k!="number"||k<0||k>=m.length||re.has(k))continue;re.add(k);let q=m[k];if(!q)continue;let H=[0,0,0],te=[0,0,0,1],Z=[1,1,1];if(Array.isArray(q.matrix)&&q.matrix.length===16){let Le=Od(q.matrix);H=Le.t,te=Le.r,Z=Le.s}else H=R(q.translation,0),Array.isArray(q.rotation)&&q.rotation.length>=4&&(te=[Je(q.rotation[0],0),Je(q.rotation[1],0),Je(q.rotation[2],0),Je(q.rotation[3],1)]),Z=R(q.scale,1);let ae,ie=V.get(k);if(ie){let Le=P(ie.input,1);if(Le&&Le.length>0){let ne=P(ie.t,3),Re=P(ie.r,4),W=P(ie.s,3),D=Array.from(Le),z=[],O=[],X=[];for(let se=0;se<Le.length;se++)z.push($(ne,se,H)),O.push(F(Re,se,te)),X.push($(W,se,Z));ae={times:D,translations:z,rotations:O,scales:X}}}let de=Array.isArray(q.children)?q.children:[],me=typeof q.mesh=="number"&&q.mesh>=0&&q.mesh<f.length,Se=t?.[k]?.userData?.xr??q.extras?.xr;if(!me&&de.length===0&&(q.camera!==void 0||q.extensions?.KHR_lights_punctual||!q.name&&!q.extras&&!Se&&!ae))continue;let Fe=(Le,ne,Re)=>({name:Le,positions:C,indices:_,isXform:!0,xrTraits:Se,timeSamples:ae,translation:H,rotation:te,scale:Z,children:ne,...Re?{invisible:!0}:{}}),_e=q.visible===!1||q.extensions?.KHR_node_visibility?.visible===!1||t?.[k]?.visible===!1;if(me){let Le=q.name||f[q.mesh]?.name||`Mesh_${k}`,ne=S(q.mesh,Le,Se,_e),Re=t?.[k],W=!!(Re?._castShdSet||Re?._recvShdSet),D=typeof q.extras?.shadow?.cast=="boolean"?q.extras.shadow.cast:W?!!Re?.castShadow:void 0;if(D!==void 0)for(let O of ne)O.castShadow=D;let z=q.extensions?.EXT_mesh_gpu_instancing?.attributes;if(z&&typeof z=="object"&&ne.length>0){let O=P(z.TRANSLATION,3),X=P(z.ROTATION,4),se=P(z.SCALE,3),ce=P(z._COLOR_0,3),pe=Math.min(1e3,O?O.length/3:X?X.length/4:se?se.length/3:0);if(pe>0){let xe=[];for(let he=0;he<pe;he++){let Ne=$(O,he,[0,0,0]),ge=F(X,he,[0,0,0,1]),Ae=$(se,he,[1,1,1]);for(let Ee of ne){let De=Ee.color||[.8,.8,.8],ke=ce&&ce.length>=(he+1)*3;xe.push({...Ee,name:`${Ee.name}_${he}`,materialName:ke?`${Ee.materialName}_inst_${he}`:Ee.materialName,color:ke?[De[0]*ce[he*3],De[1]*ce[he*3+1],De[2]*ce[he*3+2]]:Ee.color,translation:Ne,rotation:ge,scale:Ae})}}ee(de,xe),G.push(Fe(Le,xe,_e));continue}}if(ne.length===1)ne[0].translation=H,ne[0].rotation=te,ne[0].scale=Z,ne[0].timeSamples=ae,de.length>0&&(ne[0].children=[],ee(de,ne[0].children)),G.push(ne[0]);else{let O=[...ne];ee(de,O),G.push(Fe(Le,O,_e))}}else{let Le=[];ee(de,Le),G.push(Fe(q.name||`Group_${k}`,Le,_e))}}}else for(let C=0;C<f.length;C++){let _=f[C].name||`Mesh_${C}`;r.push(...S(C,_,f[C].extras?.xr))}let E=(Array.isArray(e.lights)&&e.lights.length>0?e.lights:void 0)??Wc(i)??(Array.isArray(i?.asset?.extras?.lights)?i.asset.extras.lights:[]),N=[];for(let C=0;C<E.length;C++){let _=E[C];_?.shadow?.cast&&(_.type==="directional"||_.type==="spot"||_.type==="point")&&N.push({name:`Light_${C}`,type:_.type,color:_.color,intensity:_.intensity,position:_.position,direction:_.direction,range:_.range,innerConeAngle:_.innerConeAngle,outerConeAngle:_.outerConeAngle,shadow:_.shadow})}return N.length>0&&(r.__usdaShadowLights=N),r}function Xo(e,t){if(!e||typeof e!="string")return t;let r=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(r)&&(r="_"+r),r||t}function gs(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Ct(e){if(!Number.isFinite(e)||Math.abs(e)<1e-7)return"0";let t=Number(e.toFixed(5)).toString();return t.indexOf(".")===-1?`${t}.0`:t}var Dn=(e,t,r)=>`(${Ct(e)}, ${Ct(t)}, ${Ct(r)})`,Wo=(e,t,r,i)=>`(${Ct(e)}, ${Ct(t)}, ${Ct(r)}, ${Ct(i)})`;function Fd(e){let t=e.length/3,r=new Array(t);for(let i=0;i<t;i++)r[i]=Dn(e[i*3],e[i*3+1],e[i*3+2]);return r.join(", ")}function Lp(e,t){let r=new Array(t);for(let i=0;i<t;i++)r[i]=`(${Ct(e[i*2])}, ${Ct(1-e[i*2+1])})`;return r.join(", ")}function Pp(e){return Array.from(e).join(", ")}function Ip(e,t){let r=(t??e.__usdaShadowLights??[]).filter(v=>v?.shadow?.cast),i=new Map,n=0,a=null,s=[...e];for(;s.length>0;){let v=s.pop();if(!v.isXform&&v.positions&&v.positions.length>0){let y=Xo(v.materialName,"DefaultMaterial");i.has(y)||i.set(y,{color:v.color||[1,1,1],roughness:v.roughness??.5,metallic:v.metallic??0,clearcoat:v.clearcoat??0,clearcoatRoughness:v.clearcoatRoughness??0,ior:v.ior??1.5,opacity:v.opacity??1,emissiveColor:v.emissiveColor||[0,0,0],textures:v.textures,tslGraph:v.tslGraph})}if(v.timeSamples&&v.timeSamples.times.length>0){let y=v.timeSamples.times[v.timeSamples.times.length-1];y>n&&(n=y)}else v.tslGraph&&n<=0&&JSON.stringify(v.tslGraph).includes('"time"')&&(n=60);if(v.xrTraits?.anchor&&!a&&(a=v.xrTraits.anchor==="vertical"||v.xrTraits.anchor==="wall"?"vertical":"horizontal"),v.children)for(let y=v.children.length-1;y>=0;y--)s.push(v.children[y])}let o="";n>0&&(o=`startTimeCode = 0
|
|
216
|
+
endTimeCode = ${Ct(n)}
|
|
252
217
|
timeCodesPerSecond = 1.0
|
|
253
|
-
`);let l="";
|
|
254
|
-
uniform token preliminary:planeAnchoring:alignment = "${
|
|
255
|
-
`);let
|
|
218
|
+
`);let l="";a&&(l=`uniform token preliminary:anchoring:type = "plane"
|
|
219
|
+
uniform token preliminary:planeAnchoring:alignment = "${a}"
|
|
220
|
+
`);let c=`#usda 1.0
|
|
256
221
|
(
|
|
257
222
|
defaultPrim = "Root"
|
|
258
223
|
metersPerUnit = 1.0
|
|
259
224
|
upAxis = "Y"
|
|
260
|
-
${
|
|
225
|
+
${o})
|
|
261
226
|
|
|
262
227
|
def Xform "Root" (
|
|
263
228
|
kind = "component"
|
|
@@ -265,141 +230,224 @@ kind = "component"
|
|
|
265
230
|
{
|
|
266
231
|
${l}def Scope "Materials"
|
|
267
232
|
{
|
|
268
|
-
`;for(let[
|
|
269
|
-
float inputs:roughness${
|
|
270
|
-
float inputs:roughness = ${
|
|
271
|
-
`,
|
|
272
|
-
`),
|
|
273
|
-
`),
|
|
274
|
-
`)
|
|
275
|
-
`:(
|
|
276
|
-
`),
|
|
277
|
-
`),
|
|
278
|
-
`);let
|
|
233
|
+
`;for(let[v,y]of i.entries()){let[A,b,w]=y.color,[S,E,N]=y.emissiveColor,C=`/Root/Materials/${v}`,[_,P,R,$,F]=y.textures||[],V=(G,q)=>`.connect = <${C}/${G}.outputs:${q}>`,Y=_?`color3f inputs:diffuseColor${V("DiffuseTexture","rgb")}`:`color3f inputs:diffuseColor = ${Dn(A,b,w)}`,J=P?`float inputs:metallic${V("MetallicRoughnessTexture","b")}
|
|
234
|
+
float inputs:roughness${V("MetallicRoughnessTexture","g")}`:`float inputs:metallic = ${Ct(y.metallic)}
|
|
235
|
+
float inputs:roughness = ${Ct(y.roughness)}`,re="";y.clearcoat>0&&(re+=`float inputs:clearcoat = ${Ct(y.clearcoat)}
|
|
236
|
+
`,re+=`float inputs:clearcoatRoughness = ${Ct(y.clearcoatRoughness)}
|
|
237
|
+
`),y.ior!==1.5&&(re+=`float inputs:ior = ${Ct(y.ior)}
|
|
238
|
+
`),y.opacity<1&&(re+=`float inputs:opacity = ${Ct(y.opacity)}
|
|
239
|
+
`),$?re+=`color3f inputs:emissiveColor${V("EmissiveTexture","rgb")}
|
|
240
|
+
`:(S>0||E>0||N>0)&&(re+=`color3f inputs:emissiveColor = ${Dn(S,E,N)}
|
|
241
|
+
`),R&&(re+=`normal3f inputs:normal${V("NormalTexture","rgb")}
|
|
242
|
+
`),F&&(re+=`float inputs:occlusion${V("OcclusionTexture","r")}
|
|
243
|
+
`);let Q="";if(_||P||R||$||F){Q+=`def Shader "PrimvarReader"
|
|
279
244
|
{
|
|
280
245
|
uniform token info:id = "UsdPrimvarReader_float2"
|
|
281
246
|
string inputs:varname = "st"
|
|
282
247
|
float2 outputs:result
|
|
283
248
|
}
|
|
284
|
-
`;let
|
|
285
|
-
`:"",
|
|
286
|
-
`:"";
|
|
249
|
+
`;let G=(q,H,te,Z)=>{if(!H)return;let ae=H.scale?`float4 inputs:scale = ${Wo(H.scale[0],H.scale[1],H.scale[2],H.scale[3])}
|
|
250
|
+
`:"",ie=H.bias?`float4 inputs:bias = ${Wo(H.bias[0],H.bias[1],H.bias[2],H.bias[3])}
|
|
251
|
+
`:"";Q+=`def Shader "${q}"
|
|
287
252
|
{
|
|
288
253
|
uniform token info:id = "UsdUVTexture"
|
|
289
|
-
asset inputs:file = @${
|
|
290
|
-
float2 inputs:st${
|
|
291
|
-
token inputs:sourceColorSpace = "${
|
|
292
|
-
token inputs:wrapS = "${
|
|
293
|
-
token inputs:wrapT = "${
|
|
294
|
-
${
|
|
295
|
-
`};
|
|
296
|
-
`),
|
|
254
|
+
asset inputs:file = @${gs(H.file)}@
|
|
255
|
+
float2 inputs:st${V("PrimvarReader","result")}
|
|
256
|
+
token inputs:sourceColorSpace = "${te}"
|
|
257
|
+
token inputs:wrapS = "${H.wrapS||"repeat"}"
|
|
258
|
+
token inputs:wrapT = "${H.wrapT||"repeat"}"
|
|
259
|
+
${ae}${ie}${Z}}
|
|
260
|
+
`};G("DiffuseTexture",_,"sRGB",`float3 outputs:rgb
|
|
261
|
+
`),G("MetallicRoughnessTexture",P,"raw",`float outputs:g
|
|
297
262
|
float outputs:b
|
|
298
|
-
`),
|
|
299
|
-
`),
|
|
300
|
-
`),
|
|
301
|
-
`)}
|
|
263
|
+
`),G("NormalTexture",R,"raw",`float3 outputs:rgb
|
|
264
|
+
`),G("EmissiveTexture",$,"sRGB",`float3 outputs:rgb
|
|
265
|
+
`),G("OcclusionTexture",F,"raw",`float outputs:r
|
|
266
|
+
`)}let ee=`${Y}
|
|
267
|
+
${J}
|
|
268
|
+
${re}`,k=y.tslGraph&&He().tslUsdzSerializer?.(y.tslGraph,v,ee);k&&(ee=k.surfaceInputsUsda||ee,Q+=k.nodeGraphUsda),c+=`def Material "${v}"
|
|
302
269
|
{
|
|
303
270
|
def Shader "PBRShader"
|
|
304
271
|
{
|
|
305
272
|
uniform token info:id = "UsdPreviewSurface"
|
|
306
|
-
${
|
|
307
|
-
${w}
|
|
308
|
-
${ie}token outputs:surface
|
|
273
|
+
${ee}token outputs:surface
|
|
309
274
|
}
|
|
310
|
-
token outputs:surface${
|
|
311
|
-
${
|
|
312
|
-
`}
|
|
275
|
+
token outputs:surface${V("PBRShader","surface")}
|
|
276
|
+
${Q}}
|
|
277
|
+
`}c+=`}
|
|
313
278
|
def Scope "Meshes"
|
|
314
279
|
{
|
|
315
|
-
`;let
|
|
280
|
+
`;let f=(v,y,A)=>{let b=[];y&&b.push('"MaterialBindingAPI"');let w=!!(v?.rigidBody&&v.rigidBody!=="none"&&(typeof v.rigidBody!="object"||v.rigidBody.enabled!==!1)),S=!!(v?.physics&&v.physics!=="none"||w);S&&b.push(...w?['"PhysicsBodyAPI"','"PhysicsRigidBodyAPI"','"PhysicsCollisionAPI"','"PhysicsMassAPI"']:['"PhysicsBodyAPI"','"PhysicsCollisionAPI"']);let E=[];b.length>0&&E.push(`prepend apiSchemas = [${b.join(", ")}]`);let N=He().xrTraitSerializer;if(v){let $=N?.usdLines(v,gs)??[];if(!$.length)for(let F of["grab","billboard","follow","anchor","physics"]){let V=F==="follow"&&typeof v.follow=="object"?v.follow.mode??"head":v[F];V!==void 0&&$.push(`string ${F} = "${gs(V)}"`)}$.length>0&&E.push(`customData = {
|
|
316
281
|
dictionary xr = {
|
|
317
|
-
${
|
|
282
|
+
${$.join(`
|
|
318
283
|
`)}
|
|
319
284
|
}
|
|
320
|
-
}`)}let
|
|
321
|
-
${
|
|
285
|
+
}`)}let C=E.length>0?` (
|
|
286
|
+
${E.join(`
|
|
322
287
|
`)}
|
|
323
|
-
)`:"",
|
|
324
|
-
`:"";if(
|
|
325
|
-
bool physics:kinematicEnabled = ${
|
|
288
|
+
)`:"",_=A?`uniform token visibility = "invisible"
|
|
289
|
+
`:"";if(S){let $=v?.rigidBody??v?.physics,F=$?.body??$?.mode??$;_+=`bool physics:rigidBodyEnabled = true
|
|
290
|
+
bool physics:kinematicEnabled = ${F==="static"||F==="kinematic"}
|
|
326
291
|
bool physics:collisionEnabled = true
|
|
327
|
-
|
|
328
|
-
`)}let
|
|
292
|
+
`,$?.mass>0&&Number.isFinite($.mass)&&(_+=`float physics:mass = ${Ct($.mass)}
|
|
293
|
+
`)}let P=zd(v),R=(P?`def SpatialAudio "AudioEmitter"
|
|
329
294
|
{
|
|
330
|
-
${
|
|
331
|
-
`:""}uniform token inputs:auralMode = "${
|
|
332
|
-
uniform token inputs:playbackMode = "${
|
|
333
|
-
double gain = ${
|
|
334
|
-
}
|
|
335
|
-
`:"";return{header:
|
|
336
|
-
quatf xformOp:orient.timeSamples = { ${
|
|
337
|
-
double3 xformOp:scale.timeSamples = { ${
|
|
295
|
+
${P.src?`asset inputs:file = @${gs(P.src)}@
|
|
296
|
+
`:""}uniform token inputs:auralMode = "${P.isGlobal?"nonSpatial":"spatial"}"
|
|
297
|
+
uniform token inputs:playbackMode = "${P.loop?"loopFromStart":"onceFromStart"}"
|
|
298
|
+
double gain = ${Ct(P.volume)}
|
|
299
|
+
}
|
|
300
|
+
`:"")+(v?N?.usdPrims?.(v)??"":"");return{header:C,body:_,tail:R}},m=v=>{if(v.timeSamples&&v.timeSamples.times.length>0){let E=v.timeSamples,N=(R,$,F)=>E.times.map((V,Y)=>`${Ct(V)}: ${F(R?.[Y]||$)}`).join(", "),C=N(E.translations,[0,0,0],R=>Dn(R[0],R[1],R[2])),_=N(E.rotations,[0,0,0,1],R=>{let $=Math.hypot(R[0],R[1],R[2],R[3])||1;return Wo(R[3]/$,R[0]/$,R[1]/$,R[2]/$)}),P=N(E.scales,[1,1,1],R=>Dn(R[0],R[1],R[2]));return`double3 xformOp:translate.timeSamples = { ${C} }
|
|
301
|
+
quatf xformOp:orient.timeSamples = { ${_} }
|
|
302
|
+
double3 xformOp:scale.timeSamples = { ${P} }
|
|
338
303
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:orient", "xformOp:scale"]
|
|
339
|
-
`}let
|
|
340
|
-
`,
|
|
341
|
-
`,
|
|
342
|
-
`,
|
|
343
|
-
`),
|
|
344
|
-
int[] faceVertexCounts = [${
|
|
345
|
-
int[] faceVertexIndices = [${
|
|
346
|
-
point3f[] points = [${
|
|
347
|
-
`;return
|
|
304
|
+
`}let y=[],A="",b=v.translation;b&&(Math.abs(b[0])>1e-7||Math.abs(b[1])>1e-7||Math.abs(b[2])>1e-7)&&(A+=`double3 xformOp:translate = ${Dn(b[0],b[1],b[2])}
|
|
305
|
+
`,y.push('"xformOp:translate"'));let w=v.rotation;if(w){let E=Math.hypot(w[0],w[1],w[2],w[3])||1,N=w[0]/E,C=w[1]/E,_=w[2]/E,P=w[3]/E;(1-Math.abs(P)>1e-7||Math.hypot(N,C,_)>1e-7)&&(A+=`quatf xformOp:orient = ${Wo(P,N,C,_)}
|
|
306
|
+
`,y.push('"xformOp:orient"'))}let S=v.scale;return S&&(Math.abs(S[0]-1)>1e-7||Math.abs(S[1]-1)>1e-7||Math.abs(S[2]-1)>1e-7)&&(A+=`float3 xformOp:scale = ${Dn(S[0],S[1],S[2])}
|
|
307
|
+
`,y.push('"xformOp:scale"')),y.length>0&&(A+=`uniform token[] xformOpOrder = [${y.join(", ")}]
|
|
308
|
+
`),A},h=v=>{let y=v.positions.length/3,A=1/0,b=1/0,w=1/0,S=-1/0,E=-1/0,N=-1/0;for(let $=0;$<y;$++){let F=v.positions[$*3],V=v.positions[$*3+1],Y=v.positions[$*3+2];F<A&&(A=F),F>S&&(S=F),V<b&&(b=V),V>E&&(E=V),Y<w&&(w=Y),Y>N&&(N=Y)}isFinite(A)||(A=b=w=-1,S=E=N=1);let C=Math.floor(v.indices.length/3),_=Xo(v.materialName,"DefaultMaterial"),P=C>0?C===1?"3":"3, ".repeat(C-1)+"3":"",R=`float3[] extent = [${Dn(A,b,w)}, ${Dn(S,E,N)}]
|
|
309
|
+
int[] faceVertexCounts = [${P}]
|
|
310
|
+
int[] faceVertexIndices = [${Pp(v.indices)}]
|
|
311
|
+
point3f[] points = [${Fd(v.positions)}]
|
|
312
|
+
`;return v.normals&&v.normals.length===v.positions.length&&(R+=`normal3f[] normals = [${Fd(v.normals)}] (
|
|
348
313
|
interpolation = "vertex"
|
|
349
314
|
)
|
|
350
|
-
`),
|
|
315
|
+
`),v.uvs&&v.uvs.length===y*2&&(R+=`texCoord2f[] primvars:st = [${Lp(v.uvs,y)}] (
|
|
351
316
|
interpolation = "vertex"
|
|
352
317
|
)
|
|
353
|
-
`),
|
|
354
|
-
`,
|
|
355
|
-
|
|
318
|
+
`),R+=`rel material:binding = </Root/Materials/${_}>
|
|
319
|
+
`,v.castShadow===!1&&r.length>0&&(R+=`bool primvars:doNotCastShadows = 1
|
|
320
|
+
`),R},p=new Set,g=[];for(let v=e.length-1;v>=0;v--)g.push({node:e[v],siblings:p});let x=0;for(;g.length>0;){let v=g.pop();if(v.close){c+=`}
|
|
321
|
+
`;continue}let{node:y,siblings:A}=v,b=!!(y.isXform||y.positions.length===0),w=Xc(A,Xo(y.name,b?`Group_${x}`:`Mesh_${x}`));x++;let S=y.children||[];if(b){let E=f(y.xrTraits,!1,y.invisible);c+=`def Xform "${w}"${E.header}
|
|
356
322
|
{
|
|
357
|
-
${
|
|
323
|
+
${E.body}${m(y)}${E.tail}`,g.push({close:!0});let N=new Set;for(let C=S.length-1;C>=0;C--)g.push({node:S[C],siblings:N})}else if(S.length>0){let E=f(y.xrTraits,!1,y.invisible),N=`${w}_mesh`;c+=`def Xform "${w}"${E.header}
|
|
358
324
|
{
|
|
359
|
-
${
|
|
325
|
+
${E.body}${m(y)}${E.tail}`,c+=`def Mesh "${N}" (
|
|
360
326
|
prepend apiSchemas = ["MaterialBindingAPI"]
|
|
361
327
|
)
|
|
362
328
|
{
|
|
363
|
-
${h(
|
|
364
|
-
`,
|
|
329
|
+
${h(y)}}
|
|
330
|
+
`,g.push({close:!0});let C=new Set([N]);for(let _=S.length-1;_>=0;_--)g.push({node:S[_],siblings:C})}else{let E=f(y.xrTraits,!0,y.invisible);c+=`def Mesh "${w}"${E.header}
|
|
331
|
+
{
|
|
332
|
+
${E.body}${m(y)}${h(y)}${E.tail}}
|
|
333
|
+
`}}if(c+=`}
|
|
334
|
+
`,r.length>0){c+=`def Scope "Lights"
|
|
335
|
+
{
|
|
336
|
+
`;let v=new Set;for(let y=0;y<r.length;y++){let A=r[y],b=Xc(v,Xo(A.name,`Light_${y}`)),w=A.type==="directional"?"DistantLight":A.type==="spot"?"DiskLight":"SphereLight",S=A.type==="spot"?'["ShapingAPI", "ShadowAPI"]':'["ShadowAPI"]',[E,N,C]=A.color||[1,1,1],[_,P,R]=A.position||[0,5,5],$=-_,F=-P,V=-R;A.direction&&A.direction.length>=3&&(A.type==="directional"?($=-A.direction[0],F=-A.direction[1],V=-A.direction[2]):($=A.direction[0],F=A.direction[1],V=A.direction[2]));let[Y,J,re,Q]=Vd($,F,V),ee="",k=[];A.type!=="directional"&&(Math.abs(_)>1e-7||Math.abs(P)>1e-7||Math.abs(R)>1e-7)&&(ee+=`double3 xformOp:translate = ${Dn(_,P,R)}
|
|
337
|
+
`,k.push('"xformOp:translate"')),A.type!=="point"&&(1-Math.abs(Q)>1e-7||Math.hypot(Y,J,re)>1e-7)&&(ee+=`quatf xformOp:orient = ${Wo(Q,Y,J,re)}
|
|
338
|
+
`,k.push('"xformOp:orient"')),k.length>0&&(ee+=`uniform token[] xformOpOrder = [${k.join(", ")}]
|
|
339
|
+
`);let G="";if(A.type==="spot"){let q=(A.outerConeAngle??Math.PI/3)*180/Math.PI,H=(A.innerConeAngle??q*.8)*180/Math.PI,te=q>1e-4?Math.max(0,Math.min(1,1-H/q)):0;G=`float inputs:shaping:cone:angle = ${Ct(q)}
|
|
340
|
+
float inputs:shaping:cone:softness = ${Ct(te)}
|
|
341
|
+
`}c+=`def ${w} "${b}" (
|
|
342
|
+
prepend apiSchemas = ${S}
|
|
343
|
+
)
|
|
344
|
+
{
|
|
345
|
+
color3f inputs:color = ${Dn(E,N,C)}
|
|
346
|
+
float inputs:intensity = ${Ct(A.intensity??1)}
|
|
347
|
+
bool inputs:shadow:enable = 1
|
|
348
|
+
${G}${ee}}
|
|
349
|
+
`}c+=`}
|
|
350
|
+
`}return c+=`}
|
|
351
|
+
`,c}var xs=null;function Yo(e){if(!xs){xs=new Uint32Array(256);for(let r=0;r<256;r++){let i=r;for(let n=0;n<8;n++)i=i&1?3988292384^i>>>1:i>>>1;xs[r]=i}}let t=4294967295;for(let r=0;r<e.length;r++)t=xs[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function jd(e){let t=[],r=0,i=[];for(let f of e){let m=qc(f.filename),h=Yo(f.data),p=f.data.length,g=30+m.length,x=(r+g)%64,v=x!==0?64-x:0;v>0&&v<4&&(v+=64);let y=new Uint8Array(g+v),A=new DataView(y.buffer);A.setUint32(0,67324752,!0),A.setUint16(4,20,!0),A.setUint32(14,h,!0),A.setUint32(18,p,!0),A.setUint32(22,p,!0),A.setUint16(26,m.length,!0),A.setUint16(28,v,!0),y.set(m,30),v>=4&&(A.setUint16(g,6534,!0),A.setUint16(g+2,v-4,!0)),t.push({offset:r,size:p,crc:h,filenameBytes:m,entry:f}),i.push(y,f.data),r+=y.length+f.data.length}let n=r;for(let f of t){let m=new Uint8Array(46+f.filenameBytes.length),h=new DataView(m.buffer);h.setUint32(0,33639248,!0),h.setUint16(4,20,!0),h.setUint16(6,20,!0),h.setUint32(16,f.crc,!0),h.setUint32(20,f.size,!0),h.setUint32(24,f.size,!0),h.setUint16(28,f.filenameBytes.length,!0),h.setUint32(42,f.offset,!0),m.set(f.filenameBytes,46),i.push(m),r+=m.length}let a=r-n,s=new Uint8Array(22),o=new DataView(s.buffer);o.setUint32(0,101010256,!0),o.setUint16(8,t.length,!0),o.setUint16(10,t.length,!0),o.setUint32(12,a,!0),o.setUint32(16,n,!0),i.push(s),r+=22;let l=new Uint8Array(r),c=0;for(let f of i)l.set(f,c),c+=f.length;return l}function Hd(e){let t=[{filename:"model.usda",data:qc(Ip(e))}],r=new Set(["model.usda"]),i=[...e];for(;i.length>0;){let n=i.pop();for(let a of n.textures||[])a?.file&&a.data?.byteLength&&!r.has(a.file)&&(r.add(a.file),t.push({filename:a.file,data:a.data}));if(n.children)for(let a=n.children.length-1;a>=0;a--)i.push(n.children[a])}return jd(t)}function Ko(e){return Hd(Rp(e))}function Jo(e){return Hd(Gd(wr(e)))}function Qo(e){return e&&typeof e.toUSDZ=="function"?e.toUSDZ():Jo(e)}function Zr(e){let t=Qo(e);return new Blob([t],{type:"model/vnd.usdz+zip"})}function Zo(e,t){if(!e||!e.MeshPhysicalMaterial)return null;if(t?.authorNamespace?.TSL&&t?.authorNamespace?.MeshStandardNodeMaterial)return{TSL:t.authorNamespace.TSL,MeshStandardNodeMaterial:t.authorNamespace.MeshStandardNodeMaterial,MeshPhysicalNodeMaterial:t.authorNamespace.MeshPhysicalNodeMaterial};let r=128,i=16,n=0,a=(N,C,_)=>{typeof e.warnUnsupported=="function"&&e.warnUnsupported(`${C} [${N}]`,_)},s=N=>N==="vec4"?4:N==="vec3"?3:N==="vec2"?2:1,o=N=>N===4?"vec4":N===3?"vec3":N===2?"vec2":"float",l=(N,C=0)=>{let _=Number(N);return Number.isFinite(_)?Math.fround(_):C},c=N=>!!(N&&N.isTSLNode===!0),f=(N,C=1)=>{if(c(N))return N;if(typeof N=="number"||typeof N=="boolean"){let _=l(Number(N),0);return C>1?new p("const",o(C),[],new Array(C).fill(_)):new p("const","float",[],[_])}if(typeof N=="string"){let _=new e.Color(N);return new p("const","vec3",[],[l(_.r,1),l(_.g,1),l(_.b,1)])}if(Array.isArray(N)||N instanceof Float32Array){let _=Math.max(1,Math.min(4,N.length)),P=[];for(let R=0;R<_;R++)P.push(l(N[R],0));return new p("const",o(_),[],P)}if(N&&typeof N=="object"){let _=N;if("isColor"in _||"r"in _&&"g"in _&&"b"in _)return new p("const","vec3",[],[l(_.r,1),l(_.g,1),l(_.b,1)]);if("x"in _&&"y"in _)return"z"in _&&"w"in _?new p("const","vec4",[],[l(_.x),l(_.y),l(_.z),l(_.w,1)]):"z"in _?new p("const","vec3",[],[l(_.x),l(_.y),l(_.z)]):new p("const","vec2",[],[l(_.x),l(_.y)])}return new p("const","float",[],[0])},m=(N,C)=>{let _=f(N),P=f(C);if(_._type===P._type)return[_,P,_._type];if(_._type==="float")return[_,P,P._type];if(P._type==="float")return[_,P,_._type];let R=s(_._type),$=s(P._type);if($>R)P=P.swizzle("xyzw".slice(0,R));else{let F=[P];for(let V=$;V<R;V++)F.push(new p("const","float",[],[0]));P=new p("construct",_._type,F)}return[_,P,_._type]},h=(N,C)=>{let _=f(N);if(_._type===C)return _;let P=s(C),R=s(_._type);if(P===1)return _.swizzle("x");if(R===1)return _._op==="const"&&_._val?new p("const",C,[],new Array(P).fill(_._val[0])):new p("construct",C,[_]);if(R>P)return _.swizzle("xyzw".slice(0,P));let $=[_];for(let F=R;F<P;F++)$.push(new p("const","float",[],[F===3?1:0]));return new p("construct",C,$)};class p{constructor(C,_,P,R,$,F){this.isTSLNode=!0,this._op=C,this._type=_,this._args=P,R!==void 0&&(this._val=R),$!==void 0&&(this._name=$),F!==void 0&&(this._mask=F)}get nodeType(){return this._type}get value(){return this._uVal}set value(C){this._op==="uniform"&&(this._uVal=C)}swizzle(C){let _=String(C||"x").trim().replace(/[rgba]/g,R=>"xyzw"["rgba".indexOf(R)]);if(!/^[xyzw]{1,4}$/.test(_))return a("TL501",`Invalid TSL swizzle '${C}'`,".x"),new p("const","float",[],[0]);let P=s(this._type);if(P===1&&_==="x")return this;for(let R=0;R<_.length;R++)if("xyzw".indexOf(_[R])>=P)return a("TL501",`TSL swizzle '.${C}' out of range`,"0"),new p("const",o(_.length),[],new Array(_.length).fill(0));return new p("swizzle",o(_.length),[this],void 0,void 0,_)}clamp(C=0,_=1){let P=f(C),R=f(_);return(P._type!=="float"||R._type!=="float")&&(P=h(P,this._type),R=h(R,this._type)),new p("clamp",this._type,[this,P,R])}saturate(){return this.clamp(0,1)}oneMinus(){return f(1,s(this._type)).sub(this)}mix(C,_){let[P,R,$]=m(this,C),F=f(_);return F._type!=="float"&&F._type!==$&&(F=h(F,$)),new p("mix",$,[P,R,F])}step(C){let _=f(C);return this._type==="float"?new p("step",_._type,[this,_]):new p("step",this._type,[this,h(_,this._type)])}smoothstep(C,_){let P=f(_),R=this,$=f(C);return(R._type!=="float"||$._type!=="float")&&(R=h(R,P._type),$=h($,P._type)),new p("smoothstep",P._type,[R,$,P])}dot(C){let[_,P]=m(this,C);return new p("dot","float",[_,P])}cross(C){return new p("cross","vec3",[h(this,"vec3"),h(C,"vec3")])}length(){return new p("length","float",[this])}distance(C){let[_,P]=m(this,C);return new p("distance","float",[_,P])}reflect(C){let _=this._type==="float"?h(this,"vec3"):this;return new p("reflect",_._type,[_,h(C,_._type)])}remap(C,_,P,R){let $=this.sub(C).div(f(_).sub(C)).clamp(0,1);return f(P).mix(R,$)}}let g=p.prototype;for(let[N,C]of[["x","x"],["y","y"],["z","z"],["w","w"],["r","x"],["g","y"],["b","z"],["a","w"],["xy","xy"],["xz","xz"],["yz","yz"],["xyz","xyz"],["rgb","xyz"],["xyzw","xyzw"],["rgba","xyzw"]])Object.defineProperty(g,N,{get(){return this.swizzle(C)}});let x=["add","sub","mul","div","mod","pow","atan2","min","max"];for(let N of x)g[N]=function(C){let[_,P,R]=m(this,C);return new p(N,R,[_,P])};let v=["neg","abs","sign","floor","ceil","fract","sqrt","exp","log","sin","cos","normalize"];for(let N of v)g[N]=function(){return new p(N,this._type,[this])};let y=(N,C)=>{let _=new p("builtin",C,[],void 0,N),P=()=>_;return Object.setPrototypeOf(P,g),Object.defineProperty(P,"length",{value:g.length,configurable:!0}),Object.assign(P,_),P},A=(N,C)=>{let _=s(N);if(C.length===0)return new p("const",N,[],new Array(_).fill(0));if(C.length===1)return h(C[0],N);let P=C.map(Y=>f(Y)),R=!0,$=[],F=0;for(let Y of P)if(F+=s(Y._type),Y._op==="const"&&Y._val)for(let J of Y._val)$.push(J);else R=!1;if(R&&$.length>=_)return new p("const",N,[],$.slice(0,_));if(F===_)return new p("construct",N,P);let V=[];for(let Y of P){let J=s(Y._type);for(let re=0;re<J&&V.length<_;re++)V.push(J===1?Y:Y.swizzle("xyzw"[re]))}for(;V.length<_;)V.push(new p("const","float",[],[V.length===3?1:0]));return new p("construct",N,V)},b=y("positionWorld","vec3"),w={float:(N=0)=>h(N,"float"),vec2:(...N)=>A("vec2",N),vec3:(...N)=>A("vec3",N),vec4:(...N)=>A("vec4",N),color:(N=16777215,C,_)=>{if(typeof N=="number"&&typeof C=="number"&&typeof _=="number"){let R=new e.Color(N,C,_);return new p("const","vec3",[],[l(R.r,1),l(R.g,1),l(R.b,1)])}if(c(N))return h(N,"vec3");let P=new e.Color(N);return new p("const","vec3",[],[l(P.r,1),l(P.g,1),l(P.b,1)])},uniform:(N=0,C)=>{let _=f(N),P=typeof C=="string"&&C.trim().length>0?C.trim().replace(/[^A-Za-z0-9_]/g,"_").slice(0,63):`uParam_${n++}`;/^[0-9]/.test(P)&&(P="_"+P.slice(0,62)),(P==="__proto__"||P==="constructor"||P==="prototype")&&(P=`uParam_${n++}`);let R=new p("uniform",_._type,[],void 0,P);return R._uVal=N,R},positionLocal:y("positionLocal","vec3"),positionWorld:b,normalLocal:y("normalLocal","vec3"),normalWorld:y("normalWorld","vec3"),viewDirection:y("viewDirection","vec3"),uv:y("uv","vec2"),vertexColor:y("vertexColor","vec4"),instanceIndex:y("instanceIndex","float"),time:y("time","float"),clamp:(N,C=0,_=1)=>f(N).clamp(C,_),saturate:N=>f(N).saturate(),oneMinus:N=>f(N).oneMinus(),mix:(N,C,_)=>f(N).mix(C,_),step:(N,C)=>f(N).step(C),smoothstep:(N,C,_)=>f(N).smoothstep(C,_),dot:(N,C)=>f(N).dot(C),cross:(N,C)=>f(N).cross(C),length:N=>f(N).length(),distance:(N,C)=>f(N).distance(C),reflect:(N,C)=>f(N).reflect(C),remap:(N,C,_,P,R)=>f(N).remap(C,_,P,R),fresnel:(N=2)=>new p("fresnel","float",[h(N,"float")]),simplexNoise2D:N=>new p("simplexNoise2D","float",[h(N,"vec2")]),simplexNoise3D:N=>new p("simplexNoise3D","float",[h(N,"vec3")]),voronoi2D:(N,C=1)=>new p("voronoi2D","float",[h(N,"vec2"),h(C,"float")]),checker:N=>new p("checker","float",[h(N,"vec2")]),triplanar:(N=1,C=4)=>{let _=f(N),P=_._type==="vec3"?_:b.mul(h(_,"float"));return new p("triplanar","float",[P,h(C,"float")])},hueShift:(N,C)=>new p("hueShift","vec3",[h(N,"vec3"),h(C,"float")]),bumpFromHeight:(N,C=1)=>new p("bumpFromHeight","vec3",[h(N,"float"),h(C,"float")]),Loop:()=>(a("TL504","THREE.TSL.Loop","loop-free TSL constant"),new p("const","float",[],[0])),While:()=>(a("TL504","THREE.TSL.While","loop-free TSL constant"),new p("const","float",[],[0]))};for(let N of x)w[N]=(C,_)=>f(C)[N](_);for(let N of v)w[N]=C=>f(C)[N]();class S extends e.MeshPhysicalMaterial{get opacityNode(){return this._opacityNode}set opacityNode(C){this._opacityNode=C,C!=null&&!(Number(this.alphaTest)>0)&&(this.transparent=!0)}constructor(C={}){super(C),this._opacityNode=null,this.isMeshStandardNodeMaterial=!0,this.colorNode=C.colorNode??null,this.opacityNode=C.opacityNode??null,this.emissiveNode=C.emissiveNode??null,this.roughnessNode=C.roughnessNode??null,this.metalnessNode=C.metalnessNode??null,this.normalScaleNode=C.normalScaleNode??null,this.bumpNode=C.bumpNode??null,this.positionNode=C.positionNode??null}_serializeTslGraph(){let C=[["color",this.colorNode,"vec3"],["opacity",this.opacityNode,"float"],["emissive",this.emissiveNode,"vec3"],["roughness",this.roughnessNode,"float"],["metalness",this.metalnessNode,"float"],["normalScale",this.normalScaleNode,"float"],["bump",this.bumpNode,"vec3"],["position",this.positionNode,"vec3"]],_=[];for(let[ee,k,G]of C)k!=null&&_.push([ee,h(k,G)]);if(_.length===0)return null;let P=[],R={},$=new Map,F=new Set,V="",Y="",J=(ee,k)=>{if(V)return 0;if(!ee||!ee.isTSLNode)return V="TL501",Y="Invalid non-TSL node in material socket",0;if(F.has(ee))return V="TL501",Y="Cyclic TSL node reference",0;if(k&&(ee._op==="builtin"&&ee._name==="viewDirection"||ee._op==="fresnel"||ee._op==="bumpFromHeight"))return V="TL503",Y=`Fragment-only TSL op '${ee._name||ee._op}' used in positionNode`,0;F.add(ee);let G=[];for(let ae of ee._args)if(G.push(J(ae,k)),V)return F.delete(ee),0;if(F.delete(ee),ee._op==="uniform"){let ae=ee._name||"uParam";if(ae in R){if(R[ae].type!==ee._type)return V="TL501",Y=`Conflicting types for TSL uniform '${ae}' (${R[ae].type} vs ${ee._type})`,0}else{if(Object.keys(R).length>=i)return V="TL502",Y=`TSL material exceeds MAX_TSL_UNIFORMS (${i})`,0;let ie=h(ee._uVal??0,ee._type)._val??[0];R[ae]={type:ee._type,value:ee._type==="float"?ie[0]:ie}}}let q=`${ee._op}|${ee._type}|${G.join(",")}|${ee._val?ee._val.join(","):""}|${ee._name??""}|${ee._mask??""}`,H=$.get(q);if(H!==void 0)return H;if(P.length>=r)return V="TL502",Y=`TSL material exceeds MAX_TSL_NODES (${r})`,0;let te=P.length,Z={op:ee._op,type:ee._type};return G.length>0&&(Z.args=G),ee._val&&(Z.value=[...ee._val]),ee._name&&(Z.name=ee._name),ee._mask&&(Z.mask=ee._mask),P.push(Z),$.set(q,te),te},re={};for(let[ee,k]of _)if(re[ee]=J(k,ee==="position"),V)return a(V,Y,"base MeshStandardMaterial factors"),null;let Q={version:1,nodes:P,outputs:re};return Object.keys(R).length>0&&(Q.uniforms=R),Q}clone(){let C=new S;for(let _ of["name","_em","roughness","metalness","emissiveIntensity","opacity","transparent","wireframe","side","doubleSided","map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap","aoMapIntensity","bumpMap","bumpScale","clearcoat","clearcoatRoughness","sheen","sheenRoughness","ior","transmission","thickness","attenuationDistance","dispersion","iridescence","iridescenceIOR","colorNode","opacityNode","emissiveNode","roughnessNode","metalnessNode","normalScaleNode","bumpNode","positionNode"])C[_]=this[_];return C.color.copy(this.color),C.emissive.copy(this.emissive),C.normalScale.copy(this.normalScale),C.sheenColor.copy(this.sheenColor),C.attenuationColor.copy(this.attenuationColor),C}}let E={TSL:w,TSLNode:p,MeshStandardNodeMaterial:S,MeshPhysicalNodeMaterial:S};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,E)),E}var Br="GOOGLE_material_tsl",Xd=128,eo=16,Wn=3600,Cp={positionLocal:"vec3",positionWorld:"vec3",normalLocal:"vec3",normalWorld:"vec3",viewDirection:"vec3",uv:"vec2",vertexColor:"vec4",instanceIndex:"float",time:"float"},Np={color:"vec3",opacity:"float",emissive:"vec3",roughness:"float",metalness:"float",normalScale:"float",bump:"vec3",position:"vec3"},Dp=new Set(["neg","abs","sign","floor","ceil","fract","sqrt","exp","log","sin","cos","normalize"]),Up=new Set(["add","sub","mul","div","mod","pow","atan2","min","max"]),Wd={cross:[["vec3","vec3"],"vec3"],fresnel:[["float"],"float"],simplexNoise2D:[["vec2"],"float"],checker:[["vec2"],"float"],simplexNoise3D:[["vec3"],"float"],voronoi2D:[["vec2","float"],"float"],triplanar:[["vec3","float"],"float"],hueShift:[["vec3","float"],"vec3"],bumpFromHeight:[["float","float"],"vec3"]},Bp=/^[A-Za-z_][A-Za-z0-9_]{0,63}$/,Fp=new Set(["__proto__","constructor","prototype"]);function vs(e,t){let r=Math.abs(t)<1e-6?t<0?-1e-6:1e-6:t;return e-r*Math.floor(e/r)}function Wt(e){return e==="vec4"?4:e==="vec3"?3:e==="vec2"?2:1}function Kc(e){return e===1?"float":e===2?"vec2":e===3?"vec3":e===4?"vec4":null}function Yc(e){return e==="float"||e==="vec2"||e==="vec3"||e==="vec4"}function mt(e,t,r="Use loop-free THREE.TSL expressions on MeshStandardNodeMaterial (<= 128 nodes, <= 16 uniforms)."){return{ok:!1,issue:{code:e,message:t,hint:r}}}function Ur(e,t){for(let r=0;r<t.length;r++)e=Math.imul((e^t.charCodeAt(r))>>>0,16777619)>>>0;return e}var qd=new Float32Array(1),Vp=new Uint32Array(qd.buffer);function Op(e,t){return qd[0]=t,Math.imul((e^Vp[0])>>>0,16777619)>>>0}function ei(e,t){let r=Wt(e);if(r===1){let n=typeof t=="number"?t:Array.isArray(t)&&t.length===1?Number(t[0]):NaN;return Number.isFinite(n)?[Math.fround(n),0,0,0]:null}if(!Array.isArray(t)&&!(t instanceof Float32Array)||t.length<r)return null;let i=[0,0,0,0];for(let n=0;n<r;n++){let a=Number(t[n]);if(!Number.isFinite(a))return null;i[n]=Math.fround(a)}return i}function Sr(e,t="Material"){if(!e||typeof e!="object"||Array.isArray(e))return mt("TL501",`Invalid GOOGLE_material_tsl on '${t}'.`);let r=e;if(r.version!==1)return mt("TL501",`Unsupported TSL version on '${t}'.`);let i=[],n=new Map,a=r.uniforms;if(a!=null){if(typeof a!="object"||Array.isArray(a))return mt("TL501",`Invalid TSL uniforms on '${t}'.`);let y=a,A=Object.keys(y).sort();if(A.length>16)return mt("TL502",`TSL '${t}' exceeds MAX_TSL_UNIFORMS (16).`);for(let b=0;b<A.length;b++){let w=A[b],S=y[w],E=S&&!Array.isArray(S)?S.type:null,N=Yc(E)?ei(E,S.value):null;if(Fp.has(w)||!Bp.test(w)||!Yc(E)||!N)return mt("TL501",`Invalid TSL uniform '${w}' on '${t}'.`);let C={name:w,slot:b,type:E,defaultVec4:N};i.push(C),n.set(w,C)}}let s=r.nodes;if(!Array.isArray(s)||s.length===0)return mt("TL501",`Empty TSL nodes on '${t}'.`);if(s.length>128)return mt("TL502",`TSL '${t}' exceeds MAX_TSL_NODES (128).`);let o=[],l=2166136261;for(let y of i)l=Ur(l,`U:${y.slot}:${y.type};`);for(let y=0;y<s.length;y++){let A=s[y];if(!A||typeof A!="object"||Array.isArray(A))return mt("TL501",`Invalid TSL node ${y} on '${t}'.`);let b=A,w=b.op,S=b.type;if(w==="loop"||w==="while"||w==="for"||w==="call")return mt("TL504",`Unsupported loop/call op '${w}' at node ${y} on '${t}'.`);if(typeof w!="string"||!Yc(S))return mt("TL501",`Malformed TSL node ${y} on '${t}'.`);let E=w,N=b.args,C=[];if(N!==void 0){if(!Array.isArray(N)||N.length>4)return mt("TL501",`Invalid args at node ${y} on '${t}'.`);for(let P of N){if(typeof P!="number"||!Number.isInteger(P)||P<0||P>=y)return mt("TL501",`Cyclic or out-of-order arg at node ${y} on '${t}'.`);C.push(P)}}l=Ur(l,`N${y}:${E}:${S}:`);for(let P of C)l=Ur(l,`${P},`);let _=C.map(P=>o[P].type);if(E==="const"){let P=Wt(S),R=b.value;if(C.length!==0||!Array.isArray(R)||R.length!==P)return mt("TL501",`Invalid const node ${y} on '${t}'.`);let $=[];for(let F=0;F<P;F++){let V=Number(R[F]);if(!Number.isFinite(V))return mt("TL501",`Non-finite const at node ${y}.`);let Y=Math.fround(V);$.push(Y),l=Op(l,Y)}o.push({op:E,type:S,args:[],value:$})}else if(E==="builtin"){let P=b.name;if(C.length!==0||typeof P!="string"||Cp[P]!==S)return mt("TL501",`Invalid builtin at node ${y}.`);l=Ur(l,P),o.push({op:E,type:S,args:[],builtin:P})}else if(E==="uniform"){let P=b.name,R=typeof P=="string"?n.get(P):void 0;if(C.length!==0||!R||R.type!==S)return mt("TL501",`Invalid uniform ref at node ${y}.`);l=Ur(l,`S${R.slot}`),o.push({op:E,type:S,args:[],uniformSlot:R.slot})}else if(E==="swizzle"){let P=b.mask;if(C.length!==1||typeof P!="string"||!/^[xyzw]{1,4}$/.test(P)||Kc(P.length)!==S)return mt("TL501",`Invalid swizzle at node ${y}.`);let R=Wt(_[0]);for(let $=0;$<P.length;$++)if("xyzw".indexOf(P[$])>=R)return mt("TL501",`Swizzle '.${P}' out of bounds at node ${y}.`);l=Ur(l,P),o.push({op:E,type:S,args:C,mask:P})}else if(E==="construct"){let P=Wt(S),R=_.reduce(($,F)=>$+Wt(F),0);if(C.length===0||!(C.length===1&&_[0]==="float")&&R!==P)return mt("TL501",`Invalid construct at node ${y}.`);o.push({op:E,type:S,args:C})}else if(Dp.has(E)){if(C.length!==1||_[0]!==S)return mt("TL501",`Type mismatch on '${E}' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(Up.has(E)){if((C.length===2?_[0]===_[1]?_[0]:_[0]==="float"?_[1]:_[1]==="float"?_[0]:null:null)!==S)return mt("TL501",`Type mismatch on '${E}' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E==="step"){if(C.length!==2||_[0]!==_[1]&&_[0]!=="float"||S!==_[1])return mt("TL501",`Invalid 'step' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E==="clamp"){if(!(C.length===3&&S===_[0]&&(_[1]===_[0]&&_[2]===_[0]||_[1]==="float"&&_[2]==="float")))return mt("TL501",`Invalid 'clamp' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E==="mix"){if(!(C.length===3&&_[0]===_[1]&&S===_[0]&&(_[2]===_[0]||_[2]==="float")))return mt("TL501",`Invalid 'mix' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E==="smoothstep"){if(!(C.length===3&&S===_[2]&&(_[0]===_[2]&&_[1]===_[2]||_[0]==="float"&&_[1]==="float")))return mt("TL501",`Invalid 'smoothstep' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E==="dot"||E==="distance"){if(C.length!==2||_[0]!==_[1]||S!=="float")return mt("TL501",`Invalid '${E}' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E==="length"){if(C.length!==1||S!=="float")return mt("TL501",`Invalid 'length' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E==="reflect"){if(C.length!==2||_[0]!==_[1]||_[0]==="float"||S!==_[0])return mt("TL501",`Invalid 'reflect' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E in Wd){let[P,R]=Wd[E];if(C.length!==P.length||S!==R||P.some(($,F)=>_[F]!==$))return mt("TL501",`Invalid '${E}' at node ${y}.`);o.push({op:E,type:S,args:C})}else return mt("TL501",`Unknown TSL op '${String(E)}' at node ${y}.`)}let c=r.outputs;if(!c||typeof c!="object"||Array.isArray(c))return mt("TL501",`Missing TSL outputs on '${t}'.`);let f=c,m={},h=0;for(let y of Object.keys(f).sort()){let A=Np[y];if(!A)return mt("TL501",`Unknown TSL socket '${y}' on '${t}'.`);let b=f[y];if(b!=null){if(typeof b!="number"||!Number.isInteger(b)||b<0||b>=o.length||o[b].type!==A)return mt("TL501",`Invalid TSL output '${y}' on '${t}'.`);m[y]=b,h++,l=Ur(l,`O:${y}=${b};`)}}if(h===0)return mt("TL501",`No active TSL outputs on '${t}'.`);let p=new Uint8Array(o.length),g=new Uint8Array(o.length);for(let[y,A]of Object.entries(m))y==="position"?g[A]=1:p[A]=1;for(let y=o.length-1;y>=0;y--){if(p[y])for(let A of o[y].args)p[A]=1;if(g[y])for(let A of o[y].args)g[A]=1}let x=!1,v=!1;for(let y=0;y<o.length;y++){let A=o[y];if(g[y]&&(A.op==="builtin"&&A.builtin==="viewDirection"||A.op==="fresnel"||A.op==="bumpFromHeight"))return mt("TL503",`Fragment-only TSL op '${A.builtin||A.op}' used in positionNode on '${t}'.`);(p[y]||g[y])&&(A.op==="builtin"&&A.builtin==="time"&&(x=!0),A.op==="bumpFromHeight"&&(v=!0))}return{ok:!0,graph:{nodes:o,outputs:m,uniformSlots:i,uniformSlotByName:n,hash:(l>>>0).toString(16).padStart(8,"0"),usesTime:x,usesVertexPosition:m.position!==void 0,usesDerivatives:v,fragmentReachable:p,vertexReachable:g}}}function Un(e){if(!Number.isFinite(e)||e===0)return"0.0";let t=Math.fround(e),r=Math.abs(t);if(r>=1e-4&&r<1e6){let n=Number(t.toPrecision(7)).toString();return n.includes(".")?n:`${n}.0`}let i=t.toExponential(6).split("e");return`${i[0].replace(/(\.\d*?[1-9])0+$/,"$1").replace(/\.0+$/,".0")}e${i[1]}`}function ti(e,t,r){let i={div:!1,mod:r,pow:!1,clamp:!1,smooth:!1,atan2:!1,norm:!1,fresnel:!1,snoise2:!1,snoise3:!1,voronoi2:!1,checker:!1,triplanar:!1,hueShift:!1,bump:!1};for(let n=0;n<e.length;n++)if(t[n])switch(e[n].op){case"div":i.div=!0;break;case"mod":i.mod=!0;break;case"pow":i.pow=!0;break;case"clamp":i.clamp=!0;break;case"smoothstep":i.smooth=!0,i.div=!0,i.clamp=!0;break;case"atan2":i.atan2=!0;break;case"normalize":i.norm=!0;break;case"fresnel":i.fresnel=!0,i.pow=!0,i.norm=!0;break;case"simplexNoise2D":i.snoise2=!0;break;case"simplexNoise3D":i.snoise3=!0;break;case"voronoi2D":i.voronoi2=!0;break;case"checker":i.checker=!0,i.mod=!0;break;case"triplanar":i.triplanar=!0,i.snoise2=!0,i.pow=!0,i.norm=!0;break;case"hueShift":i.hueShift=!0;break;case"bumpFromHeight":i.bump=!0,i.norm=!0;break;default:break}return i}var zp=["x","y","z","w"],Jd=[[2,"vec2"],[3,"vec3"],[4,"vec4"]];function to(e,t){return Jd.map(([r,i])=>{let n=zp.slice(0,r).map(a=>t===2?`${e}(a.${a},b.${a})`:`${e}(a.${a},b.${a},c.${a})`).join(",");return t===2?`${i} ${e}(${i} a,${i} b){return ${i}(${n});}`:`${i} ${e}(${i} a,${i} b,${i} c){return ${i}(${n});}`})}function Yd(e,t){let r=[];return e.div&&r.push("float _tslDiv(float a,float b){return a/(abs(b)<1e-6?(b<0.0?-1e-6:1e-6):b);}",...to("_tslDiv",2)),e.mod&&r.push("float _tslMod(float a,float b){float d=abs(b)<1e-6?(b<0.0?-1e-6:1e-6):b;return a-d*floor(a/d);}",...to("_tslMod",2)),e.pow&&r.push("float _tslPow(float a,float b){float e=clamp(b,-64.0,64.0);return abs(e)<1e-8?1.0:(a<=0.0?0.0:pow(max(a,1e-8),e));}",...to("_tslPow",2)),e.clamp&&r.push("float _tslClamp(float a,float b,float c){return clamp(a,min(b,c),max(b,c));}",...to("_tslClamp",3)),e.smooth&&r.push("float _tslSmooth(float a,float b,float c){float t=_tslClamp(_tslDiv(c-a,b-a),0.0,1.0);return t*t*(3.0-2.0*t);}",...to("_tslSmooth",3)),e.atan2&&r.push("float _tslAtan2(float a,float b){return(abs(a)<1e-8&&abs(b)<1e-8)?0.0:atan(a,b);}",...to("_tslAtan2",2)),e.norm&&r.push("float _tslNorm(float v){return abs(v)>1e-6?sign(v):0.0;}",...Jd.map(([,i])=>`${i} _tslNorm(${i} v){float l=length(v);return l>1e-6?v/l:${i}(0.0);}`)),(e.snoise2||e.snoise3||e.voronoi2)&&r.push("float _tslM289(float x){return x-floor(x*(1.0/289.0))*289.0;}","float _tslPerm(float x){return _tslM289((x*34.0+10.0)*x);}"),e.snoise2&&r.push("float _tslSNoise2(vec2 v){const float c0=0.21132487,c1=0.3660254,c2=-0.57735026,c3=0.024390243;float s=(v.x+v.y)*c1,ix=floor(v.x+s),iy=floor(v.y+s),t=(ix+iy)*c0,x0=v.x-ix+t,y0=v.y-iy+t,i1x=x0>y0?1.0:0.0,i1y=1.0-i1x,x1=x0+c0-i1x,y1=y0+c0-i1y,x2=x0+c2,y2=y0+c2;ix=_tslM289(ix);iy=_tslM289(iy);float p0=_tslPerm(_tslPerm(iy)+ix),p1=_tslPerm(_tslPerm(iy+i1y)+ix+i1x),p2=_tslPerm(_tslPerm(iy+1.0)+ix+1.0);vec3 m=max(0.5-vec3(x0*x0+y0*y0,x1*x1+y1*y1,x2*x2+y2*y2),0.0);m=m*m;m=m*m;vec3 gx=2.0*fract(vec3(p0,p1,p2)*c3)-1.0,hy=abs(gx)-0.5,ox=gx-floor(gx+0.5);m*=1.7928429-0.85373473*(ox*ox+hy*hy);return clamp(0.5+65.0*dot(m,ox*vec3(x0,x1,x2)+hy*vec3(y0,y1,y2)),0.0,1.0);}"),e.snoise3&&r.push("float _tslSNoise3(vec3 v){const float c0=0.16666667,c1=0.33333334,ns=0.14285715;float s=(v.x+v.y+v.z)*c1,i0=floor(v.x+s),i1=floor(v.y+s),i2=floor(v.z+s),t=(i0+i1+i2)*c0;vec3 p0=v-vec3(i0,i1,i2)+t,g=step(p0.yzx,p0.xyz),l=1.0-g.zxy,a1=min(g,l),a2=max(g,l),p1=p0-a1+c0,p2=p0-a2+c1,p3=p0-0.5;i0=_tslM289(i0);i1=_tslM289(i1);i2=_tslM289(i2);vec4 hs=vec4(_tslPerm(_tslPerm(_tslPerm(i2)+i1)+i0),_tslPerm(_tslPerm(_tslPerm(i2+a1.z)+i1+a1.y)+i0+a1.x),_tslPerm(_tslPerm(_tslPerm(i2+a2.z)+i1+a2.y)+i0+a2.x),_tslPerm(_tslPerm(_tslPerm(i2+1.0)+i1+1.0)+i0+1.0));float sum=0.0;for(int k=0;k<4;k++){float pk=hs[k],j=pk-49.0*floor(pk*ns*ns),x_=floor(j*ns),y_=floor(j-7.0*x_),gx=x_*(2.0/7.0)+(1.0/7.0)-1.0,gy=y_*(2.0/7.0)+(1.0/7.0)-1.0,gz=1.0-abs(gx)-abs(gy),sz=gz<0.0?1.0:0.0;gx-=sz*(gx>=0.0?1.0:-1.0);gy-=sz*(gy>=0.0?1.0:-1.0);float inv=1.7928429-0.85373473*(gx*gx+gy*gy+gz*gz);vec3 q=k==0?p0:(k==1?p1:(k==2?p2:p3));float m=max(0.6-dot(q,q),0.0);m=m*m;m=m*m;sum+=m*inv*(gx*q.x+gy*q.y+gz*q.z);}return clamp(0.5+21.0*sum,0.0,1.0);}"),e.voronoi2&&r.push("float _tslVoronoi2(vec2 u,float jit){vec2 n=floor(u),fr=u-n;float jt=clamp(jit,0.0,1.0),md=8.0;for(int dy=-1;dy<=1;dy++)for(int dx=-1;dx<=1;dx++){float qx=_tslM289(n.x+float(dx)),qy=_tslM289(n.y+float(dy)),hx=fract(_tslPerm(_tslPerm(qx)+qy)*(1.0/41.0)),hy=fract(_tslPerm(_tslPerm(qy+7.0)+qx+13.0)*(1.0/41.0));md=min(md,length(vec2(float(dx),float(dy))+0.5+(vec2(hx,hy)-0.5)*jt-fr));}return clamp(md,0.0,1.0);}"),e.checker&&r.push("float _tslChecker(vec2 p){return _tslMod(floor(p.x)+floor(p.y),2.0)>=1.0?1.0:0.0;}"),e.fresnel&&r.push("float _tslFresnel(float pw,vec3 nw,vec3 vd){return _tslPow(1.0-clamp(dot(_tslNorm(nw),_tslNorm(vd)),0.0,1.0),max(pw,1e-3));}"),e.triplanar&&r.push("float _tslTriplanar(vec3 p,float sh,vec3 nw){vec3 w=_tslPow(max(abs(_tslNorm(nw)),vec3(1e-4)),vec3(clamp(sh,0.5,16.0)));return(w.x*_tslSNoise2(p.yz)+w.y*_tslSNoise2(p.xz)+w.z*_tslSNoise2(p.xy))/max(w.x+w.y+w.z,1e-6);}"),e.hueShift&&r.push("vec3 _tslHueShift(vec3 rgb,float ang){const vec3 k=vec3(0.57735026);float c=cos(ang),s=sin(ang);return rgb*c+cross(k,rgb)*s+k*dot(k,rgb)*(1.0-c);}"),e.bump&&t&&r.push("vec3 _tslBump(float h,float st,vec3 nw,vec3 wp){vec3 n=_tslNorm(nw),dx=dFdx(wp),dy=dFdy(wp),r1=cross(dy,n),r2=cross(n,dx);float det=dot(dx,r1);return abs(det)<1e-8?n:_tslNorm(abs(det)*n-st*(det<0.0?-1.0:1.0)*(dFdx(h)*r1+dFdy(h)*r2));}"),r.join(`
|
|
352
|
+
`)}var $p={positionLocal:"_tslPL",positionWorld:"_tslPW",normalLocal:"_tslNL",normalWorld:"_tslNW",viewDirection:"_tslVD",uv:"_tslUV",vertexColor:"_tslVC",instanceIndex:"_tslII"};function Kd(e,t){let r=[],i=(a,s)=>a==="float"?s:`${a}(${s})`,n=(a,s,o)=>s===o?a:`${o}(${a})`;for(let a=0;a<e.length;a++){if(!t[a])continue;let s=e[a],o=s.type,l=s.args[0]!==void 0?`_t${s.args[0]}`:"",c=s.args[1]!==void 0?`_t${s.args[1]}`:"",f=s.args[2]!==void 0?`_t${s.args[2]}`:"",m=s.args[0]!==void 0?e[s.args[0]].type:"float",h=s.args[1]!==void 0?e[s.args[1]].type:"float",p=s.args[2]!==void 0?e[s.args[2]].type:"float",g=i(o,"0.0");switch(s.op){case"const":{let x=(s.value??[0]).map(Un);g=o==="float"?x[0]:`${o}(${x.join(",")})`;break}case"builtin":g=s.builtin==="time"?`_tslMod(uTslTime,${Un(3600)})`:$p[s.builtin]??"0.0";break;case"uniform":{let x=`uTslParams[${s.uniformSlot??0}]`,v=Wt(o);g=v===4?x:`${x}.${"xyz".slice(0,v)}`;break}case"swizzle":g=m==="float"?i(o,l):`${l}.${s.mask}`;break;case"construct":g=o==="float"?l:`${o}(${s.args.map(x=>`_t${x}`).join(",")})`;break;case"neg":g=`(-${l})`;break;case"abs":case"sign":case"floor":case"ceil":case"fract":case"sin":case"cos":g=`${s.op}(${l})`;break;case"sqrt":g=`sqrt(max(${l},${i(o,"0.0")}))`;break;case"exp":g=`exp(clamp(${l},${i(o,"-80.0")},${i(o,"80.0")}))`;break;case"log":g=`log(max(${l},${i(o,"1.0e-8")}))`;break;case"normalize":g=`_tslNorm(${l})`;break;case"add":case"sub":case"mul":{let x=s.op==="add"?"+":s.op==="sub"?"-":"*";g=`(${n(l,m,o)}${x}${n(c,h,o)})`;break}case"div":case"mod":case"pow":case"atan2":{g=`${s.op==="div"?"_tslDiv":s.op==="mod"?"_tslMod":s.op==="pow"?"_tslPow":"_tslAtan2"}(${n(l,m,o)},${n(c,h,o)})`;break}case"min":case"max":case"step":g=`${s.op}(${n(l,m,o)},${n(c,h,o)})`;break;case"clamp":g=`_tslClamp(${n(l,m,o)},${n(c,h,o)},${n(f,p,o)})`;break;case"mix":g=`mix(${l},${c},${n(f,p,o)})`;break;case"smoothstep":g=`_tslSmooth(${n(l,m,o)},${n(c,h,o)},${n(f,p,o)})`;break;case"dot":g=m==="float"?`(${l}*${c})`:`dot(${l},${c})`;break;case"length":g=m==="float"?`abs(${l})`:`length(${l})`;break;case"distance":g=m==="float"?`abs(${l}-${c})`:`distance(${l},${c})`;break;case"cross":case"reflect":g=`${s.op}(${l},${c})`;break;case"fresnel":g=`_tslFresnel(${l},_tslNW,_tslVD)`;break;case"simplexNoise2D":g=`_tslSNoise2(${l})`;break;case"simplexNoise3D":g=`_tslSNoise3(${l})`;break;case"voronoi2D":g=`_tslVoronoi2(${l},${c})`;break;case"checker":g=`_tslChecker(${l})`;break;case"triplanar":g=`_tslTriplanar(${l},${c},_tslNW)`;break;case"hueShift":g=`_tslHueShift(${l},${c})`;break;case"bumpFromHeight":g=`_tslBump(${l},${c},_tslNW,_tslPW)`;break;default:break}r.push(`${o} _t${a}=${g};`)}return r.join(`
|
|
353
|
+
`)}function ws(e,t,r){let i=`uniform vec4 uTslParams[16];
|
|
354
|
+
uniform float uTslTime;`,n=e.fragmentReachable.some(l=>l===1),a=t.replace("out vec2 vUV;",`${i}
|
|
355
|
+
out vec2 vUV;
|
|
356
|
+
out vec3 vTslLP,vTslLN;
|
|
357
|
+
flat out float vTslII;`),s=a.includes("morphedPos")?"morphedPos":"aPosition";if(e.usesVertexPosition&&e.outputs.position!==void 0){let l=Yd(ti(e.nodes,e.vertexReachable,e.usesTime),!1),c=Kd(e.nodes,e.vertexReachable),f=`${l}
|
|
358
|
+
vec3 _tslEvalPos(vec3 _tslPL,vec3 _tslNL,vec2 _tslUV,vec4 _tslVC,float _tslII,mat4 _m,mat3 _nm){
|
|
359
|
+
vec3 _tslPW=(_m*vec4(_tslPL,1.0)).xyz,_rn=_nm*_tslNL,_tslNW=length(_rn)>1e-5?normalize(_rn):vec3(0.0,1.0,0.0),_tslVD=vec3(0.0,0.0,1.0);
|
|
360
|
+
${c}
|
|
361
|
+
return _t${e.outputs.position};}`;a=a.replace("void main(){",`${f}
|
|
362
|
+
void main(){`);let m=`vec2 _tslScUV=uUvTransform.zw;if(_tslScUV.x==0.0&&_tslScUV.y==0.0)_tslScUV=vec2(1.0);vec2 _tslVtxUV=aUV*_tslScUV+uUvTransform.xy;
|
|
363
|
+
float _tslInstF=float(gl_InstanceID);vec3 _tslBaseP=${s},_tslNewP=_tslEvalPos(_tslBaseP,aNormal,_tslVtxUV,vInstTint,_tslInstF,uModel,uNormalMatrix),_tslNewN=aNormal;
|
|
364
|
+
if(length(aNormal)>1e-4){vec3 _n0=normalize(aNormal),_tg1=normalize(abs(_n0.y)<0.99?cross(vec3(0.0,1.0,0.0),_n0):cross(vec3(1.0,0.0,0.0),_n0)),_tg2=cross(_n0,_tg1),_cn=cross(_tslEvalPos(_tslBaseP+_tg1*1e-3,aNormal,_tslVtxUV,vInstTint,_tslInstF,uModel,uNormalMatrix)-_tslNewP,_tslEvalPos(_tslBaseP+_tg2*1e-3,aNormal,_tslVtxUV,vInstTint,_tslInstF,uModel,uNormalMatrix)-_tslNewP);if(length(_cn)>1e-10)_tslNewN=normalize(_cn);}
|
|
365
|
+
vTslLP=_tslNewP;vTslLN=_tslNewN;vTslII=_tslInstF;vec3 _rnDisp=uNormalMatrix*_tslNewN;vNormal=length(_rnDisp)>1e-5?normalize(_rnDisp):vec3(0.0);`;a.includes(`vec4 world=uModel*(skinMatrix*vec4(${s},1.0));`)?a=a.replace(`vec4 world=uModel*(skinMatrix*vec4(${s},1.0));`,`${m}
|
|
366
|
+
vec4 world=uModel*(skinMatrix*vec4(_tslNewP,1.0));`).replace(`gl_Position=uMVP*(skinMatrix*vec4(${s},1.0));`,"gl_Position=uMVP*(skinMatrix*vec4(_tslNewP,1.0));"):a=a.replace(`vec4 world=uModel*vec4(${s},1.0);`,`${m}
|
|
367
|
+
vec4 world=uModel*vec4(_tslNewP,1.0);`).replace(`gl_Position=uMVP*vec4(${s},1.0);`,"gl_Position=uMVP*vec4(_tslNewP,1.0);")}else a=a.replace("gl_Position=",`vTslLP=${s};vTslLN=aNormal;vTslII=float(gl_InstanceID);
|
|
368
|
+
gl_Position=`);let o=r.replace("in vec2 vUV;",`${i}
|
|
369
|
+
in vec2 vUV;
|
|
370
|
+
in vec3 vTslLP,vTslLN;
|
|
371
|
+
flat in float vTslII;`);if(n){let l=Yd(ti(e.nodes,e.fragmentReachable,e.usesTime),!0),c=Kd(e.nodes,e.fragmentReachable);l&&(o=o.replace("void main(){",`${l}
|
|
372
|
+
void main(){`)),e.outputs.opacity!==void 0&&(o=o.replace("if(base.a<0.004)discard;","")),o=o.replace("if(length(vNormal)<1e-4&&uHasTexture==1){","if(false&&length(vNormal)<1e-4&&uHasTexture==1){");let f=[];if(e.outputs.color!==void 0&&f.push(`base.rgb=max(_t${e.outputs.color},vec3(0.0))*vInstTint.rgb;`),e.outputs.opacity!==void 0&&f.push(`base.a=clamp(_t${e.outputs.opacity},0.0,1.0)*vInstTint.a;`,"if(base.a<0.004)discard;"),e.outputs.emissive!==void 0&&f.push(`em=max(_t${e.outputs.emissive},vec3(0.0));`),e.outputs.roughness!==void 0&&f.push(`roughness=clamp(_t${e.outputs.roughness},0.04,1.0);`),e.outputs.metalness!==void 0&&f.push(`metallic=clamp(_t${e.outputs.metalness},0.0,1.0);`),e.outputs.normalScale!==void 0&&e.outputs.bump===void 0&&(o=o.replace("if(uHasNormalTexture==1){",`vec3 _tslBaseN=N;
|
|
373
|
+
if(uHasNormalTexture==1){`),f.push(`if(uHasNormalTexture==1){N=perturbNormal(_tslBaseN,V,vUV,uNormalTexture,max(_t${e.outputs.normalScale},0.0));}`)),e.outputs.bump!==void 0){let m=e.outputs.normalScale!==void 0?`max(_t${e.outputs.normalScale},0.0)`:"1.0";f.push(`{vec3 _bn=_t${e.outputs.bump};float _bl=length(_bn);if(_bl>1e-6){vec3 _bm=N+(_bn/_bl-N)*(${m});float _ml=length(_bm);if(_ml>1e-6)N=_bm/_ml;}}`)}o=o.replace("metallic=clamp(metallic,0.0,1.0);",`metallic=clamp(metallic,0.0,1.0);
|
|
374
|
+
{vec3 _tslPL=vTslLP,_tslPW=vWorldPos,_tslNL=length(vTslLN)>1e-5?normalize(vTslLN):vec3(0.0,1.0,0.0),_tslNW=N,_tslVD=V;vec2 _tslUV=vUV;vec4 _tslVC=vInstTint;float _tslII=vTslII;
|
|
375
|
+
${c}
|
|
376
|
+
${f.join(`
|
|
377
|
+
`)}}`)}return{vs:a,fs:o}}var Gp={float:"float",vec2:"float2",vec3:"float3",vec4:"float4"},jp={float:"float",vec2:"vector2",vec3:"vector3",vec4:"vector4"};function xn(e){return Gp[e]||"float"}function Mr(e){return jp[e]||"float"}function ni(e,t){if(t===1)return Un(e[0]??0);let r=[];for(let i=0;i<t;i++)r.push(Un(e[i]??0));return`(${r.join(", ")})`}function Ss(e,t,r=""){let i;if(e&&typeof e=="object"&&"fragmentReachable"in e)i=e;else{let w=Sr(e,t);if(!w.ok)return null;i=w.graph}if(!i.fragmentReachable.some(w=>w===1))return null;let n=`/Root/Materials/${(t||"Material").replace(/[^A-Za-z0-9_]/g,"_").replace(/^([0-9])/,"_$1")||"Material"}/TSLGraph`,a=[],s=[],o=0;for(let w of i.uniformSlots){let S=xn(w.type),E=Wt(w.type);s.push(`${S} inputs:u_${w.slot} = ${ni(w.defaultVec4,E)}`)}let l=(w,S,E,N)=>(a.push(`def Shader "${w}"
|
|
365
378
|
{
|
|
366
|
-
${
|
|
367
|
-
`
|
|
379
|
+
uniform token info:id = "${S}"
|
|
380
|
+
${N.join(`
|
|
381
|
+
`)}${N.length>0?`
|
|
382
|
+
`:""}${E} outputs:out
|
|
383
|
+
}`),`${n}/${w}.outputs:out`),c=(w,S)=>{let E=Wt(w),N=`C_${o++}`;return l(N,`ND_constant_${Mr(w)}`,xn(w),[`${xn(w)} inputs:value = ${ni(S,E)}`])},f=(w,S)=>{if(S==="float")return w;let E=Wt(S),N=`B_${o++}`,C=[];for(let _=1;_<=E;_++)C.push(`float inputs:in${_}.connect = <${w}>`);return l(N,`ND_combine${E}_${Mr(S)}`,xn(S),C)},m=(w,S,E)=>S===E?w:f(w,E),h=(w,S,E)=>{if(S==="float")return w;let N=`E_${o++}`;return l(N,`ND_extract_${Mr(S)}`,"float",[`${xn(S)} inputs:in.connect = <${w}>`,`int inputs:index = ${E}`])},p=new Map,g=w=>{let S=p.get(w);if(S)return S;let E="";switch(w){case"positionLocal":E=l("BI_posLocal","ND_position_vector3","float3",['string inputs:space = "object"']);break;case"positionWorld":E=l("BI_posWorld","ND_position_vector3","float3",['string inputs:space = "world"']);break;case"normalLocal":E=l("BI_normLocal","ND_normal_vector3","float3",['string inputs:space = "object"']);break;case"normalWorld":E=l("BI_normWorld","ND_normal_vector3","float3",['string inputs:space = "world"']);break;case"viewDirection":{let N=l("BI_rawView","ND_viewdirection_vector3","float3",['string inputs:space = "world"']);E=l("BI_viewDir","ND_multiply_vector3FA","float3",[`float3 inputs:in1.connect = <${N}>`,"float inputs:in2 = -1.0"]);break}case"uv":E=l("BI_uv","ND_texcoord_vector2","float2",["int inputs:index = 0"]);break;case"vertexColor":{let N=l("BI_vcCol","ND_geomcolor_color4","color4f",["int inputs:index = 0"]);E=l("BI_vcVec","ND_convert_color4_vector4","float4",[`color4f inputs:in.connect = <${N}>`]);break}case"instanceIndex":E=c("float",[0]);break;case"time":{let N=l("BI_rawTime","ND_time_float","float",[]);E=l("BI_time","ND_modulo_float","float",[`float inputs:in1.connect = <${N}>`,`float inputs:in2 = ${Un(3600)}`]);break}default:E=c("float",[0]);break}return p.set(w,E),E},x=new Array(i.nodes.length).fill("");for(let w=0;w<i.nodes.length;w++){if(!i.fragmentReachable[w])continue;let S=i.nodes[w],E=S.type,N=xn(E),C=Mr(E),_=Wt(E),P=S.args[0]!==void 0?x[S.args[0]]:"",R=S.args[1]!==void 0?x[S.args[1]]:"",$=S.args[2]!==void 0?x[S.args[2]]:"",F=S.args[0]!==void 0?i.nodes[S.args[0]].type:"float",V=S.args[1]!==void 0?i.nodes[S.args[1]].type:"float",Y=S.args[2]!==void 0?i.nodes[S.args[2]].type:"float",J=`N${w}`;switch(S.op){case"const":x[w]=l(J,`ND_constant_${C}`,N,[`${N} inputs:value = ${ni(S.value??[0],_)}`]);break;case"builtin":x[w]=g(S.builtin??"time");break;case"uniform":x[w]=`${n}.inputs:u_${S.uniformSlot??0}`;break;case"swizzle":{let re=S.mask??"x";if(F==="float")x[w]=f(P,E);else if(re.length===1)x[w]=h(P,F,"xyzw".indexOf(re[0]));else{let Q=Array.from(re).map(ee=>h(P,F,"xyzw".indexOf(ee)));x[w]=l(J,`ND_combine${re.length}_${C}`,N,Q.map((ee,k)=>`float inputs:in${k+1}.connect = <${ee}>`))}break}case"construct":{if(E==="float")x[w]=P;else if(S.args.length===1&&F==="float")x[w]=f(P,E);else{let re=[];for(let Q of S.args){let ee=i.nodes[Q].type,k=x[Q],G=Wt(ee);if(G===1)re.push(k);else for(let q=0;q<G;q++)re.push(h(k,ee,q))}x[w]=l(J,`ND_combine${_}_${C}`,N,re.slice(0,_).map((Q,ee)=>`float inputs:in${ee+1}.connect = <${Q}>`))}break}case"neg":{x[w]=l(J,`ND_multiply_${C}`,N,[`${N} inputs:in1.connect = <${P}>`,`${N} inputs:in2 = ${ni([-1,-1,-1,-1],_)}`]);break}case"abs":case"sign":case"floor":case"ceil":case"sqrt":case"exp":case"sin":case"cos":case"normalize":{let re=S.op==="abs"?"absval":S.op;S.op==="normalize"&&E==="float"?x[w]=l(J,"ND_sign_float","float",[`float inputs:in.connect = <${P}>`]):x[w]=l(J,`ND_${re}_${C}`,N,[`${N} inputs:in.connect = <${P}>`]);break}case"log":x[w]=l(J,`ND_ln_${C}`,N,[`${N} inputs:in.connect = <${P}>`]);break;case"fract":{x[w]=l(J,`ND_modulo_${C}`,N,[`${N} inputs:in1.connect = <${P}>`,`${N} inputs:in2 = ${ni([1,1,1,1],_)}`]);break}case"add":case"sub":case"mul":case"div":case"mod":case"pow":case"atan2":case"min":case"max":{let re={add:"add",sub:"subtract",mul:"multiply",div:"divide",mod:"modulo",pow:"power",atan2:"atan2",min:"min",max:"max"},Q=m(P,F,E),ee=m(R,V,E);x[w]=l(J,`ND_${re[S.op]}_${C}`,N,[`${N} inputs:in1.connect = <${Q}>`,`${N} inputs:in2.connect = <${ee}>`]);break}case"step":{let re=m(P,F,E);if(E==="float")x[w]=l(J,"ND_ifgreater_float","float",[`float inputs:value1.connect = <${R}>`,`float inputs:value2.connect = <${re}>`,"float inputs:in1 = 1.0","float inputs:in2 = 0.0"]);else{let Q=[];for(let ee=0;ee<_;ee++){let k=h(re,E,ee),G=h(R,E,ee);Q.push(l(`S_${o++}`,"ND_ifgreater_float","float",[`float inputs:value1.connect = <${G}>`,`float inputs:value2.connect = <${k}>`,"float inputs:in1 = 1.0","float inputs:in2 = 0.0"]))}x[w]=l(J,`ND_combine${_}_${C}`,N,Q.map((ee,k)=>`float inputs:in${k+1}.connect = <${ee}>`))}break}case"clamp":{let re=m(R,V,E),Q=m($,Y,E);x[w]=l(J,`ND_clamp_${C}`,N,[`${N} inputs:in.connect = <${P}>`,`${N} inputs:low.connect = <${re}>`,`${N} inputs:high.connect = <${Q}>`]);break}case"mix":{let re=m($,Y,E);x[w]=l(J,`ND_mix_${C}`,N,[`${N} inputs:bg.connect = <${P}>`,`${N} inputs:fg.connect = <${R}>`,`${N} inputs:mix.connect = <${re}>`]);break}case"smoothstep":{let re=m(P,F,E),Q=m(R,V,E);x[w]=l(J,`ND_smoothstep_${C}`,N,[`${N} inputs:in.connect = <${$}>`,`${N} inputs:low.connect = <${re}>`,`${N} inputs:high.connect = <${Q}>`]);break}case"dot":F==="float"?x[w]=l(J,"ND_multiply_float","float",[`float inputs:in1.connect = <${P}>`,`float inputs:in2.connect = <${R}>`]):x[w]=l(J,`ND_dotproduct_${Mr(F)}`,"float",[`${xn(F)} inputs:in1.connect = <${P}>`,`${xn(F)} inputs:in2.connect = <${R}>`]);break;case"length":F==="float"?x[w]=l(J,"ND_absval_float","float",[`float inputs:in.connect = <${P}>`]):x[w]=l(J,`ND_magnitude_${Mr(F)}`,"float",[`${xn(F)} inputs:in.connect = <${P}>`]);break;case"distance":{let re=l(`D_${o++}`,`ND_subtract_${Mr(F)}`,xn(F),[`${xn(F)} inputs:in1.connect = <${P}>`,`${xn(F)} inputs:in2.connect = <${R}>`]);x[w]=F==="float"?l(J,"ND_absval_float","float",[`float inputs:in.connect = <${re}>`]):l(J,`ND_magnitude_${Mr(F)}`,"float",[`${xn(F)} inputs:in.connect = <${re}>`]);break}case"cross":x[w]=l(J,"ND_crossproduct_vector3","float3",[`float3 inputs:in1.connect = <${P}>`,`float3 inputs:in2.connect = <${R}>`]);break;case"reflect":if(E==="vec3")x[w]=l(J,"ND_reflect_vector3","float3",[`float3 inputs:in.connect = <${P}>`,`float3 inputs:normal.connect = <${R}>`]);else{let re=E==="float"?l(`RF_${o++}`,"ND_multiply_float","float",[`float inputs:in1.connect = <${R}>`,`float inputs:in2.connect = <${P}>`]):l(`RF_${o++}`,`ND_dotproduct_${C}`,"float",[`${N} inputs:in1.connect = <${R}>`,`${N} inputs:in2.connect = <${P}>`]),Q=l(`RF_${o++}`,"ND_multiply_float","float",[`float inputs:in1.connect = <${re}>`,"float inputs:in2 = 2.0"]),ee=l(`RF_${o++}`,`ND_multiply_${C}`,N,[`${N} inputs:in1.connect = <${R}>`,`${N} inputs:in2.connect = <${m(Q,"float",E)}>`]);x[w]=l(J,`ND_subtract_${C}`,N,[`${N} inputs:in1.connect = <${P}>`,`${N} inputs:in2.connect = <${ee}>`])}break;case"fresnel":{let re=g("normalWorld"),Q=g("viewDirection"),ee=l(`FR_${o++}`,"ND_dotproduct_vector3","float",[`float3 inputs:in1.connect = <${re}>`,`float3 inputs:in2.connect = <${Q}>`]),k=l(`FR_${o++}`,"ND_clamp_float","float",[`float inputs:in.connect = <${ee}>`,"float inputs:low = 0.0","float inputs:high = 1.0"]),G=l(`FR_${o++}`,"ND_subtract_float","float",["float inputs:in1 = 1.0",`float inputs:in2.connect = <${k}>`]);x[w]=l(J,"ND_power_float","float",[`float inputs:in1.connect = <${G}>`,`float inputs:in2.connect = <${P}>`]);break}case"simplexNoise2D":x[w]=l(J,"ND_noise2d_float","float",[`float2 inputs:texcoord.connect = <${P}>`,"float inputs:amplitude = 0.5","float inputs:pivot = 0.5"]);break;case"simplexNoise3D":x[w]=l(J,"ND_noise3d_float","float",[`float3 inputs:position.connect = <${P}>`,"float inputs:amplitude = 0.5","float inputs:pivot = 0.5"]);break;case"voronoi2D":x[w]=l(J,"ND_cellnoise2d_float","float",[`float2 inputs:texcoord.connect = <${P}>`]);break;case"checker":{let re=l(`CK_${o++}`,"ND_floor_vector2","float2",[`float2 inputs:in.connect = <${P}>`]),Q=h(re,"vec2",0),ee=h(re,"vec2",1),k=l(`CK_${o++}`,"ND_add_float","float",[`float inputs:in1.connect = <${Q}>`,`float inputs:in2.connect = <${ee}>`]),G=l(`CK_${o++}`,"ND_modulo_float","float",[`float inputs:in1.connect = <${k}>`,"float inputs:in2 = 2.0"]);x[w]=l(J,"ND_ifgreater_float","float",[`float inputs:value1.connect = <${G}>`,"float inputs:value2 = 0.999","float inputs:in1 = 1.0","float inputs:in2 = 0.0"]);break}case"triplanar":x[w]=l(J,"ND_noise3d_float","float",[`float3 inputs:position.connect = <${P}>`,"float inputs:amplitude = 0.5","float inputs:pivot = 0.5"]);break;case"hueShift":{let re=l(`HS_${o++}`,"ND_convert_vector3_color3","color3f",[`float3 inputs:in.connect = <${P}>`]),Q=l(`HS_${o++}`,"ND_multiply_float","float",[`float inputs:in1.connect = <${R}>`,"float inputs:in2 = 0.15915494"]),ee=l(`HS_${o++}`,"ND_combine3_vector3","float3",[`float inputs:in1.connect = <${Q}>`,"float inputs:in2 = 1.0","float inputs:in3 = 1.0"]),k=l(`HS_${o++}`,"ND_hsvadjust_color3","color3f",[`color3f inputs:in.connect = <${re}>`,`float3 inputs:amount.connect = <${ee}>`]);x[w]=l(J,"ND_convert_color3_vector3","float3",[`color3f inputs:in.connect = <${k}>`]);break}case"bumpFromHeight":{x[w]=l(J,"ND_heighttonormal_vector3","float3",[`float inputs:in.connect = <${P}>`,`float inputs:scale.connect = <${R}>`]);break}default:x[w]=c(E,[0,0,0,0]);break}}let v=[],y={};if(i.outputs.color!==void 0){let w=l("OUT_color","ND_convert_vector3_color3","color3f",[`float3 inputs:in.connect = <${x[i.outputs.color]}>`]);v.push(`color3f outputs:diffuseColor.connect = <${w}>`),y.diffuseColor=`${n}.outputs:diffuseColor`}if(i.outputs.emissive!==void 0){let w=l("OUT_emissive","ND_convert_vector3_color3","color3f",[`float3 inputs:in.connect = <${x[i.outputs.emissive]}>`]);v.push(`color3f outputs:emissiveColor.connect = <${w}>`),y.emissiveColor=`${n}.outputs:emissiveColor`}if(i.outputs.opacity!==void 0&&(v.push(`float outputs:opacity.connect = <${x[i.outputs.opacity]}>`),y.opacity=`${n}.outputs:opacity`),i.outputs.roughness!==void 0&&(v.push(`float outputs:roughness.connect = <${x[i.outputs.roughness]}>`),y.roughness=`${n}.outputs:roughness`),i.outputs.metalness!==void 0&&(v.push(`float outputs:metallic.connect = <${x[i.outputs.metalness]}>`),y.metallic=`${n}.outputs:metallic`),i.outputs.bump!==void 0&&(v.push(`normal3f outputs:normal.connect = <${x[i.outputs.bump]}>`),y.normal=`${n}.outputs:normal`),v.length===0)return null;let A=[["diffuseColor","color3f"],["metallic","float"],["roughness","float"],["opacity","float"],["emissiveColor","color3f"],["normal","normal3f"]],b=r;for(let[w,S]of A){let E=y[w];if(!E)continue;let N=`${S} inputs:${w}.connect = <${E}>`,C=new RegExp(`^${S}\\s+inputs:${w}[^
|
|
384
|
+
]*$`,"m");C.test(b)?b=b.replace(C,N):b+=`${b.endsWith(`
|
|
385
|
+
`)||!b?"":`
|
|
386
|
+
`}${N}
|
|
387
|
+
`}return{nodeGraphUsda:`def NodeGraph "TSLGraph"
|
|
388
|
+
{
|
|
389
|
+
${[...s,...v,...a].join(`
|
|
390
|
+
`)}
|
|
368
391
|
}
|
|
369
|
-
`,o}var mr=null;function An(e){if(!mr){mr=new Uint32Array(256);for(let r=0;r<256;r++){let i=r;for(let n=0;n<8;n++)i=i&1?3988292384^i>>>1:i>>>1;mr[r]=i}}let t=4294967295;for(let r=0;r<e.length;r++)t=mr[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function ys(e){let t=[],r=0,i=[];for(let h of e){let m=Ui(h.filename),c=An(h.data),d=h.data.length,f=30+m.length,g=(r+f)%64,x=g!==0?64-g:0;x>0&&x<4&&(x+=64);let b=new Uint8Array(f+x),v=new DataView(b.buffer);v.setUint32(0,67324752,!0),v.setUint16(4,20,!0),v.setUint32(14,c,!0),v.setUint32(18,d,!0),v.setUint32(22,d,!0),v.setUint16(26,m.length,!0),v.setUint16(28,x,!0),b.set(m,30),x>=4&&(v.setUint16(f,6534,!0),v.setUint16(f+2,x-4,!0)),t.push({offset:r,size:d,crc:c,filenameBytes:m,entry:h}),i.push(b,h.data),r+=b.length+h.data.length}let n=r;for(let h of t){let m=new Uint8Array(46+h.filenameBytes.length),c=new DataView(m.buffer);c.setUint32(0,33639248,!0),c.setUint16(4,20,!0),c.setUint16(6,20,!0),c.setUint32(16,h.crc,!0),c.setUint32(20,h.size,!0),c.setUint32(24,h.size,!0),c.setUint16(28,h.filenameBytes.length,!0),c.setUint32(42,h.offset,!0),m.set(h.filenameBytes,46),i.push(m),r+=m.length}let s=r-n,l=new Uint8Array(22),o=new DataView(l.buffer);o.setUint32(0,101010256,!0),o.setUint16(8,t.length,!0),o.setUint16(10,t.length,!0),o.setUint32(12,s,!0),o.setUint32(16,n,!0),i.push(l),r+=22;let a=new Uint8Array(r),u=0;for(let h of i)a.set(h,u),u+=h.length;return a}function gs(e){let t=[{filename:"model.usda",data:Ui(dc(e))}],r=new Set(["model.usda"]),i=[...e];for(;i.length>0;){let n=i.pop();for(let s of n.textures||[])s?.file&&s.data?.byteLength&&!r.has(s.file)&&(r.add(s.file),t.push({filename:s.file,data:s.data}));if(n.children)for(let s=n.children.length-1;s>=0;s--)i.push(n.children[s])}return ys(t)}function wn(e){return gs(lc(e))}function Sn(e){return gs(bs(Lt(e)))}function En(e){return e&&typeof e.toUSDZ=="function"?e.toUSDZ():Sn(e)}function on(e){let t=En(e);return new Blob([t],{type:"model/vnd.usdz+zip"})}function Ct(e,t,r,i){let n=typeof e=="number"&&Number.isFinite(e)?e:i;return Math.max(t,Math.min(r,n))}function hc(e){return Array.isArray(e)&&e.length>=3&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])}function Fi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function pc(e,t=256){return typeof e=="string"&&e.length>0?e.slice(0,t):void 0}function xs(e){let t=Fi(e);if(!t)return null;let r=t.target;return{target:hc(r)?[r[0],r[1],r[2]]:typeof r=="string"&&r.length>0&&r.length<=256?r:[0,0,0],radius:Ct(t.radius,.01,50,.5),speed:Ct(t.speed,-20,20,.5),height:Ct(t.height,-10,10,0),phase:Ct(t.phase,-1e6,1e6,0),faceCenter:t.faceCenter===!0}}var bc=["hum","reactor","wind","beacon","geiger","chimeLoop","machinery","water"],yc=["confirm","error","alarm","warning","pickup","jump","beam","impact","burst","powerup","step","pass","fail"],Wu=new Set(bc),ju=new Set(yc);function Vi(e,t){let r=pc(e,16)?.trim();if(!r)return t;let i=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(r);return i?`#${i[1].toLowerCase()}`:t}function Bi(e){if(!e||typeof e=="number"&&!(e>0&&Number.isFinite(e)))return null;let t=e===!0?{}:typeof e=="number"?{strength:e}:Fi(e);if(!t||t.enabled===!1)return null;let r=Ct(t.strength??t.intensity,0,5,.35);return r>0?{enabled:!0,strength:r,threshold:Ct(t.threshold,0,4,.8),radius:Ct(t.radius,0,2,.5)}:null}function dr(e){if(!e)return null;let t=e===!0?{}:typeof e=="string"?{color:e}:Fi(e);if(!t||t.enabled===!1)return null;let r=t.thickness??t.width;return{enabled:!0,color:Vi(t.color,"#38bdf8"),thickness:Ct(typeof r=="number"&&r>0&&r<.25?Math.max(1.5,r*140):r,.5,20,3),pulse:t.pulse===!0}}var rt=class No{constructor(t=0,r=0){this.x=Number(t),this.y=Number(r)}set(t,r){return this.x=Number(t),this.y=Number(r),this}clone(){return new No(this.x,this.y)}copy(t){return this.set(t.x,t.y)}add(t){return this.x+=t.x,this.y+=t.y,this}sub(t){return this.x-=t.x,this.y-=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divideScalar(t){return this.multiplyScalar(t?1/t:0)}setScalar(t){return this.set(t,t)}},ge=class Do{constructor(t=0,r=0,i=0){this.x=Number(t),this.y=Number(r),this.z=Number(i)}set(t,r,i){return this.x=Number(t),this.y=Number(r),this.z=Number(i),this}clone(){return new Do(this.x,this.y,this.z)}copy(t){return this.set(t.x,t.y,t.z)}add(t){return this.addVectors(this,t)}addVectors(t,r){return this.set(t.x+r.x,t.y+r.y,t.z+r.z)}sub(t){return this.subVectors(this,t)}subVectors(t,r){return this.set(t.x-r.x,t.y-r.y,t.z-r.z)}multiplyScalar(t){return this.set(this.x*t,this.y*t,this.z*t)}divideScalar(t){return this.multiplyScalar(t?1/t:0)}setScalar(t){return this.set(t,t,t)}addScaledVector(t,r){return this.set(this.x+t.x*r,this.y+t.y*r,this.z+t.z*r)}length(){return Math.hypot(this.x,this.y,this.z)}normalize(){let t=this.length();return t>1e-5?this.multiplyScalar(1/t):this}cross(t){return this.crossVectors(this,t)}crossVectors(t,r){let i=t.x,n=t.y,s=t.z,l=r.x,o=r.y,a=r.z;return this.set(n*a-s*o,s*l-i*a,i*o-n*l)}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}distanceTo(t){return Math.hypot(this.x-t.x,this.y-t.y,this.z-t.z)}lerp(t,r){return this.lerpVectors(this,t,r)}lerpVectors(t,r,i){return this.x=t.x+(r.x-t.x)*i,this.y=t.y+(r.y-t.y)*i,this.z=t.z+(r.z-t.z)*i,this}applyMatrix4(t){let r=this.x,i=this.y,n=this.z,s=t.elements,l=1/(s[3]*r+s[7]*i+s[11]*n+s[15]);return this.x=(s[0]*r+s[4]*i+s[8]*n+s[12])*l,this.y=(s[1]*r+s[5]*i+s[9]*n+s[13])*l,this.z=(s[2]*r+s[6]*i+s[10]*n+s[14])*l,this}},gr=class{constructor(e=0,t=0,r=0,i=1){this.x=Number(e),this.y=Number(t),this.z=Number(r),this.w=Number(i)}set(e,t,r,i){return this.x=Number(e),this.y=Number(t),this.z=Number(r),this.w=Number(i),this}},In=class ko{constructor(t=0,r=0,i=0,n="XYZ"){this._onChangeCallback=null,this._x=Number(t),this._y=Number(r),this._z=Number(i),this.order=n}get x(){return this._x}set x(t){this._x=Number(t),this._onChangeCallback?.()}get y(){return this._y}set y(t){this._y=Number(t),this._onChangeCallback?.()}get z(){return this._z}set z(t){this._z=Number(t),this._onChangeCallback?.()}set(t,r,i,n=this.order){return this._x=Number(t),this._y=Number(r),this._z=Number(i),this.order=n,this._onChangeCallback?.(),this}copy(t){return this.set(t.x,t.y,t.z,t.order)}clone(){return new ko(this._x,this._y,this._z,this.order)}_onChange(t){return this._onChangeCallback=t,this}},sn=class Oo{constructor(t=0,r=0,i=0,n=1){this._onChangeCallback=null,this._x=Number(t),this._y=Number(r),this._z=Number(i),this._w=Number(n)}get x(){return this._x}set x(t){this._x=Number(t),this._onChangeCallback?.()}get y(){return this._y}set y(t){this._y=Number(t),this._onChangeCallback?.()}get z(){return this._z}set z(t){this._z=Number(t),this._onChangeCallback?.()}get w(){return this._w}set w(t){this._w=Number(t),this._onChangeCallback?.()}set(t,r,i,n){return this._x=Number(t),this._y=Number(r),this._z=Number(i),this._w=Number(n),this._onChangeCallback?.(),this}copy(t){return this.set(t.x,t.y,t.z,t.w)}clone(){return new Oo(this._x,this._y,this._z,this._w)}identity(){return this.set(0,0,0,1)}setFromEuler(t,r=!0){let i=t.x,n=t.y,s=t.z,l=Math.cos(i/2),o=Math.cos(n/2),a=Math.cos(s/2),u=Math.sin(i/2),h=Math.sin(n/2),m=Math.sin(s/2);return this._x=u*o*a+l*h*m,this._y=l*h*a-u*o*m,this._z=l*o*m+u*h*a,this._w=l*o*a-u*h*m,r&&this._onChangeCallback?.(),this}setFromAxisAngle(t,r){let i=r/2,n=Math.sin(i);return this.set(t.x*n,t.y*n,t.z*n,Math.cos(i))}normalize(){let t=Math.hypot(this._x,this._y,this._z,this._w);return t===0?this.set(0,0,0,1):this.set(this._x/t,this._y/t,this._z/t,this._w/t)}setFromUnitVectors(t,r){let i=t.dot(r)+1;return i<1e-6?(Math.abs(t.x)>Math.abs(t.z)?this.set(-t.y,t.x,0,0):this.set(0,-t.z,t.y,0)).normalize():this.set(t.y*r.z-t.z*r.y,t.z*r.x-t.x*r.z,t.x*r.y-t.y*r.x,i).normalize()}multiply(t){return this.multiplyQuaternions(this,t)}multiplyQuaternions(t,r){let i=t.x,n=t.y,s=t.z,l=t.w,o=r.x,a=r.y,u=r.z,h=r.w;return this._x=i*h+l*o+n*u-s*a,this._y=n*h+l*a+s*o-i*u,this._z=s*h+l*u+i*a-n*o,this._w=l*h-i*o-n*a-s*u,this._onChangeCallback?.(),this}_onChange(t){return this._onChangeCallback=t,this}},Pt=class el{constructor(){this.elements=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}identity(){let t=this.elements;return t.fill(0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,this}copy(t){return this.elements.set(t.elements),this}clone(){let t=new el;return t.copy(this),t}compose(t,r,i){return Tt(this.elements,[r.x,r.y,r.z,r.w],[t.x,t.y,t.z],[i.x,i.y,i.z]),this}multiply(t){return this.multiplyMatrices(this,t)}multiplyMatrices(t,r){return Ie(this.elements,t.elements,r.elements),this}lookAt(t,r,i){return Jt(this.elements,[t.x,t.y,t.z],[r.x,r.y,r.z],[i.x,i.y,i.z]),this}makeRotationFromQuaternion(t){let r=new ge(0,0,0),i=new ge(1,1,1);return this.compose(r,t,i)}makeTranslation(t,r,i){return this.identity(),this.elements[12]=Number(t),this.elements[13]=Number(r),this.elements[14]=Number(i),this}makeScale(t,r,i){return this.identity(),this.elements[0]=Number(t),this.elements[5]=Number(r),this.elements[10]=Number(i),this}},xr=class{constructor(){this.elements=new Float32Array([1,0,0,0,1,0,0,0,1])}identity(){let e=this.elements;return e.fill(0),e[0]=1,e[4]=1,e[8]=1,this}getNormalMatrix(e){return Xe(this.elements,e.elements),this}},Qe=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,hr=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,vs={black:0,white:16777215,red:16711680,green:32768,lime:65280,blue:255,yellow:16776960,cyan:65535,aqua:65535,magenta:16711935,fuchsia:16711935,gray:8421504,grey:8421504,silver:12632256,orange:16753920,purple:8388736,pink:16761035,gold:16766720},ut=class tl{constructor(t,r,i){this.r=1,this.g=1,this.b=1,t!==void 0&&(r!==void 0&&i!==void 0?this.setRGB(t,r,i):this.set(t))}set(t){return typeof t=="number"?this.setHex(t):typeof t=="string"?this.setStyle(t):(t&&typeof t=="object"&&"r"in t&&(this.r=Number(t.r),this.g=Number(t.g),this.b=Number(t.b)),this)}setStyle(t){let r=t.trim().toLowerCase();if(r[0]==="#"){let i=r.slice(1);i.length===3||i.length===4?i=i[0]+i[0]+i[1]+i[1]+i[2]+i[2]:i.length===8&&(i=i.slice(0,6));let n=parseInt(i,16);i.length===6&&!Number.isNaN(n)&&this.setHex(n)}else if(r in vs)this.setHex(vs[r]);else if(r.startsWith("hsl")){let i=/^hsla?\(([^)]+)\)$/.exec(r)?.[1].trim().split(/[\s,/]+/);i&&i.length>=3&&this.setHSL((parseFloat(i[0])||0)/360,(parseFloat(i[1])||0)/100,(parseFloat(i[2])||0)/100)}else{let i=/^rgba?\(([^)]+)\)$/.exec(r)?.[1].trim().split(/[\s,/]+/);if(i&&i.length>=3){let n=s=>Qe(Math.max(0,Math.min(1,(parseFloat(s)||0)/(s.endsWith("%")?100:255))));this.setRGB(n(i[0]),n(i[1]),n(i[2]))}}return this}setHSL(t,r,i){if(t=((Number(t)||0)%1+1)%1,r=Math.max(0,Math.min(1,Number(r)||0)),i=Math.max(0,Math.min(1,Number(i)||0)),r===0){let o=Qe(i);return this.setRGB(o,o,o)}let n=i<=.5?i*(1+r):i+r-i*r,s=2*i-n,l=o=>(o<0&&(o+=1),o>1&&(o-=1),o<1/6?s+(n-s)*6*o:o<1/2?n:o<2/3?s+(n-s)*6*(2/3-o):s);return this.setRGB(Qe(l(t+1/3)),Qe(l(t)),Qe(l(t-1/3)))}lerp(t,r){return this.lerpColors(this,t,r)}lerpColors(t,r,i){let n=Number(i)||0;return this.setRGB(t.r+(r.r-t.r)*n,t.g+(r.g-t.g)*n,t.b+(r.b-t.b)*n)}multiplyScalar(t){let r=Number(t)||0;return this.setRGB(this.r*r,this.g*r,this.b*r)}setScalar(t){let r=Number(t)||0;return this.setRGB(r,r,r)}setHex(t){let r=Math.floor(t);return this.setRGB(Qe((r>>16&255)/255),Qe((r>>8&255)/255),Qe((r&255)/255))}setRGB(t,r,i){return this.r=Number(t),this.g=Number(r),this.b=Number(i),this}convertSRGBToLinear(){return this.setRGB(Qe(this.r),Qe(this.g),Qe(this.b))}convertLinearToSRGB(){return this.setRGB(hr(this.r),hr(this.g),hr(this.b))}getHex(){let t=r=>Math.round(hr(Math.max(0,Math.min(1,r)))*255);return t(this.r)<<16|t(this.g)<<8|t(this.b)}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}copy(t){return this.setRGB(t.r,t.g,t.b)}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b}clone(){return new tl(this.r,this.g,this.b)}},_s={degToRad:e=>e*Math.PI/180,radToDeg:e=>e*180/Math.PI,clamp:(e,t,r)=>Math.max(t,Math.min(r,e)),lerp:(e,t,r)=>e+(t-e)*r,generateUUID:()=>Math.random().toString(36).substring(2,15),randFloat:(e,t)=>e+Math.random()*(t-e)},$e=class rl{constructor(t,r){if(this.needsUpdate=!1,typeof r!="number"||!Number.isInteger(r)||r<1||r>16)throw new Error(`SecurityError: BufferAttribute itemSize must be an integer in [1, 16]. Received: ${String(r)}`);Array.isArray(t)?this.array=new Float32Array(t):this.array=t,this.itemSize=r;let i=this.array?this.array.length:0;if(!Number.isFinite(i)||i<0)throw new Error(`SecurityError: BufferAttribute array has a non-finite length: ${String(i)}`);this.count=Math.floor(i/r)}getX(t){return this.array[t*this.itemSize]}getY(t){return this.array[t*this.itemSize+1]}getZ(t){return this.array[t*this.itemSize+2]}setX(t,r){return this.array[t*this.itemSize]=r,this.needsUpdate=!0,this}setY(t,r){return this.array[t*this.itemSize+1]=r,this.needsUpdate=!0,this}setZ(t,r){return this.array[t*this.itemSize+2]=r,this.needsUpdate=!0,this}setXYZ(t,r,i,n){let s=t*this.itemSize;return this.array[s]=r,this.array[s+1]=i,this.array[s+2]=n,this.needsUpdate=!0,this}setUsage(t){return this}clone(){let t=this.array?.constructor||Float32Array;return new rl(new t(this.array),this.itemSize)}},vr=class extends $e{constructor(e,t){super(e instanceof Float32Array||Array.isArray(e)?e:new Float32Array(e),t)}},Mr=class extends $e{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},Tr=class extends $e{constructor(e,t){super(e instanceof Uint32Array?e:new Uint32Array(e),t)}},Be=class il{constructor(){this.name="",this.attributes={},this.index=null,this.boundingBox=null}setAttribute(t,r){return this.attributes[t]=r,this}getAttribute(t){return this.attributes[t]}setIndex(t){if(t instanceof $e)this.index=t;else if(Array.isArray(t)){let r=0;for(let i of t)i>r&&(r=i);this.index=new $e(new(r>65535?Uint32Array:Uint16Array)(t),1)}else t&&t.buffer&&(this.index=new $e(t,1));return this}computeVertexNormals(){let t=this.attributes.position;if(!t)return this;let r=!1;if(typeof r=="function"){let a=r(t.array,this.index?.array);return this.setAttribute("normal",new $e(a,3)),this}let i=t.count,n=t.array,s=new Float32Array(i*3),l=this.index?.array,o=l?l.length:i;for(let a=0;a<o;a+=3){let u=(l?l[a]:a)*3,h=(l?l[a+1]:a+1)*3,m=(l?l[a+2]:a+2)*3,c=n[h],d=n[h+1],f=n[h+2],g=n[m]-c,x=n[m+1]-d,b=n[m+2]-f,v=n[u]-c,p=n[u+1]-d,y=n[u+2]-f,M=x*y-b*p,P=b*v-g*y,F=g*p-x*v;s[u]+=M,s[u+1]+=P,s[u+2]+=F,s[h]+=M,s[h+1]+=P,s[h+2]+=F,s[m]+=M,s[m+1]+=P,s[m+2]+=F}for(let a=0;a<i*3;a+=3){let u=s[a],h=s[a+1],m=s[a+2],c=Math.hypot(u,h,m)||1;s[a]=u/c,s[a+1]=h/c,s[a+2]=m/c}return this.setAttribute("normal",new $e(s,3)),this}setFromBuffers(t,r,i,n){this.setAttribute("position",new $e(t,3)),this.setAttribute("normal",new $e(r,3)),this.setAttribute("uv",new $e(i,2)),this.setIndex(n)}setFromPoints(t){let r=[];if(Array.isArray(t))for(let i of t)r.push(Number(i?.x)||0,Number(i?.y)||0,Number(i?.z)||0);return this.setAttribute("position",new $e(r,3))}computeBoundingBox(){let t=this.attributes.position,r=new ge(1/0,1/0,1/0),i=new ge(-1/0,-1/0,-1/0);if(t&&t.count>0)for(let n=0;n<t.count;n++){let s=t.getX(n),l=t.getY(n),o=t.getZ(n);s<r.x&&(r.x=s),l<r.y&&(r.y=l),o<r.z&&(r.z=o),s>i.x&&(i.x=s),l>i.y&&(i.y=l),o>i.z&&(i.z=o)}else r.set(0,0,0),i.set(0,0,0);return this.boundingBox={min:r,max:i},this.boundingBox}center(){let t=this.computeBoundingBox();return this.translate(-(t.min.x+t.max.x)*.5,-(t.min.y+t.max.y)*.5,-(t.min.z+t.max.z)*.5)}_xform(t,r){let i=this.attributes.position;if(i){let n=i.array;for(let s=0;s<n.length;s+=3)t(n,s);i.needsUpdate=!0,r&&this.computeVertexNormals(),this.computeBoundingBox()}return this}translate(t=0,r=0,i=0){return this._xform((n,s)=>{n[s]+=t,n[s+1]+=r,n[s+2]+=i})}scale(t=1,r=1,i=1){return this._xform((n,s)=>{n[s]*=t,n[s+1]*=r,n[s+2]*=i},!0)}_rot(t,r,i){let n=Math.cos(i),s=Math.sin(i);for(let l of[this.attributes.position,this.attributes.normal]){if(!l)continue;let o=l.array;for(let a=0;a<o.length;a+=3){let u=o[a+t],h=o[a+r];o[a+t]=u*n-h*s,o[a+r]=u*s+h*n}l.needsUpdate=!0}return this}rotateX(t){return this._rot(1,2,t)}rotateY(t){return this._rot(2,0,t)}rotateZ(t){return this._rot(0,1,t)}applyMatrix4(t){let r=this.attributes.position;if(r&&t?.elements){let i=new ge;for(let n=0;n<r.count;n++)i.set(r.getX(n),r.getY(n),r.getZ(n)).applyMatrix4(t),r.setXYZ(n,i.x,i.y,i.z);this.computeVertexNormals()}return this}clone(){let t=new il;t.name=this.name;for(let r of Object.keys(this.attributes))t.attributes[r]=this.attributes[r].clone();return this.index&&(t.index=this.index.clone()),t}dispose(){}},Cn=class extends Be{constructor(e=1,t=1,r=1){super();let i=e/2,n=t/2,s=r/2,l=[-i,-n,s,i,-n,s,i,n,s,-i,n,s,i,-n,-s,-i,-n,-s,-i,n,-s,i,n,-s,-i,n,s,i,n,s,i,n,-s,-i,n,-s,-i,-n,-s,i,-n,-s,i,-n,s,-i,-n,s,i,-n,s,i,-n,-s,i,n,-s,i,n,s,-i,-n,-s,-i,-n,s,-i,n,s,-i,n,-s],o=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0],a=[],u=[];for(let h=0;h<6;h++){let m=h*4;a.push(0,0,1,0,1,1,0,1),u.push(m,m+1,m+2,m,m+2,m+3)}this.setFromBuffers(l,o,a,u)}},Ar=class extends Be{constructor(e=1,t=1,r=1,i=1){super(),r=Math.max(1,Math.floor(r)),i=Math.max(1,Math.floor(i));let n=[],s=[],l=[],o=[];for(let a=0;a<=i;a++){let u=a/i;for(let h=0;h<=r;h++){let m=h/r;if(n.push((m-.5)*e,(.5-u)*t,0),s.push(0,0,1),l.push(m,1-u),a>0&&h>0){let c=(r+1)*a+h-1,d=c-(r+1);o.push(d,c,d+1,c,c+1,d+1)}}}this.setFromBuffers(n,s,l,o)}},wr=class extends Be{constructor(e=1,t=16,r=12,i=0,n=Math.PI*2,s=0,l=Math.PI){super(),t=Math.max(3,Math.floor(t)),r=Math.max(2,Math.floor(r));let o=[],a=[],u=[],h=[],m=Math.min(s+l,Math.PI);for(let c=0;c<=r;c++){let d=c/r,f=s+d*l;for(let g=0;g<=t;g++){let x=g/t,b=i+x*n,v=-Math.cos(b)*Math.sin(f),p=Math.cos(f),y=Math.sin(b)*Math.sin(f);if(o.push(e*v,e*p,e*y),a.push(v,p,y),u.push(x,1-d),c>0&&g>0){let M=(t+1)*c+g,P=M-(t+1),F=P-1,W=M-1;(c!==1||s>0)&&h.push(P,F,M),(c!==r||m<Math.PI)&&h.push(F,W,M)}}}this.setFromBuffers(o,a,u,h)}},Dn=class extends Be{constructor(e=1,t=1,r=1,i=16,n=1,s=!1,l=0,o=Math.PI*2){super(),i=Math.max(3,Math.floor(i)),n=Math.max(1,Math.floor(Number(n)||1));let a=[],u=[],h=[],m=[],c=r/2,d=(t-e)/(r||1),f=i+1;for(let x=0;x<=n;x++){let b=x/n,v=b*(t-e)+e,p=c-b*r;for(let y=0;y<=i;y++){let M=y/i,P=l+M*o,F=Math.sin(P),W=Math.cos(P),T=Math.hypot(F,d,W)||1;if(a.push(v*F,p,v*W),u.push(F/T,d/T,W/T),h.push(M,1-b),x<n&&y<i){let E=x*f+y,S=E+f;m.push(E,S,E+1,S,S+1,E+1)}}}let g=(x,b)=>{if(s||x<=0)return;let v=b*c,p=a.length/3;a.push(0,v,0),u.push(0,b,0),h.push(.5,.5);let y=p+1;for(let M=0;M<=i;M++){let P=l+M/i*o,F=Math.sin(P),W=Math.cos(P);a.push(x*F,v,x*W),u.push(0,b,0),h.push(W*.5+.5,.5+b*F*.5),M<i&&m.push(p,y+M+(b>0?0:1),y+M+(b>0?1:0))}};g(e,1),g(t,-1),this.setFromBuffers(a,u,h,m)}},Sr=class extends Dn{constructor(e=1,t=1,r=16,i=1,n=!1,s=0,l=Math.PI*2){super(0,e,t,r,i,n,s,l)}},Er=class extends Be{constructor(e=1,t=.4,r=12,i=48,n=Math.PI*2){super(),r=Math.max(3,Math.floor(r)),i=Math.max(3,Math.floor(i));let s=[],l=[],o=[],a=[];for(let u=0;u<=r;u++){let h=u/r*Math.PI*2,m=Math.cos(h),c=Math.sin(h);for(let d=0;d<=i;d++){let f=d/i*n,g=Math.cos(f),x=Math.sin(f);if(s.push((e+t*m)*g,(e+t*m)*x,t*c),l.push(m*g,m*x,c),o.push(d/i,u/r),u>0&&d>0){let b=(i+1)*u+d-1,v=b-(i+1);a.push(b,v,b+1,v,v+1,b+1)}}}this.setFromBuffers(s,l,o,a)}};function Ls(e,t,r,i,n){let s=Math.max(2,Math.min(256,Math.floor(Number(t)||64))),l=Math.max(3,Math.min(64,Math.floor(Number(r)||8))),o=Number(i)||.1,a=[],u=[],h=[],m=[],c=[],d=new ge,f=new ge,g=new ge;for(let b=0;b<=s;b++){let v=new ge;n(b/s,v),c.push(v)}let x=l+1;for(let b=0;b<=s;b++){let v=b/s,p=c[b];d.subVectors(c[Math.min(s,b+1)],c[Math.max(0,b-1)]).normalize(),b===0&&f.set(Math.abs(d.y)>.9?1:0,Math.abs(d.y)>.9?0:1,0),g.crossVectors(d,f).normalize(),f.crossVectors(g,d).normalize();for(let y=0;y<=l;y++){let M=y/l*Math.PI*2,P=-Math.cos(M),F=Math.sin(M),W=P*f.x+F*g.x,T=P*f.y+F*g.y,E=P*f.z+F*g.z;if(a.push(p.x+o*W,p.y+o*T,p.z+o*E),u.push(W,T,E),h.push(v,y/l),b>0&&y>0){let S=x*(b-1)+y-1,O=S+x;m.push(S,O,S+1,O,O+1,S+1)}}}e.setFromBuffers(a,u,h,m)}var Rr=class extends Be{constructor(e=1,t=.4,r=64,i=8,n=2,s=3){super(),r=Math.floor(r),i=Math.floor(i),Ls(this,r,i,t,(l,o)=>{let a=l*n*Math.PI*2,u=s/n*a,h=e*(2+Math.cos(u))*.5;o.set(h*Math.cos(a),h*Math.sin(a),e*Math.sin(u)*.5)})}},St=class{getPoint(e,t=new ge){return t}getPointAt(e,t=new ge){return this.getPoint(e,t)}getTangent(e,t=new ge){return t.subVectors(this.getPoint(Math.min(1,e+.001)),this.getPoint(Math.max(0,e-.001))).normalize()}getPoints(e=5){let t=Math.max(1,Math.min(512,Math.floor(Number(e)||5))),r=[];for(let i=0;i<=t;i++)r.push(this.getPoint(i/t));return r}getSpacedPoints(e=5){return this.getPoints(e)}},_r=class extends St{constructor(e=new ge,t=new ge){super(),this.v1=e,this.v2=t}getPoint(e,t=new ge){return t.lerpVectors(this.v1,this.v2,e)}},Lr=class extends St{constructor(e=new ge,t=new ge,r=new ge){super(),this.v0=e,this.v1=t,this.v2=r}getPoint(e,t=new ge){return t.lerpVectors(this.v0,this.v1,e).lerp(new ge().lerpVectors(this.v1,this.v2,e),e)}},Ir=class extends St{constructor(e=new ge,t=new ge,r=new ge,i=new ge){super(),this.v0=e,this.v1=t,this.v2=r,this.v3=i}getPoint(e,t=new ge){let r=new ge().lerpVectors(this.v0,this.v1,e),i=new ge().lerpVectors(this.v1,this.v2,e),n=new ge().lerpVectors(this.v2,this.v3,e);return t.lerpVectors(r.lerp(i,e),i.lerp(n,e),e)}},Cr=class extends St{constructor(e=[],t=!1){super(),this.points=Array.isArray(e)?e:[],this.closed=!!t}getPoint(e,t=new ge){let r=this.points,i=r.length;if(!i)return t.set(0,0,0);if(i===1)return t.copy(r[0]);let n=(this.closed?i:i-1)*Math.max(0,Math.min(1,Number(e)||0)),s=Math.floor(n),l=n-s;!this.closed&&s>=i-1&&(s=i-2,l=1);let o=g=>r[this.closed?(g%i+i)%i:Math.max(0,Math.min(i-1,g))],a=o(s-1),u=o(s),h=o(s+1),m=o(s+2),c=l*l,d=c*l,f=(g,x,b,v)=>.5*(2*x+(b-g)*l+(2*g-5*x+4*b-v)*c+(3*x-g-3*b+v)*d);return t.set(f(a.x,u.x,h.x,m.x),f(a.y,u.y,h.y,m.y),f(a.z,u.z,h.z,m.z))}},Pn=class extends Be{constructor(e=[new rt(0,-.5),new rt(.5,0),new rt(0,.5)],t=12,r=0,i=Math.PI*2){super();let n=Array.isArray(e)&&e.length>=2?e:[new rt(.2,0),new rt(.2,.5)],s=Math.max(3,Math.min(128,Math.floor(Number(t)||12))),l=[],o=[],a=[],u=[],h=n.length;for(let m=0;m<=s;m++){let c=m/s,d=r+c*i,f=Math.sin(d),g=Math.cos(d),x=m*h;for(let b=0;b<h;b++){let v=n[b],p=Number(v?.x)||0,y=Number(v?.y)||0;l.push(p*f,y,p*g);let M=n[Math.max(0,b-1)],P=n[Math.min(h-1,b+1)],F=(Number(P?.x)||0)-(Number(M?.x)||0),W=(Number(P?.y)||0)-(Number(M?.y)||0),T=Math.hypot(W,F)||1;if(o.push(W/T*f,-F/T,W/T*g),a.push(c,b/(h-1)),m<s&&b<h-1){let E=x+b,S=E+h;u.push(E,S,E+1,S,S+1,E+1)}}}this.setFromBuffers(l,o,a,u)}},Dr=class extends Be{constructor(e,t=64,r=1,i=8,n=!1){super(),Ls(this,t,i,r,(s,l)=>{let o=e?.getPointAt??e?.getPoint;if(typeof o=="function"){let a=o.call(e,s,l);a&&a!==l&&l.copy(a)}else l.set(0,s,0)})}},pr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",an=class{constructor(e=""){this.isTexture=!0,this.wrapS=10497,this.wrapT=10497,this.repeat=new rt(1,1),this.offset=new rt(0,0),this.image=null,this.width=0,this.height=0,this.source=e,e&&typeof e=="object"&&(this.image=e)}dispose(){}},Pr=class extends an{constructor(e=null,t=1,r=1,i=1023,n=1009,s,l=1001,o=1001,a=1003,u=1003,h=1,m=""){super(""),this.isDataTexture=!0,this.avgColor=[1,1,1,1],this.flipY=!1,this.generateMipmaps=!1,this.unpackAlignment=1,this._sig=0;let c=Number(t),d=Number(r),f=e&&typeof e.length=="number"?e:null;this.width=c,this.height=d,this.image={data:f,width:c,height:d},this.format=Number(i)||1023,this.type=Number(n)||1009,this.wrapS=Number(l)||1001,this.wrapT=Number(o)||1001,this.magFilter=Number(a)||1003,this.minFilter=Number(u)||1003,this.colorSpace=m||"",this._bake()}get needsUpdate(){return!1}set needsUpdate(e){e&&this._bake()}_bake(){let e=this.image,t=e?.data,r=Number(e?.width??this.width),i=Number(e?.height??this.height);if(!t||!t.length||!(r>0&&i>0)||r>2048||i>2048){this.source="";return}let n=Math.max(1,r|0),s=Math.max(1,i|0),l=n*s,o=this.format,a=o===1021||o===1024||o===1028||t.length===l?1:o===1025||o===1030||t.length===l*2?2:o===1022||t.length===l*3?3:4,u=this.type===1015||this.type===1016||t instanceof Float32Array||t instanceof Float64Array,h=Math.min(n,48),m=Math.min(s,48),c=(this.flipY?257:1)^this.colorSpace.length^t.length,d=Math.max(1,t.length>>6|0);for(let O=0;O<t.length;O+=d)c=Math.imul(c^(t[O]*256|0),16777619)|0;if(c===this._sig&&this.source)return;this._sig=c;let f=m*(1+h*4),g=new Uint8Array(68+f),x=new DataView(g.buffer);x.setUint32(0,2303741511),x.setUint32(4,218765834),x.setUint32(8,13),x.setUint32(12,1229472850),x.setUint32(16,h),x.setUint32(20,m),g[24]=8,g[25]=6,x.setUint32(29,An(g.subarray(12,29))),x.setUint32(33,f+11),x.setUint32(37,1229209940),g[41]=120,g[42]=1,g[43]=1,x.setUint16(44,f,!0),x.setUint16(46,~f&65535,!0);let b=48,v=1,p=0,y=0,M=0,P=0,F=0,W=O=>{if(!Number.isFinite(O))return 0;let k=u&&O<=1?O*255:O;return k>0?k<255?k+.5|0:255:0};for(let O=0;O<m;O++){let k=O*s/m|0,w=this.flipY?s-1-k:k;g[b++]=0,p+=v;for(let ie=0;ie<h;ie++){let oe=(w*n+(ie*n/h|0))*a,I=o===1021?255:W(t[oe]??0),H=a>=3||o===1030?W(t[oe+1]??0):I,N=a>=3?W(t[oe+2]??0):o===1030?0:I,z=a===4?W(t[oe+3]??255):o===1021?W(t[oe]??255):o===1025?W(t[oe+1]??255):255;g[b++]=I,v+=I,p+=v,g[b++]=H,v+=H,p+=v,g[b++]=N,v+=N,p+=v,g[b++]=z,v+=z,p+=v,y+=I,M+=H,P+=N,F+=z}v%=65521,p%=65521}x.setUint32(b,(p<<16|v)>>>0),x.setUint32(b+4,An(g.subarray(37,b+4))),x.setUint32(b+12,1229278788),x.setUint32(b+16,2923585666);let T=h*m*255,E=this.colorSpace==="srgb-linear";this.avgColor=[E?y/T:Qe(y/T),E?M/T:Qe(M/T),E?P/T:Qe(P/T),F/T];let S=["data:image/png;base64,"];for(let O=0;O<g.length;O+=3){let k=g[O]<<16|(g[O+1]??0)<<8|(g[O+2]??0);S.push(pr[k>>18&63]+pr[k>>12&63]+(O+1<g.length?pr[k>>6&63]:"=")+(O+2<g.length?pr[k&63]:"="))}this.source=S.join("")}},Nr=class{load(e,t){let r=new an(e);return t?.(r),r}};function Ye(e,t){return e!==void 0?Number(e):t}function zi(e,t){return e!==void 0?!!e:t}var et=class{constructor(e={}){this.name=e.name||"",this.color=new ut(e.color??16777215),this.emissive=new ut(e.emissive??0),this.emissiveIntensity=Ye(e.emissiveIntensity,1),this.roughness=Ye(e.roughness,.5),this.metalness=Ye(e.metalness,0),this.opacity=Ye(e.opacity,1),this.transparent=zi(e.transparent,!1),this.wireframe=zi(e.wireframe,!1),this.side=Ye(e.side,2),this.doubleSided=zi(e.doubleSided,!0),this.map=e.map||null;for(let t of["normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap"])e[t]&&(this[t]=e[t]);this.clearcoat=Ye(e.clearcoat,0),this.clearcoatRoughness=Ye(e.clearcoatRoughness,0),this.sheen=Ye(e.sheen,0),this.sheenColor=new ut(e.sheenColor??0),this.sheenRoughness=Ye(e.sheenRoughness,0),this.transmission=Ye(e.transmission,0),this.thickness=Ye(e.thickness,0),this.attenuationColor=new ut(e.attenuationColor??16777215),this.attenuationDistance=Ye(e.attenuationDistance,1/0),this.ior=Ye(e.ior,1.5),this.dispersion=Ye(e.dispersion,0),this.iridescence=Ye(e.iridescence,0),this.iridescenceIOR=Ye(e.iridescenceIOR,1.3)}dispose(){}},Bt=class extends et{},kr=class extends et{},Or=class extends et{},Ur=class extends et{},Fr=class extends et{},lt=class nl{constructor(){this.name="",this.matrixAutoUpdate=!0,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.parent=null,this.children=[],this.userData={},this.position=new ge,this.rotation=new In,this.quaternion=new sn,this.scale=new ge(1,1,1),this.matrix=new Pt,this.matrixWorld=new Pt,this.rotation._onChange(()=>{this.quaternion.setFromEuler(this.rotation,!1)}),this.quaternion._onChange(()=>{let t=this.quaternion,r=Math.atan2(2*(t.w*t.x+t.y*t.z),1-2*(t.x*t.x+t.y*t.y)),i=Math.asin(Math.max(-1,Math.min(1,2*(t.w*t.y-t.z*t.x)))),n=Math.atan2(2*(t.w*t.z+t.x*t.y),1-2*(t.y*t.y+t.z*t.z));this.rotation.set(r,i,n)})}add(...t){for(let r of t)r&&r instanceof nl&&(r.parent&&r.parent.remove(r),r.parent=this,this.children.push(r));return this}remove(...t){for(let r of t){let i=this.children.indexOf(r);i!==-1&&(r.parent=null,this.children.splice(i,1))}return this}traverse(t){let r=new Set,i=[this];for(;i.length>0;){let n=i.pop();if(!n||typeof n!="object"||r.has(n))continue;r.add(n),t(n);let s=n.children;if(Array.isArray(s))for(let l=s.length-1;l>=0;l--)i.push(s[l])}}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale)}updateMatrixWorld(t=!1){this.traverse(r=>{Is(r),(r.matrixAutoUpdate||t)&&r.updateMatrix?.(),r.parent&&r.parent.matrixWorld?r.matrixWorld?.multiplyMatrices(r.parent.matrixWorld,r.matrix):r.matrix&&r.matrixWorld?.copy(r.matrix)})}lookAt(t,r,i){let n=typeof t=="object"?t:new ge(t,r,i);this.target instanceof ge?this.target.copy(n):this.target?.position instanceof ge&&this.target.position.copy(n),this.updateMatrixWorld(!0);let s=new Pt;s.lookAt(this.position,n,new ge(0,1,0));let l=s.elements,o=l[0],a=l[4],u=l[8],h=l[1],m=l[5],c=l[9],d=l[2],f=l[6],g=l[10],x=o+m+g;if(x>0){let b=.5/Math.sqrt(x+1);this.quaternion.set((f-c)*b,(u-d)*b,(h-a)*b,.25/b)}}translateOnAxis(t,r){let i=t.clone().applyMatrix4(new Pt().makeRotationFromQuaternion(this.quaternion)).multiplyScalar(r);return this.position.add(i),this}translateX(t){return this.translateOnAxis(new ge(1,0,0),t)}translateY(t){return this.translateOnAxis(new ge(0,1,0),t)}translateZ(t){return this.translateOnAxis(new ge(0,0,1),t)}rotateX(t){return this.rotation.x+=t,this}rotateY(t){return this.rotation.y+=t,this}rotateZ(t){return this.rotation.z+=t,this}_chain(){let t=[];for(let r=this;r&&t.length<64;r=r.parent)t.push(r);return t}_syncWorld(){let t=this._chain();for(let r=t.length-1;r>=0;r--){let i=t[r];i.updateMatrix?.(),i.parent?.matrixWorld?i.matrixWorld.multiplyMatrices(i.parent.matrixWorld,i.matrix):i.matrixWorld?.copy(i.matrix)}return this.matrixWorld.elements}getWorldPosition(t=new ge){let r=this._syncWorld();return t.set(r[12],r[13],r[14])}getWorldScale(t=new ge){let r=this._syncWorld();return t.set(Math.hypot(r[0],r[1],r[2]),Math.hypot(r[4],r[5],r[6]),Math.hypot(r[8],r[9],r[10]))}getWorldDirection(t=new ge){let r=this._syncWorld();return t.set(r[8],r[9],r[10]).normalize()}getWorldQuaternion(t=new sn){let r=this._chain();t.set(0,0,0,1);for(let i=r.length-1;i>=0;i--)t.multiply(r[i].quaternion);return t}clone(t=!0){let r=this instanceof Nt?new this.constructor(this._sourceGeo||this.geometry,this.material):this instanceof gt?new gt(this.geometry,this.material):new this.constructor;r.name=this.name,r.position.copy(this.position),r.quaternion.copy(this.quaternion),r.scale.copy(this.scale),r.visible=this.visible,r.castShadow=this.castShadow,r.receiveShadow=this.receiveShadow;try{r.userData=JSON.parse(JSON.stringify(this.userData||{}))}catch{r.userData={...this.userData||{}}}if(t)for(let i of this.children)r.add(i.clone(!0));return r}},Vr=class extends lt{},gt=class extends lt{constructor(e,t){super(),this.isMesh=!0;let r=Array.isArray(t)?t[0]:t;this.geometry=e instanceof Be?e:e?(Gt("unsupported geometry","BoxGeometry"),new Cn(.5,.5,.5)):new Be,this.material=r instanceof et?r:r?(Gt("unsupported material","MeshStandardMaterial"),new Bt({color:13421772})):new Bt}};function Is(e){typeof e?._bakeAuthorGeometry=="function"&&e._bakeAuthorGeometry();let t=Ae().materializeDeclarativeGeometry;typeof t=="function"&&t(e)}var Nn=1e4,kn=class extends gt{constructor(e,t,r=1){super(e,t),this.instanceColor=null,this.isInstancedMesh=!0;let i=Number(r);if(!Number.isFinite(i)||i<0||i>Nn)throw new RangeError(`SecurityError: InstancedMesh count (${String(r)}) exceeds MAX_INSTANCES_PER_MESH (${Nn})`);this.count=Math.floor(i);let n=new Float32Array(this.count*16);for(let s=0;s<this.count;s++){let l=s*16;n[l]=1,n[l+5]=1,n[l+10]=1,n[l+15]=1}this.instanceMatrix=new $e(n,16)}setMatrixAt(e,t){let r=Math.floor(Number(e));if(!Number.isFinite(r)||r<0||r>=this.count||!t||!t.elements)return;let i=this.instanceMatrix.array,n=r*16;if(!(n+16>i.length))for(let s=0;s<16;s++){let l=Number(t.elements[s]);i[n+s]=Number.isFinite(l)?l:s%5===0?1:0}}getMatrixAt(e,t){let r=Math.floor(Number(e));if(!Number.isFinite(r)||r<0||r>=this.count||!t||!t.elements)return;let i=this.instanceMatrix.array,n=r*16;if(!(n+16>i.length))for(let s=0;s<16;s++)t.elements[s]=i[n+s]}setColorAt(e,t){let r=Math.floor(Number(e));if(!Number.isFinite(r)||r<0||r>=this.count||!t)return;if(!this.instanceColor||this.instanceColor.array.length<this.count*3){let s=new Float32Array(this.count*3);s.fill(1),this.instanceColor=new $e(s,3)}let i=this.instanceColor.array,n=r*3;i[n]=Number.isFinite(t.r)?t.r:1,i[n+1]=Number.isFinite(t.g)?t.g:1,i[n+2]=Number.isFinite(t.b)?t.b:1}getColorAt(e,t){let r=Math.floor(Number(e));if(!Number.isFinite(r)||r<0||r>=this.count||!t)return;if(!this.instanceColor||this.instanceColor.array.length<(r+1)*3){t.setRGB(1,1,1);return}let i=this.instanceColor.array,n=r*3;t.setRGB(i[n],i[n+1],i[n+2])}dispose(){}},zt=class extends lt{constructor(e=16777215,t=1){super(),this.color=new ut(e),this.intensity=Number(t),this.type="directional"}},On=class extends zt{constructor(e,t){super(e,t),this.type="ambient"}},Br=class extends zt{constructor(e,t){super(e,t),this.target=new lt,this.type="directional"}},Un=class extends zt{constructor(e,t,r=0,i=2){super(e,t),this.type="point",this.distance=r,this.decay=i}},Fn=class extends lt{},zr=class extends Fn{constructor(e=45,t=1,r=.1,i=1e3){super(),this.target=new ge(0,0,0),this.fov=Number(e),this.aspect=Number(t),this.near=Number(r),this.far=Number(i)}},Vn=class extends lt{constructor(){super(...arguments),this.background=null,this.environmentIntensity=1}toCanvas3D(){return yt.validate(this),rn(this)}toGLB(){return yt.validate(this),Tn(this)}toUSDZ(){return yt.validate(this),wn(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let e=new Map,t=0;return this.traverse(r=>{if(r instanceof gt){let i=new Float32Array(r.matrixWorld.elements);e.set(t,i),r.name&&e.set(r.name,i),t++}}),e}},Gi=rn,Hi=Tn,Cs=wn,yt=class{static validate(e){let t=0,r=0,i=0,n=new Set,s=(o,a,u)=>{throw new Error(`SecurityError: Scene exceeds SECURITY_3D_MAX_${o} (${a}). Found: ${u}`)},l=(o,a)=>{if(!Number.isFinite(a))throw new Error(`SecurityError: Scene reports a non-finite ${o} count (${String(a)}), which cannot be bounds-checked.`);return a};e.traverse(o=>{if(Is(o),o instanceof gt||o.geometry?.attributes?.position?.count){if(i++,i>1e3&&s("MESHES",1e3,i),o instanceof kn){let u=l("instance",o.count);(u<0||u>Nn)&&s("INSTANCES",Nn,u)}let a=o.geometry;if(a){let u=0;if(a.attributes.position&&(u=l("vertex",a.attributes.position.count),t+=u,t>1e5&&s("VERTICES",1e5,t)),a.index){let h=l("index",a.index.count);r+=h,r>3e5&&s("INDICES",3e5,r);let m=a.index.array;if(m&&u>0){let c=Math.min(h,m.length);for(let d=0;d<c;d++){let f=m[d];if(!Number.isFinite(f)||f<0||f>=u)throw new Error(`SecurityError: Index buffer value (${String(f)}) out of vertex bounds [0, ${u}).`)}}}}if(o.material){let u=o.material;for(let h of["map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap"])u[h]&&n.add(u[h])}}}),n.size>16&&s("TEXTURES",16,n.size);for(let o of n){let a=o,u=a.image,h=Number(u?.width??a.width??0)||0,m=Number(u?.height??a.height??0)||0;(!Number.isFinite(h)||!Number.isFinite(m)||h>2048||m>2048)&&s("TEXTURE_DIMENSION",2048,Math.max(h,m))}}},Gr=class{constructor(e={}){this.shadowMap={enabled:!1,type:0},this.capabilities={isWebGL2:!0,maxTextures:16},this.boundViewer=null,this.hasInitialModelRendered=!1,this.domElement=e.canvas||(typeof document<"u"?document.createElement("canvas"):{}),e.viewer&&(this.boundViewer=e.viewer),e.container?.threeLiveViewer&&(this.boundViewer=e.container.threeLiveViewer),e.canvas?.parentElement?.threeLiveViewer&&(this.boundViewer=e.canvas.parentElement.threeLiveViewer);let t=typeof WorkerGlobalScope<"u"&&typeof self<"u"&&self instanceof WorkerGlobalScope;this.isSandboxed=e.isSandboxed||t,this.containerId=e.containerId||""}setSize(e,t){return this}setPixelRatio(e){return this}setClearColor(e,t=1){let r=new ut(e);return this.boundViewer&&typeof this.boundViewer.setClearColor=="function"&&this.boundViewer.setClearColor(r.r,r.g,r.b,t),this}clear(){return this}dispose(){}render(e,t){if(this.isSandboxed){yt.validate(e);let i=(n,s)=>{typeof self<"u"&&typeof self.postMessage=="function"&&(s&&s.length?self.postMessage(n,s):self.postMessage(n))};if(this.hasInitialModelRendered){let n=e.getMeshTransforms(),s={};for(let[l,o]of n.entries())s[l]=Array.from(o);i({type:"3D_UPDATE_TRANSFORMS",containerId:this.containerId,transforms:s})}else{this.hasInitialModelRendered=!0;let n=Gi(e),s=Hi(e),l=(n.lights||[]).map(o=>({type:o.type,color:o.color,intensity:o.intensity,position:o.position}));i({type:"3D_MODEL_READY",containerId:this.containerId,glbBuffer:s.buffer,dynamicLights:l,camera:t?{fov:t.fov||60,position:[t.position.x,t.position.y,t.position.z]}:void 0},[s.buffer])}return}let r=this.boundViewer;!r&&this.domElement?.parentElement&&this.domElement.parentElement.threeLiveViewer&&(r=this.domElement.parentElement.threeLiveViewer,this.boundViewer=r),!r&&typeof window<"u"&&(r=window.__three_live_active_viewer__,this.boundViewer=r),r&&typeof r.loadModel=="function"&&(r._hasThreeLiveModelLoaded?typeof r.updateMeshTransforms=="function"&&r.updateMeshTransforms(e.getMeshTransforms()):(r.loadModel(e.toCanvas3D()),r._hasThreeLiveModelLoaded=!0))}};function Ms(){return typeof globalThis<"u"&&typeof globalThis.__three_live_sim_time_ms__=="number"?globalThis.__three_live_sim_time_ms__:typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Hr=class{constructor(e=!0){this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1,this.autoStart=e,e&&this.start()}start(){this.startTime=Ms(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running&&this.start(),this.running){let t=Ms();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function gc(){}var _n=new Proxy(gc,{get:(e,t)=>{if(t==="isProxy")return!0;if(!(t==="constructor"||t==="__proto__"||t==="prototype"))return t==="domElement"?typeof document<"u"?document.createElement("canvas"):{}:t==="shadowMap"?{enabled:!1,type:0}:t==="capabilities"?{isWebGL2:!0,maxTextures:16}:t===Symbol.toPrimitive?()=>0:_n},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>_n,construct:()=>_n}),Ts=(()=>{try{if(typeof document>"u")return null;let e=document.currentScript;return e?.src?e.src:e?.textContent&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(new Blob([e.textContent],{type:"text/javascript"})):null}catch{return null}})();function ii(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function cn(e,t){if(!e||typeof e!="string")return!1;let r=e.trim();if(!r)return!1;try{let i=new URL(r,ii());return!(i.protocol!=="https:"&&i.protocol!=="http:"&&i.protocol!=="blob:"||t?.requireSameOrigin&&i.protocol!=="blob:"&&typeof location<"u"&&location.origin&&location.origin!=="null"&&i.origin!==location.origin)}catch{return!1}}var As,Rn;function Ds(e){if(!cn(e))throw new Error(`SecurityError: Refusing to create TrustedScriptURL for disallowed URL "${e}".`);let t=globalThis.trustedTypes;if(!t||typeof t.createPolicy!="function")return e;if(Rn===void 0||As!==t){As=t;try{Rn=t.createPolicy("three-live#worker",{createScriptURL:r=>{if(!cn(r))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${r}".`);return r}})}catch{Rn=null}}return Rn?Rn.createScriptURL(e):e}function xc(e){Ae().sandboxEngineSrc=e}function Xi(){let e=Ae().sandboxEngineSrc;if(e)return e;if(Ts)return Ts;try{if(typeof document>"u")return null;let t=ii(),r=Array.from(document.querySelectorAll("script[src]"));for(let i of r){let n=i.src;if(!n)continue;let s=new URL(n,t).pathname;if(/(?:^|\/)(?:three|xr)-live[^/]*\.js$/.test(s)&&cn(n,{requireSameOrigin:!0}))return n}}catch{}return null}function $i(e,t){if(!cn(e))throw new Error(`SecurityError: Refusing to load ${t} from disallowed URL "${e}". Only http:, https:, and blob: URLs are permitted.`);return new URL(e,ii()).href}function vc(){let e=Xi();if(!e)throw new Error("Three-Live could not locate its own bundle URL, which the worker sandbox needs in order to load the THREE runtime. Set it explicitly, e.g. ThreeLiveElement.sandboxEngineSrc = new URL('three-live.min.js', import.meta.url).href. Refusing to execute the script, because unsandboxed host-realm execution is prohibited.");return $i(e,"sandbox engine")}function Mc(e){Ae().sandboxIframeSrc=e}function Ps(){let e=Ae().sandboxIframeSrc;if(e)return e;let t=Xi();if(!t||!cn(t))return null;let r=new URL(t,ii());return r.protocol==="blob:"?null:new URL("three-live-sandbox.html",r).href}function Tc(){let e=Ps();if(!e)throw new Error("Three-Live could not locate three-live-sandbox.html for iframe sandbox execution. Set ThreeLiveElement.sandboxIframeSrc (or ThreeLiveElement.sandboxEngineSrc) explicitly.");return $i(e,"sandbox iframe")}function Ac(e){Ae().allowClientScripts=e}function Ns(){return!!Ae().allowClientScripts}function wc(e){return $i(e,"procedural scene script")}var Sc=["fetch","XMLHttpRequest","WebSocket","WebSocketStream","WebTransport","EventSource","importScripts","Request","Response","Headers","navigator","WorkerNavigator","WorkerLocation","RTCPeerConnection","RTCDataChannel","FontFace","FontFaceSet","fonts","PerformanceObserver","ReportingObserver","indexedDB","IDBFactory","caches","CacheStorage","Cache","cookieStore","StorageManager","FileSystemHandle","Worker","SharedWorker","ServiceWorker","ServiceWorkerContainer","ServiceWorkerRegistration","registration","clients","BroadcastChannel","MessageChannel","MessagePort","createImageBitmap","OffscreenCanvas","WebAssembly","WorkerGlobalScope","DedicatedWorkerGlobalScope","trustedTypes","TrustedTypePolicyFactory","SharedArrayBuffer","Atomics"];function Ec(e,t){let r=self,i=e.nonce,n=e.engineSrc,s=e.allowedScriptUrl,l=e.allowClientScripts,o=e.revoked,a=r.postMessage.bind(r);function u(p){a({type:"ERROR",nonce:i,message:String(p)})}let h=typeof r.importScripts=="function"?r.importScripts.bind(r):null,m=s,c=null;try{let p=n;if(typeof r.trustedTypes<"u"&&r.trustedTypes&&typeof r.trustedTypes.createPolicy=="function")try{let y={createScriptURL:function(P){if(P!==n&&(!s||P!==s))throw new TypeError("Disallowed worker importScripts URL");return P}};l&&(y.createScript=function(P){return String(P)});let M=r.trustedTypes.createPolicy("three-live#worker-boot",y);p=M.createScriptURL(n),s&&(m=M.createScriptURL(s)),l&&typeof M.createScript=="function"&&(c=M.createScript.bind(M))}catch{}h(p)}catch(p){u('Sandbox failed to load the Three-Live engine from "'+n+'". It must be a same-origin (or CORS-enabled) IIFE bundle such as three-live.min.js. Underlying error: '+(p&&p.message||p));return}let d=r.THREE;if(!d||typeof d.Scene!="function"){u('Sandbox loaded "'+n+'" but it did not install a THREE namespace. Point sandboxEngineSrc at an IIFE build (three-live.min.js), not an ES module build.');return}if(Array.isArray(t)){let p=r.__THREE_LIVE_REGISTRY__;for(let y=0;y<t.length;y++)if(typeof t[y]=="function")try{t[y](d,p)}catch{}}function f(p,y,M){let P=r;for(;P&&P!==Object.prototype;){if(!M&&P!==r)try{delete P[p]}catch{}if(!M||P===r||Object.prototype.hasOwnProperty.call(P,p))try{Object.defineProperty(P,p,M?{value:y,writable:!1,configurable:!1}:{value:y,writable:!1,configurable:!1,enumerable:!1})}catch{}try{P=Object.getPrototypeOf(P)}catch{break}}}for(let p=0;p<o.length;p++)f(o[p],void 0);f("performance",Object.freeze({now:function(){return Date.now()}}));let g=["3D_MODEL_READY","3D_UPDATE_TRANSFORMS"],x=!1;function b(p,y){if(p.type==="3D_MODEL_READY"){if(x)return;x=!0}p.nonce=i,y&&y.length?a(p,y):a(p)}f("postMessage",function(p,y){if(!p||g.indexOf(p.type)===-1)throw new Error("Sandboxed scripts may only post Three-Live scene messages ("+g.join(", ")+").");b(p,y)},!0);let v=!1;r.onmessage=function(p){let y=p&&p.data;if(!(!y||y.nonce!==i)&&!(y.type!=="EXECUTE"&&y.type!=="EXECUTE_URL")&&!v){v=!0;try{let M=new d.Scene,P=new d.PerspectiveCamera(60,1,.1,1e3),F=new d.WebGLRenderer({isSandboxed:!0});if(y.type==="EXECUTE_URL"){if(!s||y.scriptUrl!==s||typeof h!="function"){u("SecurityError: Refusing to execute unapproved script URL inside sandbox worker.");return}let W=m||s,T=h;if(h=null,m=null,r.THREE=d,r.scene=M,r.camera=P,r.renderer=F,T(W),typeof r.__THREE_LIVE_SCENE__=="function"){let E=r.__THREE_LIVE_SCENE__(d,M,P,F);E&&typeof E.toGLB=="function"&&(M=E)}else r.scene&&typeof r.scene.toGLB=="function"&&(M=r.scene)}else{if(!l){u("SecurityError: Client-modified script compilation (Use Case 1) is disabled in this sandbox worker.");return}let W=c?(0,eval)(c(`(function (THREE, scene, camera, renderer) {
|
|
392
|
+
`,surfaceConnections:y,surfaceInputsUsda:b,usesTime:i.usesTime}}function Ar(e,t,r,i){let n=typeof e=="number"&&Number.isFinite(e)?e:i;return Math.max(t,Math.min(r,n))}function Hp(e){return Array.isArray(e)&&e.length>=3&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])}function Jc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Wp(e,t=256){return typeof e=="string"&&e.length>0?e.slice(0,t):void 0}function Qd(e){let t=Jc(e);if(!t)return null;let r=t.target;return{target:Hp(r)?[r[0],r[1],r[2]]:typeof r=="string"&&r.length>0&&r.length<=256?r:[0,0,0],radius:Ar(t.radius,.01,50,.5),speed:Ar(t.speed,-20,20,.5),height:Ar(t.height,-10,10,0),phase:Ar(t.phase,-1e6,1e6,0),faceCenter:t.faceCenter===!0}}var Xp=["hum","reactor","wind","beacon","geiger","chimeLoop","machinery","water"],qp=["confirm","error","alarm","warning","pickup","jump","beam","impact","burst","powerup","step","pass","fail"],wg=new Set(Xp),Sg=new Set(qp);function Qc(e,t){let r=Wp(e,16)?.trim();if(!r)return t;let i=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(r);return i?`#${i[1].toLowerCase()}`:t}function Zc(e){if(!e||typeof e=="number"&&!(e>0&&Number.isFinite(e)))return null;let t=e===!0?{}:typeof e=="number"?{strength:e}:Jc(e);if(!t||t.enabled===!1)return null;let r=Ar(t.strength??t.intensity,0,5,.35);return r>0?{enabled:!0,strength:r,threshold:Ar(t.threshold,0,4,.8),radius:Ar(t.radius,0,2,.5)}:null}function Ms(e){if(!e)return null;let t=e===!0?{}:typeof e=="string"?{color:e}:Jc(e);if(!t||t.enabled===!1)return null;let r=t.thickness??t.width;return{enabled:!0,color:Qc(t.color,"#38bdf8"),thickness:Ar(typeof r=="number"&&r>0&&r<.25?Math.max(1.5,r*140):r,.5,20,3),pulse:t.pulse===!0}}var tn=class Dh{constructor(t=0,r=0){this.x=Number(t),this.y=Number(r)}set(t,r){return this.x=Number(t),this.y=Number(r),this}clone(){return new Dh(this.x,this.y)}copy(t){return this.set(t.x,t.y)}add(t){return this.x+=t.x,this.y+=t.y,this}sub(t){return this.x-=t.x,this.y-=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divideScalar(t){return this.multiplyScalar(t?1/t:0)}setScalar(t){return this.set(t,t)}get width(){return this.x}set width(t){this.x=Number(t)}get height(){return this.y}set height(t){this.y=Number(t)}},Ze=class Fh{constructor(t=0,r=0,i=0){this.x=Number(t),this.y=Number(r),this.z=Number(i)}set(t,r,i){return this.x=Number(t),this.y=Number(r),this.z=Number(i),this}clone(){return new Fh(this.x,this.y,this.z)}copy(t){return this.set(t.x,t.y,t.z)}add(t){return this.addVectors(this,t)}addVectors(t,r){return this.set(t.x+r.x,t.y+r.y,t.z+r.z)}sub(t){return this.subVectors(this,t)}subVectors(t,r){return this.set(t.x-r.x,t.y-r.y,t.z-r.z)}multiplyScalar(t){return this.set(this.x*t,this.y*t,this.z*t)}divideScalar(t){return this.multiplyScalar(t?1/t:0)}setScalar(t){return this.set(t,t,t)}addScaledVector(t,r){return this.set(this.x+t.x*r,this.y+t.y*r,this.z+t.z*r)}length(){return Math.hypot(this.x,this.y,this.z)}normalize(){let t=this.length();return t>1e-5?this.multiplyScalar(1/t):this}cross(t){return this.crossVectors(this,t)}crossVectors(t,r){let i=t.x,n=t.y,a=t.z,s=r.x,o=r.y,l=r.z;return this.set(n*l-a*o,a*s-i*l,i*o-n*s)}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}distanceTo(t){return Math.hypot(this.x-t.x,this.y-t.y,this.z-t.z)}lerp(t,r){return this.lerpVectors(this,t,r)}lerpVectors(t,r,i){return this.x=t.x+(r.x-t.x)*i,this.y=t.y+(r.y-t.y)*i,this.z=t.z+(r.z-t.z)*i,this}applyMatrix4(t){let r=this.x,i=this.y,n=this.z,a=t.elements,s=1/(a[3]*r+a[7]*i+a[11]*n+a[15]);return this.x=(a[0]*r+a[4]*i+a[8]*n+a[12])*s,this.y=(a[1]*r+a[5]*i+a[9]*n+a[13])*s,this.z=(a[2]*r+a[6]*i+a[10]*n+a[14])*s,this}},ks=class{constructor(e=0,t=0,r=0,i=1){this.x=Number(e),this.y=Number(t),this.z=Number(r),this.w=Number(i)}set(e,t,r,i){return this.x=Number(e),this.y=Number(t),this.z=Number(r),this.w=Number(i),this}},si=class Bh{constructor(t=0,r=0,i=0,n="XYZ"){this._onChangeCallback=null,this._x=Number(t),this._y=Number(r),this._z=Number(i),this.order=n}get x(){return this._x}set x(t){this._x=Number(t),this._onChangeCallback?.()}get y(){return this._y}set y(t){this._y=Number(t),this._onChangeCallback?.()}get z(){return this._z}set z(t){this._z=Number(t),this._onChangeCallback?.()}set(t,r,i,n=this.order){return this._x=Number(t),this._y=Number(r),this._z=Number(i),this.order=n,this._onChangeCallback?.(),this}copy(t){return this.set(t.x,t.y,t.z,t.order)}clone(){return new Bh(this._x,this._y,this._z,this.order)}_onChange(t){return this._onChangeCallback=t,this}},no=class zh{constructor(t=0,r=0,i=0,n=1){this._onChangeCallback=null,this._x=Number(t),this._y=Number(r),this._z=Number(i),this._w=Number(n)}get x(){return this._x}set x(t){this._x=Number(t),this._onChangeCallback?.()}get y(){return this._y}set y(t){this._y=Number(t),this._onChangeCallback?.()}get z(){return this._z}set z(t){this._z=Number(t),this._onChangeCallback?.()}get w(){return this._w}set w(t){this._w=Number(t),this._onChangeCallback?.()}set(t,r,i,n){return this._x=Number(t),this._y=Number(r),this._z=Number(i),this._w=Number(n),this._onChangeCallback?.(),this}copy(t){return this.set(t.x,t.y,t.z,t.w)}clone(){return new zh(this._x,this._y,this._z,this._w)}identity(){return this.set(0,0,0,1)}setFromEuler(t,r=!0){let i=t.x,n=t.y,a=t.z,s=Math.cos(i/2),o=Math.cos(n/2),l=Math.cos(a/2),c=Math.sin(i/2),f=Math.sin(n/2),m=Math.sin(a/2);return this._x=c*o*l+s*f*m,this._y=s*f*l-c*o*m,this._z=s*o*m+c*f*l,this._w=s*o*l-c*f*m,r&&this._onChangeCallback?.(),this}setFromAxisAngle(t,r){let i=r/2,n=Math.sin(i);return this.set(t.x*n,t.y*n,t.z*n,Math.cos(i))}normalize(){let t=Math.hypot(this._x,this._y,this._z,this._w);return t===0?this.set(0,0,0,1):this.set(this._x/t,this._y/t,this._z/t,this._w/t)}setFromUnitVectors(t,r){let i=t.dot(r)+1;return i<1e-6?(Math.abs(t.x)>Math.abs(t.z)?this.set(-t.y,t.x,0,0):this.set(0,-t.z,t.y,0)).normalize():this.set(t.y*r.z-t.z*r.y,t.z*r.x-t.x*r.z,t.x*r.y-t.y*r.x,i).normalize()}multiply(t){return this.multiplyQuaternions(this,t)}multiplyQuaternions(t,r){let i=t.x,n=t.y,a=t.z,s=t.w,o=r.x,l=r.y,c=r.z,f=r.w;return this._x=i*f+s*o+n*c-a*l,this._y=n*f+s*l+a*o-i*c,this._z=a*f+s*c+i*l-n*o,this._w=s*f-i*o-n*l-a*c,this._onChangeCallback?.(),this}_onChange(t){return this._onChangeCallback=t,this}},_r=class Vh{constructor(){this.elements=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}identity(){let t=this.elements;return t.fill(0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,this}copy(t){return this.elements.set(t.elements),this}clone(){let t=new Vh;return t.copy(this),t}compose(t,r,i){return or(this.elements,[r.x,r.y,r.z,r.w],[t.x,t.y,t.z],[i.x,i.y,i.z]),this}multiply(t){return this.multiplyMatrices(this,t)}multiplyMatrices(t,r){return at(this.elements,t.elements,r.elements),this}lookAt(t,r,i){return xr(this.elements,[t.x,t.y,t.z],[r.x,r.y,r.z],[i.x,i.y,i.z]),this}makeRotationFromQuaternion(t){let r=new Ze(0,0,0),i=new Ze(1,1,1);return this.compose(r,t,i)}makeTranslation(t,r,i){return this.identity(),this.elements[12]=Number(t),this.elements[13]=Number(r),this.elements[14]=Number(i),this}makeScale(t,r,i){return this.identity(),this.elements[0]=Number(t),this.elements[5]=Number(r),this.elements[10]=Number(i),this}},Rs=class{constructor(){this.elements=new Float32Array([1,0,0,0,1,0,0,0,1])}identity(){let e=this.elements;return e.fill(0),e[0]=1,e[4]=1,e[8]=1,this}getNormalMatrix(e){return Bt(this.elements,e.elements),this}},ln=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,As=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,Zd={black:0,white:16777215,red:16711680,green:32768,lime:65280,blue:255,yellow:16776960,cyan:65535,aqua:65535,magenta:16711935,fuchsia:16711935,gray:8421504,grey:8421504,silver:12632256,orange:16753920,purple:8388736,pink:16761035,gold:16766720},Bn=class Uh{constructor(t,r,i){this.r=1,this.g=1,this.b=1,t!==void 0&&(r!==void 0&&i!==void 0?this.setRGB(t,r,i):this.set(t))}set(t){return typeof t=="number"?this.setHex(t):typeof t=="string"?this.setStyle(t):(t&&typeof t=="object"&&"r"in t&&(this.r=Number(t.r),this.g=Number(t.g),this.b=Number(t.b)),this)}setStyle(t){let r=t.trim().toLowerCase();if(r[0]==="#"){let i=r.slice(1);i.length===3||i.length===4?i=i[0]+i[0]+i[1]+i[1]+i[2]+i[2]:i.length===8&&(i=i.slice(0,6));let n=parseInt(i,16);i.length===6&&!Number.isNaN(n)&&this.setHex(n)}else if(r in Zd)this.setHex(Zd[r]);else if(r.startsWith("hsl")){let i=/^hsla?\(([^)]+)\)$/.exec(r)?.[1].trim().split(/[\s,/]+/);i&&i.length>=3&&this.setHSL((parseFloat(i[0])||0)/360,(parseFloat(i[1])||0)/100,(parseFloat(i[2])||0)/100)}else{let i=/^rgba?\(([^)]+)\)$/.exec(r)?.[1].trim().split(/[\s,/]+/);if(i&&i.length>=3){let n=a=>ln(Math.max(0,Math.min(1,(parseFloat(a)||0)/(a.endsWith("%")?100:255))));this.setRGB(n(i[0]),n(i[1]),n(i[2]))}}return this}setHSL(t,r,i){if(t=((Number(t)||0)%1+1)%1,r=Math.max(0,Math.min(1,Number(r)||0)),i=Math.max(0,Math.min(1,Number(i)||0)),r===0){let o=ln(i);return this.setRGB(o,o,o)}let n=i<=.5?i*(1+r):i+r-i*r,a=2*i-n,s=o=>(o<0&&(o+=1),o>1&&(o-=1),o<1/6?a+(n-a)*6*o:o<1/2?n:o<2/3?a+(n-a)*6*(2/3-o):a);return this.setRGB(ln(s(t+1/3)),ln(s(t)),ln(s(t-1/3)))}lerp(t,r){return this.lerpColors(this,t,r)}lerpColors(t,r,i){let n=Number(i)||0;return this.setRGB(t.r+(r.r-t.r)*n,t.g+(r.g-t.g)*n,t.b+(r.b-t.b)*n)}multiplyScalar(t){let r=Number(t)||0;return this.setRGB(this.r*r,this.g*r,this.b*r)}setScalar(t){let r=Number(t)||0;return this.setRGB(r,r,r)}setHex(t){let r=Math.floor(t);return this.setRGB(ln((r>>16&255)/255),ln((r>>8&255)/255),ln((r&255)/255))}setRGB(t,r,i){return this.r=Number(t),this.g=Number(r),this.b=Number(i),this}convertSRGBToLinear(){return this.setRGB(ln(this.r),ln(this.g),ln(this.b))}convertLinearToSRGB(){return this.setRGB(As(this.r),As(this.g),As(this.b))}getHex(){let t=r=>Math.round(As(Math.max(0,Math.min(1,r)))*255);return t(this.r)<<16|t(this.g)<<8|t(this.b)}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}copy(t){return this.setRGB(t.r,t.g,t.b)}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b}clone(){return new Uh(this.r,this.g,this.b)}},el=1234567,cf={degToRad:e=>e*Math.PI/180,radToDeg:e=>e*180/Math.PI,clamp:(e,t,r)=>Math.max(t,Math.min(r,e)),lerp:(e,t,r)=>e+(t-e)*r,generateUUID:()=>Math.random().toString(36).substring(2,15),randInt:(e,t)=>e+Math.floor(Math.random()*(t-e+1)),randFloat:(e,t)=>e+Math.random()*(t-e),randFloatSpread:e=>e*(.5-Math.random()),seededRandom:e=>{e!==void 0&&(el=Number.isFinite(e)?e|0:0);let t=el=el+1831565813|0;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}},Vt=class Oh{constructor(t,r){if(this.needsUpdate=!1,typeof r!="number"||!Number.isInteger(r)||r<1||r>16)throw new Error(`SecurityError: BufferAttribute itemSize must be an integer in [1, 16]. Received: ${String(r)}`);Array.isArray(t)?this.array=new Float32Array(t):this.array=t,this.itemSize=r;let i=this.array?this.array.length:0;if(!Number.isFinite(i)||i<0)throw new Error(`SecurityError: BufferAttribute array has a non-finite length: ${String(i)}`);this.count=Math.floor(i/r)}getX(t){return this.array[t*this.itemSize]}getY(t){return this.itemSize>=2?this.array[t*this.itemSize+1]:0}getZ(t){return this.itemSize>=3?this.array[t*this.itemSize+2]:0}setX(t,r){return this.array[t*this.itemSize]=r,this.needsUpdate=!0,this}setY(t,r){return this.array[t*this.itemSize+1]=r,this.needsUpdate=!0,this}setZ(t,r){return this.array[t*this.itemSize+2]=r,this.needsUpdate=!0,this}setXYZ(t,r,i,n){let a=t*this.itemSize;return this.array[a]=r,this.array[a+1]=i,this.array[a+2]=n,this.needsUpdate=!0,this}setUsage(t){return this}clone(){let t=this.array?.constructor||Float32Array;return new Oh(new t(this.array),this.itemSize)}},Ls=class extends Vt{constructor(e,t){super(e instanceof Float32Array||Array.isArray(e)?e:new Float32Array(e),t)}},Ps=class extends Vt{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},Is=class extends Vt{constructor(e,t){super(e instanceof Uint32Array?e:new Uint32Array(e),t)}},Nt=class jh{constructor(){this.name="",this.attributes={},this.index=null,this.boundingBox=null}setAttribute(t,r){return this.attributes[t]=r,this}getAttribute(t){return this.attributes[t]}setIndex(t){if(t instanceof Vt)this.index=t;else if(Array.isArray(t)){let r=0;for(let i of t)i>r&&(r=i);this.index=new Vt(new(r>65535?Uint32Array:Uint16Array)(t),1)}else t&&t.buffer&&(this.index=new Vt(t,1));return this}computeVertexNormals(){let t=this.attributes.position;if(!t)return this;let r=!1;if(typeof r=="function"){let l=r(t.array,this.index?.array);return this.setAttribute("normal",new Vt(l,3)),this}let i=t.count,n=t.array,a=new Float32Array(i*3),s=this.index?.array,o=s?s.length:i;for(let l=0;l<o;l+=3){let c=(s?s[l]:l)*3,f=(s?s[l+1]:l+1)*3,m=(s?s[l+2]:l+2)*3,h=n[f],p=n[f+1],g=n[f+2],x=n[m]-h,v=n[m+1]-p,y=n[m+2]-g,A=n[c]-h,b=n[c+1]-p,w=n[c+2]-g,S=v*w-y*b,E=y*A-x*w,N=x*b-v*A;a[c]+=S,a[c+1]+=E,a[c+2]+=N,a[f]+=S,a[f+1]+=E,a[f+2]+=N,a[m]+=S,a[m+1]+=E,a[m+2]+=N}for(let l=0;l<i*3;l+=3){let c=a[l],f=a[l+1],m=a[l+2],h=Math.hypot(c,f,m)||1;a[l]=c/h,a[l+1]=f/h,a[l+2]=m/h}return this.setAttribute("normal",new Vt(a,3)),this}setFromBuffers(t,r,i,n){this.setAttribute("position",new Vt(t,3)),this.setAttribute("normal",new Vt(r,3)),this.setAttribute("uv",new Vt(i,2)),this.setIndex(n)}setFromPoints(t){let r=[];if(Array.isArray(t))for(let i of t)r.push(Number(i?.x)||0,Number(i?.y)||0,Number(i?.z)||0);return this.setAttribute("position",new Vt(r,3))}computeBoundingBox(){let t=this.attributes.position,r=new Ze(1/0,1/0,1/0),i=new Ze(-1/0,-1/0,-1/0);if(t&&t.count>0)for(let n=0;n<t.count;n++){let a=t.getX(n),s=t.getY(n),o=t.getZ(n);a<r.x&&(r.x=a),s<r.y&&(r.y=s),o<r.z&&(r.z=o),a>i.x&&(i.x=a),s>i.y&&(i.y=s),o>i.z&&(i.z=o)}else r.set(0,0,0),i.set(0,0,0);return this.boundingBox={min:r,max:i},this.boundingBox}center(){let t=this.computeBoundingBox();return t.max.x<t.min.x?this:this.translate(-(t.min.x+t.max.x)*.5,-(t.min.y+t.max.y)*.5,-(t.min.z+t.max.z)*.5)}_xform(t,r){let i=this.attributes.position;if(i){let n=i.array;for(let a=0;a<n.length;a+=3)t(n,a);i.needsUpdate=!0,r&&this.computeVertexNormals(),this.computeBoundingBox()}return this}translate(t=0,r=0,i=0){return this._xform((n,a)=>{n[a]+=t,n[a+1]+=r,n[a+2]+=i})}scale(t=1,r=1,i=1){return this._xform((n,a)=>{n[a]*=t,n[a+1]*=r,n[a+2]*=i},!0)}_rot(t,r,i){let n=Math.cos(i),a=Math.sin(i);for(let s of[this.attributes.position,this.attributes.normal]){if(!s)continue;let o=s.array;for(let l=0;l<o.length;l+=3){let c=o[l+t],f=o[l+r];o[l+t]=c*n-f*a,o[l+r]=c*a+f*n}s.needsUpdate=!0}return this}rotateX(t){return this._rot(1,2,t)}rotateY(t){return this._rot(2,0,t)}rotateZ(t){return this._rot(0,1,t)}applyMatrix4(t){let r=this.attributes.position;if(r&&t?.elements){let i=new Ze;for(let n=0;n<r.count;n++)i.set(r.getX(n),r.getY(n),r.getZ(n)).applyMatrix4(t),r.setXYZ(n,i.x,i.y,i.z);this.computeVertexNormals()}return this}clone(){let t=new jh;t.name=this.name;for(let r of Object.keys(this.attributes))t.attributes[r]=this.attributes[r].clone();return this.index&&(t.index=this.index.clone()),t}dispose(){}},ai=class extends Nt{constructor(e=1,t=1,r=1){super();let i=e/2,n=t/2,a=r/2,s=[-i,-n,a,i,-n,a,i,n,a,-i,n,a,i,-n,-a,-i,-n,-a,-i,n,-a,i,n,-a,-i,n,a,i,n,a,i,n,-a,-i,n,-a,-i,-n,-a,i,-n,-a,i,-n,a,-i,-n,a,i,-n,a,i,-n,-a,i,n,-a,i,n,a,-i,-n,-a,-i,-n,a,-i,n,a,-i,n,-a],o=[],l=[],c=[];for(let f=0;f<6;f++){let m=f*4,h=2-(f>>1),p=f&1?-1:1;for(let g=0;g<4;g++)o.push(h===0?p:0,h===1?p:0,h===2?p:0);l.push(0,0,1,0,1,1,0,1),c.push(m,m+1,m+2,m,m+2,m+3)}this.setFromBuffers(s,o,l,c)}},Cs=class extends Nt{constructor(e=1,t=1,r=1,i=1){super(),r=Math.max(1,Math.floor(r)),i=Math.max(1,Math.floor(i));let n=[],a=[],s=[],o=[];for(let l=0;l<=i;l++){let c=l/i;for(let f=0;f<=r;f++){let m=f/r;if(n.push((m-.5)*e,(.5-c)*t,0),a.push(0,0,1),s.push(m,1-c),l>0&&f>0){let h=(r+1)*l+f-1,p=h-(r+1);o.push(p,h,p+1,h,h+1,p+1)}}}this.setFromBuffers(n,a,s,o)}},Ns=class extends Nt{constructor(e=1,t=16,r=12,i=0,n=Math.PI*2,a=0,s=Math.PI){super(),t=Math.max(3,Math.floor(t)),r=Math.max(2,Math.floor(r));let o=[],l=[],c=[],f=[],m=Math.min(a+s,Math.PI);for(let h=0;h<=r;h++){let p=h/r,g=a+p*s;for(let x=0;x<=t;x++){let v=x/t,y=i+v*n,A=-Math.cos(y)*Math.sin(g),b=Math.cos(g),w=Math.sin(y)*Math.sin(g);if(o.push(e*A,e*b,e*w),l.push(A,b,w),c.push(v,1-p),h>0&&x>0){let S=(t+1)*h+x,E=S-(t+1),N=E-1,C=S-1;(h!==1||a>0)&&f.push(E,N,S),(h!==r||m<Math.PI)&&f.push(N,C,S)}}}this.setFromBuffers(o,l,c,f)}},ci=class extends Nt{constructor(e=1,t=1,r=1,i=16,n=1,a=!1,s=0,o=Math.PI*2){super(),i=Math.max(3,Math.floor(i)),n=Math.max(1,Math.floor(Number(n)||1));let l=[],c=[],f=[],m=[],h=r/2,p=(t-e)/(r||1),g=i+1;for(let v=0;v<=n;v++){let y=v/n,A=y*(t-e)+e,b=h-y*r;for(let w=0;w<=i;w++){let S=w/i,E=s+S*o,N=Math.sin(E),C=Math.cos(E),_=Math.hypot(N,p,C)||1;if(l.push(A*N,b,A*C),c.push(N/_,p/_,C/_),f.push(S,1-y),v<n&&w<i){let P=v*g+w,R=P+g;m.push(P,R,P+1,R,R+1,P+1)}}}let x=(v,y)=>{if(a||v<=0)return;let A=y*h,b=l.length/3;l.push(0,A,0),c.push(0,y,0),f.push(.5,.5);let w=b+1;for(let S=0;S<=i;S++){let E=s+S/i*o,N=Math.sin(E),C=Math.cos(E);l.push(v*N,A,v*C),c.push(0,y,0),f.push(C*.5+.5,.5+y*N*.5),S<i&&m.push(b,w+S+(y>0?0:1),w+S+(y>0?1:0))}};x(e,1),x(t,-1),this.setFromBuffers(l,c,f,m)}},Ds=class extends ci{constructor(e=1,t=1,r=16,i=1,n=!1,a=0,s=Math.PI*2){super(0,e,t,r,i,n,a,s)}},Us=class extends Nt{constructor(e=1,t=.4,r=12,i=48,n=Math.PI*2){super(),r=Math.max(3,Math.floor(r)),i=Math.max(3,Math.floor(i));let a=[],s=[],o=[],l=[];for(let c=0;c<=r;c++){let f=c/r*Math.PI*2,m=Math.cos(f),h=Math.sin(f);for(let p=0;p<=i;p++){let g=p/i*n,x=Math.cos(g),v=Math.sin(g);if(a.push((e+t*m)*x,(e+t*m)*v,t*h),s.push(m*x,m*v,h),o.push(p/i,c/r),c>0&&p>0){let y=(i+1)*c+p-1,A=y-(i+1);l.push(y,A,y+1,A,A+1,y+1)}}}this.setFromBuffers(a,s,o,l)}};function lf(e,t,r,i,n){let a=Math.max(2,Math.min(256,Math.floor(Number(t)||64))),s=Math.max(3,Math.min(64,Math.floor(Number(r)||8))),o=Number(i)||.1,l=[],c=[],f=[],m=[],h=[],p=new Ze,g=new Ze,x=new Ze;for(let y=0;y<=a;y++){let A=new Ze;n(y/a,A),h.push(A)}let v=s+1;for(let y=0;y<=a;y++){let A=y/a,b=h[y];p.subVectors(h[Math.min(a,y+1)],h[Math.max(0,y-1)]).normalize(),y===0&&g.set(Math.abs(p.y)>.9?1:0,Math.abs(p.y)>.9?0:1,0),x.crossVectors(p,g).normalize(),g.crossVectors(x,p).normalize();for(let w=0;w<=s;w++){let S=w/s*Math.PI*2,E=-Math.cos(S),N=Math.sin(S),C=E*g.x+N*x.x,_=E*g.y+N*x.y,P=E*g.z+N*x.z;if(l.push(b.x+o*C,b.y+o*_,b.z+o*P),c.push(C,_,P),f.push(A,w/s),y>0&&w>0){let R=v*(y-1)+w-1,$=R+v;m.push(R,$,R+1,$,$+1,R+1)}}}e.setFromBuffers(l,c,f,m)}var Bs=class extends Nt{constructor(e=1,t=.4,r=64,i=8,n=2,a=3){super(),r=Math.floor(r),i=Math.floor(i),lf(this,r,i,t,(s,o)=>{let l=s*n*Math.PI*2,c=a/n*l,f=e*(2+Math.cos(c))*.5;o.set(f*Math.cos(l),f*Math.sin(l),e*Math.sin(c)*.5)})}},ar=class{getPoint(e,t=new Ze){return t}getPointAt(e,t=new Ze){return this.getPoint(e,t)}getTangent(e,t=new Ze){return t.subVectors(this.getPoint(Math.min(1,e+.001)),this.getPoint(Math.max(0,e-.001))).normalize()}getPoints(e=5){let t=Math.max(1,Math.min(512,Math.floor(Number(e)||5))),r=[];for(let i=0;i<=t;i++)r.push(this.getPoint(i/t));return r}getSpacedPoints(e=5){return this.getPoints(e)}},Fs=class extends ar{constructor(e=new Ze,t=new Ze){super(),this.v1=e,this.v2=t}getPoint(e,t=new Ze){return t.lerpVectors(this.v1,this.v2,e)}},Vs=class extends ar{constructor(e=new Ze,t=new Ze,r=new Ze){super(),this.v0=e,this.v1=t,this.v2=r}getPoint(e,t=new Ze){return t.lerpVectors(this.v0,this.v1,e).lerp(new Ze().lerpVectors(this.v1,this.v2,e),e)}},Os=class extends ar{constructor(e=new Ze,t=new Ze,r=new Ze,i=new Ze){super(),this.v0=e,this.v1=t,this.v2=r,this.v3=i}getPoint(e,t=new Ze){let r=new Ze().lerpVectors(this.v0,this.v1,e),i=new Ze().lerpVectors(this.v1,this.v2,e),n=new Ze().lerpVectors(this.v2,this.v3,e);return t.lerpVectors(r.lerp(i,e),i.lerp(n,e),e)}},zs=class extends ar{constructor(e=[],t=!1){super(),this.points=Array.isArray(e)?e:[],this.closed=!!t}getPoint(e,t=new Ze){let r=this.points,i=r.length;if(!i)return t.set(0,0,0);if(i===1)return t.copy(r[0]);let n=(this.closed?i:i-1)*Math.max(0,Math.min(1,Number(e)||0)),a=Math.floor(n),s=n-a;!this.closed&&a>=i-1&&(a=i-2,s=1);let o=x=>r[this.closed?(x%i+i)%i:Math.max(0,Math.min(i-1,x))],l=o(a-1),c=o(a),f=o(a+1),m=o(a+2),h=s*s,p=h*s,g=(x,v,y,A)=>.5*(2*v+(y-x)*s+(2*x-5*v+4*y-A)*h+(3*v-x-3*y+A)*p);return t.set(g(l.x,c.x,f.x,m.x),g(l.y,c.y,f.y,m.y),g(l.z,c.z,f.z,m.z))}},li=class extends Nt{constructor(e=[new tn(0,-.5),new tn(.5,0),new tn(0,.5)],t=12,r=0,i=Math.PI*2){super();let n=Array.isArray(e)&&e.length>=2?e:[new tn(.2,0),new tn(.2,.5)],a=Math.max(3,Math.min(128,Math.floor(Number(t)||12))),s=[],o=[],l=[],c=[],f=n.length;for(let m=0;m<=a;m++){let h=m/a,p=r+h*i,g=Math.sin(p),x=Math.cos(p),v=m*f;for(let y=0;y<f;y++){let A=n[y],b=Number(A?.x)||0,w=Number(A?.y)||0;s.push(b*g,w,b*x);let S=n[Math.max(0,y-1)],E=n[Math.min(f-1,y+1)],N=(Number(E?.x)||0)-(Number(S?.x)||0),C=(Number(E?.y)||0)-(Number(S?.y)||0),_=Math.hypot(C,N)||1;if(o.push(C/_*g,-N/_,C/_*x),l.push(h,y/(f-1)),m<a&&y<f-1){let P=v+y,R=P+f;c.push(P,R,P+1,R,R+1,P+1)}}}this.setFromBuffers(s,o,l,c)}},$s=class extends Nt{constructor(e,t=64,r=1,i=8,n=!1){super(),lf(this,t,i,r,(a,s)=>{let o=e?.getPointAt??e?.getPoint;if(typeof o=="function"){let l=o.call(e,a,s);l&&l!==s&&s.copy(l)}else s.set(0,a,0)})}},Ts="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ro=class{constructor(e=""){this.isTexture=!0,this.wrapS=10497,this.wrapT=10497,this.repeat=new tn(1,1),this.offset=new tn(0,0),this.image=null,this.width=0,this.height=0,this.source=e,e&&typeof e=="object"&&(this.image=e)}dispose(){}},Gs=class extends ro{constructor(e=null,t=1,r=1,i=1023,n=1009,a,s=1001,o=1001,l=1003,c=1003,f=1,m=""){super(""),this.isDataTexture=!0,this.avgColor=[1,1,1,1],this.flipY=!1,this.generateMipmaps=!1,this.unpackAlignment=1,this._sig=0;let h=Number(t),p=Number(r),g=e&&typeof e.length=="number"?e:null;this.width=h,this.height=p,this.image={data:g,width:h,height:p},this.format=Number(i)||1023,this.type=Number(n)||1009,this.wrapS=Number(s)||1001,this.wrapT=Number(o)||1001,this.magFilter=Number(l)||1003,this.minFilter=Number(c)||1003,this.colorSpace=m||"",this._bake()}get needsUpdate(){return!1}set needsUpdate(e){e&&this._bake()}_bake(){let e=this.image,t=e?.data,r=Number(e?.width??this.width),i=Number(e?.height??this.height);if(!t||!t.length||!(r>0&&i>0)||r>2048||i>2048){this.source="";return}let n=Math.max(1,r|0),a=Math.max(1,i|0),s=n*a,o=this.format,l=o===1021||o===1024||o===1028||t.length===s?1:o===1025||o===1030||t.length===s*2?2:o===1022||t.length===s*3?3:4,c=this.type===1015||this.type===1016||t instanceof Float32Array||t instanceof Float64Array,f=Math.min(n,64),m=Math.min(a,64),h=(this.flipY?257:1)^this.colorSpace.length^t.length,p=Math.max(1,t.length>>6|0);for(let $=0;$<t.length;$+=p)h=Math.imul(h^(t[$]*256|0),16777619)|0;if(h===this._sig&&this.source)return;this._sig=h;let g=m*(1+f*4),x=new Uint8Array(68+g),v=new DataView(x.buffer);v.setUint32(0,2303741511),v.setUint32(4,218765834),v.setUint32(8,13),v.setUint32(12,1229472850),v.setUint32(16,f),v.setUint32(20,m),x[24]=8,x[25]=6,v.setUint32(29,Yo(x.subarray(12,29))),v.setUint32(33,g+11),v.setUint32(37,1229209940),x[41]=120,x[42]=1,x[43]=1,v.setUint16(44,g,!0),v.setUint16(46,~g&65535,!0);let y=48,A=1,b=0,w=0,S=0,E=0,N=0,C=$=>{if(!Number.isFinite($))return 0;let F=c&&$<=1?$*255:$;return F>0?F<255?F+.5|0:255:0};for(let $=0;$<m;$++){let F=$*a/m|0,V=this.flipY?a-1-F:F;x[y++]=0,b+=A;for(let Y=0;Y<f;Y++){let J=(V*n+(Y*n/f|0))*l,re=o===1021?255:C(t[J]??0),Q=l>=3||o===1030?C(t[J+1]??0):re,ee=l>=3?C(t[J+2]??0):o===1030?0:re,k=l===4?C(t[J+3]??255):o===1021?C(t[J]??255):o===1025?C(t[J+1]??255):255;x[y++]=re,A+=re,b+=A,x[y++]=Q,A+=Q,b+=A,x[y++]=ee,A+=ee,b+=A,x[y++]=k,A+=k,b+=A,w+=re,S+=Q,E+=ee,N+=k}A%=65521,b%=65521}v.setUint32(y,(b<<16|A)>>>0),v.setUint32(y+4,Yo(x.subarray(37,y+4))),v.setUint32(y+12,1229278788),v.setUint32(y+16,2923585666);let _=f*m*255,P=this.colorSpace==="srgb-linear";this.avgColor=[P?w/_:ln(w/_),P?S/_:ln(S/_),P?E/_:ln(E/_),N/_];let R=["data:image/png;base64,"];for(let $=0;$<x.length;$+=3){let F=x[$]<<16|(x[$+1]??0)<<8|(x[$+2]??0);R.push(Ts[F>>18&63]+Ts[F>>12&63]+($+1<x.length?Ts[F>>6&63]:"=")+($+2<x.length?Ts[F&63]:"="))}this.source=R.join("")}},js=class{load(e,t){let r=new ro(e);return t?.(r),r}};function Ft(e,t){return e!==void 0?Number(e):t}function tl(e,t){return e!==void 0?!!e:t}var vn=class{constructor(e={}){this.name=e.name||"",this.color=new Bn(e.color??16777215),this._em=e.emissive!==void 0,this.emissive=new Bn(e.emissive??0),this.emissiveIntensity=Ft(e.emissiveIntensity,1),this.roughness=Ft(e.roughness,e.roughnessMap?1:.5),this.metalness=Ft(e.metalness,e.metalnessMap?1:0),this.opacity=Ft(e.opacity,1),this.transparent=tl(e.transparent,!1),this.wireframe=tl(e.wireframe,!1),this.side=Ft(e.side,2),this.doubleSided=tl(e.doubleSided,!0),this.map=e.map||null,this.normalMap=e.normalMap||null;let t=e.normalScale;this.normalScale=typeof t=="number"?new tn(t,t):new tn(Ft(t?.x,1),Ft(t?.y,1)),this.roughnessMap=e.roughnessMap||null,this.metalnessMap=e.metalnessMap||null,this.emissiveMap=e.emissiveMap||null,this.aoMap=e.aoMap||null,this.aoMapIntensity=Ft(e.aoMapIntensity,1),this.bumpMap=e.bumpMap||null,this.bumpScale=Ft(e.bumpScale,1),this.clearcoat=Ft(e.clearcoat,0),this.clearcoatRoughness=Ft(e.clearcoatRoughness,0),this.sheen=Ft(e.sheen,0),this.sheenColor=new Bn(e.sheenColor??0),this.sheenRoughness=Ft(e.sheenRoughness,0),this.transmission=Ft(e.transmission,0),this.thickness=Ft(e.thickness,0),this.attenuationColor=new Bn(e.attenuationColor??16777215),this.attenuationDistance=Ft(e.attenuationDistance,1/0),this.ior=Ft(e.ior,1.5),this.dispersion=Ft(e.dispersion,0),this.iridescence=Ft(e.iridescence,0),this.iridescenceIOR=Ft(e.iridescenceIOR,1.3)}dispose(){}},Fr=class extends vn{},Hs=class extends vn{},Ws=class extends vn{},Xs=class extends vn{},qs=class extends vn{},Fn=class Gh{constructor(){this.name="",this.matrixAutoUpdate=!0,this.visible=!0,this._castShd=!1,this._castShdSet=!1,this._recvShd=!1,this._recvShdSet=!1,this.parent=null,this.children=[],this.userData={},this.position=new Ze,this.rotation=new si,this.quaternion=new no,this.scale=new Ze(1,1,1),this.matrix=new _r,this.matrixWorld=new _r,this.rotation._onChange(()=>{this.quaternion.setFromEuler(this.rotation,!1)}),this.quaternion._onChange(()=>{let t=this.quaternion,r=Math.atan2(2*(t.w*t.x+t.y*t.z),1-2*(t.x*t.x+t.y*t.y)),i=Math.asin(Math.max(-1,Math.min(1,2*(t.w*t.y-t.z*t.x)))),n=Math.atan2(2*(t.w*t.z+t.x*t.y),1-2*(t.y*t.y+t.z*t.z));this.rotation.set(r,i,n)})}get castShadow(){return this._castShd}set castShadow(t){this._castShd=!!t,this._castShdSet=!0}get receiveShadow(){return this._recvShd}set receiveShadow(t){this._recvShd=!!t,this._recvShdSet=!0}add(...t){for(let r of t)r&&r instanceof Gh&&(r.parent&&r.parent.remove(r),r.parent=this,this.children.push(r));return this}remove(...t){for(let r of t){let i=this.children.indexOf(r);i!==-1&&(r.parent=null,this.children.splice(i,1))}return this}traverse(t){let r=new Set,i=[this];for(;i.length>0;){let n=i.pop();if(!n||typeof n!="object"||r.has(n))continue;r.add(n),t(n);let a=n.children;if(Array.isArray(a))for(let s=a.length-1;s>=0;s--)i.push(a[s])}}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale)}updateMatrixWorld(t=!1){this.traverse(r=>{uf(r),(r.matrixAutoUpdate||t)&&r.updateMatrix?.(),r.parent&&r.parent.matrixWorld?r.matrixWorld?.multiplyMatrices(r.parent.matrixWorld,r.matrix):r.matrix&&r.matrixWorld?.copy(r.matrix)})}lookAt(t,r,i){let n=typeof t=="object"?t:new Ze(t,r,i);this.target instanceof Ze?this.target.copy(n):this.target?.position instanceof Ze&&this.target.position.copy(n),this.updateMatrixWorld(!0);let a=new _r;a.lookAt(this.position,n,new Ze(0,1,0));let s=a.elements,o=s[0],l=s[4],c=s[8],f=s[1],m=s[5],h=s[9],p=s[2],g=s[6],x=s[10],v=o+m+x;if(v>0){let y=.5/Math.sqrt(v+1);this.quaternion.set((g-h)*y,(c-p)*y,(f-l)*y,.25/y)}}translateOnAxis(t,r){let i=t.clone().applyMatrix4(new _r().makeRotationFromQuaternion(this.quaternion)).multiplyScalar(r);return this.position.add(i),this}translateX(t){return this.translateOnAxis(new Ze(1,0,0),t)}translateY(t){return this.translateOnAxis(new Ze(0,1,0),t)}translateZ(t){return this.translateOnAxis(new Ze(0,0,1),t)}rotateX(t){return this.rotation.x+=t,this}rotateY(t){return this.rotation.y+=t,this}rotateZ(t){return this.rotation.z+=t,this}_chain(){let t=[];for(let r=this;r&&t.length<64;r=r.parent)t.push(r);return t}_syncWorld(){let t=this._chain();for(let r=t.length-1;r>=0;r--){let i=t[r];i.updateMatrix?.(),i.parent?.matrixWorld?i.matrixWorld.multiplyMatrices(i.parent.matrixWorld,i.matrix):i.matrixWorld?.copy(i.matrix)}return this.matrixWorld.elements}getWorldPosition(t=new Ze){let r=this._syncWorld();return t.set(r[12],r[13],r[14])}getWorldScale(t=new Ze){let r=this._syncWorld();return t.set(Math.hypot(r[0],r[1],r[2]),Math.hypot(r[4],r[5],r[6]),Math.hypot(r[8],r[9],r[10]))}getWorldDirection(t=new Ze){let r=this._syncWorld();return t.set(r[8],r[9],r[10]).normalize()}getWorldQuaternion(t=new no){let r=this._chain();t.set(0,0,0,1);for(let i=r.length-1;i>=0;i--)t.multiply(r[i].quaternion);return t}clone(t=!0){let r=typeof this._cloneCustom=="function"?this._cloneCustom():this instanceof kr?new this.constructor(this._sourceGeo||this.geometry,this.material):this instanceof qn?new qn(this.geometry,this.material):new this.constructor;if(this instanceof cr){r.color.copy(this.color),r.intensity=this.intensity,r.shadow.copy(this.shadow);let i=this.target;i?.position&&r.target?.position&&r.target.position.copy(i.position),this instanceof vi&&r.groundColor.copy(this.groundColor)}r.name=this.name,r.position.copy(this.position),r.quaternion.copy(this.quaternion),r.scale.copy(this.scale),r.visible=this.visible,this._castShdSet&&(r.castShadow=this.castShadow),this._recvShdSet&&(r.receiveShadow=this.receiveShadow);try{r.userData=JSON.parse(JSON.stringify(this.userData||{}))}catch{r.userData={...this.userData||{}}}if(t)for(let i of this.children)r.add(i.clone(!0));return r}},Ys=class extends Fn{},qn=class extends Fn{constructor(e,t){super(),this.isMesh=!0;let r=Array.isArray(t)?t[0]:t;this.geometry=e instanceof Nt?e:e?(Er("unsupported geometry","BoxGeometry"),new ai(.5,.5,.5)):new Nt,this.material=r instanceof vn?r:r?(Er("unsupported material","MeshStandardMaterial"),new Fr({color:13421772})):new Fr}};function uf(e){typeof e?._bakeAuthorGeometry=="function"&&e._bakeAuthorGeometry();let t=He().materializeDeclarativeGeometry;typeof t=="function"&&t(e)}var ui=1e4,di=class extends qn{constructor(e,t,r=1){super(e,t),this.instanceColor=null,this.isInstancedMesh=!0;let i=Number(r);if(!Number.isFinite(i)||i<0||i>ui)throw new RangeError(`SecurityError: InstancedMesh count (${String(r)}) exceeds MAX_INSTANCES_PER_MESH (${ui})`);this.count=Math.floor(i);let n=new Float32Array(this.count*16);for(let a=0;a<this.count;a++){let s=a*16;n[s]=1,n[s+5]=1,n[s+10]=1,n[s+15]=1}this.instanceMatrix=new Vt(n,16)}setMatrixAt(e,t){let r=Math.floor(Number(e));if(!Number.isFinite(r)||r<0||r>=this.count||!t||!t.elements)return;let i=this.instanceMatrix.array,n=r*16;if(!(n+16>i.length))for(let a=0;a<16;a++){let s=Number(t.elements[a]);i[n+a]=Number.isFinite(s)?s:a%5===0?1:0}}getMatrixAt(e,t){let r=Math.floor(Number(e));if(!Number.isFinite(r)||r<0||r>=this.count||!t||!t.elements)return;let i=this.instanceMatrix.array,n=r*16;if(!(n+16>i.length))for(let a=0;a<16;a++)t.elements[a]=i[n+a]}setColorAt(e,t){let r=Math.floor(Number(e));if(!Number.isFinite(r)||r<0||r>=this.count||!t)return;if(!this.instanceColor||this.instanceColor.array.length<this.count*3){let a=new Float32Array(this.count*3);a.fill(1),this.instanceColor=new Vt(a,3)}let i=this.instanceColor.array,n=r*3;i[n]=Number.isFinite(t.r)?t.r:1,i[n+1]=Number.isFinite(t.g)?t.g:1,i[n+2]=Number.isFinite(t.b)?t.b:1}getColorAt(e,t){let r=Math.floor(Number(e));if(!Number.isFinite(r)||r<0||r>=this.count||!t)return;if(!this.instanceColor||this.instanceColor.array.length<(r+1)*3){t.setRGB(1,1,1);return}let i=this.instanceColor.array,n=r*3;t.setRGB(i[n],i[n+1],i[n+2])}dispose(){}},fi=class Hh{constructor(){this.mapSize=new tn(1024,1024),this.bias=-5e-4,this.normalBias=.015,this.radius=1.5,this.camera={near:.1,far:100,left:-5,right:5,top:5,bottom:-5,fov:50,updateProjectionMatrix:()=>{}}}copy(t){return this.mapSize.copy(t.mapSize),this.bias=Number(t.bias),this.normalBias=Number(t.normalBias),this.radius=Number(t.radius),this}clone(){return new Hh().copy(this)}},cr=class extends Fn{constructor(e=16777215,t=1){super(),this.isLight=!0,this.shadow=new fi,this.color=new Bn(e),this.intensity=Number(t),this.type="directional"}},mi=class extends cr{constructor(e,t){super(e,t),this.type="ambient"}},Ks=class extends cr{constructor(e,t){super(e,t),this.target=new Fn,this.type="directional"}},hi=class extends cr{constructor(e,t,r=0,i=2){super(e,t),this.type="point",this.distance=r,this.decay=i}},pi=class extends Fn{},Js=class extends pi{constructor(e=45,t=1,r=.1,i=1e3){super(),this.target=new Ze(0,0,0),this.fov=Number(e),this.aspect=Number(t),this.near=Number(r),this.far=Number(i)}},bi=class extends Fn{constructor(){super(...arguments),this.background=null,this.environmentIntensity=1}toCanvas3D(){return Xn.validate(this),Qr(this)}toGLB(){return Xn.validate(this),qo(this)}toUSDZ(){return Xn.validate(this),Ko(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let e=new Map,t=0;return this.traverse(r=>{if(r instanceof qn){let i=new Float32Array(r.matrixWorld.elements);e.set(t,i),r.name&&e.set(r.name,i),t++}}),e}},nl=Qr,rl=qo,df=Ko;He().makePngDeflater=zc;var Xn=class{static validate(e){let t=0,r=0,i=0,n=new Set,a=(o,l,c)=>{throw new Error(`SecurityError: Scene exceeds SECURITY_3D_MAX_${o} (${l}). Found: ${c}`)},s=(o,l)=>{if(!Number.isFinite(l))throw new Error(`SecurityError: Scene reports a non-finite ${o} count (${String(l)}), which cannot be bounds-checked.`);return l};e.traverse(o=>{if(uf(o),o instanceof qn||o.geometry?.attributes?.position?.count){if(i++,i>1e3&&a("MESHES",1e3,i),o instanceof di){let c=s("instance",o.count);(c<0||c>ui)&&a("INSTANCES",ui,c)}let l=o.geometry;if(l){let c=0;if(l.attributes.position&&(c=s("vertex",l.attributes.position.count),t+=c,t>1e5&&a("VERTICES",1e5,t)),l.index){let f=s("index",l.index.count);r+=f,r>3e5&&a("INDICES",3e5,r);let m=l.index.array;if(m&&c>0){let h=Math.min(f,m.length);for(let p=0;p<h;p++){let g=m[p];if(!Number.isFinite(g)||g<0||g>=c)throw new Error(`SecurityError: Index buffer value (${String(g)}) out of vertex bounds [0, ${c}).`)}}}}if(o.material){let c=o.material;for(let f of["map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap","bumpMap"])c[f]&&n.add(c[f])}}}),n.size>16&&a("TEXTURES",16,n.size);for(let o of n){let l=o,c=l.image,f=Number(c?.width??l.width??0)||0,m=Number(c?.height??l.height??0)||0;(!Number.isFinite(f)||!Number.isFinite(m)||f>2048||m>2048)&&a("TEXTURE_DIMENSION",2048,Math.max(f,m))}}},Qs=class{constructor(e={}){this.shadowMap={enabled:!1,type:0},this.capabilities={isWebGL2:!0,maxTextures:16},this.boundViewer=null,this.hasInitialModelRendered=!1,this.domElement=e.canvas||(typeof document<"u"?document.createElement("canvas"):{}),e.viewer&&(this.boundViewer=e.viewer),e.container?.threeLiveViewer&&(this.boundViewer=e.container.threeLiveViewer),e.canvas?.parentElement?.threeLiveViewer&&(this.boundViewer=e.canvas.parentElement.threeLiveViewer);let t=typeof WorkerGlobalScope<"u"&&typeof self<"u"&&self instanceof WorkerGlobalScope;this.isSandboxed=e.isSandboxed||t,this.containerId=e.containerId||""}setSize(e,t){return this}setPixelRatio(e){return this}setClearColor(e,t=1){let r=new Bn(e);return this.boundViewer&&typeof this.boundViewer.setClearColor=="function"&&this.boundViewer.setClearColor(r.r,r.g,r.b,t),this}clear(){return this}dispose(){}render(e,t){if(this.isSandboxed){Xn.validate(e);let i=(n,a)=>{typeof self<"u"&&typeof self.postMessage=="function"&&(a&&a.length?self.postMessage(n,a):self.postMessage(n))};if(this.hasInitialModelRendered){let n=e.getMeshTransforms(),a={};for(let[s,o]of n.entries())a[s]=Array.from(o);i({type:"3D_UPDATE_TRANSFORMS",containerId:this.containerId,transforms:a})}else{this.hasInitialModelRendered=!0;let n=nl(e),a=rl(e),s=(n.lights||[]).map(o=>({type:o.type,color:o.color,intensity:o.intensity,position:o.position}));i({type:"3D_MODEL_READY",containerId:this.containerId,glbBuffer:a.buffer,dynamicLights:s,camera:t?{fov:t.fov||60,position:[t.position.x,t.position.y,t.position.z]}:void 0},[a.buffer])}return}let r=this.boundViewer;!r&&this.domElement?.parentElement&&this.domElement.parentElement.threeLiveViewer&&(r=this.domElement.parentElement.threeLiveViewer,this.boundViewer=r),!r&&typeof window<"u"&&(r=window.__three_live_active_viewer__,this.boundViewer=r),r&&typeof r.loadModel=="function"&&(r._hasThreeLiveModelLoaded?typeof r.updateMeshTransforms=="function"&&r.updateMeshTransforms(e.getMeshTransforms()):(r.loadModel(e.toCanvas3D()),r._hasThreeLiveModelLoaded=!0))}};function ef(){return typeof globalThis<"u"&&typeof globalThis.__three_live_sim_time_ms__=="number"?globalThis.__three_live_sim_time_ms__:typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Zs=class{constructor(e=!0){this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1,this.autoStart=e,e&&this.start()}start(){this.startTime=ef(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running&&this.start(),this.running){let t=ef();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function Yp(){}var oi=new Proxy(Yp,{get:(e,t)=>{if(t==="isProxy")return!0;if(!(t==="constructor"||t==="__proto__"||t==="prototype"))return t==="domElement"?typeof document<"u"?document.createElement("canvas"):{}:t==="shadowMap"?{enabled:!1,type:0}:t==="capabilities"?{isWebGL2:!0,maxTextures:16}:t===Symbol.toPrimitive?()=>0:oi},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>oi,construct:()=>oi}),tf=(()=>{try{if(typeof document>"u")return null;let e=document.currentScript;return e?.src?e.src:e?.textContent&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(new Blob([e.textContent],{type:"text/javascript"})):null}catch{return null}})();function pa(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function oo(e,t){if(!e||typeof e!="string")return!1;let r=e.trim();if(!r)return!1;try{let i=new URL(r,pa());return!(i.protocol!=="https:"&&i.protocol!=="http:"&&i.protocol!=="blob:"||t?.requireSameOrigin&&i.protocol!=="blob:"&&typeof location<"u"&&location.origin&&location.origin!=="null"&&i.origin!==location.origin)}catch{return!1}}var nf,ri;function ff(e){if(!oo(e))throw new Error(`SecurityError: Refusing to create TrustedScriptURL for disallowed URL "${e}".`);let t=globalThis.trustedTypes;if(!t||typeof t.createPolicy!="function")return e;if(ri===void 0||nf!==t){nf=t;try{ri=t.createPolicy("three-live#worker",{createScriptURL:r=>{if(!oo(r))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${r}".`);return r}})}catch{ri=null}}return ri?ri.createScriptURL(e):e}function Kp(e){He().sandboxEngineSrc=e}function ol(){let e=He().sandboxEngineSrc;if(e)return e;if(tf)return tf;try{if(typeof document>"u")return null;let t=pa(),r=Array.from(document.querySelectorAll("script[src]"));for(let i of r){let n=i.src;if(!n)continue;let a=new URL(n,t).pathname;if(/(?:^|\/)(?:three|xr)-live[^/]*\.js$/.test(a)&&oo(n,{requireSameOrigin:!0}))return n}}catch{}return null}function il(e,t){if(!oo(e))throw new Error(`SecurityError: Disallowed ${t} URL "${e}" (http:, https:, or blob: required).`);return new URL(e,pa()).href}function Jp(){let e=ol();if(!e)throw new Error("SecurityError: Could not locate Three-Live bundle URL for worker sandbox; set ThreeLiveElement.sandboxEngineSrc explicitly.");return il(e,"sandbox engine")}function Qp(e){He().sandboxIframeSrc=e}function mf(){let e=He().sandboxIframeSrc;if(e)return e;let t=ol();if(!t||!oo(t))return null;let r=new URL(t,pa());return r.protocol==="blob:"?null:new URL("three-live-sandbox.html",r).href}function Zp(){let e=mf();if(!e)throw new Error("SecurityError: Could not locate three-live-sandbox.html; set ThreeLiveElement.sandboxIframeSrc explicitly.");return il(e,"sandbox iframe")}function e0(e){He().allowClientScripts=e}function hf(){return!!He().allowClientScripts}function t0(e){return il(e,"procedural scene script")}var n0="fetch XMLHttpRequest WebSocket WebSocketStream WebTransport EventSource importScripts Request Response Headers navigator WorkerNavigator WorkerLocation RTCPeerConnection RTCDataChannel FontFace FontFaceSet fonts PerformanceObserver ReportingObserver indexedDB IDBFactory caches CacheStorage Cache cookieStore StorageManager FileSystemHandle Worker SharedWorker ServiceWorker ServiceWorkerContainer ServiceWorkerRegistration registration clients BroadcastChannel MessageChannel MessagePort createImageBitmap OffscreenCanvas WebAssembly WorkerGlobalScope DedicatedWorkerGlobalScope trustedTypes TrustedTypePolicyFactory SharedArrayBuffer Atomics".split(" ");function r0(e,t,r){let i=self,n=e.nonce,a=e.engineSrc,s=e.allowedScriptUrl,o=e.allowClientScripts,l=e.revoked,c=i.postMessage.bind(i),f=null;try{f=r?r(i.CompressionStream):null}catch{}let m=null;function h(N,C){let _=()=>C&&C.length?c(N,C):c(N);m?m=m.then(_,_):_()}function p(N){h({type:"ERROR",nonce:n,message:String(N)})}let g=typeof i.importScripts=="function"?i.importScripts.bind(i):null,x=s,v=null;try{let N=a;if(typeof i.trustedTypes<"u"&&i.trustedTypes&&typeof i.trustedTypes.createPolicy=="function")try{let C={createScriptURL:function(P){if(P!==a&&(!s||P!==s))throw new TypeError("Disallowed worker importScripts URL");return P}};o&&(C.createScript=function(P){return String(P)});let _=i.trustedTypes.createPolicy("three-live#worker-boot",C);N=_.createScriptURL(a),s&&(x=_.createScriptURL(s)),o&&typeof _.createScript=="function"&&(v=_.createScript.bind(_))}catch{}g(N)}catch(N){p('Sandbox failed to load "'+a+'" (must be an IIFE bundle like three-live.min.js): '+(N&&N.message||N));return}let y=i.THREE;if(!y||typeof y.Scene!="function"){p('Sandbox "'+a+'" did not install THREE; point sandboxEngineSrc at three-live.min.js.');return}if(Array.isArray(t)){let N=i.__THREE_LIVE_REGISTRY__;for(let C=0;C<t.length;C++)if(typeof t[C]=="function")try{t[C](y,N)}catch{}}function A(N,C,_){let P=i;for(;P&&P!==Object.prototype;){if(!_&&P!==i)try{delete P[N]}catch{}if(!_||P===i||Object.prototype.hasOwnProperty.call(P,N))try{Object.defineProperty(P,N,_?{value:C,writable:!1,configurable:!1}:{value:C,writable:!1,configurable:!1,enumerable:!1})}catch{}try{P=Object.getPrototypeOf(P)}catch{break}}}for(let N=0;N<l.length;N++)A(l[N],void 0);A("performance",Object.freeze({now:function(){return Date.now()}}));let b=["3D_MODEL_READY","3D_UPDATE_TRANSFORMS"],w=!1;function S(N,C){if(N.type==="3D_MODEL_READY"){if(w)return;w=!0}if(N.nonce=n,N.type==="3D_MODEL_READY"&&f&&N.glbBuffer instanceof ArrayBuffer){let _=N.glbBuffer;m=(m||Promise.resolve()).then(()=>f.glb(new Uint8Array(_))).then(P=>{P.buffer!==_&&(N.glbBuffer=P.byteOffset===0&&P.byteLength===P.buffer.byteLength?P.buffer:P.slice().buffer),c(N,[N.glbBuffer])},()=>c(N,[_]));return}C&&C.length?h(N,C):h(N)}A("postMessage",function(N,C){if(!N||b.indexOf(N.type)===-1)throw new Error("Sandboxed scripts may only post Three-Live scene messages ("+b.join(", ")+").");S(N,C)},!0);let E=!1;i.onmessage=function(N){let C=N&&N.data;if(!C||C.nonce!==n||C.type!=="EXECUTE"&&C.type!=="EXECUTE_URL"||E)return;E=!0;let _=C.texturePack;if(_&&typeof _=="object"){let P=Object.create(null),R=0;for(let $ of Object.keys(_)){let F=_[$],V=F&&F.size;R<64&&/^[0-9a-f]{16}$/.test($)&&(V===256||V===512||V===1024)&&F.rgba instanceof Uint8Array&&F.rgba.length===V*V*4&&(P[$]=Object.freeze({size:V,rgba:F.rgba}),R++)}i.__three_live_texture_pack__=Object.freeze(P)}try{let P=new y.Scene,R=new y.PerspectiveCamera(60,1,.1,1e3),$=new y.WebGLRenderer({isSandboxed:!0});if(C.type==="EXECUTE_URL"){if(!s||C.scriptUrl!==s||typeof g!="function"){p("SecurityError: Refusing to execute unapproved script URL inside sandbox worker.");return}let F=x||s,V=g;if(g=null,x=null,i.THREE=y,i.scene=P,i.camera=R,i.renderer=$,V(F),typeof i.__THREE_LIVE_SCENE__=="function"){let Y=i.__THREE_LIVE_SCENE__(y,P,R,$);Y&&typeof Y.toGLB=="function"&&(P=Y)}else i.scene&&typeof i.scene.toGLB=="function"&&(P=i.scene)}else{if(!o){p("SecurityError: Client-modified script compilation (Use Case 1) is disabled in this sandbox worker.");return}let F=v?(0,eval)(v(`(function (THREE, scene, camera, renderer) {
|
|
370
393
|
return (function () {
|
|
371
|
-
`+
|
|
394
|
+
`+C.script+`
|
|
372
395
|
;
|
|
373
396
|
return typeof scene === "object" && scene ? scene : undefined;
|
|
374
397
|
})();
|
|
375
398
|
})`)):new Function("THREE","scene","camera","renderer",`return (function () {
|
|
376
|
-
`+
|
|
399
|
+
`+C.script+`
|
|
377
400
|
;
|
|
378
401
|
return typeof scene === "object" && scene ? scene : undefined;
|
|
379
|
-
})();`);c=null;let T=W(d,M,P,F);T&&typeof T.toGLB=="function"&&(M=T)}if(!x){d.SceneQuotaValidator&&d.SceneQuotaValidator.validate(M);let W=M.toGLB(),T=W instanceof ArrayBuffer?W:W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength);b({type:"3D_MODEL_READY",glbBuffer:T},[T])}a({type:"DONE",nonce:i})}catch(M){u(M&&M.message||M)}}},a({type:"READY",nonce:i})}function Wi(e,t,r){let i=r?.allowedScriptUrl??null,n=r?.allowClientScripts??i===null,s={nonce:t,engineSrc:e,allowedScriptUrl:i,allowClientScripts:n,revoked:Sc},l=(Ae().workerExtensionInstallers??[]).map(o=>`(${o.toString()})`).join(",");return`'use strict';(${Ec.toString()})(${JSON.stringify(s)},[${l}]);`}function ks(e){e.onError?.(new Error("SecurityError: Sandboxed script exceeded SECURITY_3D_SANDBOX_TIMEOUT_MS (3000 ms) and was terminated.")),e.onToast?.("Security Error: script timed out and was stopped.")}var Dt=0;function Os(){try{let e=new Uint32Array(4);return globalThis.crypto?.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(8,"0")).join("")}catch{return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}}function Rc(e){try{return new TextEncoder().encode(e).length}catch{return e.length}}var _c=1024,Lc=256;function ws(e){if(!Array.isArray(e)&&!(e instanceof Float32Array)||e.length!==16)return!1;for(let t=0;t<16;t++){let r=e[t];if(typeof r!="number"||!Number.isFinite(r))return!1}return!0}function ji(e,t){if(!e||typeof e!="object")return null;let r=e;if(r.nonce!==t)return null;switch(r.type){case"READY":return{type:"READY"};case"DONE":return{type:"DONE"};case"ERROR":return{type:"ERROR",message:(typeof r.message=="string"?r.message:String(r.message??"Unknown worker error")).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").slice(0,_c)};case"3D_UPDATE_TRANSFORMS":{let i=r.transforms;if(Array.isArray(i)){if(i.length>1e3)return null;for(let n of i)if(!ws(n))return null;return{type:"3D_UPDATE_TRANSFORMS",transforms:i}}if(i&&typeof i=="object"){let n=Object.keys(i);if(n.length>1e3)return null;let s=Object.create(null),l=i;for(let o of n){if(o.length>Lc||o==="__proto__"||o==="constructor"||o==="prototype")return null;let a=l[o];if(!ws(a))return null;s[o]=a}return{type:"3D_UPDATE_TRANSFORMS",transforms:s}}return null}case"3D_MODEL_READY":{let i=r.glbBuffer;return!(i instanceof ArrayBuffer)||i.byteLength>16777216?null:{type:"3D_MODEL_READY",payload:i}}default:return null}}function Ic(e){let t=Rc(e);if(t>1048576)throw new Error(`SecurityError: Script length (${t} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function Us(e,t,r,i){switch(e.type){case"READY":return;case"3D_UPDATE_TRANSFORMS":t.onUpdateTransforms?.(e.transforms);return;case"3D_MODEL_READY":if(i.modelDispatched)return;i.modelDispatched=!0,t.onModelReady(e.payload);return;case"DONE":r();return;case"ERROR":r(),t.onError?.(new Error(`Worker script error: ${e.message}`));return;default:return e}}function Cc(e,t,r,i){let n=Os(),s=Wi(t,n,e.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:e.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),l=document.createElement("iframe");l.setAttribute("sandbox","allow-scripts"),l.setAttribute("aria-hidden","true"),l.tabIndex=-1,l.style.display="none",l.src=r,Dt++;let o=!1,a=!1,u={modelDispatched:!1},h,m=()=>{if(o||a)return;let g=l.contentWindow;!g||typeof g.postMessage!="function"||(a=!0,g.postMessage(e.kind==="url"?{type:"SANDBOX_RUN",nonce:n,workerSource:s,scriptUrl:e.scriptUrl}:{type:"SANDBOX_RUN",nonce:n,workerSource:s,script:e.script},"*"))},c=()=>{},d=g=>{if(o||!l.contentWindow||g.source!==l.contentWindow)return;let x=g.data;if(x&&typeof x=="object"&&x.type==="IFRAME_READY"){m();return}let b=ji(x,n);b&&Us(b,i,c,u)};c=()=>{o||(o=!0,h!==void 0&&clearTimeout(h),Dt=Math.max(0,Dt-1),typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("message",d),typeof l.remove=="function"?l.remove():l.parentNode&&l.parentNode.removeChild(l))},h=setTimeout(()=>{o||(c(),ks(i))},3e3),typeof globalThis.addEventListener=="function"&&globalThis.addEventListener("message",d),l.onload=()=>{m()},l.onerror=()=>{c(),i.onError?.(new Error(`Sandbox iframe failed to load "${r}". Verify that three-live-sandbox.html is served at that URL.`))};let f=document.body||document.documentElement;if(!f||typeof f.appendChild!="function"){c();let g=new Error("SecurityError: Cannot mount sandbox iframe because document.body is unavailable.");throw i.onError?.(g),g}return f.appendChild(l),{terminate:c}}function Ss(e,t,r,i){if(t==="worker"&&typeof Worker>"u")return i("Sandboxed procedural execution requires Web Workers, but Workers are unavailable in this environment. For host security, Three-Live prohibits unsandboxed in-process evaluation.","Security Error: Web Workers unavailable. Script execution aborted.");if(t==="iframe"&&(typeof document>"u"||typeof document.createElement!="function"))return i("Sandboxed iframe execution requires a DOM environment with document.createElement. Refusing to evaluate in the host realm.","Security Error: DOM unavailable for iframe sandbox.");if(Dt>=32)return i(`SecurityError: ${Dt} sandbox workers are already running, which meets SECURITY_3D_MAX_CONCURRENT_TASKS (32). Refusing to start another.`,"Security Error: too many concurrent sandboxed scripts.");let n;try{n=vc()}catch(c){let d=c instanceof Error?c.message:String(c);return i(d,"Security Error: sandbox engine URL is not configured.")}if(t==="iframe"){let c;try{c=Tc()}catch(d){let f=d instanceof Error?d.message:String(d);return i(f,"Security Error: sandbox iframe URL is not configured.")}try{return Promise.resolve(Cc(e,n,c,r))}catch(d){return Promise.reject(d)}}let s=Os(),l=Wi(n,s,e.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:e.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),o;try{let c=new Blob([l],{type:"application/javascript"}),d=URL.createObjectURL(c);try{let f=Ds(d);o=new Worker(f)}finally{URL.revokeObjectURL(d)}}catch(c){let d=c instanceof Error?c.message:String(c);return i(`Failed to initialize Web Worker for sandboxed execution (CSP may block blob workers): ${d}`,"Security Error: Failed to start Worker sandbox.")}Dt++;let a=!1,u={modelDispatched:!1},h,m=()=>{a||(a=!0,h!==void 0&&clearTimeout(h),Dt=Math.max(0,Dt-1),o.terminate())};return h=setTimeout(()=>{a||(m(),ks(r))},3e3),o.onmessage=c=>{let d=ji(c.data,s);d&&Us(d,r,m,u)},o.onerror=c=>{m(),r.onError?.(new Error(`Worker execution error: ${c.message}`))},e.kind==="url"?o.postMessage({type:"EXECUTE_URL",scriptUrl:e.scriptUrl,nonce:s}):o.postMessage({type:"EXECUTE",script:e.script,nonce:s}),Promise.resolve({terminate:m})}function Es(e,t){return e==="none"||e==="unsafe-host-realm"?t(`SecurityError: sandbox="${e}" is prohibited. Sandboxing is mandatory for live compilation and cannot be bypassed. Use sandbox="worker" (default) or sandbox="iframe".`,`Security Error: sandbox="${e}" is not permitted.`):e!=="worker"&&e!=="iframe"?t(`SecurityError: Unsupported sandbox mode "${e}". Live compilation requires sandbox="worker" or sandbox="iframe".`,"Security Error: unsupported sandbox mode."):null}var Rs=e=>(t,r)=>{let i=new Error(t);return e.onError?.(i),r&&e.onToast?.(r),Promise.reject(i)},ln={execute(e,t,r,i){let n=Rs(r),s=Es(t,n);if(s)return s;try{Ic(e)}catch(l){let o=l instanceof Error?l.message:String(l);return n(o,"Security Error: script exceeds the size limit.")}return i?.allowClientScripts??Ns()?Ss({kind:"script",script:e},t,r,n):n(Qn,Jn)},executeUrl(e,t,r){let i=Rs(r),n=Es(t,i);if(n)return n;let s;try{s=wc(e)}catch(l){let o=l instanceof Error?l.message:String(l);return i(o,"Security Error: disallowed scene script URL.")}return Ss({kind:"url",scriptUrl:s},t,r,i)}},Xr=new Set;function Gt(e,t){let r=`[three-live] ${e} is unsupported; degraded to ${t}.`;Xr.has(r)||(Xr.add(r),typeof console<"u"&&typeof console.warn=="function"&&console.warn(r))}function Fs(){return Array.from(Xr)}function Vs(){Xr.clear()}var Bn=class extends Bt{constructor(e={}){Gt("ShaderMaterial","MeshStandardMaterial");let t=e.uniforms||{},r=t.color?.value??t.uColor?.value??t.diffuse?.value??e.color;super({color:r!==void 0?r:8421504,opacity:t.opacity?.value??e.opacity??1,transparent:!!e.transparent,wireframe:!!e.wireframe,side:e.side}),this.uniforms=t}},Bs=Bn,Et=class extends Be{constructor(e=[],t=[],r=1,i=0){super();let n=Number(r)||1,s=Math.max(0,Math.min(7,Math.floor(Number(i)||0))),l=s+1,o=[],a=[],u=[],h=[],m=new ge,c=new ge,d=new ge,f=(b,v)=>v.set(e[b*3]||0,e[b*3+1]||0,e[b*3+2]||0),g=(b,v)=>{let p=b.clone().normalize();o.push(p.x*n,p.y*n,p.z*n),a.push(v.x,v.y,v.z),u.push(Math.atan2(p.z,-p.x)/(2*Math.PI)+.5,1-Math.acos(Math.max(-1,Math.min(1,p.y)))/Math.PI)},x=(b,v,p)=>{let y=o.length/3,M=s===0?new ge().subVectors(p,v).cross(new ge().subVectors(b,v)).normalize():null;g(b,M||b.clone().normalize()),g(v,M||v.clone().normalize()),g(p,M||p.clone().normalize()),h.push(y,y+1,y+2)};for(let b=0;b<t.length;b+=3){f(t[b],m),f(t[b+1],c),f(t[b+2],d);let v=[];for(let p=0;p<=l;p++){v[p]=[];let y=m.clone().lerp(d,p/l),M=c.clone().lerp(d,p/l),P=l-p;for(let F=0;F<=P;F++)v[p][F]=P===0?y.clone():y.clone().lerp(M,F/P)}for(let p=0;p<l;p++)for(let y=0;y<2*(l-p)-1;y++){let M=y>>1;(y&1)===0?x(v[p][M+1],v[p+1][M],v[p][M]):x(v[p][M+1],v[p+1][M+1],v[p+1][M])}}this.setFromBuffers(o,a,u,h)}},Dc=Et,$r=class extends Et{constructor(e=1,t=0){super([1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],e,t)}},br=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],zs=[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],Wr=class extends Et{constructor(e=1,t=0){super(br,zs,e,t)}},Ne=(1+Math.sqrt(5))/2,jr=class extends Et{constructor(e=1,t=0){super([-1,Ne,0,1,Ne,0,-1,-Ne,0,1,-Ne,0,0,-1,Ne,0,1,Ne,0,-1,-Ne,0,1,-Ne,Ne,0,-1,Ne,0,1,-Ne,0,-1,-Ne,0,1],[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],e,t)}},nt=1/Ne,Kr=class extends Et{constructor(e=1,t=0){super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-nt,-Ne,0,-nt,Ne,0,nt,-Ne,0,nt,Ne,-nt,-Ne,0,-nt,Ne,0,nt,-Ne,0,nt,Ne,0,-Ne,0,-nt,Ne,0,-nt,-Ne,0,nt,Ne,0,nt],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],e,t)}},qr=class extends Pn{constructor(e=1,t=1,r=4,i=8){let n=Math.max(1e-4,Number(e)||1),s=Math.max(0,Number.isFinite(Number(t))?Number(t):1)*.5,l=Math.max(2,Math.min(64,Math.floor(Number(r)||4))),o=[];for(let a=-1;a<=1;a+=2)for(let u=0;u<=l;u++){if(a>0&&u===0&&s===0)continue;let h=(a<0?u/l-1:u/l)*(Math.PI/2);o.push(new rt(Math.max(0,Math.cos(h)*n),a*s+Math.sin(h)*n))}super(o,Math.max(4,Math.min(128,Math.floor(Number(i)||8))))}},zn=class extends Be{constructor(e=.5,t=1,r=32,i=1,n=0,s=Math.PI*2){super();let l=Math.max(1e-4,Number(t)||1),o=Number(e),a=Number.isFinite(o)?Math.max(0,o):l*.5,u=Math.max(l,a),h=Math.min(u*.999,Math.min(l,a)),m=Math.max(3,Math.min(256,Math.floor(Number(r)||32))),c=Math.max(1,Math.min(64,Math.floor(Number(i)||1))),d=Number.isFinite(Number(n))?Number(n):0,f=Number.isFinite(Number(s))?Number(s):Math.PI*2,g=[],x=[],b=[],v=[];for(let p=0;p<=c;p++){let y=h+p/c*(u-h);for(let M=0;M<=m;M++){let P=d+M/m*f,F=Math.cos(P),W=Math.sin(P);if(g.push(y*F,y*W,0),x.push(0,0,1),b.push(y/u*F*.5+.5,y/u*W*.5+.5),p<c&&M<m){let T=p*(m+1)+M,E=T+m+1;y>1e-6&&v.push(T,E,T+1),v.push(E,E+1,T+1)}}}this.setFromBuffers(g,x,b,v)}},Yr=class extends zn{constructor(e=1,t=32,r=0,i=Math.PI*2){super(0,e,t,1,r,i)}},Gn=class extends et{constructor(e={}){super({roughness:.35,metalness:.1,side:2,...e});let t=Number(e.size);this.size=Number.isFinite(t)?Math.max(.002,Math.min(2,t)):.05,this.sizeAttenuation=e.sizeAttenuation!==!1,e.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.35)}},un=class extends et{constructor(e={}){super({roughness:.4,metalness:.1,side:2,...e});let t=Number(e.linewidth);this.linewidth=Number.isFinite(t)?Math.max(.5,Math.min(20,t)):1,e.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.3)}},Zr=class extends un{constructor(e={}){super(e),this.dashSize=Number(e.dashSize)||3,this.gapSize=Number(e.gapSize)||1,this.scale=Number(e.scale)||1}};function Gs(e,t){let r=e?.attributes?.position;if(!r?.array||r.count<3)return new Float32Array(0);let i=r.array,n=e?.index?.array,s=Math.min(8192,Math.floor((n?n.length:r.count)/3)),l=c=>`${Math.round((i[c*3]||0)*1e4)},${Math.round((i[c*3+1]||0)*1e4)},${Math.round((i[c*3+2]||0)*1e4)}`,o=t===void 0,a=o?1:Math.cos(t*Math.PI/180),u={},h=[],m=(c,d)=>h.push(i[c*3]||0,i[c*3+1]||0,i[c*3+2]||0,i[d*3]||0,i[d*3+1]||0,i[d*3+2]||0);for(let c=0;c<s;c++){let d=n?n[c*3]:c*3,f=n?n[c*3+1]:c*3+1,g=n?n[c*3+2]:c*3+2,x=i[d*3]||0,b=i[d*3+1]||0,v=i[d*3+2]||0,p=(i[f*3]||0)-x,y=(i[f*3+1]||0)-b,M=(i[f*3+2]||0)-v,P=(i[g*3]||0)-x,F=(i[g*3+1]||0)-b,W=(i[g*3+2]||0)-v,T=y*W-M*F,E=M*P-p*W,S=p*F-y*P,O=Math.hypot(T,E,S);if(!o&&O<1e-8)continue;O>0&&(T/=O,E/=O,S/=O);let k=[d,f,g];for(let w=0;w<3;w++){let ie=k[w],oe=k[(w+1)%3],I=l(ie),H=l(oe);if(I===H)continue;let N=I<H?`${I}|${H}`:`${H}|${I}`,z=u[N];z?z.m||(z.m=1,z.nx*T+z.ny*E+z.nz*S<=a&&m(ie,oe)):(u[N]={va:ie,vb:oe,nx:T,ny:E,nz:S,m:o?1:0},o&&m(ie,oe))}}if(!o){let c=Object.keys(u);for(let d=0;d<c.length;d++){let f=u[c[d]];f&&!f.m&&m(f.va,f.vb)}}return new Float32Array(h)}var Qr=class extends Be{constructor(e){super(),this.setAttribute("position",new $e(Gs(e),3)),this.__isSegmentPairs=!0}},Jr=class extends Be{constructor(e,t=1){super();let r=Number.isFinite(Number(t))?Number(t):1;this.setAttribute("position",new $e(Gs(e,r),3)),this.__isSegmentPairs=!0}};function Pc(e,t,r=1){let i=new Be;i.__baked=!0;let n=e?.attributes?.position;if(!n?.array||n.count<2)return i;let s=n.array,l=e.index?.array,o=e.__isSegmentPairs?"segments":t,a=l?l.length:n.count,u=Math.min(4096,Math.max(0,o==="segments"?Math.floor(a/2):o==="loop"&&a>=3?a:a-1));if(u===0)return i;e.computeBoundingBox();let h=e.boundingBox,m=h&&h.max.distanceTo(h.min)||1,c=Math.max(.0015,Math.min(.025,m*.003))*(.5+.5*Math.max(.5,Math.min(6,Number(r)||1))),d=[],f=[],g=[],x=[];for(let b=0;b<u;b++){let v=o==="segments"?b*2:b,p=o==="segments"?b*2+1:(b+1)%a,y=l?l[v]:v,M=l?l[p]:p,P=s[y*3]||0,F=s[y*3+1]||0,W=s[y*3+2]||0,T=(s[M*3]||0)-P,E=(s[M*3+1]||0)-F,S=(s[M*3+2]||0)-W,O=Math.hypot(T,E,S);if(O<1e-6)continue;let k=T/O,w=E/O,ie=S/O,oe=(Math.abs(w)<.9?Math.hypot(ie,k):Math.hypot(ie,w))||1,I=Math.abs(w)<.9?ie/oe:0,H=Math.abs(w)<.9?0:-ie/oe,N=Math.abs(w)<.9?-k/oe:w/oe,z=w*N-ie*H,ue=ie*I-k*N,ce=k*H-w*I,B=d.length/3,$=[[I,H,N],[z,ue,ce],[-I,-H,-N],[-z,-ue,-ce]];for(let _=0;_<2;_++){let G=P+_*T,j=F+_*E,q=W+_*S;for(let D=0;D<4;D++){let Y=$[D];d.push(G+Y[0]*c,j+Y[1]*c,q+Y[2]*c),f.push(Y[0],Y[1],Y[2]),g.push(D/4,_)}}for(let _=0;_<4;_++){let G=(_+1)%4;x.push(B+_,B+G,B+4+G,B+_,B+4+G,B+4+_)}}return d.length>0&&i.setFromBuffers(d,f,g,x),i}function Nc(e,t=.05){let r=new Be;r.__baked=!0;let i=e?.attributes?.position;if(!i?.array||i.count<1)return r;let n=i.array,s=i.count,l=Math.min(s,5e3),o=Math.max(.003,Math.min(.25,(Number(t)||.05)*.6)),a=[],u=[],h=[],m=[];for(let c=0;c<l;c++){let d=s<=5e3?c:Math.floor(c*s/l),f=n[d*3]||0,g=n[d*3+1]||0,x=n[d*3+2]||0,b=c*6;for(let v=0;v<6;v++){let p=br[v*3],y=br[v*3+1],M=br[v*3+2];a.push(f+p*o,g+y*o,x+M*o),u.push(p,y,M),h.push(.5,.5)}for(let v=0;v<24;v++)m.push(b+zs[v])}return r.setFromBuffers(a,u,h,m),r}var Nt=class extends gt{constructor(e,t,r="strip"){let i=t&&typeof t=="object"?t:{},n=t instanceof et?t:r==="points"?new Gn(i):new un(i),s=e instanceof Be?e:new Be;super(s,n),this.isLine=!0,this._lineMode=r,this._sourceGeo=s}computeLineDistances(){return this}_bakeAuthorGeometry(){this.geometry&&!this.geometry.__baked&&(this._sourceGeo=this.geometry);let e=this._lineMode==="points";if(e){let t=this._sourceGeo?.attributes?.color;if(t?.array&&t.count>0&&this.material?.color.r===1&&this.material.color.g===1&&this.material.color.b===1){let r=t.array,i=Math.min(t.count,64),n=0,s=0,l=0;for(let o=0;o<i;o++)n+=r[o*3]||0,s+=r[o*3+1]||0,l+=r[o*3+2]||0;this.material.color.setRGB(n/i,s/i,l/i)}}!this.geometry?.__baked&&this._sourceGeo?.attributes?.position?.count>=(e?1:2)&&(this.geometry=e?Nc(this._sourceGeo,this.material?.size??.05):Pc(this._sourceGeo,this._lineMode,this.material?.linewidth??1))}},ei=class extends Nt{constructor(e,t){super(e,t,"loop"),this.isLineLoop=!0}},ti=class extends Nt{constructor(e,t){super(e,t,"segments"),this.isLineSegments=!0}},ni=class extends Nt{constructor(e,t){super(e,t,"points"),this.isPoints=!0}},ri=class extends Un{constructor(e,t,r=0,i=Math.PI/3,n=0,s=2){super(e,t,r,s),this.target=new lt,this.type="spot";let l=Number(i);this.angle=Number.isFinite(l)?Math.max(.01,Math.min(Math.PI/2,l)):Math.PI/3;let o=Number(n);this.penumbra=Number.isFinite(o)?Math.max(0,Math.min(1,o)):0}},Hn=class extends On{constructor(e,t,r){Gt("HemisphereLight","AmbientLight"),super(e,r),this.groundColor=new ut(t??4473924)}},Hs=Hn,Xs={Vector2:rt,Vector3:ge,Vector4:gr,Euler:In,Quaternion:sn,Matrix4:Pt,Matrix3:xr,Color:ut,MathUtils:_s,BufferAttribute:$e,Float32BufferAttribute:vr,Uint16BufferAttribute:Mr,Uint32BufferAttribute:Tr,BufferGeometry:Be,BoxGeometry:Cn,PlaneGeometry:Ar,SphereGeometry:wr,CylinderGeometry:Dn,ConeGeometry:Sr,TorusGeometry:Er,TorusKnotGeometry:Rr,Curve:St,Curve3:St,LineCurve3:_r,QuadraticBezierCurve3:Lr,CubicBezierCurve3:Ir,CatmullRomCurve3:Cr,LatheGeometry:Pn,TubeGeometry:Dr,PolyhedronGeometry:Et,IcosahedronGeometry:jr,OctahedronGeometry:Wr,DodecahedronGeometry:Kr,TetrahedronGeometry:$r,CapsuleGeometry:qr,RingGeometry:zn,CircleGeometry:Yr,WireframeGeometry:Qr,EdgesGeometry:Jr,FrontSide:0,BackSide:1,DoubleSide:2,NoBlending:0,NormalBlending:1,AdditiveBlending:2,MultiplyBlending:4,RepeatWrapping:1e3,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002,NearestFilter:1003,NearestMipmapNearestFilter:1004,NearestMipmapLinearFilter:1005,LinearFilter:1006,LinearMipmapNearestFilter:1007,LinearMipmapLinearFilter:1008,UnsignedByteType:1009,ByteType:1010,ShortType:1011,UnsignedShortType:1012,IntType:1013,UnsignedIntType:1014,FloatType:1015,HalfFloatType:1016,AlphaFormat:1021,RGBFormat:1022,RGBAFormat:1023,LuminanceFormat:1024,LuminanceAlphaFormat:1025,RedFormat:1028,RGFormat:1030,NoColorSpace:"",SRGBColorSpace:"srgb",LinearSRGBColorSpace:"srgb-linear",StaticDrawUsage:35044,DynamicDrawUsage:35048,ACESFilmicToneMapping:4,PCFSoftShadowMap:2,Texture:an,DataTexture:Pr,TextureLoader:Nr,Material:et,MeshStandardMaterial:Bt,MeshBasicMaterial:kr,MeshLambertMaterial:Or,MeshPhongMaterial:Ur,MeshPhysicalMaterial:Fr,PointsMaterial:Gn,LineBasicMaterial:un,LineDashedMaterial:Zr,ShaderMaterial:Bn,RawShaderMaterial:Bs,Object3D:lt,Group:Vr,Mesh:gt,InstancedMesh:kn,Line:Nt,LineLoop:ei,LineSegments:ti,Points:ni,Light:zt,AmbientLight:On,DirectionalLight:Br,PointLight:Un,SpotLight:ri,HemisphereLight:Hn,RectAreaLight:Hs,Camera:Fn,PerspectiveCamera:zr,Scene:Vn,WebGLRenderer:Gr,Clock:Hr,SceneQuotaValidator:yt,exportSceneToCanvas3D:Gi,exportSceneToGLB:Hi,exportSceneToUSDZ:Cs,generateUSDZ:En,glbToUSDZ:Sn,sceneToCanvas3D:rn,sceneToGLB:Tn,sceneToUSDZ:wn,authorScriptRunner:ln,getAuthorWarnings:Fs,clearAuthorWarnings:Vs};Object.freeze(yt),Object.freeze(yt.prototype),Object.freeze(Vn.prototype),Object.freeze(Xs);var Ht=new Proxy(Xs,{get:(e,t)=>{if(t in e)return e[t];let r=Ae().authorNamespace;return r&&typeof t=="string"&&t in r?r[t]:(typeof t=="string"&&t!=="then"&&t!=="toJSON"&&!t.startsWith("__")&&Gt(`THREE.${t}`,"no-op proxy"),_n)},has:(e,t)=>{if(t in e)return!0;let r=Ae().authorNamespace;return!!(r&&typeof t=="string"&&t in r)},set:(e,t)=>{throw new TypeError(`Cannot assign to read only property '${String(t)}' of #<THREE>`)},defineProperty:(e,t)=>{throw new TypeError(`Cannot define property '${String(t)}', object is not extensible`)},deleteProperty:(e,t)=>{throw new TypeError(`Cannot delete property '${String(t)}' of #<THREE>`)},setPrototypeOf:()=>{throw new TypeError("#<THREE> is not extensible")}}),yr=Ae();if(yr.threeNamespace=Ht,yr.workerExtensionInstallers)for(let e of yr.workerExtensionInstallers)e(Ht,yr);var Ln={name:"three_author",THREE:Ht},kc=Ln,wt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;if(typeof wt.THREE>"u"&&(wt.THREE=Ht),typeof wt.requestAnimationFrame!="function"&&(wt.requestAnimationFrame=e=>(typeof e=="function"&&typeof wt.__three_live_raf_cb__!="function"&&(wt.__three_live_raf_cb__=e),wt.__three_live_in_step__||Gt("requestAnimationFrame","single-frame static evaluation"),0)),typeof wt.cancelAnimationFrame!="function"&&(wt.cancelAnimationFrame=()=>{}),typeof window<"u"){let e=window;e.ThreeLive=e.ThreeLive||{},e.ThreeLive.THREE=Ht,e.ThreeLivePlugins=e.ThreeLivePlugins||{},e.ThreeLivePlugins.threeAuthor=Ln,e.ThreeLivePlugins.three_author=Ln,e.ThreeLivePlugins["three-author"]=Ln}function mn(e,t){let r=e?.trim(),i=r?Number(r):NaN;return Number.isFinite(i)?i:t}var Ki=(e,t,r)=>({x:e,y:t,z:r,toString:()=>`${e}m ${t}m ${r}m`}),Oc=typeof HTMLElement<"u"?HTMLElement:class{};typeof CustomEvent>"u"&&typeof Event<"u"&&(globalThis.CustomEvent=class extends Event{constructor(e,t){super(e,t),this.detail=t?.detail??null}});var ze=class Ge extends Oc{constructor(){super(...arguments),this.viewer=null,this.canvas=null,this.posterEl=null,this.arButton=null,this.currentModel=null,this.activeXRSession=null,this.toastTimer=null,this.currentModelLimits=void 0,this.isModelLoaded=!1,this.scriptHandle=null,this.loadController=null,this.resizeObserver=null,this.mutationObserver=null}static get arProvider(){return Ae().arProvider}static set arProvider(t){Ae().arProvider=t}static get scriptRunner(){return Ae().scriptRunner}static set scriptRunner(t){Ae().scriptRunner=t}static get sandboxEngineSrc(){return Ae().sandboxEngineSrc??null}static set sandboxEngineSrc(t){Ae().sandboxEngineSrc=t}static get sandboxIframeSrc(){return Ae().sandboxIframeSrc??null}static set sandboxIframeSrc(t){Ae().sandboxIframeSrc=t}static get allowClientScripts(){return!!Ae().allowClientScripts}static set allowClientScripts(t){Ae().allowClientScripts=t}static registerScriptRunner(t){Ge.scriptRunner=t}static defineModelViewer(t="model-viewer"){if(typeof customElements>"u")return!1;let r=customElements.get(t);if(r!=null)return r===Ge||r.prototype instanceof Ge;class i extends Ge{}return customElements.define(t,i),!0}static registerDecoder(t,r){Ke.registerDecoder(t,r)}static getDecoder(t){return Ke.getDecoder(t)}static registerAR(t){typeof t=="function"?Ge.arProvider={activateAR:t}:Ge.arProvider=t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(r=>{r instanceof Ge&&r.updateARButtonVisibility()})}static isARSupported(){return!!Ge.arProvider}getLoadedModel(){return this.currentModel}beginLoad(){let t=this.loadController,r=this.scriptHandle,i=new AbortController;return this.loadController=i,this.scriptHandle=null,t?.abort(),r?.terminate(),i}connectedCallback(){if(typeof document>"u")return;(!this.style.display||this.style.display==="inline")&&(this.style.display="block"),getComputedStyle(this).position==="static"&&(this.style.position="relative"),this.style.overflow="hidden",this.setupDOM(),this.initViewer(),this.setupResizeObserver();let t=this.getAttribute("src"),r=this.getAttribute("script-src");if(t)this.loadModel(t).catch(()=>{});else if(r)this.loadScriptFromSrc(r).catch(()=>{});else{let i=this.querySelector('script[type="text/three"], script[type="text/three-live"]');i&&i.textContent&&this.executeScript(i.textContent).catch(()=>{})}for(let i of Ke.getRegisteredPlugins())i.onElementConnected?.(this)}disconnectedCallback(){for(let t of Ke.getRegisteredPlugins())t.onElementDisconnected?.(this);this.beginLoad().abort(),this.mutationObserver?.disconnect(),this.mutationObserver=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.activeXRSession?.stop?.().catch?.(()=>{}),this.activeXRSession=null,this.toastTimer&&clearTimeout(this.toastTimer),this.toastTimer=null,this.viewer?.destroy(),this.viewer=null,this.isModelLoaded=!1}attributeChangedCallback(t,r,i){if(r!==i){switch(t){case"src":i&&this.loadModel(i).catch(()=>{});break;case"camera-target":this.applyCameraTarget(i);break;case"min-camera-orbit":case"max-camera-orbit":this.applyOrbitLimits();break;case"field-of-view":this.applyFieldOfView(i);break;case"script-src":i&&this.loadScriptFromSrc(i).catch(()=>{});break;case"sandbox":case"allow-client-scripts":case"ios-src":break;case"poster":this.updatePoster(i);break;case"camera-orbit":this.applyCameraOrbit(i);break;case"selected-mesh":this.viewer&&i!==null&&this.viewer.setSelectedMesh(i);break;case"exposure":if(this.viewer&&i!==null){let n=parseFloat(i);isNaN(n)||this.viewer.setExposure(n)}break;case"shadow-intensity":case"shadow-softness":this.viewer&&this.viewer.setShadow(this.shadowIntensity,this.shadowSoftness);break;case"tone-mapping":this.viewer?.setToneMapping(Vt(i));break;case"environment-image":this.viewer&&this.viewer.setEnvironmentImage(i).catch(()=>{});break;case"skybox-image":this.viewer&&this.viewer.setSkyboxImage?.(i)?.catch?.(()=>{});break;case"camera-controls":{let n=this.cameraControls;this.viewer&&this.viewer.setInteractive?.(n),this.canvas&&(this.canvas.style.touchAction=n?"none":"auto");break}case"autoplay":this.viewer&&this.viewer.setAutoplay(i!==null&&i!=="false");break;case"animation-name":this.viewer&&i!==null&&this.viewer.setAnimationName(i);break;case"variant-name":this.viewer&&this.selectVariant(i);break;case"auto-rotate":this.viewer&&this.viewer.setAutoRotate(i!==null&&i!=="false");break;case"auto-rotate-delay":this.viewer&&this.viewer.setAutoRotateDelay(this.autoRotateDelay);break;case"rotation-per-second":this.viewer&&this.viewer.setAutoRotateSpeed(this.parseRotationPerSecond(i));break;case"ar":this.updateARButtonVisibility();break}for(let n of Ke.getRegisteredPlugins())n.onAttributeChanged?.(this,t,r,i)}}getAttr(t){return this.getAttribute(t)}setAttr(t,r){r!==null?this.setAttribute(t,String(r)):this.removeAttribute(t)}getBoolAttr(t){return this.hasAttribute(t)&&this.getAttr(t)!=="false"}setBoolAttr(t,r){this.setAttr(t,r?"":null)}getFloatAttr(t,r){let i=this.getAttr(t);return i!==null?parseFloat(i):r}get src(){return this.getAttr("src")}set src(t){this.setAttr("src",t)}get cameraControls(){return this.getBoolAttr("camera-controls")}set cameraControls(t){this.setBoolAttr("camera-controls",t)}get cameraOrbit(){return this.getAttr("camera-orbit")}set cameraOrbit(t){this.setAttr("camera-orbit",t)}get cameraTarget(){return this.getAttr("camera-target")}set cameraTarget(t){this.setAttr("camera-target",t)}get minCameraOrbit(){return this.getAttr("min-camera-orbit")}set minCameraOrbit(t){this.setAttr("min-camera-orbit",t)}get maxCameraOrbit(){return this.getAttr("max-camera-orbit")}set maxCameraOrbit(t){this.setAttr("max-camera-orbit",t)}get fieldOfView(){return this.getAttr("field-of-view")}set fieldOfView(t){this.setAttr("field-of-view",t)}get iosSrc(){return this.getAttr("ios-src")}set iosSrc(t){this.setAttr("ios-src",t)}get scriptSrc(){return this.getAttr("script-src")}set scriptSrc(t){this.setAttr("script-src",t)}get sandbox(){return this.getAttr("sandbox")||(Ae().sandboxIframeSrc?"iframe":"worker")}set sandbox(t){this.setAttr("sandbox",t)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||Ge.allowClientScripts}set allowClientScripts(t){this.setBoolAttr("allow-client-scripts",t)}get poster(){return this.getAttr("poster")}set poster(t){this.setAttr("poster",t)}get selectedMesh(){return this.getAttr("selected-mesh")}set selectedMesh(t){this.setAttr("selected-mesh",t)}get exposure(){return this.getFloatAttr("exposure",1)}set exposure(t){this.setAttr("exposure",t)}get autoRotate(){return this.getBoolAttr("auto-rotate")}set autoRotate(t){this.setBoolAttr("auto-rotate",t)}get autoRotateDelay(){return this.getFloatAttr("auto-rotate-delay",3e3)}set autoRotateDelay(t){this.setAttr("auto-rotate-delay",t)}get rotationPerSecond(){return this.getAttr("rotation-per-second")||"30deg"}set rotationPerSecond(t){this.setAttr("rotation-per-second",t)}get turntableRotation(){return this.viewer?this.viewer.turntableRotation:0}get ar(){return this.hasAttribute("ar")}set ar(t){this.setBoolAttr("ar",t)}get arScale(){return this.getAttr("ar-scale")||"auto"}set arScale(t){this.setAttr("ar-scale",t)}get arPlacement(){return this.getAttr("ar-placement")||"floor"}set arPlacement(t){this.setAttr("ar-placement",t)}get canActivateAR(){return Ge.isARSupported()}get shadowIntensity(){return this.getFloatAttr("shadow-intensity",0)}set shadowIntensity(t){this.setAttr("shadow-intensity",t)}get shadowSoftness(){return this.getFloatAttr("shadow-softness",.5)}set shadowSoftness(t){this.setAttr("shadow-softness",t)}get toneMapping(){return Vt(this.getAttr("tone-mapping"))}set toneMapping(t){this.setAttr("tone-mapping",t)}get bloom(){return this.getFloatAttr("bloom",0)}set bloom(t){this.setAttr("bloom",t)}get bloomThreshold(){return mn(this.getAttr("bloom-threshold"),.62)}set bloomThreshold(t){this.setAttr("bloom-threshold",t)}get bloomRadius(){return mn(this.getAttr("bloom-radius"),.75)}set bloomRadius(t){this.setAttr("bloom-radius",t)}get outlineSelected(){return this.getBoolAttr("outline-selected")}set outlineSelected(t){this.setBoolAttr("outline-selected",t)}get outlineColor(){return this.getAttr("outline-color")||"#38bdf8"}set outlineColor(t){this.setAttr("outline-color",t)}get environmentImage(){return this.getAttr("environment-image")}set environmentImage(t){this.setAttr("environment-image",t)}get skyboxImage(){return this.getAttr("skybox-image")}set skyboxImage(t){this.setAttr("skybox-image",t)}get autoplay(){return this.getBoolAttr("autoplay")}set autoplay(t){this.setBoolAttr("autoplay",t)}get animationName(){return this.getAttr("animation-name")}set animationName(t){this.setAttr("animation-name",t)}get availableAnimations(){return this.viewer?this.viewer.getAvailableAnimations():[]}get variantName(){return this.viewer?this.viewer.getVariantName():this.getAttr("variant-name")}set variantName(t){this.setAttr("variant-name",t)}get availableVariants(){return this.viewer?this.viewer.getAvailableVariants():[]}fireEvent(t,r){this.dispatchEvent(new CustomEvent(t,{bubbles:!0,composed:!0,detail:r}))}setSlotVisible(t,r){let i=typeof this.querySelector=="function"?this.querySelector(`[slot="${t}"]`):null;i&&(i.hidden=!r,i.style&&(i.style.display=r?"":"none"))}emitError(t,r="script"){this.setSlotVisible("error",!0),this.fireEvent("error",{error:t}),this.fireEvent("three-error",{error:t,message:t?.message||String(t),stage:r})}selectVariant(t){if(!this.viewer)return!1;let r=this.viewer.selectVariant(t);return r&&this.fireEvent("variant-applied",{variantName:this.viewer.getVariantName()}),r}get model(){let t=this.viewer?this.viewer.getModelMaterials():[];return{materials:t,getMaterialByName(r){return t.find(i=>i.name===r)??null}}}play(){this.viewer&&this.viewer.playAnimation(this.animationName||void 0)}pause(){this.viewer&&this.viewer.pauseAnimation()}resetCamera(){this.viewer?.resetCamera()}resetTurntableRotation(t=0){this.viewer?.resetTurntableRotation(t)}setCamera(t,r,i,n){this.viewer&&this.viewer.setCamera(t,r,i,n)}getCameraOrbit(){return this.viewer?this.viewer.getCameraOrbit():{theta:0,phi:0,radius:3,toString(){return"0rad 0rad 3m"}}}getCameraTarget(){return this.viewer?this.viewer.getCameraTarget():Ki(0,0,0)}getFieldOfView(){return this.viewer?this.viewer.getFieldOfView():45}jumpCameraToGoal(){this.viewer?.jumpCameraToGoal()}toDataURL(t,r){return this.viewer?.render?.(),this.canvas?this.canvas.toDataURL(t,r):""}toBlob(t){return this.viewer?.render?.(),new Promise((r,i)=>{if(!this.canvas||typeof this.canvas.toBlob!="function"){i(new Error("Canvas toBlob is not supported in this environment."));return}this.canvas.toBlob(n=>{n?r(n):i(new Error("Failed to capture canvas blob."))},t?.mimeType,t?.qualityArgument)})}positionAndNormalFromPoint(t,r){let i=this.viewer?.raycastFromScreenPoint(t,r);if(!i)return null;let[n,s,l]=i.hitPoint||i.point,[o,a,u]=i.normal;return{position:Ki(n,s,l),normal:Ki(o,a,u)}}loadModel(t){return this.loadModelWithLimits(t)}async loadModelWithLimits(t,r,i=this.beginLoad()){if(i.signal.throwIfAborted(),!this.viewer){this.currentModel=t,this.currentModelLimits=r;return}try{let n;if(typeof t=="string"){let a=await fetch(t,{signal:i.signal});if(!a.ok)throw new Error(`Failed to load "${t}": HTTP ${a.status}`);n=await a.arrayBuffer()}else n=t;i.signal.throwIfAborted();let s=Lt(n);this.viewer.loadGLBData(s,r),this.currentModel=s,this.currentModelLimits=r,this.isModelLoaded=!0,this.hidePoster(),this.setSlotVisible("error",!1),this.updateHotspots();let l=this.getAttr("selected-mesh");l&&this.viewer.setSelectedMesh(l);let o=this.getAttr("variant-name");o&&this.selectVariant(o),this.fireEvent("load",{model:s}),this.fireEvent("three-load",{model:s,source:typeof t=="string"?"src":"model"})}catch(n){throw i.signal.aborted||this.emitError(n,"load"),n}}showToast(t,r=4500){if(typeof document>"u")return;let i=this.querySelector(".three-live-toast");i||(i=document.createElement("div"),i.className="three-live-toast",i.style.cssText="position:absolute;bottom:70px;left:50%;transform:translateX(-50%) translateY(10px);z-index:10;padding:10px 16px;background-color:rgba(15,23,42,0.94);color:#f8fafc;border:1px solid rgba(56,189,248,0.45);border-radius:14px;font:500 13px/1.35 system-ui,-apple-system,sans-serif;box-shadow:0 10px 25px rgba(0,0,0,0.45);backdrop-filter:blur(12px);pointer-events:none;opacity:0;transition:opacity .25s ease,transform .25s ease;max-width:88%;text-align:center;white-space:normal;word-break:break-word",this.appendChild(i)),i.textContent=t,this.toastTimer&&clearTimeout(this.toastTimer);let n=()=>{i&&(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)")};typeof requestAnimationFrame<"u"?requestAnimationFrame(n):n(),this.toastTimer=setTimeout(()=>{i&&(i.style.opacity="0",i.style.transform="translateX(-50%) translateY(10px)"),this.toastTimer=null},r)}async activateAR(){this.activeXRSession?.isSessionActive?.()&&(await this.activeXRSession.stop().catch(()=>{}),this.activeXRSession=null);let t=(n,s=n.message)=>{throw this.fireEvent("ar-status",{status:"failed",error:n}),this.showToast(s,6e3),n};this.currentModel||t(new Error("No 3D model is loaded in <three-live>.")),Ge.arProvider||t(new Error("AR module not bundled. Use the default 'three-live' bundle or call ThreeLiveElement.registerAR()."));let r=this.getAttr("ios-src"),i=(this.getAttr("ar-modes")||"").split(/\s+/).filter(Boolean);try{this.fireEvent("ar-status",{status:"session-started"});let n=await Ge.arProvider.activateAR({model:r||this.currentModel,glbUrl:typeof this.currentModel=="string"?this.currentModel:void 0,view:this.viewer||void 0,element:this,preferredModes:i.length>0?i:void 0,arScale:this.arScale,arPlacement:this.arPlacement,webXROptions:{onExit:()=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"not-presenting"})},onError:s=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"failed",error:s}),this.showToast(`AR error: ${s.message}`,6e3)}}});if(n.success){n.session&&(this.activeXRSession=n.session);let s=n.mode==="quick-look"?"Opening Apple AR Quick Look...":n.mode==="scene-viewer"?"Opening Google Scene Viewer...":n.mode==="webxr"?"WebXR AR session started.":"";s&&this.showToast(s)}else{let s=n.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.";if(this.isDesktopMac()&&typeof document<"u"&&this.currentModel&&Ge.arProvider.createUSDZBlob)try{let l=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:Ge.arProvider.createUSDZBlob(this.currentModel),o=URL.createObjectURL(l),a=document.createElement("a");a.href=o,a.download="three_live_model.usdz",document.body.appendChild(a),a.click(),document.body.removeChild(a),setTimeout(()=>URL.revokeObjectURL(o),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(s,6e3)}else this.showToast(s,6e3);n.error&&this.fireEvent("ar-status",{status:"failed",error:n.error})}return n}catch(n){return this.activeXRSession=null,t(n,`AR error: ${n.message||String(n)}`)}}setupDOM(){let t=this.querySelector("canvas");t||(t=document.createElement("canvas"),t.style.cssText=`width:100%;height:100%;display:block;touch-action:${this.cameraControls?"none":"auto"};outline:none`,this.appendChild(t)),this.canvas=t,typeof t.addEventListener=="function"&&!t.__tlCtxBound&&(t.__tlCtxBound=!0,t.addEventListener("webglcontextlost",i=>this.fireEvent("three-context-lost",{originalEvent:i})),t.addEventListener("webglcontextrestored",i=>this.fireEvent("three-context-restored",{originalEvent:i}))),this.setSlotVisible("error",!1),this.isModelLoaded||this.setSlotVisible("poster",!0);let r=this.getAttr("poster");r&&this.updatePoster(r),this.createARButton(),typeof MutationObserver<"u"&&!this.mutationObserver&&(this.mutationObserver=new MutationObserver(()=>{this.updateARButtonVisibility()}),this.mutationObserver.observe(this,{childList:!0}))}initViewer(){if(!this.canvas)return;let t=this.autoRotate,r=this.exposure,i=this.parseOrbitLimit(this.getAttr("min-camera-orbit")),n=this.parseOrbitLimit(this.getAttr("max-camera-orbit")),s=this.parseCameraTarget(this.getAttr("camera-target")),l=this.parseFieldOfView(this.getAttr("field-of-view"));this.viewer=new Ke(this,this.canvas,{autoRotate:t,autoRotateDelay:this.autoRotateDelay,autoRotateSpeed:this.parseRotationPerSecond(this.getAttr("rotation-per-second")),exposure:r,shadowIntensity:this.shadowIntensity,shadowSoftness:this.shadowSoftness,toneMapping:this.toneMapping,environmentImage:this.environmentImage,autoplay:this.autoplay,animationName:this.animationName||void 0,variantName:this.getAttr("variant-name")||void 0,fieldOfView:l,cameraTarget:s,minCameraOrbit:i,maxCameraOrbit:n,onMeshClick:a=>{this.fireEvent("meshclick",a)},onCameraChange:a=>{this.updateHotspots();for(let u of Ke.getRegisteredPlugins())u.onCameraChange?.(this.viewer,this);this.fireEvent("camera-change",a)}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let o=this.getAttr("camera-orbit");o&&this.applyCameraOrbit(o),this.currentModel&&this.loadModelWithLimits(this.currentModel,this.currentModelLimits)}setupResizeObserver(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>{this.viewer&&(this.viewer.resize(),this.viewer.render(),this.updateHotspots())}),this.resizeObserver.observe(this))}updatePoster(t){if(!(typeof document>"u")){if(!t){this.posterEl&&(this.posterEl.remove(),this.posterEl=null);return}this.posterEl||(this.posterEl=document.createElement("img"),this.posterEl.alt="3D Scene Preview",this.posterEl.style.cssText="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity .35s ease-out;pointer-events:none;z-index:1",this.appendChild(this.posterEl)),this.posterEl.src=t,this.isModelLoaded||(this.posterEl.style.opacity="1")}}hidePoster(){this.setSlotVisible("poster",!1),this.posterEl&&(this.posterEl.style.opacity="0",setTimeout(()=>{this.isModelLoaded&&this.posterEl&&(this.posterEl.remove(),this.posterEl=null)},400))}isDesktopMac(){let t=typeof navigator<"u"&&navigator.userAgent||"";return/Macintosh/i.test(t)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1)&&!/Android|iPhone|iPad|iPod/i.test(t)}syncARButtonLabel(t){let r=this.isDesktopMac(),i=r?"Quick Look (.usdz)":"View in AR",n=r?"Download .usdz preview for macOS Quick Look (live camera AR requires iOS or Android)":"View in Augmented Reality";typeof t.setAttribute=="function"&&(t.setAttribute("aria-label",n),t.setAttribute("title",n));let s=t._labelSpan||(typeof t.querySelector=="function"?t.querySelector("span"):null);s&&(s.textContent=i)}createARButton(){if(!(typeof document>"u")){if(!this.arButton){let t=document.createElement("button");t.type="button",t.className="three-live-ar-button",t.setAttribute("part","default-ar-button");let r="http://www.w3.org/2000/svg";if(typeof document.createElementNS=="function"){let n=document.createElementNS(r,"svg");for(let[l,o]of[["width","20"],["height","20"],["viewBox","0 0 24 24"],["fill","none"],["stroke","currentColor"],["stroke-width","2"],["stroke-linecap","round"],["stroke-linejoin","round"]])n.setAttribute(l,o);n.style.marginRight="6px";let s=document.createElementNS(r,"path");s.setAttribute("d","M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16zM3.27 6.96 12 12.01l8.73-5.05M12 22.08V12"),n.appendChild(s),t.appendChild(n)}let i=document.createElement("span");t._labelSpan=i,t.appendChild(i),this.syncARButtonLabel(t),t.style.cssText="position:absolute;right:16px;bottom:16px;z-index:2;align-items:center;justify-content:center;padding:8px 16px;background-color:rgba(15,23,42,0.85);color:#fff;border:1px solid rgba(255,255,255,0.15);border-radius:9999px;font:600 13px system-ui,-apple-system,sans-serif;cursor:pointer;backdrop-filter:blur(8px);box-shadow:0 4px 12px rgba(0,0,0,0.25);transition:transform .15s ease,background-color .15s ease;display:none",t.addEventListener("mouseenter",()=>{t.style.backgroundColor="rgba(30, 41, 59, 0.95)",t.style.transform="scale(1.04)"}),t.addEventListener("mouseleave",()=>{t.style.backgroundColor="rgba(15, 23, 42, 0.85)",t.style.transform="scale(1)"}),t.addEventListener("click",n=>{n.stopPropagation(),this.activateAR()}),this.arButton=t,this.appendChild(t)}this.updateARButtonVisibility()}}updateARButtonVisibility(){let t=this.hasAttribute("ar")&&!!Ge.arProvider,r=typeof this.querySelector=="function"?this.querySelector('[slot="ar-button"]'):null;r?(this.arButton&&(this.arButton.style.display="none"),r.__tlARBound||(r.__tlARBound=!0,r.addEventListener("click",i=>{i.stopPropagation(),this.activateAR()})),r.dataset.tlOrigDisplay===void 0&&(r.dataset.tlOrigDisplay=r.style.display==="none"?"":r.style.display),r.style.display=t?r.dataset.tlOrigDisplay||"":"none"):this.arButton&&(this.syncARButtonLabel(this.arButton),this.arButton.style.display=t?"flex":"none")}applyCameraOrbit(t){if(!(!t||!this.viewer))try{let r=JSON.parse(t);this.viewer.setInitialCamera(r.theta,r.phi,r.distance,r.zoom)}catch{let r=this.parseOrbitLimit(t);(r.theta!==void 0||r.phi!==void 0)&&this.viewer.setInitialCamera(r.theta,r.phi,r.distance)}}parseOrbitLimit(t){if(!t)return{};let[r,i,n]=t.trim().split(/\s+/),s=n&&n!=="auto"?parseFloat(n):NaN;return{theta:r&&r!=="auto"?this.parseFieldOfView(r):void 0,phi:i&&i!=="auto"?this.parseFieldOfView(i):void 0,distance:isNaN(s)?void 0:s}}applyOrbitLimits(){if(!this.viewer)return;let t=this.parseOrbitLimit(this.getAttr("min-camera-orbit")),r=this.parseOrbitLimit(this.getAttr("max-camera-orbit"));this.viewer.setOrbitLimits({minTheta:t.theta,maxTheta:r.theta,minPhi:t.phi,maxPhi:r.phi,minDistance:t.distance,maxDistance:r.distance})}parseCameraTarget(t){if(!t)return;let r=t.trim().split(/\s+/).map(parseFloat);return r.length>=3&&!r.some(isNaN)?[r[0],r[1],r[2]]:void 0}parseFieldOfView(t){if(!t)return;let r=parseFloat(t);return isNaN(r)?void 0:t.endsWith("rad")?r*180/Math.PI:r}parseRotationPerSecond(t){if(!t)return Math.PI/6;let r=t.trim(),i=parseFloat(r);return isNaN(i)?Math.PI/6:r.endsWith("rad")?i:r.endsWith("%")?i/100*Math.PI*2:i*Math.PI/180}applyCameraTarget(t){let r=this.parseCameraTarget(t);this.viewer&&r&&this.viewer.setTarget(r[0],r[1],r[2])}applyFieldOfView(t){let r=this.parseFieldOfView(t);this.viewer&&r!==void 0&&this.viewer.setFieldOfView(r)}updateHotspot(t){let r=this.querySelector(`[slot="${t.name}"]`);r&&(t.position!==void 0&&r.setAttribute("data-position",t.position),t.normal!==void 0&&r.setAttribute("data-normal",t.normal)),this.updateHotspots()}updateHotspots(){for(let t of Ke.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}runWithScriptRunner(t){let r=Ge.scriptRunner;if(!r){let s=new Error('Script execution requires "three-live/full" or registerScriptRunner().');return this.showToast(s.message),this.emitError(s,"script"),Promise.reject(s)}let i=this.beginLoad(),n=()=>!i.signal.aborted;return new Promise((s,l)=>{let o=()=>l(i.signal.reason);if(i.signal.addEventListener("abort",o,{once:!0}),!n()){o();return}let a={onModelReady:u=>{this.loadModelWithLimits(u,as,i).then(()=>s(u),l)},onUpdateTransforms:u=>{n()&&this.viewer?.updateMeshTransforms(u)},onError:u=>{n()&&(this.showToast(u.message),this.emitError(u,"script"),l(u))},onToast:u=>{n()&&this.showToast(u)}};t(r,a).then(u=>{n()?this.scriptHandle=u||null:u?.terminate()},u=>{n()&&a.onError?.(u)})})}loadScriptFromSrc(t){return this.runWithScriptRunner((r,i)=>{if(typeof r.executeUrl!="function"){let n=new Error("Registered ScriptRunner does not support executeUrl() for server-generated scripts.");return i.onError?.(n),Promise.reject(n)}return r.executeUrl(t,this.sandbox,i)})}executeScript(t){if(!Ge.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(Qn);return this.showToast(Jn),this.emitError(r,"security"),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(t,this.sandbox,i,{allowClientScripts:!0}))}};ze.observedAttributes=["src","ios-src","script-src","sandbox","allow-client-scripts","poster","camera-controls","camera-orbit","camera-target","min-camera-orbit","max-camera-orbit","field-of-view","selected-mesh","ar","ar-modes","ar-scale","ar-placement","exposure","shadow-intensity","shadow-softness","tone-mapping","bloom","bloom-threshold","bloom-radius","outline","outline-selected","outline-color","environment-image","skybox-image","autoplay","animation-name","variant-name","auto-rotate","auto-rotate-delay","rotation-per-second"],ze.registerPlugin=Ke.registerPlugin,ze.getRegisteredPlugins=Ke.getRegisteredPlugins;var mt=ze;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",mt);function $s(e="model-viewer"){return mt.defineModelViewer(e)}function Ws(e,t,r){return t%4===0?new Float32Array(e,t,r):new Float32Array(e.slice(t,t+r*4))}function oi(e,t,r,i){let n=t[0],s=t[1],l=t[2],o=t[3],a=r[0],u=r[1],h=r[2],m=r[3],c=n*a+s*u+l*h+o*m;if(c<0&&(a=-a,u=-u,h=-h,m=-m,c=-c),Math.abs(c)>=1)return e[0]=n,e[1]=s,e[2]=l,e[3]=o,e;let d=Math.acos(c),f=Math.sqrt(1-c*c);if(Math.abs(f)<.001)return e[0]=.5*(n+a),e[1]=.5*(s+u),e[2]=.5*(l+h),e[3]=.5*(o+m),e;let g=Math.sin((1-i)*d)/f,x=Math.sin(i*d)/f;return e[0]=n*g+a*x,e[1]=s*g+u*x,e[2]=l*g+h*x,e[3]=o*g+m*x,e}function js(e,t,r,i){return e[0]=t[0]+i*(r[0]-t[0]),e[1]=t[1]+i*(r[1]-t[1]),e[2]=t[2]+i*(r[2]-t[2]),e}function Ji(e,t){if(!Array.isArray(e?.animations))return[];let r=[];for(let i=0;i<e.animations.length;i++){let n=e.animations[i],s=n.name||`Animation_${i}`,l=[],o=0;if(Array.isArray(n.channels)&&Array.isArray(n.samplers))for(let a of n.channels){if(!a.target||a.target.node===void 0||!a.target.path)continue;let u=n.samplers[a.sampler];if(!u)continue;let h=e.accessors?.[u.input],m=e.accessors?.[u.output];if(!h||!m)continue;let c=e.bufferViews?.[h.bufferView],d=e.bufferViews?.[m.bufferView];if(!c||!d)continue;let f=(c.byteOffset||0)+(h.byteOffset||0),g=(d.byteOffset||0)+(m.byteOffset||0),x=bt(e,t,h,1)??Ws(t,f,h.count);x.length>0&&x[x.length-1]>o&&(o=x[x.length-1]);let b=a.target.path==="rotation"?4:a.target.path==="weights"?Math.max(1,Math.round(m.count/Math.max(1,h.count))):3,v=a.target.path==="weights"?1:b,p=bt(e,t,m,v)??Ws(t,g,m.count*v),y=u.interpolation==="STEP"?"STEP":"LINEAR";l.push({nodeIndex:a.target.node,path:a.target.path,times:x,values:p,interpolation:y})}l.length>0&&r.push({name:s,duration:o,channels:l})}return r}function fn(e,t,r){let{times:i,values:n,path:s,interpolation:l}=e,o=i.length;if(o===0)return;let a=s==="rotation"?4:s==="weights"?Math.max(1,Math.round(n.length/o)):3;if(t<=i[0]){for(let v=0;v<a;v++)r[v]=n[v];return}if(t>=i[o-1]){let v=(o-1)*a;for(let p=0;p<a;p++)r[p]=n[v+p];return}let u=0,h=o-1;for(;u<=h;){let v=u+h>>1;i[v]<=t?u=v+1:h=v-1}let m=Math.max(0,h),c=Math.min(o-1,m+1);if(l==="STEP"||m===c){let v=m*a;for(let p=0;p<a;p++)r[p]=n[v+p];return}let d=i[m],f=i[c],g=(t-d)/Math.max(1e-5,f-d),x=m*a,b=c*a;if(s==="rotation"){let v=[n[x],n[x+1],n[x+2],n[x+3]],p=[n[b],n[b+1],n[b+2],n[b+3]];oi(r,v,p,g)}else for(let v=0;v<a;v++)r[v]=n[x+v]+g*(n[b+v]-n[x+v])}var Xn=new WeakMap;function eo(e,t,r=.3){if(!e?.animations)return;let i=e.animations.find(o=>o.name===t);if(!i)return;let n=Xn.get(e);n||(n=[],e.currentClip&&n.push({clip:e.currentClip,time:e.animationTime||0,weight:1,fadeSpeed:0}),Xn.set(e,n));let s=r>0?1/r:1e3;for(let o of n)o.clip.name!==t&&(o.fadeSpeed=-s);let l=n.find(o=>o.clip.name===t);l?l.fadeSpeed=s:n.push({clip:i,time:0,weight:r>0?0:1,fadeSpeed:s}),e.currentClip=i,e.isPlayingAnimation=!0}function Zi(e,t){if(!e.gltf||!Array.isArray(e.gltf.nodes))return;let r=Xn.get(e);if(!r||r.length===0){if(!e.currentClip)return;r=[{clip:e.currentClip,time:t,weight:1,fadeSpeed:0}]}let i=e.gltf.nodes.length,n=[];for(let m=0;m<i;m++){let c=e.initialNodeTransforms[m];c?n.push({t:[c.t[0],c.t[1],c.t[2]],r:[c.r[0],c.r[1],c.r[2],c.r[3]],s:[c.s[0],c.s[1],c.s[2]]}):n.push({t:[0,0,0],r:[0,0,0,1],s:[1,1,1]})}let s=[0,0,0],l=[0,0,0,1],o=[1,1,1],a=new Float32Array(64);for(let m of r){let c=Math.max(0,Math.min(1,m.weight));if(!(c<=1e-4))for(let d of m.clip.channels){if(d.nodeIndex<0||d.nodeIndex>=i)continue;let f=n[d.nodeIndex];if(d.path==="translation")fn(d,m.time,s),js(f.t,f.t,s,c);else if(d.path==="rotation")fn(d,m.time,l),oi(f.r,f.r,l,c);else if(d.path==="scale")fn(d,m.time,o),js(f.s,f.s,o,c);else if(d.path==="weights"&&(fn(d,m.time,a),e.meshes)){for(let g of e.meshes)if(g.nodeIndex===d.nodeIndex){for(let x of g.primitives)if(x.pluginData?.morph?.weights){let b=x.pluginData.morph.weights,v=x.pluginData.morph.numTargets||b.length;for(let p=0;p<v;p++)b[p]=b[p]*(1-c)+a[p]*c}}}}}let u=[];for(let m=0;m<i;m++){let c=Se(),{t:d,r:f,s:g}=n[m];Tt(c,f,d,g),u.push(c)}let h=Ft(e.gltf,u);e.worldMatrices=h;for(let m of e.meshes)m.nodeIndex>=0&&m.nodeIndex<h.length&&(m.transform.set(h[m.nodeIndex]),Xe(m.normalMatrix,m.transform))}var Qi=e=>{Xn.delete(e)},to={name:"keyframes",evaluateAnimation:Zi,crossFadeTo:eo,onParseGLB(e){!e.animations&&e.gltf?.animations&&(e.animations=Ji(e.gltf,e.bin))},onLoadModel:Qi,onClearScene:Qi,onDestroy:(e,t)=>Qi(t),onUpdate(e,t){if(!e.isPlayingAnimation)return;let r=Xn.get(e);if(r&&r.length>0){for(let i=r.length-1;i>=0;i--){let n=r[i];if(n.time+=t,n.clip.duration>0&&(n.time%=n.clip.duration),n.fadeSpeed!==0)if(n.weight+=n.fadeSpeed*t,n.weight<=0){r.splice(i,1);continue}else n.weight>=1&&(n.weight=1,n.fadeSpeed=0)}r.length>0&&(e.animationTime=r[r.length-1].time),Zi(e,e.animationTime)}else e.currentClip&&(e.animationTime+=t,e.currentClip.duration>0&&(e.animationTime%=e.currentClip.duration),Zi(e,e.animationTime))}},$n=64;function Ks(e,t,r){if(!(!e?.meshes||t<0||t>=$n))for(let i of e.meshes)for(let n of i.primitives){let s=n.pluginData?.morph;s?.weights&&(s.weights[t]=r)}}var no={name:"morph",onResolveShader(e,t,r,i){if(!Array.isArray(e?.targets)||e.targets.length===0)return null;let n=r.replace("uniform mat4 uMVP,uModel;",`uniform mat4 uMVP,uModel;
|
|
402
|
+
})();`);v=null;let V=F(y,P,R,$);V&&typeof V.toGLB=="function"&&(P=V)}if(!w){y.SceneQuotaValidator&&y.SceneQuotaValidator.validate(P);let F=P.toGLB(),V=F instanceof ArrayBuffer?F:F.buffer.slice(F.byteOffset,F.byteOffset+F.byteLength);S({type:"3D_MODEL_READY",glbBuffer:V},[V])}h({type:"DONE",nonce:n})}catch(P){p(P&&P.message||P)}},h({type:"READY",nonce:n})}function sl(e,t,r){let i=r?.allowedScriptUrl??null,n=r?.allowClientScripts??i===null,a={nonce:t,engineSrc:e,allowedScriptUrl:i,allowClientScripts:n,revoked:n0},s=(He().workerExtensionInstallers??[]).map(o=>`(${o.toString()})`).join(",");return`'use strict';(${r0.toString()})(${JSON.stringify(a)},[${s}],(${zc.toString()}));`}function pf(e){e.onError?.(new Error("SecurityError: Sandboxed script exceeded SECURITY_3D_SANDBOX_TIMEOUT_MS (3000 ms) and was terminated.")),e.onToast?.("Security Error: script timed out and was stopped.")}var Tr=0;function bf(){try{let e=new Uint32Array(4);return globalThis.crypto?.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(8,"0")).join("")}catch{return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}}function o0(e){try{return new TextEncoder().encode(e).length}catch{return e.length}}var i0=1024,s0=256;function rf(e){if(!Array.isArray(e)&&!(e instanceof Float32Array)||e.length!==16)return!1;for(let t=0;t<16;t++){let r=e[t];if(typeof r!="number"||!Number.isFinite(r))return!1}return!0}function al(e,t){if(!e||typeof e!="object")return null;let r=e;if(r.nonce!==t)return null;switch(r.type){case"READY":return{type:"READY"};case"DONE":return{type:"DONE"};case"ERROR":return{type:"ERROR",message:(typeof r.message=="string"?r.message:String(r.message??"Unknown worker error")).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").slice(0,i0)};case"3D_UPDATE_TRANSFORMS":{let i=r.transforms;if(Array.isArray(i)){if(i.length>1e3)return null;for(let n of i)if(!rf(n))return null;return{type:"3D_UPDATE_TRANSFORMS",transforms:i}}if(i&&typeof i=="object"){let n=Object.keys(i);if(n.length>1e3)return null;let a=Object.create(null),s=i;for(let o of n){if(o.length>s0||o==="__proto__"||o==="constructor"||o==="prototype")return null;let l=s[o];if(!rf(l))return null;a[o]=l}return{type:"3D_UPDATE_TRANSFORMS",transforms:a}}return null}case"3D_MODEL_READY":{let i=r.glbBuffer;return!(i instanceof ArrayBuffer)||i.byteLength>16777216?null:{type:"3D_MODEL_READY",payload:i}}default:return null}}function a0(e){let t=o0(e);if(t>1048576)throw new Error(`SecurityError: Script length (${t} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function yf(e,t,r,i){switch(e.type){case"READY":return;case"3D_UPDATE_TRANSFORMS":t.onUpdateTransforms?.(e.transforms);return;case"3D_MODEL_READY":if(i.modelDispatched)return;i.modelDispatched=!0,t.onModelReady(e.payload);return;case"DONE":r();return;case"ERROR":r(),t.onError?.(new Error(`Worker script error: ${e.message}`));return;default:return e}}function c0(e,t,r,i){let n=bf(),a=sl(t,n,e.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:e.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),s=document.createElement("iframe");s.setAttribute("sandbox","allow-scripts"),s.setAttribute("aria-hidden","true"),s.tabIndex=-1,s.style.display="none",s.src=r,Tr++;let o=!1,l=!1,c={modelDispatched:!1},f,m=()=>{if(o||l)return;let x=s.contentWindow;!x||typeof x.postMessage!="function"||(l=!0,x.postMessage(e.kind==="url"?{type:"SANDBOX_RUN",nonce:n,workerSource:a,scriptUrl:e.scriptUrl,texturePack:e.texturePack??null}:{type:"SANDBOX_RUN",nonce:n,workerSource:a,script:e.script,texturePack:e.texturePack??null},"*"))},h=()=>{},p=x=>{if(o||!s.contentWindow||x.source!==s.contentWindow)return;let v=x.data;if(v&&typeof v=="object"&&v.type==="IFRAME_READY"){m();return}let y=al(v,n);y&&yf(y,i,h,c)};h=()=>{o||(o=!0,f!==void 0&&clearTimeout(f),Tr=Math.max(0,Tr-1),typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("message",p),typeof s.remove=="function"?s.remove():s.parentNode&&s.parentNode.removeChild(s))},f=setTimeout(()=>{o||(h(),pf(i))},3e3),typeof globalThis.addEventListener=="function"&&globalThis.addEventListener("message",p),s.onload=()=>{m()},s.onerror=()=>{h(),i.onError?.(new Error(`Sandbox iframe failed to load "${r}". Verify that three-live-sandbox.html is served at that URL.`))};let g=document.body||document.documentElement;if(!g||typeof g.appendChild!="function"){h();let x=new Error("SecurityError: Cannot mount sandbox iframe because document.body is unavailable.");throw i.onError?.(x),x}return g.appendChild(s),{terminate:h}}function of(e,t,r,i){if(t==="worker"&&typeof Worker>"u")return i("SecurityError: Web Workers are unavailable for sandboxed execution.","Security Error: Web Workers unavailable.");if(t==="iframe"&&(typeof document>"u"||typeof document.createElement!="function"))return i("SecurityError: DOM unavailable for iframe sandbox execution.","Security Error: DOM unavailable for iframe sandbox.");if(Tr>=32)return i(`SecurityError: ${Tr} workers running, meeting SECURITY_3D_MAX_CONCURRENT_TASKS (32).`,"Security Error: too many concurrent sandboxed scripts.");let n;try{n=Jp()}catch(h){let p=h instanceof Error?h.message:String(h);return i(p,"Security Error: sandbox engine URL is not configured.")}if(t==="iframe"){let h;try{h=Zp()}catch(p){let g=p instanceof Error?p.message:String(p);return i(g,"Security Error: sandbox iframe URL is not configured.")}try{return Promise.resolve(c0(e,n,h,r))}catch(p){return Promise.reject(p)}}let a=bf(),s=sl(n,a,e.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:e.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),o;try{let h=new Blob([s],{type:"application/javascript"}),p=URL.createObjectURL(h);try{let g=ff(p);o=new Worker(g)}finally{URL.revokeObjectURL(p)}}catch(h){let p=h instanceof Error?h.message:String(h);return i(`Failed to initialize Web Worker for sandboxed execution (CSP may block blob workers): ${p}`,"Security Error: Failed to start Worker sandbox.")}Tr++;let l=!1,c={modelDispatched:!1},f,m=()=>{l||(l=!0,f!==void 0&&clearTimeout(f),Tr=Math.max(0,Tr-1),o.terminate())};return f=setTimeout(()=>{l||(m(),pf(r))},3e3),o.onmessage=h=>{let p=al(h.data,a);p&&yf(p,r,m,c)},o.onerror=h=>{m(),r.onError?.(new Error(`Worker execution error: ${h.message}`))},e.kind==="url"?o.postMessage({type:"EXECUTE_URL",scriptUrl:e.scriptUrl,nonce:a,texturePack:e.texturePack??null}):o.postMessage({type:"EXECUTE",script:e.script,nonce:a,texturePack:e.texturePack??null}),Promise.resolve({terminate:m})}function sf(e,t){return e!=="worker"&&e!=="iframe"?t(`SecurityError: Unsupported sandbox="${e}"; require "worker" or "iframe".`,`Security Error: sandbox="${e}" is not permitted.`):null}var af=e=>(t,r)=>{let i=new Error(t);return e.onError?.(i),r&&e.onToast?.(r),Promise.reject(i)},so={execute(e,t,r,i){let n=af(r),a=sf(t,n);if(a)return a;try{a0(e)}catch(s){let o=s instanceof Error?s.message:String(s);return n(o,"Security Error: script exceeds the size limit.")}return i?.allowClientScripts??hf()?of({kind:"script",script:e,texturePack:i?.texturePack},t,r,n):n(os,is)},executeUrl(e,t,r,i){let n=af(r),a=sf(t,n);if(a)return a;let s;try{s=t0(e)}catch(o){let l=o instanceof Error?o.message:String(o);return n(l,"Security Error: disallowed scene script URL.")}return of({kind:"url",scriptUrl:s,texturePack:i?.texturePack},t,r,n)}},ea=new Set;function Er(e,t){let r=`[three-live] ${e} is unsupported; degraded to ${t}.`;ea.has(r)||(ea.add(r),typeof console<"u"&&typeof console.warn=="function"&&console.warn(r))}function gf(){return Array.from(ea)}function xf(){ea.clear()}var yi=class extends Fr{constructor(e={}){Er("ShaderMaterial","MeshStandardMaterial");let t=e.uniforms||{},r=t.color?.value??t.uColor?.value??t.diffuse?.value??e.color;super({color:r!==void 0?r:8421504,opacity:t.opacity?.value??e.opacity??1,transparent:!!e.transparent,wireframe:!!e.wireframe,side:e.side}),this.uniforms=t}},vf=yi,lr=class extends Nt{constructor(e=[],t=[],r=1,i=0){super();let n=Number(r)||1,a=Math.max(0,Math.min(7,Math.floor(Number(i)||0))),s=a+1,o=[],l=[],c=[],f=[],m=new Ze,h=new Ze,p=new Ze,g=(y,A)=>A.set(e[y*3]||0,e[y*3+1]||0,e[y*3+2]||0),x=(y,A)=>{let b=y.clone().normalize();o.push(b.x*n,b.y*n,b.z*n),l.push(A.x,A.y,A.z),c.push(Math.atan2(b.z,-b.x)/(2*Math.PI)+.5,1-Math.acos(Math.max(-1,Math.min(1,b.y)))/Math.PI)},v=(y,A,b)=>{let w=o.length/3,S=a===0?new Ze().subVectors(b,A).cross(new Ze().subVectors(y,A)).normalize():null;x(y,S||y.clone().normalize()),x(A,S||A.clone().normalize()),x(b,S||b.clone().normalize()),f.push(w,w+1,w+2)};for(let y=0;y<t.length;y+=3){g(t[y],m),g(t[y+1],h),g(t[y+2],p);let A=[];for(let b=0;b<=s;b++){A[b]=[];let w=m.clone().lerp(p,b/s),S=h.clone().lerp(p,b/s),E=s-b;for(let N=0;N<=E;N++)A[b][N]=E===0?w.clone():w.clone().lerp(S,N/E)}for(let b=0;b<s;b++)for(let w=0;w<2*(s-b)-1;w++){let S=w>>1;(w&1)===0?v(A[b][S+1],A[b+1][S],A[b][S]):v(A[b][S+1],A[b+1][S+1],A[b+1][S])}}this.setFromBuffers(o,l,c,f)}},l0=lr,ta=class extends lr{constructor(e=1,t=0){super([1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],e,t)}},cl=e=>Array.from(e,t=>parseInt(t,36)),_s=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],wf=cl("024043035052125153134142"),na=class extends lr{constructor(e=1,t=0){super(_s,wf,e,t)}},Rt=(1+Math.sqrt(5))/2,ra=class extends lr{constructor(e=1,t=0){super([-1,Rt,0,1,Rt,0,-1,-Rt,0,1,-Rt,0,0,-1,Rt,0,1,Rt,0,-1,-Rt,0,1,-Rt,Rt,0,-1,Rt,0,1,-Rt,0,-1,-Rt,0,1],cl("0b505101707a0ab1595b4ba2a7671839434232636838949524b62a867981"),e,t)}},_n=1/Rt,oa=class extends lr{constructor(e=1,t=0){super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-_n,-Rt,0,-_n,Rt,0,_n,-Rt,0,_n,Rt,-_n,-Rt,0,-_n,Rt,0,_n,-Rt,0,_n,Rt,0,-Rt,0,-_n,Rt,0,-_n,-Rt,0,_n,Rt,0,_n],cl("3b737f3fd7jh7h676fh48h8aha680g8g282a0c101i0ig6a262d6df2gi2i323di19i9bib34ec4c0408b95b5jbj7j5eje4j4h1ce1e5159"),e,t)}},ia=class extends li{constructor(e=1,t=1,r=4,i=8){let n=Math.max(1e-4,Number(e)||1),a=Math.max(0,Number.isFinite(Number(t))?Number(t):1)*.5,s=Math.max(2,Math.min(64,Math.floor(Number(r)||4))),o=[];for(let l=-1;l<=1;l+=2)for(let c=0;c<=s;c++){if(l>0&&c===0&&a===0)continue;let f=(l<0?c/s-1:c/s)*(Math.PI/2);o.push(new tn(Math.max(0,Math.cos(f)*n),l*a+Math.sin(f)*n))}super(o,Math.max(4,Math.min(128,Math.floor(Number(i)||8))))}},gi=class extends Nt{constructor(e=.5,t=1,r=32,i=1,n=0,a=Math.PI*2){super();let s=Math.max(1e-4,Number(t)||1),o=Number(e),l=Number.isFinite(o)?Math.max(0,o):s*.5,c=Math.max(s,l),f=Math.min(c*.999,Math.min(s,l)),m=Math.max(3,Math.min(256,Math.floor(Number(r)||32))),h=Math.max(1,Math.min(64,Math.floor(Number(i)||1))),p=Number.isFinite(Number(n))?Number(n):0,g=Number.isFinite(Number(a))?Number(a):Math.PI*2,x=[],v=[],y=[],A=[];for(let b=0;b<=h;b++){let w=f+b/h*(c-f);for(let S=0;S<=m;S++){let E=p+S/m*g,N=Math.cos(E),C=Math.sin(E);if(x.push(w*N,w*C,0),v.push(0,0,1),y.push(w/c*N*.5+.5,w/c*C*.5+.5),b<h&&S<m){let _=b*(m+1)+S,P=_+m+1;w>1e-6&&A.push(_,P,_+1),A.push(P,P+1,_+1)}}}this.setFromBuffers(x,v,y,A)}},sa=class extends gi{constructor(e=1,t=32,r=0,i=Math.PI*2){super(0,e,t,1,r,i)}},xi=class extends vn{constructor(e={}){super({roughness:.35,metalness:.1,side:2,...e});let t=Number(e.size);this.size=Number.isFinite(t)?Math.max(.002,Math.min(2,t)):.05,this.sizeAttenuation=e.sizeAttenuation!==!1,e.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.35)}},io=class extends vn{constructor(e={}){super({roughness:.4,metalness:.1,side:2,...e});let t=Number(e.linewidth);this.linewidth=Number.isFinite(t)?Math.max(.5,Math.min(20,t)):1,e.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.3)}},aa=class extends io{constructor(e={}){super(e),this.dashSize=Number(e.dashSize)||3,this.gapSize=Number(e.gapSize)||1,this.scale=Number(e.scale)||1}};function Sf(e,t){let r=e?.attributes?.position;if(!r?.array||r.count<3)return new Float32Array(0);let i=r.array,n=e?.index?.array,a=Math.min(8192,Math.floor((n?n.length:r.count)/3)),s=h=>`${Math.round((i[h*3]||0)*1e4)},${Math.round((i[h*3+1]||0)*1e4)},${Math.round((i[h*3+2]||0)*1e4)}`,o=t===void 0,l=o?1:Math.cos(t*Math.PI/180),c={},f=[],m=(h,p)=>f.push(i[h*3]||0,i[h*3+1]||0,i[h*3+2]||0,i[p*3]||0,i[p*3+1]||0,i[p*3+2]||0);for(let h=0;h<a;h++){let p=n?n[h*3]:h*3,g=n?n[h*3+1]:h*3+1,x=n?n[h*3+2]:h*3+2,v=i[p*3]||0,y=i[p*3+1]||0,A=i[p*3+2]||0,b=(i[g*3]||0)-v,w=(i[g*3+1]||0)-y,S=(i[g*3+2]||0)-A,E=(i[x*3]||0)-v,N=(i[x*3+1]||0)-y,C=(i[x*3+2]||0)-A,_=w*C-S*N,P=S*E-b*C,R=b*N-w*E,$=Math.hypot(_,P,R);if(!o&&$<1e-8)continue;$>0&&(_/=$,P/=$,R/=$);let F=[p,g,x];for(let V=0;V<3;V++){let Y=F[V],J=F[(V+1)%3],re=s(Y),Q=s(J);if(re===Q)continue;let ee=re<Q?`${re}|${Q}`:`${Q}|${re}`,k=c[ee];k?k.m||(k.m=1,k.nx*_+k.ny*P+k.nz*R<=l&&m(Y,J)):(c[ee]={va:Y,vb:J,nx:_,ny:P,nz:R,m:o?1:0},o&&m(Y,J))}}if(!o){let h=Object.keys(c);for(let p=0;p<h.length;p++){let g=c[h[p]];g&&!g.m&&m(g.va,g.vb)}}return new Float32Array(f)}var ca=class extends Nt{constructor(e){super(),this.setAttribute("position",new Vt(Sf(e),3)),this.__isSegmentPairs=!0}},la=class extends Nt{constructor(e,t=1){super();let r=Number.isFinite(Number(t))?Number(t):1;this.setAttribute("position",new Vt(Sf(e,r),3)),this.__isSegmentPairs=!0}};function u0(e,t,r=1){let i=new Nt;i.__baked=!0;let n=e?.attributes?.position;if(!n?.array||n.count<2)return i;let a=n.array,s=e.index?.array,o=e.__isSegmentPairs?"segments":t,l=s?s.length:n.count,c=Math.min(4096,Math.max(0,o==="segments"?Math.floor(l/2):o==="loop"&&l>=3?l:l-1));if(c===0)return i;e.computeBoundingBox();let f=e.boundingBox,m=f&&f.max.x>=f.min.x&&f.max.distanceTo(f.min)||1,h=Math.max(.0015,Math.min(.025,m*.003))*(.5+.5*Math.max(.5,Math.min(6,Number(r)||1))),p=[],g=[],x=[],v=[];for(let y=0;y<c;y++){let A=o==="segments"?y*2:y,b=o==="segments"?y*2+1:(y+1)%l,w=s?s[A]:A,S=s?s[b]:b,E=a[w*3]||0,N=a[w*3+1]||0,C=a[w*3+2]||0,_=(a[S*3]||0)-E,P=(a[S*3+1]||0)-N,R=(a[S*3+2]||0)-C,$=Math.hypot(_,P,R);if($<1e-6)continue;let F=_/$,V=P/$,Y=R/$,J=(Math.abs(V)<.9?Math.hypot(Y,F):Math.hypot(Y,V))||1,re=Math.abs(V)<.9?Y/J:0,Q=Math.abs(V)<.9?0:-Y/J,ee=Math.abs(V)<.9?-F/J:V/J,k=V*ee-Y*Q,G=Y*re-F*ee,q=F*Q-V*re,H=p.length/3,te=[[re,Q,ee],[k,G,q],[-re,-Q,-ee],[-k,-G,-q]];for(let Z=0;Z<2;Z++){let ae=E+Z*_,ie=N+Z*P,de=C+Z*R;for(let me=0;me<4;me++){let Se=te[me];p.push(ae+Se[0]*h,ie+Se[1]*h,de+Se[2]*h),g.push(Se[0],Se[1],Se[2]),x.push(me/4,Z)}}for(let Z=0;Z<4;Z++){let ae=(Z+1)%4;v.push(H+Z,H+ae,H+4+ae,H+Z,H+4+ae,H+4+Z)}}return p.length>0&&i.setFromBuffers(p,g,x,v),i}function d0(e,t=.05){let r=new Nt;r.__baked=!0;let i=e?.attributes?.position;if(!i?.array||i.count<1)return r;let n=i.array,a=i.count,s=Math.min(a,5e3),o=Math.max(.003,Math.min(.25,(Number(t)||.05)*.6)),l=[],c=[],f=[],m=[];for(let h=0;h<s;h++){let p=a<=5e3?h:Math.floor(h*a/s),g=n[p*3]||0,x=n[p*3+1]||0,v=n[p*3+2]||0,y=h*6;for(let A=0;A<6;A++){let b=_s[A*3],w=_s[A*3+1],S=_s[A*3+2];l.push(g+b*o,x+w*o,v+S*o),c.push(b,w,S),f.push(.5,.5)}for(let A=0;A<24;A++)m.push(y+wf[A])}return r.setFromBuffers(l,c,f,m),r}var kr=class extends qn{constructor(e,t,r="strip"){let i=t&&typeof t=="object"?t:{},n=t instanceof vn?t:r==="points"?new xi(i):new io(i),a=e instanceof Nt?e:new Nt;super(a,n),this.isLine=!0,this._lineMode=r,this._sourceGeo=a}computeLineDistances(){return this}_bakeAuthorGeometry(){this.geometry&&!this.geometry.__baked&&(this._sourceGeo=this.geometry);let e=this._lineMode==="points";if(e){let t=this._sourceGeo?.attributes?.color;if(t?.array&&t.count>0&&this.material?.color.r===1&&this.material.color.g===1&&this.material.color.b===1){let r=t.array,i=Math.min(t.count,64),n=0,a=0,s=0;for(let o=0;o<i;o++)n+=r[o*3]||0,a+=r[o*3+1]||0,s+=r[o*3+2]||0;this.material.color.setRGB(n/i,a/i,s/i)}}!this.geometry?.__baked&&this._sourceGeo?.attributes?.position?.count>=(e?1:2)&&(this.geometry=e?d0(this._sourceGeo,this.material?.size??.05):u0(this._sourceGeo,this._lineMode,this.material?.linewidth??1))}},ua=class extends kr{constructor(e,t){super(e,t,"loop"),this.isLineLoop=!0}},da=class extends kr{constructor(e,t){super(e,t,"segments"),this.isLineSegments=!0}},fa=class extends kr{constructor(e,t){super(e,t,"points"),this.isPoints=!0}},ma=class extends hi{constructor(e,t,r=0,i=Math.PI/3,n=0,a=2){super(e,t,r,a),this.target=new Fn,this.type="spot";let s=Number(i);this.angle=Number.isFinite(s)?Math.max(.01,Math.min(Math.PI/2,s)):Math.PI/3;let o=Number(n);this.penumbra=Number.isFinite(o)?Math.max(0,Math.min(1,o)):0}},vi=class extends cr{constructor(e,t,r){super(e,r),this.type="hemisphere",this.groundColor=new Bn(t??4473924),this.position.set(0,1,0)}},ha=class extends mi{constructor(e,t){Er("RectAreaLight","AmbientLight"),super(e,t)}},Mf={Vector2:tn,Vector3:Ze,Vector4:ks,Euler:si,Quaternion:no,Matrix4:_r,Matrix3:Rs,Color:Bn,MathUtils:cf,BufferAttribute:Vt,Float32BufferAttribute:Ls,Uint16BufferAttribute:Ps,Uint32BufferAttribute:Is,BufferGeometry:Nt,BoxGeometry:ai,PlaneGeometry:Cs,SphereGeometry:Ns,CylinderGeometry:ci,ConeGeometry:Ds,TorusGeometry:Us,TorusKnotGeometry:Bs,Curve:ar,Curve3:ar,LineCurve3:Fs,QuadraticBezierCurve3:Vs,CubicBezierCurve3:Os,CatmullRomCurve3:zs,LatheGeometry:li,TubeGeometry:$s,PolyhedronGeometry:lr,IcosahedronGeometry:ra,OctahedronGeometry:na,DodecahedronGeometry:oa,TetrahedronGeometry:ta,CapsuleGeometry:ia,RingGeometry:gi,CircleGeometry:sa,WireframeGeometry:ca,EdgesGeometry:la,FrontSide:0,BackSide:1,DoubleSide:2,NoBlending:0,NormalBlending:1,AdditiveBlending:2,MultiplyBlending:4,RepeatWrapping:1e3,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002,NearestFilter:1003,NearestMipmapNearestFilter:1004,NearestMipmapLinearFilter:1005,LinearFilter:1006,LinearMipmapNearestFilter:1007,LinearMipmapLinearFilter:1008,UnsignedByteType:1009,ByteType:1010,ShortType:1011,UnsignedShortType:1012,IntType:1013,UnsignedIntType:1014,FloatType:1015,HalfFloatType:1016,AlphaFormat:1021,RGBFormat:1022,RGBAFormat:1023,LuminanceFormat:1024,LuminanceAlphaFormat:1025,RedFormat:1028,RGFormat:1030,NoColorSpace:"",SRGBColorSpace:"srgb",LinearSRGBColorSpace:"srgb-linear",StaticDrawUsage:35044,DynamicDrawUsage:35048,ACESFilmicToneMapping:4,BasicShadowMap:0,PCFShadowMap:1,PCFSoftShadowMap:2,VSMShadowMap:3,Texture:ro,DataTexture:Gs,TextureLoader:js,Material:vn,MeshStandardMaterial:Fr,MeshBasicMaterial:Hs,MeshLambertMaterial:Ws,MeshPhongMaterial:Xs,MeshPhysicalMaterial:qs,PointsMaterial:xi,LineBasicMaterial:io,LineDashedMaterial:aa,ShaderMaterial:yi,RawShaderMaterial:vf,Object3D:Fn,Group:Ys,Mesh:qn,InstancedMesh:di,Line:kr,LineLoop:ua,LineSegments:da,Points:fa,LightShadow:fi,Light:cr,AmbientLight:mi,DirectionalLight:Ks,PointLight:hi,SpotLight:ma,HemisphereLight:vi,RectAreaLight:ha,Camera:pi,PerspectiveCamera:Js,Scene:bi,WebGLRenderer:Qs,Clock:Zs,SceneQuotaValidator:Xn,exportSceneToCanvas3D:nl,exportSceneToGLB:rl,exportSceneToUSDZ:df,generateUSDZ:Qo,glbToUSDZ:Jo,sceneToCanvas3D:Qr,sceneToGLB:qo,sceneToUSDZ:Ko,authorScriptRunner:so,warnUnsupported:Er,getAuthorWarnings:gf,clearAuthorWarnings:xf};Object.freeze(Xn),Object.freeze(Xn.prototype),Object.freeze(bi.prototype),Object.freeze(Mf);var Vr=new Proxy(Mf,{get:(e,t)=>{if(t in e)return e[t];let r=He().authorNamespace;return r&&typeof t=="string"&&t in r?r[t]:(typeof t=="string"&&t!=="then"&&t!=="toJSON"&&!t.startsWith("__")&&Er(`THREE.${t}`,"no-op proxy"),oi)},has:(e,t)=>{if(t in e)return!0;let r=He().authorNamespace;return!!(r&&typeof t=="string"&&t in r)},set:(e,t)=>{throw new TypeError(`Cannot assign to read only property '${String(t)}' of #<THREE>`)},defineProperty:(e,t)=>{throw new TypeError(`Cannot define property '${String(t)}', object is not extensible`)},deleteProperty:(e,t)=>{throw new TypeError(`Cannot delete property '${String(t)}' of #<THREE>`)},setPrototypeOf:()=>{throw new TypeError("#<THREE> is not extensible")}}),Es=He();if(Es.threeNamespace=Vr,Es.workerExtensionInstallers)for(let e of Es.workerExtensionInstallers)e(Vr,Es);var ii={name:"three_author",THREE:Vr},f0=ii,sr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;if(typeof sr.THREE>"u"&&(sr.THREE=Vr),typeof sr.requestAnimationFrame!="function"&&(sr.requestAnimationFrame=e=>(typeof e=="function"&&typeof sr.__three_live_raf_cb__!="function"&&(sr.__three_live_raf_cb__=e),sr.__three_live_in_step__||Er("requestAnimationFrame","single-frame static evaluation"),0)),typeof sr.cancelAnimationFrame!="function"&&(sr.cancelAnimationFrame=()=>{}),typeof window<"u"){let e=window;e.ThreeLive=e.ThreeLive||{},e.ThreeLive.THREE=Vr,e.ThreeLivePlugins=e.ThreeLivePlugins||{},e.ThreeLivePlugins.threeAuthor=ii,e.ThreeLivePlugins.three_author=ii,e.ThreeLivePlugins["three-author"]=ii}function ao(e,t){let r=e?.trim(),i=r?Number(r):NaN;return Number.isFinite(i)?i:t}var ll=(e,t,r)=>({x:e,y:t,z:r,toString:()=>`${e}m ${t}m ${r}m`}),m0=typeof HTMLElement<"u"?HTMLElement:class{};typeof CustomEvent>"u"&&typeof Event<"u"&&(globalThis.CustomEvent=class extends Event{constructor(e,t){super(e,t),this.detail=t?.detail??null}});var En=class Cn extends m0{constructor(){super(...arguments),this.viewer=null,this.canvas=null,this.posterEl=null,this.arButton=null,this.currentModel=null,this.activeXRSession=null,this.toastTimer=null,this.currentModelLimits=void 0,this.isModelLoaded=!1,this.scriptHandle=null,this.loadController=null,this.resizeObserver=null,this.mutationObserver=null}static get sandboxEngineSrc(){return He().sandboxEngineSrc??null}static set sandboxEngineSrc(t){He().sandboxEngineSrc=t}static get sandboxIframeSrc(){return He().sandboxIframeSrc??null}static set sandboxIframeSrc(t){He().sandboxIframeSrc=t}static get allowClientScripts(){return!!He().allowClientScripts}static set allowClientScripts(t){He().allowClientScripts=t}static registerScriptRunner(t){He().scriptRunner=t}static defineModelViewer(t="model-viewer"){if(typeof customElements>"u")return!1;let r=customElements.get(t);return r!=null?r===Cn||r.prototype instanceof Cn:(customElements.define(t,class extends Cn{}),!0)}static registerDecoder(t,r){Ht.registerDecoder(t,r)}static getDecoder(t){return Ht.getDecoder(t)}static registerAR(t){He().arProvider=typeof t=="function"?{activateAR:t}:t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(r=>{r instanceof Cn&&r.updateARButtonVisibility()})}static isARSupported(){return!!He().arProvider}getLoadedModel(){return this.currentModel}beginLoad(){let t=this.loadController,r=this.scriptHandle,i=new AbortController;return this.loadController=i,this.scriptHandle=null,t?.abort(),r?.terminate(),i}connectedCallback(){if(typeof document>"u")return;(!this.style.display||this.style.display==="inline")&&(this.style.display="block"),getComputedStyle(this).position==="static"&&(this.style.position="relative"),this.style.overflow="hidden",this.setupDOM(),this.initViewer(),this.setupResizeObserver();let t=this.getAttribute("src"),r=this.getAttribute("script-src");t?this.loadModel(t).catch(()=>{}):r?this.loadScriptFromSrc(r).catch(()=>{}):this.scheduleInlineScript();for(let i of Ht.getRegisteredPlugins())i.onElementConnected?.(this)}scheduleInlineScript(){let t=this.loadController,r=()=>{let i=this.querySelector('script[type="text/three"], script[type="text/three-live"]');return this.loadController===t&&i?.textContent?(this.executeScript(i.textContent).catch(()=>{}),!0):!1};queueMicrotask(()=>r()||document.addEventListener("DOMContentLoaded",r))}disconnectedCallback(){for(let t of Ht.getRegisteredPlugins())t.onElementDisconnected?.(this);this.beginLoad().abort(),this.mutationObserver?.disconnect(),this.mutationObserver=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.activeXRSession?.stop?.().catch?.(()=>{}),this.activeXRSession=null,this.toastTimer&&clearTimeout(this.toastTimer),this.toastTimer=null,this.viewer?.destroy(),this.viewer=null,this.isModelLoaded=!1}attributeChangedCallback(t,r,i){if(r===i)return;let n=this.viewer;switch(t){case"src":i&&this.loadModel(i).catch(()=>{});break;case"camera-target":{let a=this.parseCameraTarget(i);n&&a&&n.setTarget(a[0],a[1],a[2]);break}case"min-camera-orbit":case"max-camera-orbit":if(n){let a=this.parseOrbitLimit(this.getAttr("min-camera-orbit")),s=this.parseOrbitLimit(this.getAttr("max-camera-orbit"));n.setOrbitLimits({minTheta:a.theta,maxTheta:s.theta,minPhi:a.phi,maxPhi:s.phi,minDistance:a.distance,maxDistance:s.distance})}break;case"field-of-view":{let a=this.parseFieldOfView(i);n&&a!==void 0&&n.setFieldOfView(a);break}case"script-src":i&&this.loadScriptFromSrc(i).catch(()=>{});break;case"poster":this.updatePoster(i);break;case"camera-orbit":this.applyCameraOrbit(i);break;case"selected-mesh":n?.setSelectedMesh(i??"");break;case"exposure":if(n&&i!==null){let a=parseFloat(i);isNaN(a)||n.setExposure(a)}break;case"shadow-intensity":case"shadow-softness":n?.setShadow(this.shadowIntensity,this.shadowSoftness);break;case"tone-mapping":n?.setToneMapping(Dr(i));break;case"environment-image":n?.setEnvironmentImage(i).catch(()=>{});break;case"skybox-image":n?.setSkyboxImage?.(i)?.catch?.(()=>{});break;case"camera-controls":{let a=this.cameraControls;n?.setInteractive?.(a),this.canvas&&(this.canvas.style.touchAction=a?"none":"auto");break}case"autoplay":n?.setAutoplay(i!==null&&i!=="false");break;case"animation-name":n&&i!==null&&n.setAnimationName(i);break;case"variant-name":n&&this.selectVariant(i);break;case"auto-rotate":n?.setAutoRotate(i!==null&&i!=="false");break;case"auto-rotate-delay":n?.setAutoRotateDelay(this.autoRotateDelay);break;case"rotation-per-second":n?.setAutoRotateSpeed(this.parseRotationPerSecond(i));break;case"ar":this.updateARButtonVisibility();break;case"renderer":n?.render();break;case"shadow-maps":n&&(n.shadowMaps=i!==null?this.shadowMaps:void 0),n?.render();break}for(let a of Ht.getRegisteredPlugins())a.onAttributeChanged?.(this,t,r,i)}getAttr(t){return this.getAttribute(t)}setAttr(t,r){r!==null?this.setAttribute(t,String(r)):this.removeAttribute(t)}getBoolAttr(t){return this.hasAttribute(t)&&this.getAttr(t)!=="false"}setBoolAttr(t,r){this.setAttr(t,r?"":null)}getFloatAttr(t,r){let i=this.getAttr(t);return i!==null?parseFloat(i):r}get sandbox(){return this.getAttr("sandbox")||(He().sandboxIframeSrc?"iframe":"worker")}set sandbox(t){this.setAttr("sandbox",t)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||Cn.allowClientScripts}set allowClientScripts(t){this.setBoolAttr("allow-client-scripts",t)}get turntableRotation(){return this.viewer?this.viewer.turntableRotation:0}get ar(){return this.hasAttribute("ar")}set ar(t){this.setBoolAttr("ar",t)}get canActivateAR(){return Cn.isARSupported()}get toneMapping(){return Dr(this.getAttr("tone-mapping"))}set toneMapping(t){this.setAttr("tone-mapping",t)}get bloomThreshold(){return ao(this.getAttr("bloom-threshold"),.62)}set bloomThreshold(t){this.setAttr("bloom-threshold",t)}get bloomRadius(){return ao(this.getAttr("bloom-radius"),.75)}set bloomRadius(t){this.setAttr("bloom-radius",t)}get availableAnimations(){return this.viewer?this.viewer.getAvailableAnimations():[]}get variantName(){return this.viewer?this.viewer.getVariantName():this.getAttr("variant-name")}set variantName(t){this.setAttr("variant-name",t)}get availableVariants(){return this.viewer?this.viewer.getAvailableVariants():[]}get renderer(){let t=this.getAttr("renderer")?.trim().toLowerCase();return t==="webgpu"||t==="webgl2"?t:"auto"}set renderer(t){this.setAttr("renderer",t)}get shadowMaps(){let t=this.getAttr("shadow-maps")?.trim().toLowerCase();return t==="pcf"||t==="off"?t:"auto"}set shadowMaps(t){this.setAttr("shadow-maps",t)}fireEvent(t,r){this.dispatchEvent(new CustomEvent(t,{bubbles:!0,composed:!0,detail:r}))}setSlotVisible(t,r){let i=typeof this.querySelector=="function"?this.querySelector(`[slot="${t}"]`):null;i&&(i.hidden=!r,i.style&&(i.style.display=r?"":"none"))}emitError(t,r="script"){this.setSlotVisible("error",!0),this.fireEvent("error",{error:t}),this.fireEvent("three-error",{error:t,message:t?.message||String(t),stage:r})}selectVariant(t){if(!this.viewer)return!1;let r=this.viewer.selectVariant(t);return r&&this.fireEvent("variant-applied",{variantName:this.viewer.getVariantName()}),r}get model(){let t=this.viewer?this.viewer.getModelMaterials():[];return{materials:t,getMaterialByName(r){return t.find(i=>i.name===r)??null}}}play(){this.viewer?.playAnimation(this.animationName||void 0)}pause(){this.viewer?.pauseAnimation()}resetCamera(){this.viewer?.resetCamera()}resetTurntableRotation(t=0){this.viewer?.resetTurntableRotation(t)}setCamera(t,r,i,n){this.viewer?.setCamera(t,r,i,n)}getCameraOrbit(){return this.viewer?.getCameraOrbit()??{theta:0,phi:0,radius:3,toString:()=>"0rad 0rad 3m"}}getCameraTarget(){return this.viewer?this.viewer.getCameraTarget():ll(0,0,0)}getFieldOfView(){return this.viewer?this.viewer.getFieldOfView():45}jumpCameraToGoal(){this.viewer?.jumpCameraToGoal()}toDataURL(t,r){return this.viewer?.render?.(),this.canvas?this.canvas.toDataURL(t,r):""}toBlob(t){return this.viewer?.render?.(),new Promise((r,i)=>{if(!this.canvas||typeof this.canvas.toBlob!="function"){i(new Error("Canvas toBlob is not supported in this environment."));return}this.canvas.toBlob(n=>{n?r(n):i(new Error("Failed to capture canvas blob."))},t?.mimeType,t?.qualityArgument)})}positionAndNormalFromPoint(t,r){let i=this.viewer?.raycastFromScreenPoint(t,r);if(!i)return null;let[n,a,s]=i.hitPoint||i.point,[o,l,c]=i.normal;return{position:ll(n,a,s),normal:ll(o,l,c)}}loadModel(t){return this.loadModelWithLimits(t)}async loadModelWithLimits(t,r,i=this.beginLoad()){if(i.signal.throwIfAborted(),!this.viewer){this.currentModel=t,this.currentModelLimits=r;return}try{let n;if(typeof t=="string"){let l=await fetch(t,{signal:i.signal});if(!l.ok)throw new Error(`Failed to load "${t}": HTTP ${l.status}`);n=await l.arrayBuffer()}else n=t;i.signal.throwIfAborted();let a=wr(n);this.viewer.loadGLBData(a,r),this.currentModel=a,this.currentModelLimits=r,this.isModelLoaded=!0,this.hidePoster(),this.setSlotVisible("error",!1),this.updateHotspots();let s=this.getAttr("selected-mesh");s&&this.viewer.setSelectedMesh(s);let o=this.getAttr("variant-name");o&&this.selectVariant(o),this.fireEvent("load",{model:a}),this.fireEvent("three-load",{model:a,source:typeof t=="string"?"src":"model"})}catch(n){throw i.signal.aborted||this.emitError(n,"load"),n}}showToast(t,r=4500){if(typeof document>"u")return;let i=this.querySelector(".three-live-toast");i||(i=document.createElement("div"),i.className="three-live-toast",i.style.cssText="position:absolute;bottom:70px;left:50%;transform:translateX(-50%) translateY(10px);z-index:10;padding:10px 16px;background:rgba(15,23,42,.94);color:#f8fafc;border:1px solid rgba(56,189,248,.45);border-radius:14px;font:500 13px/1.35 system-ui,-apple-system,sans-serif;box-shadow:0 10px 25px rgba(0,0,0,.45);backdrop-filter:blur(12px);pointer-events:none;opacity:0;transition:opacity .25s,transform .25s;max-width:88%;text-align:center;white-space:normal;word-break:break-word",this.appendChild(i)),i.textContent=t,this.toastTimer&&clearTimeout(this.toastTimer);let n=()=>{i&&(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)")};typeof requestAnimationFrame<"u"?requestAnimationFrame(n):n(),this.toastTimer=setTimeout(()=>{i&&(i.style.opacity="0",i.style.transform="translateX(-50%) translateY(10px)"),this.toastTimer=null},r)}async activateAR(){this.activeXRSession?.isSessionActive?.()&&(await this.activeXRSession.stop().catch(()=>{}),this.activeXRSession=null);let t=(a,s=a.message)=>{throw this.fireEvent("ar-status",{status:"failed",error:a}),this.showToast(s,6e3),a};this.currentModel||t(new Error("No 3D model is loaded in <three-live>."));let r=He().arProvider;r||t(new Error("AR module not bundled. Use the default 'three-live' bundle or call ThreeLiveElement.registerAR()."));let i=this.getAttr("ios-src"),n=(this.getAttr("ar-modes")||"").split(/\s+/).filter(Boolean);try{this.fireEvent("ar-status",{status:"session-started"});let a=await r.activateAR({model:i||this.currentModel,glbUrl:typeof this.currentModel=="string"?this.currentModel:void 0,view:this.viewer||void 0,element:this,preferredModes:n.length>0?n:void 0,arScale:this.arScale,arPlacement:this.arPlacement,webXROptions:{onExit:()=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"not-presenting"})},onError:s=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"failed",error:s}),this.showToast(`AR error: ${s.message}`,6e3)}}});if(a.success){a.session&&(this.activeXRSession=a.session);let s={"quick-look":"Opening Apple AR Quick Look...","scene-viewer":"Opening Google Scene Viewer...",webxr:"WebXR AR session started."}[a.mode||""]||"";s&&this.showToast(s)}else{let s=a.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.";if(this.isDesktopMac()&&typeof document<"u"&&this.currentModel&&r.createUSDZBlob)try{let o=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:r.createUSDZBlob(this.currentModel),l=URL.createObjectURL(o),c=document.createElement("a");c.href=l,c.download="three_live_model.usdz",document.body.appendChild(c),c.click(),document.body.removeChild(c),setTimeout(()=>URL.revokeObjectURL(l),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(s,6e3)}else this.showToast(s,6e3);a.error&&this.fireEvent("ar-status",{status:"failed",error:a.error})}return a}catch(a){return this.activeXRSession=null,t(a,`AR error: ${a.message||String(a)}`)}}setupDOM(){let t=this.querySelector("canvas");t||(t=document.createElement("canvas"),t.style.cssText=`width:100%;height:100%;display:block;touch-action:${this.cameraControls?"none":"auto"};outline:none`,this.appendChild(t)),this.canvas=t,typeof t.addEventListener=="function"&&!t.__tlCtxBound&&(t.__tlCtxBound=!0,t.addEventListener("webglcontextlost",i=>this.fireEvent("three-context-lost",{originalEvent:i})),t.addEventListener("webglcontextrestored",i=>this.fireEvent("three-context-restored",{originalEvent:i}))),this.setSlotVisible("error",!1),this.isModelLoaded||this.setSlotVisible("poster",!0);let r=this.getAttr("poster");r&&this.updatePoster(r),this.createARButton(),typeof MutationObserver<"u"&&!this.mutationObserver&&(this.mutationObserver=new MutationObserver(()=>{this.updateARButtonVisibility()}),this.mutationObserver.observe(this,{childList:!0}))}initViewer(){if(!this.canvas)return;this.viewer=new Ht(this,this.canvas,{autoRotate:this.autoRotate,autoRotateDelay:this.autoRotateDelay,autoRotateSpeed:this.parseRotationPerSecond(this.getAttr("rotation-per-second")),exposure:this.exposure,shadowIntensity:this.shadowIntensity,shadowSoftness:this.shadowSoftness,shadowMaps:this.hasAttribute("shadow-maps")?this.shadowMaps:void 0,toneMapping:this.toneMapping,environmentImage:this.environmentImage,autoplay:this.autoplay,animationName:this.animationName||void 0,variantName:this.getAttr("variant-name")||void 0,fieldOfView:this.parseFieldOfView(this.getAttr("field-of-view")),cameraTarget:this.parseCameraTarget(this.getAttr("camera-target")),minCameraOrbit:this.parseOrbitLimit(this.getAttr("min-camera-orbit")),maxCameraOrbit:this.parseOrbitLimit(this.getAttr("max-camera-orbit")),onMeshClick:r=>{this.fireEvent("meshclick",r)},onCameraChange:r=>{this.updateHotspots();for(let i of Ht.getRegisteredPlugins())i.onCameraChange?.(this.viewer,this);this.fireEvent("camera-change",r)}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let t=this.getAttr("camera-orbit");t&&this.applyCameraOrbit(t),this.currentModel&&this.loadModelWithLimits(this.currentModel,this.currentModelLimits)}setupResizeObserver(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>{this.viewer&&(this.viewer.resize(),this.viewer.render(),this.updateHotspots())}),this.resizeObserver.observe(this))}updatePoster(t){if(!(typeof document>"u")){if(!t){this.posterEl&&(this.posterEl.remove(),this.posterEl=null);return}this.posterEl||(this.posterEl=document.createElement("img"),this.posterEl.alt="3D Scene Preview",this.posterEl.style.cssText="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity .35s ease-out;pointer-events:none;z-index:1",this.appendChild(this.posterEl)),this.posterEl.src=t,this.isModelLoaded||(this.posterEl.style.opacity="1")}}hidePoster(){this.setSlotVisible("poster",!1),this.posterEl&&(this.posterEl.style.opacity="0",setTimeout(()=>{this.isModelLoaded&&this.posterEl&&(this.posterEl.remove(),this.posterEl=null)},400))}isDesktopMac(){let t=typeof navigator<"u"&&navigator.userAgent||"";return/Macintosh/i.test(t)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1)&&!/Android|iPhone|iPad|iPod/i.test(t)}syncARButtonLabel(t){let r=this.isDesktopMac(),i=r?"Quick Look (.usdz)":"View in AR",n=r?"Download .usdz preview for macOS Quick Look (live camera AR requires iOS or Android)":"View in Augmented Reality";typeof t.setAttribute=="function"&&(t.setAttribute("aria-label",n),t.setAttribute("title",n));let a=t._labelSpan||(typeof t.querySelector=="function"?t.querySelector("span"):null);a&&(a.textContent=i)}createARButton(){if(!(typeof document>"u")){if(!this.arButton){let t=document.createElement("button");t.type="button",t.className="three-live-ar-button",t.setAttribute("part","default-ar-button");let r="http://www.w3.org/2000/svg";if(typeof document.createElementNS=="function"){let n=document.createElementNS(r,"svg");for(let[s,o]of Object.entries({width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"}))n.setAttribute(s,o);n.style.marginRight="6px";let a=document.createElementNS(r,"path");a.setAttribute("d","M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16zM3.27 6.96 12 12.01l8.73-5.05M12 22.08V12"),n.appendChild(a),t.appendChild(n)}let i=document.createElement("span");t._labelSpan=i,t.appendChild(i),this.syncARButtonLabel(t),t.style.cssText="position:absolute;right:16px;bottom:16px;z-index:2;align-items:center;justify-content:center;padding:8px 16px;background-color:rgba(15,23,42,.85);color:#fff;border:1px solid rgba(255,255,255,.15);border-radius:9999px;font:600 13px system-ui,-apple-system,sans-serif;cursor:pointer;backdrop-filter:blur(8px);box-shadow:0 4px 12px rgba(0,0,0,.25);transition:transform .15s,background-color .15s;display:none";for(let[n,a,s]of[["mouseenter","rgba(30, 41, 59, 0.95)","scale(1.04)"],["mouseleave","rgba(15, 23, 42, 0.85)","scale(1)"]])t.addEventListener(n,()=>{t.style.backgroundColor=a,t.style.transform=s});t.addEventListener("click",n=>{n.stopPropagation(),this.activateAR()}),this.arButton=t,this.appendChild(t)}this.updateARButtonVisibility()}}updateARButtonVisibility(){let t=this.hasAttribute("ar")&&Cn.isARSupported(),r=typeof this.querySelector=="function"?this.querySelector('[slot="ar-button"]'):null;r?(this.arButton&&(this.arButton.style.display="none"),r.__tlARBound||(r.__tlARBound=!0,r.addEventListener("click",i=>{i.stopPropagation(),this.activateAR()})),r.dataset.tlOrigDisplay===void 0&&(r.dataset.tlOrigDisplay=r.style.display==="none"?"":r.style.display),r.style.display=t?r.dataset.tlOrigDisplay||"":"none"):this.arButton&&(this.syncARButtonLabel(this.arButton),this.arButton.style.display=t?"flex":"none")}applyCameraOrbit(t){if(!(!t||!this.viewer))try{let r=JSON.parse(t);this.viewer.setInitialCamera(r.theta,r.phi,r.distance,r.zoom)}catch{let r=this.parseOrbitLimit(t);(r.theta!==void 0||r.phi!==void 0)&&this.viewer.setInitialCamera(r.theta,r.phi,r.distance)}}parseOrbitLimit(t){if(!t)return{};let[r,i,n]=t.trim().split(/\s+/),a=n&&n!=="auto"?parseFloat(n):NaN;return{theta:r&&r!=="auto"?this.parseFieldOfView(r):void 0,phi:i&&i!=="auto"?this.parseFieldOfView(i):void 0,distance:isNaN(a)?void 0:a}}parseCameraTarget(t){if(!t)return;let r=t.trim().split(/\s+/).map(parseFloat);return r.length>=3&&!r.some(isNaN)?[r[0],r[1],r[2]]:void 0}parseFieldOfView(t){if(!t)return;let r=parseFloat(t);return isNaN(r)?void 0:t.endsWith("rad")?r*180/Math.PI:r}parseRotationPerSecond(t){if(!t)return Math.PI/6;let r=t.trim(),i=parseFloat(r);return isNaN(i)?Math.PI/6:r.endsWith("rad")?i:r.endsWith("%")?i/100*Math.PI*2:i*Math.PI/180}updateHotspot(t){let r=this.querySelector(`[slot="${t.name}"]`);r&&(t.position!==void 0&&r.setAttribute("data-position",t.position),t.normal!==void 0&&r.setAttribute("data-normal",t.normal)),this.updateHotspots()}updateHotspots(){for(let t of Ht.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}runWithScriptRunner(t){let r=He().scriptRunner;if(!r){let a=new Error('Script execution requires "three-live/full" or registerScriptRunner().');return this.showToast(a.message),this.emitError(a,"script"),Promise.reject(a)}let i=this.beginLoad(),n=()=>!i.signal.aborted;return new Promise((a,s)=>{let o=()=>s(i.signal.reason);if(i.signal.addEventListener("abort",o,{once:!0}),!n()){o();return}let l={onModelReady:c=>{this.loadModelWithLimits(c,Nd,i).then(()=>a(c),s)},onUpdateTransforms:c=>{n()&&this.viewer?.updateMeshTransforms(c)},onError:c=>{n()&&(this.showToast(c.message),this.emitError(c,"script"),s(c))},onToast:c=>{n()&&this.showToast(c)}};t(r,l).then(c=>{n()?this.scriptHandle=c||null:c?.terminate()},c=>{n()&&l.onError?.(c)})})}loadScriptFromSrc(t){return this.runWithScriptRunner((r,i)=>{if(typeof r.executeUrl!="function"){let n=new Error("Registered ScriptRunner does not support executeUrl() for server-generated scripts.");return i.onError?.(n),Promise.reject(n)}return r.executeUrl(t,this.sandbox,i)})}executeScript(t){if(!He().scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(os);return this.showToast(is),this.emitError(r,"security"),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(t,this.sandbox,i,{allowClientScripts:!0}))}};En.observedAttributes="src ios-src script-src sandbox allow-client-scripts poster camera-controls camera-orbit camera-target min-camera-orbit max-camera-orbit field-of-view selected-mesh ar ar-modes ar-scale ar-placement exposure shadow-intensity shadow-softness tone-mapping bloom bloom-threshold bloom-radius outline outline-selected outline-color environment-image skybox-image autoplay animation-name variant-name auto-rotate auto-rotate-delay rotation-per-second renderer shadow-maps".split(" "),En.registerPlugin=Ht.registerPlugin,En.getRegisteredPlugins=Ht.getRegisteredPlugins;var kn=En;{let e=kn.prototype,t=(i,n,a)=>Object.defineProperty(e,i,{get:n,set:a,configurable:!0}),r=i=>i.replace(/[A-Z]/g,n=>"-"+n.toLowerCase());for(let i of"src cameraOrbit cameraTarget minCameraOrbit maxCameraOrbit fieldOfView iosSrc scriptSrc poster selectedMesh environmentImage skyboxImage animationName".split(" ")){let n=r(i);t(i,function(){return this.getAttr(n)},function(a){this.setAttr(n,a)})}for(let i of"cameraControls autoRotate outlineSelected autoplay".split(" ")){let n=r(i);t(i,function(){return this.getBoolAttr(n)},function(a){this.setBoolAttr(n,a)})}for(let[i,n]of[["exposure",1],["autoRotateDelay",3e3],["shadowIntensity",0],["shadowSoftness",.5],["bloom",0]]){let a=r(i);t(i,function(){return this.getFloatAttr(a,n)},function(s){this.setAttr(a,s)})}for(let[i,n]of[["rotationPerSecond","30deg"],["arScale","auto"],["arPlacement","floor"],["outlineColor","#38bdf8"]]){let a=r(i);t(i,function(){return this.getAttr(a)||n},function(s){this.setAttr(a,s)})}}typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",kn);function Af(e="model-viewer"){return kn.defineModelViewer(e)}var xl={eye:[0,1.6,5],target:[0,.8,0]},Pf=new Set("the a an please can could would you will i want wanna to me my that this those these of one ones object objects thing things item items mesh meshes piece pieces part parts just only also too is are there here which select pick choose highlight grab focus on in at by some most side hand them it its and s now again as well other others".split(" ")),h0=["sofa couch settee","lamp light lantern","door gate doorway","table desk","chair seat stool","rug carpet mat","cup mug","tv television screen monitor","car vehicle automobile","box crate cube","ball sphere orb","floor ground","plant tree bush","cabinet cupboard closet"].map(e=>e.split(" ")),ga=[["red",[220,40,40],"red"],["orange",[245,140,30],"orange"],["yellow",[240,220,40],"yellow"],["gold",[212,175,55],"yellow"],["green",[50,170,60],"green"],["teal",[0,128,128],"green"],["cyan",[40,200,220],"blue"],["blue",[40,80,220],"blue"],["navy",[20,30,100],"blue"],["purple",[130,50,180],"purple"],["magenta",[220,40,200],"pink"],["pink",[240,120,180],"pink"],["brown",[130,80,40],"brown"],["beige",[225,205,160],"brown"],["white",[245,245,245],"white"],["silver",[192,192,192],"gray"],["gray",[128,128,128],"gray"],["black",[20,20,20],"black"]],Tf={grey:"gray",golden:"gold",crimson:"red",maroon:"red",violet:"purple",aqua:"cyan",turquoise:"cyan",tan:"beige"},pl={};function Vn(e,t){for(let r of e.split(" "))pl[r]=t}Vn("left leftmost",["right",!1]),Vn("right rightmost",["right",!0]),Vn("front nearest closest frontmost",["depth",!1]),Vn("back farthest furthest rear far backmost",["depth",!0]),Vn("top highest upper topmost",["up",!0]),Vn("bottom lowest lower bottommost",["up",!1]),Vn("biggest largest big large huge bigger larger",["size",!0]),Vn("smallest small tiny little smaller",["size",!1]),Vn("tallest tall taller",["height",!0]),Vn("shortest short shorter",["height",!1]),Vn("middle center centre central","middle");var _f={first:0,second:1,third:2,fourth:3,fifth:4,last:-1},Ef={two:2,pair:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10},If=new Set(["all","every","everything","each","everybody"]),bl=e=>/^[0-9]+$/.test(e),xa=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),vl=e=>xa(pl,e)?pl[e]:null,Cf=e=>xa(_f,e)?_f[e]:null;function Nf(e){let t;if(xa(Ef,e))t=Ef[e];else if(/^[0-9]{1,3}$/.test(e))t=Number(e);else return null;return t>=1&&t<=50?t:null}function Df(e){return xa(Tf,e)?Tf[e]:ga.some(t=>t[0]===e)?e:null}function p0(e){for(let t=0;t<e.length;t++){let r=e[t],i=e[t+1]??"";if(/^(near|nearby|beside|behind|under|underneath|beneath|above|below|between|inside|within|against|with|beyond|around)$/.test(r)||(r==="next"||r==="close")&&i==="to"||(r==="front"||r==="top")&&i==="of")return!0;if(r==="on"||r==="by"){let n=t+1;for(;n<e.length&&/^(the|a|an|its|my)$/.test(e[n]);)n++;let a=e[n];if(a!==void 0&&!vl(a)&&a!=="side"&&a!=="end")return!0}}return!1}function b0(e){return String(e??"").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function Uf(e){let t=e.length;if(t>4&&e.endsWith("ies"))return e.slice(0,-3)+"y";if(t>4&&e.endsWith("ves"))return e.slice(0,-3)+"f";for(let r of["ches","shes","xes","sses","zes"])if(t>r.length+1&&e.endsWith(r))return e.slice(0,-2);return t>3&&e.endsWith("s")&&!e.endsWith("ss")&&!e.endsWith("us")?e.slice(0,-1):e}function y0(e){let t=[],r="",i="",n=o=>o>="a"&&o<="z",a=o=>o>="A"&&o<="Z",s=o=>o>="0"&&o<="9";for(let o of String(e)){if(!(n(o)||a(o)||s(o))){r&&t.push(r),r="",i="";continue}i&&r&&(n(i)&&a(o)||s(i)!==s(o))&&(t.push(r),r=""),r+=o.toLowerCase(),i=o}return r&&t.push(r),t.map(Uf)}var g0=e=>e.replace(/[^A-Za-z0-9]/g,"").toLowerCase(),x0=(e,t)=>h0.some(r=>r.includes(e)&&r.includes(t));function kf(e,t){return e===t||x0(e,t)||t.length>=4&&e.length>=4&&(e.startsWith(t)||t.startsWith(e))}function fl(e){let t=Math.min(1,Math.max(0,Number.isFinite(e)?e:0));return(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)*255}function v0(e){let t=[fl(e[0]),fl(e[1]),fl(e[2])],r=ga[0][0],i=1/0;for(let[n,a]of ga){let s=(t[0]-a[0])**2+(t[1]-a[1])**2+(t[2]-a[2])**2;s<i&&(i=s,r=n)}return r}var w0=e=>ga.find(t=>t[0]===e)?.[2]??"";function S0(e,t){return e.words.includes(t)?!0:e.colorName!=null&&(e.colorName===t||w0(e.colorName)===t)}function wi(e){return e.map((t,r)=>{let i=[0,1,2].map(n=>Math.abs(t.max[n]-t.min[n]));return{id:r,name:t.name,words:y0(t.name),colorName:t.color?v0(t.color):null,size:Math.max(i[0],.01)*Math.max(i[1],.01)*Math.max(i[2],.01),height:i[1],center:[0,1,2].map(n=>(t.min[n]+t.max[n])/2)}})}function M0(e){let t=[0,1,2].map(s=>e.target[s]-e.eye[s]),r=Math.hypot(t[0],t[1],t[2]),i=r<1e-9?[0,0,-1]:t.map(s=>s/r),n=[-i[2],0,i[0]],a=Math.hypot(n[0],n[1],n[2]);return{eye:e.eye,right:a<1e-9?[1,0,0]:n.map(s=>s/a)}}function co(e,t,r){let i=[0,1,2].map(n=>e.center[n]-r.eye[n]);switch(t){case"right":return i[0]*r.right[0]+i[1]*r.right[1]+i[2]*r.right[2];case"depth":return Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]);case"up":return e.center[1];case"size":return e.size;default:return e.height}}var Bf=e=>e.length?e.reduce((t,r)=>t+r,0)/e.length:0;function ml(e,t,r){let i;if(t==="middle"){if(e.length<3)return e;let n=e.map(o=>co(o,"right",r)),a=Math.min(...n),s=Math.max(...n);i=e.filter((o,l)=>n[l]>a+1e-6&&n[l]<s-1e-6)}else{let n=e.map(s=>co(s,t[0],r)),a=Bf(n);i=e.filter((s,o)=>t[1]?n[o]>a+1e-6:n[o]<a-1e-6)}return i.length?i:e}function Rf(e,t,r){let i;if(t==="middle"){let n=Bf(e.map(a=>co(a,"right",r)));i=e.map(a=>[a,Math.abs(co(a,"right",r)-n)])}else i=e.map(n=>[n,t[1]?-co(n,t[0],r):co(n,t[0],r)]);return i.sort((n,a)=>n[1]-a[1])}function un(e,t,r){let i=[...e].sort((s,o)=>s.id-o.id),n=[...new Set(i.map(s=>s.id))],a=[];for(let s of i)!a.includes(s.name)&&a.length<50&&a.push(s.name);return t==="high"?{ids:n,names:a,confidence:t,candidates:[],reason:r}:t==="ambiguous"?{ids:[],names:[],confidence:t,candidates:a.slice(0,10),reason:r}:{ids:[],names:[],confidence:t,candidates:[],reason:r}}var Or=e=>un([],"none",e);function va(e,t,r=xl,i){let n=i?e.filter(s=>i.includes(s.name)):[...e],a=b0(t);for(let s=0;s<a.length;s++){let o=a[s],l=a[s+1]??"",c=o==="except"||o==="excluding";if(!(c||o==="but"&&l==="not"||o==="other"&&l==="than"))continue;let f=hl(n,a.slice(0,s),r);if(f.confidence!=="high")return f;let m=n.filter(g=>f.ids.includes(g.id)),h=hl(m,a.slice(s+(c?1:2)),r);if(h.confidence!=="high")return un(m,"ambiguous","except");let p=m.filter(g=>!h.ids.includes(g.id));return p.length?un(p,"high","match"):Or("no_match")}return hl(n,a,r)}function A0(e){return!(Pf.has(e)||If.has(e)||e==="both"||Nf(e)!==null||Cf(e)!==null||Df(e)!==null||vl(e)!==null||bl(e))}function hl(e,t,r){let i=[[]];for(let l of t)l==="and"?i.push([]):i[i.length-1].push(l);let n=i.filter(l=>l.length);if(n.length<2||!n.every(l=>l.some(A0)))return Lf(e,t,r);let a=[],s=!1;for(let l of n){let c=Lf(e,l,r);if(c.confidence==="none")return c;c.confidence==="ambiguous"?(s=!0,a.push(...e.filter(f=>c.candidates.includes(f.name)))):a.push(...e.filter(f=>c.ids.includes(f.id)))}let o=[...new Map(a.map(l=>[l.id,l])).values()];return s?un(o,"ambiguous","multiple"):un(o,"high","match")}function Lf(e,t,r){if(!e.length)return Or("no_match");let i=0;for(;i<t.length&&/^(select|pick|choose|highlight|grab|the|a|an|just|only)$/.test(t[i]);)i++;let n=t.slice(i).join("");if(n){let y=e.filter(A=>g0(A.name)===n);if(y.length)return un(y,"high","exact")}if(p0(t))return Or("relation");let a=[],s=!1,o=!1,l=null,c=null,f=[],m=[],h=!1;for(let y of t){if(h&&bl(y)){a.push(y);continue}h=!1;let A,b,w;if(If.has(y))o=!0,s=!0;else if(y==="both")l=2,s=!0;else if((A=Nf(y))!==null)l=A,s=s||A>1;else if((A=Cf(y))!==null)c=A;else if((b=Df(y))!==null)f.push(b);else if((w=vl(y))!==null)m.push(w);else if(!Pf.has(y)){let S=Uf(y);S!==y&&(s=!0),a.push(S),h=!0}}if(!a.length&&!f.length&&!m.length&&c===null&&!o&&l===null)return Or("empty");let p=M0(r),g=e;if(a.length){let y=g.map(S=>({e:S,n:a.filter(E=>S.words.some(N=>kf(N,E))).length})),A=Math.max(0,...y.map(S=>S.n));if(A===0)return Or("no_match");g=y.filter(S=>S.n===A).map(S=>S.e);let b=S=>S.words.filter(E=>!bl(E)&&!a.some(N=>kf(E,N))).length,w=Math.min(...g.map(b));g=g.filter(S=>b(S)===w)}if(f.length&&(g=g.filter(y=>f.some(A=>S0(y,A)))),!g.length)return Or("no_match");if(c!==null){for(let w of m)g=ml(g,w,p);let y=Rf(g,["right",!1],p),A=Math.min(l??1,y.length),b;if(c<0)b=y.slice(y.length-A);else{let w=c*(l!==null?A:1);if(w>=y.length)return Or("no_match");b=y.slice(w,w+A)}return un(b.map(w=>w[0]),"high","match")}let x=!s&&l===null,v=x?1:o?null:l;if(v!==null&&m.length){for(let b of m.slice(0,-1))g=ml(g,b,p);let y=Rf(g,m[m.length-1],p),A=v;if(y.length<A)return un(y.map(b=>b[0]),"ambiguous","count_mismatch");if(y.length>A&&Math.abs(y[A][1]-y[A-1][1])<=1e-6){let b=y[A-1][1];return un(y.filter(w=>Math.abs(w[1]-b)<=1e-6).map(w=>w[0]),"ambiguous","multiple")}return un(y.slice(0,A).map(b=>b[0]),"high","match")}for(let y of m)g=ml(g,y,p);return x?g.length===1?un(g,"high","match"):un(g,"ambiguous","multiple"):l!==null&&g.length!==l?un(g,"ambiguous","count_mismatch"):un(g,"high","match")}var Ff="make paint color colour turn move rotate scale resize delete remove change set add put give raise lower shrink enlarge hide show swap replace spin flip double halve duplicate copy animate brighten darken".split(" "),ba=(e,t)=>{for(let r of t)if(e.startsWith(r))return e.slice(r.length).trim()||null;return null},yl=(e,t)=>{for(let r of t)if(e.endsWith(r))return e.slice(0,-r.length).trim()||null;return null},gl=e=>e.replace(/[.!?,]+$/,"");function T0(e){let t=e.split(" ");for(let r=0;r<t.length;r++){let i=t[r].endsWith(","),n=r>0&&(t[r]==="and"||t[r]==="then");if(!(i||n))continue;let a=r+1;for(;a<t.length&&(t[a]==="then"||t[a]==="and");)a++;if(a>=t.length||!Ff.includes(t[a]))continue;let s=(n?t.slice(0,r):t.slice(0,r+1)).join(" ").replace(/,+$/,"").trim();if(s)return[s,t.slice(a).join(" ")]}return[e,null]}function Vf(e,t){let r=e.split(/\s+/).filter(Boolean);return r.length&&gl(r[r.length-1]).toLowerCase()==="please"&&r.pop(),gl(r.slice(Math.max(0,r.length-t)).join(" "))}function ya(e,t,r){let[i,n]=T0(t),a=yl(i,[" too"," as well"," also"]);if(a!==null&&e==="replace"&&(e="add",i=a),n!==null){let s=n.split(/\s+/).filter(Boolean).length;return{kind:"mixed",mode:e,query:i,instruction:Vf(r,s)}}return{kind:"select",mode:e,query:i}}var _0=["please ","ok ","ok, ","okay ","okay, ","now ","now, ","hey ","um ","um, ","uh ","uh, ","so ","so, ","and "],E0=new Set(["clear selection","clear the selection","reset selection","reset the selection","select nothing","select none","deselect","deselect all","deselect everything","unselect","unselect all","unselect everything","clear","clear all"]),k0=["select only ","select just ","only select ","just select ","select ","pick ","choose ","highlight ","grab ","focus on "];function wa(e){let t=String(e??"").trim(),r=t.toLowerCase().replace(/[\u2018\u2019]/g,"'").split(/\s+/).filter(Boolean).join(" ");for(r=gl(r);;){let n=r.length;for(let a of _0)r.startsWith(a)&&(r=r.slice(a.length));if(r.endsWith(" please")&&(r=r.slice(0,-7).replace(/,+$/,"")),r.length===n)break}if(r=r.trim(),E0.has(r))return{kind:"clear",mode:"clear"};let i=ba(r,["deselect ","unselect ","don't select ","do not select "]);if(i!==null)return ya("remove",i,t);for(let n of["remove ","take "])if(r.startsWith(n)){let a=yl(r.slice(n.length),[" from the selection"," from selection"," out of the selection"]);if(a!==null)return{kind:"select",mode:"remove",query:a}}if(i=ba(r,["also select ","also pick ","also choose ","also add "]),i!==null)return ya("add",i,t);if(r.startsWith("add ")){let n=yl(r.slice(4),[" to the selection"," to selection"]);if(n!==null)return{kind:"select",mode:"add",query:n}}return i=ba(r,k0),i!==null||(i=ba(r,["just ","only "]),i!==null&&!Ff.includes(i.split(" ")[0]))?ya("replace",i,t):{kind:"edit",instruction:Vf(t,1/0)}}var Of=50;function wl(e){let t=[];for(let r of e){let i=typeof r=="string"?r.slice(0,200):"";if(i&&!t.includes(i)&&t.push(i),t.length>=Of)break}return t}function nn(e){let t=e.__tlSelection??[],r=e.selectedMesh||null;return(t[0]??null)!==r?r?[r]:[]:[...t]}function rn(e,t,r={}){let i=r.mode??"replace",n=nn(e),a=wl(typeof t=="string"?[t]:t??[]),s;switch(i){case"clear":s=[];break;case"add":s=wl([...n,...a]);break;case"remove":s=n.filter(f=>!a.includes(f));break;case"toggle":s=wl([...n.filter(f=>!a.includes(f)),...a.filter(f=>!n.includes(f))]);break;default:s=a}let o=s.filter(f=>!n.includes(f)),l=n.filter(f=>!s.includes(f));if(!o.length&&!l.length&&s.join(`
|
|
403
|
+
`)===n.join(`
|
|
404
|
+
`))return null;e.__tlSelection=s,e.selectedMesh=s[0]??null,e.viewer?.setSelectedMeshes?.(s);let c={mesh:s[0]??null,meshes:s,added:o,removed:l,source:r.source??"api",...r.query?{query:String(r.query).slice(0,2e3)}:{}};return e.fireEvent?.("three-live-select",c),c}function zf(e){!e||e.__tlSelectionInstalled||(e.__tlSelectionInstalled=!0,"selectedMeshes"in e||Object.defineProperty(e,"selectedMeshes",{get:()=>nn(e),set:t=>{rn(e,t??[],{mode:"replace",source:"api"})},configurable:!0}),e.addEventListener?.("three-load",()=>{let t=nn(e);t.length>1&&e.viewer?.setSelectedMeshes?.(t)}))}function Si(e){if(!e.length)return"The user cleared the selection.";if(e.length===1)return`The user selected the mesh "${e[0]}". "This" or "it" now refers to it.`;let t=e.slice(0,20).map(i=>`"${i}"`),r=e.length>20?` and ${e.length-20} more`:"";return`The user selected ${e.length} meshes: ${t.join(", ")}${r}. "These", "them", or "it" refer to them.`}var Sl=new WeakMap;function R0(e){let t=e;if(Sl.has(t))return Sl.get(t);let r=[1/0,1/0,1/0],i=[-1/0,-1/0,-1/0];for(let a=0;a+2<e.length;a+=3)for(let s=0;s<3;s++){let o=e[a+s];o<r[s]&&(r[s]=o),o>i[s]&&(i[s]=o)}let n=Number.isFinite(r[0])?[r,i]:null;return Sl.set(t,n),n}function uo(e){let t=e.viewer?.meshes??[],r=[];for(let i of t.slice(0,5e3)){if(!i?.name||i.visible===!1)continue;let n=i.transform,a=[1/0,1/0,1/0],s=[-1/0,-1/0,-1/0];for(let l of i.primitives??[]){let c=l.positions?R0(l.positions):null;if(c)for(let f=0;f<8;f++){let m=c[f&1?1:0][0],h=c[f&2?1:0][1],p=c[f&4?1:0][2];for(let g=0;g<3;g++){let x=n?n[g]*m+n[4+g]*h+n[8+g]*p+n[12+g]:[m,h,p][g];x<a[g]&&(a[g]=x),x>s[g]&&(s[g]=x)}}}if(!Number.isFinite(a[0]))continue;let o=i.primitives?.[0]?.baseColor;r.push({name:i.name,min:a,max:s,color:o?[o[0],o[1],o[2]]:null})}return r}function Sa(e){let t=e.viewer,r=t?.getCameraOrbit?.(),i=t?.getCameraTarget?.();if(!r||!i||![r.theta,r.phi,r.radius,i.x,i.y,i.z].every(Number.isFinite))return xl;let n=r.radius*Math.cos(r.phi);return{eye:[i.x+n*Math.sin(r.theta),i.y+r.radius*Math.sin(r.phi),i.z+n*Math.cos(r.theta)],target:[i.x,i.y,i.z]}}function Ma(e,t,r={}){let i=wi(uo(e));return va(i,t,Sa(e),r.within??null)}var L0=["You find the objects a user means in a 3D scene.",'Reply with JSON only: {"ids": [numbers], "confidence": "high" or "low", "question": "text"}.',"Use only ids from the objects list.",`Left and right are as seen from the camera: "right" is the camera's right direction.`,'If several objects fit equally, or none fits, set confidence to "low" and ask one short question that names the options.'].join(" "),lo=e=>Math.round(e*100)/100;function Ml(e,t,r,i=[]){let n=[0,1,2].map(o=>r.target[o]-r.eye[o]),a=Math.hypot(n[2],n[0])||1,s={camera:{eye:r.eye.map(lo),target:r.target.map(lo),right:[lo(-n[2]/a),0,lo(n[0]/a)]},objects:e.slice(0,300).map(o=>({id:o.id,name:o.name,color:o.colorName,center:o.center.map(lo),size:lo(Math.cbrt(o.size))})),selected:i.slice(0,50),request:String(t).slice(0,500)};return[{role:"system",content:L0},{role:"user",content:JSON.stringify(s)}]}function Al(e,t){let r=String(e??""),i=r.indexOf("{"),n=r.lastIndexOf("}"),a={};if(i>=0&&n>i)try{a=JSON.parse(r.slice(i,n+1))??{}}catch{}let s=[];for(let l of Array.isArray(a.ids)?a.ids:[]){let c=Number.isInteger(l)?t[l]:void 0;c&&!s.includes(c.name)&&s.length<Of&&s.push(c.name)}let o=(typeof a.question=="string"?a.question:"").replace(/[\u0000-\u001f\u007f]+/g," ").trim().slice(0,300);return{names:s,confidence:a.confidence==="high"&&s.length?"high":"low",question:o}}async function Aa(e,t,r,i={}){let n=uo(e);i.within&&(n=n.filter(o=>i.within.includes(o.name)));let a=wi(n);if(!a.length)return{names:[],confidence:"low",question:""};let s=await r.complete({messages:Ml(a,t,Sa(e),nn(e)),signal:i.signal});return Al(s,a)}var P0=32,I0=32,C0=80,jf=2e3,_a=32*1024*1024,N0=1024,D0=256,U0=2048,Tl=["You reconstruct a 3D scene from a reference image into a Three.js script for Three-Live, which compiles it to glTF for Web, Android, and iOS.","Reply with the COMPLETE script in a single ```js code block and nothing else.","Rules:","- Use the pre-defined globals `THREE`, `scene`, and `camera`. No imports, renderer, loaders, DOM, network, or timers.","- Decompose visible objects into `THREE.Group` and `THREE.Mesh` hierarchies with a unique, descriptive `.name` on every Mesh and Group (for example `Table`, `Chair_Left`, `Desk_Lamp`) before attaching `userData.xr` or `userData.interactivity`.","- Use real-world meters (1 unit = 1 m), +Y up, with the floor or resting surface at y = 0 (or the given metric floorY).","- When metric spatial priors (floor height, camera pose, planes, or 3D object boxes) are provided, place meshes at those exact metric [x, y, z] coordinates, dimensions, and yaw angles, and set `mesh.userData.xr = { grab: true }` on movable props.","- Supported: core geometries (`BoxGeometry`, `SphereGeometry`, `CylinderGeometry`, `ConeGeometry`, `CapsuleGeometry`, `PlaneGeometry`, `TorusGeometry`, `LatheGeometry`, `ExtrudeGeometry`, `TubeGeometry`, `Shape`, `Path`), `THREE.CSG`, `MeshStandardMaterial` / `MeshPhysicalMaterial` / `MeshStandardNodeMaterial` (loop-free `THREE.TSL`), `THREE.CanvasTexture`, `THREE.ProceduralTexture` presets (`wood`, `marble`, `brick`, `concrete`, `brushedMetal`, `rust`, `leather`, `fabric`, `carbonFiber`, `checkerboard`, `grid`), lights (`AmbientLight`, `HemisphereLight`, `DirectionalLight`, `PointLight`, `SpotLight`), and canonical `node.userData.xr` traits (`grab`, `anchor`, `physics`, `joint`, `handles`, `dimensions`, `billboard`, `orbit`, `follow`).","- Always include balanced lighting (`AmbientLight` or `HemisphereLight` plus a `DirectionalLight` or `PointLight`) and frame `camera.position.set(x, y, z)` and `camera.lookAt(tx, ty, tz)` so 100% of meshes are inside the camera frustum."].join(`
|
|
405
|
+
`);function $f(e){if(typeof e!="string")return"";let t="",r=!0;for(let i of e){let n=i.charCodeAt(0);n<=32||n===127||i==='"'||/\s/.test(i)?r||(t+=" ",r=!0):(t+=i,r=!1)}return Array.from(t.trim()).slice(0,C0).join("")}function ur(e){let t=Math.round(e*100)/100;return(Object.is(t,-0)||Math.abs(t)<1e-9?0:t).toFixed(2)}function Gf(e){let t=Math.round(e),r=Object.is(t,-0)?0:t;return String(r)}function fo(e){if(!Array.isArray(e)||e.length<3)return null;let t=Number(e[0]),r=Number(e[1]),i=Number(e[2]);return!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(i)?null:[t,r,i]}function B0(e){if(!Array.isArray(e)||e.length<2)return null;let t=Number(e[0]),r=Number(e[1]);return!Number.isFinite(t)||!Number.isFinite(r)||t<=0||r<=0?null:[t,r]}function F0(e){let t=fo(e);return!t||t[0]<=0||t[1]<=0||t[2]<=0?null:t}function Mi(e){return`[${ur(e[0])}, ${ur(e[1])}, ${ur(e[2])}]`}function Ea(e){if(!e||typeof e!="object")return"";let t=[];if(typeof e.floorY=="number"&&Number.isFinite(e.floorY)&&t.push(`- Floor height: y = ${ur(e.floorY)} m`),e.camera&&typeof e.camera=="object"){let r=fo(e.camera.eye),i=fo(e.camera.target);if(r&&i){let n=`- Camera: eye ${Mi(r)}, target ${Mi(i)}`,a=Number(e.camera.fovDeg);Number.isFinite(a)&&a>=1&&a<=179&&(n+=`, fov ${Gf(a)} deg`),t.push(n)}}if(Array.isArray(e.planes)){let r=[];for(let i of e.planes){if(r.length>=P0)break;if(!i||typeof i!="object")continue;let n=fo(i.center);if(!n)continue;let a=String(i.orientation??"").toLowerCase()==="vertical"?"vertical":"horizontal",s=$f(i.label),o=B0(i.extent),l=fo(i.normal),c=` ${r.length+1}. ${a}`;s&&(c+=` "${s}"`),c+=` at ${Mi(n)}`,o&&(c+=`, extent ${ur(o[0])}m x ${ur(o[1])}m`),l&&(c+=`, normal ${Mi(l)}`),r.push(c)}r.length>0&&t.push("- Planes:",...r)}if(Array.isArray(e.objects)){let r=[];for(let i of e.objects){if(r.length>=I0)break;if(!i||typeof i!="object")continue;let n=$f(i.label),a=fo(i.center);if(!n||!a)continue;let s=F0(i.size),o=typeof i.yawDeg=="number"&&Number.isFinite(i.yawDeg)?i.yawDeg:null,l=` ${r.length+1}. "${n}" at ${Mi(a)}`;s&&(l+=`, size ${ur(s[0])}m x ${ur(s[1])}m x ${ur(s[2])}m`),o!==null&&(l+=`, yaw ${Gf(o)} deg`),r.push(l)}r.length>0&&t.push("- Detected 3D objects (place meshes at these metric bounds):",...r)}return t.length===0?"":`Metric spatial priors (world meters, +Y up):
|
|
406
|
+
${t.join(`
|
|
407
|
+
`)}
|
|
408
|
+
`}function On(e){let t=String(e??"").trim();if(!t)return!1;if(/^data:image\/(png|jpeg|jpg|webp);base64,[A-Za-z0-9+/=\s]+$/i.test(t)){let r=t.indexOf(",");return r>0&&t.slice(r+1).trim().length>0}if(/[\s\x00-\x1f\x7f]/.test(t))return!1;try{let r=new URL(t);return r.protocol==="https:"?!!r.hostname:r.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(r.hostname)}catch{return!1}}function _l(e,t){let r=`Reconstruct the 3D scene shown in this reference image as a complete Three-Live script.
|
|
409
|
+
`;r+=Ea(t);let i=Array.from(String(e??"").trim()).slice(0,jf).join("");return i&&(r+=`Additional instructions: ${i}
|
|
410
|
+
`),r+="Return only the complete script in a single ```js code block.",r}function El(e,t,r){let i=String(e??"").trim();if(!On(i))throw new Error("compileFromImage: imageUrl must be a base64 data:image/(png|jpeg|webp) URI or an https:// URL.");let n=_l(t,r);return[{role:"system",content:Tl},{role:"user",content:[{type:"image_url",image_url:{url:i}},{type:"text",text:n}]}]}function kl(e,t){let r=String(e??"").trim(),i=(t??[]).map(n=>String(n??"").trim()).filter(Boolean).slice(0,20);if(r){let n=`That script was rejected by the Three-Live sandbox: ${r}
|
|
411
|
+
`;return i.length>0&&(n+=`Additional diagnostics:
|
|
412
|
+
${i.map(a=>`- ${a}`).join(`
|
|
413
|
+
`)}
|
|
414
|
+
`),n+="Return the complete corrected script in a single ```js code block.",n}return i.length>0?`The script compiled, but the Three-Live linter reported warnings that should be fixed:
|
|
415
|
+
${i.map(n=>`- ${n}`).join(`
|
|
416
|
+
`)}
|
|
417
|
+
Fix every warning above (assign unique \`.name\` values before attaching \`userData.xr\`, use only canonical \`userData.xr\` traits, replace unsupported classes with supported Three-Live primitives, and frame \`camera.position\` and \`camera.lookAt\` so all meshes are inside the frustum) while keeping the full scene intact.
|
|
418
|
+
Return the complete corrected script in a single \`\`\`js code block.`:"Return the complete corrected script in a single ```js code block."}function Rl(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":null}function V0(e){let t=globalThis;if(t.Buffer&&typeof t.Buffer.from=="function")return t.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64");let r="",i=8192;for(let n=0;n<e.length;n+=i){let a=e.subarray(n,Math.min(n+i,e.length));r+=String.fromCharCode(...a)}return btoa(r)}function O0(e){let t=Number(e);return Number.isFinite(t)?Math.max(D0,Math.min(U0,Math.round(t))):N0}function Ta(e){if(e.byteLength===0)throw new Error("compileFromImage: image buffer is empty.");if(e.byteLength>_a)throw new Error("compileFromImage: image exceeds the 32 MB limit.");let t=Rl(e);if(!t)throw new Error("compileFromImage: unsupported image format (expected PNG, JPEG, or WebP magic bytes).");return`data:${t};base64,${V0(e)}`}function z0(e,t,r,i){let n=Math.max(t,r),a=n>i?i/n:1,s=Math.max(1,Math.round(t*a)),o=Math.max(1,Math.round(r*a)),l=e;if(a===1&&typeof l.toDataURL=="function")try{let c=l.toDataURL("image/jpeg",.88);if(On(c))return c}catch{}if(typeof document<"u"&&typeof document.createElement=="function")try{let c=document.createElement("canvas");if(c&&typeof c.getContext=="function"){c.width=s,c.height=o;let f=c.getContext("2d");if(f&&typeof f.drawImage=="function"&&(f.drawImage(e,0,0,s,o),typeof c.toDataURL=="function")){let m=c.toDataURL("image/jpeg",.88);if(On(m))return m}}}catch{}if(typeof l.toDataURL=="function")try{let c=l.toDataURL("image/jpeg",.88);if(On(c))return c}catch{}return null}async function ka(e,t={}){if(t.signal?.aborted)throw t.signal.reason??new Error("compileFromImage aborted");if(e==null)throw new Error("compileFromImage: image input is required.");let r=O0(t.maxEdge);if(typeof e=="string"){let s=e.trim();if(!s)throw new Error("compileFromImage: image input is empty.");if(/^data:/i.test(s)){if(!On(s))throw new Error("compileFromImage: data URI must be a base64-encoded image/png, image/jpeg, or image/webp.");let p=s.indexOf(","),g=s.slice(0,p).toLowerCase().replace("image/jpg","image/jpeg"),x=s.slice(p+1).replace(/\s+/g,"");if(Math.floor(x.length*3/4)>_a)throw new Error("compileFromImage: image exceeds the 32 MB limit.");return`${g},${x}`}if(/^(javascript|vbscript|file|ftp|ws|wss):/i.test(s))throw new Error("compileFromImage: unsupported or unsafe image URL scheme.");if(/^http:/i.test(s)&&!On(s))throw new Error("compileFromImage: remote image URLs must use https:// (or http:// on localhost).");let o=/^https?:/i.test(s)&&On(s);if(o&&!t.fetch)return s;let l=s;if(!/^https?:|^blob:/i.test(s)){let p=globalThis.location?.href;if(!p)throw new Error("compileFromImage: imageUrl must be a base64 data:image/(png|jpeg|webp) URI or an https:// URL.");if(l=new URL(s,p).href,!/^blob:/i.test(l)&&!On(l))throw new Error("compileFromImage: resolved image URL must use https:// (or http:// on localhost).")}let c=t.fetch??globalThis.fetch?.bind(globalThis);if(typeof c!="function"){if(o)return s;throw new Error("compileFromImage: no fetch() implementation is available.")}let f=await c(l,{mode:"cors",credentials:"omit",signal:t.signal});if(!f.ok)throw new Error(`compileFromImage: failed to fetch image (HTTP ${f.status}).`);let m=Number(f.headers?.get?.("content-length"));if(Number.isFinite(m)&&m>_a)throw new Error("compileFromImage: image exceeds the 32 MB limit.");let h=await f.arrayBuffer();if(t.signal?.aborted)throw t.signal.reason??new Error("compileFromImage aborted");return Ta(new Uint8Array(h))}if(e instanceof ArrayBuffer||Object.prototype.toString.call(e)==="[object ArrayBuffer]")return Ta(new Uint8Array(e));if(ArrayBuffer.isView(e))return Ta(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));if(typeof Blob<"u"&&e instanceof Blob||typeof e.arrayBuffer=="function"){let s=e;if(typeof s.size=="number"&&s.size>_a)throw new Error("compileFromImage: image exceeds the 32 MB limit.");let o=await s.arrayBuffer();if(t.signal?.aborted)throw t.signal.reason??new Error("compileFromImage aborted");return Ta(new Uint8Array(o))}let i=e,n=Number(i.videoWidth||i.naturalWidth||i.width||0),a=Number(i.videoHeight||i.naturalHeight||i.height||0);if(n>0&&a>0){let s=z0(e,n,a,r);if(s)return s}if(typeof i.toDataURL=="function"){let s=i.toDataURL("image/jpeg",.88);if(On(s))return s}if(typeof i.src=="string"&&i.src.trim())return ka(i.src,t);throw new Error("compileFromImage: unsupported or unloaded image source.")}async function Ra(e,t,r={}){if(!e?.allowClientScripts)throw new Error("compileFromImage requires client scripts: add the allow-client-scripts attribute.");let i=La(e,r,"compileFromImage"),n=Pa(e);e.__tlAiAbort?.abort(new Error("compileFromImage superseded by a newer call"));let a=new AbortController;e.__tlAiAbort=a;let s=()=>a.abort(r.signal?.reason);r.signal?.aborted&&s(),r.signal?.addEventListener("abort",s,{once:!0});let o=a.signal,l=Array.from(String(r.prompt??"").trim()).slice(0,jf).join(""),c=Ea(r.priors).length>0,f=Math.max(0,Math.min(3,Math.floor(Number(r.maxRepairs??1))||0)),m="",h="",p=[],g=0,x=null;try{let y=await ka(t,{maxEdge:r.maxEdge,signal:o,fetch:r.fetch});if(o.aborted)throw o.reason;let A=El(y,l,r.priors);e.fireEvent?.("three-live-image-start",{prompt:l,hasPriors:c});for(let b=0;b<=f;b++){let w=await i.complete({messages:A,signal:o});if(o.aborted)throw o.reason;if(m=Ai(w),p=[],!m)h="The model reply did not contain a scene script.";else if(new TextEncoder().encode(m).length>Ll)h="The generated script exceeds the 1 MB script limit.";else try{let S=await Cl(e,m,o,"compileFromImage");p=[...S.warnings];let E=Il(S.model);E.unnamedXrNodes>0&&!p.some(N=>N.includes("TL204"))&&p.push("[TL204] Node with userData.xr is missing a unique .name."),E.meshes===0?h="The generated scene contains no meshes.":(h="",x={code:m,warnings:[...p]})}catch(S){if(o.aborted)throw o.reason;let E=S,N=String(E?.message||S);h=E?.name&&E.name!=="Error"&&!N.startsWith(E.name)?`${E.name}: ${N}`:N}if(!h&&p.length===0)break;b<f&&(g++,A.push({role:"assistant",content:w},{role:"user",content:kl(h,p)}))}}finally{r.signal?.removeEventListener("abort",s),e.__tlAiAbort===a&&(e.__tlAiAbort=null)}if(h&&x&&(m=x.code,p=x.warnings,h=""),!h&&!r.dryRun)try{if(await e.executeScript(m),n.trim()){let y=e.__tlAiHistory??(e.__tlAiHistory=[]);y.push(n),y.length>Pl&&y.shift()}e.__tlAiSource=m,rn(e,[],{mode:"clear",source:"api"})}catch(y){h=`The generated scene compiled but failed to load: ${y?.message||String(y)}`,e.__tlAiSource=n,n.trim()&&e.executeScript(n).catch(()=>{})}let v={applied:!h,code:m,repairs:g,warnings:p,...h?{error:h}:{}};return e.fireEvent?.("three-live-image",{prompt:l,...v}),v}var Nl="three-live-texture-pack",Dl=1,Hf=64,Wf=6*1024*1024,Ia=16*1024*1024,$0=64*1024*1024,Bl=" Seamless tileable PBR albedo texture, flat even lighting, orthographic top-down view, no perspective, no shadows, no text.";function Yf(){return He()}function Kf(e){let t=Yf().canonicalTextureSpec;if(typeof t!="function")throw new Error("AI textures need the procedural plugin (three-live-procedural.min.js or a full bundle).");return t(e)}function G0(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)}catch{return!1}}function Ca(e,t){let r=e.replace(/\s+/g,"");if(r.length>Math.ceil(t*4/3)+4)throw new Error("image exceeds the size limit");let i=atob(r),n=new Uint8Array(i.length);for(let a=0;a<i.length;a++)n[a]=i.charCodeAt(a);return n}function j0(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}async function H0(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e&&typeof e.arrayBuffer=="function")return new Uint8Array(await e.arrayBuffer());throw new Error("image provider returned no image bytes")}function Fl(e){let t=String(e?.endpoint??"");if(!G0(t))throw new Error("ai-image: endpoint must be an https:// URL (or http:// on localhost).");let r=e.fetch??globalThis.fetch?.bind(globalThis);if(typeof r!="function")throw new Error("ai-image: no fetch() implementation is available.");let i=Math.max(1e3,Number(e.timeoutMs)||12e4),n=new URL(t).origin;return{name:"openai-images",model:e.model,async generateImage({prompt:a,signal:s}){let o=new AbortController,l=()=>o.abort(s?.reason);s?.aborted&&l(),s?.addEventListener("abort",l,{once:!0});let c=setTimeout(()=>o.abort(new Error(`ai-image: timed out after ${i} ms`)),i);try{let f={prompt:a+Bl,n:1,size:e.imageSize||"1024x1024"};e.model&&(f.model=e.model),e.responseFormat!==null&&(f.response_format=e.responseFormat??"b64_json");let m=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...e.headers},body:JSON.stringify(f),signal:o.signal}),h=await m.text();if(!m.ok)throw new Error(`ai-image: HTTP ${m.status} from endpoint: ${h.slice(0,300)}`);let p;try{p=JSON.parse(h)}catch{throw new Error("ai-image: endpoint returned non-JSON content.")}let g=p?.data?.[0];if(typeof g?.b64_json=="string")return Ca(g.b64_json,Ia);let x=typeof g?.url=="string"?g.url:"";if(x.startsWith("data:image/"))return Ca(x.slice(x.indexOf(",")+1),Ia);if(x){let v=!1;try{v=new URL(x,t).origin===n}catch{}if(!e.allowResponseUrls||!v)throw new Error('ai-image: the endpoint returned an image URL; use response_format "b64_json" (or allowResponseUrls for same-origin URLs).');let y=await r(new URL(x,t).href,{signal:o.signal});if(!y.ok)throw new Error(`ai-image: HTTP ${y.status} fetching the image.`);let A=new Uint8Array(await y.arrayBuffer());if(A.length>Ia)throw new Error("ai-image: image exceeds 16 MB.");return A}throw new Error("ai-image: response had no image.")}finally{clearTimeout(c),s?.removeEventListener("abort",l)}}}}function Jf(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?"png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"webp":null}var Ei={async decode(e){let t=Jf(e);if(!t)throw new Error("image must be PNG, JPEG, or WebP");let r=new Blob([e],{type:`image/${t}`}),i=await createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"}),{width:n,height:a}=i,s=(typeof OffscreenCanvas<"u"?new OffscreenCanvas(n,a):Object.assign(document.createElement("canvas"),{width:n,height:a})).getContext("2d",{willReadFrequently:!0});if(!s)throw new Error("2D canvas unavailable for image decoding");s.drawImage(i,0,0),i.close?.();let o=s.getImageData(0,0,n,a).data;return{width:n,height:a,rgba:new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}},async encodePng(e,t){let r=Yf().encodeRgbaPngDataUri;if(typeof r=="function"){let i=r(e,t,t),n=Ca(i.slice(i.indexOf(",")+1),1/0),a=He().makePngDeflater?.(globalThis.CompressionStream);return a?a.png(n):n}throw new Error("PNG encoding needs the procedural plugin")}};function W0(e,t,r,i,n){let a=new Uint8Array(i*n*4);for(let s=0;s<n;s++){let o=Math.floor(s*r/n),l=Math.min(r,Math.max(o+1,Math.floor((s+1)*r/n)));for(let c=0;c<i;c++){let f=Math.floor(c*t/i),m=Math.min(t,Math.max(f+1,Math.floor((c+1)*t/i))),h=0,p=0,g=0,x=0,v=0;for(let A=o;A<l;A++)for(let b=f;b<m;b++){let w=(A*t+b)*4;h+=e[w],p+=e[w+1],g+=e[w+2],x+=e[w+3],v++}let y=(s*i+c)*4;a[y]=Math.floor((h+v/2)/v),a[y+1]=Math.floor((p+v/2)/v),a[y+2]=Math.floor((g+v/2)/v),a[y+3]=Math.floor((x+v/2)/v)}}return a}function X0(e,t){let r=Math.max(1,Math.floor(t/8)),i=Math.floor(t/2),n=s=>{let o=Math.max(0,Math.min(1,s));return o*o*(3-2*o)},a=new Uint8Array(t*t*4);for(let s=0;s<t;s++){let o=(Math.min(s,t-1-s)+.5)/r;for(let l=0;l<t;l++){let c=(Math.min(l,t-1-l)+.5)/r,f=1-n(Math.min(c,o)),m=(s*t+l)*4,h=((s+i)%t*t+(l+i)%t)*4;for(let p=0;p<3;p++){let g=e[m+p];a[m+p]=Math.max(0,Math.min(255,Math.floor(g+(e[h+p]-g)*f+.5)))}a[m+3]=255}}return a}function Vl(e,t){let r=Math.min(e.width,e.height);if(!(r>0))throw new Error("generated image is empty");let i=Math.floor((e.width-r)/2),n=Math.floor((e.height-r)/2),a=new Uint8Array(r*r*4);for(let o=0;o<r;o++){let l=((n+o)*e.width+i)*4;a.set(e.rgba.subarray(l,l+r*4),o*r*4)}let s=r===t?a:W0(a,r,r,t,t);for(let o=3;o<s.length;o+=4)s[o]=255;return X0(s,t)}async function Ol(e,t=Ei){let r=typeof e=="string"?JSON.parse(e):e;if(!r||r.format!==Nl)throw new Error(`texture pack: format must be "${Nl}"`);if(r.version!==Dl)throw new Error(`texture pack: version must be ${Dl}`);if(!r.entries||typeof r.entries!="object"||Array.isArray(r.entries))throw new Error("texture pack: entries must be an object");let i=Object.keys(r.entries);if(i.length>Hf)throw new Error(`texture pack: more than ${Hf} entries`);let n=new Map;for(let a of i){let s=r.entries[a];if(!/^[0-9a-f]{16}$/.test(a))throw new Error(`texture pack: invalid key '${a}'`);let o=Kf(s?.spec);if(!o)throw new Error(`texture pack: entry ${a}: invalid spec`);if(o.key!==a)throw new Error(`texture pack: entry ${a}: key does not match its spec (${o.key})`);let l=typeof s?.albedo=="string"?s.albedo:"",c="data:image/png;base64,";if(!l.startsWith(c))throw new Error(`texture pack: entry ${a}: albedo must be a data:image/png;base64 URL`);let f=Ca(l.slice(c.length),Wf);if(f.length>Wf||Jf(f)!=="png")throw new Error(`texture pack: entry ${a}: albedo is not a PNG within 6 MB`);let m=await t.decode(f);if(m.width!==o.size||m.height!==o.size)throw new Error(`texture pack: entry ${a}: albedo is ${m.width}x${m.height}, expected ${o.size}x${o.size}`);let h=new Uint8Array(m.rgba);for(let g=3;g<h.length;g+=4)h[g]=255;let p=s.provenance&&typeof s.provenance=="object"?s.provenance:void 0;n.set(a,{key:a,spec:{prompt:o.prompt,size:o.size,seed:o.seed},rgba:h,...p?{provenance:p}:{}})}return n}async function zl(e,t=Ei){let r={};for(let i of[...e.keys()].sort()){let n=e.get(i),a=await t.encodePng(n.rgba,n.spec.size);r[i]={spec:n.spec,albedo:`data:image/png;base64,${j0(a)}`,...n.provenance?{provenance:n.provenance}:{}}}return{format:Nl,version:Dl,entries:r}}function q0(e){let t=e?.gltf;if(t)return t;if(e instanceof ArrayBuffer&&e.byteLength>=20){let r=new DataView(e);if(r.getUint32(0,!0)===1179937895)try{return JSON.parse(new TextDecoder().decode(new Uint8Array(e,20,r.getUint32(12,!0))))}catch{}}return null}function Na(e){let t=new Map;for(let r of q0(e)?.nodes??[]){let i=r?.extras?.xr?.material;if(!i||typeof i!="object"||i.prompt==null)continue;let n=Kf(i);if(!n)continue;let a=t.get(n.key)??{spec:{prompt:n.prompt,size:n.size,seed:n.seed},meshes:[]};typeof r.name=="string"&&r.name&&a.meshes.push(r.name),t.set(n.key,a)}return[...t].map(([r,i])=>({key:r,spec:i.spec,meshes:i.meshes}))}function $l(e=$0){if(typeof indexedDB>"u")return null;let t=null,r=()=>t??(t=new Promise((n,a)=>{let s=indexedDB.open("three-live-textures",1);s.onupgradeneeded=()=>{s.result.createObjectStore("textures",{keyPath:"key"})},s.onsuccess=()=>n(s.result),s.onerror=()=>a(s.error)})),i=(n,a)=>r().then(s=>new Promise((o,l)=>{let c=s.transaction("textures",n),f=a(c.objectStore("textures"));c.oncomplete=()=>o(f?f.result:void 0),c.onerror=()=>l(c.error)}));return{async get(n){try{let a=await i("readonly",s=>s.get(n));return!a||!(a.rgba instanceof Uint8Array)?null:(i("readwrite",s=>s.put({...a,t:Date.now()})).catch(()=>{}),a)}catch{return null}},async put(n){try{await i("readwrite",l=>l.put({...n,t:Date.now()}));let a=await i("readonly",l=>l.getAll())??[],s=a.reduce((l,c)=>l+(c.rgba?.byteLength??0),0);a.sort((l,c)=>l.t-c.t);let o=[];for(let l of a){if(s<=e)break;s-=l.rgba?.byteLength??0,o.push(l.key)}o.length&&await i("readwrite",l=>{for(let c of o)l.delete(c)})}catch{}}}}var Ti=null,Xf=!1;function Yn(e){return e.__tlTex??(e.__tlTex={pack:new Map,packJson:null,failed:new Set,inflight:new Map,lastModel:null,lastRun:null,cache:void 0,loadSeq:0})}function Y0(e){let t=e.__tlTex;if(!t||t.pack.size===0)return null;let r={};for(let[i,n]of t.pack)r[i]={size:n.spec.size,rgba:n.rgba};return r}function K0(){let e=He(),t=e.scriptRunner;if(!t||t.__tlTexWrapped)return;let r=i=>Ti&&!i?.texturePack?{...i,texturePack:Ti}:i;e.scriptRunner={__tlTexWrapped:!0,execute:(i,n,a,s)=>t.execute(i,n,a,r(s)),...typeof t.executeUrl=="function"?{executeUrl:(i,n,a,s)=>t.executeUrl(i,n,a,r(s))}:{}}}function Gl(e,t){K0();let r=Ti;Ti=Y0(e);try{return t()}finally{Ti=r}}function Qf(e,t){let r=t??e.aiImageProvider;if(r&&typeof r.generateImage=="function")return r;let i=e.getAttribute?.("ai-image-endpoint");return i?Fl({endpoint:i,model:e.getAttribute?.("ai-image-model")||void 0}):null}function Zf(e){if(e.textureCache!==void 0)return e.textureCache;let t=Yn(e);return t.cache===void 0&&(t.cache=$l()),t.cache}function jl(e){return e.textureCodec??Ei}function _i(e){let t=e.querySelector?.('script[type="text/three"], script[type="text/three-live"]')?.textContent,r=Yn(e).lastRun??(t?{kind:"script",value:t}:null);return r?r.kind==="url"&&typeof e.loadScriptFromSrc=="function"?e.loadScriptFromSrc(r.value):e.executeScript(r.value):Promise.resolve()}function em(e,t){let r=Yn(e);r.pack.set(t.key,t),r.packJson=null,r.failed.delete(t.key)}async function tm(e,t){let r=Zf(e);if(!r)return[];let i=[];for(let n of t){let a=await r.get(n.key);a&&a.spec?.size===n.spec.size&&a.rgba?.length===n.spec.size*n.spec.size*4&&(em(e,{key:n.key,spec:n.spec,rgba:a.rgba,provenance:a.provenance}),e.fireEvent?.("three-live-texture",{key:n.key,meshes:n.meshes,source:"cache"}),i.push(n.key))}return i}async function nm(e,t,r,i){let n=Yn(e),a=n.inflight.get(r.key);if(a)return a;let s=(async()=>{try{let o=await H0(await t.generateImage({...r.spec,signal:i}));if(o.length>Ia)throw new Error("generated image exceeds 16 MB");let l=Vl(await jl(e).decode(o),r.spec.size),c={provider:t.name??"custom",...t.model?{model:t.model}:{},createdAt:new Date().toISOString()};return em(e,{key:r.key,spec:r.spec,rgba:l,provenance:c}),Zf(e)?.put({key:r.key,spec:r.spec,rgba:l,provenance:c}),e.fireEvent?.("three-live-texture",{key:r.key,meshes:r.meshes,source:"provider"}),!0}catch(o){return n.failed.add(r.key),e.fireEvent?.("three-live-texture-error",{key:r.key,meshes:r.meshes,error:String(o?.message||o)}),!1}finally{n.inflight.delete(r.key)}})();return n.inflight.set(r.key,s),s}async function J0(e,t,r){let i=0,n=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;)await r(e[i++])});await Promise.all(n)}function Hl(e,t){let r=Yn(e);r.lastModel=t;let i;try{i=Na(t).filter(a=>!r.pack.has(a.key))}catch{return}let n=i.filter(a=>!r.failed.has(a.key)&&!r.inflight.has(a.key));n.length&&(async()=>{if((await tm(e,n)).length){await _i(e).catch(()=>{});return}if((e.getAttribute?.("ai-textures")||"auto").toLowerCase()==="manual")return;let a=Qf(e);if(!a)return;e.fireEvent?.("three-live-texture-start",{keys:n.map(o=>o.key)});let s=(await Promise.all(n.map(o=>nm(e,a,o)))).filter(Boolean).length;s&&(Xf||(Xf=!0,console.info(`[three-live] Generated ${s} AI texture(s) at runtime. Each visitor without a cached copy triggers new (and different) generations. For consistent results, save el.exportTexturePack() and load it via texture-pack.`)),await _i(e).catch(()=>{}))})()}function Wl(e,t){Yn(e).lastRun=t}async function Ul(e,t){let r=Yn(e),i=++r.loadSeq;if(t==null){r.pack=new Map,r.packJson=null,await _i(e).catch(()=>{});return}try{let n=await Ol(t,jl(e));if(i!==r.loadSeq)return;r.pack=n,r.packJson=typeof t=="string"?JSON.parse(t):t,r.failed.clear(),await _i(e).catch(()=>{})}catch(n){e.fireEvent?.("three-live-texture-error",{key:null,meshes:[],error:String(n?.message||n)})}}async function qf(e,t){try{let r=typeof document<"u"?document.baseURI:void 0,i=await fetch(new URL(t,r).href,{credentials:"same-origin"});if(!i.ok)throw new Error(`HTTP ${i.status} loading texture-pack "${t}"`);await Ul(e,await i.json())}catch(r){e.fireEvent?.("three-live-texture-error",{key:null,meshes:[],error:String(r?.message||r)})}}async function Q0(e,t={}){let r=Yn(e),i=t.meshes?new Set(t.meshes):null,n=Na(r.lastModel).filter(c=>(t.force||!r.pack.has(c.key))&&(!i||c.meshes.some(f=>i.has(f)))),a=[],s=[],o=[],l=n;if(!t.force){let c=new Set(await tm(e,n));a.push(...c),l=n.filter(f=>!c.has(f.key))}if(l.length){let c=Qf(e,t.provider);if(!c)throw new Error("generateTextures: no image provider. Set el.aiImageProvider, or the ai-image-endpoint (and ai-image-model) attributes.");e.fireEvent?.("three-live-texture-start",{keys:l.map(h=>h.key)});let f=Math.max(1,Math.min(4,Math.floor(Number(t.concurrency??2))||2)),m=h=>o.push(h);await J0(l,f,async h=>{r.failed.delete(h.key),t.force&&r.pack.delete(h.key),await nm(e,c,h,t.signal)?s.push(h.key):m({key:h.key,error:"generation failed (see three-live-texture-error)"})})}return(a.length||s.length)&&await _i(e).catch(()=>{}),{generated:s,cached:a,failed:o,pack:await rm(e)}}async function rm(e){let t=Yn(e);return t.packJson??(t.packJson=await zl(t.pack,jl(e)))}function om(e){if(!e||e.__tlTexInstalled)return;e.__tlTexInstalled=!0,Yn(e),Object.defineProperty(e,"texturePack",{get:()=>e.__tlTex?.packJson??null,set:n=>{Ul(e,n)},configurable:!0}),e.generateTextures=n=>Q0(e,n),e.exportTexturePack=()=>rm(e);let t=e.querySelector?.('script[type="application/three-live-texture-pack"]');t?.textContent?.trim()&&Ul(e,t.textContent);let r=e.getAttribute?.("texture-pack");r&&qf(e,r);let i=e;typeof MutationObserver<"u"&&i&&typeof i.nodeType=="number"&&new MutationObserver(()=>{let n=e.getAttribute?.("texture-pack");n&&qf(e,n)}).observe(i,{attributes:!0,attributeFilter:["texture-pack"]})}var Da=12;function Ua(e){return String(e).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Za-z])([0-9])/g,"$1 $2").replace(/[_\-.]+/g," ").trim().slice(0,60)}function Z0(e){if(typeof document>"u")return!1;let t=(e.getAttribute?.("ai-select-chips")??"").toLowerCase();return t!=="off"&&t!=="false"}function Ba(e,t,r,i=!1){let n=document.createElement("button");return n.type="button",n.textContent=e,n.setAttribute("aria-label",t),Object.assign(n.style,{border:"none",borderRadius:"14px",padding:"4px 10px",font:"13px system-ui, sans-serif",cursor:"pointer",background:i?"#1a73e8":"rgba(255,255,255,0.92)",color:i?"#fff":"#202124"}),n.addEventListener("click",a=>{a.stopPropagation(),r()}),n}function mo(e){let t=e.__tlChips;t&&(t.off(),t.root.remove(),e.__tlChips=null)}function Va(e,t,r){if(!Z0(e))return null;let i=e.__tlChips;if(!i){let n=document.createElement("div");n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),n.setAttribute("part","selection-chips"),Object.assign(n.style,{position:"absolute",left:"64px",bottom:"12px",maxWidth:"calc(100% - 76px)",boxSizing:"border-box",display:"flex",flexWrap:"wrap",alignItems:"center",gap:"6px",padding:"6px 8px",borderRadius:"18px",background:"rgba(32,33,36,0.85)",boxShadow:"0 1px 4px rgba(0,0,0,0.3)",zIndex:"10",font:"13px system-ui, sans-serif",color:"#fff",pointerEvents:"auto"});let a=()=>{e.__tlChips&&!e.__tlChips.state.question&&Fa(e,e.__tlChips.state,r)};e.addEventListener?.("three-live-select",a),e.appendChild?.(n),i={root:n,off:()=>e.removeEventListener?.("three-live-select",a),state:t},e.__tlChips=i}return Fa(e,t,r),i.root}function Fa(e,t,r){let i=e.__tlChips;if(!i)return;i.state=t;let n=i.root;n.replaceChildren();let a=s=>{let o=document.createElement("span");o.textContent=s,n.appendChild(o)};if(t.question){a(t.question);for(let s of(t.candidates??[]).slice(0,Da))n.appendChild(Ba(Ua(s),`Select ${Ua(s)}`,()=>{rn(e,[s],{mode:t.mode==="add"||t.mode==="remove"?t.mode:"replace",source:"tap",query:t.query}),Fa(e,{pending:t.pending},r)}))}else{let s=nn(e);if(!s.length&&!t.pending){mo(e);return}a(s.length?"Selected:":"Nothing selected");for(let o of s.slice(0,Da))n.appendChild(Ba(`${Ua(o)} \xD7`,`Remove ${Ua(o)} from the selection`,()=>rn(e,[o],{mode:"remove",source:"tap"})));if(s.length>Da&&a(`+${s.length-Da} more`),t.pending&&r&&s.length){let o=t.pending;n.appendChild(Ba(`Apply: ${o.slice(0,40)}`,`Apply: ${o.slice(0,200)}`,()=>{Fa(e,{},r),r(o)},!0))}}n.appendChild(Ba("\u2715","Dismiss",()=>mo(e)))}var eb=500,po=2e3,tb=8,nb=[{name:"edit_scene",description:'Change the 3D scene the user is looking at. Call this whenever the user asks to add, remove, move, resize, recolor, or otherwise modify anything. Pass their request as a clear, self-contained instruction. If they selected a mesh, "this" or "it" refers to that mesh; the tool knows which one.',parameters:{type:"object",properties:{instruction:{type:"string",description:'The requested change, e.g. "make the roof red".'}},required:["instruction"]}},{name:"undo_edit",description:"Undo the last scene change.",parameters:{type:"object",properties:{}}},{name:"select_meshes",description:'Select objects in the scene so the user can see what an edit will change. Call this when the user refers to objects by name, color, or position ("the two red chairs on the left"). Pass their words as query, or exact mesh names as names. The result lists the selection, or a question to ask when the reference was unclear.',parameters:{type:"object",properties:{query:{type:"string",description:`The user's words for the objects, e.g. "the lamp next to the sofa".`},names:{type:"array",items:{type:"string"},description:"Exact mesh names, when known."},mode:{type:"string",enum:["replace","add","remove","clear"],description:"replace (default), add, remove, or clear."}}}}],rb=["You are a voice assistant inside a live 3D scene editor.","Keep spoken replies short: one sentence.","To change the scene, call edit_scene with the request; never describe code.","After a tool result, say briefly what changed, or why it could not be done.","When the user refers to objects by name, color, or position, call select_meshes with their words first.","If its result has a question, ask it and wait; otherwise say what is selected, and if they also asked for a change, call edit_scene."].join(" ");function ob(e){try{let t=new URL(e);return t.protocol==="wss:"?!0:t.protocol==="ws:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)}catch{return!1}}function ib(e){if(!ob(e))throw new Error("connectVoice: url must be wss:// (or ws:// on localhost).");let t=new WebSocket(e),r=[],i={send(n){let a=JSON.stringify(n);t.readyState===1?t.send(a):t.readyState===0&&r.length<256&&r.push(a)},close(){r.length=0,t.onopen=t.onmessage=t.onclose=null,t.close(),i.onClose?.()}};return t.onopen=()=>{for(let n of r.splice(0))t.send(n)},t.onmessage=async n=>{let a=i.onMessage;try{let s=typeof n.data=="string"?n.data:await n.data.text(),o=JSON.parse(s);o&&typeof o=="object"&&a?.(o)}catch{}},t.onclose=()=>i.onClose?.(),i}function _t(e){return typeof e=="string"?e:""}function Rn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Xl(e,t){let r={...e};for(let[i,n]of Object.entries(t??{})){if(i==="__proto__"||i==="constructor"||i==="prototype")continue;let a=r[i];r[i]=n&&typeof n=="object"&&!Array.isArray(n)&&a&&typeof a=="object"&&!Array.isArray(a)?Xl(a,n):n}return r}function im(e){if(e&&typeof e=="object")return Rn(e);try{return Rn(JSON.parse(_t(e)||"{}"))}catch{return{}}}var ql={name:"ai-realtime",inputRate:24e3,setup(e){let t={type:"realtime",instructions:e.instructions,audio:{input:{format:{type:"audio/pcm",rate:24e3},turn_detection:{type:"server_vad"}},output:{format:{type:"audio/pcm",rate:24e3},...e.voice?{voice:e.voice}:{}}},tools:e.tools.map(r=>({type:"function",...r})),tool_choice:"auto",...e.model?{model:e.model}:{}};return[{type:"session.update",session:Xl(t,e.overrides)}]},audio(e){return{type:"input_audio_buffer.append",audio:e}},text(e,t){let r=[{type:"conversation.item.create",item:{type:"message",role:t?"user":"system",content:[{type:"input_text",text:e}]}}];return t&&r.push({type:"response.create"}),r},toolResult(e,t,r){return[{type:"conversation.item.create",item:{type:"function_call_output",call_id:e,output:JSON.stringify(r)}},{type:"response.create"}]},parse(e){switch(_t(e.type)){case"response.output_audio.delta":case"response.audio.delta":return _t(e.delta)?[{type:"audio",base64:_t(e.delta),rate:24e3}]:[];case"response.output_audio_transcript.delta":case"response.audio_transcript.delta":return[{type:"transcript",speaker:"model",text:_t(e.delta),isFinal:!1}];case"response.output_audio_transcript.done":case"response.audio_transcript.done":return[{type:"transcript",speaker:"model",text:_t(e.transcript),isFinal:!0}];case"conversation.item.input_audio_transcription.delta":return[{type:"transcript",speaker:"user",text:_t(e.delta),isFinal:!1}];case"conversation.item.input_audio_transcription.completed":return[{type:"transcript",speaker:"user",text:_t(e.transcript),isFinal:!0}];case"response.function_call_arguments.done":return[{type:"toolCall",id:_t(e.call_id)||_t(e.item_id),name:_t(e.name),args:im(e.arguments)}];case"input_audio_buffer.speech_started":return[{type:"interrupted"}];case"response.done":return[{type:"turnComplete"}];case"error":return[{type:"error",message:_t(Rn(e.error).message)||"Realtime server error"}];default:return[]}}},Yl={name:"gemini-live",inputRate:16e3,setup(e){let t={...e.model?{model:e.model}:{},generationConfig:{responseModalities:["AUDIO"],...e.voice?{speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:e.voice}}}}:{}},systemInstruction:{parts:[{text:e.instructions}]},tools:[{functionDeclarations:e.tools.map(r=>({...r}))}],inputAudioTranscription:{},outputAudioTranscription:{}};return[{setup:Xl(t,e.overrides)}]},audio(e){return{realtimeInput:{audio:{mimeType:"audio/pcm;rate=16000",data:e}}}},text(e,t){return[{clientContent:{turns:[{role:"user",parts:[{text:e}]}],turnComplete:t}}]},toolResult(e,t,r){return[{toolResponse:{functionResponses:[{id:e,name:t,response:r}]}}]},parse(e){let t=[],r=Rn(e.serverContent);r.interrupted&&t.push({type:"interrupted"});let i=Rn(r.inputTranscription);_t(i.text)&&t.push({type:"transcript",speaker:"user",text:_t(i.text),isFinal:!1});let n=Rn(r.outputTranscription);_t(n.text)&&t.push({type:"transcript",speaker:"model",text:_t(n.text),isFinal:!1});let a=Rn(r.modelTurn).parts;for(let l of Array.isArray(a)?a:[]){let c=Rn(Rn(l).inlineData),f=_t(c.mimeType);if(f.startsWith("audio/pcm")&&_t(c.data)){let m=Number(/rate=(\d+)/.exec(f)?.[1])||24e3;t.push({type:"audio",base64:_t(c.data),rate:m})}}r.turnComplete&&t.push({type:"turnComplete"});let s=Rn(e.toolCall).functionCalls;for(let l of Array.isArray(s)?s:[]){let c=Rn(l);t.push({type:"toolCall",id:_t(c.id),name:_t(c.name),args:im(c.args)})}let o=Rn(e.error);return _t(o.message)&&t.push({type:"error",message:_t(o.message)}),t}},sb={"ai-realtime":ql,"gemini-live":Yl};function ab(e){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r="";for(let i=0;i<t.length;i+=32768)r+=String.fromCharCode(...t.subarray(i,i+32768));return btoa(r)}function cb(e,t,r){let i=t/r,n=Math.max(0,Math.floor(e.length/i)),a=new Int16Array(n);for(let s=0;s<n;s++){let o=s*i,l=Math.floor(o),c=Math.min(l+1,e.length-1),f=e[l]+(e[c]-e[l])*(o-l),m=Math.max(-1,Math.min(1,f));a[s]=m<0?m*32768:m*32767}return a}function lb(e){let t=atob(e),r=t.length>>1,i=new Float32Array(r);for(let n=0;n<r;n++){let a=t.charCodeAt(n*2)|t.charCodeAt(n*2+1)<<8;a&32768&&(a-=65536),i[n]=a/32768}return i}function sm(){let e=globalThis;return e.AudioContext??e.webkitAudioContext}function ub(){let e=null,t=null,r=null;return{async start(i,n){let a=sm(),s=globalThis.navigator?.mediaDevices;if(!a||!s?.getUserMedia)throw new Error("connectVoice: microphone capture is not available here.");e=await s.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,channelCount:1}}),t=new a;let o=t.createMediaStreamSource(e);r=t.createScriptProcessor(4096,1,1);let l=t.sampleRate;r.onaudioprocess=c=>{let f=cb(c.inputBuffer.getChannelData(0),l,i);f.length&&n(ab(f))},o.connect(r),r.connect(t.destination)},stop(){r&&(r.onaudioprocess=null),r?.disconnect();for(let i of e?.getTracks()??[])i.stop();t?.close(),r=null,e=null,t=null}}}function db(){let e=null,t=0,r=new Set,i={play(n,a){let s=sm();if(!e&&s)try{e=new s}catch{return}if(!e)return;e.state==="suspended"&&e.resume?.();let o=lb(n);if(!o.length)return;let l=e.createBuffer(1,o.length,a);l.getChannelData(0).set(o);let c=e.createBufferSource();c.buffer=l,c.connect(e.destination);let f=Math.max(e.currentTime,t);c.start(f),t=f+l.duration,r.add(c),c.onended=()=>r.delete(c)},flush(){for(let n of r)try{n.stop()}catch{}r.clear(),t=0},close(){i.flush(),e?.close(),e=null}};return i}function Gt(e,t){e.fireEvent?.("three-live-voice",t)}var ki=class{constructor(e,t){this.el=e,this.options=t,this.state="connecting",this.userText="",this.modelText="",this.onSelect=n=>{let a=n.detail;if(a?.source==="voice")return;let s=Array.isArray(a?.meshes)?a.meshes:a?.mesh?[a.mesh]:[];this.sendContext(Si(s))};let r=t.provider??"ai-realtime",i=sb[r];if(!i)throw new Error(`connectVoice: unknown provider '${r}' (use ai-realtime or gemini-live).`);if(this.adapter=i,t.transport)this.transport=t.transport;else if(t.url)this.transport=ib(t.url);else throw new Error("connectVoice: pass a wss:// url or a transport.");this.mic=t.microphone===!1?null:t.microphoneSource??ub(),this.sink=t.playAudio===!1?null:t.audioSink??db()}async start(){this.transport.onMessage=r=>this.handle(r),this.transport.onClose=()=>this.shutdown();let e=[rb,this.options.instructions].filter(Boolean).join(`
|
|
419
|
+
`);for(let r of this.adapter.setup({instructions:e,tools:nb,model:this.options.model,voice:this.options.voice,overrides:this.options.session}))this.transport.send(r);this.sink?.play("",24e3),this.el.addEventListener?.("three-live-select",this.onSelect);let t=nn(this.el);t.length&&this.sendContext(Si(t));try{await this.mic?.start(this.adapter.inputRate,r=>{this.state!=="closed"&&this.transport.send(this.adapter.audio(r))})}catch(r){throw this.setState("error",{error:r?.message||String(r)}),this.close(),r}return this.setState("listening"),this}sendText(e){let t=String(e??"").trim().slice(0,po);if(!(!t||this.state==="closed"))for(let r of this.adapter.text(t,!0))this.transport.send(r)}close(){this.state!=="closed"&&(this.transport.onClose=void 0,this.transport.close(),this.shutdown())}shutdown(){this.state!=="closed"&&(this.mic?.stop(),this.sink?.close(),this.el.removeEventListener?.("three-live-select",this.onSelect),this.el.__tlVoiceSession===this&&(this.el.__tlVoiceSession=null),this.setState("closed"))}sendContext(e){if(this.state!=="closed")for(let t of this.adapter.text(e,!1))this.transport.send(t)}setState(e,t={}){this.state=e,Gt(this.el,{state:e,...t})}handle(e){if(this.state==="closed")return;let t=0;for(let r of this.adapter.parse(e))switch(r.type){case"audio":this.state!=="editing"&&(this.state="speaking"),this.sink?.play(r.base64,r.rate);break;case"interrupted":this.sink?.flush();break;case"transcript":r.speaker==="user"?(this.userText=(r.isFinal?r.text:this.userText+r.text).slice(-po),Gt(this.el,{state:this.state,transcript:this.userText,isFinal:r.isFinal}),r.isFinal&&(this.userText="")):(this.modelText=(r.isFinal?r.text:this.modelText+r.text).slice(-po),Gt(this.el,{state:this.state,reply:this.modelText,isFinal:r.isFinal}),r.isFinal&&(this.modelText=""));break;case"turnComplete":this.userText&&(Gt(this.el,{state:this.state,transcript:this.userText,isFinal:!0}),this.userText=""),this.modelText&&(Gt(this.el,{state:this.state,reply:this.modelText,isFinal:!0}),this.modelText=""),(this.state==="speaking"||this.state==="thinking")&&this.setState("listening");break;case"toolCall":++t<=tb&&this.runTool(r.id,r.name,r.args);break;case"error":Gt(this.el,{state:this.state,error:r.message});break}}async runTool(e,t,r){let i;try{if(t==="edit_scene"){let n=_t(r.instruction).trim().slice(0,po);if(!n)throw new Error("instruction is empty");if(typeof this.el.editScene!="function")throw new Error("scene editing is not available on this element");this.setState("editing",{transcript:n});let a=await this.el.editScene(n,{provider:this.options.editProvider});i=a.applied?{applied:!0,repairs:a.repairs}:{applied:!1,error:a.error??"edit rejected"},this.setState("thinking",{result:a})}else if(t==="select_meshes"){let n=_t(r.mode),a=["replace","add","remove","clear"].includes(n)?n:"replace",s=Array.isArray(r.names)?r.names.filter(l=>typeof l=="string"):[],o=s.length&&a!=="clear"?Jl(this.el,s,a):await yo(this.el,_t(r.query),{mode:a,provider:this.options.editProvider??this.el.__tlSelectProvider?.()??null});i={changed:o.applied,selected:o.meshes.slice(0,50),say:o.say,...o.applied?{}:{question:o.say,candidates:o.match?.candidates??[]}}}else t==="undo_edit"?i=await this.el.undoEdit?.()??!1?{undone:!0}:{undone:!1,error:"nothing to undo"}:i={error:`unknown tool ${t}`}}catch(n){i={applied:!1,error:n?.message||String(n)},this.state==="editing"&&this.setState("thinking")}if(this.state!=="closed")for(let n of this.adapter.toolResult(e,t,i))this.transport.send(n)}};async function Ri(e,t){if(!t?.editProvider&&!e.aiProvider&&!e.getAttribute?.("ai-endpoint"))throw new Error("connectVoice: edits need a code model. Set el.aiProvider, the ai-endpoint attribute, or options.editProvider.");e.__tlVoiceSession?.close();let r=new ki(e,t??{});return e.__tlVoiceSession=r,Gt(e,{state:"connecting"}),r.start()}function Kl(){let e=globalThis,t=e.SpeechRecognition??e.webkitSpeechRecognition;return t?{listen({lang:r,signal:i,onPartial:n}){return new Promise((a,s)=>{let o=new t;o.lang=r||globalThis.document?.documentElement?.lang||"en-US",o.interimResults=!0,o.continuous=!1,o.maxAlternatives=1;let l="",c="",f=!1,m=p=>{f||(f=!0,i?.removeEventListener("abort",h),p())},h=()=>{try{o.abort()}catch{}m(()=>s(i?.reason??new Error("voice edit aborted")))};if(o.onresult=p=>{let g="";for(let x=p.resultIndex;x<p.results.length;x++){let v=p.results[x];v.isFinal?l+=v[0].transcript:g+=v[0].transcript}c=(l+g).trim(),n?.(c)},o.onerror=p=>{p?.error==="no-speech"||p?.error==="aborted"||m(()=>s(new Error(`Speech recognition failed: ${p?.error||"unknown error"}`)))},o.onend=()=>m(()=>a((l||c).trim())),i?.aborted)return h();i?.addEventListener("abort",h,{once:!0});try{o.start()}catch(p){m(()=>s(p))}})}}:null}function Oa(e,t){let r=globalThis;if(!(!r.speechSynthesis||!r.SpeechSynthesisUtterance))try{r.speechSynthesis.cancel();let i=new r.SpeechSynthesisUtterance(e);t&&(i.lang=t),r.speechSynthesis.speak(i)}catch{}}function za(e){return String(e).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Za-z])([0-9])/g,"$1 $2").replace(/[_\-.]+/g," ").replace(/\s+/g," ").trim()}function ho(e,t="and"){let r=e.slice(0,5).map(za),i=e.length-r.length;return i>0?`${r.join(", ")} ${t} ${i} more`:r.length<2?r.join(""):`${r.slice(0,-1).join(", ")} ${t} ${r[r.length-1]}`}function bo(e,t,r,i){if(e==="clear")return"Selection cleared.";if(!t)return"Which object?";if(t.confidence==="high")return e==="remove"?r.length?`Removed ${ho(t.names)}. ${r.length} selected.`:`Removed ${ho(t.names)}. Nothing is selected.`:e==="add"?`Added ${ho(t.names)}. ${r.length} selected.`:t.names.length===1?`Selected ${za(t.names[0])}.`:`Selected ${t.names.length}: ${ho(t.names)}.`;if(t.confidence==="ambiguous")return t.reason==="count_mismatch"?`I found ${t.candidates.length}: ${ho(t.candidates)}. Which ones?`:`Which one: ${ho(t.candidates,"or")}?`;let n=String(i).replace(/\s+/g," ").trim().slice(0,80);return t.reason==="relation"?`I can't tell which one "${n}" is yet. Try its name or color, or tap it.`:t.reason==="empty"?"Which object?":`I couldn't find "${n}".`}async function yo(e,t,r={}){let i=r.mode??"replace",n=String(t??"").slice(0,po);if(i==="clear")return rn(e,[],{mode:"clear",source:"voice",query:n||"clear"}),{mode:i,query:n,match:null,applied:!0,tier:1,meshes:[],say:bo(i,null,[],n)};let a=i==="remove"?nn(e):null;if(a&&!a.length)return{mode:i,query:n,match:null,applied:!1,tier:1,meshes:[],say:"Nothing is selected."};let s=Ma(e,n,{within:a}),o=1,l="",c=r.provider===void 0?e.__tlSelectProvider?.()??null:r.provider;if(c&&n.trim()&&s.confidence==="none"&&(s.reason==="relation"||s.reason==="no_match"))try{let p=await Aa(e,n,c,{within:a,signal:r.signal});o=2,l=p.question,s=p.confidence==="high"?{ids:[],names:p.names,confidence:"high",candidates:[],reason:"model"}:{ids:[],names:[],confidence:p.names.length?"ambiguous":"none",candidates:p.names.slice(0,10),reason:"model"}}catch(p){if(r.signal?.aborted)throw p}let f=!1;s.confidence==="high"&&s.names.length&&(rn(e,s.names,{mode:i,source:"voice",query:n}),f=!0);let m=nn(e),h=!f&&l?l:bo(i,s,m,n);return{mode:i,query:n,match:s,applied:f,tier:o,meshes:m,say:h}}function Jl(e,t,r="replace"){let i=new Set(uo(e).map(l=>l.name)),n=t.filter(l=>typeof l=="string"&&i.has(l)).slice(0,50),a=t.filter(l=>typeof l=="string").join(", ").slice(0,200);if(!n.length){let l={ids:[],names:[],confidence:"none",candidates:[],reason:"no_match"},c=nn(e);return{mode:r,query:a,match:l,applied:!1,tier:1,meshes:c,say:bo(r,l,c,a)}}rn(e,n,{mode:r,source:"voice",query:a});let s={ids:[],names:n,confidence:"high",candidates:[],reason:"exact"},o=nn(e);return{mode:r,query:a,match:s,applied:!0,tier:1,meshes:o,say:bo(r,s,o,a)}}function $a(e){return e.applied?"Done.":`Sorry, I couldn't apply that: ${String(e.error??"the edit was rejected").replace(/\s+/g," ").slice(0,160)}`}async function fb(e,t,r){if(typeof e.editScene!="function")return;Gt(e,{state:"editing",transcript:t,isFinal:!0});let i;try{i=await e.editScene(t)}catch(n){i={applied:!1,code:"",repairs:0,warnings:[],error:n?.message||String(n)}}Gt(e,{state:"idle",transcript:t,isFinal:!0,result:i}),r.speak!==!1&&Oa($a(i),r.lang)}async function Li(e,t={}){if(typeof e.editScene!="function")throw new Error("startVoiceEdit needs three-live-ai.min.js (el.editScene).");let r=t.recognizer??Kl();if(!r)throw new Error("startVoiceEdit: this browser has no speech recognition; use el.connectVoice() (ai-realtime or gemini-live) instead.");Gt(e,{state:"listening"});let i="";try{i=(await r.listen({lang:t.lang,signal:t.signal,onPartial:l=>Gt(e,{state:"listening",transcript:l,isFinal:!1})})).trim().slice(0,po)}catch(l){throw Gt(e,{state:"error",error:l?.message||String(l)}),l}if(!i){let l="I didn't catch that.";throw Gt(e,{state:"idle",transcript:i,isFinal:!0,error:l}),t.speak!==!1&&Oa(l,t.lang),new Error(`startVoiceEdit: ${l}`)}let n=i,a,s=t.talkToSelect===!1?null:wa(i);if(s&&s.kind!=="edit"){Gt(e,{state:"thinking",transcript:i,isFinal:!0});try{a=await yo(e,s.kind==="clear"?"":s.query,{mode:s.mode,signal:t.signal})}catch(m){throw Gt(e,{state:"error",error:m?.message||String(m)}),m}let l=s.kind==="mixed"?s.instruction:void 0,c=l!==void 0&&a.applied&&a.tier===1,f=t.chips!==!1&&!e.__tlVoiceSession;if(f){let m=a;Va(e,m.applied||m.mode==="clear"?{pending:c?void 0:l}:m.match?.candidates.length?{question:m.say,candidates:m.match.candidates,mode:m.mode,query:m.query,pending:l}:{},h=>fb(e,h,t))}if(!c){if(Gt(e,{state:"idle",transcript:i,isFinal:!0,selection:a}),t.speak!==!1){let m=l!==void 0&&a.applied?f&&e.__tlChips?" Tap Apply to make the change.":" Say the change again to apply it.":"";Oa(a.say+m,t.lang)}return{transcript:i,result:null,selection:a}}n=l}else t.chips!==!1&&e.__tlChips&&mo(e);Gt(e,{state:"editing",transcript:i,isFinal:!0,...a?{selection:a}:{}});let o;try{o=await e.editScene(n,{signal:t.signal})}catch(l){o={applied:!1,code:"",repairs:0,warnings:[],error:l?.message||String(l)}}if(Gt(e,{state:"idle",transcript:i,isFinal:!0,result:o,...a?{selection:a}:{}}),t.speak!==!1){let l=$a(o);Oa(a?`${a.say} ${l}`:l,t.lang)}return{transcript:i,result:o,...a?{selection:a}:{}}}function Pi(e,t){if(!t){e.__tlTapHandler&&e.removeEventListener?.("meshclick",e.__tlTapHandler),e.__tlTapDown&&e.removeEventListener?.("pointerdown",e.__tlTapDown),e.__tlTapHandler=null,e.__tlTapDown=null;return}if(e.__tlTapHandler)return;let r=!1,i=0,n=a=>{let s=a;r=!!(s.shiftKey||s.ctrlKey||s.metaKey),i=Date.now()};e.__tlTapDown=n,e.addEventListener?.("pointerdown",n),e.__tlTapHandler=a=>{let s=a.detail?.meshName;if(typeof s!="string"||!s)return;let o=i>0&&Date.now()-i>=eb,l=nn(e);r||o?rn(e,[s],{mode:"toggle",source:"tap"}):l.length===1&&l[0]===s?rn(e,[],{mode:"clear",source:"tap"}):rn(e,[s],{mode:"replace",source:"tap"}),r=!1,i=0},e.addEventListener?.("meshclick",e.__tlTapHandler)}var mb='<svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true" fill="currentColor"><path d="M12 14a3 3 0 0 0 3-3V5a3 3 0 0 0-6 0v6a3 3 0 0 0 3 3zm5-3a5 5 0 0 1-10 0H5a7 7 0 0 0 6 6.92V21h2v-3.08A7 7 0 0 0 19 11h-2z"/></svg>';function am(e){if(e.__tlVoiceButton||typeof document>"u")return;let t=e.querySelector?.('[slot="voice-button"]'),r=t??document.createElement("button");t||(r.setAttribute("type","button"),r.setAttribute("aria-label","Edit the scene by voice"),r.innerHTML=mb,Object.assign(r.style,{position:"absolute",left:"12px",bottom:"12px",width:"44px",height:"44px",borderRadius:"22px",border:"none",background:"rgba(32,33,36,0.85)",color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",zIndex:"10",boxShadow:"0 1px 4px rgba(0,0,0,0.3)"}),e.appendChild?.(r)),e.__tlVoiceButton=r;let i=null,n=a=>{r.setAttribute("aria-pressed",a?"true":"false"),t||(r.style.background=a?"rgba(217,48,37,0.9)":"rgba(32,33,36,0.85)")};r.addEventListener("click",a=>{a.stopPropagation();let s=e.getAttribute?.("ai-voice-url");if(s){if(e.__tlVoiceSession){e.__tlVoiceSession.close(),n(!1);return}n(!0);let o=e.getAttribute?.("ai-voice-provider")||"ai-realtime";Ri(e,{provider:o,url:s,model:e.getAttribute?.("ai-voice-model")||void 0}).then(l=>{e.addEventListener?.("three-live-voice",function c(f){f.detail?.state==="closed"&&(e.removeEventListener?.("three-live-voice",c),e.__tlVoiceSession!==l&&n(!1))})}).catch(()=>n(!1));return}if(i){i.abort(new Error("voice edit cancelled"));return}i=new AbortController,n(!0),Li(e,{signal:i.signal}).catch(()=>{}).finally(()=>{i=null,n(!1)})})}var Ll=1048576,Pl=20,cm=15e3,hb=["You edit Three.js scene scripts for Three-Live, which compiles them to glTF for Web, Android, and iOS.","Reply with the COMPLETE updated script in a single ```js code block and nothing else.","Rules:","- Use the pre-defined globals `THREE`, `scene`, and `camera`. No imports, renderer, loaders, DOM, network, or timers.","- Change only what the instruction asks; keep every other object, name, and value as it is.","- Give new meshes and groups descriptive `.name` values; keep existing names stable.","- Keep objects resting on y = 0 and within view of the camera.","- Supported: core geometries and materials (MeshStandardMaterial / MeshPhysicalMaterial with PBR maps, and MeshStandardNodeMaterial with loop-free THREE.TSL colorNode / emissiveNode / roughnessNode / metalnessNode / opacityNode / bumpNode / positionNode), lights, Group, InstancedMesh, THREE.CSG, THREE.CanvasTexture, THREE.ProceduralTexture presets (wood, marble, brick, concrete, brushedMetal, rust, leather, fabric, carbonFiber, checkerboard, grid), and declarative mesh.userData.xr traits. Optional per-frame motion: function animate(t) { ... }.","- Keep every userData.xr.material preset; add a prompt (AI texture) only when the instruction asks for a specific surface."].join(`
|
|
420
|
+
`);function pb(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)}catch{return!1}}function Ql(e){let t=String(e?.endpoint??"");if(!pb(t))throw new Error("ai-chat: endpoint must be an https:// URL (or http:// on localhost).");let r=e.fetch??globalThis.fetch?.bind(globalThis);if(typeof r!="function")throw new Error("ai-chat: no fetch() implementation is available.");let i=Number.isFinite(e.temperature)?Number(e.temperature):.2,n=Math.max(1e3,Number(e.timeoutMs)||12e4);return{async complete({messages:a,signal:s}){let o=new AbortController,l=()=>o.abort(s?.reason);s?.aborted&&l(),s?.addEventListener("abort",l,{once:!0});let c=setTimeout(()=>o.abort(new Error(`ai-chat: timed out after ${n} ms`)),n);try{let f={messages:a,temperature:i,stream:!1};e.model&&(f.model=e.model);let m=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...e.headers},body:JSON.stringify(f),signal:o.signal}),h=await m.text();if(!m.ok)throw new Error(`ai-chat: HTTP ${m.status} from endpoint: ${h.slice(0,300)}`);let p;try{p=JSON.parse(h)}catch{throw new Error("ai-chat: endpoint returned non-JSON content.")}let g=p?.choices?.[0]?.message?.content,x=Array.isArray(g)?g.map(v=>typeof v=="string"?v:String(v?.text??"")).join(""):g;if(typeof x!="string"||!x.trim())throw new Error("ai-chat: response had no message content.");return x}finally{clearTimeout(c),s?.removeEventListener("abort",l)}}}}function Ai(e){let t=String(e??""),r=/```[ \t]*([A-Za-z0-9_+-]*)[^\n]*\n([\s\S]*?)```/g,i,n="";for(;i=r.exec(t);){let s=i[1].toLowerCase();if(n||(n=i[2]),["js","javascript","ts","typescript","mjs"].includes(s))return i[2].trim()}if(n)return n.trim();let a=/```[^\n]*\n([\s\S]*)$/.exec(t);return a?a[1].trim():/\bscene\b/.test(t)?t.trim():""}function Il(e){let t=new Set,r=e?.gltf;if(!r&&e instanceof ArrayBuffer&&e.byteLength>=20){let a=new DataView(e);if(a.getUint32(0,!0)===1179937895){let s=a.getUint32(12,!0);try{r=JSON.parse(new TextDecoder().decode(new Uint8Array(e,20,s)))}catch{}}}let i=0,n=0;for(let a of r?.nodes??[]){let s=typeof a?.name=="string"?a.name.trim():"",o=/^Node_\d+$/.test(s),l=s.length>0&&!o;l&&t.add(s),a?.mesh!==void 0&&i++,!l&&(a?.extras?.xr!=null||a?.extras?.interactivity!=null)&&n++}return{meshNames:t,meshes:i,unnamedXrNodes:n}}function Cl(e,t,r,i="editScene"){let n=He().scriptRunner;if(!n||typeof n.execute!="function")return Promise.reject(new Error(`${i} needs a script runner (load three-live.min.js or three-live-full.min.js).`));let a=[];return new Promise((s,o)=>{let l,c=!1,f=p=>{if(!c){c=!0,clearTimeout(h),r?.removeEventListener("abort",m);try{l?.terminate?.()}catch{}p()}},m=()=>f(()=>o(r?.reason??new Error("editScene aborted"))),h=setTimeout(()=>f(()=>o(new Error(`Scene did not finish compiling within ${cm} ms.`))),cm);if(r?.aborted)return m();r?.addEventListener("abort",m,{once:!0}),Promise.resolve(n.execute(t,e.sandbox??"worker",{onModelReady:p=>f(()=>s({model:p,warnings:a})),onError:p=>f(()=>o(p instanceof Error?p:new Error(String(p)))),onToast:p=>{a.length<20&&a.push(String(p))}},{allowClientScripts:!0})).then(p=>{if(l=p,c)try{p?.terminate?.()}catch{}},p=>f(()=>o(p instanceof Error?p:new Error(String(p)))))})}var bb=50;function yb(e){let t=typeof e=="string"?[e]:Array.isArray(e)?e:[],r=[];for(let i of t){let n=typeof i=="string"?i.slice(0,200):"";if(n&&!r.includes(n)&&r.push(n),r.length>=bb)break}return r}function gb(e){return e.length===0?"":e.length===1?`The user selected the mesh named "${e[0]}"; the instruction refers to it.
|
|
421
|
+
`:`The user selected the meshes named ${e.map(t=>`"${t}"`).join(", ")}; the instruction refers to them.
|
|
422
|
+
`}function La(e,t,r="editScene"){let i=t.provider??e.aiProvider;if(i&&typeof i.complete=="function")return i;let n=e.getAttribute?.("ai-endpoint");if(!n)throw new Error(`${r}: no AI provider. Set el.aiProvider, or the ai-endpoint (and ai-model) attributes.`);let a=(e.getAttribute?.("ai-provider")||"ai-chat").toLowerCase();if(a!=="ai-chat")throw new Error(`${r}: unknown ai-provider '${a}' (supported: ai-chat, or set el.aiProvider).`);return Ql({endpoint:n,model:e.getAttribute?.("ai-model")||void 0})}function Pa(e){return typeof e.__tlAiSource=="string"?e.__tlAiSource:e.querySelector?.('script[type="text/three"], script[type="text/three-live"]')?.textContent??""}async function Zl(e,t,r={}){let i=String(t??"").trim();if(!i)throw new Error("editScene: instruction is empty.");if(!e?.allowClientScripts)throw new Error("editScene requires client scripts: add the allow-client-scripts attribute.");let n=r.source??Pa(e);if(!n.trim())throw new Error('editScene needs a Three.js scene script (inline <script type="text/three"> or a prior editScene/executeScript).');let a=La(e,r);e.__tlAiAbort?.abort(new Error("editScene superseded by a newer call"));let s=new AbortController;e.__tlAiAbort=s;let o=()=>s.abort(r.signal?.reason);r.signal?.aborted&&o(),r.signal?.addEventListener("abort",o,{once:!0});let l=s.signal,c=yb(r.selection===void 0?e.selectedMeshes??e.selectedMesh:r.selection),f=c.length>1?c:c[0]??null,m=Math.max(0,Math.min(3,Math.floor(Number(r.maxRepairs??1))||0)),h=[{role:"system",content:hb},{role:"user",content:`Current scene script:
|
|
423
|
+
\`\`\`js
|
|
424
|
+
${n}
|
|
425
|
+
\`\`\`
|
|
426
|
+
`+gb(c)+`Instruction: ${i}`}];e.fireEvent?.("three-live-edit-start",{instruction:i,selection:f});let p="",g="",x=[],v=0;try{for(let A=0;A<=m;A++){let b=await a.complete({messages:h,signal:l});if(l.aborted)throw l.reason;if(p=Ai(b),!p)g="The model reply did not contain a scene script.";else if(new TextEncoder().encode(p).length>Ll)g="The generated script exceeds the 1 MB script limit.";else try{let w=await Cl(e,p,l);x=w.warnings;let S=Il(w.model);if(S.meshes===0)g="The edited scene contains no meshes.";else if(c.some(E=>!S.meshNames.has(E))&&!/\b(remove|delete|rename)\b/i.test(i)){let E=c.filter(N=>!S.meshNames.has(N));g=E.length===1?`The edited scene no longer contains the selected mesh "${E[0]}".`:`The edited scene no longer contains the selected meshes ${E.map(N=>`"${N}"`).join(", ")}.`}else g=""}catch(w){if(l.aborted)throw l.reason;let S=w,E=String(S?.message||w);g=S?.name&&S.name!=="Error"&&!E.startsWith(S.name)?`${S.name}: ${E}`:E}if(!g)break;A<m&&(v++,h.push({role:"assistant",content:b},{role:"user",content:`That script was rejected by the Three-Live sandbox: ${g}
|
|
427
|
+
Return the complete corrected script in a single \`\`\`js code block.`}))}}finally{r.signal?.removeEventListener("abort",o),e.__tlAiAbort===s&&(e.__tlAiAbort=null)}if(!g&&!r.dryRun)try{await e.executeScript(p);let A=e.__tlAiHistory??(e.__tlAiHistory=[]);A.push(n),A.length>Pl&&A.shift(),e.__tlAiSource=p}catch(A){g=`The edit compiled but failed to load: ${A?.message||String(A)}`,e.__tlAiSource=n,e.executeScript(n).catch(()=>{})}let y={applied:!g,code:p,repairs:v,warnings:x,...g?{error:g}:{}};return e.fireEvent?.("three-live-edit",{instruction:i,...y}),y}async function eu(e){let t=e?.__tlAiHistory?.pop();return typeof t!="string"?!1:(e.__tlAiSource=t,await e.executeScript(t),!0)}var Ga={name:"ai",onRegister(){typeof document>"u"||document.querySelectorAll?.("three-live, xr-live").forEach(e=>Ga.onElementConnected?.(e))},onElementConnected(e){let t=e;if(!t||t.__tlAiInstalled)return;t.__tlAiInstalled=!0,t.editScene=(s,o)=>Zl(t,s,o),t.compileFromImage=(s,o)=>Ra(t,s,o),t.undoEdit=()=>eu(t),zf(t);let r=t;t.startVoiceEdit=s=>Li(r,s),r.__tlSelectProvider=()=>{try{return La(t,{})}catch{return null}},t.selectByVoice=(s,o)=>yo(r,s,o),t.connectVoice=s=>Ri(r,s),t.setSelectOnTap=s=>Pi(r,s),t.hasAttribute?.("ai-select-on-tap")&&Pi(r,!0),t.hasAttribute?.("ai-voice-button")&&am(r),"sceneSource"in t||Object.defineProperty(t,"sceneSource",{get:()=>Pa(t),configurable:!0});let i=t;om(i);let n=t.executeScript;typeof n=="function"&&(t.executeScript=s=>(Wl(i,{kind:"script",value:String(s)}),Gl(i,()=>n.call(t,s)).then(o=>(t.__tlAiSource=String(s),Hl(i,o),o))));let a=i.loadScriptFromSrc;typeof a=="function"&&(i.loadScriptFromSrc=s=>(Wl(i,{kind:"url",value:String(s)}),Gl(i,()=>a.call(t,s)).then(o=>(Hl(i,o),o))))}};gt(Ga);function lm(e,t,r){return t%4===0?new Float32Array(e,t,r):new Float32Array(e.slice(t,t+r*4))}function ja(e,t,r,i){let n=t[0],a=t[1],s=t[2],o=t[3],l=r[0],c=r[1],f=r[2],m=r[3],h=n*l+a*c+s*f+o*m;if(h<0&&(l=-l,c=-c,f=-f,m=-m,h=-h),Math.abs(h)>=1)return e[0]=n,e[1]=a,e[2]=s,e[3]=o,e;let p=Math.acos(h),g=Math.sqrt(1-h*h);if(Math.abs(g)<.001)return e[0]=.5*(n+l),e[1]=.5*(a+c),e[2]=.5*(s+f),e[3]=.5*(o+m),e;let x=Math.sin((1-i)*p)/g,v=Math.sin(i*p)/g;return e[0]=n*x+l*v,e[1]=a*x+c*v,e[2]=s*x+f*v,e[3]=o*x+m*v,e}function um(e,t,r,i){return e[0]=t[0]+i*(r[0]-t[0]),e[1]=t[1]+i*(r[1]-t[1]),e[2]=t[2]+i*(r[2]-t[2]),e}function ru(e,t){if(!Array.isArray(e?.animations))return[];let r=[];for(let i=0;i<e.animations.length;i++){let n=e.animations[i],a=n.name||`Animation_${i}`,s=[],o=0;if(Array.isArray(n.channels)&&Array.isArray(n.samplers))for(let l of n.channels){if(!l.target||l.target.node===void 0||!l.target.path)continue;let c=n.samplers[l.sampler];if(!c)continue;let f=e.accessors?.[c.input],m=e.accessors?.[c.output];if(!f||!m)continue;let h=e.bufferViews?.[f.bufferView],p=e.bufferViews?.[m.bufferView];if(!h||!p)continue;let g=(h.byteOffset||0)+(f.byteOffset||0),x=(p.byteOffset||0)+(m.byteOffset||0),v=Hn(e,t,f,1)??lm(t,g,f.count);v.length>0&&v[v.length-1]>o&&(o=v[v.length-1]);let y=l.target.path==="rotation"?4:l.target.path==="weights"?Math.max(1,Math.round(m.count/Math.max(1,f.count))):3,A=l.target.path==="weights"?1:y,b=Hn(e,t,m,A)??lm(t,x,m.count*A),w=c.interpolation==="STEP"?"STEP":"LINEAR";s.push({nodeIndex:l.target.node,path:l.target.path,times:v,values:b,interpolation:w})}s.length>0&&r.push({name:a,duration:o,channels:s})}return r}function go(e,t,r){let{times:i,values:n,path:a,interpolation:s}=e,o=i.length;if(o===0)return;let l=a==="rotation"?4:a==="weights"?Math.max(1,Math.round(n.length/o)):3;if(t<=i[0]){for(let A=0;A<l;A++)r[A]=n[A];return}if(t>=i[o-1]){let A=(o-1)*l;for(let b=0;b<l;b++)r[b]=n[A+b];return}let c=0,f=o-1;for(;c<=f;){let A=c+f>>1;i[A]<=t?c=A+1:f=A-1}let m=Math.max(0,f),h=Math.min(o-1,m+1);if(s==="STEP"||m===h){let A=m*l;for(let b=0;b<l;b++)r[b]=n[A+b];return}let p=i[m],g=i[h],x=(t-p)/Math.max(1e-5,g-p),v=m*l,y=h*l;if(a==="rotation"){let A=[n[v],n[v+1],n[v+2],n[v+3]],b=[n[y],n[y+1],n[y+2],n[y+3]];ja(r,A,b,x)}else for(let A=0;A<l;A++)r[A]=n[v+A]+x*(n[y+A]-n[v+A])}var Ii=new WeakMap;function ou(e,t,r=.3){if(!e?.animations)return;let i=e.animations.find(o=>o.name===t);if(!i)return;let n=Ii.get(e);n||(n=[],e.currentClip&&n.push({clip:e.currentClip,time:e.animationTime||0,weight:1,fadeSpeed:0}),Ii.set(e,n));let a=r>0?1/r:1e3;for(let o of n)o.clip.name!==t&&(o.fadeSpeed=-a);let s=n.find(o=>o.clip.name===t);s?s.fadeSpeed=a:n.push({clip:i,time:0,weight:r>0?0:1,fadeSpeed:a}),e.currentClip=i,e.isPlayingAnimation=!0}function tu(e,t){if(!e.gltf||!Array.isArray(e.gltf.nodes))return;let r=Ii.get(e);if(!r||r.length===0){if(!e.currentClip)return;r=[{clip:e.currentClip,time:t,weight:1,fadeSpeed:0}]}let i=e.gltf.nodes.length,n=[];for(let m=0;m<i;m++){let h=e.initialNodeTransforms[m];h?n.push({t:[h.t[0],h.t[1],h.t[2]],r:[h.r[0],h.r[1],h.r[2],h.r[3]],s:[h.s[0],h.s[1],h.s[2]]}):n.push({t:[0,0,0],r:[0,0,0,1],s:[1,1,1]})}let a=[0,0,0],s=[0,0,0,1],o=[1,1,1],l=new Float32Array(64);for(let m of r){let h=Math.max(0,Math.min(1,m.weight));if(!(h<=1e-4))for(let p of m.clip.channels){if(p.nodeIndex<0||p.nodeIndex>=i)continue;let g=n[p.nodeIndex];if(p.path==="translation")go(p,m.time,a),um(g.t,g.t,a,h);else if(p.path==="rotation")go(p,m.time,s),ja(g.r,g.r,s,h);else if(p.path==="scale")go(p,m.time,o),um(g.s,g.s,o,h);else if(p.path==="weights"&&(go(p,m.time,l),e.meshes)){for(let x of e.meshes)if(x.nodeIndex===p.nodeIndex){for(let v of x.primitives)if(v.pluginData?.morph?.weights){let y=v.pluginData.morph.weights,A=v.pluginData.morph.numTargets||y.length;for(let b=0;b<A;b++)y[b]=y[b]*(1-h)+l[b]*h}}}}}let c=[];for(let m=0;m<i;m++){let h=rt(),{t:p,r:g,s:x}=n[m];or(h,g,p,x),c.push(h)}let f=vr(e.gltf,c);e.worldMatrices=f;for(let m of e.meshes)m.nodeIndex>=0&&m.nodeIndex<f.length&&(m.transform.set(f[m.nodeIndex]),Bt(m.normalMatrix,m.transform))}var nu=e=>{Ii.delete(e)},iu={name:"keyframes",evaluateAnimation:tu,crossFadeTo:ou,onParseGLB(e){(e.animationsParsed===!1||!e.animations)&&(e.animations=ru(e.gltf,e.bin),e.animationsParsed=!0)},onLoadModel:nu,onClearScene:nu,onDestroy:(e,t)=>nu(t),onUpdate(e,t){if(!e.isPlayingAnimation)return;let r=Ii.get(e);if(r&&r.length>0){for(let i=r.length-1;i>=0;i--){let n=r[i];if(n.time+=t,n.clip.duration>0&&(n.time%=n.clip.duration),n.fadeSpeed!==0)if(n.weight+=n.fadeSpeed*t,n.weight<=0){r.splice(i,1);continue}else n.weight>=1&&(n.weight=1,n.fadeSpeed=0)}r.length>0&&(e.animationTime=r[r.length-1].time),tu(e,e.animationTime)}else e.currentClip&&(e.animationTime+=t,e.currentClip.duration>0&&(e.animationTime%=e.currentClip.duration),tu(e,e.animationTime))}},Ci=64;function dm(e,t,r){if(!(!e?.meshes||t<0||t>=Ci))for(let i of e.meshes)for(let n of i.primitives){let a=n.pluginData?.morph;a?.weights&&(a.weights[t]=r)}}var su={name:"morph",onResolveShader(e,t,r,i){if(!Array.isArray(e?.targets)||e.targets.length===0)return null;let n=r.replace("uniform mat4 uMVP,uModel;",`uniform mat4 uMVP,uModel;
|
|
380
428
|
uniform sampler2D uMorphDeltasTex;
|
|
381
|
-
uniform float uMorphWeights[${
|
|
429
|
+
uniform float uMorphWeights[${Ci}];
|
|
382
430
|
uniform int uNumMorphTargets;`);return n=n.replace("vec4 world=uModel*vec4(aPosition,1.0);",`vec3 morphedPos = aPosition;
|
|
383
|
-
for (int m = 0; m < ${
|
|
431
|
+
for (int m = 0; m < ${Ci}; m++) {
|
|
384
432
|
if (m >= uNumMorphTargets) break;
|
|
385
433
|
float w = uMorphWeights[m];
|
|
386
434
|
if (abs(w) > 0.0001) {
|
|
387
435
|
morphedPos += texelFetch(uMorphDeltasTex, ivec2(gl_VertexID, m), 0).xyz * w;
|
|
388
436
|
}
|
|
389
437
|
}
|
|
390
|
-
vec4 world=uModel*vec4(morphedPos,1.0);`).replace("gl_Position=uMVP*vec4(aPosition,1.0);","gl_Position=uMVP*vec4(morphedPos,1.0);"),{vs:n,fs:i}},onBuildPrimitiveVAO(e,t,r,i,n){let
|
|
438
|
+
vec4 world=uModel*vec4(morphedPos,1.0);`).replace("gl_Position=uMVP*vec4(aPosition,1.0);","gl_Position=uMVP*vec4(morphedPos,1.0);"),{vs:n,fs:i}},onBuildPrimitiveVAO(e,t,r,i,n){let a=r?.targets;if(!Array.isArray(a)||a.length===0)return null;let s=r.attributes?.POSITION,o=i?.accessors?.[s];if(!o)return null;let l=o.count,c=Math.min(a.length,Ci),f=new Float32Array(l*c*4);for(let p=0;p<c;p++){let g=a[p].POSITION;if(g===void 0)continue;let x=i.accessors?.[g],v=i.bufferViews?.[x?.bufferView];if(!x||!v)continue;let y=Hn(i,n,x,3);if(!y||y.length<l*3)continue;let A=p*l*4;for(let b=0;b<l;b++)f[A+b*4]=y[b*3],f[A+b*4+1]=y[b*3+1],f[A+b*4+2]=y[b*3+2],f[A+b*4+3]=0}let m=e.createTexture();e.bindTexture(3553,m),e.texImage2D(3553,0,34836,l,c,0,6408,5126,f),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728);let h=new Float32Array(Ci);return{hasMorph:!0,morphTex:m,numTargets:c,vertexCount:l,weights:h}},onBeforeDrawPrimitive(e,t,r,i,n,a){let s=r.pluginData?.morph;if(!s?.hasMorph||!s.morphTex)return;e.activeTexture(33989),e.bindTexture(3553,s.morphTex);let o=e.getUniformLocation(t,"uMorphDeltasTex");o&&e.uniform1i(o,5);let l=e.getUniformLocation(t,"uNumMorphTargets");l&&e.uniform1i(l,s.numTargets);let c=e.getUniformLocation(t,"uMorphWeights[0]");c&&e.uniform1fv(c,s.weights)}},au=64,cu={name:"skinning",onResolveShader(e,t,r,i){if(e?.attributes?.JOINTS_0===void 0||e?.attributes?.WEIGHTS_0===void 0)return null;let n=r.replace("layout(location=2) in vec2 aUV;",`layout(location=2) in vec2 aUV;
|
|
391
439
|
layout(location=4) in uvec4 aJoints;
|
|
392
440
|
layout(location=5) in vec4 aWeights;
|
|
393
|
-
uniform mat4 uJointMatrix[${
|
|
441
|
+
uniform mat4 uJointMatrix[${au}];`),a=n.includes("morphedPos")?"morphedPos":"aPosition";return n=n.replace(`vec4 world=uModel*vec4(${a},1.0);`,`mat4 skinMatrix =
|
|
394
442
|
aWeights.x * uJointMatrix[int(aJoints.x)] +
|
|
395
443
|
aWeights.y * uJointMatrix[int(aJoints.y)] +
|
|
396
444
|
aWeights.z * uJointMatrix[int(aJoints.z)] +
|
|
397
445
|
aWeights.w * uJointMatrix[int(aJoints.w)];
|
|
398
|
-
vec4 world=uModel*(skinMatrix*vec4(${
|
|
399
|
-
layout(location=0) in vec3 aPosition;layout(location=1) in vec2 aUV;uniform mat4 uMVP;out vec2 vUV;void main(){vUV=aUV;gl_Position=uMVP*vec4(aPosition,1.);}`,
|
|
400
|
-
precision highp float;in vec2 vUV;uniform float uShadowIntensity,uShadowSoftness;out vec4 fragColor;void main(){vec2 p=(vUV-.5)*2.;float d=clamp(length(p),0.,1.);fragColor=vec4(0.,0.,0.,pow(1.-d*d,mix(1.2,2.8,uShadowSoftness))*smoothstep(1.,.85-uShadowSoftness*.6,d)*uShadowIntensity);}`,Wn=new WeakMap,qs=new Float32Array(20);function oo(e,t){let[r,i,n,s,l,o]=t;return[e[0]*r+e[4]*i+e[8]*n+e[12],e[1]*r+e[5]*i+e[9]*n+e[13],e[2]*r+e[6]*i+e[10]*n+e[14],Math.abs(e[0])*s+Math.abs(e[4])*l+Math.abs(e[8])*o,Math.abs(e[1])*s+Math.abs(e[5])*l+Math.abs(e[9])*o,Math.abs(e[2])*s+Math.abs(e[6])*l+Math.abs(e[10])*o]}function Vc(e){if(e._lb!==void 0)return e._lb;let t=1e9,r=1e9,i=1e9,n=-1e9,s=-1e9,l=-1e9;for(let o of e.primitives||[]){let a=o.positions;if(a)for(let u=0;u<a.length;u+=3)a[u]<t&&(t=a[u]),a[u+1]<r&&(r=a[u+1]),a[u+2]<i&&(i=a[u+2]),a[u]>n&&(n=a[u]),a[u+1]>s&&(s=a[u+1]),a[u+2]>l&&(l=a[u+2])}return e._lb=t<=n?[(t+n)*.5,(r+s)*.5,(i+l)*.5,(n-t)*.5,(s-r)*.5,(l-i)*.5]:null}function Bc(e){let t=Wn.get(e);if(t)return t;let r=(o,a)=>{let u=e.createShader(o);return e.shaderSource(u,a),e.compileShader(u),u},i=e.createProgram();e.attachShader(i,r(35633,Uc)),e.attachShader(i,r(35632,Fc)),e.linkProgram(i);let n=e.createVertexArray(),s=e.createBuffer(),l=e.createBuffer();return e.bindVertexArray(n),e.bindBuffer(34962,s),e.bufferData(34962,80,35048),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,3,5126,!1,20,0),e.enableVertexAttribArray(1),e.vertexAttribPointer(1,2,5126,!1,20,12),e.bindBuffer(34963,l),e.bufferData(34963,new Uint16Array([0,1,2,0,2,3]),35044),e.bindVertexArray(null),t={prog:i,vao:n,vbo:s,ibo:l,uMVP:e.getUniformLocation(i,"uMVP"),uIntensity:e.getUniformLocation(i,"uShadowIntensity"),uSoftness:e.getUniformLocation(i,"uShadowSoftness")},Wn.set(e,t),t}var jn={name:"contact-shadow",onContextRestored(e){Wn.delete(e)},onAfterRender(e,t,r){let i=t.shadowIntensity;if(i<=0||!t.bounds)return;let n=Bc(e),s=!t.xrSessionActive&&(t.backdropMeshes?.length??0)>0,l=[],o=[];for(let f of t.meshes||[]){if(!f||f.visible===!1||f.isPluginMesh||f.name==="__xr_reticle__"||f.name?.startsWith("__xr_slot_"))continue;let g=Vc(f);if(!g)continue;f.transform&&(g=oo(f.transform,g)),t.modelRootMatrix&&(g=oo(t.modelRootMatrix,g));let[x,b,v,p,y,M]=g,P=[x,v,p,M,b-y,b+y];/floor|table|pedestal|ground|base|plane/i.test(f.name||"")||y<.14&&Math.min(p,M)>.45?o.push(P):l.push(P)}let a=[],u=t.bounds.center||[0,0,0],h=Math.max(.05,Number(t.bounds.radius)||.5),m=t.bounds.min,c=m?[u[0],u[1],u[2],h,Math.max(.01,u[1]-m[1]),h]:[u[0],u[1],u[2],h,h,h];t.modelRootMatrix&&(c=oo(t.modelRootMatrix,c));let d=t.xrSessionActive&&o.length===0&&String(t.container?.tagName||"").toLowerCase()==="xr-live"?(t.modelRootMatrix?t.modelRootMatrix[5]*-.25+t.modelRootMatrix[13]:-.25)+.002:c[1]-c[4]+.002;for(let[f,g,x,b,v]of l){let p=-1/0;for(let[M,P,F,W,,T]of o)v>=T-.08&&Math.abs(f-M)<=F&&Math.abs(g-P)<=W&&T+.002>p&&(p=T+.002);s&&(p=Math.max(p,f>=.04&&f<=.36&&g>=-.34&&g<=-.04&&v>=.01?.036:Math.hypot(f,g)<=.66&&v>=-.06?.003:-.477)),isFinite(p)||(p=d);let y=a.find(M=>Math.hypot(f-M[0],g-M[1])<.06&&Math.abs(p-M[5])<.05);y?(y[2]=Math.max(y[2],x*.78),y[3]=Math.max(y[3],b*.78),y[4]=Math.min(y[4],v)):a.push([f,g,x,b,v,p])}if(a.length===0){let f=Math.max(.1,c[3]*1.5)/1.45;a.push([c[0],c[2],f,f,d,d])}e.useProgram(n.prog),e.uniformMatrix4fv(n.uMVP,!1,r),e.enable(3042),(e.blendFuncSeparate||e.blendFunc).call(e,770,771,1,771),e.depthMask(!1),e.bindVertexArray(n.vao),e.bindBuffer(34962,n.vbo);for(let[f,g,x,b,v,p]of a){let y=Math.max(0,v-p),M=i/(1+y*2);if(M<.02)continue;let P=1+Math.min(.75,y*.85),F=Math.max(.045,x*1.45*P),W=Math.max(.045,b*1.45*P);qs.set([f-F,p,g-W,0,0,f+F,p,g-W,1,0,f+F,p,g+W,1,1,f-F,p,g+W,0,1]),e.bufferSubData(34962,0,qs),e.uniform1f(n.uIntensity,M),e.uniform1f(n.uSoftness,Math.min(1,t.shadowSoftness+Math.min(.45,y*.6))),e.drawElements(4,6,5123,0)}e.bindVertexArray(null),e.depthMask(!0),e.disable(3042)},onDestroy(e){let t=Wn.get(e);t&&(e.deleteVertexArray(t.vao),e.deleteBuffer(t.vbo),e.deleteBuffer(t.ibo),e.deleteProgram(t.prog),Wn.delete(e))}};function co(){if(typeof window>"u"||typeof navigator>"u")return!1;let e=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(e)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))return!1;let t=document.createElement("a");return t.relList!==void 0&&t.relList.supports!==void 0&&t.relList.supports("ar")}function uo(){if(typeof navigator>"u")return!1;let e=navigator.userAgent||"";return/android/i.test(e)}async function lo(){if(typeof navigator>"u")return!1;let e=navigator;if(!e.xr||typeof e.xr.isSessionSupported!="function")return!1;try{return await e.xr.isSessionSupported("immersive-ar")?!0:await e.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function Qs(){return(await ai()).bestMode}async function ai(){let[e,t,r]=await Promise.all([lo(),Promise.resolve(co()),Promise.resolve(uo())]),i=[];t&&i.push("quick-look"),e&&i.push("webxr"),r&&i.push("scene-viewer");let n=null;return t?n="quick-look":e?n="webxr":r&&(n="scene-viewer"),{webxr:e,quickLook:t,sceneViewer:r,availableModes:i,bestMode:n}}function Ys(e,t={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let r,i=!1;if(typeof e=="string"){if(r=zc(e),!r)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else r=URL.createObjectURL(e),i=!0;let n=[];if(t.allowScale===!1&&n.push("allowsContentScaling=0"),t.canonicalWebPageUrl){let o=si(t.canonicalWebPageUrl,!1);o&&n.push(`canonicalWebPageURL=${encodeURIComponent(o)}`)}t.checkoutTitle&&n.push(`checkoutTitle=${encodeURIComponent(t.checkoutTitle)}`),t.checkoutSubtitle&&n.push(`checkoutSubtitle=${encodeURIComponent(t.checkoutSubtitle)}`),t.price&&n.push(`price=${encodeURIComponent(t.price)}`),n.length>0&&(r+=`#${n.join("&")}`);let s=document.createElement("a");s.setAttribute("rel","ar"),s.setAttribute("href",r);let l=document.createElement("img");l.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),l.style.display="none",s.appendChild(l),document.body.appendChild(s),s.click(),setTimeout(()=>{document.body.removeChild(s),i&&URL.revokeObjectURL(r.split("#")[0])},3e3)}function si(e,t=!1){if(typeof e!="string")return"";let r=e.replace(/[\x00-\x1f\x7f]+/g,"").trim();if(!r)return"";if(/^[\\/]{2}/.test(r))throw new Error(`[XR-Live Security] Rejected protocol-relative URL in Scene Viewer intent: ${r.slice(0,32)}`);let i=r.toLowerCase();if(i.startsWith("https://")||i.startsWith("http://")||t&&i.startsWith("blob:")||!/^[a-z][a-z0-9+.-]*:/i.test(r))return r;throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Scene Viewer intent: ${r.slice(0,32)}`)}function zc(e){try{return si(e,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(e||"").trim().slice(0,32)}`)}}function Gc(e,t={}){let r=si(e,!0),i=t.mode||"ar_preferred",n=new URLSearchParams({file:r,mode:i,resizable:t.resizable!==!1?"true":"false",enable_vertical_placement:t.enableVerticalPlacement?"true":"false"});return t.title&&n.set("title",t.title),t.link&&n.set("link",si(t.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${n.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function Hc(e,t={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let r=Gc(e,t);window.location.href=r}var Xt=null;function Xc(e,t){let r=new Float32Array(144),i=new Float32Array(144),n=new Float32Array(96),s=new Uint16Array(144);for(let h=0;h<24;h++){let m=h/24*Math.PI*2,c=Math.cos(m),d=Math.sin(m),f=h*2,g=f+1,x=(h+1)%24*2;r[f*3]=c*.11,r[f*3+1]=.002,r[f*3+2]=d*.11,r[g*3]=c*.145,r[g*3+1]=.002,r[g*3+2]=d*.145,i[f*3+1]=i[g*3+1]=1,s.set([f,x,g,g,x,x+1],h*6)}let l=e.createVertexArray();e.bindVertexArray(l);let o=(h,m,c)=>{let d=e.createBuffer();return e.bindBuffer(34962,d),e.bufferData(34962,h,35044),e.enableVertexAttribArray(m),e.vertexAttribPointer(m,c,5126,!1,0,0),d},a=[o(r,0,3),o(i,1,3),o(n,2,2)],u=e.createBuffer();return a.push(u),e.bindBuffer(34963,u),e.bufferData(34963,s,35044),e.bindVertexArray(null),{name:"__xr_reticle__",nodeIndex:-1,worldSpace:!0,visible:!1,transform:new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),normalMatrix:new Float32Array([1,0,0,0,1,0,0,0,1]),primitives:[{vao:l,indexCount:s.length,indexType:5123,baseColor:t&&t.length>=3?[t[0],t[1],t[2],t[3]??.95]:[.22,.74,.97,.95],metallic:0,roughness:.2,positions:r,indices:s,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:a}]}}function Zs(e,t,r,i,n){let s=Math.cos(i),l=Math.sin(i),o=Math.max(.01,n);e.fill(0),e[0]=o*s,e[2]=-o*l,e[5]=o,e[8]=o*l,e[10]=o*s,e[12]=t[0]-o*(s*r[0]+l*r[2]),e[13]=t[1]-o*r[1],e[14]=t[2]-o*(-l*r[0]+s*r[2]),e[15]=1}var ao=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.");Xt&&Xt!==this&&Xt.isSessionActive()&&await Xt.stop().catch(()=>{});let r=navigator.xr,i=this.opts,n=t||e?.container,s=String(n?.tagName||"").toLowerCase()==="xr-live",l=e?.bounds,o=Number(l?.radius)||1,a=Array.isArray(l?.center)?l.center:[0,0,0],u=Array.isArray(l?.min)?l.min:[-.5,-.5,-.5],h=typeof navigator<"u"&&navigator.userAgent||"",m=/Android|iPhone|iPad|iPod/i.test(h)&&!/Quest|Oculus|Pico|Vision/i.test(h),c=s?i.arScale==="fixed"?1:m?.55:1:i.arScale==="fixed"?1:o>.45?.3/o:o<.05?.12/Math.max(o,.001):1,d=s?[0,-.25,0]:[a[0]||0,i.arPlacement==="wall"?a[1]:u[1]??0,a[2]||0],f="immersive-ar";try{await r.isSessionSupported("immersive-ar")||(f="immersive-vr")}catch{f="immersive-vr"}let g=n?.querySelector?.('[slot="ar-overlay"]')||null,x=!1,b=null,v=()=>{x&&g?.parentNode&&g.parentNode.removeChild(g),g=null,b=null,x=!1};if(f==="immersive-ar"){if(g)g.addEventListener?.("beforexrselect",_=>_.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let _=document.createElement("div");_.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 G=document.createElement("button");G.type="button",G.textContent="\u2715 Exit AR",G.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",G.addEventListener("beforexrselect",j=>j.preventDefault()),G.addEventListener("click",j=>{j.stopPropagation(),this.stop().catch(()=>{})}),b=document.createElement("div"),b.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",b.textContent="Move phone to detect a surface \u2022 Tap to place",_.appendChild(G),_.appendChild(b),document.body.appendChild(_),g=_,x=!0}}let p=new Set(i.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),y={requiredFeatures:i.requiredFeatures?[...i.requiredFeatures]:[],optionalFeatures:Array.from(p)};g&&(p.add("dom-overlay"),y.optionalFeatures=Array.from(p),y.domOverlay={root:g});for(let _ of Oe)_.onConfigureXRSessionInit?.(n,y);Array.isArray(y.optionalFeatures)&&y.optionalFeatures.includes("dom-overlay")&&!y.domOverlay?.root&&(y.optionalFeatures=y.optionalFeatures.filter(_=>_!=="dom-overlay"));let M=_=>{let G=String(_?.name||"");return G==="NotAllowedError"||G==="SecurityError"};try{this.s=await r.requestSession(f,y)}catch(_){if(v(),M(_))throw i.onError?.(_),_;try{this.s=await r.requestSession(f,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(G){if(M(G))throw i.onError?.(G),G;try{this.s=await r.requestSession(f)}catch(j){throw i.onError?.(j),j}}}let P=this.s;Xt=this,this.placed=!1;let F=null,W=null,T=null,E=null,S=null,O=[0,-.25,-1.2],k=[0,-.25,-1.2],w=new Float32Array(16),ie=new Float32Array(16),oe=!1,I=1,H=0,N=!1,z=null,ue=null,ce=0,B=null,$=()=>{Xt===this&&(Xt=null),B?.(),B=null;try{W?.cancel?.()}catch{}if(W=null,T){let _=e?.meshes;if(Array.isArray(_)){let j=_.indexOf(T);j!==-1&&_.splice(j,1)}let G=e.getGLContext?.()||e?.gl;if(G)for(let j of T.primitives||[]){G.deleteVertexArray?.(j.vao);for(let q of j.buffers||[])G.deleteBuffer?.(q)}T=null}e?.setXRSessionActive?.(!1),v(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=$,P.addEventListener("end",()=>{$(),i.onExit?.()}),P.addEventListener("select",()=>{if(!this.placed){let _=S||O;k=[_[0],_[1],_[2]],Zs(this.placedMat,k,d,H,c*I),this.placed=!0,T&&(T.visible=!1),b&&(b.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),i.onPlaced?.(this.placedMat)}});try{let _=e.getGLContext?.()||e?.gl;_&&typeof _.makeXRCompatible=="function"&&await _.makeXRCompatible();let G=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;_&&typeof G=="function"&&typeof P.updateRenderState=="function"&&P.updateRenderState({baseLayer:new G(P,_,{alpha:!0})});try{F=await P.requestReferenceSpace("local")}catch{try{F=await P.requestReferenceSpace("local-floor")}catch{F=await P.requestReferenceSpace("viewer")}}let j=await P.requestReferenceSpace("viewer").catch(()=>F);if(typeof P.requestHitTestSource=="function"&&j&&(W=await P.requestHitTestSource({space:j}).catch(()=>null)),f==="immersive-ar"&&_&&typeof _.createVertexArray=="function"&&Array.isArray(e.meshes)&&(T=Xc(_,i.reticleColor),e.meshes.push(T)),typeof window<"u"&&typeof window.addEventListener=="function"){let D=V=>Math.hypot(V.touches[1].clientX-V.touches[0].clientX,V.touches[1].clientY-V.touches[0].clientY),Y=V=>Math.atan2(V.touches[1].clientY-V.touches[0].clientY,V.touches[1].clientX-V.touches[0].clientX),te=V=>{this.s&&(V.touches.length===1&&this.placed?N=!0:V.touches.length>=2&&(N=!1,z=D(V),ue=Y(V)))},se=V=>{if(!this.s||V.touches.length<2)return;let ee=D(V),R=Y(V);if(z&&z>4&&i.arScale!=="fixed"&&(I=Math.max(.15,Math.min(6,I*(ee/z)))),ue!==null){let A=R-ue;A>Math.PI&&(A-=Math.PI*2),A<-Math.PI&&(A+=Math.PI*2),H-=A}z=ee,ue=R},le=V=>{(!V.touches||V.touches.length===0)&&(N=!1),(!V.touches||V.touches.length<2)&&(z=null,ue=null)};window.addEventListener("touchstart",te,{passive:!0}),window.addEventListener("touchmove",se,{passive:!0}),window.addEventListener("touchend",le,{passive:!0}),window.addEventListener("touchcancel",le,{passive:!0}),B=()=>{window.removeEventListener("touchstart",te),window.removeEventListener("touchmove",se),window.removeEventListener("touchend",le),window.removeEventListener("touchcancel",le)}}e.setXRSessionActive?.(!0);let q=(D,Y)=>{if(this.s!==P)return;P.requestAnimationFrame(q);let te=ce>0?Math.min(Math.max((D-ce)/1e3,0),.1):1/60;ce=D,e?.stepXRUpdate?.(te);let se=Y.getViewerPose(F);if(!se)return;let le=se.views?.[0];if(!oe&&le?.transform){let C=le.transform.position,U=le.transform.matrix,Q=C?.x??(U?U[12]:0),X=C?.y??(U?U[13]:0),Z=C?.z??(U?U[14]:0),J=U?-U[8]:0,K=U?-U[10]:-1,ae=Math.hypot(J,K);ae>1e-4?(J/=ae,K/=ae):(J=0,K=-1),O=[Q+J*1.2,X-.25,Z+K*1.2],H=Math.atan2(-J,-K),oe=!0}if(W&&typeof Y.getHitTestResults=="function"&&(!this.placed||N)){let C=Y.getHitTestResults(W)||[],U=!1;for(let Q of C){let X=Q.getPose(F);if(X?.transform?.matrix){let Z=X.transform.matrix,J=Z[5];if(i.arPlacement==="wall"&&Math.abs(J)>.35||i.arPlacement==="floor"&&Math.abs(J)<.65)continue;E||(E=new Float32Array(16)),E.set(Z),S=[Z[12],Z[13],Z[14]],this.placed&&N&&(k=[Z[12],Z[13],Z[14]]),T&&(T.visible=!this.placed||N,T.transform.set(Z)),!this.placed&&b&&(b.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),i.onHit?.(E),U=!0;break}}!U&&T&&(T.visible=!1)}Zs(w,this.placed?k:S||O,d,H,c*I),this.placed&&this.placedMat.set(w);let V=e.xrRigMatrix;V instanceof Float32Array&&V.length===16?Ie(ie,V,w):ie.set(w),e.modelRootMatrix&&e.modelRootMatrix.set(ie);for(let C of Oe)C.onXRFrame?.(e,P,Y,F);let ee=e.getGLContext?.()||e?.gl,R=P.renderState?.baseLayer;ee&&R&&R.framebuffer!==void 0&&ee.bindFramebuffer(36160,R.framebuffer);let A=f==="immersive-ar",L=se.views||[];for(let C=0;C<L.length;C++){let U=L[C];if(typeof e.renderXRView=="function"){let Q;if(R&&typeof R.getViewport=="function"){let X=R.getViewport(U);X&&X.width>0&&X.height>0&&(Q=[X.x,X.y,X.width,X.height])}else R?.framebufferWidth>0&&R?.framebufferHeight>0&&(Q=[0,0,R.framebufferWidth,R.framebufferHeight]);e.renderXRView(U,ie,this.placed,Q,A,C)}}ee&&R&&R.framebuffer&&ee.bindFramebuffer(36160,null)};P.requestAnimationFrame(q)}catch(_){throw typeof P.end=="function"&&await P.end().catch(()=>{}),$(),i.onError?.(_),_}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function ci(e){let t=await ai(),r=e.preferredModes||["quick-look","webxr","scene-viewer"],i=null;for(let o of r)if(t.availableModes.includes(o)){i=o;break}if(i||(i=t.bestMode),!i)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let n={...e.quickLookOptions,allowScale:e.arScale==="fixed"?!1:e.quickLookOptions?.allowScale},s={...e.sceneViewerOptions,resizable:e.arScale==="fixed"?!1:e.sceneViewerOptions?.resizable,enableVerticalPlacement:e.arPlacement==="wall"?!0:e.sceneViewerOptions?.enableVerticalPlacement},l={...e.webXROptions,arScale:e.arScale||e.webXROptions?.arScale,arPlacement:e.arPlacement||e.webXROptions?.arPlacement};try{if(i==="quick-look"){let o;if(e.model instanceof Blob&&e.model.type==="model/vnd.usdz+zip")o=e.model;else{if(typeof e.model=="string")return Ys(e.model,n),{mode:"quick-look",success:!0};o=on(e.model)}return Ys(o,n),{mode:"quick-look",success:!0}}if(i==="scene-viewer"){let o=e.glbUrl||(typeof e.model=="string"?e.model:null);if(!o)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return Hc(o,s),{mode:"scene-viewer",success:!0}}if(i==="webxr"){if(!e.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let o=new ao(l);return await o.start(e.view,e.element),{mode:"webxr",success:!0,session:o}}}catch(o){return{mode:i,success:!1,error:o}}return{mode:i,success:!1,error:new Error(`Unhandled AR mode: ${i}`)}}mt.registerAR({activateAR:ci,createUSDZBlob:on}),mt.registerScriptRunner(ln),Ve(jn);var fo=new WeakMap;function ui(e,t){let r=t instanceof Float32Array?t:new Float32Array(t);fo.set(e,r)}function ta(e){return fo.get(e)}async function $c(e,t){if(!t)return null;let r;if(typeof t=="string")if(typeof fetch<"u"&&typeof createImageBitmap=="function"){let n=await(await fetch(t)).blob();r=await createImageBitmap(n)}else if(typeof Image<"u")r=await new Promise((n,s)=>{let l=new Image;l.crossOrigin="anonymous",l.onload=()=>n(l),l.onerror=s,l.src=t});else return null;else r=t;let i=e.createTexture();return e.bindTexture(3553,i),e.texImage2D(3553,0,6408,6408,5121,r),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071),e.texParameteri(3553,10241,9987),e.texParameteri(3553,10240,9729),e.generateMipmap(3553),i}var mo=new WeakMap,Js=new Float32Array(16);async function ea(e,t,r){let i=r?await $c(e.gl,r):null;e[t]&&e.gl.deleteTexture(e[t]),e[t]=i}var ho={name:"environment-map",onContextRestored(e){mo.delete(e)},setEnvironmentImage(e,t){return ea(e,"environmentTexture",t)},setSkyboxImage(e,t){return ea(e,"skyboxTexture",t)},onBeforeDrawScene(e,t,r,i,n){if(!e.skyboxTexture||typeof t.createProgram!="function")return;let s=mo.get(t);if(!s){let m=(f,g)=>{let x=t.createShader(f);return t.shaderSource(x,g),t.compileShader(x),x},c=t.createProgram();t.attachShader(c,m(35633,`#version 300 es
|
|
401
|
-
out vec2 vNDC;void main(){vec2 p=vec2((gl_VertexID<<1)&2,gl_VertexID&2);vNDC=p*2.-1.;gl_Position=vec4(vNDC,.999999,1.);}`)),t.attachShader(
|
|
402
|
-
precision highp float;in vec2 vNDC;uniform mat4 uInvVP;uniform vec3 uCameraPos;uniform sampler2D uSkyboxMap;uniform float uExposure;out vec4 fragColor;vec2 eqUV(vec3 d){return vec2(atan(d.x,d.z)/6.2831853+.5,asin(clamp(d.y,-1.,1.))/3.1415926+.5);}void main(){vec4 fp=uInvVP*vec4(vNDC,1.,1.);vec3 dir=normalize(fp.xyz/fp.w-uCameraPos);fragColor=vec4(pow(texture(uSkyboxMap,eqUV(dir)).rgb*uExposure,vec3(1./2.2)),1.);}`)),t.linkProgram(
|
|
446
|
+
vec4 world=uModel*(skinMatrix*vec4(${a},1.0));`).replace(`gl_Position=uMVP*vec4(${a},1.0);`,`gl_Position=uMVP*(skinMatrix*vec4(${a},1.0));`),{vs:n,fs:i}},onBuildPrimitiveVAO(e,t,r,i,n){let a=r?.attributes;if(!a||a.JOINTS_0===void 0||a.WEIGHTS_0===void 0)return null;let s=i.accessors[a.JOINTS_0],o=i.accessors[a.WEIGHTS_0];if(!s||!o)return null;let l=i.bufferViews[s.bufferView],c=i.bufferViews[o.bufferView];if(!l||!c)return null;let f=(l.byteOffset||0)+(s.byteOffset||0),m=(c.byteOffset||0)+(o.byteOffset||0),h=e.createBuffer();e.bindBuffer(34962,h);let p=s.componentType===5121?5121:5123,g=p===5121?new Uint8Array(n,f,s.count*4):new Uint16Array(n,f,s.count*4);e.bufferData(34962,g,35044),e.enableVertexAttribArray(4),e.vertexAttribIPointer(4,4,p,0,0);let x=e.createBuffer();e.bindBuffer(34962,x);let v=Hn(i,n,o,4)??new Float32Array(n,m,o.count*4);return e.bufferData(34962,v,35044),e.enableVertexAttribArray(5),e.vertexAttribPointer(5,4,5126,!1,0,0),{hasSkin:!0,buffers:[h,x]}},onBeforeDrawPrimitive(e,t,r,i,n,a){if(!r.pluginData?.skinning?.hasSkin)return;let s=a?.nodes?.[i.nodeIndex]?.skin;if(s===void 0||!a.skins||!a.skins[s])return;let o=a.skins[s].joints||[],l=new Float32Array(au*16);for(let f=0;f<o.length&&f<au;f++){let m=o[f],h=n[m]||rt();l.subarray(f*16,(f+1)*16).set(h)}let c=e.getUniformLocation(t,"uJointMatrix[0]");c&&e.uniformMatrix4fv(c,!1,l)}};gt(su),gt(iu),gt(cu),gt(Fc),gt(kc);var xb=`#version 300 es
|
|
447
|
+
layout(location=0) in vec3 aPosition;layout(location=1) in vec2 aUV;uniform mat4 uMVP;out vec2 vUV;void main(){vUV=aUV;gl_Position=uMVP*vec4(aPosition,1.);}`,vb=`#version 300 es
|
|
448
|
+
precision highp float;in vec2 vUV;uniform float uShadowIntensity,uShadowSoftness;out vec4 fragColor;void main(){vec2 p=(vUV-.5)*2.;float d=clamp(length(p),0.,1.);fragColor=vec4(0.,0.,0.,pow(1.-d*d,mix(1.2,2.8,uShadowSoftness))*smoothstep(1.,.85-uShadowSoftness*.6,d)*uShadowIntensity);}`,Ni=new WeakMap,fm=new Float32Array(20);function lu(e,t){let[r,i,n,a,s,o]=t;return[e[0]*r+e[4]*i+e[8]*n+e[12],e[1]*r+e[5]*i+e[9]*n+e[13],e[2]*r+e[6]*i+e[10]*n+e[14],Math.abs(e[0])*a+Math.abs(e[4])*s+Math.abs(e[8])*o,Math.abs(e[1])*a+Math.abs(e[5])*s+Math.abs(e[9])*o,Math.abs(e[2])*a+Math.abs(e[6])*s+Math.abs(e[10])*o]}function wb(e){if(e._lb!==void 0)return e._lb;let t=1e9,r=1e9,i=1e9,n=-1e9,a=-1e9,s=-1e9;for(let o of e.primitives||[]){let l=o.positions;if(l)for(let c=0;c<l.length;c+=3)l[c]<t&&(t=l[c]),l[c+1]<r&&(r=l[c+1]),l[c+2]<i&&(i=l[c+2]),l[c]>n&&(n=l[c]),l[c+1]>a&&(a=l[c+1]),l[c+2]>s&&(s=l[c+2])}return e._lb=t<=n?[(t+n)*.5,(r+a)*.5,(i+s)*.5,(n-t)*.5,(a-r)*.5,(s-i)*.5]:null}function Sb(e){let t=Ni.get(e);if(t)return t;let r=(o,l)=>{let c=e.createShader(o);return e.shaderSource(c,l),e.compileShader(c),c},i=e.createProgram();e.attachShader(i,r(35633,xb)),e.attachShader(i,r(35632,vb)),e.linkProgram(i);let n=e.createVertexArray(),a=e.createBuffer(),s=e.createBuffer();return e.bindVertexArray(n),e.bindBuffer(34962,a),e.bufferData(34962,80,35048),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,3,5126,!1,20,0),e.enableVertexAttribArray(1),e.vertexAttribPointer(1,2,5126,!1,20,12),e.bindBuffer(34963,s),e.bufferData(34963,new Uint16Array([0,1,2,0,2,3]),35044),e.bindVertexArray(null),t={prog:i,vao:n,vbo:a,ibo:s,uMVP:e.getUniformLocation(i,"uMVP"),uIntensity:e.getUniformLocation(i,"uShadowIntensity"),uSoftness:e.getUniformLocation(i,"uShadowSoftness")},Ni.set(e,t),t}var Di={name:"contact-shadow",onContextRestored(e){Ni.delete(e)},onAfterRender(e,t,r){let i=t.shadowIntensity;if(i<=0||!t.bounds)return;let n=Sb(e),a=!t.xrSessionActive&&(t.backdropMeshes?.length??0)>0,s=[],o=[];for(let g of t.meshes||[]){if(!g||g.visible===!1||g.isPluginMesh||g.name==="__xr_reticle__"||g.name?.startsWith("__xr_slot_"))continue;let x=wb(g);if(!x)continue;g.transform&&(x=lu(g.transform,x)),t.modelRootMatrix&&(x=lu(t.modelRootMatrix,x));let[v,y,A,b,w,S]=x,E=[v,A,b,S,y-w,y+w];/floor|table|pedestal|ground|base|plane/i.test(g.name||"")||w<.14&&Math.min(b,S)>.45?o.push(E):s.push(E)}let l=[],c=t.bounds.center||[0,0,0],f=Math.max(.05,Number(t.bounds.radius)||.5),m=t.bounds.min,h=m?[c[0],c[1],c[2],f,Math.max(.01,c[1]-m[1]),f]:[c[0],c[1],c[2],f,f,f];t.modelRootMatrix&&(h=lu(t.modelRootMatrix,h));let p=t.xrSessionActive&&o.length===0&&String(t.container?.tagName||"").toLowerCase()==="xr-live"?(t.modelRootMatrix?t.modelRootMatrix[5]*-.25+t.modelRootMatrix[13]:-.25)+.002:h[1]-h[4]+.002;for(let[g,x,v,y,A]of s){let b=-1/0;for(let[S,E,N,C,,_]of o)A>=_-.08&&Math.abs(g-S)<=N&&Math.abs(x-E)<=C&&_+.002>b&&(b=_+.002);a&&(b=Math.max(b,g>=.04&&g<=.36&&x>=-.34&&x<=-.04&&A>=.01?.036:Math.hypot(g,x)<=.66&&A>=-.06?.003:-.477)),isFinite(b)||(b=p);let w=l.find(S=>Math.hypot(g-S[0],x-S[1])<.06&&Math.abs(b-S[5])<.05);w?(w[2]=Math.max(w[2],v*.78),w[3]=Math.max(w[3],y*.78),w[4]=Math.min(w[4],A)):l.push([g,x,v,y,A,b])}if(l.length===0){let g=Math.max(.1,h[3]*1.5)/1.45;l.push([h[0],h[2],g,g,p,p])}e.useProgram(n.prog),e.uniformMatrix4fv(n.uMVP,!1,r),e.enable(3042),(e.blendFuncSeparate||e.blendFunc).call(e,770,771,1,771),e.depthMask(!1),e.bindVertexArray(n.vao),e.bindBuffer(34962,n.vbo);for(let[g,x,v,y,A,b]of l){let w=Math.max(0,A-b),S=i/(1+w*2);if(S<.02)continue;let E=1+Math.min(.75,w*.85),N=Math.max(.045,v*1.45*E),C=Math.max(.045,y*1.45*E);fm.set([g-N,b,x-C,0,0,g+N,b,x-C,1,0,g+N,b,x+C,1,1,g-N,b,x+C,0,1]),e.bufferSubData(34962,0,fm),e.uniform1f(n.uIntensity,S),e.uniform1f(n.uSoftness,Math.min(1,t.shadowSoftness+Math.min(.45,w*.6))),e.drawElements(4,6,5123,0)}e.bindVertexArray(null),e.depthMask(!0),e.disable(3042)},onDestroy(e){let t=Ni.get(e);t&&(e.deleteVertexArray(t.vao),e.deleteBuffer(t.vbo),e.deleteBuffer(t.ibo),e.deleteProgram(t.prog),Ni.delete(e))}};function fu(){if(typeof window>"u"||typeof navigator>"u")return!1;let e=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(e)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))return!1;let t=document.createElement("a");return t.relList!==void 0&&t.relList.supports!==void 0&&t.relList.supports("ar")}function mu(){if(typeof navigator>"u")return!1;let e=navigator.userAgent||"";return/android/i.test(e)}async function hu(){if(typeof navigator>"u")return!1;let e=navigator;if(!e.xr||typeof e.xr.isSessionSupported!="function")return!1;try{return await e.xr.isSessionSupported("immersive-ar")?!0:await e.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function pm(){return(await Wa()).bestMode}async function Wa(){let[e,t,r]=await Promise.all([hu(),Promise.resolve(fu()),Promise.resolve(mu())]),i=[];t&&i.push("quick-look"),e&&i.push("webxr"),r&&i.push("scene-viewer");let n=null;return t?n="quick-look":e?n="webxr":r&&(n="scene-viewer"),{webxr:e,quickLook:t,sceneViewer:r,availableModes:i,bestMode:n}}function mm(e,t={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let r,i=!1;if(typeof e=="string"){if(r=Mb(e),!r)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else r=URL.createObjectURL(e),i=!0;let n=[];if(t.allowScale===!1&&n.push("allowsContentScaling=0"),t.canonicalWebPageUrl){let o=Ha(t.canonicalWebPageUrl,!1);o&&n.push(`canonicalWebPageURL=${encodeURIComponent(o)}`)}t.checkoutTitle&&n.push(`checkoutTitle=${encodeURIComponent(t.checkoutTitle)}`),t.checkoutSubtitle&&n.push(`checkoutSubtitle=${encodeURIComponent(t.checkoutSubtitle)}`),t.price&&n.push(`price=${encodeURIComponent(t.price)}`),n.length>0&&(r+=`#${n.join("&")}`);let a=document.createElement("a");a.setAttribute("rel","ar"),a.setAttribute("href",r);let s=document.createElement("img");s.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),s.style.display="none",a.appendChild(s),document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),i&&URL.revokeObjectURL(r.split("#")[0])},3e3)}function Ha(e,t=!1){if(typeof e!="string")return"";let r=e.replace(/[\x00-\x1f\x7f]+/g,"").trim();if(!r)return"";if(/^[\\/]{2}/.test(r))throw new Error(`[XR-Live Security] Rejected protocol-relative URL in Scene Viewer intent: ${r.slice(0,32)}`);let i=r.toLowerCase();if(i.startsWith("https://")||i.startsWith("http://")||t&&i.startsWith("blob:")||!/^[a-z][a-z0-9+.-]*:/i.test(r))return r;throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Scene Viewer intent: ${r.slice(0,32)}`)}function Mb(e){try{return Ha(e,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(e||"").trim().slice(0,32)}`)}}function Ab(e,t={}){let r=Ha(e,!0),i=t.mode||"ar_preferred",n=new URLSearchParams({file:r,mode:i,resizable:t.resizable!==!1?"true":"false",enable_vertical_placement:t.enableVerticalPlacement?"true":"false"});return t.title&&n.set("title",t.title),t.link&&n.set("link",Ha(t.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${n.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function Tb(e,t={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let r=Ab(e,t);window.location.href=r}var zr=null;function _b(e,t){let r=new Float32Array(144),i=new Float32Array(144),n=new Float32Array(96),a=new Uint16Array(144);for(let f=0;f<24;f++){let m=f/24*Math.PI*2,h=Math.cos(m),p=Math.sin(m),g=f*2,x=g+1,v=(f+1)%24*2;r[g*3]=h*.11,r[g*3+1]=.002,r[g*3+2]=p*.11,r[x*3]=h*.145,r[x*3+1]=.002,r[x*3+2]=p*.145,i[g*3+1]=i[x*3+1]=1,a.set([g,v,x,x,v,v+1],f*6)}let s=e.createVertexArray();e.bindVertexArray(s);let o=(f,m,h)=>{let p=e.createBuffer();return e.bindBuffer(34962,p),e.bufferData(34962,f,35044),e.enableVertexAttribArray(m),e.vertexAttribPointer(m,h,5126,!1,0,0),p},l=[o(r,0,3),o(i,1,3),o(n,2,2)],c=e.createBuffer();return l.push(c),e.bindBuffer(34963,c),e.bufferData(34963,a,35044),e.bindVertexArray(null),{name:"__xr_reticle__",nodeIndex:-1,worldSpace:!0,visible:!1,transform:new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),normalMatrix:new Float32Array([1,0,0,0,1,0,0,0,1]),primitives:[{vao:s,indexCount:a.length,indexType:5123,baseColor:t&&t.length>=3?[t[0],t[1],t[2],t[3]??.95]:[.22,.74,.97,.95],metallic:0,roughness:.2,positions:r,indices:a,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:l}]}}function hm(e,t,r,i,n){let a=Math.cos(i),s=Math.sin(i),o=Math.max(.01,n);e.fill(0),e[0]=o*a,e[2]=-o*s,e[5]=o,e[8]=o*s,e[10]=o*a,e[12]=t[0]-o*(a*r[0]+s*r[2]),e[13]=t[1]-o*r[1],e[14]=t[2]-o*(-s*r[0]+a*r[2]),e[15]=1}var du=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.");zr&&zr!==this&&zr.isSessionActive()&&await zr.stop().catch(()=>{});let r=navigator.xr,i=this.opts,n=t||e?.container,a=String(n?.tagName||"").toLowerCase()==="xr-live",s=e?.bounds,o=Number(s?.radius)||1,l=Array.isArray(s?.center)?s.center:[0,0,0],c=Array.isArray(s?.min)?s.min:[-.5,-.5,-.5],f=typeof navigator<"u"&&navigator.userAgent||"",m=/Android|iPhone|iPad|iPod/i.test(f)&&!/Quest|Oculus|Pico|Vision/i.test(f),h=a?i.arScale==="fixed"?1:m?.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]:c[1]??0,l[2]||0],g="immersive-ar";try{await r.isSessionSupported("immersive-ar")||(g="immersive-vr")}catch{g="immersive-vr"}let x=n?.querySelector?.('[slot="ar-overlay"]')||null,v=!1,y=null,A=()=>{v&&x?.parentNode&&x.parentNode.removeChild(x),x=null,y=null,v=!1};if(g==="immersive-ar"){if(x)x.addEventListener?.("beforexrselect",Z=>Z.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let Z=document.createElement("div");Z.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 ae=document.createElement("button");ae.type="button",ae.textContent="\u2715 Exit AR",ae.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",ae.addEventListener("beforexrselect",ie=>ie.preventDefault()),ae.addEventListener("click",ie=>{ie.stopPropagation(),this.stop().catch(()=>{})}),y=document.createElement("div"),y.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",y.textContent="Move phone to detect a surface \u2022 Tap to place",Z.appendChild(ae),Z.appendChild(y),document.body.appendChild(Z),x=Z,v=!0}}let b=new Set(i.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),w={requiredFeatures:i.requiredFeatures?[...i.requiredFeatures]:[],optionalFeatures:Array.from(b)};x&&(b.add("dom-overlay"),w.optionalFeatures=Array.from(b),w.domOverlay={root:x});for(let Z of kt)Z.onConfigureXRSessionInit?.(n,w);Array.isArray(w.optionalFeatures)&&w.optionalFeatures.includes("dom-overlay")&&!w.domOverlay?.root&&(w.optionalFeatures=w.optionalFeatures.filter(Z=>Z!=="dom-overlay"));let S=Z=>{let ae=String(Z?.name||"");return ae==="NotAllowedError"||ae==="SecurityError"};try{this.s=await r.requestSession(g,w)}catch(Z){if(A(),S(Z))throw i.onError?.(Z),Z;try{this.s=await r.requestSession(g,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(ae){if(S(ae))throw i.onError?.(ae),ae;try{this.s=await r.requestSession(g)}catch(ie){throw i.onError?.(ie),ie}}}let E=this.s;zr=this,this.placed=!1;let N=null,C=null,_=null,P=null,R=null,$=[0,-.25,-1.2],F=[0,-.25,-1.2],V=new Float32Array(16),Y=new Float32Array(16),J=!1,re=1,Q=0,ee=!1,k=null,G=null,q=0,H=null,te=()=>{zr===this&&(zr=null),H?.(),H=null;try{C?.cancel?.()}catch{}if(C=null,_){let Z=e?.meshes;if(Array.isArray(Z)){let ie=Z.indexOf(_);ie!==-1&&Z.splice(ie,1)}let ae=e.getGLContext?.()||e?.gl;if(ae)for(let ie of _.primitives||[]){ae.deleteVertexArray?.(ie.vao);for(let de of ie.buffers||[])ae.deleteBuffer?.(de)}_=null}e?.setXRSessionActive?.(!1),A(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=te,E.addEventListener("end",()=>{te(),i.onExit?.()}),E.addEventListener("select",()=>{if(!this.placed){let Z=R||$;F=[Z[0],Z[1],Z[2]],hm(this.placedMat,F,p,Q,h*re),this.placed=!0,_&&(_.visible=!1),y&&(y.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),i.onPlaced?.(this.placedMat)}});try{let Z=e.getGLContext?.()||e?.gl;Z&&typeof Z.makeXRCompatible=="function"&&await Z.makeXRCompatible();let ae=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;Z&&typeof ae=="function"&&typeof E.updateRenderState=="function"&&E.updateRenderState({baseLayer:new ae(E,Z,{alpha:!0})});try{N=await E.requestReferenceSpace("local")}catch{try{N=await E.requestReferenceSpace("local-floor")}catch{N=await E.requestReferenceSpace("viewer")}}let ie=await E.requestReferenceSpace("viewer").catch(()=>N);if(typeof E.requestHitTestSource=="function"&&ie&&(C=await E.requestHitTestSource({space:ie}).catch(()=>null)),g==="immersive-ar"&&Z&&typeof Z.createVertexArray=="function"&&Array.isArray(e.meshes)&&(_=_b(Z,i.reticleColor),e.meshes.push(_)),typeof window<"u"&&typeof window.addEventListener=="function"){let me=ne=>Math.hypot(ne.touches[1].clientX-ne.touches[0].clientX,ne.touches[1].clientY-ne.touches[0].clientY),Se=ne=>Math.atan2(ne.touches[1].clientY-ne.touches[0].clientY,ne.touches[1].clientX-ne.touches[0].clientX),Fe=ne=>{this.s&&(ne.touches.length===1&&this.placed?ee=!0:ne.touches.length>=2&&(ee=!1,k=me(ne),G=Se(ne)))},_e=ne=>{if(!this.s||ne.touches.length<2)return;let Re=me(ne),W=Se(ne);if(k&&k>4&&i.arScale!=="fixed"&&(re=Math.max(.15,Math.min(6,re*(Re/k)))),G!==null){let D=W-G;D>Math.PI&&(D-=Math.PI*2),D<-Math.PI&&(D+=Math.PI*2),Q-=D}k=Re,G=W},Le=ne=>{(!ne.touches||ne.touches.length===0)&&(ee=!1),(!ne.touches||ne.touches.length<2)&&(k=null,G=null)};window.addEventListener("touchstart",Fe,{passive:!0}),window.addEventListener("touchmove",_e,{passive:!0}),window.addEventListener("touchend",Le,{passive:!0}),window.addEventListener("touchcancel",Le,{passive:!0}),H=()=>{window.removeEventListener("touchstart",Fe),window.removeEventListener("touchmove",_e),window.removeEventListener("touchend",Le),window.removeEventListener("touchcancel",Le)}}e.setXRSessionActive?.(!0);let de=(me,Se)=>{if(this.s!==E)return;E.requestAnimationFrame(de);let Fe=q>0?Math.min(Math.max((me-q)/1e3,0),.1):1/60;q=me,e?.stepXRUpdate?.(Fe);let _e=Se.getViewerPose(N);if(!_e)return;let Le=_e.views?.[0];if(!J&&Le?.transform){let O=Le.transform.position,X=Le.transform.matrix,se=O?.x??(X?X[12]:0),ce=O?.y??(X?X[13]:0),pe=O?.z??(X?X[14]:0),xe=X?-X[8]:0,he=X?-X[10]:-1,Ne=Math.hypot(xe,he);Ne>1e-4?(xe/=Ne,he/=Ne):(xe=0,he=-1),$=[se+xe*1.2,ce-.25,pe+he*1.2],Q=Math.atan2(-xe,-he),J=!0}if(C&&typeof Se.getHitTestResults=="function"&&(!this.placed||ee)){let O=Se.getHitTestResults(C)||[],X=!1;for(let se of O){let ce=se.getPose(N);if(ce?.transform?.matrix){let pe=ce.transform.matrix,xe=pe[5];if(i.arPlacement==="wall"&&Math.abs(xe)>.35||i.arPlacement==="floor"&&Math.abs(xe)<.65)continue;P||(P=new Float32Array(16)),P.set(pe),R=[pe[12],pe[13],pe[14]],this.placed&&ee&&(F=[pe[12],pe[13],pe[14]]),_&&(_.visible=!this.placed||ee,_.transform.set(pe)),!this.placed&&y&&(y.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),i.onHit?.(P),X=!0;break}}!X&&_&&(_.visible=!1)}hm(V,this.placed?F:R||$,p,Q,h*re),this.placed&&this.placedMat.set(V);let ne=e.xrRigMatrix;ne instanceof Float32Array&&ne.length===16?at(Y,ne,V):Y.set(V),e.modelRootMatrix&&e.modelRootMatrix.set(Y);for(let O of kt)O.onXRFrame?.(e,E,Se,N);let Re=e.getGLContext?.()||e?.gl,W=E.renderState?.baseLayer;Re&&W&&W.framebuffer!==void 0&&Re.bindFramebuffer(36160,W.framebuffer);let D=g==="immersive-ar",z=_e.views||[];for(let O=0;O<z.length;O++){let X=z[O];if(typeof e.renderXRView=="function"){let se;if(W&&typeof W.getViewport=="function"){let ce=W.getViewport(X);ce&&ce.width>0&&ce.height>0&&(se=[ce.x,ce.y,ce.width,ce.height])}else W?.framebufferWidth>0&&W?.framebufferHeight>0&&(se=[0,0,W.framebufferWidth,W.framebufferHeight]);e.renderXRView(X,Y,this.placed,se,D,O)}}Re&&W&&W.framebuffer&&Re.bindFramebuffer(36160,null)};E.requestAnimationFrame(de)}catch(Z){throw typeof E.end=="function"&&await E.end().catch(()=>{}),te(),i.onError?.(Z),Z}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function Xa(e){let t=await Wa(),r=e.preferredModes||["quick-look","webxr","scene-viewer"],i=null;for(let o of r)if(t.availableModes.includes(o)){i=o;break}if(i||(i=t.bestMode),!i)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let n={...e.quickLookOptions,allowScale:e.arScale==="fixed"?!1:e.quickLookOptions?.allowScale},a={...e.sceneViewerOptions,resizable:e.arScale==="fixed"?!1:e.sceneViewerOptions?.resizable,enableVerticalPlacement:e.arPlacement==="wall"?!0:e.sceneViewerOptions?.enableVerticalPlacement},s={...e.webXROptions,arScale:e.arScale||e.webXROptions?.arScale,arPlacement:e.arPlacement||e.webXROptions?.arPlacement};try{if(i==="quick-look"){let o;if(e.model instanceof Blob&&e.model.type==="model/vnd.usdz+zip")o=e.model;else{if(typeof e.model=="string")return mm(e.model,n),{mode:"quick-look",success:!0};o=Zr(e.model)}return mm(o,n),{mode:"quick-look",success:!0}}if(i==="scene-viewer"){let o=e.glbUrl||(typeof e.model=="string"?e.model:null);if(!o)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return Tb(o,a),{mode:"scene-viewer",success:!0}}if(i==="webxr"){if(!e.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let o=new du(s);return await o.start(e.view,e.element),{mode:"webxr",success:!0,session:o}}}catch(o){return{mode:i,success:!1,error:o}}return{mode:i,success:!1,error:new Error(`Unhandled AR mode: ${i}`)}}kn.registerAR({activateAR:Xa,createUSDZBlob:Zr}),kn.registerScriptRunner(so),gt(Di),gt(Oc);var bu=new WeakMap;function qa(e,t){let r=t instanceof Float32Array?t:new Float32Array(t);bu.set(e,r)}function gm(e){return bu.get(e)}async function Eb(e,t){if(!t)return null;let r;if(typeof t=="string")if(typeof fetch<"u"&&typeof createImageBitmap=="function"){let n=await(await fetch(t)).blob();r=await createImageBitmap(n)}else if(typeof Image<"u")r=await new Promise((n,a)=>{let s=new Image;s.crossOrigin="anonymous",s.onload=()=>n(s),s.onerror=a,s.src=t});else return null;else r=t;let i=e.createTexture();return e.bindTexture(3553,i),e.texImage2D(3553,0,6408,6408,5121,r),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071),e.texParameteri(3553,10241,9987),e.texParameteri(3553,10240,9729),e.generateMipmap(3553),i&&(i.__gpuImageSource=r),i}var pu=new WeakMap,bm=new Float32Array(16);async function ym(e,t,r){let i=r?await Eb(e.gl,r):null;e[t]&&e.gl.deleteTexture(e[t]),e[t]=i}var yu={name:"environment-map",onContextRestored(e){pu.delete(e)},setEnvironmentImage(e,t){return ym(e,"environmentTexture",t)},setSkyboxImage(e,t){return ym(e,"skyboxTexture",t)},onBeforeDrawScene(e,t,r,i,n){if(!e.skyboxTexture||typeof t.createProgram!="function")return;let a=pu.get(t);if(!a){let m=(g,x)=>{let v=t.createShader(g);return t.shaderSource(v,x),t.compileShader(v),v},h=t.createProgram();t.attachShader(h,m(35633,`#version 300 es
|
|
449
|
+
out vec2 vNDC;void main(){vec2 p=vec2((gl_VertexID<<1)&2,gl_VertexID&2);vNDC=p*2.-1.;gl_Position=vec4(vNDC,.999999,1.);}`)),t.attachShader(h,m(35632,`#version 300 es
|
|
450
|
+
precision highp float;in vec2 vNDC;uniform mat4 uInvVP;uniform vec3 uCameraPos;uniform sampler2D uSkyboxMap;uniform float uExposure;out vec4 fragColor;vec2 eqUV(vec3 d){return vec2(atan(d.x,d.z)/6.2831853+.5,asin(clamp(d.y,-1.,1.))/3.1415926+.5);}void main(){vec4 fp=uInvVP*vec4(vNDC,1.,1.);vec3 dir=normalize(fp.xyz/fp.w-uCameraPos);fragColor=vec4(pow(texture(uSkyboxMap,eqUV(dir)).rgb*uExposure,vec3(1./2.2)),1.);}`)),t.linkProgram(h);let p=typeof t.createVertexArray=="function"?t.createVertexArray():null;a={program:h,vao:p},pu.set(t,a)}let s=Kr(bm,r)||bm;t.depthMask(!1),t.useProgram(a.program),a.vao&&t.bindVertexArray(a.vao),t.activeTexture(33984),t.bindTexture(3553,e.skyboxTexture);let o=t.getUniformLocation(a.program,"uSkyboxMap");o&&t.uniform1i(o,0);let l=t.getUniformLocation(a.program,"uInvVP");l&&t.uniformMatrix4fv(l,!1,s);let c=t.getUniformLocation(a.program,"uCameraPos");c&&t.uniform3f(c,i[0],i[1],i[2]);let f=t.getUniformLocation(a.program,"uExposure");f&&t.uniform1f(f,e.exposure??1),t.drawArrays(4,0,3),t.depthMask(!0)},onResolveShader(e,t,r,i){if(i.includes("evalSHIrradiance"))return null;let n=i.replace("out vec4 fragColor;",`uniform vec3 uSH[9];
|
|
403
451
|
uniform int uHasSH;
|
|
404
452
|
out vec4 fragColor;`).replace("void main(){",`vec3 integrateBRDFApprox(vec3 f0,float r,float NoV){vec4 c0=vec4(-1.,-.0275,-.572,.022),c1=vec4(1.,.0425,1.04,-.04),rv=r*c0+c1;float a=min(rv.x*rv.x,exp2(-9.28*NoV))*rv.x+rv.y;vec2 ab=vec2(-1.04,1.04)*a+rv.zw;return f0*ab.x+vec3(ab.y);}
|
|
405
453
|
vec3 evalSHIrradiance(vec3 n){return max(vec3(0.),uSH[0]+uSH[1]*n.y+uSH[2]*n.z+uSH[3]*n.x+uSH[4]*(n.x*n.y)+uSH[5]*(n.y*n.z)+uSH[6]*(3.*n.z*n.z-1.)+uSH[7]*(n.x*n.z)+uSH[8]*(n.x*n.x-n.y*n.y));}
|
|
@@ -412,15 +460,15 @@ envDiffuse=uHasSH==1?evalSHIrradiance(N):textureLod(uEnvironmentMap,equirectangu
|
|
|
412
460
|
}else if(uHasSH==1){
|
|
413
461
|
specularIBL=getStudioRadiance(R,roughness)*integrateBRDFApprox(F,roughness,NoV);
|
|
414
462
|
envDiffuse=evalSHIrradiance(N);
|
|
415
|
-
}`),{vs:r,fs:n}},onBeforeDrawPrimitive(e,t,r,i,n,s){let l=fo.get(e),o=e.getUniformLocation(t,"uHasSH");if(l&&l.length>=27){o&&e.uniform1i(o,1);let a=e.getUniformLocation(t,"uSH");a&&e.uniform3fv(a,l)}else o&&e.uniform1i(o,0)},onAttributeChanged(e,t,r,i){t==="environment-image"&&e.viewer?this.setEnvironmentImage?.(e.viewer,i):t==="skybox-image"&&e.viewer&&this.setSkyboxImage?.(e.viewer,i)}},po=new WeakMap;function bo(e,t){let r=t||e.viewer;if(!r||typeof r.projectPointToScreen!="function")return;let i=e.mockHotspots||e.querySelectorAll('[slot^="hotspot-"], [data-position]');for(let n=0;n<i.length;n++){let s=i[n],l=s.getAttribute("data-position");if(!l)continue;let o=l.trim().split(/\s+/).map(m=>parseFloat(m.replace(/m$/,"")));if(o.length<3||o.some(isNaN))continue;let a=s.getAttribute("data-normal"),u;if(a){let m=a.trim().split(/\s+/).map(c=>parseFloat(c));m.length>=3&&!m.some(isNaN)&&(u=[m[0],m[1],m[2]])}let h=r.projectPointToScreen([o[0],o[1],o[2]],u);s.style.position="absolute",s.style.left="0",s.style.top="0",s.style.transform=`translate(-50%, -50%) translate3d(${h.x}px, ${h.y}px, 0)`,s.style.zIndex="3",h.visible?(s.style.opacity="1",s.style.pointerEvents="auto",s.removeAttribute("data-occluded")):(s.style.opacity="0",s.style.pointerEvents="none",s.setAttribute("data-occluded",""))}}var yo={name:"hotspots",updateHotspotsForElement:bo,onElementConnected(e){if(typeof MutationObserver>"u"||!e)return;let t=new MutationObserver(()=>{bo(e)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-position","data-normal"]}),po.set(e,t)},onCameraChange(e,t){t&&bo(t,e)},onElementDisconnected(e){let t=po.get(e);t&&(t.disconnect(),po.delete(e))}},na=1024,go=256,li=2048,Wc=128,jc=64,Kc=16,qc=1e4,Yc=8,Rt=new Set(["__proto__","constructor","prototype"]),ra={neg:e=>-e,abs:Math.abs,sign:Math.sign,floor:Math.floor,ceil:Math.ceil,round:Math.round,trunc:Math.trunc,fract:e=>e-Math.floor(e),sqrt:e=>Math.sqrt(Math.max(0,e)),cbrt:Math.cbrt,exp:Math.exp,log:e=>e>0?Math.log(e):0,sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:e=>Math.asin(Math.max(-1,Math.min(1,e))),acos:e=>Math.acos(Math.max(-1,Math.min(1,e))),atan:Math.atan,rad:e=>e*Math.PI/180,deg:e=>e*180/Math.PI,saturate:e=>Math.max(0,Math.min(1,e))},ia={add:(e,t)=>e+t,sub:(e,t)=>e-t,mul:(e,t)=>e*t,div:(e,t)=>Math.abs(t)<1e-12?0:e/t,rem:(e,t)=>Math.abs(t)<1e-12?0:e%t,mod:(e,t)=>Math.abs(t)<1e-12?0:e%t,min:Math.min,max:Math.max,pow:Math.pow,atan2:Math.atan2},mi={translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1]},fi=(e,t)=>e!==null&&typeof e=="object"&&!Rt.has(t)&&Object.prototype.hasOwnProperty.call(e,t),it=e=>Array.isArray(e)?[...e]:e,ca=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&fi(e,"value")?e.value:e,De=(e,t)=>fi(e.configuration,t)?ca(e.configuration[t]):void 0,he=(e,t=0)=>{let r=Number(e);return Number.isFinite(r)?r:t},$t=e=>Math.max(0,Math.min(1,e)),ft=e=>typeof e=="boolean"?e:typeof e=="number"?e!==0&&!Number.isNaN(e):typeof e=="string"?e.length>0&&e!=="false":!!e;function Kn(e){if(typeof e!="string"||!e.startsWith("/"))return null;let t=[];for(let r of e.slice(1).split("/")){let i=r.replace(/~1/g,"/").replace(/~0/g,"~");if(!i||Rt.has(i)||Rt.has(r))return null;t.push(i)}return{segments:t}}var dn=(e,t)=>{if(e===void 0||!/^\d+$/.test(e))return-1;let r=Number(e);return Number.isSafeInteger(r)&&r>=0&&r<t?r:-1},oa=e=>{let t=he(e[0]),r=he(e[1]),i=he(e[2]),n=he(e[3],1),s=Math.hypot(t,r,i,n);return s>1e-8?[t/s,r/s,i/s,n/s]:[0,0,0,1]},sa=(e,t,r,i)=>{if(typeof e=="number"&&typeof t=="number")return e+(t-e)*r;if(Array.isArray(e)&&Array.isArray(t)){if(i&&e.length===4&&t.length===4){let n=[0,0,0,1];return oi(n,oa(e),oa(t),r),n}return e.slice(0,t.length).map((n,s)=>n+(t[s]-n)*r)}return r>=.5?t:e},xo=(e,t,r)=>Array.isArray(e)&&Array.isArray(t)?e.slice(0,t.length).map((i,n)=>r(he(i),he(t[n]))):Array.isArray(e)?e.map(i=>r(he(i),he(t))):Array.isArray(t)?t.map(i=>r(he(e),he(i))):r(he(e),he(t)),Zc=(e,t)=>Array.isArray(e)?e.map(r=>t(he(r))):t(he(e)),aa=(e,t)=>Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every((r,i)=>Math.abs(r-t[i])<=1e-6):e===t,qn=class{constructor(e,t,r){let i=Array.isArray(r.nodes)?r.nodes:[];if(i.length>na)throw new Error(`SecurityError: Exceeds MAX_GRAPH_NODES (${na})`);let n=Array.isArray(r.variables)?r.variables:[];if(n.length>go)throw new Error(`SecurityError: Exceeds MAX_VARIABLES (${go})`);let s=Array.isArray(r.declarations)?r.declarations:[],l=Array.isArray(r.events)?r.events:[],o=new Map,a=new Map,u=new Map,h=new Map,m=new Map,c=new Map,d=[],f=[],g=new Map,x=1,b=0,v=0,p=0,y=0,M=!1,P=!1,F=!1;n.forEach((B,$)=>{if(!B||typeof B!="object")return;let _=it(ca(B.value));o.set($,_);let G=B.id??B.name;typeof G=="string"&&G&&!Rt.has(G)&&o.set(G,_)}),(t?.nodes||[]).forEach((B,$)=>{for(let _ of B?.children||[])typeof _=="number"&&g.set(_,$)});let W=B=>B.op||typeof B.declaration=="number"&&s[B.declaration]?.op||"",T=(B,$,_)=>{if(Rt.has($))return;let G=a.get(B);G||a.set(B,G=Object.create(null)),G[$]=_},E=(B,$)=>{if(typeof B!="number"&&typeof B!="string"||typeof B=="string"&&Rt.has(B)||!o.has(B)&&o.size>=go*2)return;let _=it($);if(o.set(B,_),typeof B=="number"){let G=n[B]?.id??n[B]?.name;typeof G=="string"&&!Rt.has(G)&&o.set(G,_)}},S=B=>typeof B=="number"?l[B]?.id??String(B):typeof B=="string"?/^\d+$/.test(B)&&l[Number(B)]?.id?l[Number(B)].id:B:"",O=(B,$)=>{for(let _=B,G=0;_!==void 0&&_>=0&&G<128;_=g.get(_),G++)if(_===$)return!0;return!1},k=B=>{for(let $=d.length-1;$>=0;$--)d[$].key===B&&d.splice($,1)},w=B=>{k(B.key),d.length>=Wc&&d.shift(),d.push(B)},ie=B=>{let $=Kn(B)?.segments;if($){if($[0]==="nodes"&&Array.isArray(t?.nodes)){let _=t.nodes[dn($[1],t.nodes.length)];if(!_)return;let G=$[2];if(G in mi){let j=mi[G],q=_[G]||j;return j.map((D,Y)=>he(q[Y],D))}if(G==="weights"){let j=Array.isArray(_.weights)?_.weights:[0],q=$.length===4?dn($[3],64):-2;return q===-2?j.map(D=>he(D)):q>=0?he(j[q]):void 0}if(G==="visible"||G==="extensions"&&$[3]==="KHR_node_visibility"&&$[4]==="visible")return _.extensions?.KHR_node_visibility?.visible??_.visible??!0}else if($[0]==="materials"&&Array.isArray(t?.materials)){let _=t.materials[dn($[1],t.materials.length)];if(!_)return;let G=_.pbrMetallicRoughness||{};if($[2]==="pbrMetallicRoughness"){if($[3]==="baseColorFactor"){let j=G.baseColorFactor||[1,1,1,1];return[he(j[0],1),he(j[1],1),he(j[2],1),he(j[3],1)]}if($[3]==="metallicFactor"||$[3]==="roughnessFactor")return he(G[$[3]],1)}if($[2]==="emissiveFactor"){let j=_.emissiveFactor||[0,0,0];return[he(j[0]),he(j[1]),he(j[2])]}if($[2]==="alphaCutoff")return he(_.alphaCutoff,.5)}}},oe=(B,$)=>{let _=Kn(B)?.segments;if(!_)return!1;if(_[0]==="nodes"&&Array.isArray(t?.nodes)){let G=dn(_[1],t.nodes.length),j=t.nodes[G];if(!j)return!1;let q=_[2];if(q in mi&&Array.isArray($)){let D=mi[q];if($.length<D.length)return!1;let Y=D.map((se,le)=>he($[le],se));if(q==="rotation"){let se=Math.hypot(...Y);Y=se>1e-8?Y.map(le=>le/se):[0,0,0,1]}j[q]=Y,delete j.matrix;let te=e?.initialNodeTransforms?.[G];return te&&(te[q[0]]=[...Y]),M=!0,!0}if(q==="weights"){Array.isArray(j.weights)||(j.weights=[]);let D=(Y,te)=>{for(let se of e?.meshes||[])if(se.nodeIndex===G)for(let le of se.primitives||[])le.pluginData?.morph?.weights&&(le.pluginData.morph.weights[Y]=te)};if(_.length===4){let Y=dn(_[3],64);if(Y<0)return!1;D(Y,j.weights[Y]=he($))}else if(Array.isArray($))j.weights=$.slice(0,64).map(Y=>he(Y)),j.weights.forEach((Y,te)=>D(te,Y));else return!1;return F=!0,!0}if(q==="visible"||q==="extensions"&&_[3]==="KHR_node_visibility"&&_[4]==="visible"){let D=ft($);return j.visible=D,(!j.extensions||typeof j.extensions!="object")&&(j.extensions={}),j.extensions.KHR_node_visibility={visible:D},P=!0,!0}}else if(_[0]==="materials"&&Array.isArray(t?.materials)){let G=dn(_[1],t.materials.length),j=t.materials[G];if(!j)return!1;let q=j.pbrMetallicRoughness||(j.pbrMetallicRoughness={}),D=Y=>{for(let te of e?.meshes||[])for(let se of te.primitives||[])(se.materialIndex??0)===G&&Y(se)};if(_[2]==="pbrMetallicRoughness"){if(_[3]==="baseColorFactor"&&Array.isArray($)&&$.length>=3){let Y=[$t(he($[0],1)),$t(he($[1],1)),$t(he($[2],1)),$[3]!==void 0?$t(he($[3],1)):q.baseColorFactor?.[3]??1];return q.baseColorFactor=Y,D(te=>te.baseColor=[...Y]),F=!0}if(_[3]==="metallicFactor"||_[3]==="roughnessFactor"){let Y=_[3]==="metallicFactor",te=$t(he($,Y?0:.5));return q[_[3]]=te,D(se=>se[Y?"metallic":"roughness"]=te),F=!0}}if(_[2]==="emissiveFactor"&&Array.isArray($)&&$.length>=3)return j.emissiveFactor=[0,1,2].map(Y=>Math.max(0,he($[Y]))),F=!0;if(_[2]==="alphaCutoff")return j.alphaCutoff=$t(he($,.5)),F=!0}return!1},I=(B,$,_=new Set)=>{let G=De($,"pointer");if(typeof G!="string"||!G.startsWith("/"))return null;let j=G.replace(/\{([a-zA-Z0-9_]+)\}/g,(q,D)=>{let Y=Math.trunc(Number(H(B,D,void 0,_)??De($,D)));return Number.isSafeInteger(Y)&&Y>=0?String(Y):"-1"});return Kn(j)?j:null},H=(B,$,_,G)=>{let j=i[B]?.values;if(!fi(j,$))return _;let q=j[$];if(q==null)return _;if(typeof q!="object"||Array.isArray(q))return it(q);let D=q;return typeof D.node=="number"?N(D.node,D.socket||"value",G):fi(D,"value")?it(D.value):_},N=(B,$,_)=>{if(B<0||B>=i.length||_.has(B)||_.size>128||++p>qc)return;let G=i[B],j=W(G);if(/^(event\/|pointer\/on|scene\/on|flow\/)/.test(j))return it(a.get(B)?.[$]);_.add(B);try{let q=(D,Y=0)=>H(B,D,Y,_);if(j==="variable/get"){let D=De(G,"variable")??De(G,"id");return typeof D=="number"||typeof D=="string"?it(o.get(D)):void 0}if(j==="pointer/get"){let D=I(B,G,_);return D?ie(D):void 0}if(j.startsWith("math/")){let D=j.slice(5);if(D in ra)return Zc(q("a"),ra[D]);if(D in ia){let Y=/^(mul|div|rem|mod|pow)$/.test(D)?1:0;return xo(q("a",D==="mul"?1:0),q("b",Y),ia[D])}if(D==="pi")return Math.PI;if(D==="e")return Math.E;if(D==="random")return Math.random();if(D==="clamp")return xo(xo(q("a"),q("b",q("min",0)),Math.max),q("c",q("max",1)),Math.min);if(D==="mix"||D==="quatSlerp")return sa(q("a",0),q("b",1),he(q("c",q("t",.5)),.5),D==="quatSlerp");if(D==="dot"){let Y=q("a"),te=q("b");return Array.isArray(Y)&&Array.isArray(te)?Y.reduce((se,le,V)=>se+(le||0)*(te[V]||0),0):he(Y)*he(te)}if(D==="cross"){let Y=q("a",[0,0,0]),te=q("b",[0,0,0]);return Array.isArray(Y)&&Array.isArray(te)?[(Y[1]||0)*(te[2]||0)-(Y[2]||0)*(te[1]||0),(Y[2]||0)*(te[0]||0)-(Y[0]||0)*(te[2]||0),(Y[0]||0)*(te[1]||0)-(Y[1]||0)*(te[0]||0)]:[0,0,0]}if(D==="length"){let Y=q("a");return Array.isArray(Y)?Math.hypot(...Y):Math.abs(he(Y))}if(D==="distance"){let Y=q("a"),te=q("b");return Array.isArray(Y)&&Array.isArray(te)?Math.hypot(...Y.map((se,le)=>(se||0)-(te[le]||0))):Math.abs(he(Y)-he(te))}if(D==="normalize"){let Y=q("a");if(!Array.isArray(Y))return he(Y)>=0?1:-1;let te=Math.hypot(...Y);return te>1e-8?Y.map(se=>se/te):Y.map(()=>0)}if(D.startsWith("combine"))return["a","b","c","d"].slice(0,Number(D[7])||2).map(Y=>he(q(Y)));if(D.startsWith("extract")){let Y=q("a");return Array.isArray(Y)?Y[$==="0"||$==="x"?0:$==="1"||$==="y"?1:$==="2"||$==="z"?2:3]??0:0}if(D==="eq")return aa(q("a"),q("b"));if(D==="ne")return!aa(q("a"),q("b"));if(D==="lt")return he(q("a"))<he(q("b"));if(D==="le")return he(q("a"))<=he(q("b"));if(D==="gt")return he(q("a"))>he(q("b"));if(D==="ge")return he(q("a"))>=he(q("b"));if(D==="isNaN")return Number.isNaN(Number(q("a")));if(D==="isInf"){let Y=Number(q("a"));return!Number.isFinite(Y)&&!Number.isNaN(Y)}return D==="and"?ft(q("a",!1))&&ft(q("b",!1)):D==="or"?ft(q("a",!1))||ft(q("b",!1)):D==="xor"?ft(q("a",!1))!==ft(q("b",!1)):D==="not"?!ft(q("a",!1)):D==="select"?it(ft(q("condition",!1))?q("a"):q("b")):void 0}return j==="type/boolToInt"||j==="type/boolToFloat"?ft(q("a",!1))?1:0:j==="type/intToBool"||j==="type/floatToBool"?he(q("a",0))!==0:j==="type/intToFloat"?he(q("a",0)):j==="type/floatToInt"?Math.trunc(he(q("a",0))):void 0}finally{_.delete(B)}},z=()=>{if(M){M=!1,F=!0;let B=Ft(t);if(e){e.worldMatrices=B;for(let $ of e.meshes||[])$.nodeIndex>=0&&$.nodeIndex<B.length&&($.transform.set(B[$.nodeIndex]),Xe($.normalMatrix,$.transform))}}if(P){P=!1,F=!0;let B=t?.nodes;if(Array.isArray(e?.meshes)&&Array.isArray(B))for(let $ of e.meshes){let _=!0;for(let G=$.nodeIndex,j=0;G!==void 0&&G>=0&&j<128;G=g.get(G),j++){let q=B[G];if(q?.visible===!1||q?.extensions?.KHR_node_visibility?.visible===!1){_=!1;break}}$.visible=_}}F&&(F=!1,e?.render?.())},ue=(B,$={steps:0})=>{if(!B||typeof B.node!="number")return;$.steps===0&&(p=0);let _=[B],G=j=>{_.length+$.steps<li&&_.push(j)};for(;_.length>0&&$.steps<li;){$.steps++;let j=_.shift();if(!j||j.node<0||j.node>=i.length)continue;let q=j.node,D=i[q];if(!D)continue;let Y=j.socket||"in",te=W(D),se=(V,ee=void 0)=>H(q,V,ee,new Set),le=(V="out")=>{let ee=D.flows?.[V];ee&&G(ee)};switch(te){case"flow/branch":le(ft(se("condition",!1))?"true":"false");break;case"flow/sequence":for(let V of Object.keys(D.flows||{}).sort((ee,R)=>Number(ee)-Number(R)||ee.localeCompare(R)))le(V);break;case"flow/switch":{let V=D.flows?.[String(se("selection",se("value",0)))]??D.flows?.default;V&&G(V);break}case"flow/for":{let V=Math.trunc(he(se("startIndex",0))),ee=Math.trunc(he(se("endIndex",0))),R=Math.max(1,Math.trunc(he(se("step",1),1))),A=D.flows?.body;if(A&&ee>V&&y<Yc){let C=Math.min(Math.ceil((ee-V)/R),li);y++;try{for(let U=0;U<C&&$.steps<li;U++)T(q,"index",V+U*R),ue(A,$)}finally{y--}}let L=D.flows?.completed??D.flows?.out;L&&G(L);break}case"flow/doN":{let V=Y==="reset"?0:(u.get(q)||0)+1;if(u.set(q,V),T(q,"currentCount",V),T(q,"count",V),Y!=="reset"){let ee=Math.trunc(he(se("n",De(D,"stopIterations")??De(D,"n")??1),1));V<=ee&&le()}break}case"flow/multiGate":{if(Y==="reset"){c.set(q,0);break}let V=Object.keys(D.flows||{}).sort();if(!V.length)break;let ee=De(D,"isRandom")?Math.floor(Math.random()*V.length):c.get(q)||0;ee<V.length&&(le(V[ee]),c.set(q,De(D,"isLoop")!==!1?(ee+1)%V.length:ee+1));break}case"flow/waitAll":{if(Y==="reset"){h.delete(q);break}let V=h.get(q);V||h.set(q,V=new Set),V.add(Y),V.size>=Math.max(1,Math.trunc(Number(De(D,"inputFlows")??2)||2))&&(V.clear(),le("out"),le("completed"));break}case"flow/throttle":{if(Y==="reset"){m.delete(q);break}let V=Math.max(0,he(se("duration",0))),ee=m.get(q);ee===void 0||b-ee>=V?(m.set(q,b),T(q,"lastRemainingTime",0),le()):T(q,"lastRemainingTime",Math.max(0,V-(b-ee)));break}case"flow/delay":case"flow/setDelay":{if(Y==="cancel"){for(let A=f.length-1;A>=0;A--)f[A].nodeIdx===q&&f.splice(A,1);T(q,"lastDelayIndex",-1);break}let V=Math.max(0,he(se("duration",De(D,"duration")??0))),ee=D.flows?.done??D.flows?.out;if(V<=0){T(q,"lastDelayIndex",-1),ee&&G(ee);break}f.length>=jc&&f.shift();let R=x++;T(q,"lastDelayIndex",R),f.push({id:R,nodeIdx:q,rem:V,done:ee}),te==="flow/setDelay"&&D.flows?.out&&D.flows?.done&&le("out");break}case"flow/cancelDelay":{let V=Math.trunc(he(se("delayIndex",-1),-1));if(V<0)f.length=0;else for(let ee=f.length-1;ee>=0;ee--)f[ee].id===V&&f.splice(ee,1);le();break}case"variable/set":E(De(D,"variable")??De(D,"id"),se("value")),le();break;case"variable/interpolate":{let V=De(D,"variable")??De(D,"id"),ee=se("value",se("target")),R=Math.max(0,he(se("duration",De(D,"duration")??.3),.3));V!==void 0&&ee!==void 0&&w({key:`var:${String(V)}`,varKey:V,from:it(se("from")??o.get(V)??0),to:it(ee),dur:R,elapsed:0,quat:!1,linear:De(D,"easing")==="linear",done:D.flows?.done}),le();break}case"pointer/set":{let V=I(q,D),ee=se("value");V&&ee!==void 0&&(k(`ptr:${V}`),oe(V,ee)),le();break}case"pointer/interpolate":{let V=I(q,D),ee=se("value",se("target")),R=Math.max(0,he(se("duration",De(D,"duration")??.3),.3));if(V&&ee!==void 0){let A=se("from")??ie(V);A!==void 0&&(R<=0?(oe(V,ee),le("done")):w({key:`ptr:${V}`,ptr:V,from:it(A),to:it(ee),dur:R,elapsed:0,quat:V.endsWith("/rotation"),linear:De(D,"easing")==="linear",done:D.flows?.done}))}le();break}case"animation/start":{let V=se("animation")??De(D,"animation")??De(D,"clipName"),ee=typeof V=="number"?e?.animations?.[V]?.name??t?.animations?.[V]?.name:typeof V=="string"?V:void 0;e?.playAnimation?.(ee),F=!0,le();break}case"animation/stop":case"animation/resetAt":e?.pauseAnimation?.(),te==="animation/resetAt"&&e?.evaluateAnimation?.(he(se("time",0))),F=!0,le();break;case"event/send":case"customEvent/send":{let V=S(De(D,"event")??De(D,"id")),ee={};for(let R of Object.keys(D.values||{}))Rt.has(R)||(ee[R]=se(R));V&&(typeof CustomEvent<"u"&&typeof e?.container?.dispatchEvent=="function"&&e.container.dispatchEvent(new CustomEvent("interactivityEvent",{bubbles:!0,composed:!0,detail:{id:V,values:ee}})),ce(V,ee,$)),le();break}default:le();break}}};this.readScenePointer=ie,this.writeScenePointer=oe,this.fireOnStart=()=>{i.forEach(B=>{W(B)==="event/onStart"&&ue(B.flows?.out)}),z()},this.fireOnSelect=B=>{if(!B)return;let $=typeof B.meshIndex=="number"?B.meshIndex:-1,_=typeof B.nodeIndex=="number"?B.nodeIndex:e?.meshes?.[$]?.nodeIndex??-1;i.forEach((G,j)=>{if(!/^(pointer|event|scene)\/onSelect$/.test(W(G)))return;let q=De(G,"nodeIndex")??De(G,"node")??H(j,"nodeIndex",void 0,new Set),D=De(G,"meshName");if(typeof D=="string"&&D?B.meshName===D:q==null||Number(q)<0||Number.isNaN(Number(q))||O(_,Math.trunc(Number(q)))){if(T(j,"nodeIndex",_),T(j,"meshIndex",$),Array.isArray(B.hitPoint)){let Y=[he(B.hitPoint[0]),he(B.hitPoint[1]),he(B.hitPoint[2])];T(j,"hitPoint",Y),T(j,"point",Y),T(j,"intersectionPoint",Y)}if(Array.isArray(B.normal)){let Y=[he(B.normal[0]),he(B.normal[1],1),he(B.normal[2])];T(j,"normal",Y),T(j,"hitNormal",Y)}typeof B.distance=="number"&&T(j,"distance",B.distance),ue(G.flows?.out)}}),z()},this.receiveCustomEvent=(B,$={})=>ce(B,$,{steps:0});function ce(B,$,_){if(!(v>=Kc)){v++;try{let G=S(B);i.forEach((j,q)=>{if(!/^(customE|e)vent\/receive$/.test(W(j)))return;let D=De(j,"event")??De(j,"id");if(!(S(D)!==G&&String(D)!==String(B))){for(let[Y,te]of Object.entries($))Rt.has(Y)||T(q,Y,it(te));ue(j.flows?.out,_)}}),z()}finally{v--}}}this.tick=B=>{if(!Number.isFinite(B)||B<0)return;let $=Math.min(B,.25);b+=$,i.forEach((G,j)=>{W(G)==="event/onTick"&&(T(j,"timeDelta",$),T(j,"dt",$),T(j,"timeElapsed",b),ue(G.flows?.out))});let _=[];for(let G=d.length-1;G>=0;G--){let j=d[G];j.elapsed+=$;let q=j.dur>1e-6?$t(j.elapsed/j.dur):1,D=j.linear?q:q*q*(3-2*q),Y=sa(j.from,j.to,D,j.quat);j.ptr?oe(j.ptr,Y):j.varKey!==void 0&&E(j.varKey,Y),q>=1&&(d.splice(G,1),j.done&&_.push(j.done))}for(let G=f.length-1;G>=0;G--){let j=f[G];j.rem-=$,j.rem<=0&&(f.splice(G,1),j.done&&_.push(j.done))}for(let G of _)ue(G);z()},this.dispose=()=>{d.length=0,f.length=0,o.clear(),a.clear(),u.clear(),h.clear(),m.clear(),c.clear()}}},xt=new WeakMap,di=new WeakMap;function Qc(e,t){if(!e||typeof e!="object"||!Number.isFinite(t)||t<=0||tr().some(o=>o.name==="xr-live-head-follow")||(typeof e.getAutoRotate=="function"?e.getAutoRotate():e.autoRotate)===!1)return;let r=e.gltf,i=r?.nodes;if(!Array.isArray(i)||i.length===0)return;let n=Math.min(t,.1),s=(di.get(e)||0)+n,l=!1;for(let o=0;o<i.length;o++){let a=i[o],u=xs(a?.extras?.xr?.orbit);if(!u)continue;let h=0,m=0,c=0;if(Array.isArray(u.target))h=u.target[0],m=u.target[1],c=u.target[2];else if(typeof u.target=="string"&&u.target!=="head"){let b=i.find(v=>v?.name===u.target);Array.isArray(b?.translation)&&(h=he(b.translation[0]),m=he(b.translation[1]),c=he(b.translation[2]))}let d=u.phase+u.speed*s,f=h+Math.cos(d)*u.radius,g=m+u.height,x=c+Math.sin(d)*u.radius;if(a.translation=[f,g,x],u.faceCenter){let b=Math.atan2(h-f,c-x);a.rotation=[0,Math.sin(b*.5),0,Math.cos(b*.5)]}l=!0}if(l){di.set(e,s);let o=Ft(r);e.worldMatrices=o;for(let a of e.meshes||[])a.nodeIndex>=0&&a.nodeIndex<o.length&&(a.transform.set(o[a.nodeIndex]),Xe(a.normalMatrix,a.transform))}}function hi(e){if(!(!e||typeof e!="object"))return xt.get(e)||xt.get(e.viewer)||xt.get(e._view)}function vo(e,t,r){let i=hi(e);return i?(i.receiveCustomEvent(t,r),!0):!1}var Mo={name:"khr-interactivity",sendInteractivityEvent:vo,getInteractivityVM:hi,onLoadModel(e,t){if(!e||typeof e!="object")return;xt.get(e)?.dispose(),xt.delete(e),di.delete(e);let r=t?.extensions?.KHR_interactivity,i=Array.isArray(r?.graphs)?r.graphs[r.graph??0]:r;if(!i||!Array.isArray(i.nodes))return;let n=new qn(e,t,i);xt.set(e,n),n.fireOnStart()},onMeshSelect(e,t){xt.get(e)?.fireOnSelect(t)},onUpdate(e,t){xt.get(e)?.tick(t),Qc(e,t)},onDestroy(e,t){xt.get(t)?.dispose(),xt.delete(t),di.delete(t)}},Yn=new Map,pi=new WeakMap;function ua(e,t){Yn.set(e,t)}var To={name:"materials",onContextRestored(e){pi.delete(e)},onBuildPrimitiveVAO(e,t,r,i,n){return(((i?.materials&&r.material!==void 0?i.materials[r.material]:null)?.extensions||{}).KHR_materials_transmission?.transmissionFactor??0)>0?{isTransmissive:!0}:null},onBeforeTransmissivePass(e,t){let r=pi.get(e);r||(r=e.createTexture(),pi.set(e,r));let i=Math.max(1,t.canvas.width),n=Math.max(1,t.canvas.height);e.activeTexture(33990),e.bindTexture(3553,r),e.copyTexImage2D(3553,0,6408,0,0,i,n,0),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071),e.texParameteri(3553,10241,9987),e.texParameteri(3553,10240,9729),e.generateMipmap(3553)},onResolveShader(e,t,r,i){if(!t)return null;if(t.name&&Yn.has(t.name)){let f=Yn.get(t.name);return{vs:f.vs||r,fs:f.fs||i}}let n=t.extensions||{},s=n.KHR_materials_clearcoat,l=n.KHR_materials_sheen,o=!!n.KHR_materials_transmission,a=!!n.KHR_materials_ior,u=n.KHR_materials_iridescence;if(!s&&!l&&!n.KHR_materials_unlit&&!o&&!n.KHR_materials_volume&&!a&&!n.KHR_materials_dispersion&&!u)return null;if(n.KHR_materials_unlit)return{vs:r,fs:i.replace("fragColor=vec4(color,outAlpha);","fragColor=vec4(base.rgb,outAlpha);").replace("fragColor=vec4(color,base.a);","fragColor=vec4(base.rgb,base.a);")};let h=i;if(o){let f=h.includes("uniform vec2 uViewportSize;")?"":`uniform vec2 uViewportSize;
|
|
416
|
-
`;
|
|
417
|
-
${
|
|
418
|
-
vec2 sUV=gl_FragCoord.xy/max(uViewportSize,vec2(1.));float iorB=${m(
|
|
463
|
+
}`),{vs:r,fs:n}},onBeforeDrawPrimitive(e,t,r,i,n,a){let s=bu.get(e),o=e.getUniformLocation(t,"uHasSH");if(s&&s.length>=27){o&&e.uniform1i(o,1);let l=e.getUniformLocation(t,"uSH");l&&e.uniform3fv(l,s)}else o&&e.uniform1i(o,0)},onAttributeChanged(e,t,r,i){t==="environment-image"&&e.viewer?this.setEnvironmentImage?.(e.viewer,i):t==="skybox-image"&&e.viewer&&this.setSkyboxImage?.(e.viewer,i)}},gu=new WeakMap;function xu(e,t){let r=t||e.viewer;if(!r||typeof r.projectPointToScreen!="function")return;let i=e.mockHotspots||e.querySelectorAll('[slot^="hotspot-"], [data-position]');for(let n=0;n<i.length;n++){let a=i[n],s=a.getAttribute("data-position");if(!s)continue;let o=s.trim().split(/\s+/).map(m=>parseFloat(m.replace(/m$/,"")));if(o.length<3||o.some(isNaN))continue;let l=a.getAttribute("data-normal"),c;if(l){let m=l.trim().split(/\s+/).map(h=>parseFloat(h));m.length>=3&&!m.some(isNaN)&&(c=[m[0],m[1],m[2]])}let f=r.projectPointToScreen([o[0],o[1],o[2]],c);a.style.position="absolute",a.style.left="0",a.style.top="0",a.style.transform=`translate(-50%, -50%) translate3d(${f.x}px, ${f.y}px, 0)`,a.style.zIndex="3",f.visible?(a.style.opacity="1",a.style.pointerEvents="auto",a.removeAttribute("data-occluded")):(a.style.opacity="0",a.style.pointerEvents="none",a.setAttribute("data-occluded",""))}}var vu={name:"hotspots",updateHotspotsForElement:xu,onElementConnected(e){if(typeof MutationObserver>"u"||!e)return;let t=new MutationObserver(()=>{xu(e)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-position","data-normal"]}),gu.set(e,t)},onCameraChange(e,t){t&&xu(t,e)},onElementDisconnected(e){let t=gu.get(e);t&&(t.disconnect(),gu.delete(e))}},xm=1024,wu=256,Ya=2048,kb=128,Rb=64,Lb=16,Pb=1e4,Ib=8,dr=new Set(["__proto__","constructor","prototype"]),vm={neg:e=>-e,abs:Math.abs,sign:Math.sign,floor:Math.floor,ceil:Math.ceil,round:Math.round,trunc:Math.trunc,fract:e=>e-Math.floor(e),sqrt:e=>Math.sqrt(Math.max(0,e)),cbrt:Math.cbrt,exp:Math.exp,log:e=>e>0?Math.log(e):0,sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:e=>Math.asin(Math.max(-1,Math.min(1,e))),acos:e=>Math.acos(Math.max(-1,Math.min(1,e))),atan:Math.atan,rad:e=>e*Math.PI/180,deg:e=>e*180/Math.PI,saturate:e=>Math.max(0,Math.min(1,e))},wm={add:(e,t)=>e+t,sub:(e,t)=>e-t,mul:(e,t)=>e*t,div:(e,t)=>Math.abs(t)<1e-12?0:e/t,rem:(e,t)=>Math.abs(t)<1e-12?0:e%t,mod:(e,t)=>Math.abs(t)<1e-12?0:e%t,min:Math.min,max:Math.max,pow:Math.pow,atan2:Math.atan2},Ka={translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1]},Ja=(e,t)=>e!==null&&typeof e=="object"&&!dr.has(t)&&Object.prototype.hasOwnProperty.call(e,t),Ln=e=>Array.isArray(e)?[...e]:e,Tm=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&Ja(e,"value")?e.value:e,At=(e,t)=>Ja(e.configuration,t)?Tm(e.configuration[t]):void 0,$e=(e,t=0)=>{let r=Number(e);return Number.isFinite(r)?r:t},$r=e=>Math.max(0,Math.min(1,e)),zn=e=>typeof e=="boolean"?e:typeof e=="number"?e!==0&&!Number.isNaN(e):typeof e=="string"?e.length>0&&e!=="false":!!e;function Ui(e){if(typeof e!="string"||!e.startsWith("/"))return null;let t=[];for(let r of e.slice(1).split("/")){let i=r.replace(/~1/g,"/").replace(/~0/g,"~");if(!i||dr.has(i)||dr.has(r))return null;t.push(i)}return{segments:t}}var xo=(e,t)=>{if(e===void 0||!/^\d+$/.test(e))return-1;let r=Number(e);return Number.isSafeInteger(r)&&r>=0&&r<t?r:-1},Sm=e=>{let t=$e(e[0]),r=$e(e[1]),i=$e(e[2]),n=$e(e[3],1),a=Math.hypot(t,r,i,n);return a>1e-8?[t/a,r/a,i/a,n/a]:[0,0,0,1]},Mm=(e,t,r,i)=>{if(typeof e=="number"&&typeof t=="number")return e+(t-e)*r;if(Array.isArray(e)&&Array.isArray(t)){if(i&&e.length===4&&t.length===4){let n=[0,0,0,1];return ja(n,Sm(e),Sm(t),r),n}return e.slice(0,t.length).map((n,a)=>n+(t[a]-n)*r)}return r>=.5?t:e},Su=(e,t,r)=>Array.isArray(e)&&Array.isArray(t)?e.slice(0,t.length).map((i,n)=>r($e(i),$e(t[n]))):Array.isArray(e)?e.map(i=>r($e(i),$e(t))):Array.isArray(t)?t.map(i=>r($e(e),$e(i))):r($e(e),$e(t)),Cb=(e,t)=>Array.isArray(e)?e.map(r=>t($e(r))):t($e(e)),Am=(e,t)=>Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every((r,i)=>Math.abs(r-t[i])<=1e-6):e===t,Bi=class{constructor(e,t,r){let i=Array.isArray(r.nodes)?r.nodes:[];if(i.length>xm)throw new Error(`SecurityError: Exceeds MAX_GRAPH_NODES (${xm})`);let n=Array.isArray(r.variables)?r.variables:[];if(n.length>wu)throw new Error(`SecurityError: Exceeds MAX_VARIABLES (${wu})`);let a=Array.isArray(r.declarations)?r.declarations:[],s=Array.isArray(r.events)?r.events:[],o=new Map,l=new Map,c=new Map,f=new Map,m=new Map,h=new Map,p=[],g=[],x=new Map,v=1,y=0,A=0,b=0,w=0,S=!1,E=!1,N=!1;n.forEach((H,te)=>{if(!H||typeof H!="object")return;let Z=Ln(Tm(H.value));o.set(te,Z);let ae=H.id??H.name;typeof ae=="string"&&ae&&!dr.has(ae)&&o.set(ae,Z)}),(t?.nodes||[]).forEach((H,te)=>{for(let Z of H?.children||[])typeof Z=="number"&&x.set(Z,te)});let C=H=>H.op||typeof H.declaration=="number"&&a[H.declaration]?.op||"",_=(H,te,Z)=>{if(dr.has(te))return;let ae=l.get(H);ae||l.set(H,ae=Object.create(null)),ae[te]=Z},P=(H,te)=>{if(typeof H!="number"&&typeof H!="string"||typeof H=="string"&&dr.has(H)||!o.has(H)&&o.size>=wu*2)return;let Z=Ln(te);if(o.set(H,Z),typeof H=="number"){let ae=n[H]?.id??n[H]?.name;typeof ae=="string"&&!dr.has(ae)&&o.set(ae,Z)}},R=H=>typeof H=="number"?s[H]?.id??String(H):typeof H=="string"?/^\d+$/.test(H)&&s[Number(H)]?.id?s[Number(H)].id:H:"",$=(H,te)=>{for(let Z=H,ae=0;Z!==void 0&&Z>=0&&ae<128;Z=x.get(Z),ae++)if(Z===te)return!0;return!1},F=H=>{for(let te=p.length-1;te>=0;te--)p[te].key===H&&p.splice(te,1)},V=H=>{F(H.key),p.length>=kb&&p.shift(),p.push(H)},Y=H=>{let te=Ui(H)?.segments;if(te){if(te[0]==="nodes"&&Array.isArray(t?.nodes)){let Z=t.nodes[xo(te[1],t.nodes.length)];if(!Z)return;let ae=te[2];if(ae in Ka){let ie=Ka[ae],de=Z[ae]||ie;return ie.map((me,Se)=>$e(de[Se],me))}if(ae==="weights"){let ie=Array.isArray(Z.weights)?Z.weights:[0],de=te.length===4?xo(te[3],64):-2;return de===-2?ie.map(me=>$e(me)):de>=0?$e(ie[de]):void 0}if(ae==="visible"||ae==="extensions"&&te[3]==="KHR_node_visibility"&&te[4]==="visible")return Z.extensions?.KHR_node_visibility?.visible??Z.visible??!0}else if(te[0]==="materials"&&Array.isArray(t?.materials)){let Z=t.materials[xo(te[1],t.materials.length)];if(!Z)return;let ae=Z.pbrMetallicRoughness||{};if(te[2]==="pbrMetallicRoughness"){if(te[3]==="baseColorFactor"){let ie=ae.baseColorFactor||[1,1,1,1];return[$e(ie[0],1),$e(ie[1],1),$e(ie[2],1),$e(ie[3],1)]}if(te[3]==="metallicFactor"||te[3]==="roughnessFactor")return $e(ae[te[3]],1)}if(te[2]==="emissiveFactor"){let ie=Z.emissiveFactor||[0,0,0];return[$e(ie[0]),$e(ie[1]),$e(ie[2])]}if(te[2]==="alphaCutoff")return $e(Z.alphaCutoff,.5)}}},J=(H,te)=>{let Z=Ui(H)?.segments;if(!Z)return!1;if(Z[0]==="nodes"&&Array.isArray(t?.nodes)){let ae=xo(Z[1],t.nodes.length),ie=t.nodes[ae];if(!ie)return!1;let de=Z[2];if(de in Ka&&Array.isArray(te)){let me=Ka[de];if(te.length<me.length)return!1;let Se=me.map((_e,Le)=>$e(te[Le],_e));if(de==="rotation"){let _e=Math.hypot(...Se);Se=_e>1e-8?Se.map(Le=>Le/_e):[0,0,0,1]}ie[de]=Se,delete ie.matrix;let Fe=e?.initialNodeTransforms?.[ae];return Fe&&(Fe[de[0]]=[...Se]),S=!0,!0}if(de==="weights"){Array.isArray(ie.weights)||(ie.weights=[]);let me=(Se,Fe)=>{for(let _e of e?.meshes||[])if(_e.nodeIndex===ae)for(let Le of _e.primitives||[])Le.pluginData?.morph?.weights&&(Le.pluginData.morph.weights[Se]=Fe)};if(Z.length===4){let Se=xo(Z[3],64);if(Se<0)return!1;me(Se,ie.weights[Se]=$e(te))}else if(Array.isArray(te))ie.weights=te.slice(0,64).map(Se=>$e(Se)),ie.weights.forEach((Se,Fe)=>me(Fe,Se));else return!1;return N=!0,!0}if(de==="visible"||de==="extensions"&&Z[3]==="KHR_node_visibility"&&Z[4]==="visible"){let me=zn(te);return ie.visible=me,(!ie.extensions||typeof ie.extensions!="object")&&(ie.extensions={}),ie.extensions.KHR_node_visibility={visible:me},E=!0,!0}}else if(Z[0]==="materials"&&Array.isArray(t?.materials)){let ae=xo(Z[1],t.materials.length),ie=t.materials[ae];if(!ie)return!1;let de=ie.pbrMetallicRoughness||(ie.pbrMetallicRoughness={}),me=Se=>{for(let Fe of e?.meshes||[])for(let _e of Fe.primitives||[])(_e.materialIndex??0)===ae&&Se(_e)};if(Z[2]==="pbrMetallicRoughness"){if(Z[3]==="baseColorFactor"&&Array.isArray(te)&&te.length>=3){let Se=[$r($e(te[0],1)),$r($e(te[1],1)),$r($e(te[2],1)),te[3]!==void 0?$r($e(te[3],1)):de.baseColorFactor?.[3]??1];return de.baseColorFactor=Se,me(Fe=>Fe.baseColor=[...Se]),N=!0}if(Z[3]==="metallicFactor"||Z[3]==="roughnessFactor"){let Se=Z[3]==="metallicFactor",Fe=$r($e(te,Se?0:.5));return de[Z[3]]=Fe,me(_e=>_e[Se?"metallic":"roughness"]=Fe),N=!0}}if(Z[2]==="emissiveFactor"&&Array.isArray(te)&&te.length>=3)return ie.emissiveFactor=[0,1,2].map(Se=>Math.max(0,$e(te[Se]))),N=!0;if(Z[2]==="alphaCutoff")return ie.alphaCutoff=$r($e(te,.5)),N=!0}return!1},re=(H,te,Z=new Set)=>{let ae=At(te,"pointer");if(typeof ae!="string"||!ae.startsWith("/"))return null;let ie=ae.replace(/\{([a-zA-Z0-9_]+)\}/g,(de,me)=>{let Se=Math.trunc(Number(Q(H,me,void 0,Z)??At(te,me)));return Number.isSafeInteger(Se)&&Se>=0?String(Se):"-1"});return Ui(ie)?ie:null},Q=(H,te,Z,ae)=>{let ie=i[H]?.values;if(!Ja(ie,te))return Z;let de=ie[te];if(de==null)return Z;if(typeof de!="object"||Array.isArray(de))return Ln(de);let me=de;return typeof me.node=="number"?ee(me.node,me.socket||"value",ae):Ja(me,"value")?Ln(me.value):Z},ee=(H,te,Z)=>{if(H<0||H>=i.length||Z.has(H)||Z.size>128||++b>Pb)return;let ae=i[H],ie=C(ae);if(/^(event\/|pointer\/on|scene\/on|flow\/)/.test(ie))return Ln(l.get(H)?.[te]);Z.add(H);try{let de=(me,Se=0)=>Q(H,me,Se,Z);if(ie==="variable/get"){let me=At(ae,"variable")??At(ae,"id");return typeof me=="number"||typeof me=="string"?Ln(o.get(me)):void 0}if(ie==="pointer/get"){let me=re(H,ae,Z);return me?Y(me):void 0}if(ie.startsWith("math/")){let me=ie.slice(5);if(me in vm)return Cb(de("a"),vm[me]);if(me in wm){let Se=/^(mul|div|rem|mod|pow)$/.test(me)?1:0;return Su(de("a",me==="mul"?1:0),de("b",Se),wm[me])}if(me==="pi")return Math.PI;if(me==="e")return Math.E;if(me==="random")return Math.random();if(me==="clamp")return Su(Su(de("a"),de("b",de("min",0)),Math.max),de("c",de("max",1)),Math.min);if(me==="mix"||me==="quatSlerp")return Mm(de("a",0),de("b",1),$e(de("c",de("t",.5)),.5),me==="quatSlerp");if(me==="dot"){let Se=de("a"),Fe=de("b");return Array.isArray(Se)&&Array.isArray(Fe)?Se.reduce((_e,Le,ne)=>_e+(Le||0)*(Fe[ne]||0),0):$e(Se)*$e(Fe)}if(me==="cross"){let Se=de("a",[0,0,0]),Fe=de("b",[0,0,0]);return Array.isArray(Se)&&Array.isArray(Fe)?[(Se[1]||0)*(Fe[2]||0)-(Se[2]||0)*(Fe[1]||0),(Se[2]||0)*(Fe[0]||0)-(Se[0]||0)*(Fe[2]||0),(Se[0]||0)*(Fe[1]||0)-(Se[1]||0)*(Fe[0]||0)]:[0,0,0]}if(me==="length"){let Se=de("a");return Array.isArray(Se)?Math.hypot(...Se):Math.abs($e(Se))}if(me==="distance"){let Se=de("a"),Fe=de("b");return Array.isArray(Se)&&Array.isArray(Fe)?Math.hypot(...Se.map((_e,Le)=>(_e||0)-(Fe[Le]||0))):Math.abs($e(Se)-$e(Fe))}if(me==="normalize"){let Se=de("a");if(!Array.isArray(Se))return $e(Se)>=0?1:-1;let Fe=Math.hypot(...Se);return Fe>1e-8?Se.map(_e=>_e/Fe):Se.map(()=>0)}if(me.startsWith("combine"))return["a","b","c","d"].slice(0,Number(me[7])||2).map(Se=>$e(de(Se)));if(me.startsWith("extract")){let Se=de("a");return Array.isArray(Se)?Se[te==="0"||te==="x"?0:te==="1"||te==="y"?1:te==="2"||te==="z"?2:3]??0:0}if(me==="eq")return Am(de("a"),de("b"));if(me==="ne")return!Am(de("a"),de("b"));if(me==="lt")return $e(de("a"))<$e(de("b"));if(me==="le")return $e(de("a"))<=$e(de("b"));if(me==="gt")return $e(de("a"))>$e(de("b"));if(me==="ge")return $e(de("a"))>=$e(de("b"));if(me==="isNaN")return Number.isNaN(Number(de("a")));if(me==="isInf"){let Se=Number(de("a"));return!Number.isFinite(Se)&&!Number.isNaN(Se)}return me==="and"?zn(de("a",!1))&&zn(de("b",!1)):me==="or"?zn(de("a",!1))||zn(de("b",!1)):me==="xor"?zn(de("a",!1))!==zn(de("b",!1)):me==="not"?!zn(de("a",!1)):me==="select"?Ln(zn(de("condition",!1))?de("a"):de("b")):void 0}return ie==="type/boolToInt"||ie==="type/boolToFloat"?zn(de("a",!1))?1:0:ie==="type/intToBool"||ie==="type/floatToBool"?$e(de("a",0))!==0:ie==="type/intToFloat"?$e(de("a",0)):ie==="type/floatToInt"?Math.trunc($e(de("a",0))):void 0}finally{Z.delete(H)}},k=()=>{if(S){S=!1,N=!0;let H=vr(t);if(e){e.worldMatrices=H;for(let te of e.meshes||[])te.nodeIndex>=0&&te.nodeIndex<H.length&&(te.transform.set(H[te.nodeIndex]),Bt(te.normalMatrix,te.transform))}}if(E){E=!1,N=!0;let H=t?.nodes;if(Array.isArray(e?.meshes)&&Array.isArray(H))for(let te of e.meshes){let Z=!0;for(let ae=te.nodeIndex,ie=0;ae!==void 0&&ae>=0&&ie<128;ae=x.get(ae),ie++){let de=H[ae];if(de?.visible===!1||de?.extensions?.KHR_node_visibility?.visible===!1){Z=!1;break}}te.visible=Z}}N&&(N=!1,e?.render?.())},G=(H,te={steps:0})=>{if(!H||typeof H.node!="number")return;te.steps===0&&(b=0);let Z=[H],ae=ie=>{Z.length+te.steps<Ya&&Z.push(ie)};for(;Z.length>0&&te.steps<Ya;){te.steps++;let ie=Z.shift();if(!ie||ie.node<0||ie.node>=i.length)continue;let de=ie.node,me=i[de];if(!me)continue;let Se=ie.socket||"in",Fe=C(me),_e=(ne,Re=void 0)=>Q(de,ne,Re,new Set),Le=(ne="out")=>{let Re=me.flows?.[ne];Re&&ae(Re)};switch(Fe){case"flow/branch":Le(zn(_e("condition",!1))?"true":"false");break;case"flow/sequence":for(let ne of Object.keys(me.flows||{}).sort((Re,W)=>Number(Re)-Number(W)||Re.localeCompare(W)))Le(ne);break;case"flow/switch":{let ne=me.flows?.[String(_e("selection",_e("value",0)))]??me.flows?.default;ne&&ae(ne);break}case"flow/for":{let ne=Math.trunc($e(_e("startIndex",0))),Re=Math.trunc($e(_e("endIndex",0))),W=Math.max(1,Math.trunc($e(_e("step",1),1))),D=me.flows?.body;if(D&&Re>ne&&w<Ib){let O=Math.min(Math.ceil((Re-ne)/W),Ya);w++;try{for(let X=0;X<O&&te.steps<Ya;X++)_(de,"index",ne+X*W),G(D,te)}finally{w--}}let z=me.flows?.completed??me.flows?.out;z&&ae(z);break}case"flow/doN":{let ne=Se==="reset"?0:(c.get(de)||0)+1;if(c.set(de,ne),_(de,"currentCount",ne),_(de,"count",ne),Se!=="reset"){let Re=Math.trunc($e(_e("n",At(me,"stopIterations")??At(me,"n")??1),1));ne<=Re&&Le()}break}case"flow/multiGate":{if(Se==="reset"){h.set(de,0);break}let ne=Object.keys(me.flows||{}).sort();if(!ne.length)break;let Re=At(me,"isRandom")?Math.floor(Math.random()*ne.length):h.get(de)||0;Re<ne.length&&(Le(ne[Re]),h.set(de,At(me,"isLoop")!==!1?(Re+1)%ne.length:Re+1));break}case"flow/waitAll":{if(Se==="reset"){f.delete(de);break}let ne=f.get(de);ne||f.set(de,ne=new Set),ne.add(Se),ne.size>=Math.max(1,Math.trunc(Number(At(me,"inputFlows")??2)||2))&&(ne.clear(),Le("out"),Le("completed"));break}case"flow/throttle":{if(Se==="reset"){m.delete(de);break}let ne=Math.max(0,$e(_e("duration",0))),Re=m.get(de);Re===void 0||y-Re>=ne?(m.set(de,y),_(de,"lastRemainingTime",0),Le()):_(de,"lastRemainingTime",Math.max(0,ne-(y-Re)));break}case"flow/delay":case"flow/setDelay":{if(Se==="cancel"){for(let D=g.length-1;D>=0;D--)g[D].nodeIdx===de&&g.splice(D,1);_(de,"lastDelayIndex",-1);break}let ne=Math.max(0,$e(_e("duration",At(me,"duration")??0))),Re=me.flows?.done??me.flows?.out;if(ne<=0){_(de,"lastDelayIndex",-1),Re&&ae(Re);break}g.length>=Rb&&g.shift();let W=v++;_(de,"lastDelayIndex",W),g.push({id:W,nodeIdx:de,rem:ne,done:Re}),Fe==="flow/setDelay"&&me.flows?.out&&me.flows?.done&&Le("out");break}case"flow/cancelDelay":{let ne=Math.trunc($e(_e("delayIndex",-1),-1));if(ne<0)g.length=0;else for(let Re=g.length-1;Re>=0;Re--)g[Re].id===ne&&g.splice(Re,1);Le();break}case"variable/set":P(At(me,"variable")??At(me,"id"),_e("value")),Le();break;case"variable/interpolate":{let ne=At(me,"variable")??At(me,"id"),Re=_e("value",_e("target")),W=Math.max(0,$e(_e("duration",At(me,"duration")??.3),.3));ne!==void 0&&Re!==void 0&&V({key:`var:${String(ne)}`,varKey:ne,from:Ln(_e("from")??o.get(ne)??0),to:Ln(Re),dur:W,elapsed:0,quat:!1,linear:At(me,"easing")==="linear",done:me.flows?.done}),Le();break}case"pointer/set":{let ne=re(de,me),Re=_e("value");ne&&Re!==void 0&&(F(`ptr:${ne}`),J(ne,Re)),Le();break}case"pointer/interpolate":{let ne=re(de,me),Re=_e("value",_e("target")),W=Math.max(0,$e(_e("duration",At(me,"duration")??.3),.3));if(ne&&Re!==void 0){let D=_e("from")??Y(ne);D!==void 0&&(W<=0?(J(ne,Re),Le("done")):V({key:`ptr:${ne}`,ptr:ne,from:Ln(D),to:Ln(Re),dur:W,elapsed:0,quat:ne.endsWith("/rotation"),linear:At(me,"easing")==="linear",done:me.flows?.done}))}Le();break}case"animation/start":{let ne=_e("animation")??At(me,"animation")??At(me,"clipName"),Re=typeof ne=="number"?e?.animations?.[ne]?.name??t?.animations?.[ne]?.name:typeof ne=="string"?ne:void 0;e?.playAnimation?.(Re),N=!0,Le();break}case"animation/stop":case"animation/resetAt":e?.pauseAnimation?.(),Fe==="animation/resetAt"&&e?.evaluateAnimation?.($e(_e("time",0))),N=!0,Le();break;case"event/send":case"customEvent/send":{let ne=R(At(me,"event")??At(me,"id")),Re={};for(let W of Object.keys(me.values||{}))dr.has(W)||(Re[W]=_e(W));ne&&(typeof CustomEvent<"u"&&typeof e?.container?.dispatchEvent=="function"&&e.container.dispatchEvent(new CustomEvent("interactivityEvent",{bubbles:!0,composed:!0,detail:{id:ne,values:Re}})),q(ne,Re,te)),Le();break}default:Le();break}}};this.readScenePointer=Y,this.writeScenePointer=J,this.fireOnStart=()=>{i.forEach(H=>{C(H)==="event/onStart"&&G(H.flows?.out)}),k()},this.fireOnSelect=H=>{if(!H)return;let te=typeof H.meshIndex=="number"?H.meshIndex:-1,Z=typeof H.nodeIndex=="number"?H.nodeIndex:e?.meshes?.[te]?.nodeIndex??-1;i.forEach((ae,ie)=>{if(!/^(pointer|event|scene)\/onSelect$/.test(C(ae)))return;let de=At(ae,"nodeIndex")??At(ae,"node")??Q(ie,"nodeIndex",void 0,new Set),me=At(ae,"meshName");if(typeof me=="string"&&me?H.meshName===me:de==null||Number(de)<0||Number.isNaN(Number(de))||$(Z,Math.trunc(Number(de)))){if(_(ie,"nodeIndex",Z),_(ie,"meshIndex",te),Array.isArray(H.hitPoint)){let Se=[$e(H.hitPoint[0]),$e(H.hitPoint[1]),$e(H.hitPoint[2])];_(ie,"hitPoint",Se),_(ie,"point",Se),_(ie,"intersectionPoint",Se)}if(Array.isArray(H.normal)){let Se=[$e(H.normal[0]),$e(H.normal[1],1),$e(H.normal[2])];_(ie,"normal",Se),_(ie,"hitNormal",Se)}typeof H.distance=="number"&&_(ie,"distance",H.distance),G(ae.flows?.out)}}),k()},this.receiveCustomEvent=(H,te={})=>q(H,te,{steps:0});function q(H,te,Z){if(!(A>=Lb)){A++;try{let ae=R(H);i.forEach((ie,de)=>{if(!/^(customE|e)vent\/receive$/.test(C(ie)))return;let me=At(ie,"event")??At(ie,"id");if(!(R(me)!==ae&&String(me)!==String(H))){for(let[Se,Fe]of Object.entries(te))dr.has(Se)||_(de,Se,Ln(Fe));G(ie.flows?.out,Z)}}),k()}finally{A--}}}this.tick=H=>{if(!Number.isFinite(H)||H<0)return;let te=Math.min(H,.25);y+=te,i.forEach((ae,ie)=>{C(ae)==="event/onTick"&&(_(ie,"timeDelta",te),_(ie,"dt",te),_(ie,"timeElapsed",y),G(ae.flows?.out))});let Z=[];for(let ae=p.length-1;ae>=0;ae--){let ie=p[ae];ie.elapsed+=te;let de=ie.dur>1e-6?$r(ie.elapsed/ie.dur):1,me=ie.linear?de:de*de*(3-2*de),Se=Mm(ie.from,ie.to,me,ie.quat);ie.ptr?J(ie.ptr,Se):ie.varKey!==void 0&&P(ie.varKey,Se),de>=1&&(p.splice(ae,1),ie.done&&Z.push(ie.done))}for(let ae=g.length-1;ae>=0;ae--){let ie=g[ae];ie.rem-=te,ie.rem<=0&&(g.splice(ae,1),ie.done&&Z.push(ie.done))}for(let ae of Z)G(ae);k()},this.dispose=()=>{p.length=0,g.length=0,o.clear(),l.clear(),c.clear(),f.clear(),m.clear(),h.clear()}}},Kn=new WeakMap,Qa=new WeakMap;function Nb(e,t){if(!e||typeof e!="object"||!Number.isFinite(t)||t<=0||as().some(o=>o.name==="xr-live-head-follow")||(typeof e.getAutoRotate=="function"?e.getAutoRotate():e.autoRotate)===!1)return;let r=e.gltf,i=r?.nodes;if(!Array.isArray(i)||i.length===0)return;let n=Math.min(t,.1),a=(Qa.get(e)||0)+n,s=!1;for(let o=0;o<i.length;o++){let l=i[o],c=Qd(l?.extras?.xr?.orbit);if(!c)continue;let f=0,m=0,h=0;if(Array.isArray(c.target))f=c.target[0],m=c.target[1],h=c.target[2];else if(typeof c.target=="string"&&c.target!=="head"){let y=i.find(A=>A?.name===c.target);Array.isArray(y?.translation)&&(f=$e(y.translation[0]),m=$e(y.translation[1]),h=$e(y.translation[2]))}let p=c.phase+c.speed*a,g=f+Math.cos(p)*c.radius,x=m+c.height,v=h+Math.sin(p)*c.radius;if(l.translation=[g,x,v],c.faceCenter){let y=Math.atan2(f-g,h-v);l.rotation=[0,Math.sin(y*.5),0,Math.cos(y*.5)]}s=!0}if(s){Qa.set(e,a);let o=vr(r);e.worldMatrices=o;for(let l of e.meshes||[])l.nodeIndex>=0&&l.nodeIndex<o.length&&(l.transform.set(o[l.nodeIndex]),Bt(l.normalMatrix,l.transform))}}function Za(e){if(!(!e||typeof e!="object"))return Kn.get(e)||Kn.get(e.viewer)||Kn.get(e._view)}function Mu(e,t,r){let i=Za(e);return i?(i.receiveCustomEvent(t,r),!0):!1}var Au={name:"khr-interactivity",sendInteractivityEvent:Mu,getInteractivityVM:Za,onLoadModel(e,t){if(!e||typeof e!="object")return;Kn.get(e)?.dispose(),Kn.delete(e),Qa.delete(e);let r=t?.extensions?.KHR_interactivity,i=Array.isArray(r?.graphs)?r.graphs[r.graph??0]:r;if(!i||!Array.isArray(i.nodes))return;let n=new Bi(e,t,i);Kn.set(e,n),n.fireOnStart()},onMeshSelect(e,t){Kn.get(e)?.fireOnSelect(t)},onUpdate(e,t){Kn.get(e)?.tick(t),Nb(e,t)},onDestroy(e,t){Kn.get(t)?.dispose(),Kn.delete(t),Qa.delete(t)}},Fi=new Map,ec=new WeakMap;function _m(e,t){Fi.set(e,t)}var Tu={name:"materials",onContextRestored(e){ec.delete(e)},onBuildPrimitiveVAO(e,t,r,i,n){return(((i?.materials&&r.material!==void 0?i.materials[r.material]:null)?.extensions||{}).KHR_materials_transmission?.transmissionFactor??0)>0?{isTransmissive:!0}:null},onBeforeTransmissivePass(e,t){let r=ec.get(e);r||(r=e.createTexture(),ec.set(e,r));let i=Math.max(1,t.canvas.width),n=Math.max(1,t.canvas.height);e.activeTexture(33990),e.bindTexture(3553,r),e.copyTexImage2D(3553,0,6408,0,0,i,n,0),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071),e.texParameteri(3553,10241,9987),e.texParameteri(3553,10240,9729),e.generateMipmap(3553)},onResolveShader(e,t,r,i){if(!t)return null;if(t.name&&Fi.has(t.name)){let g=Fi.get(t.name);return{vs:g.vs||r,fs:g.fs||i}}let n=t.extensions||{},a=n.KHR_materials_clearcoat,s=n.KHR_materials_sheen,o=!!n.KHR_materials_transmission,l=!!n.KHR_materials_ior,c=n.KHR_materials_iridescence;if(!a&&!s&&!n.KHR_materials_unlit&&!o&&!n.KHR_materials_volume&&!l&&!n.KHR_materials_dispersion&&!c)return null;if(n.KHR_materials_unlit)return{vs:r,fs:i.replace("fragColor=vec4(color,outAlpha);","fragColor=vec4(base.rgb,outAlpha);").replace("fragColor=vec4(color,base.a);","fragColor=vec4(base.rgb,base.a);")};let f=i;if(o){let g=f.includes("uniform vec2 uViewportSize;")?"":`uniform vec2 uViewportSize;
|
|
464
|
+
`;f=f.replace("out vec4 fragColor;",`uniform sampler2D uTransmissionTex;
|
|
465
|
+
${g}out vec4 fragColor;`)}let m=(g,x,v=0,y=1e6,A=3)=>{let b=Number(g);return(Number.isFinite(b)?Math.min(y,Math.max(v,b)):x).toFixed(A)},h=Number(n.KHR_materials_ior?.ior??1.5),p=Number.isFinite(h)?Math.min(10,Math.max(1,h)):1.5;if(l){let g=Math.pow((p-1)/(p+1),2);f=f.replace("vec3 F0=mix(vec3(0.04),base.rgb,metallic);",`vec3 F0=mix(vec3(${m(g,.04,0,1,4)}),base.rgb,metallic);`)}if(c){let g=m(c.iridescenceFactor,1,0,1),x=m(c.iridescenceIor,1.3,1,10);f=f.replace("vec3 F=F_SchlickRoughness(F0,roughness,NoV);",`vec3 F=F_SchlickRoughness(F0,roughness,NoV);vec3 iridColor=.5+.5*cos(800.*${x}*NoV*vec3(.015,.018,.022));F=mix(F,iridColor,${g}*pow(1.-NoV,2.));`)}if(o){let g=m(n.KHR_materials_transmission?.transmissionFactor,1,0,1),x=n.KHR_materials_volume||{},v=m(x.thicknessFactor,.5,0,1e4),y=m(x.attenuationDistance,1,.001,1e6),A=Array.isArray(x.attenuationColor)?x.attenuationColor:[1,1,1],b=m(n.KHR_materials_dispersion?.dispersion,0,0,10);f=f.replace("vec3 diffuseIBL=kD*base.rgb*(uAmbientColor+envDiffuse*0.5)*occ;",`vec3 diffuseIBL=kD*base.rgb*(uAmbientColor+envDiffuse*0.5)*occ;
|
|
466
|
+
vec2 sUV=gl_FragCoord.xy/max(uViewportSize,vec2(1.));float iorB=${m(p,1.5,1,10)},dV=${b},tV=${v},lod=clamp(roughness*5.,0.,5.),sc=.06*(1.+tV);
|
|
419
467
|
vec3 refractedR=refract(-V,N,1./(iorB-.02*dV)),rG=refract(-V,N,1./iorB),refractedB=refract(-V,N,1./(iorB+.02*dV));
|
|
420
468
|
vec3 tr=vec3(textureLod(uTransmissionTex,clamp(sUV+refractedR.xy*sc,.001,.999),lod).r,textureLod(uTransmissionTex,clamp(sUV+rG.xy*sc,.001,.999),lod).g,textureLod(uTransmissionTex,clamp(sUV+refractedB.xy*sc,.001,.999),lod).b);
|
|
421
|
-
vec3 aCol=vec3(${m(
|
|
422
|
-
vec3 volumeAtten=exp(-tV*(vec3(1.)-aCol)/max(${
|
|
423
|
-
diffuseIBL=mix(diffuseIBL,tr*volumeAtten*base.rgb,${f});`)}if(s&&!i.includes("uClearcoat")){let f=m(s.clearcoatFactor,1,0,1),g=m(s.clearcoatRoughnessFactor,0,0,1);h=h.replace("fragColor=vec4(color,base.a);",`vec3 ccF=F_SchlickRoughness(vec3(.04),${g},NoV)*${f};color=color*(vec3(1.)-ccF)+getStudioRadiance(R,${g})*ccF;fragColor=vec4(color,base.a);`)}if(l){let f=Array.isArray(l.sheenColorFactor)?l.sheenColorFactor:[1,1,1],g=`color+=vec3(${m(f[0],1,0,1)},${m(f[1],1,0,1)},${m(f[2],1,0,1)})*pow(1.-NoV,4.)*.5;`;h.includes("color=applyToneMapping(color,uToneMapping);")?h=h.replace("color=applyToneMapping(color,uToneMapping);",`${g}color=applyToneMapping(color,uToneMapping);`):h=h.replace("fragColor=vec4(color,base.a);",`${g}fragColor=vec4(color,base.a);`)}return{vs:r,fs:h}},onBeforeDrawPrimitive(e,t,r,i,n,s){let l=r.materialIndex;if(l!==void 0&&s?.materials){let o=s.materials[l];o?.name&&Yn.has(o.name)&&Yn.get(o.name).onBindUniforms?.(e,t,r)}if(r.isTransmissive){let o=pi.get(e);if(o){e.activeTexture(33990),e.bindTexture(3553,o);let a=e.getUniformLocation(t,"uTransmissionTex");a&&e.uniform1i(a,6);let u=e.getUniformLocation(t,"uViewportSize");u&&e.uniform2f(u,e.drawingBufferWidth||1,e.drawingBufferHeight||1)}}}},la=64*1024*1024,ma=128*1024*1024,Jc=16777216;function eu(e){return(e>>>1^-(e&1))&255}function tu(e){return(e>>>1^-(e&1))&65535}function nu(e){let t=e<<24>>24;return(t<<1^t>>7)&255}function fa(e){return(e<<1^e>>31)>>>0}function pa(e){if(e!==void 0&&e!=="NONE"&&e!=="OCTAHEDRAL"&&e!=="QUATERNION"&&e!=="EXPONENTIAL"&&e!=="COLOR")throw Re(`unknown filter "${String(e)}"`)}var we=Math.fround;function hn(e){return Math.trunc(we(e+(e>=0?.5:-.5)))}function Ao(e,t,r,i="NONE"){if(pa(i),!i||i==="NONE"||t<=0)return;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(i==="OCTAHEDRAL"){if(r!==4&&r!==8)throw Re(`OCTAHEDRAL filter requires byteStride 4 or 8 (got ${r})`);let m=r===8,c=m?32767:127,d=x=>m?n.getInt16(x,!0):n.getInt8(x),f=(x,b)=>m?n.setInt16(x,b,!0):n.setInt8(x,b<<24>>24),g=m?2:1;for(let x=0;x<t;x++){let b=x*r,v=d(b),p=d(b+g),y=we(d(b+2*g)-Math.abs(v)-Math.abs(p)),M=y>=0?0:y;v=we(v+(v>=0?M:-M)),p=we(p+(p>=0?M:-M));let P=we(Math.sqrt(we(we(we(v*v)+we(p*p))+we(y*y))));if(P===0){f(b,0),f(b+g,0),f(b+2*g,c);continue}let F=we(c/P);f(b,hn(we(v*F))),f(b+g,hn(we(p*F))),f(b+2*g,hn(we(y*F)))}return}if(i==="QUATERNION"){if(r!==8)throw Re(`QUATERNION filter requires byteStride 8 (got ${r})`);let m=we(32767/we(Math.SQRT2));for(let c=0;c<t;c++){let d=c*8,f=n.getInt16(d+6,!0),g=f|3,x=n.getInt16(d,!0),b=n.getInt16(d+2,!0),v=n.getInt16(d+4,!0),p=we(g*g),y=we(we(we(we(p*2)-we(x*x))-we(b*b))-we(v*v)),M=we(Math.sqrt(y>=0?y:0)),P=we(m/g),F=f&3,W=[0,0,0,0];W[F+1&3]=hn(we(x*P)),W[F+2&3]=hn(we(b*P)),W[F+3&3]=hn(we(v*P)),W[F]=Math.trunc(we(we(M*P)+.5));for(let T=0;T<4;T++)n.setInt16(d+T*2,W[T]<<16>>16,!0)}return}if(i==="EXPONENTIAL"){if(r<4||r%4!==0)throw Re(`EXPONENTIAL filter requires byteStride multiple of 4 (got ${r})`);let m=t*r>>>2;for(let c=0;c<m;c++){let d=c*4,f=n.getUint32(d,!0),g=f<<8>>8,x=f>>24;n.setUint32(d,x+127<<23>>>0,!0);let b=n.getFloat32(d,!0);n.setFloat32(d,we(b*g),!0)}return}if(r!==4&&r!==8)throw new Error(`KHR_meshopt_compression: COLOR filter requires byteStride 4 or 8 (got ${r})`);let s=r===8,l=s?65535:255,o=m=>s?n.getUint16(m,!0):n.getUint8(m),a=m=>s?n.getInt16(m,!0):n.getInt8(m),u=(m,c)=>s?n.setUint16(m,c&65535,!0):n.setUint8(m,c&255),h=s?2:1;for(let m=0;m<t;m++){let c=m*r,d=o(c+3*h);d|=d>>1,d|=d>>2,d|=d>>4,d|=d>>8;let f=o(c),g=a(c+h),x=a(c+2*h),b=f+g-x,v=f+x,p=f-g-x,y=o(c+3*h);y=y<<1&d|y&1;let M=d===0?0:we(l/d);u(c,Math.trunc(we(we(b*M)+.5))),u(c+h,Math.trunc(we(we(v*M)+.5))),u(c+2*h,Math.trunc(we(we(p*M)+.5))),u(c+3*h,Math.trunc(we(we(y*M)+.5)))}}var ba=160,vt=16,ru=24,ya=32,iu=24,ou=[0,2,4,8],su=[0,1,2,4,8];function ga(e){let t=Math.floor(8192/e)&~(vt-1);return t<256?t:256}function Re(e){return new Error(`EXT_meshopt_compression: ${e}`)}function au(e,t,r,i,n){if(n===0)return r.fill(0,i,i+vt),t;if(n===8)return r.set(e.subarray(t,t+vt),i),t+vt;let s=(1<<n)-1,l=8/n,o=t+vt*n/8;for(let a=0;a<vt;a++){let u=e[t+Math.floor(a/l)],h=a%l,m=n===1?u>>h&1:u>>8-n-h*n&s;r[i+a]=m===s?e[o++]:m}return o}function da(e,t,r,i,n,s,l,o){let a=s/vt,u=a+3>>2;if(r-t<u)throw Re("truncated ATTRIBUTES stream");let h=t;t+=u;for(let m=0;m<a;m++){if(r-t<ru)throw Re("truncated ATTRIBUTES stream");let c=e[h+(m>>2)]>>(m&3)*2&3;t=au(e,t,i,n+m*vt,l[o+c])}return t}function cu(e,t,r,i){if(r%4!==0||r>256)throw Re(`ATTRIBUTES byteStride must be a multiple of 4 and <= 256 (got ${r})`);let n=e.byteLength;if(n<1)throw Re("truncated ATTRIBUTES stream");let s=e[0];if((s&240)!==ba)throw Re(`unsupported ATTRIBUTES header 0x${s.toString(16)}`);let l=s&15;if(l>1)throw Re(`unsupported ATTRIBUTES codec version ${l}`);let o=r+(l===0?0:r/4),a=l===0?ya:iu,u=o<a?a:o;if(n-1<u)throw Re("truncated ATTRIBUTES stream");let h=n-o,m=e.slice(h,h+r),c=h+r,d=ga(r),f=new Uint8Array(256*4),g=1;for(let x=0;x<t;){let b=Math.min(d,t-x),v=b+vt-1&~(vt-1),p=l===0?0:r/4;if(n-g<p)throw Re("truncated ATTRIBUTES stream");let y=g;g+=p;for(let M=0;M<r;M+=4){let P=l===0?0:e[y+M/4];for(let T=0;T<4;T++){let E=P>>T*2&3;if(E===3){if(n-g<b)throw Re("truncated ATTRIBUTES stream");f.set(e.subarray(g,g+b),T*b),g+=b}else E===2?f.fill(0,T*b,T*b+b):g=l===0?da(e,g,n,f,T*b,v,ou,0):da(e,g,n,f,T*b,v,su,E)}let F=l===0?0:e[c+M/4],W=F&3;if(W===0)for(let T=0;T<4;T++){let E=m[M+T];for(let S=0;S<b;S++)E=eu(f[T*b+S])+E&255,i[(x+S)*r+M+T]=E}else if(W===1)for(let T=0;T<4;T+=2){let E=m[M+T]|m[M+T+1]<<8,S=T*b;for(let O=0;O<b;O++){let k=f[S+O]|f[S+b+O]<<8;E=tu(k)+E&65535;let w=(x+O)*r+M+T;i[w]=E&255,i[w+1]=E>>8}}else if(W===2){let T=32-(F>>4)&31,E=(m[M]|m[M+1]<<8|m[M+2]<<16|m[M+3]<<24)>>>0;for(let S=0;S<b;S++){let O=(f[S]|f[b+S]<<8|f[2*b+S]<<16|f[3*b+S]<<24)>>>0;O=((O<<T|O>>>(32-T&31))^E)>>>0,E=O;let k=(x+S)*r+M;i[k]=O&255,i[k+1]=O>>>8&255,i[k+2]=O>>>16&255,i[k+3]=O>>>24}}else throw Re(`invalid ATTRIBUTES channel ${F}`)}m.set(i.subarray((x+b-1)*r,(x+b)*r)),x+=b}if(n-g!==u)throw Re("ATTRIBUTES trailing data")}var xa=224,va=208;function Ma(e,t){let r=e[t.pos++]??0;if(r<128)return r;let i=r&127,n=7;for(let s=0;s<4;s++){let l=e[t.pos++]??0;if(i=(i|(l&127)<<n)>>>0,n+=7,l<128)break}return i>>>0}function bi(e,t,r){let i=Ma(e,t),n=i>>>1^-(i&1);return r+n>>>0}function uu(e,t,r){if(t%3!==0)throw Re(`TRIANGLES count must be divisible by 3 (got ${t})`);let i=t/3;if(e.byteLength<1+i+16)throw Re("truncated TRIANGLES stream");let n=e[0];if((n&240)!==xa)throw Re(`unsupported TRIANGLES header 0x${n.toString(16)}`);let s=n&15;if(s>1)throw Re(`unsupported TRIANGLES codec version ${s}`);let l=new Uint32Array(16).fill(4294967295),o=new Uint32Array(16).fill(4294967295),a=new Uint32Array(16).fill(4294967295),u=0,h=0,m=(P,F)=>{l[u]=P,o[u]=F,u=u+1&15},c=(P,F=1)=>{a[h]=P,h=h+F&15},d=0,f=0,g=s>=1?13:15,x=1+i,b=e.byteLength-16,v=b,p={pos:x},y=0,M=(P,F,W)=>{r(y++,P),r(y++,F),r(y++,W)};for(let P=1;P<x;P++){let F=e[P];if(F<240){let W=F>>4,T=u-1-W&15,E=l[T],S=o[T],O=0,k=F&15;if(k<g){let w=a[h-1-k&15];O=k===0?d:w;let ie=k===0?1:0;d=d+ie>>>0,c(O,ie)}else{if(p.pos>b)throw Re("truncated TRIANGLES stream");O=k!==15?f+(k*2-27)>>>0:bi(e,p,f),f=O,c(O)}m(O,S),m(E,O),M(E,S,O)}else if(F<254){let W=e[v+(F&15)],T=W>>4,E=W&15,S=d;d=d+1>>>0;let O=a[h-T&15],k=T===0?d:O,w=T===0?1:0;d=d+w>>>0;let ie=a[h-E&15],oe=E===0?d:ie,I=E===0?1:0;d=d+I>>>0,M(S,k,oe),c(S),c(k,w),c(oe,I),m(k,S),m(oe,k),m(S,oe)}else{if(p.pos>b)throw Re("truncated TRIANGLES stream");let W=e[p.pos++],T=F===254?0:15,E=W>>4,S=W&15;W===0&&(d=0);let O=0;T===0&&(O=d,d=d+1>>>0);let k;E===0?(k=d,d=d+1>>>0):k=a[h-E&15];let w;S===0?(w=d,d=d+1>>>0):w=a[h-S&15],T===15&&(f=O=bi(e,p,f)),E===15&&(f=k=bi(e,p,f)),S===15&&(f=w=bi(e,p,f)),M(O,k,w),c(O),c(k,E===0||E===15?1:0),c(w,S===0||S===15?1:0),m(k,O),m(w,k),m(O,w)}}if(p.pos!==b)throw Re("TRIANGLES trailing data")}function lu(e,t,r){if(e.byteLength<1+t+4)throw Re("truncated INDICES stream");let i=e[0];if((i&240)!==va)throw Re(`unsupported INDICES header 0x${i.toString(16)}`);let n=i&15;if(n>1)throw Re(`unsupported INDICES codec version ${n}`);let s=e.byteLength-4,l=[0,0],o={pos:1};for(let a=0;a<t;a++){if(o.pos>=s)throw Re("truncated INDICES stream");let u=Ma(e,o),h=u&1;u>>>=1;let m=u>>>1^-(u&1),c=l[h]+m>>>0;l[h]=c,r(a,c)}if(o.pos!==s)throw Re("INDICES trailing data")}function wo(e,t,r,i,n="NONE"){if(pa(n),!Number.isInteger(t)||t<0||t>Jc||!Number.isInteger(r)||r<=0||r>256)throw Re(`invalid count (${t}) or byteStride (${r})`);let s=t*r;if(s>la)throw Re(`decompressed size (${s}) exceeds MAX_MESHOPT_BUFFER_BYTES (${la})`);if(t===0)return new Uint8Array(0);let l=new Uint8Array(s);if(i==="ATTRIBUTES")return cu(e,t,r,l),Ao(l,t,r,n),l;if(i==="TRIANGLES"||i==="INDICES"){if(r!==2&&r!==4)throw Re(`${i} byteStride must be 2 or 4 (got ${r})`);if(n&&n!=="NONE")throw Re(`filter ${n} is only valid for ATTRIBUTES`);let o=new DataView(l.buffer),a=r===2?(u,h)=>o.setUint16(u*2,h&65535,!0):(u,h)=>o.setUint32(u*4,h>>>0,!0);return i==="TRIANGLES"?uu(e,t,a):lu(e,t,a),l}throw Re(`unknown mode "${String(i)}"`)}function ha(e,t){t>>>=0;do e.push(t&127|(t>127?128:0)),t>>>=7;while(t)}function Ta(e,t,r,i){let n=t*r;if(e.byteLength<n)throw new Error(`encodeMeshoptBuffer: raw buffer (${e.byteLength}) smaller than count * byteStride (${n})`);if(i==="ATTRIBUTES"){if(r%4!==0||r>256)throw new Error(`encodeMeshoptBuffer: ATTRIBUTES byteStride must be a multiple of 4 and <= 256 (got ${r})`);let o=[ba],a=ga(r),u=new Uint8Array(r);t>0&&u.set(e.subarray(0,r));let h=u.slice(),m=new Uint8Array(256);for(let c=0;c<t;){let d=Math.min(a,t-c),f=d+15&-16;for(let g=0;g<r;g++){m.fill(0);let x=u[g];for(let p=0;p<d;p++){let y=e[(c+p)*r+g];m[p]=nu(y-x&255),x=y}u[g]=x;let b=f/16,v=o.length;for(let p=0;p<b+3>>2;p++)o.push(0);for(let p=0;p<b;p++){let y=m.subarray(p*16,p*16+16);if(!y.every(M=>M===0)){o[v+(p>>2)]|=3<<(p&3)*2;for(let M of y)o.push(M)}}}c+=d}for(let c=r;c<ya;c++)o.push(0);for(let c=0;c<r;c++)o.push(h[c]);return new Uint8Array(o)}if(r!==2&&r!==4)throw new Error(`encodeMeshoptBuffer: ${i} byteStride must be 2 or 4 (got ${r})`);let s=new DataView(e.buffer,e.byteOffset,e.byteLength),l=o=>r===2?s.getUint16(o*2,!0):s.getUint32(o*4,!0);if(i==="INDICES"){let o=[va|1],a=0;for(let u=0;u<t;u++){let h=l(u),m=h-a|0;a=h,ha(o,fa(m)<<1>>>0)}return o.push(0,0,0,0),new Uint8Array(o)}if(i==="TRIANGLES"){if(t%3!==0)throw new Error(`encodeMeshoptBuffer: TRIANGLES count must be divisible by 3 (got ${t})`);let o=t/3,a=[xa|1];for(let h=0;h<o;h++)a.push(255);let u=0;for(let h=0;h<o;h++){a.push(255);for(let m=0;m<3;m++){let c=l(h*3+m);ha(a,fa(c-u|0)),u=c}}for(let h=0;h<16;h++)a.push(0);return new Uint8Array(a)}throw new Error(`encodeMeshoptBuffer: unknown mode "${String(i)}"`)}function yi(e,t){let r=t&&typeof t=="object"?t:e,i=t&&typeof t=="object"?e:r?.gltf;if(!i||!Array.isArray(i.bufferViews))return;let n=new Uint8Array(r.bin),s=[],l=0;for(let m=0;m<i.bufferViews.length;m++){let c=i.bufferViews[m],d=c?.extensions?.KHR_meshopt_compression,f=d??c?.extensions?.EXT_meshopt_compression;if(!f||typeof f!="object")continue;let g=d?"KHR_meshopt_compression":"EXT_meshopt_compression",x=Number(f.count),b=Number(f.byteStride),v=Number(f.byteOffset??0),p=Number(f.byteLength??0),y=f.mode||"ATTRIBUTES",M=f.filter||"NONE";if(M==="COLOR"&&!d)throw Re(`bufferView ${m} uses the COLOR filter, which requires KHR_meshopt_compression`);if(Number(f.buffer??0)!==0)throw new Error(`${g}: bufferView ${m} references buffer ${String(f.buffer)}; only the GLB BIN chunk (buffer 0) is supported`);if(!Number.isInteger(v)||v<0||!Number.isInteger(p)||p<0||v+p>n.byteLength)throw new Error(`${g}: bufferView ${m} compressed range [${v}, ${v+p}] out of bounds (${n.byteLength})`);let P=x*b;if(l+=P,l>ma)throw Re(`total decompressed size (${l}) exceeds MAX_MESHOPT_TOTAL_BYTES (${ma})`);let F=n.subarray(v,v+p),W=wo(F,x,b,y,M);s.push({index:m,bytes:W,ext:f})}if(s.length===0)return;let o=n.byteLength+3&-4,a=0;for(let m of s)a+=m.bytes.byteLength+3&-4;let u=new Uint8Array(o+a);u.set(n,0);let h=o;for(let m of s){u.set(m.bytes,h);let c=i.bufferViews[m.index];c.buffer=0,c.byteOffset=h,c.byteLength=m.bytes.byteLength,c._decoded=m.bytes,m.ext.mode==="ATTRIBUTES"&&c.byteStride===void 0&&(c.byteStride=Number(m.ext.byteStride)),c.extensions&&(delete c.extensions.EXT_meshopt_compression,delete c.extensions.KHR_meshopt_compression),h+=m.bytes.byteLength+3&-4}r.bin=u.buffer}var gi={decodeBufferViews(e,t){yi(t)},decodePrimitive(e,t,r){let i=t?.extensions;i?.EXT_meshopt_compression&&delete i.EXT_meshopt_compression,i?.KHR_meshopt_compression&&delete i.KHR_meshopt_compression}};Ae().decoders.set("meshopt",gi);var So={name:"meshopt",onParseGLB(e){Ae().decoders.set("meshopt",gi),yi(e)}},mu=`#version 300 es
|
|
469
|
+
vec3 aCol=vec3(${m(A[0],1,0,1)},${m(A[1],1,0,1)},${m(A[2],1,0,1)});
|
|
470
|
+
vec3 volumeAtten=exp(-tV*(vec3(1.)-aCol)/max(${y},.001));
|
|
471
|
+
diffuseIBL=mix(diffuseIBL,tr*volumeAtten*base.rgb,${g});`)}if(a&&!i.includes("uClearcoat")){let g=m(a.clearcoatFactor,1,0,1),x=m(a.clearcoatRoughnessFactor,0,0,1);f=f.replace("fragColor=vec4(color,base.a);",`vec3 ccF=F_SchlickRoughness(vec3(.04),${x},NoV)*${g};color=color*(vec3(1.)-ccF)+getStudioRadiance(R,${x})*ccF;fragColor=vec4(color,base.a);`)}if(s){let g=Array.isArray(s.sheenColorFactor)?s.sheenColorFactor:[1,1,1],x=`color+=vec3(${m(g[0],1,0,1)},${m(g[1],1,0,1)},${m(g[2],1,0,1)})*pow(1.-NoV,4.)*.5;`;f.includes("color=applyToneMapping(color,uToneMapping);")?f=f.replace("color=applyToneMapping(color,uToneMapping);",`${x}color=applyToneMapping(color,uToneMapping);`):f=f.replace("fragColor=vec4(color,base.a);",`${x}fragColor=vec4(color,base.a);`)}return{vs:r,fs:f}},onBeforeDrawPrimitive(e,t,r,i,n,a){let s=r.materialIndex;if(s!==void 0&&a?.materials){let o=a.materials[s];o?.name&&Fi.has(o.name)&&Fi.get(o.name).onBindUniforms?.(e,t,r)}if(r.isTransmissive){let o=ec.get(e);if(o){e.activeTexture(33990),e.bindTexture(3553,o);let l=e.getUniformLocation(t,"uTransmissionTex");l&&e.uniform1i(l,6);let c=e.getUniformLocation(t,"uViewportSize");c&&e.uniform2f(c,e.drawingBufferWidth||1,e.drawingBufferHeight||1)}}}},Em=64*1024*1024,km=128*1024*1024,Db=16777216;function Ub(e){return(e>>>1^-(e&1))&255}function Bb(e){return(e>>>1^-(e&1))&65535}function Fb(e){let t=e<<24>>24;return(t<<1^t>>7)&255}function Rm(e){return(e<<1^e>>31)>>>0}function Im(e){if(e!==void 0&&e!=="NONE"&&e!=="OCTAHEDRAL"&&e!=="QUATERNION"&&e!=="EXPONENTIAL"&&e!=="COLOR")throw ht(`unknown filter "${String(e)}"`)}var ct=Math.fround;function vo(e){return Math.trunc(ct(e+(e>=0?.5:-.5)))}function _u(e,t,r,i="NONE"){if(Im(i),!i||i==="NONE"||t<=0)return;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(i==="OCTAHEDRAL"){if(r!==4&&r!==8)throw ht(`OCTAHEDRAL filter requires byteStride 4 or 8 (got ${r})`);let m=r===8,h=m?32767:127,p=v=>m?n.getInt16(v,!0):n.getInt8(v),g=(v,y)=>m?n.setInt16(v,y,!0):n.setInt8(v,y<<24>>24),x=m?2:1;for(let v=0;v<t;v++){let y=v*r,A=p(y),b=p(y+x),w=ct(p(y+2*x)-Math.abs(A)-Math.abs(b)),S=w>=0?0:w;A=ct(A+(A>=0?S:-S)),b=ct(b+(b>=0?S:-S));let E=ct(Math.sqrt(ct(ct(ct(A*A)+ct(b*b))+ct(w*w))));if(E===0){g(y,0),g(y+x,0),g(y+2*x,h);continue}let N=ct(h/E);g(y,vo(ct(A*N))),g(y+x,vo(ct(b*N))),g(y+2*x,vo(ct(w*N)))}return}if(i==="QUATERNION"){if(r!==8)throw ht(`QUATERNION filter requires byteStride 8 (got ${r})`);let m=ct(32767/ct(Math.SQRT2));for(let h=0;h<t;h++){let p=h*8,g=n.getInt16(p+6,!0),x=g|3,v=n.getInt16(p,!0),y=n.getInt16(p+2,!0),A=n.getInt16(p+4,!0),b=ct(x*x),w=ct(ct(ct(ct(b*2)-ct(v*v))-ct(y*y))-ct(A*A)),S=ct(Math.sqrt(w>=0?w:0)),E=ct(m/x),N=g&3,C=[0,0,0,0];C[N+1&3]=vo(ct(v*E)),C[N+2&3]=vo(ct(y*E)),C[N+3&3]=vo(ct(A*E)),C[N]=Math.trunc(ct(ct(S*E)+.5));for(let _=0;_<4;_++)n.setInt16(p+_*2,C[_]<<16>>16,!0)}return}if(i==="EXPONENTIAL"){if(r<4||r%4!==0)throw ht(`EXPONENTIAL filter requires byteStride multiple of 4 (got ${r})`);let m=t*r>>>2;for(let h=0;h<m;h++){let p=h*4,g=n.getUint32(p,!0),x=g<<8>>8,v=g>>24;n.setUint32(p,v+127<<23>>>0,!0);let y=n.getFloat32(p,!0);n.setFloat32(p,ct(y*x),!0)}return}if(r!==4&&r!==8)throw new Error(`KHR_meshopt_compression: COLOR filter requires byteStride 4 or 8 (got ${r})`);let a=r===8,s=a?65535:255,o=m=>a?n.getUint16(m,!0):n.getUint8(m),l=m=>a?n.getInt16(m,!0):n.getInt8(m),c=(m,h)=>a?n.setUint16(m,h&65535,!0):n.setUint8(m,h&255),f=a?2:1;for(let m=0;m<t;m++){let h=m*r,p=o(h+3*f);p|=p>>1,p|=p>>2,p|=p>>4,p|=p>>8;let g=o(h),x=l(h+f),v=l(h+2*f),y=g+x-v,A=g+v,b=g-x-v,w=o(h+3*f);w=w<<1&p|w&1;let S=p===0?0:ct(s/p);c(h,Math.trunc(ct(ct(y*S)+.5))),c(h+f,Math.trunc(ct(ct(A*S)+.5))),c(h+2*f,Math.trunc(ct(ct(b*S)+.5))),c(h+3*f,Math.trunc(ct(ct(w*S)+.5)))}}var Cm=160,Jn=16,Vb=24,Nm=32,Ob=24,zb=[0,2,4,8],$b=[0,1,2,4,8];function Dm(e){let t=Math.floor(8192/e)&~(Jn-1);return t<256?t:256}function ht(e){return new Error(`EXT_meshopt_compression: ${e}`)}function Gb(e,t,r,i,n){if(n===0)return r.fill(0,i,i+Jn),t;if(n===8)return r.set(e.subarray(t,t+Jn),i),t+Jn;let a=(1<<n)-1,s=8/n,o=t+Jn*n/8;for(let l=0;l<Jn;l++){let c=e[t+Math.floor(l/s)],f=l%s,m=n===1?c>>f&1:c>>8-n-f*n&a;r[i+l]=m===a?e[o++]:m}return o}function Lm(e,t,r,i,n,a,s,o){let l=a/Jn,c=l+3>>2;if(r-t<c)throw ht("truncated ATTRIBUTES stream");let f=t;t+=c;for(let m=0;m<l;m++){if(r-t<Vb)throw ht("truncated ATTRIBUTES stream");let h=e[f+(m>>2)]>>(m&3)*2&3;t=Gb(e,t,i,n+m*Jn,s[o+h])}return t}function jb(e,t,r,i){if(r%4!==0||r>256)throw ht(`ATTRIBUTES byteStride must be a multiple of 4 and <= 256 (got ${r})`);let n=e.byteLength;if(n<1)throw ht("truncated ATTRIBUTES stream");let a=e[0];if((a&240)!==Cm)throw ht(`unsupported ATTRIBUTES header 0x${a.toString(16)}`);let s=a&15;if(s>1)throw ht(`unsupported ATTRIBUTES codec version ${s}`);let o=r+(s===0?0:r/4),l=s===0?Nm:Ob,c=o<l?l:o;if(n-1<c)throw ht("truncated ATTRIBUTES stream");let f=n-o,m=e.slice(f,f+r),h=f+r,p=Dm(r),g=new Uint8Array(256*4),x=1;for(let v=0;v<t;){let y=Math.min(p,t-v),A=y+Jn-1&~(Jn-1),b=s===0?0:r/4;if(n-x<b)throw ht("truncated ATTRIBUTES stream");let w=x;x+=b;for(let S=0;S<r;S+=4){let E=s===0?0:e[w+S/4];for(let _=0;_<4;_++){let P=E>>_*2&3;if(P===3){if(n-x<y)throw ht("truncated ATTRIBUTES stream");g.set(e.subarray(x,x+y),_*y),x+=y}else P===2?g.fill(0,_*y,_*y+y):x=s===0?Lm(e,x,n,g,_*y,A,zb,0):Lm(e,x,n,g,_*y,A,$b,P)}let N=s===0?0:e[h+S/4],C=N&3;if(C===0)for(let _=0;_<4;_++){let P=m[S+_];for(let R=0;R<y;R++)P=Ub(g[_*y+R])+P&255,i[(v+R)*r+S+_]=P}else if(C===1)for(let _=0;_<4;_+=2){let P=m[S+_]|m[S+_+1]<<8,R=_*y;for(let $=0;$<y;$++){let F=g[R+$]|g[R+y+$]<<8;P=Bb(F)+P&65535;let V=(v+$)*r+S+_;i[V]=P&255,i[V+1]=P>>8}}else if(C===2){let _=32-(N>>4)&31,P=(m[S]|m[S+1]<<8|m[S+2]<<16|m[S+3]<<24)>>>0;for(let R=0;R<y;R++){let $=(g[R]|g[y+R]<<8|g[2*y+R]<<16|g[3*y+R]<<24)>>>0;$=(($<<_|$>>>(32-_&31))^P)>>>0,P=$;let F=(v+R)*r+S;i[F]=$&255,i[F+1]=$>>>8&255,i[F+2]=$>>>16&255,i[F+3]=$>>>24}}else throw ht(`invalid ATTRIBUTES channel ${N}`)}m.set(i.subarray((v+y-1)*r,(v+y)*r)),v+=y}if(n-x!==c)throw ht("ATTRIBUTES trailing data")}var Um=224,Bm=208;function Fm(e,t){let r=e[t.pos++]??0;if(r<128)return r;let i=r&127,n=7;for(let a=0;a<4;a++){let s=e[t.pos++]??0;if(i=(i|(s&127)<<n)>>>0,n+=7,s<128)break}return i>>>0}function tc(e,t,r){let i=Fm(e,t),n=i>>>1^-(i&1);return r+n>>>0}function Hb(e,t,r){if(t%3!==0)throw ht(`TRIANGLES count must be divisible by 3 (got ${t})`);let i=t/3;if(e.byteLength<1+i+16)throw ht("truncated TRIANGLES stream");let n=e[0];if((n&240)!==Um)throw ht(`unsupported TRIANGLES header 0x${n.toString(16)}`);let a=n&15;if(a>1)throw ht(`unsupported TRIANGLES codec version ${a}`);let s=new Uint32Array(16).fill(4294967295),o=new Uint32Array(16).fill(4294967295),l=new Uint32Array(16).fill(4294967295),c=0,f=0,m=(E,N)=>{s[c]=E,o[c]=N,c=c+1&15},h=(E,N=1)=>{l[f]=E,f=f+N&15},p=0,g=0,x=a>=1?13:15,v=1+i,y=e.byteLength-16,A=y,b={pos:v},w=0,S=(E,N,C)=>{r(w++,E),r(w++,N),r(w++,C)};for(let E=1;E<v;E++){let N=e[E];if(N<240){let C=N>>4,_=c-1-C&15,P=s[_],R=o[_],$=0,F=N&15;if(F<x){let V=l[f-1-F&15];$=F===0?p:V;let Y=F===0?1:0;p=p+Y>>>0,h($,Y)}else{if(b.pos>y)throw ht("truncated TRIANGLES stream");$=F!==15?g+(F*2-27)>>>0:tc(e,b,g),g=$,h($)}m($,R),m(P,$),S(P,R,$)}else if(N<254){let C=e[A+(N&15)],_=C>>4,P=C&15,R=p;p=p+1>>>0;let $=l[f-_&15],F=_===0?p:$,V=_===0?1:0;p=p+V>>>0;let Y=l[f-P&15],J=P===0?p:Y,re=P===0?1:0;p=p+re>>>0,S(R,F,J),h(R),h(F,V),h(J,re),m(F,R),m(J,F),m(R,J)}else{if(b.pos>y)throw ht("truncated TRIANGLES stream");let C=e[b.pos++],_=N===254?0:15,P=C>>4,R=C&15;C===0&&(p=0);let $=0;_===0&&($=p,p=p+1>>>0);let F;P===0?(F=p,p=p+1>>>0):F=l[f-P&15];let V;R===0?(V=p,p=p+1>>>0):V=l[f-R&15],_===15&&(g=$=tc(e,b,g)),P===15&&(g=F=tc(e,b,g)),R===15&&(g=V=tc(e,b,g)),S($,F,V),h($),h(F,P===0||P===15?1:0),h(V,R===0||R===15?1:0),m(F,$),m(V,F),m($,V)}}if(b.pos!==y)throw ht("TRIANGLES trailing data")}function Wb(e,t,r){if(e.byteLength<1+t+4)throw ht("truncated INDICES stream");let i=e[0];if((i&240)!==Bm)throw ht(`unsupported INDICES header 0x${i.toString(16)}`);let n=i&15;if(n>1)throw ht(`unsupported INDICES codec version ${n}`);let a=e.byteLength-4,s=[0,0],o={pos:1};for(let l=0;l<t;l++){if(o.pos>=a)throw ht("truncated INDICES stream");let c=Fm(e,o),f=c&1;c>>>=1;let m=c>>>1^-(c&1),h=s[f]+m>>>0;s[f]=h,r(l,h)}if(o.pos!==a)throw ht("INDICES trailing data")}function Eu(e,t,r,i,n="NONE"){if(Im(n),!Number.isInteger(t)||t<0||t>Db||!Number.isInteger(r)||r<=0||r>256)throw ht(`invalid count (${t}) or byteStride (${r})`);let a=t*r;if(a>Em)throw ht(`decompressed size (${a}) exceeds MAX_MESHOPT_BUFFER_BYTES (${Em})`);if(t===0)return new Uint8Array(0);let s=new Uint8Array(a);if(i==="ATTRIBUTES")return jb(e,t,r,s),_u(s,t,r,n),s;if(i==="TRIANGLES"||i==="INDICES"){if(r!==2&&r!==4)throw ht(`${i} byteStride must be 2 or 4 (got ${r})`);if(n&&n!=="NONE")throw ht(`filter ${n} is only valid for ATTRIBUTES`);let o=new DataView(s.buffer),l=r===2?(c,f)=>o.setUint16(c*2,f&65535,!0):(c,f)=>o.setUint32(c*4,f>>>0,!0);return i==="TRIANGLES"?Hb(e,t,l):Wb(e,t,l),s}throw ht(`unknown mode "${String(i)}"`)}function Pm(e,t){t>>>=0;do e.push(t&127|(t>127?128:0)),t>>>=7;while(t)}function Vm(e,t,r,i){let n=t*r;if(e.byteLength<n)throw new Error(`encodeMeshoptBuffer: raw buffer (${e.byteLength}) smaller than count * byteStride (${n})`);if(i==="ATTRIBUTES"){if(r%4!==0||r>256)throw new Error(`encodeMeshoptBuffer: ATTRIBUTES byteStride must be a multiple of 4 and <= 256 (got ${r})`);let o=[Cm],l=Dm(r),c=new Uint8Array(r);t>0&&c.set(e.subarray(0,r));let f=c.slice(),m=new Uint8Array(256);for(let h=0;h<t;){let p=Math.min(l,t-h),g=p+15&-16;for(let x=0;x<r;x++){m.fill(0);let v=c[x];for(let b=0;b<p;b++){let w=e[(h+b)*r+x];m[b]=Fb(w-v&255),v=w}c[x]=v;let y=g/16,A=o.length;for(let b=0;b<y+3>>2;b++)o.push(0);for(let b=0;b<y;b++){let w=m.subarray(b*16,b*16+16);if(!w.every(S=>S===0)){o[A+(b>>2)]|=3<<(b&3)*2;for(let S of w)o.push(S)}}}h+=p}for(let h=r;h<Nm;h++)o.push(0);for(let h=0;h<r;h++)o.push(f[h]);return new Uint8Array(o)}if(r!==2&&r!==4)throw new Error(`encodeMeshoptBuffer: ${i} byteStride must be 2 or 4 (got ${r})`);let a=new DataView(e.buffer,e.byteOffset,e.byteLength),s=o=>r===2?a.getUint16(o*2,!0):a.getUint32(o*4,!0);if(i==="INDICES"){let o=[Bm|1],l=0;for(let c=0;c<t;c++){let f=s(c),m=f-l|0;l=f,Pm(o,Rm(m)<<1>>>0)}return o.push(0,0,0,0),new Uint8Array(o)}if(i==="TRIANGLES"){if(t%3!==0)throw new Error(`encodeMeshoptBuffer: TRIANGLES count must be divisible by 3 (got ${t})`);let o=t/3,l=[Um|1];for(let f=0;f<o;f++)l.push(255);let c=0;for(let f=0;f<o;f++){l.push(255);for(let m=0;m<3;m++){let h=s(f*3+m);Pm(l,Rm(h-c|0)),c=h}}for(let f=0;f<16;f++)l.push(0);return new Uint8Array(l)}throw new Error(`encodeMeshoptBuffer: unknown mode "${String(i)}"`)}function nc(e,t){let r=t&&typeof t=="object"?t:e,i=t&&typeof t=="object"?e:r?.gltf;if(!i||!Array.isArray(i.bufferViews))return;let n=new Uint8Array(r.bin),a=[],s=0;for(let m=0;m<i.bufferViews.length;m++){let h=i.bufferViews[m],p=h?.extensions?.KHR_meshopt_compression,g=p??h?.extensions?.EXT_meshopt_compression;if(!g||typeof g!="object")continue;let x=p?"KHR_meshopt_compression":"EXT_meshopt_compression",v=Number(g.count),y=Number(g.byteStride),A=Number(g.byteOffset??0),b=Number(g.byteLength??0),w=g.mode||"ATTRIBUTES",S=g.filter||"NONE";if(S==="COLOR"&&!p)throw ht(`bufferView ${m} uses the COLOR filter, which requires KHR_meshopt_compression`);if(Number(g.buffer??0)!==0)throw new Error(`${x}: bufferView ${m} references buffer ${String(g.buffer)}; only the GLB BIN chunk (buffer 0) is supported`);if(!Number.isInteger(A)||A<0||!Number.isInteger(b)||b<0||A+b>n.byteLength)throw new Error(`${x}: bufferView ${m} compressed range [${A}, ${A+b}] out of bounds (${n.byteLength})`);let E=v*y;if(s+=E,s>km)throw ht(`total decompressed size (${s}) exceeds MAX_MESHOPT_TOTAL_BYTES (${km})`);let N=n.subarray(A,A+b),C=Eu(N,v,y,w,S);a.push({index:m,bytes:C,ext:g})}if(a.length===0)return;let o=n.byteLength+3&-4,l=0;for(let m of a)l+=m.bytes.byteLength+3&-4;let c=new Uint8Array(o+l);c.set(n,0);let f=o;for(let m of a){c.set(m.bytes,f);let h=i.bufferViews[m.index];h.buffer=0,h.byteOffset=f,h.byteLength=m.bytes.byteLength,h._decoded=m.bytes,m.ext.mode==="ATTRIBUTES"&&h.byteStride===void 0&&(h.byteStride=Number(m.ext.byteStride)),h.extensions&&(delete h.extensions.EXT_meshopt_compression,delete h.extensions.KHR_meshopt_compression),f+=m.bytes.byteLength+3&-4}r.bin=c.buffer}var rc={decodeBufferViews(e,t){nc(t)},decodePrimitive(e,t,r){let i=t?.extensions;i?.EXT_meshopt_compression&&delete i.EXT_meshopt_compression,i?.KHR_meshopt_compression&&delete i.KHR_meshopt_compression}};He().decoders.set("meshopt",rc);var ku={name:"meshopt",onParseGLB(e){He().decoders.set("meshopt",rc),nc(e)}},Xb=`#version 300 es
|
|
424
472
|
layout(location=0) in vec3 aPosition;
|
|
425
473
|
layout(location=1) in vec3 aNormal;
|
|
426
474
|
uniform mat4 uMVP,uVP;
|
|
@@ -441,19 +489,19 @@ vec2 pxOffset=dir*(uOutlineThickness*2.0/max(uViewportSize,vec2(1.0)))*clipPos.w
|
|
|
441
489
|
clipPos.xy+=pxOffset;
|
|
442
490
|
clipPos.z+=1e-4*clipPos.w;
|
|
443
491
|
gl_Position=clipPos;
|
|
444
|
-
}`,
|
|
492
|
+
}`,qb=`#version 300 es
|
|
445
493
|
precision highp float;
|
|
446
494
|
uniform vec4 uOutlineColor;
|
|
447
495
|
out vec4 fragColor;
|
|
448
496
|
void main(){
|
|
449
497
|
fragColor=uOutlineColor;
|
|
450
|
-
}`,
|
|
498
|
+
}`,Om=`#version 300 es
|
|
451
499
|
out vec2 vUV;
|
|
452
500
|
void main(){
|
|
453
501
|
vec2 pos=vec2((gl_VertexID<<1)&2,gl_VertexID&2);
|
|
454
502
|
vUV=pos;
|
|
455
503
|
gl_Position=vec4(pos*2.0-1.0,0.0,1.0);
|
|
456
|
-
}`,
|
|
504
|
+
}`,Yb=`#version 300 es
|
|
457
505
|
precision highp float;
|
|
458
506
|
in vec2 vUV;
|
|
459
507
|
uniform sampler2D uSourceTex;
|
|
@@ -476,7 +524,7 @@ c+=prefilter(texture(uSourceTex,vUV+vec2(h.x,-h.y)).rgb)*0.125;
|
|
|
476
524
|
c+=prefilter(texture(uSourceTex,vUV+vec2(-h.x,h.y)).rgb)*0.125;
|
|
477
525
|
c+=prefilter(texture(uSourceTex,vUV+vec2(h.x,h.y)).rgb)*0.125;
|
|
478
526
|
fragColor=vec4(c,1.0);
|
|
479
|
-
}`,
|
|
527
|
+
}`,Kb=`#version 300 es
|
|
480
528
|
precision highp float;
|
|
481
529
|
in vec2 vUV;
|
|
482
530
|
uniform sampler2D uBloomTex;
|
|
@@ -498,4 +546,674 @@ sum+=texture(uBloomTex,vUV+vec2(-d.x,-d.y)).rgb*2.0;
|
|
|
498
546
|
vec3 bloom=(sum/12.0)*uStrength;
|
|
499
547
|
float a=clamp(min(bloom.r,min(bloom.g,bloom.b)),0.0,1.0);
|
|
500
548
|
fragColor=vec4(bloom,a);
|
|
501
|
-
}`,xi=3,Zn=new WeakMap;function Eo(e,t=[.22,.74,.97]){let r=Vi(e,"");if(!r.startsWith("#"))return[t[0],t[1],t[2]];let i=r.slice(1);if(i.length===3){let n=+("0x"+i[0]+i[0])/255,s=+("0x"+i[1]+i[1])/255,l=+("0x"+i[2]+i[2])/255;return[n,s,l]}if(i.length===6){let n=+("0x"+i.slice(0,2))/255,s=+("0x"+i.slice(2,4))/255,l=+("0x"+i.slice(4,6))/255;return[n,s,l]}return[t[0],t[1],t[2]]}function Ea(e,t,r=.8,i=.5){let n=Number.isFinite(t)?Math.max(0,t):0;if(n<=0)return[0,0,0];let s=Math.max(0,Number(e[0])||0),l=Math.max(0,Number(e[1])||0),o=Math.max(0,Number(e[2])||0),a=Math.max(s,l,o);if(a<=1e-6)return[0,0,0];let u=Number.isFinite(r)?Math.max(0,r):.8,h=Math.max(u*Math.max(0,i),1e-4),m=Math.max(0,Math.min(2*h,a-u+h)),c=m*m/(4*h+1e-4),d=Math.min(1,Math.max(0,Math.max(c,a-u)/Math.max(a,1e-4)))*n;return[s*d,l*d,o*d]}function Ra(e,t,r,i){let n=Number(e[0])||0,s=Number(e[1])||0,l=Math.hypot(n,s);if(l<=1e-5||t<=0||r<=0)return[0,0];let o=Math.max(1,Number(i[0])||1),a=Math.max(1,Number(i[1])||1),u=Math.max(0,r)*2*t;return[n/l*(u/o),s/l*(u/a)]}var wa=new WeakSet;function Sa(e){let t=Zn.get(e);if(t){if(typeof e.isProgram!="function"||e.isProgram(t.outlineProg))return t;Zn.delete(e)}if(wa.has(e)||e.isContextLost?.())return null;let r=_t(e,mu,fu,!1),i=_t(e,Aa,du,!1),n=_t(e,Aa,hu,!1);if(!r||!i||!n){for(let l of[r,i,n])l&&e.deleteProgram(l);return wa.add(e),null}let s=typeof e.createVertexArray=="function"?e.createVertexArray():null;return t={outlineProg:r,uOutlineMVP:e.getUniformLocation(r,"uMVP"),uOutlineVP:e.getUniformLocation(r,"uVP"),uOutlineNormalMatrix:e.getUniformLocation(r,"uNormalMatrix"),uOutlineViewportSize:e.getUniformLocation(r,"uViewportSize"),uOutlineThickness:e.getUniformLocation(r,"uOutlineThickness"),uOutlineColor:e.getUniformLocation(r,"uOutlineColor"),downProg:i,uDownSourceTex:e.getUniformLocation(i,"uSourceTex"),uDownTexelSize:e.getUniformLocation(i,"uTexelSize"),uDownThreshold:e.getUniformLocation(i,"uThreshold"),upProg:n,uUpBloomTex:e.getUniformLocation(n,"uBloomTex"),uUpTexelSize:e.getUniformLocation(n,"uTexelSize"),uUpRadius:e.getUniformLocation(n,"uRadius"),uUpStrength:e.getUniformLocation(n,"uStrength"),fsVao:s,sceneTex:null,bloomTex:[],bloomFbo:[],mipWidth:[],mipHeight:[],texWidth:0,texHeight:0},Zn.set(e,t),t}function pu(e,t,r,i){if(typeof e.createFramebuffer!="function"||typeof e.copyTexSubImage2D!="function")return!1;let n=Math.max(2,r|0),s=Math.max(2,i|0);if(t.sceneTex&&t.bloomFbo.length===xi&&t.texWidth===n&&t.texHeight===s)return!0;t.sceneTex||(t.sceneTex=e.createTexture()),e.bindTexture(3553,t.sceneTex),e.texImage2D(3553,0,6408,n,s,0,6408,5121,null),e.texParameteri(3553,10241,9729),e.texParameteri(3553,10240,9729),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071);let l=n,o=s;for(let a=0;a<xi;a++)l=Math.max(1,l>>1),o=Math.max(1,o>>1),t.mipWidth[a]=l,t.mipHeight[a]=o,t.bloomTex[a]||(t.bloomTex[a]=e.createTexture()),e.bindTexture(3553,t.bloomTex[a]),e.texImage2D(3553,0,6408,l,o,0,6408,5121,null),e.texParameteri(3553,10241,9729),e.texParameteri(3553,10240,9729),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071),t.bloomFbo[a]||(t.bloomFbo[a]=e.createFramebuffer()),e.bindFramebuffer(36160,t.bloomFbo[a]),e.framebufferTexture2D(36160,36064,3553,t.bloomTex[a],0);return e.bindFramebuffer(36160,null),t.texWidth=n,t.texHeight=s,!0}function bu(e){let t=e.container;if(t&&typeof t.getAttribute=="function"){let i=t.getAttribute("bloom");if(i!==null){let n=i.trim().toLowerCase();if(n==="false"||n==="0"||n==="none")return null;let s=n===""||n==="true"?.35:Number(n);if(!Number.isFinite(s)||s<=0)return null;let l=Bi({strength:s,threshold:mn(t.getAttribute("bloom-threshold"),.62),radius:mn(t.getAttribute("bloom-radius"),.75)});if(l)return l}}let r=null;for(let i of e.meshes||[]){if(i.visible===!1)continue;let n=i?.extras?.xr?.bloom??i?.userData?.xr?.bloom,s=Bi(n);s&&(!r||s.strength>r.strength)&&(r=s)}return r}function yu(e,t){if(e==null)return null;let r=e.trim(),i=r.toLowerCase();if(i==="false"||i==="0"||i==="none")return null;let n=t,s=3.5,l=!1;if(r&&i!=="true"){let o=r.split(/\s+/);for(let a of o)if(a.startsWith("#"))n=a;else if(a.toLowerCase()==="pulse")l=!0;else{let u=Number(a);Number.isFinite(u)&&u>0&&(s=u)}}return dr({color:n,thickness:s,pulse:l})}var gu=new Set(["floor","pedestal","ground","table","grid","pad"]);function xu(e){return e.replace(/([a-z\d])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z]+/).some(t=>gu.has(t))}function vu(e,t){let r=e.container,i=typeof r?.getAttribute=="function"?r.getAttribute("outline"):null;if(i!=null){let h=i.trim().toLowerCase();if(h==="false"||h==="0"||h==="none")return null}let n=t?.extras?.xr?.outline??t?.userData?.xr?.outline,s=dr(n);if(s)return s;let l=typeof r?.getAttribute=="function"&&r.getAttribute("outline-color")||"#38bdf8",o=yu(i,l),a=r!=null&&typeof r.hasAttribute=="function"&&r.hasAttribute("outline-selected")&&r.getAttribute("outline-selected")!=="false",u=e.getSelectedMesh?.()||"";if(u)return t.name!==u?null:o||(a?dr({color:l,thickness:3,pulse:!1}):null);if(o){let h=t.name||"";return xu(h)?null:o}return null}var Ro={name:"postprocessing",onAttributeChanged(e,t){(t==="bloom"||t==="bloom-threshold"||t==="bloom-radius"||t==="outline"||t==="outline-selected"||t==="outline-color"||t==="selected-mesh")&&e.viewer?.render?.()},onAfterRender(e,t,r){if(!t.meshes||t.meshes.length===0)return;let i=Math.max(1,t.canvas?.width||300),n=Math.max(1,t.canvas?.height||150),s=[];for(let c of t.meshes){if(c.visible===!1)continue;let d=vu(t,c);d&&s.push({mesh:c,trait:d})}let l=s.length>0?Sa(e):null;if(l){let c=l,d=Se(),f=Se(),g=new Float32Array(9),x=(typeof performance<"u"?performance.now():Date.now())*.001,b=typeof e.getParameter=="function"?e.getParameter(e.VIEWPORT):null,v=Math.max(1,b?.[2]||i),p=Math.max(1,b?.[3]||n);e.useProgram(c.outlineProg),c.uOutlineViewportSize&&e.uniform2f(c.uOutlineViewportSize,v,p),c.uOutlineVP&&e.uniformMatrix4fv(c.uOutlineVP,!1,r),e.enable(e.CULL_FACE),e.cullFace(e.FRONT),e.enable(2929),e.depthFunc(e.LEQUAL),e.depthMask(!1);for(let{mesh:y,trait:M}of s){let[P,F,W]=Eo(M.color),T=M.pulse?.8+.25*Math.sin(x*4):1;c.uOutlineColor&&e.uniform4f(c.uOutlineColor,P,F,W,1),c.uOutlineThickness&&e.uniform1f(c.uOutlineThickness,M.thickness*T),y.worldSpace===!0?d.set(y.transform):Ie(d,t.modelRootMatrix,y.transform);let E=y.instanceMatrices;for(let S of y.primitives)if(!(S.pluginData?.skinning?.hasSkin||S.pluginData?.morph?.hasMorph))if(e.bindVertexArray(S.vao),E&&E.length>=16){let O=E.length>>4,k=Se();for(let w=0;w<O;w++)Ie(k,d,E.subarray(w*16,w*16+16)),Ie(f,r,k),Xe(g,k),e.uniformMatrix4fv(c.uOutlineMVP,!1,f),e.uniformMatrix3fv(c.uOutlineNormalMatrix,!1,g),S.indices?e.drawElements(4,S.indexCount,S.indexType,0):e.drawArrays(4,0,S.indexCount)}else Ie(f,r,d),Xe(g,d),e.uniformMatrix4fv(c.uOutlineMVP,!1,f),e.uniformMatrix3fv(c.uOutlineNormalMatrix,!1,g),S.indices?e.drawElements(4,S.indexCount,S.indexType,0):e.drawArrays(4,0,S.indexCount)}e.bindVertexArray(null),e.cullFace(e.BACK),e.disable(e.CULL_FACE),e.depthFunc(e.LESS),e.depthMask(!0)}if(t.xrSessionActive||t.stereoSBS)return;let o=bu(t);if(!o||o.strength<=0)return;let a=Sa(e);if(!a||!pu(e,a,i,n)||!a.fsVao)return;e.activeTexture(33984),e.bindTexture(3553,a.sceneTex),e.copyTexSubImage2D(3553,0,0,0,0,0,i,n),e.disable(2929),e.depthMask(!1),e.disable(3042),e.useProgram(a.downProg),e.uniform1i(a.uDownSourceTex,0),e.bindVertexArray(a.fsVao);let u=a.sceneTex,h=i,m=n;for(let c=0;c<xi;c++){let d=a.mipWidth[c],f=a.mipHeight[c];e.bindFramebuffer(36160,a.bloomFbo[c]),e.viewport(0,0,d,f),e.bindTexture(3553,u),e.uniform2f(a.uDownTexelSize,1/h,1/m),e.uniform1f(a.uDownThreshold,c===0?o.threshold:0),e.drawArrays(4,0,3),u=a.bloomTex[c],h=d,m=f}e.enable(3042),typeof e.blendFuncSeparate=="function"?e.blendFuncSeparate(e.ONE,e.ONE,e.ONE,771):e.blendFunc(e.ONE,e.ONE),e.useProgram(a.upProg),e.uniform1i(a.uUpBloomTex,0),e.uniform1f(a.uUpRadius,o.radius);for(let c=xi-1;c>=1;c--){let d=c-1;e.bindFramebuffer(36160,a.bloomFbo[d]),e.viewport(0,0,a.mipWidth[d],a.mipHeight[d]),e.bindTexture(3553,a.bloomTex[c]),e.uniform2f(a.uUpTexelSize,1/a.mipWidth[c],1/a.mipHeight[c]),e.uniform1f(a.uUpStrength,.85),e.drawArrays(4,0,3)}e.bindFramebuffer(36160,null),e.viewport(0,0,i,n),e.bindTexture(3553,a.bloomTex[0]),e.uniform2f(a.uUpTexelSize,1/a.mipWidth[0],1/a.mipHeight[0]),e.uniform1f(a.uUpStrength,o.strength),e.drawArrays(4,0,3),e.bindVertexArray(null),e.blendFunc(770,771),e.disable(3042),e.depthMask(!0),e.enable(2929)},onDestroy(e){let t=Zn.get(e);if(t){e.deleteProgram(t.outlineProg),e.deleteProgram(t.downProg),e.deleteProgram(t.upProg),t.fsVao&&e.deleteVertexArray(t.fsVao),t.sceneTex&&e.deleteTexture(t.sceneTex);for(let r of t.bloomTex)r&&e.deleteTexture(r);for(let r of t.bloomFbo)r&&e.deleteFramebuffer(r);Zn.delete(e)}}};function _o(e){let t=e?.extensions?.KHR_materials_variants?.variants;if(!Array.isArray(t))return[];let r=[];for(let i=0;i<t.length&&r.length<256;i++){let n=t[i]?.name;r.push(typeof n=="string"&&n.length>0?n:`Variant_${i}`)}return r}function _a(e){let t=e?.extensions?.KHR_materials_variants?.mappings;if(!Array.isArray(t))return[];let r=[];for(let i of t){if(!i||typeof i!="object")continue;let n=i,s=Number(n.material);if(!Number.isInteger(s)||s<0)continue;let l=[];if(Array.isArray(n.variants))for(let o of n.variants){let a=Number(o);Number.isInteger(a)&&a>=0&&l.push(a)}l.length>0&&r.push({material:s,variants:l})}return r}function La(e,t,r,i=0){let n=e;if(n&&typeof n.selectVariant=="function"&&!Array.isArray(t))return n.selectVariant(typeof t=="string"?t:null);let s=e,l=Array.isArray(t)?t:[],o=r??null;if(!o)return i;let a=_o(s).indexOf(o);if(a<0)return i;for(let u of l)if(u.variants.includes(a))return u.material;return i}var Lo={name:"variants",onLoadModel(e,t){let r=e.getVariantName?.();r&&e.selectVariant(r)}},Ia=new WeakMap,Io={name:"webxr-suite",onConfigureXRSessionInit(e,t){let r=new Set(t.optionalFeatures||[]);r.add("hit-test"),r.add("light-estimation");let i=e?.querySelector?.('[slot="ar-overlay"]')||null;i&&(r.add("dom-overlay"),t.domOverlay={root:i},i.addEventListener?.("beforexrselect",n=>{n.preventDefault()})),t.optionalFeatures=Array.from(r)},onXRFrame(e,t,r,i){if(!e||!t||!r||!i)return;let n=Ia.get(t);if(n||(n={lightProbe:null},Ia.set(t,n),typeof t.requestLightProbe=="function"&&t.requestLightProbe().then(s=>{n&&s&&(n.lightProbe=s)}).catch(()=>{})),n.lightProbe&&typeof r.getLightEstimate=="function"){let s=r.getLightEstimate(n.lightProbe);if(s){let l=s.primaryLightDirection,o=s.primaryLightIntensity;if(l&&o&&Array.isArray(e.lights)){let a=e.lights.find(h=>h.type==="directional");a||(a={type:"directional",direction:[.5,1,.8],color:[1,1,1],intensity:1},e.lights.push(a)),a.direction=[l.x,l.y,l.z];let u=Math.max(o.x,o.y,o.z,.001);a.color=[o.x/u,o.y/u,o.z/u],a.intensity=u}s.sphericalHarmonicsCoefficients&&e.gl&&ui(e.gl,s.sphericalHarmonicsCoefficients)}}}};Ve(jn),Ve(yo),Ve(ho),Ve(To),Ve(Io),Ve(Mo),Ve(So),Ve(Lo),Ve(Ro),Ve(Pi),mt.registerScriptRunner(ln),typeof window<"u"&&(window.ThreeLiveBundle=Co);
|
|
549
|
+
}`,oc=3,Vi=new WeakMap;function Ru(e,t=[.22,.74,.97]){let r=Qc(e,"");if(!r.startsWith("#"))return[t[0],t[1],t[2]];let i=r.slice(1);if(i.length===3){let n=+("0x"+i[0]+i[0])/255,a=+("0x"+i[1]+i[1])/255,s=+("0x"+i[2]+i[2])/255;return[n,a,s]}if(i.length===6){let n=+("0x"+i.slice(0,2))/255,a=+("0x"+i.slice(2,4))/255,s=+("0x"+i.slice(4,6))/255;return[n,a,s]}return[t[0],t[1],t[2]]}function Gm(e,t,r=.8,i=.5){let n=Number.isFinite(t)?Math.max(0,t):0;if(n<=0)return[0,0,0];let a=Math.max(0,Number(e[0])||0),s=Math.max(0,Number(e[1])||0),o=Math.max(0,Number(e[2])||0),l=Math.max(a,s,o);if(l<=1e-6)return[0,0,0];let c=Number.isFinite(r)?Math.max(0,r):.8,f=Math.max(c*Math.max(0,i),1e-4),m=Math.max(0,Math.min(2*f,l-c+f)),h=m*m/(4*f+1e-4),p=Math.min(1,Math.max(0,Math.max(h,l-c)/Math.max(l,1e-4)))*n;return[a*p,s*p,o*p]}function jm(e,t,r,i){let n=Number(e[0])||0,a=Number(e[1])||0,s=Math.hypot(n,a);if(s<=1e-5||t<=0||r<=0)return[0,0];let o=Math.max(1,Number(i[0])||1),l=Math.max(1,Number(i[1])||1),c=Math.max(0,r)*2*t;return[n/s*(c/o),a/s*(c/l)]}var zm=new WeakSet;function $m(e){let t=Vi.get(e);if(t){if(typeof e.isProgram!="function"||e.isProgram(t.outlineProg))return t;Vi.delete(e)}if(zm.has(e)||e.isContextLost?.())return null;let r=ir(e,Xb,qb,!1),i=ir(e,Om,Yb,!1),n=ir(e,Om,Kb,!1);if(!r||!i||!n){for(let s of[r,i,n])s&&e.deleteProgram(s);return zm.add(e),null}let a=typeof e.createVertexArray=="function"?e.createVertexArray():null;return t={outlineProg:r,uOutlineMVP:e.getUniformLocation(r,"uMVP"),uOutlineVP:e.getUniformLocation(r,"uVP"),uOutlineNormalMatrix:e.getUniformLocation(r,"uNormalMatrix"),uOutlineViewportSize:e.getUniformLocation(r,"uViewportSize"),uOutlineThickness:e.getUniformLocation(r,"uOutlineThickness"),uOutlineColor:e.getUniformLocation(r,"uOutlineColor"),downProg:i,uDownSourceTex:e.getUniformLocation(i,"uSourceTex"),uDownTexelSize:e.getUniformLocation(i,"uTexelSize"),uDownThreshold:e.getUniformLocation(i,"uThreshold"),upProg:n,uUpBloomTex:e.getUniformLocation(n,"uBloomTex"),uUpTexelSize:e.getUniformLocation(n,"uTexelSize"),uUpRadius:e.getUniformLocation(n,"uRadius"),uUpStrength:e.getUniformLocation(n,"uStrength"),fsVao:a,sceneTex:null,bloomTex:[],bloomFbo:[],mipWidth:[],mipHeight:[],texWidth:0,texHeight:0},Vi.set(e,t),t}function Jb(e,t,r,i){if(typeof e.createFramebuffer!="function"||typeof e.copyTexSubImage2D!="function")return!1;let n=Math.max(2,r|0),a=Math.max(2,i|0);if(t.sceneTex&&t.bloomFbo.length===oc&&t.texWidth===n&&t.texHeight===a)return!0;t.sceneTex||(t.sceneTex=e.createTexture()),e.bindTexture(3553,t.sceneTex),e.texImage2D(3553,0,6408,n,a,0,6408,5121,null),e.texParameteri(3553,10241,9729),e.texParameteri(3553,10240,9729),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071);let s=n,o=a;for(let l=0;l<oc;l++)s=Math.max(1,s>>1),o=Math.max(1,o>>1),t.mipWidth[l]=s,t.mipHeight[l]=o,t.bloomTex[l]||(t.bloomTex[l]=e.createTexture()),e.bindTexture(3553,t.bloomTex[l]),e.texImage2D(3553,0,6408,s,o,0,6408,5121,null),e.texParameteri(3553,10241,9729),e.texParameteri(3553,10240,9729),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071),t.bloomFbo[l]||(t.bloomFbo[l]=e.createFramebuffer()),e.bindFramebuffer(36160,t.bloomFbo[l]),e.framebufferTexture2D(36160,36064,3553,t.bloomTex[l],0);return e.bindFramebuffer(36160,null),t.texWidth=n,t.texHeight=a,!0}function Qb(e){let t=e.container;if(t&&typeof t.getAttribute=="function"){let i=t.getAttribute("bloom");if(i!==null){let n=i.trim().toLowerCase();if(n==="false"||n==="0"||n==="none")return null;let a=n===""||n==="true"?.35:Number(n);if(!Number.isFinite(a)||a<=0)return null;let s=Zc({strength:a,threshold:ao(t.getAttribute("bloom-threshold"),.62),radius:ao(t.getAttribute("bloom-radius"),.75)});if(s)return s}}let r=null;for(let i of e.meshes||[]){if(i.visible===!1)continue;let n=i?.extras?.xr?.bloom??i?.userData?.xr?.bloom,a=Zc(n);a&&(!r||a.strength>r.strength)&&(r=a)}return r}function Zb(e,t){if(e==null)return null;let r=e.trim(),i=r.toLowerCase();if(i==="false"||i==="0"||i==="none")return null;let n=t,a=3.5,s=!1;if(r&&i!=="true"){let o=r.split(/\s+/);for(let l of o)if(l.startsWith("#"))n=l;else if(l.toLowerCase()==="pulse")s=!0;else{let c=Number(l);Number.isFinite(c)&&c>0&&(a=c)}}return Ms({color:n,thickness:a,pulse:s})}var ey=new Set(["floor","pedestal","ground","table","grid","pad"]);function ty(e){return e.replace(/([a-z\d])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z]+/).some(t=>ey.has(t))}function ny(e,t){let r=e.container,i=typeof r?.getAttribute=="function"?r.getAttribute("outline"):null;if(i!=null){let f=i.trim().toLowerCase();if(f==="false"||f==="0"||f==="none")return null}let n=t?.extras?.xr?.outline??t?.userData?.xr?.outline,a=Ms(n);if(a)return a;let s=typeof r?.getAttribute=="function"&&r.getAttribute("outline-color")||"#38bdf8",o=Zb(i,s),l=r!=null&&typeof r.hasAttribute=="function"&&r.hasAttribute("outline-selected")&&r.getAttribute("outline-selected")!=="false",c=e.getSelectedMesh?.()||"";if(c)return t.name!==c?null:o||(l?Ms({color:s,thickness:3,pulse:!1}):null);if(o){let f=t.name||"";return ty(f)?null:o}return null}var Lu={name:"postprocessing",onAttributeChanged(e,t){(t==="bloom"||t==="bloom-threshold"||t==="bloom-radius"||t==="outline"||t==="outline-selected"||t==="outline-color"||t==="selected-mesh")&&e.viewer?.render?.()},onAfterRender(e,t,r){if(!t.meshes||t.meshes.length===0)return;let i=Math.max(1,t.canvas?.width||300),n=Math.max(1,t.canvas?.height||150),a=[];for(let h of t.meshes){if(h.visible===!1)continue;let p=ny(t,h);p&&a.push({mesh:h,trait:p})}let s=a.length>0?$m(e):null;if(s){let h=s,p=rt(),g=rt(),x=new Float32Array(9),v=(typeof performance<"u"?performance.now():Date.now())*.001,y=typeof e.getParameter=="function"?e.getParameter(2978):null,A=Math.max(1,y?.[2]||i),b=Math.max(1,y?.[3]||n);e.useProgram(h.outlineProg),h.uOutlineViewportSize&&e.uniform2f(h.uOutlineViewportSize,A,b),h.uOutlineVP&&e.uniformMatrix4fv(h.uOutlineVP,!1,r),e.enable(e.CULL_FACE),e.cullFace(e.FRONT),e.enable(2929),e.depthFunc(515),e.depthMask(!1);for(let{mesh:w,trait:S}of a){let[E,N,C]=Ru(S.color),_=S.pulse?.8+.25*Math.sin(v*4):1;h.uOutlineColor&&e.uniform4f(h.uOutlineColor,E,N,C,1),h.uOutlineThickness&&e.uniform1f(h.uOutlineThickness,S.thickness*_),w.worldSpace===!0?p.set(w.transform):at(p,t.modelRootMatrix,w.transform);let P=w.instanceMatrices;for(let R of w.primitives)if(!(R.pluginData?.skinning?.hasSkin||R.pluginData?.morph?.hasMorph))if(e.bindVertexArray(R.vao),P&&P.length>=16){let $=P.length>>4,F=rt();for(let V=0;V<$;V++)at(F,p,P.subarray(V*16,V*16+16)),at(g,r,F),Bt(x,F),e.uniformMatrix4fv(h.uOutlineMVP,!1,g),e.uniformMatrix3fv(h.uOutlineNormalMatrix,!1,x),R.indices?e.drawElements(4,R.indexCount,R.indexType,0):e.drawArrays(4,0,R.indexCount)}else at(g,r,p),Bt(x,p),e.uniformMatrix4fv(h.uOutlineMVP,!1,g),e.uniformMatrix3fv(h.uOutlineNormalMatrix,!1,x),R.indices?e.drawElements(4,R.indexCount,R.indexType,0):e.drawArrays(4,0,R.indexCount)}e.bindVertexArray(null),e.cullFace(e.BACK),e.disable(e.CULL_FACE),e.depthFunc(e.LESS),e.depthMask(!0)}if(t.xrSessionActive||t.stereoSBS)return;let o=Qb(t);if(!o||o.strength<=0)return;let l=$m(e);if(!l||!Jb(e,l,i,n)||!l.fsVao)return;e.activeTexture(33984),e.bindTexture(3553,l.sceneTex),e.copyTexSubImage2D(3553,0,0,0,0,0,i,n),e.disable(2929),e.depthMask(!1),e.disable(3042),e.useProgram(l.downProg),e.uniform1i(l.uDownSourceTex,0),e.bindVertexArray(l.fsVao);let c=l.sceneTex,f=i,m=n;for(let h=0;h<oc;h++){let p=l.mipWidth[h],g=l.mipHeight[h];e.bindFramebuffer(36160,l.bloomFbo[h]),e.viewport(0,0,p,g),e.bindTexture(3553,c),e.uniform2f(l.uDownTexelSize,1/f,1/m),e.uniform1f(l.uDownThreshold,h===0?o.threshold:0),e.drawArrays(4,0,3),c=l.bloomTex[h],f=p,m=g}e.enable(3042),typeof e.blendFuncSeparate=="function"?e.blendFuncSeparate(e.ONE,e.ONE,e.ONE,771):e.blendFunc(e.ONE,e.ONE),e.useProgram(l.upProg),e.uniform1i(l.uUpBloomTex,0),e.uniform1f(l.uUpRadius,o.radius);for(let h=oc-1;h>=1;h--){let p=h-1;e.bindFramebuffer(36160,l.bloomFbo[p]),e.viewport(0,0,l.mipWidth[p],l.mipHeight[p]),e.bindTexture(3553,l.bloomTex[h]),e.uniform2f(l.uUpTexelSize,1/l.mipWidth[h],1/l.mipHeight[h]),e.uniform1f(l.uUpStrength,.85),e.drawArrays(4,0,3)}e.bindFramebuffer(36160,null),e.viewport(0,0,i,n),e.bindTexture(3553,l.bloomTex[0]),e.uniform2f(l.uUpTexelSize,1/l.mipWidth[0],1/l.mipHeight[0]),e.uniform1f(l.uUpStrength,o.strength),e.drawArrays(4,0,3),e.bindVertexArray(null),e.blendFunc(770,771),e.disable(3042),e.depthMask(!0),e.enable(2929)},onDestroy(e){let t=Vi.get(e);if(t){e.deleteProgram(t.outlineProg),e.deleteProgram(t.downProg),e.deleteProgram(t.upProg),t.fsVao&&e.deleteVertexArray(t.fsVao),t.sceneTex&&e.deleteTexture(t.sceneTex);for(let r of t.bloomTex)r&&e.deleteTexture(r);for(let r of t.bloomFbo)r&&e.deleteFramebuffer(r);Vi.delete(e)}}},Ao=4,Cu=9,ry=32*1024*1024,ac=rt(),Hm=new Int32Array([-1,-1]);function Pu(e,t,r,i){let n=Number(e);return Number.isFinite(n)?Math.max(t,Math.min(r,n)):i}var Wm=new WeakMap,hr=new WeakMap,zi=new WeakMap,Mo=rt(),ic=rt(),pr=rt(),wo=rt(),Ym=new Float32Array(1),oy=new Uint32Array(Ym.buffer);function Nu(e){if(typeof e!="string")return"auto";let t=e.trim().toLowerCase();return t==="pcf"||t==="off"?t:"auto"}function iy(e){let t=Wm.get(e);if(t)return t;let r=1/0,i=1/0,n=1/0,a=-1/0,s=-1/0,o=-1/0;for(let c=0;c+2<e.length;c+=3){let f=e[c],m=e[c+1],h=e[c+2];f<r&&(r=f),f>a&&(a=f),m<i&&(i=m),m>s&&(s=m),h<n&&(n=h),h>o&&(o=h)}let l=Number.isFinite(r)?[r,i,n,a,s,o]:[-.5,-.5,-.5,.5,.5,.5];return Wm.set(e,l),l}function So(e,t,r,i){let n=(e[0]+e[3])*.5,a=(e[1]+e[4])*.5,s=(e[2]+e[5])*.5,o=Math.max(0,(e[3]-e[0])*.5),l=Math.max(0,(e[4]-e[1])*.5),c=Math.max(0,(e[5]-e[2])*.5),f=t[0]*n+t[4]*a+t[8]*s+t[12],m=t[1]*n+t[5]*a+t[9]*s+t[13],h=t[2]*n+t[6]*a+t[10]*s+t[14],p=Math.abs(t[0])*o+Math.abs(t[4])*l+Math.abs(t[8])*c,g=Math.abs(t[1])*o+Math.abs(t[5])*l+Math.abs(t[9])*c,x=Math.abs(t[2])*o+Math.abs(t[6])*l+Math.abs(t[10])*c;f-p<r[0]&&(r[0]=f-p),m-g<r[1]&&(r[1]=m-g),h-x<r[2]&&(r[2]=h-x),f+p>i[0]&&(i[0]=f+p),m+g>i[1]&&(i[1]=m+g),h+x>i[2]&&(i[2]=h+x)}function Du(e){let t=e||{},r=t.modelRootMatrix??ac,i=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];for(let m of t.meshes??[]){if(!Fu(m))continue;m.worldSpace===!0?pr.set(m.transform):at(pr,r,m.transform);let h=m.instanceMatrices;for(let p of m.primitives??[]){if(!p.positions||p.positions.length<3)continue;let g=iy(p.positions);if(h&&h.length>=16){let x=h.length>>4,v=x>64?Math.ceil(x/64):1;for(let y=0;y<x;y+=v)at(wo,pr,h.subarray(y*16,y*16+16)),So(g,wo,i,n);if(v>1){let y=x-1;at(wo,pr,h.subarray(y*16,y*16+16)),So(g,wo,i,n)}}else So(g,pr,i,n)}}if(!Number.isFinite(i[0])){let m=t.bounds;m&&Array.isArray(m.min)&&Array.isArray(m.max)&&So([m.min[0],m.min[1],m.min[2],m.max[0],m.max[1],m.max[2]],r,i,n)}Number.isFinite(i[0])||(i[0]=i[1]=i[2]=-1,n[0]=n[1]=n[2]=1);let a=(i[0]+n[0])*.5,s=(i[1]+n[1])*.5,o=(i[2]+n[2])*.5,l=Math.max(.03,(n[0]-i[0])*.5),c=Math.max(.03,(n[1]-i[1])*.5),f=Math.max(.03,(n[2]-i[2])*.5);return{center:[a,s,o],radius:Math.max(.05,Math.hypot(l,c,f)),min:[a-l,s-c,o-f],max:[a+l,s+c,o+f]}}function Uu(e,t,r){let i=Number(t[0])||0,n=Number(t[1])||0,a=Number(t[2])||0,s=Math.hypot(i,n,a);s>1e-6?(i/=s,n/=s,a/=s):(i=.37139067,n=.74278135,a=.59422508);let o=Math.max(.05,r.radius),[l,c,f]=r.center,m=o*2.2,h=[l+i*m,c+n*m,f+a*m],p=Math.abs(n)>.99?[0,0,1]:[0,1,0];xr(Mo,h,r.center,p);let g=[1/0,1/0,1/0],x=[-1/0,-1/0,-1/0];So([...r.min,...r.max],Mo,g,x);let v=Math.max(.02,o*.05),y=Math.max(.01,-x[2]-v),A=Math.max(y+.1,-g[2]+v);return yd(ic,g[0]-v,Math.max(g[0]+.05,x[0])+v,g[1]-v,Math.max(g[1]+.05,x[1])+v,y,A),at(e,ic,Mo)}function sc(e,t,r,i,n,a){let s=Number(t[0])||0,o=Number(t[1])||0,l=Number(t[2])||0,c=Number(r[0])||0,f=Number(r[1])||0,m=Number(r[2])||0,h=Math.hypot(c,f,m);h<=1e-6&&(c=a.center[0]-s,f=a.center[1]-o,m=a.center[2]-l,h=Math.hypot(c,f,m)),h>1e-6?(c/=h,f/=h,m/=h):(c=0,f=-1,m=0);let p=Math.abs(f)>.99?[0,0,1]:[0,1,0];xr(Mo,[s,o,l],[s+c,o+f,l+m],p);let g=[1/0,1/0,1/0],x=[-1/0,-1/0,-1/0];So([...a.min,...a.max],Mo,g,x);let v=-x[2],y=-g[2],A=Math.max(.05,a.radius),b=Math.hypot(a.center[0]-s,a.center[1]-o,a.center[2]-l),w=Math.max(.5,y+A*.25,b+A),S=n&&n>0?Math.max(.25,Math.min(n,w)):w,E=Math.max(.02,S/1500),N=Math.min(S*.4,Math.max(E,Number.isFinite(v)?v-A*.05:E)),C=Math.max(.08,Math.min(2.35,i*2*1.04));return Oo(ic,C,1,N,Math.max(N+.1,S)),at(e,ic,Mo)}function Bu(e){let t=e||{};for(let b of t.meshes??[])if(b.name==="__xr_section_gizmo__"&&b.visible!==!1&&b.worldMatrix&&b.worldMatrix.length>=16){let w=b.worldMatrix,S=Math.hypot(w[8],w[9],w[10])||1,E=w[8]/S,N=w[9]/S,C=w[10]/S;return{enabled:!0,normal:[E,N,C],constant:E*w[12]+N*w[13]+C*w[14]}}let r=(t.container?.getAttribute?.("section-plane")??"").trim().toLowerCase();if(!r||r==="none"||r==="false")return null;let i=[1,0,0],n=0;if(r==="interactive")n=t.bounds?.center[0]??0;else{let b=/^([+-]?[xyz])\s*:\s*([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)$/.exec(r);if(!b)return null;let w=b[1].startsWith("-")?-1:1,S=b[1].replace(/^[+-]/,""),E=Math.max(-1e3,Math.min(1e3,Number(b[2])||0));i=S==="x"?[w,0,0]:S==="y"?[0,w,0]:[0,0,w],n=E*w}let a=t.modelRootMatrix??ac,s=a[0]*i[0]+a[4]*i[1]+a[8]*i[2],o=a[1]*i[0]+a[5]*i[1]+a[9]*i[2],l=a[2]*i[0]+a[6]*i[1]+a[10]*i[2],c=Math.hypot(s,o,l)||1,f=s/c,m=o/c,h=l/c,p=i[0]*n,g=i[1]*n,x=i[2]*n,v=a[0]*p+a[4]*g+a[8]*x+a[12],y=a[1]*p+a[5]*g+a[9]*x+a[13],A=a[2]*p+a[6]*g+a[10]*x+a[14];return{enabled:!0,normal:[f,m,h],constant:f*v+m*y+h*A}}function Fu(e){if(e.visible===!1||e.isPluginMesh||e.name==="__contact_shadow__"||e.name==="__xr_reticle__"||e.name==="__xr_section_gizmo__")return!1;let t=e.extras?.xr??e.userData?.xr;return!(t?.splatUrl||t?.splat)}function Gr(e,t){if(!Fu(e))return!1;let r=e.castShadow??e.extras?.shadow?.cast;return r===!1?!1:t?!0:r===!0}function $i(e,t){if(!e||typeof e!="object")return!1;let r=e;if(!Fu(r))return!1;let i=r.receiveShadow??r.extras?.shadow?.receive;return i!==void 0?!!i:t}function Iu(e){return!(e.isTransmissive||e.alphaMode==="BLEND"||(e.baseColor?.[3]??1)<.98)}function fr(e,t){return Math.imul((e^t>>>0)>>>0,16777619)>>>0}function mr(e,t){return Ym[0]=t||0,fr(e,oy[0])}function Oi(e,t,r=64){let i=t.length;if(e=fr(e,i),i<=r)for(let n=0;n<i;n++)e=mr(e,t[n]);else{let n=Math.max(1,Math.floor(i/r));for(let a=0;a<i;a+=n)e=mr(e,t[a]);e=mr(e,t[i-1])}return e}function Gi(e){let t=e||{},r=t.shadowMaps??t.container?.getAttribute?.("shadow-maps")??"auto",i=Nu(r),n=[-1,-1],a=[-1,-1],s=($=!1)=>({mode:i,mapSize:0,slices:[],dirSlots:n,ptSlots:a,promoteAllCasters:$,promoteAllReceivers:$,digest:0,sectionPlane:null});if(i==="off")return s();let o=[],l=null,c=null,f=!1,m=0,h=0;for(let $ of t.lights??[])$.type==="hemisphere"?f=!0:$.type==="directional"&&m<2?(l||(l=$),$.shadow?.cast&&o.length<Ao&&o.push({kind:"directional",subIdx:m,light:$}),m++):($.type==="spot"||$.type==="point")&&h<2&&(c||(c={kind:$.type,light:$}),$.shadow?.cast&&o.length<Ao&&o.push({kind:$.type,subIdx:h,light:$}),h++);if(i==="pcf"&&o.length===0&&(l?o.push({kind:"directional",subIdx:0,light:l}):f?c&&o.push({kind:c.kind,subIdx:0,light:c.light}):o.push({kind:"directional",subIdx:0,light:{type:"directional",direction:[.5,1,.8]}})),o.length===0)return s();let p=t.meshes??[],g=!1;for(let $ of p)if($.castShadow!==void 0||$.receiveShadow!==void 0||$.extras?.shadow!==void 0){g=!0;break}let x=i==="pcf"||!g,v=x,y=!1;for(let $ of p)if(Gr($,x)){for(let F of $.primitives??[])if(Iu(F)&&F.indexCount>0){y=!0;break}if(y)break}if(!y)return s(x);let A=1024;for(let $ of o){let F=$.light.shadow?.mapSize;typeof F=="number"&&Number.isFinite(F)&&(A=Math.max(A,Math.round(F)))}let b=Math.max(256,Math.min(2048,A)),w=o.length;for(;b>256&&b*b*w*4>ry;)b=Math.max(256,b>>1);let S=Du(t),E=S.radius*2.2/b,N=[];for(let $=0;$<o.length;$++){let F=o[$],V=F.light,Y=V.shadow,J=rt(),re;if(F.kind==="directional"){n[F.subIdx]=$;let G=V.direction??[.5,1,.8],q=Math.hypot(G[0]??.5,G[1]??1,G[2]??.8)||1;re=[-(G[0]??.5)/q,-(G[1]??1)/q,-(G[2]??.8)/q],Uu(J,G,S)}else{a[F.subIdx]=$;let G=V.position??[0,2,0];if(F.kind==="spot"){let q=V.direction??[0,-1,0],H=Math.hypot(q[0]??0,q[1]??-1,q[2]??0)||1;re=[(q[0]??0)/H,(q[1]??-1)/H,(q[2]??0)/H];let te=Math.max(.02,Math.min(Math.PI/2,V.outerConeAngle??Math.PI/3));sc(J,G,re,te,V.range,S)}else{let q=S.center[0]-(G[0]??0),H=S.center[1]-(G[1]??0),te=S.center[2]-(G[2]??0),Z=Math.hypot(q,H,te);re=Z>1e-6?[q/Z,H/Z,te/Z]:[0,-1,0],sc(J,G,re,Math.PI/3,V.range,S)}}let Q=Pu(Y?.bias,-.05,.05,-5e-4),ee=Pu(Y?.normalBias,0,.5,.015),k=Pu(Y?.radius,0,16,1.5);N.push({slot:$,viewProj:J,rayDir:re,depthBias:Q,normalBiasWorld:ee/.015*1.75*E,uvRadius:k*1.35/b})}let C=Bu(t),_=2166136261;_=fr(_,i==="pcf"?2:1),_=fr(_,b),_=fr(_,N.length);for(let $ of N)_=Oi(_,$.viewProj,16),_=mr(_,$.depthBias),_=mr(_,$.normalBiasWorld);C?.enabled?(_=fr(_,1),_=mr(_,C.normal[0]),_=mr(_,C.normal[1]),_=mr(_,C.normal[2]),_=mr(_,C.constant)):_=fr(_,0);let P=t.modelRootMatrix??ac;_=Oi(_,P,16);let R=0;for(let $ of p){if(!Gr($,x)){R++;continue}_=fr(_,R++),_=Oi(_,$.transform,16),$.instanceMatrices&&(_=Oi(_,$.instanceMatrices,64));for(let F of $.primitives??[])Iu(F)&&(_=fr(_,F.indexCount),F.translations&&(_=Oi(_,F.translations,48)))}return _===0&&(_=1),{mode:i,mapSize:b,slices:N,dirSlots:n,ptSlots:a,promoteAllCasters:x,promoteAllReceivers:v,digest:_,sectionPlane:C}}function Km(e){let t=hr.get(e);return t?{renderedPasses:t.renderedPasses,cacheHits:t.cacheHits,activeLights:t.activeLights,mapSize:t.allocSize}:{renderedPasses:0,cacheHits:0,activeLights:0,mapSize:0}}var sy=`#version 300 es
|
|
550
|
+
layout(location=0) in vec3 aPos;
|
|
551
|
+
layout(location=1) in vec3 aNormal;
|
|
552
|
+
layout(location=3) in vec3 aOff;
|
|
553
|
+
layout(location=8) in vec4 aInst0;
|
|
554
|
+
layout(location=9) in vec4 aInst1;
|
|
555
|
+
layout(location=10) in vec4 aInst2;
|
|
556
|
+
layout(location=11) in vec4 aInst3;
|
|
557
|
+
uniform mat4 uLightVP,uModel;
|
|
558
|
+
uniform vec4 uBiasRay;
|
|
559
|
+
uniform int uInstanced;
|
|
560
|
+
out vec3 vWorldPos;
|
|
561
|
+
void main(){
|
|
562
|
+
mat4 m=uInstanced==1?uModel*mat4(aInst0,aInst1,aInst2,aInst3):uModel;
|
|
563
|
+
vec4 wp=m*vec4(aPos+aOff,1.0);
|
|
564
|
+
vec3 wn=mat3(m)*aNormal;
|
|
565
|
+
float nl=length(wn);
|
|
566
|
+
if(nl>1e-5&&uBiasRay.w>0.0){
|
|
567
|
+
wn/=nl;
|
|
568
|
+
wp.xyz+=wn*(uBiasRay.w*max(1.0-abs(dot(wn,uBiasRay.xyz)),0.15));
|
|
569
|
+
}
|
|
570
|
+
vWorldPos=wp.xyz;
|
|
571
|
+
gl_Position=uLightVP*wp;
|
|
572
|
+
}`,ay=`#version 300 es
|
|
573
|
+
precision highp float;
|
|
574
|
+
in vec3 vWorldPos;
|
|
575
|
+
uniform vec4 uSecPlane;
|
|
576
|
+
uniform int uSecOn;
|
|
577
|
+
void main(){
|
|
578
|
+
if(uSecOn==1&&dot(vWorldPos,uSecPlane.xyz)>uSecPlane.w)discard;
|
|
579
|
+
}`,cy=`
|
|
580
|
+
uniform highp sampler2DArrayShadow uShadowMap;
|
|
581
|
+
uniform mat4 uShadowVP[4];
|
|
582
|
+
uniform vec4 uShadowParams[4];
|
|
583
|
+
uniform int uDirShdSlot[2],uPtShdSlot[2],uReceiveShadow;
|
|
584
|
+
const vec2 _VD[8]=vec2[8](
|
|
585
|
+
vec2(0.1768,0.0),vec2(-0.2265,0.2078),vec2(0.0355,-0.4150),vec2(0.3204,0.3888),
|
|
586
|
+
vec2(-0.5562,-0.1455),vec2(0.4916,-0.3806),vec2(-0.1419,0.6596),vec2(-0.5177,-0.5150));
|
|
587
|
+
float shdEval(int s,vec3 wp,vec3 N,vec3 L){
|
|
588
|
+
if(s<0||uReceiveShadow==0)return 1.0;
|
|
589
|
+
float nl=dot(N,L);
|
|
590
|
+
if(nl<=0.0)return 0.0;
|
|
591
|
+
mat4 vp=s==0?uShadowVP[0]:s==1?uShadowVP[1]:s==2?uShadowVP[2]:uShadowVP[3];
|
|
592
|
+
vec4 p=s==0?uShadowParams[0]:s==1?uShadowParams[1]:s==2?uShadowParams[2]:uShadowParams[3];
|
|
593
|
+
vec4 sc=vp*vec4(wp+N*(p.y*(1.0-nl)),1.0);
|
|
594
|
+
if(sc.w<=1e-6)return 1.0;
|
|
595
|
+
vec3 u=sc.xyz/sc.w*0.5+0.5;
|
|
596
|
+
if(u.x<=0.002||u.x>=0.998||u.y<=0.002||u.y>=0.998||u.z>1.0||u.z<0.0)return 1.0;
|
|
597
|
+
float rz=clamp(u.z+p.x,0.0,1.0);
|
|
598
|
+
if(p.z<=1e-6)return texture(uShadowMap,vec4(u.xy,float(s),rz));
|
|
599
|
+
float a=fract(52.9829189*fract(dot(gl_FragCoord.xy,vec2(0.06711056,0.00583715))))*6.2831853;
|
|
600
|
+
float ca=cos(a),sa=sin(a),sum=0.0;
|
|
601
|
+
mat2 rot=mat2(ca,sa,-sa,ca);
|
|
602
|
+
for(int k=0;k<8;k++)sum+=texture(uShadowMap,vec4(u.xy+rot*_VD[k]*p.z,float(s),rz));
|
|
603
|
+
return sum*0.125;
|
|
604
|
+
}`,ly=["uShadowMap","uShadowVP","uShadowParams","uDirShdSlot","uPtShdSlot","uReceiveShadow"];function uy(e){let t=hr.get(e);return t||(t={texArray:null,fbo:null,allocSize:0,allocLayers:0,lastDigest:0,renderedPasses:0,cacheHits:0,activeLights:0,vpFlat:new Float32Array(64),paramsFlat:new Float32Array(16),dirSlots:new Int32Array([-1,-1]),ptSlots:new Int32Array([-1,-1]),promoteAllReceivers:!1},hr.set(e,t)),t}function Jm(e,t,r){let i=e.createTexture?.();if(!i)return null;let n=35866;if(e.bindTexture(n,i),typeof e.texStorage3D=="function")e.texStorage3D(n,1,33190,t,t,r);else if(typeof e.texImage3D=="function")e.texImage3D(n,0,33190,t,t,r,0,6402,5125,null);else return e.deleteTexture?.(i),null;return e.texParameteri(n,10241,9729),e.texParameteri(n,10240,9729),e.texParameteri(n,10242,33071),e.texParameteri(n,10243,33071),e.texParameteri(n,34892,34894),e.texParameteri(n,34893,515),i}function Qm(e){let t=zi.get(e);if(t&&(t.prog===null||e.isProgram?.(t.prog)!==!1))return t;let r=null,i=e.createShader?.(35633),n=e.createShader?.(35632);if(i&&n){e.shaderSource(i,sy),e.compileShader(i),e.shaderSource(n,ay),e.compileShader(n);let a=e.createProgram();a&&(e.attachShader(a,i),e.attachShader(a,n),e.linkProgram(a),e.detachShader?.(a,i),e.detachShader?.(a,n),e.getProgramParameter(a,35714)!==!1?r=a:e.deleteProgram(a)),e.deleteShader(i),e.deleteShader(n)}return t={prog:r,uLightVP:r?e.getUniformLocation(r,"uLightVP"):null,uModel:r?e.getUniformLocation(r,"uModel"):null,uBiasRay:r?e.getUniformLocation(r,"uBiasRay"):null,uInstanced:r?e.getUniformLocation(r,"uInstanced"):null,uSecPlane:r?e.getUniformLocation(r,"uSecPlane"):null,uSecOn:r?e.getUniformLocation(r,"uSecOn"):null,dummyArrayTex:Jm(e,1,1)},zi.set(e,t),t}var Xm={uniformsGLSL:cy,dirGLSL:"*shdEval(uDirShdSlot[i],vWorldPos,N,normalize(uDirLightDir[i]))",ptGLSL:"*shdEval(uPtShdSlot[i],vWorldPos,N,L)",uniformNames:ly,bind(e,t,r,i){let n=t.uShadowMap;if(n===void 0)return;let a=r&&typeof r=="object"?hr.get(r):void 0,s=Qm(e),o=!!(a&&a.activeLights>0&&a.texArray),l=o?a.texArray:s.dummyArrayTex;l&&(e.activeTexture(33993),e.bindTexture(35866,l)),n&&e.uniform1i(n,Cu);let c=t.uDirShdSlot,f=t.uPtShdSlot,m=t.uReceiveShadow;if(!o){c&&e.uniform1iv?.(c,Hm),f&&e.uniform1iv?.(f,Hm),m&&e.uniform1i?.(m,0);return}c&&e.uniform1iv?.(c,a.dirSlots),f&&e.uniform1iv?.(f,a.ptSlots);let h=t.uShadowVP;h&&e.uniformMatrix4fv?.(h,!1,a.vpFlat);let p=t.uShadowParams;p&&e.uniform4fv?.(p,a.paramsFlat),m&&e.uniform1i?.(m,$i(i,a.promoteAllReceivers)?1:0)}};function qm(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}var Vu={name:"shadow-maps",onRegister(){He().shadowMapShader=Xm},onLoadModel(e){if(e&&typeof e=="object"){let t=hr.get(e);t&&(t.lastDigest=0)}},onClearScene(e){if(e&&typeof e=="object"){let t=hr.get(e);t&&(t.lastDigest=0,t.activeLights=0)}},onContextRestored(e,t){if(zi.delete(e),t&&typeof t=="object"){let r=hr.get(t);r&&(r.texArray=null,r.fbo=null,r.allocSize=0,r.allocLayers=0,r.lastDigest=0,r.activeLights=0)}},onDestroy(e,t){if(t&&typeof t=="object"){let r=hr.get(t);r&&(r.texArray&&e.deleteTexture?.(r.texArray),r.fbo&&e.deleteFramebuffer?.(r.fbo),hr.delete(t))}else if(e){let r=zi.get(e);r&&(r.prog&&e.deleteProgram?.(r.prog),r.dummyArrayTex&&e.deleteTexture?.(r.dummyArrayTex),zi.delete(e))}},onBeforeDrawScene(e,t){if(!e||typeof e!="object")return;let r=e,i=He();if(i.shadowMapShader||(i.shadowMapShader=Xm),r.uRender&&!("uShadowMap"in r.uRender)&&r.recompileRenderProgram?.(),i.gpuSceneAccelerator?.willRenderScene?.(e))return;let n=uy(e),a=Gi(r);if(n.promoteAllReceivers=a.promoteAllReceivers,n.dirSlots[0]=a.dirSlots[0],n.dirSlots[1]=a.dirSlots[1],n.ptSlots[0]=a.ptSlots[0],n.ptSlots[1]=a.ptSlots[1],a.slices.length===0||typeof t.framebufferTextureLayer!="function"){n.activeLights=0;return}let s=Qm(t);if(!s.prog){n.activeLights=0;return}let o=a.slices.length;if(!n.texArray||!n.fbo||n.allocSize!==a.mapSize||n.allocLayers<o){n.texArray&&t.deleteTexture?.(n.texArray);let p=Math.max(n.allocLayers,o);if(n.texArray=Jm(t,a.mapSize,p),n.fbo||(n.fbo=t.createFramebuffer?.()??null),!n.texArray||!n.fbo){n.activeLights=0;return}n.allocSize=a.mapSize,n.allocLayers=p,n.lastDigest=0}n.activeLights=o,n.vpFlat.fill(0),n.paramsFlat.fill(0);for(let p of a.slices){n.vpFlat.set(p.viewProj,p.slot*16);let g=p.slot*4;n.paramsFlat[g]=p.depthBias,n.paramsFlat[g+1]=p.normalBiasWorld*.5,n.paramsFlat[g+2]=p.uvRadius}if(n.lastDigest===a.digest){n.cacheHits++;return}n.lastDigest=a.digest;let l=t.getParameter?.(36006)??null,c=t.getParameter?.(2978),f=c&&c.length>=4?[c[0],c[1],c[2],c[3]]:[0,0,Math.max(1,r.canvas?.width||1),Math.max(1,r.canvas?.height||1)],m=r.modelRootMatrix??ac,h=r.meshes??[];t.bindFramebuffer(36160,n.fbo),t.drawBuffers?.([0]),t.readBuffer?.(0),t.viewport(0,0,a.mapSize,a.mapSize),t.colorMask?.(!1,!1,!1,!1),t.depthMask?.(!0),t.enable(2929),t.enable(32823),t.polygonOffset?.(1.5,4),t.useProgram(s.prog),s.uSecOn&&(a.sectionPlane?.enabled?(t.uniform1i(s.uSecOn,1),s.uSecPlane&&t.uniform4f(s.uSecPlane,a.sectionPlane.normal[0],a.sectionPlane.normal[1],a.sectionPlane.normal[2],a.sectionPlane.constant)):t.uniform1i(s.uSecOn,0));for(let p of a.slices){t.framebufferTextureLayer(36160,36096,n.texArray,0,p.slot),t.clear(256),s.uLightVP&&t.uniformMatrix4fv(s.uLightVP,!1,p.viewProj),s.uBiasRay&&t.uniform4f(s.uBiasRay,p.rayDir[0],p.rayDir[1],p.rayDir[2],p.normalBiasWorld);for(let g of h){if(!Gr(g,a.promoteAllCasters))continue;g.worldSpace===!0?pr.set(g.transform):at(pr,m,g.transform);let x=g.instanceMatrices;for(let v of g.primitives??[])if(!(!v.vao||v.indexCount<=0||!Iu(v)))if(t.bindVertexArray(v.vao),t.vertexAttrib3f?.(3,0,0,0),s.uInstanced&&t.uniform1i(s.uInstanced,0),s.uModel&&t.uniformMatrix4fv(s.uModel,!1,pr),v.instanceCount!==void 0)t.drawElementsInstanced(4,v.indexCount,v.indexType,0,v.instanceCount);else if(x&&x.length>=16&&v.instanced&&s.uInstanced){let y=x.length>>4;t.uniform1i(s.uInstanced,1),v.indices?t.drawElementsInstanced(4,v.indexCount,v.indexType,0,y):t.drawArraysInstanced(4,0,v.indexCount,y),t.uniform1i(s.uInstanced,0)}else if(x&&x.length>=16){let y=x.length>>4;for(let A=0;A<y;A++)at(wo,pr,x.subarray(A*16,A*16+16)),s.uModel&&t.uniformMatrix4fv(s.uModel,!1,wo),qm(t,v)}else qm(t,v)}n.renderedPasses++}t.bindVertexArray(null),t.disable(32823),t.colorMask?.(!0,!0,!0,!0),t.bindFramebuffer(36160,l),t.viewport(f[0],f[1],f[2],f[3])}};function Ou(e){let t=e?.extensions?.KHR_materials_variants?.variants;if(!Array.isArray(t))return[];let r=[];for(let i=0;i<t.length&&r.length<256;i++){let n=t[i]?.name;r.push(typeof n=="string"&&n.length>0?n:`Variant_${i}`)}return r}function Zm(e){let t=e?.extensions?.KHR_materials_variants?.mappings;if(!Array.isArray(t))return[];let r=[];for(let i of t){if(!i||typeof i!="object")continue;let n=i,a=Number(n.material);if(!Number.isInteger(a)||a<0)continue;let s=[];if(Array.isArray(n.variants))for(let o of n.variants){let l=Number(o);Number.isInteger(l)&&l>=0&&s.push(l)}s.length>0&&r.push({material:a,variants:s})}return r}function eh(e,t,r,i=0){let n=e;if(n&&typeof n.selectVariant=="function"&&!Array.isArray(t))return n.selectVariant(typeof t=="string"?t:null);let a=e,s=Array.isArray(t)?t:[],o=r??null;if(!o)return i;let l=Ou(a).indexOf(o);if(l<0)return i;for(let c of s)if(c.variants.includes(l))return c.material;return i}var zu={name:"variants",onLoadModel(e,t){let r=e.getVariantName?.();r&&e.selectVariant(r)}},th=new WeakMap,$u={name:"webxr-suite",onConfigureXRSessionInit(e,t){let r=new Set(t.optionalFeatures||[]);r.add("hit-test"),r.add("light-estimation");let i=e?.querySelector?.('[slot="ar-overlay"]')||null;i&&(r.add("dom-overlay"),t.domOverlay={root:i},i.addEventListener?.("beforexrselect",n=>{n.preventDefault()})),t.optionalFeatures=Array.from(r)},onXRFrame(e,t,r,i){if(!e||!t||!r||!i)return;let n=th.get(t);if(n||(n={lightProbe:null},th.set(t,n),typeof t.requestLightProbe=="function"&&t.requestLightProbe().then(a=>{n&&a&&(n.lightProbe=a)}).catch(()=>{})),n.lightProbe&&typeof r.getLightEstimate=="function"){let a=r.getLightEstimate(n.lightProbe);if(a){let s=a.primaryLightDirection,o=a.primaryLightIntensity;if(s&&o&&Array.isArray(e.lights)){let l=e.lights.find(f=>f.type==="directional");l||(l={type:"directional",direction:[.5,1,.8],color:[1,1,1],intensity:1},e.lights.push(l)),l.direction=[s.x,s.y,s.z];let c=Math.max(o.x,o.y,o.z,.001);l.color=[o.x/c,o.y/c,o.z/c],l.intensity=c}a.sphericalHarmonicsCoefficients&&e.gl&&qa(e.gl,a.sphericalHarmonicsCoefficients)}}}};gt(Di),gt(Vu),gt(vu),gt(yu),gt(Tu),gt($u),gt(Au),gt(ku),gt(zu),gt(Lu),gt(Vc);var rh=272,dy=["x","y","z","w"],oh=[[2,"vec2<f32>"],[3,"vec3<f32>"],[4,"vec4<f32>"]];function To(e,t){return oh.map(([r,i])=>{let n=dy.slice(0,r).map(a=>t===2?`${e}1(a.${a},b.${a})`:`${e}1(a.${a},b.${a},c.${a})`).join(",");return t===2?`fn ${e}${r}(a:${i},b:${i})->${i}{return ${i}(${n});}`:`fn ${e}${r}(a:${i},b:${i},c:${i})->${i}{return ${i}(${n});}`})}function nh(e,t){let r=[];return e.div&&r.push("fn _tslDiv1(a:f32,b:f32)->f32{return a/select(b,select(1e-6,-1e-6,b<0.0),abs(b)<1e-6);}",...To("_tslDiv",2)),e.mod&&r.push("fn _tslMod1(a:f32,b:f32)->f32{let d=select(b,select(1e-6,-1e-6,b<0.0),abs(b)<1e-6);return a-d*floor(a/d);}",...To("_tslMod",2)),e.pow&&r.push("fn _tslPow1(a:f32,b:f32)->f32{let e=clamp(b,-64.0,64.0);if(abs(e)<1e-8){return 1.0;}if(a<=0.0){return 0.0;}return pow(max(a,1e-8),e);}",...To("_tslPow",2)),e.clamp&&r.push("fn _tslClamp1(a:f32,b:f32,c:f32)->f32{return clamp(a,min(b,c),max(b,c));}",...To("_tslClamp",3)),e.smooth&&r.push("fn _tslSmooth1(a:f32,b:f32,c:f32)->f32{let t=_tslClamp1(_tslDiv1(c-a,b-a),0.0,1.0);return t*t*(3.0-2.0*t);}",...To("_tslSmooth",3)),e.atan2&&r.push("fn _tslAtan1(a:f32,b:f32)->f32{return select(atan2(a,b),0.0,abs(a)<1e-8&&abs(b)<1e-8);}",...To("_tslAtan",2)),e.norm&&r.push("fn _tslNorm1(v:f32)->f32{return select(0.0,sign(v),abs(v)>1e-6);}",...oh.map(([i,n])=>`fn _tslNorm${i}(v:${n})->${n}{let l=length(v);return select(${n}(0.0),v/l,l>1e-6);}`)),(e.snoise2||e.snoise3||e.voronoi2)&&r.push("fn _tslM289(x:f32)->f32{return x-floor(x*(1.0/289.0))*289.0;}","fn _tslPerm(x:f32)->f32{return _tslM289((x*34.0+10.0)*x);}"),e.snoise2&&r.push("fn _tslSNoise2(v:vec2<f32>)->f32{let c0=0.21132487;let c1=0.3660254;let c2=-0.57735026;let c3=0.024390243;let s=(v.x+v.y)*c1;var ix=floor(v.x+s);var iy=floor(v.y+s);let t=(ix+iy)*c0;let x0=v.x-ix+t;let y0=v.y-iy+t;let i1x=select(0.0,1.0,x0>y0);let i1y=1.0-i1x;let x1=x0+c0-i1x;let y1=y0+c0-i1y;let x2=x0+c2;let y2=y0+c2;ix=_tslM289(ix);iy=_tslM289(iy);let p0=_tslPerm(_tslPerm(iy)+ix);let p1=_tslPerm(_tslPerm(iy+i1y)+ix+i1x);let p2=_tslPerm(_tslPerm(iy+1.0)+ix+1.0);var m=max(vec3<f32>(0.5)-vec3<f32>(x0*x0+y0*y0,x1*x1+y1*y1,x2*x2+y2*y2),vec3<f32>(0.0));m=m*m;m=m*m;let gx=2.0*fract(vec3<f32>(p0,p1,p2)*c3)-vec3<f32>(1.0);let hy=abs(gx)-vec3<f32>(0.5);let ox=gx-floor(gx+vec3<f32>(0.5));m*=vec3<f32>(1.7928429)-0.85373473*(ox*ox+hy*hy);return clamp(0.5+65.0*dot(m,ox*vec3<f32>(x0,x1,x2)+hy*vec3<f32>(y0,y1,y2)),0.0,1.0);}"),e.snoise3&&r.push("fn _tslSNoise3(v:vec3<f32>)->f32{let c0=0.16666667;let c1=0.33333334;let ns=0.14285715;let s=(v.x+v.y+v.z)*c1;var i0=floor(v.x+s);var i1=floor(v.y+s);var i2=floor(v.z+s);let t=(i0+i1+i2)*c0;let p0=v-vec3<f32>(i0,i1,i2)+vec3<f32>(t);let g=step(p0.yzx,p0.xyz);let l=vec3<f32>(1.0)-g.zxy;let a1=min(g,l);let a2=max(g,l);let p1=p0-a1+vec3<f32>(c0);let p2=p0-a2+vec3<f32>(c1);let p3=p0-vec3<f32>(0.5);i0=_tslM289(i0);i1=_tslM289(i1);i2=_tslM289(i2);let hs=array<f32,4>(_tslPerm(_tslPerm(_tslPerm(i2)+i1)+i0),_tslPerm(_tslPerm(_tslPerm(i2+a1.z)+i1+a1.y)+i0+a1.x),_tslPerm(_tslPerm(_tslPerm(i2+a2.z)+i1+a2.y)+i0+a2.x),_tslPerm(_tslPerm(_tslPerm(i2+1.0)+i1+1.0)+i0+1.0));let qs=array<vec3<f32>,4>(p0,p1,p2,p3);var sum=0.0;for(var k=0;k<4;k=k+1){let pk=hs[k];let j=pk-49.0*floor(pk*ns*ns);let x_=floor(j*ns);let y_=floor(j-7.0*x_);var gx=x_*(2.0/7.0)+(1.0/7.0)-1.0;var gy=y_*(2.0/7.0)+(1.0/7.0)-1.0;let gz=1.0-abs(gx)-abs(gy);let sz=select(0.0,1.0,gz<0.0);gx-=sz*select(-1.0,1.0,gx>=0.0);gy-=sz*select(-1.0,1.0,gy>=0.0);let inv=1.7928429-0.85373473*(gx*gx+gy*gy+gz*gz);let q=qs[k];var m=max(0.6-dot(q,q),0.0);m=m*m;m=m*m;sum+=m*inv*(gx*q.x+gy*q.y+gz*q.z);}return clamp(0.5+21.0*sum,0.0,1.0);}"),e.voronoi2&&r.push("fn _tslVoronoi2(u:vec2<f32>,jit:f32)->f32{let n=floor(u);let fr=u-n;let jt=clamp(jit,0.0,1.0);var md=8.0;for(var dy=-1;dy<=1;dy=dy+1){for(var dx=-1;dx<=1;dx=dx+1){let qx=_tslM289(n.x+f32(dx));let qy=_tslM289(n.y+f32(dy));let hx=fract(_tslPerm(_tslPerm(qx)+qy)*(1.0/41.0));let hy=fract(_tslPerm(_tslPerm(qy+7.0)+qx+13.0)*(1.0/41.0));md=min(md,length(vec2<f32>(f32(dx),f32(dy))+vec2<f32>(0.5)+(vec2<f32>(hx,hy)-vec2<f32>(0.5))*jt-fr));}}return clamp(md,0.0,1.0);}"),e.checker&&r.push("fn _tslChecker(p:vec2<f32>)->f32{return select(0.0,1.0,_tslMod1(floor(p.x)+floor(p.y),2.0)>=1.0);}"),e.fresnel&&r.push("fn _tslFresnel(pw:f32,nw:vec3<f32>,vd:vec3<f32>)->f32{return _tslPow1(1.0-clamp(dot(_tslNorm3(nw),_tslNorm3(vd)),0.0,1.0),max(pw,1e-3));}"),e.triplanar&&r.push("fn _tslTriplanar(p:vec3<f32>,sh:f32,nw:vec3<f32>)->f32{let w=_tslPow3(max(abs(_tslNorm3(nw)),vec3<f32>(1e-4)),vec3<f32>(clamp(sh,0.5,16.0)));return(w.x*_tslSNoise2(p.yz)+w.y*_tslSNoise2(p.xz)+w.z*_tslSNoise2(p.xy))/max(w.x+w.y+w.z,1e-6);}"),e.hueShift&&r.push("fn _tslHueShift(rgb:vec3<f32>,ang:f32)->vec3<f32>{let k=vec3<f32>(0.57735026);let c=cos(ang);let s=sin(ang);return rgb*c+cross(k,rgb)*s+k*dot(k,rgb)*(1.0-c);}"),e.bump&&t&&r.push("fn _tslBump(dhx:f32,dhy:f32,st:f32,nw:vec3<f32>,dx:vec3<f32>,dy:vec3<f32>)->vec3<f32>{let n=_tslNorm3(nw);let r1=cross(dy,n);let r2=cross(n,dx);let det=dot(dx,r1);if(abs(det)<1e-8){return n;}return _tslNorm3(abs(det)*n-st*select(1.0,-1.0,det<0.0)*(dhx*r1+dhy*r2));}"),r.join(`
|
|
605
|
+
`)}var fy={positionLocal:"_tslPL",positionWorld:"_tslPW",normalLocal:"_tslNL",normalWorld:"_tslNW",viewDirection:"_tslVD",uv:"_tslUV",vertexColor:"_tslVC",instanceIndex:"_tslII"};function Gu(e,t){let r=[],i=s=>s==="float"?"f32":`${s}<f32>`,n=(s,o)=>s==="float"?o:`${s}<f32>(${o})`,a=(s,o,l)=>o===l?s:`${l}<f32>(${s})`;for(let s=0;s<e.length;s++){if(!t[s])continue;let o=e[s],l=o.type,c=Wt(l),f=o.args[0]!==void 0?`_t${o.args[0]}`:"",m=o.args[1]!==void 0?`_t${o.args[1]}`:"",h=o.args[2]!==void 0?`_t${o.args[2]}`:"",p=o.args[0]!==void 0?e[o.args[0]].type:"float",g=o.args[1]!==void 0?e[o.args[1]].type:"float",x=o.args[2]!==void 0?e[o.args[2]].type:"float",v=n(l,"0.0");switch(o.op){case"const":{let y=(o.value??[0]).map(Un);v=l==="float"?y[0]:`${l}<f32>(${y.join(",")})`;break}case"builtin":v=o.builtin==="time"?`_tslMod1(tslU.timeAndPad.x,${Un(3600)})`:fy[o.builtin]??"0.0";break;case"uniform":{let y=`tslU.params[${o.uniformSlot??0}]`;v=c===4?y:`${y}.${"xyz".slice(0,c)}`;break}case"swizzle":v=p==="float"?n(l,f):`${f}.${o.mask}`;break;case"construct":v=l==="float"?f:`${l}<f32>(${o.args.map(y=>`_t${y}`).join(",")})`;break;case"neg":v=`(-${f})`;break;case"abs":case"sign":case"floor":case"ceil":case"fract":case"sin":case"cos":v=`${o.op}(${f})`;break;case"sqrt":v=`sqrt(max(${f},${n(l,"0.0")}))`;break;case"exp":v=`exp(clamp(${f},${n(l,"-80.0")},${n(l,"80.0")}))`;break;case"log":v=`log(max(${f},${n(l,"1.0e-8")}))`;break;case"normalize":v=`_tslNorm${c}(${f})`;break;case"add":case"sub":case"mul":{let y=o.op==="add"?"+":o.op==="sub"?"-":"*";v=`(${a(f,p,l)}${y}${a(m,g,l)})`;break}case"div":case"mod":case"pow":case"atan2":{v=`${o.op==="div"?"_tslDiv":o.op==="mod"?"_tslMod":o.op==="pow"?"_tslPow":"_tslAtan"}${c}(${a(f,p,l)},${a(m,g,l)})`;break}case"min":case"max":case"step":v=`${o.op}(${a(f,p,l)},${a(m,g,l)})`;break;case"clamp":v=`_tslClamp${c}(${a(f,p,l)},${a(m,g,l)},${a(h,x,l)})`;break;case"mix":v=`mix(${f},${m},${a(h,x,l)})`;break;case"smoothstep":v=`_tslSmooth${c}(${a(f,p,l)},${a(m,g,l)},${a(h,x,l)})`;break;case"dot":v=p==="float"?`(${f}*${m})`:`dot(${f},${m})`;break;case"length":v=p==="float"?`abs(${f})`:`length(${f})`;break;case"distance":v=p==="float"?`abs(${f}-${m})`:`distance(${f},${m})`;break;case"cross":case"reflect":v=`${o.op}(${f},${m})`;break;case"fresnel":v=`_tslFresnel(${f},_tslNW,_tslVD)`;break;case"simplexNoise2D":v=`_tslSNoise2(${f})`;break;case"simplexNoise3D":v=`_tslSNoise3(${f})`;break;case"voronoi2D":v=`_tslVoronoi2(${f},${m})`;break;case"checker":v=`_tslChecker(${f})`;break;case"triplanar":v=`_tslTriplanar(${f},${m},_tslNW)`;break;case"hueShift":v=`_tslHueShift(${f},${m})`;break;case"bumpFromHeight":v=`_tslBump(dpdx(${f}),-dpdy(${f}),${m},_tslNW,p1,p2)`;break;default:break}r.push(` let _t${s}:${i(l)}=${v};`)}return r.join(`
|
|
606
|
+
`)}function cc(e,t,r){let i=`struct TslUniformBlock{params:array<vec4<f32>,16>,timeAndPad:vec4<f32>,};
|
|
607
|
+
`,n=new Uint8Array(e.nodes.length);for(let c=0;c<e.nodes.length;c++)n[c]=e.fragmentReachable[c]||e.vertexReachable[c];let a=e.fragmentReachable.some(c=>c===1),s=nh(ti(e.nodes,n,e.usesTime),!0),o=t.replace("@group(1) @binding(4) var emTex: texture_2d<f32>;",`@group(1) @binding(4) var emTex: texture_2d<f32>;
|
|
608
|
+
${i}@group(2) @binding(0) var<uniform> tslU: TslUniformBlock;`).replace("@location(3) @interpolate(flat) instIdx: u32,",`@location(3) @interpolate(flat) instIdx: u32,
|
|
609
|
+
@location(4) localPos: vec3<f32>,
|
|
610
|
+
@location(5) localNorm: vec3<f32>,`).replace(`out.instIdx = instIdx;
|
|
611
|
+
return out;`,`out.instIdx = instIdx;
|
|
612
|
+
out.localPos = vec3<f32>(0.0);
|
|
613
|
+
out.localNorm = vec3<f32>(0.0, 1.0, 0.0);
|
|
614
|
+
return out;`);if(s&&(o=o.replace("@vertex",`${s}
|
|
615
|
+
@vertex`)),e.usesVertexPosition&&e.outputs.position!==void 0){let c=`fn _tslEvalPos(_tslPL:vec3<f32>,_tslNL:vec3<f32>,_tslUV:vec2<f32>,_tslVC:vec4<f32>,_tslII:f32,m:mat4x4<f32>)->vec3<f32>{
|
|
616
|
+
let _tslPW=(m*vec4<f32>(_tslPL,1.0)).xyz;let _rn=m[0].xyz*_tslNL.x+m[1].xyz*_tslNL.y+m[2].xyz*_tslNL.z;let _rl=length(_rn);
|
|
617
|
+
let _tslNW=select(vec3<f32>(0.0,1.0,0.0),_rn/_rl,_rl>1e-5);let _tslVD=vec3<f32>(0.0,0.0,1.0);
|
|
618
|
+
${Gu(e.nodes,e.vertexReachable)}
|
|
619
|
+
return _t${e.outputs.position};}`;o=o.replace("@vertex",`${c}
|
|
620
|
+
@vertex`).replace("let world = m * vec4<f32>(aPos, 1.0);",`let _tslInstF=f32(instIdx);let _tslNewP=_tslEvalPos(aPos,aNormal,aUV,vec4<f32>(1.0),_tslInstF,m);var _tslNewN=aNormal;
|
|
621
|
+
if(length(aNormal)>1e-4){let _n0=normalize(aNormal);let _tg1=normalize(select(cross(vec3<f32>(1.0,0.0,0.0),_n0),cross(vec3<f32>(0.0,1.0,0.0),_n0),abs(_n0.y)<0.99));let _tg2=cross(_n0,_tg1);let _cn=cross(_tslEvalPos(aPos+_tg1*1e-3,aNormal,aUV,vec4<f32>(1.0),_tslInstF,m)-_tslNewP,_tslEvalPos(aPos+_tg2*1e-3,aNormal,aUV,vec4<f32>(1.0),_tslInstF,m)-_tslNewP);if(length(_cn)>1e-10){_tslNewN=normalize(_cn);}}
|
|
622
|
+
let world = m * vec4<f32>(_tslNewP, 1.0);`).replace(`rawN = (adj0 * aNormal.x + adj1 * aNormal.y + adj2 * aNormal.z) * sgn;
|
|
623
|
+
} else {
|
|
624
|
+
rawN = c0 * aNormal.x + c1 * aNormal.y + c2 * aNormal.z;`,`rawN = (adj0 * _tslNewN.x + adj1 * _tslNewN.y + adj2 * _tslNewN.z) * sgn;
|
|
625
|
+
} else {
|
|
626
|
+
rawN = c0 * _tslNewN.x + c1 * _tslNewN.y + c2 * _tslNewN.z;`).replace(`out.instIdx = instIdx;
|
|
627
|
+
return out;`,`out.instIdx = instIdx;
|
|
628
|
+
out.localPos = _tslNewP;
|
|
629
|
+
out.localNorm = _tslNewN;
|
|
630
|
+
return out;`)}else o=o.replace(`out.instIdx = instIdx;
|
|
631
|
+
return out;`,`out.instIdx = instIdx;
|
|
632
|
+
out.localPos = aPos;
|
|
633
|
+
out.localNorm = aNormal;
|
|
634
|
+
return out;`);if(a){let c=` let _nL=length(in.normal);var _nU:vec3<f32>;if(_nL<1e-4){let _fc=cross(p1,p2);let _fl=length(_fc);_nU=select(vec3<f32>(0.0,1.0,0.0),_fc/_fl,_fl>1e-8);}else{_nU=in.normal/_nL;}if(!frontFacing){_nU=-_nU;}
|
|
635
|
+
let _toC=sc.camAndExp.xyz-in.worldPos;let _cD=length(_toC);let _tslVD=select(vec3<f32>(0.0,0.0,1.0),_toC/_cD,_cD>1e-6);let _tslNW=_nU;
|
|
636
|
+
let _lnL=length(in.localNorm);let _tslNL=select(vec3<f32>(0.0,1.0,0.0),in.localNorm/_lnL,_lnL>1e-5);let _tslPL=in.localPos;let _tslPW=in.worldPos;let _tslUV=in.uv;let _tslVC=vec4<f32>(1.0);let _tslII=f32(in.instIdx);
|
|
637
|
+
${Gu(e.nodes,e.fragmentReachable)}`;o=o.replace("let emTexel = textureSample(emTex, linSampler, in.uv);",`let emTexel = textureSample(emTex, linSampler, in.uv);
|
|
638
|
+
${c}`),e.outputs.opacity!==void 0&&(o=o.replace(`if (base.a < 0.004) {
|
|
639
|
+
discard;
|
|
640
|
+
}`,`base.a = clamp(_t${e.outputs.opacity}, 0.0, 1.0);
|
|
641
|
+
if (base.a < 0.004) {
|
|
642
|
+
discard;
|
|
643
|
+
}`)),o=o.replace("if (nInLen < 1e-4 && (pFlags & 2u) != 0u) {","if (false && nInLen < 1e-4 && (pFlags & 2u) != 0u) {"),e.outputs.normalScale!==void 0&&e.outputs.bump===void 0&&(o=o.replace("q = vec3<f32>(q.xy * p.aux.x, q.z);",`q = vec3<f32>(q.xy * max(_t${e.outputs.normalScale}, 0.0), q.z);`));let f=[];if(e.outputs.color!==void 0&&f.push(` base=vec4<f32>(max(_t${e.outputs.color},vec3<f32>(0.0)),base.a);`),e.outputs.emissive!==void 0&&f.push(` em=max(_t${e.outputs.emissive},vec3<f32>(0.0));`),e.outputs.roughness!==void 0&&f.push(` roughness=clamp(_t${e.outputs.roughness},0.04,1.0);`),e.outputs.metalness!==void 0&&f.push(` metallic=clamp(_t${e.outputs.metalness},0.0,1.0);`),e.outputs.bump!==void 0){let m=e.outputs.normalScale!==void 0?`max(_t${e.outputs.normalScale},0.0)`:"1.0";f.push(` let _bn=_t${e.outputs.bump};let _bl=length(_bn);if(_bl>1e-6){let _bm=N+(_bn/_bl-N)*(${m});let _ml=length(_bm);if(_ml>1e-6){N=_bm/_ml;}}`)}f.length>0&&(o=o.replace("metallic = clamp(metallic, 0.0, 1.0);",`metallic = clamp(metallic, 0.0, 1.0);
|
|
644
|
+
${f.join(`
|
|
645
|
+
`)}`))}let l=null;if(e.usesVertexPosition&&e.outputs.position!==void 0){let c=nh(ti(e.nodes,e.vertexReachable,e.usesTime),!1),f=Gu(e.nodes,e.vertexReachable);l=r.replace("@group(0) @binding(1) var<storage, read> parts: array<PartInstance>;",`@group(0) @binding(1) var<storage, read> parts: array<PartInstance>;
|
|
646
|
+
${i}@group(1) @binding(0) var<uniform> tslU: TslUniformBlock;
|
|
647
|
+
${c}`).replace("@location(1) aNormal: vec3<f32>,",`@location(1) aNormal: vec3<f32>,
|
|
648
|
+
@location(2) aUV: vec2<f32>,`).replace("var wp = m * vec4<f32>(aPos, 1.0);",`let _tslPL=aPos;let _tslPW=(m*vec4<f32>(aPos,1.0)).xyz;let _tslNL=aNormal;let _rn=m[0].xyz*aNormal.x+m[1].xyz*aNormal.y+m[2].xyz*aNormal.z;let _rl=length(_rn);let _tslNW=select(vec3<f32>(0.0,1.0,0.0),_rn/_rl,_rl>1e-5);let _tslVD=vec3<f32>(0.0,0.0,1.0);let _tslUV=aUV;let _tslVC=vec4<f32>(1.0);let _tslII=f32(instIdx);
|
|
649
|
+
${f}
|
|
650
|
+
var wp = m * vec4<f32>(_t${e.outputs.position}, 1.0);`)}return{hash:e.hash,pbrWgsl:o,shadowDepthWgsl:l}}var Wi=new WeakMap,_o=new WeakMap,ih=new WeakMap,ji=new Map,my=128;function hy(e,t){let r=ih.get(t);return r||(r={paramsLoc:e.getUniformLocation(t,"uTslParams[0]")??e.getUniformLocation(t,"uTslParams"),timeLoc:e.getUniformLocation(t,"uTslTime")},ih.set(t,r)),r}function py(e,t){let r=new Float32Array(68);for(let i of t.uniformSlots){let n=i.slot*4;r[n]=i.defaultVec4[0],r[n+1]=i.defaultVec4[1],r[n+2]=i.defaultVec4[2],r[n+3]=i.defaultVec4[3]}return{name:e,hash:t.hash,graph:t,buf68:r,usesTime:t.usesTime,usesVertexPosition:t.usesVertexPosition,version:1}}function Hi(e,t){let r=new Map,i=new Map,n=!1,a=Array.isArray(t?.materials)?t.materials:[];for(let l=0;l<a.length;l++){let c=a[l],f=c?.extensions?.[Br];if(!f)continue;let m=typeof c.name=="string"&&c.name.length>0?c.name:`Material_${l}`,h=Sr(f,m);if(!h.ok){console.warn(`[three-live] [${h.issue.code}] ${h.issue.message} Falling back to base PBR material.`);continue}let p=py(m,h.graph);r.set(l,p);let g=i.get(m)??[];g.push(p),i.set(m,g),h.graph.usesTime&&(n=!0)}let s={materialsByIndex:r,materialsByName:i,hasAnimatedTsl:n,elapsedSec:0};Wi.set(e,s);let o=e.gl;return o&&typeof o=="object"&&_o.set(o,s),s}function sh(e,t){let r=Wi.get(e);if(!r){let i=t??e.gltf;if(!i)return null;r=Hi(e,i)}return r}function by(e){if(e==null)return null;if(typeof e=="number"||Array.isArray(e)||e instanceof Float32Array)return e;if(typeof e=="object"){let t=e;if("r"in t&&"g"in t&&"b"in t)return[Number(t.r),Number(t.g),Number(t.b)];if("x"in t&&"y"in t&&"z"in t&&"w"in t)return[Number(t.x),Number(t.y),Number(t.z),Number(t.w)];if("x"in t&&"y"in t&&"z"in t)return[Number(t.x),Number(t.y),Number(t.z)];if("x"in t&&"y"in t)return[Number(t.x),Number(t.y)]}return null}function ju(e,t,r,i){if(!e||typeof e!="object")return!1;let n=e,a=n.viewer&&typeof n.viewer=="object"?n.viewer:e,s=sh(a);if(!s||s.materialsByIndex.size===0)return!1;let o=t==="*"||t===""?Array.from(s.materialsByIndex.values()):s.materialsByName.get(t)??[];if(o.length===0)return!1;let l=by(i);if(l===null)return!1;let c=!1;for(let f of o){let m=f.graph.uniformSlotByName.get(r);if(!m)continue;let h=ei(m.type,l);if(!h)continue;let p=m.slot*4;f.buf68[p]=h[0],f.buf68[p+1]=h[1],f.buf68[p+2]=h[2],f.buf68[p+3]=h[3],f.version++,c=!0}return c&&a.animFrameId===null&&typeof a.render=="function"&&a.render(),c}function lc(e){if(!e||typeof e!="object")return;let t=e;typeof t.setMaterialUniform!="function"&&(t.setMaterialUniform=(r,i,n)=>ju(e,r,i,n))}function yy(){let e=He();jn(Zo);let t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t?Zo(t,e):e.authorNamespace||(e.authorNamespace={}),e.tslWgslCompiler=(r,i,n)=>!r||typeof r!="object"?null:cc(r,i,n),e.tslMaterialResolver=(r,i)=>i===void 0||i<0?null:sh(r)?.materialsByIndex.get(i)??null,e.tslUsdzSerializer=Ss}var uc={name:"tsl",onRegister(){yy()},onElementConnected(e){lc(e),e?.viewer&&(lc(e.viewer),e.viewer.gltf&&(Hi(e.viewer,e.viewer.gltf),e.viewer.recompileRenderProgram?.()))},onBuildPrimitiveVAO(e,t,r,i){let n=r?.material;if(typeof n!="number")return null;let a=i?.materials?.[n]?.extensions?.[Br];if(!a)return null;let s=Sr(a,i?.materials?.[n]?.name||`Material_${n}`);return s.ok?{hash:s.graph.hash,materialIndex:n}:null},onResolveShader(e,t,r,i){let n=t?.extensions?.[Br];if(!n)return null;let a=Sr(n,t?.name||"Material");if(!a.ok)return console.warn(`[three-live] [${a.issue.code}] ${a.issue.message} Falling back to base PBR shader.`),null;let s=`${a.graph.hash}|${r.length}|${i.length}|${i.slice(-64)}`,o=ji.get(s);if(!o){if(ji.size>=my){let l=ji.keys().next().value;l!==void 0&&ji.delete(l)}o=ws(a.graph,r,i),ji.set(s,o)}return o},onLoadModel(e,t){lc(e),e?.container&&lc(e.container),Hi(e,t).hasAnimatedTsl&&e&&e.animFrameId===null&&typeof e.start=="function"&&e.opts?.autoStart!==!1&&typeof requestAnimationFrame<"u"&&e.start()},onUpdate(e,t){let r=Wi.get(e);if(!r||!r.hasAnimatedTsl)return;let i=Number.isFinite(t)&&t>0?Math.min(t,.25):0;r.elapsedSec=vs(r.elapsedSec+i,3600);for(let n of r.materialsByIndex.values())n.usesTime&&(n.buf68[64]=r.elapsedSec,n.version++)},onBeforeDrawPrimitive(e,t,r,i,n,a){let s=r?.materialIndex;if(typeof s!="number"||!a?.materials?.[s]?.extensions?.[Br])return;let o=hy(e,t);if(!o.paramsLoc&&!o.timeLoc)return;let l=_o.get(e);l||(l=Hi(e,a),_o.set(e,l));let c=l.materialsByIndex.get(s);c&&(o.paramsLoc&&e.uniform4fv(o.paramsLoc,c.buf68,0,64),o.timeLoc&&e.uniform1f(o.timeLoc,c.buf68[64]))},onClearScene(e){Wi.delete(e),e?.gl&&typeof e.gl=="object"&&_o.delete(e.gl)},onContextRestored(e,t){if(t?.gltf){let r=Hi(t,t.gltf);e&&typeof e=="object"&&_o.set(e,r)}},onDestroy(e,t){Wi.delete(t),e&&typeof e=="object"&&_o.delete(e)}};gt(uc);var jr=800,qi=32,Yi=128,Eo=8,Hr=32;function Xi(e,t){for(let r=0;r<4;r++){let i=r*4,n=t[i+2],a=t[i+3];e[i]=t[i],e[i+1]=t[i+1],e[i+2]=.5*(n+a),e[i+3]=a}return e}function Ki(e,t){let r=new Float32Array(e,0,200),i=new Uint32Array(e,0,200),n=new Int32Array(e,0,200);r.fill(0),Xi(r.subarray(0,16),t.vp);for(let x=0;x<16;x++)r[16+x]=t.modelRoot[x]??(x%5===0?1:0);r[32]=t.eyePos[0],r[33]=t.eyePos[1],r[34]=t.eyePos[2],r[35]=Number.isFinite(t.exposure)?Math.max(0,t.exposure):1;let a=.28,s=.28,o=.28,l=!1,c=0,f=1,m=0,h=0,p=0;for(let x of t.lights){let v=x.color??[1,1,1],y=x.intensity!==void 0?x.intensity:1;if(x.type==="ambient")a=(v[0]??1)*y,s=(v[1]??1)*y,o=(v[2]??1)*y;else if(x.type==="hemisphere"){l=!0;let A=x.groundColor??[.2,.2,.2],b=y*.65;r[40]+=(v[0]??1)*b,r[41]+=(v[1]??1)*b,r[42]+=(v[2]??1)*b,r[44]+=(A[0]??.2)*b,r[45]+=(A[1]??.2)*b,r[46]+=(A[2]??.2)*b;let w=x.position??[0,1,0],S=Math.hypot(w[0]??0,w[1]??1,w[2]??0);S>1e-5&&(c=(w[0]??0)/S,f=(w[1]??1)/S,m=(w[2]??0)/S)}else if(x.type==="directional"&&h<2){let A=x.direction??[.5,1,.8],b=52+h*8;r[b]=A[0]??.5,r[b+1]=A[1]??1,r[b+2]=A[2]??.8,r[b+4]=(v[0]??1)*y,r[b+5]=(v[1]??1)*y,r[b+6]=(v[2]??1)*y,h++}else if((x.type==="point"||x.type==="spot")&&p<2){let A=x.position??[0,0,0],b=68+p*16;if(r[b]=A[0]??0,r[b+1]=A[1]??0,r[b+2]=A[2]??0,r[b+4]=(v[0]??1)*y,r[b+5]=(v[1]??1)*y,r[b+6]=(v[2]??1)*y,x.type==="spot"){let w=x.direction??[0,-1,0],S=Math.max(.01,Math.min(Math.PI/2,x.outerConeAngle??Math.PI/3)),E=Math.max(0,Math.min(S-1e-4,x.innerConeAngle??0)),N=Math.hypot(w[0]??0,w[1]??-1,w[2]??0)||1;r[b+8]=(w[0]??0)/N,r[b+9]=(w[1]??-1)/N,r[b+10]=(w[2]??0)/N,r[b+12]=Math.cos(E),r[b+13]=Math.cos(S)}else r[b+9]=-1,r[b+12]=-2,r[b+13]=-3;p++}}h===0&&!l&&(r[52]=.5,r[53]=1,r[54]=.8,r[56]=1,r[57]=1,r[58]=1,h=1),r[36]=a,r[37]=s,r[38]=o,r[39]=Number.isFinite(t.envIntensity)?Math.max(0,t.envIntensity):1,r[48]=c,r[49]=f,r[50]=m;let g=0;if(t.hasEnvMap&&(g|=1),t.sectionPlane?.enabled&&(g|=2,r[100]=t.sectionPlane.normal[0],r[101]=t.sectionPlane.normal[1],r[102]=t.sectionPlane.normal[2],r[103]=t.sectionPlane.constant),t.isRightEye&&(g|=4),t.contactShadow&&t.contactShadow.intensity>0&&(r[104]=t.contactShadow.centerX,r[105]=t.contactShadow.floorY,r[106]=t.contactShadow.centerZ,r[107]=Math.max(.01,t.contactShadow.halfExtentX),r[108]=Math.max(.01,t.contactShadow.halfExtentZ),r[109]=Math.min(1,Math.max(0,t.contactShadow.intensity)),r[110]=Math.min(1,Math.max(0,t.contactShadow.softness))),i[112]=Math.max(0,t.toneMappingIndex|0)>>>0,i[113]=h>>>0,i[114]=p>>>0,i[115]=g>>>0,n[196]=-1,n[197]=-1,n[198]=-1,n[199]=-1,t.shadowMap&&t.shadowMap.slices.length>0){for(let x of t.shadowMap.slices){if(x.slot<0||x.slot>=4)continue;Xi(r.subarray(116+x.slot*16,132+x.slot*16),x.viewProj);let v=180+x.slot*4;r[v]=x.depthBias,r[v+1]=x.normalBiasWorld*.5,r[v+2]=x.uvRadius}n[196]=t.shadowMap.dirSlots[0]|0,n[197]=t.shadowMap.dirSlots[1]|0,n[198]=t.shadowMap.ptSlots[0]|0,n[199]=t.shadowMap.ptSlots[1]|0}}function ah(e,t,r,i,n,a){let s=new Float32Array(e,0,44),o=new Uint32Array(e,0,44);s.fill(0),Xi(s.subarray(0,16),t);for(let l=0;l<16;l++)s[16+l]=r[l]??(l%5===0?1:0);s[32]=i[0],s[33]=i[1],s[34]=i[2],s[35]=n,a?.enabled&&(s[36]=a.normal[0],s[37]=a.normal[1],s[38]=a.normal[2],s[39]=a.constant,o[40]=1)}var Hu=`
|
|
651
|
+
struct SceneUniforms {
|
|
652
|
+
viewProj: mat4x4<f32>,
|
|
653
|
+
modelRoot: mat4x4<f32>,
|
|
654
|
+
camAndExp: vec4<f32>,
|
|
655
|
+
ambAndEnv: vec4<f32>,
|
|
656
|
+
hemiSky: vec4<f32>,
|
|
657
|
+
hemiGround: vec4<f32>,
|
|
658
|
+
hemiAxis: vec4<f32>,
|
|
659
|
+
dirDir0: vec4<f32>,
|
|
660
|
+
dirCol0: vec4<f32>,
|
|
661
|
+
dirDir1: vec4<f32>,
|
|
662
|
+
dirCol1: vec4<f32>,
|
|
663
|
+
ptPos0: vec4<f32>,
|
|
664
|
+
ptCol0: vec4<f32>,
|
|
665
|
+
ptSpotDir0: vec4<f32>,
|
|
666
|
+
ptSpotCone0: vec4<f32>,
|
|
667
|
+
ptPos1: vec4<f32>,
|
|
668
|
+
ptCol1: vec4<f32>,
|
|
669
|
+
ptSpotDir1: vec4<f32>,
|
|
670
|
+
ptSpotCone1: vec4<f32>,
|
|
671
|
+
sectionPlane: vec4<f32>,
|
|
672
|
+
shadowBox: vec4<f32>,
|
|
673
|
+
shadowParams: vec4<f32>,
|
|
674
|
+
flags: vec4<u32>,
|
|
675
|
+
shdVP0: mat4x4<f32>,
|
|
676
|
+
shdVP1: mat4x4<f32>,
|
|
677
|
+
shdVP2: mat4x4<f32>,
|
|
678
|
+
shdVP3: mat4x4<f32>,
|
|
679
|
+
shdParams0: vec4<f32>,
|
|
680
|
+
shdParams1: vec4<f32>,
|
|
681
|
+
shdParams2: vec4<f32>,
|
|
682
|
+
shdParams3: vec4<f32>,
|
|
683
|
+
shdSlots: vec4<i32>,
|
|
684
|
+
};
|
|
685
|
+
|
|
686
|
+
struct PartInstance {
|
|
687
|
+
model: mat4x4<f32>,
|
|
688
|
+
baseColor: vec4<f32>,
|
|
689
|
+
pbr: vec4<f32>,
|
|
690
|
+
emissive: vec4<f32>,
|
|
691
|
+
aux: vec2<f32>,
|
|
692
|
+
flags: u32,
|
|
693
|
+
pickId: u32,
|
|
694
|
+
};
|
|
695
|
+
|
|
696
|
+
@group(0) @binding(0) var<uniform> sc: SceneUniforms;
|
|
697
|
+
@group(0) @binding(1) var<storage, read> parts: array<PartInstance>;
|
|
698
|
+
@group(0) @binding(2) var linSampler: sampler;
|
|
699
|
+
@group(0) @binding(3) var envTex: texture_2d<f32>;
|
|
700
|
+
@group(0) @binding(4) var shadowSampler: sampler_comparison;
|
|
701
|
+
@group(0) @binding(5) var shadowTex: texture_depth_2d_array;
|
|
702
|
+
`,Ji=Hu+`
|
|
703
|
+
@group(1) @binding(0) var baseTex: texture_2d<f32>;
|
|
704
|
+
@group(1) @binding(1) var mrTex: texture_2d<f32>;
|
|
705
|
+
@group(1) @binding(2) var normTex: texture_2d<f32>;
|
|
706
|
+
@group(1) @binding(3) var occTex: texture_2d<f32>;
|
|
707
|
+
@group(1) @binding(4) var emTex: texture_2d<f32>;
|
|
708
|
+
|
|
709
|
+
struct VsOut {
|
|
710
|
+
@builtin(position) clipPos: vec4<f32>,
|
|
711
|
+
@location(0) worldPos: vec3<f32>,
|
|
712
|
+
@location(1) normal: vec3<f32>,
|
|
713
|
+
@location(2) uv: vec2<f32>,
|
|
714
|
+
@location(3) @interpolate(flat) instIdx: u32,
|
|
715
|
+
};
|
|
716
|
+
|
|
717
|
+
@vertex
|
|
718
|
+
fn vsMain(
|
|
719
|
+
@location(0) aPos: vec3<f32>,
|
|
720
|
+
@location(1) aNormal: vec3<f32>,
|
|
721
|
+
@location(2) aUV: vec2<f32>,
|
|
722
|
+
@builtin(instance_index) instIdx: u32,
|
|
723
|
+
) -> VsOut {
|
|
724
|
+
let p = parts[instIdx];
|
|
725
|
+
var out: VsOut;
|
|
726
|
+
if ((p.flags & 128u) != 0u) {
|
|
727
|
+
out.clipPos = vec4<f32>(2.0, 2.0, 2.0, 1.0);
|
|
728
|
+
out.worldPos = vec3<f32>(0.0);
|
|
729
|
+
out.normal = vec3<f32>(0.0, 1.0, 0.0);
|
|
730
|
+
out.uv = vec2<f32>(0.0);
|
|
731
|
+
out.instIdx = instIdx;
|
|
732
|
+
return out;
|
|
733
|
+
}
|
|
734
|
+
var m: mat4x4<f32>;
|
|
735
|
+
if ((p.flags & 1u) != 0u) {
|
|
736
|
+
m = p.model;
|
|
737
|
+
} else {
|
|
738
|
+
m = sc.modelRoot * p.model;
|
|
739
|
+
}
|
|
740
|
+
let world = m * vec4<f32>(aPos, 1.0);
|
|
741
|
+
|
|
742
|
+
let c0 = m[0].xyz;
|
|
743
|
+
let c1 = m[1].xyz;
|
|
744
|
+
let c2 = m[2].xyz;
|
|
745
|
+
let adj0 = cross(c1, c2);
|
|
746
|
+
let adj1 = cross(c2, c0);
|
|
747
|
+
let adj2 = cross(c0, c1);
|
|
748
|
+
let det = dot(c0, adj0);
|
|
749
|
+
var rawN = vec3<f32>(0.0);
|
|
750
|
+
if (abs(det) > 1e-12) {
|
|
751
|
+
let sgn = select(-1.0, 1.0, det > 0.0);
|
|
752
|
+
rawN = (adj0 * aNormal.x + adj1 * aNormal.y + adj2 * aNormal.z) * sgn;
|
|
753
|
+
} else {
|
|
754
|
+
rawN = c0 * aNormal.x + c1 * aNormal.y + c2 * aNormal.z;
|
|
755
|
+
}
|
|
756
|
+
let nLen = length(rawN);
|
|
757
|
+
|
|
758
|
+
let stereoMode = (p.flags >> 8u) & 3u;
|
|
759
|
+
let isRight = (sc.flags.w & 4u) != 0u;
|
|
760
|
+
var uv = aUV;
|
|
761
|
+
if (stereoMode == 1u) {
|
|
762
|
+
uv = vec2<f32>(aUV.x * 0.5 + select(0.0, 0.5, isRight), aUV.y);
|
|
763
|
+
} else if (stereoMode == 2u) {
|
|
764
|
+
uv = vec2<f32>(aUV.x, aUV.y * 0.5 + select(0.0, 0.5, isRight));
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
out.clipPos = sc.viewProj * world;
|
|
768
|
+
out.worldPos = world.xyz;
|
|
769
|
+
out.normal = select(vec3<f32>(0.0), rawN / nLen, nLen > 1e-5);
|
|
770
|
+
out.uv = uv;
|
|
771
|
+
out.instIdx = instIdx;
|
|
772
|
+
return out;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
fn envBRDF(r: f32, n: f32) -> vec2<f32> {
|
|
776
|
+
let c0 = vec4<f32>(-1.0, -0.0275, -0.572, 0.022);
|
|
777
|
+
let c1 = vec4<f32>(1.0, 0.0425, 1.04, -0.04);
|
|
778
|
+
let rv = r * c0 + c1;
|
|
779
|
+
let a = min(rv.x * rv.x, exp2(-9.28 * n)) * rv.x + rv.y;
|
|
780
|
+
return vec2<f32>(-1.04, 1.04) * a + rv.zw;
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
fn fSchlickRoughness(f0: vec3<f32>, r: f32, n: f32) -> vec3<f32> {
|
|
784
|
+
return f0 + (max(vec3<f32>(1.0 - r), f0) - f0) * pow(clamp(1.0 - n, 0.0, 1.0), 5.0);
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
fn getStudioRadiance(rDir: vec3<f32>, r: f32) -> vec3<f32> {
|
|
788
|
+
let kd = normalize(vec3<f32>(0.0, 1.0, 0.35));
|
|
789
|
+
let fd = normalize(vec3<f32>(-0.85, 0.45, -0.35));
|
|
790
|
+
let ki = pow(max(dot(rDir, kd), 0.0), mix(96.0, 1.5, r)) * mix(2.4, 0.5, r);
|
|
791
|
+
let fi = pow(max(dot(rDir, fd), 0.0), mix(36.0, 1.2, r)) * mix(1.3, 0.35, r);
|
|
792
|
+
let ri = pow(clamp(1.0 - abs(rDir.y), 0.0, 1.0), 3.5) * mix(0.55, 0.22, r);
|
|
793
|
+
return mix(vec3<f32>(0.06, 0.06, 0.08), vec3<f32>(0.48, 0.50, 0.55), rDir.y * 0.5 + 0.5)
|
|
794
|
+
+ vec3<f32>(1.0, 0.98, 0.94) * ki
|
|
795
|
+
+ vec3<f32>(0.85, 0.92, 1.0) * fi
|
|
796
|
+
+ vec3<f32>(0.65, 0.72, 0.85) * ri;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
fn equirectangularUV(dir: vec3<f32>) -> vec2<f32> {
|
|
800
|
+
let d = normalize(dir);
|
|
801
|
+
return vec2<f32>(
|
|
802
|
+
atan2(d.z, d.x) * 0.15915494309 + 0.5,
|
|
803
|
+
0.5 - asin(clamp(d.y, -1.0, 1.0)) * 0.31830988618,
|
|
804
|
+
);
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
fn neutralToneMapping(cIn: vec3<f32>) -> vec3<f32> {
|
|
808
|
+
var c = cIn;
|
|
809
|
+
let x = min(c.r, min(c.g, c.b));
|
|
810
|
+
c -= select(0.04, x - 6.25 * x * x, x < 0.08);
|
|
811
|
+
let p = max(c.r, max(c.g, c.b));
|
|
812
|
+
if (p < 0.76) {
|
|
813
|
+
return clamp(c, vec3<f32>(0.0), vec3<f32>(1.0));
|
|
814
|
+
}
|
|
815
|
+
let n = 1.0 - 0.0576 / (p - 0.52);
|
|
816
|
+
c *= n / p;
|
|
817
|
+
return clamp(mix(c, vec3<f32>(n), 1.0 - 1.0 / (0.15 * (p - n) + 1.0)), vec3<f32>(0.0), vec3<f32>(1.0));
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
fn acesToneMapping(cIn: vec3<f32>) -> vec3<f32> {
|
|
821
|
+
let c = cIn * 0.6;
|
|
822
|
+
return clamp((c * (2.51 * c + 0.03)) / (c * (2.43 * c + 0.59) + 0.14), vec3<f32>(0.0), vec3<f32>(1.0));
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
fn agxToneMapping(cIn: vec3<f32>) -> vec3<f32> {
|
|
826
|
+
let c = max(cIn, vec3<f32>(0.0));
|
|
827
|
+
let inset = mat3x3<f32>(
|
|
828
|
+
vec3<f32>(0.84247906, 0.04232824, 0.04237565),
|
|
829
|
+
vec3<f32>(0.0784336, 0.87846864, 0.0784336),
|
|
830
|
+
vec3<f32>(0.07922375, 0.07916613, 0.87914297),
|
|
831
|
+
) * c;
|
|
832
|
+
let e = clamp((log2(max(inset, vec3<f32>(1e-6))) + 12.47393) / 16.5, vec3<f32>(0.0), vec3<f32>(1.0));
|
|
833
|
+
let x2 = e * e;
|
|
834
|
+
let x4 = x2 * x2;
|
|
835
|
+
let s = 15.5 * x4 * x2 - 40.14 * x4 * e + 31.96 * x4 - 6.868 * x2 * e + 0.4298 * x2 + 0.1191 * e - 0.00232;
|
|
836
|
+
let outset = mat3x3<f32>(
|
|
837
|
+
vec3<f32>(1.196879, -0.05289685, -0.05297164),
|
|
838
|
+
vec3<f32>(-0.09802088, 1.15190313, -0.09804345),
|
|
839
|
+
vec3<f32>(-0.09902974, -0.09896118, 1.15107367),
|
|
840
|
+
) * s;
|
|
841
|
+
return clamp(pow(max(outset, vec3<f32>(0.0)), vec3<f32>(2.2)), vec3<f32>(0.0), vec3<f32>(1.0));
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
fn applyToneMapping(c: vec3<f32>, mode: u32) -> vec3<f32> {
|
|
845
|
+
if (mode == 0u) { return neutralToneMapping(c); }
|
|
846
|
+
if (mode == 1u) { return c / (c + vec3<f32>(1.0)); }
|
|
847
|
+
if (mode == 3u) { return acesToneMapping(c); }
|
|
848
|
+
if (mode == 4u) { return agxToneMapping(c); }
|
|
849
|
+
return clamp(c, vec3<f32>(0.0), vec3<f32>(1.0));
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
fn evalLight(lDir: vec3<f32>, vDir: vec3<f32>, nDir: vec3<f32>, baseRgb: vec3<f32>, specExp: f32, specW: f32, cc: vec2<f32>) -> vec3<f32> {
|
|
853
|
+
let h = max(dot(nDir, normalize(lDir + vDir)), 0.0);
|
|
854
|
+
return baseRgb * max(dot(nDir, lDir), 0.0) * 0.75
|
|
855
|
+
+ vec3<f32>(pow(h, specExp) * specW + cc.x * pow(h, mix(64.0, 512.0, 1.0 - cc.y)) * 0.35);
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
const VOGEL_DISK = array<vec2<f32>, 8>(
|
|
859
|
+
vec2<f32>(0.1768, 0.0),
|
|
860
|
+
vec2<f32>(-0.2265, 0.2078),
|
|
861
|
+
vec2<f32>(0.0355, -0.4150),
|
|
862
|
+
vec2<f32>(0.3204, 0.3888),
|
|
863
|
+
vec2<f32>(-0.5562, -0.1455),
|
|
864
|
+
vec2<f32>(0.4916, -0.3806),
|
|
865
|
+
vec2<f32>(-0.1419, 0.6596),
|
|
866
|
+
vec2<f32>(-0.5177, -0.5150),
|
|
867
|
+
);
|
|
868
|
+
|
|
869
|
+
fn evalShadow(slot: i32, recv: bool, wp: vec3<f32>, nDir: vec3<f32>, lDir: vec3<f32>, fragXY: vec2<f32>) -> f32 {
|
|
870
|
+
if (!recv || slot < 0) {
|
|
871
|
+
return 1.0;
|
|
872
|
+
}
|
|
873
|
+
let nl = dot(nDir, lDir);
|
|
874
|
+
if (nl <= 0.0) {
|
|
875
|
+
return 0.0;
|
|
876
|
+
}
|
|
877
|
+
var vp: mat4x4<f32>;
|
|
878
|
+
var sp: vec4<f32>;
|
|
879
|
+
if (slot == 0) {
|
|
880
|
+
vp = sc.shdVP0;
|
|
881
|
+
sp = sc.shdParams0;
|
|
882
|
+
} else if (slot == 1) {
|
|
883
|
+
vp = sc.shdVP1;
|
|
884
|
+
sp = sc.shdParams1;
|
|
885
|
+
} else if (slot == 2) {
|
|
886
|
+
vp = sc.shdVP2;
|
|
887
|
+
sp = sc.shdParams2;
|
|
888
|
+
} else {
|
|
889
|
+
vp = sc.shdVP3;
|
|
890
|
+
sp = sc.shdParams3;
|
|
891
|
+
}
|
|
892
|
+
let scPos = vp * vec4<f32>(wp + nDir * (sp.y * (1.0 - nl)), 1.0);
|
|
893
|
+
if (scPos.w <= 1e-6) {
|
|
894
|
+
return 1.0;
|
|
895
|
+
}
|
|
896
|
+
let ndc = scPos.xyz / scPos.w;
|
|
897
|
+
let suv = vec2<f32>(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
|
|
898
|
+
if (suv.x <= 0.002 || suv.x >= 0.998 || suv.y <= 0.002 || suv.y >= 0.998 || ndc.z > 1.0 || ndc.z < 0.0) {
|
|
899
|
+
return 1.0;
|
|
900
|
+
}
|
|
901
|
+
let refZ = clamp(ndc.z + sp.x, 0.0, 1.0);
|
|
902
|
+
if (sp.z <= 1e-6) {
|
|
903
|
+
return textureSampleCompareLevel(shadowTex, shadowSampler, suv, slot, refZ);
|
|
904
|
+
}
|
|
905
|
+
let ang = fract(52.9829189 * fract(dot(fragXY, vec2<f32>(0.06711056, 0.00583715)))) * 6.2831853;
|
|
906
|
+
let ca = cos(ang);
|
|
907
|
+
let sa = sin(ang);
|
|
908
|
+
var sum = 0.0;
|
|
909
|
+
for (var k = 0; k < 8; k = k + 1) {
|
|
910
|
+
let t = VOGEL_DISK[k];
|
|
911
|
+
let rot = vec2<f32>(ca * t.x - sa * t.y, sa * t.x + ca * t.y) * sp.z;
|
|
912
|
+
sum += textureSampleCompareLevel(shadowTex, shadowSampler, suv + rot, slot, refZ);
|
|
913
|
+
}
|
|
914
|
+
return sum * 0.125;
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
@fragment
|
|
918
|
+
fn fsMain(in: VsOut, @builtin(front_facing) frontFacing: bool) -> @location(0) vec4<f32> {
|
|
919
|
+
let p1 = dpdx(in.worldPos);
|
|
920
|
+
let p2 = -dpdy(in.worldPos);
|
|
921
|
+
let u1 = dpdx(in.uv);
|
|
922
|
+
let u2 = -dpdy(in.uv);
|
|
923
|
+
let baseTexel = textureSample(baseTex, linSampler, in.uv);
|
|
924
|
+
let mrTexel = textureSample(mrTex, linSampler, in.uv);
|
|
925
|
+
let normTexel = textureSample(normTex, linSampler, in.uv);
|
|
926
|
+
let occTexel = textureSample(occTex, linSampler, in.uv);
|
|
927
|
+
let emTexel = textureSample(emTex, linSampler, in.uv);
|
|
928
|
+
|
|
929
|
+
let p = parts[in.instIdx];
|
|
930
|
+
let pFlags = p.flags;
|
|
931
|
+
let secOn = (sc.flags.w & 2u) != 0u && (pFlags & 64u) == 0u;
|
|
932
|
+
if (secOn && dot(in.worldPos, sc.sectionPlane.xyz) > sc.sectionPlane.w) {
|
|
933
|
+
discard;
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
var base = p.baseColor;
|
|
937
|
+
if ((pFlags & 2u) != 0u) {
|
|
938
|
+
base *= baseTexel;
|
|
939
|
+
}
|
|
940
|
+
if (base.a < 0.004) {
|
|
941
|
+
discard;
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
var em = p.emissive.xyz;
|
|
945
|
+
if ((pFlags & 32u) != 0u) {
|
|
946
|
+
em *= emTexel.rgb;
|
|
947
|
+
}
|
|
948
|
+
let selGlow = vec3<f32>(p.emissive.w * 0.35, p.emissive.w * 0.5, p.emissive.w * 0.7);
|
|
949
|
+
|
|
950
|
+
let nInLen = length(in.normal);
|
|
951
|
+
if (nInLen < 1e-4 && (pFlags & 2u) != 0u) {
|
|
952
|
+
let unlit = clamp(base.rgb + em + selGlow, vec3<f32>(0.0), vec3<f32>(1.0));
|
|
953
|
+
return vec4<f32>(unlit * base.a, base.a);
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
var N: vec3<f32>;
|
|
957
|
+
if (nInLen < 1e-4) {
|
|
958
|
+
let flatCross = cross(p1, p2);
|
|
959
|
+
let fLen = length(flatCross);
|
|
960
|
+
N = select(vec3<f32>(0.0, 1.0, 0.0), flatCross / fLen, fLen > 1e-8);
|
|
961
|
+
} else {
|
|
962
|
+
N = in.normal / nInLen;
|
|
963
|
+
}
|
|
964
|
+
if (!frontFacing) {
|
|
965
|
+
N = -N;
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
let toCam = sc.camAndExp.xyz - in.worldPos;
|
|
969
|
+
let camDist = length(toCam);
|
|
970
|
+
let V = select(vec3<f32>(0.0, 0.0, 1.0), toCam / camDist, camDist > 1e-6);
|
|
971
|
+
|
|
972
|
+
if ((pFlags & 8u) != 0u) {
|
|
973
|
+
var q = normTexel.xyz * 2.0 - 1.0;
|
|
974
|
+
q = vec3<f32>(q.xy * p.aux.x, q.z);
|
|
975
|
+
let c2 = cross(p2, N);
|
|
976
|
+
let c1 = cross(N, p1);
|
|
977
|
+
let T = c2 * u1.x + c1 * u2.x;
|
|
978
|
+
let B = c2 * u1.y + c1 * u2.y;
|
|
979
|
+
let maxTB = max(dot(T, T), dot(B, B));
|
|
980
|
+
if (maxTB > 1e-12 && length(q) > 1e-5) {
|
|
981
|
+
let k = inverseSqrt(maxTB);
|
|
982
|
+
N = normalize(mat3x3<f32>(T * k, B * k, N) * normalize(q));
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
var metallic = p.pbr.x;
|
|
987
|
+
var roughness = p.pbr.y;
|
|
988
|
+
if ((pFlags & 4u) != 0u) {
|
|
989
|
+
roughness *= mrTexel.g;
|
|
990
|
+
metallic *= mrTexel.b;
|
|
991
|
+
}
|
|
992
|
+
roughness = clamp(roughness, 0.04, 1.0);
|
|
993
|
+
metallic = clamp(metallic, 0.0, 1.0);
|
|
994
|
+
|
|
995
|
+
var occ = 1.0;
|
|
996
|
+
if ((pFlags & 16u) != 0u) {
|
|
997
|
+
occ = mix(1.0, occTexel.r, p.aux.y);
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
let gloss = 1.0 - roughness;
|
|
1001
|
+
let specExp = mix(16.0, 256.0, gloss * gloss);
|
|
1002
|
+
let specWeight = mix(0.22 * gloss, 1.0, metallic);
|
|
1003
|
+
let cc = p.pbr.zw;
|
|
1004
|
+
|
|
1005
|
+
let recvShd = (pFlags & 2048u) != 0u;
|
|
1006
|
+
var directLight = vec3<f32>(0.0);
|
|
1007
|
+
let numDir = sc.flags.y;
|
|
1008
|
+
if (numDir > 0u) {
|
|
1009
|
+
let dL0 = normalize(sc.dirDir0.xyz);
|
|
1010
|
+
let sh0 = evalShadow(sc.shdSlots.x, recvShd, in.worldPos, N, dL0, in.clipPos.xy);
|
|
1011
|
+
directLight += evalLight(dL0, V, N, base.rgb, specExp, specWeight, cc) * sc.dirCol0.xyz * sh0;
|
|
1012
|
+
}
|
|
1013
|
+
if (numDir > 1u) {
|
|
1014
|
+
let dL1 = normalize(sc.dirDir1.xyz);
|
|
1015
|
+
let sh1 = evalShadow(sc.shdSlots.y, recvShd, in.worldPos, N, dL1, in.clipPos.xy);
|
|
1016
|
+
directLight += evalLight(dL1, V, N, base.rgb, specExp, specWeight, cc) * sc.dirCol1.xyz * sh1;
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
let numPt = sc.flags.z;
|
|
1020
|
+
if (numPt > 0u) {
|
|
1021
|
+
let toL = sc.ptPos0.xyz - in.worldPos;
|
|
1022
|
+
let dist = length(toL);
|
|
1023
|
+
let L = toL / max(dist, 0.0001);
|
|
1024
|
+
var spotAtt = clamp((dot(-L, sc.ptSpotDir0.xyz) - sc.ptSpotCone0.y) / max(sc.ptSpotCone0.x - sc.ptSpotCone0.y, 0.0001), 0.0, 1.0);
|
|
1025
|
+
spotAtt *= spotAtt;
|
|
1026
|
+
let shP0 = evalShadow(sc.shdSlots.z, recvShd, in.worldPos, N, L, in.clipPos.xy);
|
|
1027
|
+
directLight += evalLight(L, V, N, base.rgb, specExp, specWeight, cc) * sc.ptCol0.xyz * spotAtt / (1.0 + 0.09 * dist + 0.032 * dist * dist) * shP0;
|
|
1028
|
+
}
|
|
1029
|
+
if (numPt > 1u) {
|
|
1030
|
+
let toL = sc.ptPos1.xyz - in.worldPos;
|
|
1031
|
+
let dist = length(toL);
|
|
1032
|
+
let L = toL / max(dist, 0.0001);
|
|
1033
|
+
var spotAtt = clamp((dot(-L, sc.ptSpotDir1.xyz) - sc.ptSpotCone1.y) / max(sc.ptSpotCone1.x - sc.ptSpotCone1.y, 0.0001), 0.0, 1.0);
|
|
1034
|
+
spotAtt *= spotAtt;
|
|
1035
|
+
let shP1 = evalShadow(sc.shdSlots.w, recvShd, in.worldPos, N, L, in.clipPos.xy);
|
|
1036
|
+
directLight += evalLight(L, V, N, base.rgb, specExp, specWeight, cc) * sc.ptCol1.xyz * spotAtt / (1.0 + 0.09 * dist + 0.032 * dist * dist) * shP1;
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
let R = reflect(-V, N);
|
|
1040
|
+
let NoV = clamp(dot(N, V), 0.001, 1.0);
|
|
1041
|
+
let F0 = mix(vec3<f32>(0.04), base.rgb, metallic);
|
|
1042
|
+
let F = fSchlickRoughness(F0, roughness, NoV);
|
|
1043
|
+
let brdf = envBRDF(roughness, NoV);
|
|
1044
|
+
|
|
1045
|
+
var specularIBL: vec3<f32>;
|
|
1046
|
+
var envDiffuse: vec3<f32>;
|
|
1047
|
+
if ((sc.flags.w & 1u) != 0u) {
|
|
1048
|
+
specularIBL = textureSampleLevel(envTex, linSampler, equirectangularUV(R), 0.0).rgb * (F * brdf.x + brdf.y);
|
|
1049
|
+
envDiffuse = textureSampleLevel(envTex, linSampler, equirectangularUV(N), 0.0).rgb;
|
|
1050
|
+
} else {
|
|
1051
|
+
specularIBL = getStudioRadiance(R, roughness) * (F * brdf.x + brdf.y);
|
|
1052
|
+
envDiffuse = mix(vec3<f32>(0.10, 0.10, 0.12), vec3<f32>(0.52, 0.54, 0.58), N.y * 0.5 + 0.5);
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
let kD = (vec3<f32>(1.0) - F) * (1.0 - metallic);
|
|
1056
|
+
directLight += kD * base.rgb * mix(sc.hemiGround.xyz, sc.hemiSky.xyz, dot(N, sc.hemiAxis.xyz) * 0.5 + 0.5) * occ;
|
|
1057
|
+
let diffuseIBL = kD * base.rgb * (sc.ambAndEnv.xyz + envDiffuse * 0.5) * occ;
|
|
1058
|
+
var color = directLight + (diffuseIBL + specularIBL) * sc.ambAndEnv.w + em + selGlow;
|
|
1059
|
+
if (cc.x > 0.0) {
|
|
1060
|
+
let ccF = fSchlickRoughness(vec3<f32>(0.04), cc.y, NoV) * cc.x;
|
|
1061
|
+
color = color * (vec3<f32>(1.0) - ccF) + getStudioRadiance(R, cc.y) * ccF * sc.ambAndEnv.w;
|
|
1062
|
+
}
|
|
1063
|
+
color = applyToneMapping(color * sc.camAndExp.w, sc.flags.x);
|
|
1064
|
+
return vec4<f32>(color * base.a, base.a);
|
|
1065
|
+
}
|
|
1066
|
+
`,dc=Hu+`
|
|
1067
|
+
struct ShadowVsOut {
|
|
1068
|
+
@builtin(position) clipPos: vec4<f32>,
|
|
1069
|
+
@location(0) localUv: vec2<f32>,
|
|
1070
|
+
};
|
|
1071
|
+
|
|
1072
|
+
@vertex
|
|
1073
|
+
fn vsShadow(@builtin(vertex_index) vid: u32) -> ShadowVsOut {
|
|
1074
|
+
let sx = select(-1.0, 1.0, (vid & 1u) != 0u);
|
|
1075
|
+
let sz = select(-1.0, 1.0, (vid & 2u) != 0u);
|
|
1076
|
+
let world = vec4<f32>(
|
|
1077
|
+
sc.shadowBox.x + sx * sc.shadowBox.w,
|
|
1078
|
+
sc.shadowBox.y,
|
|
1079
|
+
sc.shadowBox.z + sz * sc.shadowParams.x,
|
|
1080
|
+
1.0,
|
|
1081
|
+
);
|
|
1082
|
+
var out: ShadowVsOut;
|
|
1083
|
+
out.clipPos = sc.viewProj * world;
|
|
1084
|
+
out.localUv = vec2<f32>(sx, sz);
|
|
1085
|
+
return out;
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
@fragment
|
|
1089
|
+
fn fsShadow(in: ShadowVsOut) -> @location(0) vec4<f32> {
|
|
1090
|
+
let r2 = dot(in.localUv, in.localUv);
|
|
1091
|
+
if (r2 >= 1.0) {
|
|
1092
|
+
discard;
|
|
1093
|
+
}
|
|
1094
|
+
let softness = sc.shadowParams.z;
|
|
1095
|
+
let falloff = mix(6.5, 2.2, softness);
|
|
1096
|
+
let edgeFade = 1.0 - smoothstep(0.55, 1.0, sqrt(r2));
|
|
1097
|
+
let alpha = clamp(exp(-r2 * falloff) * edgeFade * sc.shadowParams.y * 0.72, 0.0, 1.0);
|
|
1098
|
+
return vec4<f32>(0.0, 0.0, 0.0, alpha);
|
|
1099
|
+
}
|
|
1100
|
+
`,fc=Hu+`
|
|
1101
|
+
struct PickVsOut {
|
|
1102
|
+
@builtin(position) clipPos: vec4<f32>,
|
|
1103
|
+
@location(0) worldPos: vec3<f32>,
|
|
1104
|
+
@location(1) @interpolate(flat) instIdx: u32,
|
|
1105
|
+
};
|
|
1106
|
+
|
|
1107
|
+
@vertex
|
|
1108
|
+
fn vsPick(
|
|
1109
|
+
@location(0) aPos: vec3<f32>,
|
|
1110
|
+
@builtin(instance_index) instIdx: u32,
|
|
1111
|
+
) -> PickVsOut {
|
|
1112
|
+
let p = parts[instIdx];
|
|
1113
|
+
var out: PickVsOut;
|
|
1114
|
+
if (p.pickId == 0u || (p.flags & 128u) != 0u) {
|
|
1115
|
+
out.clipPos = vec4<f32>(2.0, 2.0, 2.0, 1.0);
|
|
1116
|
+
out.worldPos = vec3<f32>(0.0);
|
|
1117
|
+
out.instIdx = instIdx;
|
|
1118
|
+
return out;
|
|
1119
|
+
}
|
|
1120
|
+
var m: mat4x4<f32>;
|
|
1121
|
+
if ((p.flags & 1u) != 0u) {
|
|
1122
|
+
m = p.model;
|
|
1123
|
+
} else {
|
|
1124
|
+
m = sc.modelRoot * p.model;
|
|
1125
|
+
}
|
|
1126
|
+
let world = m * vec4<f32>(aPos, 1.0);
|
|
1127
|
+
out.clipPos = sc.viewProj * world;
|
|
1128
|
+
out.worldPos = world.xyz;
|
|
1129
|
+
out.instIdx = instIdx;
|
|
1130
|
+
return out;
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
@fragment
|
|
1134
|
+
fn fsPick(in: PickVsOut) -> @location(0) vec4<f32> {
|
|
1135
|
+
let p = parts[in.instIdx];
|
|
1136
|
+
let secOn = (sc.flags.w & 2u) != 0u && (p.flags & 64u) == 0u;
|
|
1137
|
+
if (secOn && dot(in.worldPos, sc.sectionPlane.xyz) > sc.sectionPlane.w) {
|
|
1138
|
+
discard;
|
|
1139
|
+
}
|
|
1140
|
+
let id = p.pickId;
|
|
1141
|
+
return vec4<f32>(
|
|
1142
|
+
f32(id & 255u) / 255.0,
|
|
1143
|
+
f32((id >> 8u) & 255u) / 255.0,
|
|
1144
|
+
f32((id >> 16u) & 255u) / 255.0,
|
|
1145
|
+
1.0,
|
|
1146
|
+
);
|
|
1147
|
+
}
|
|
1148
|
+
`,Wu=`
|
|
1149
|
+
struct ShadowSliceUniforms {
|
|
1150
|
+
lightVP: mat4x4<f32>,
|
|
1151
|
+
modelRoot: mat4x4<f32>,
|
|
1152
|
+
biasRay: vec4<f32>,
|
|
1153
|
+
sectionPlane: vec4<f32>,
|
|
1154
|
+
flags: vec4<u32>,
|
|
1155
|
+
};
|
|
1156
|
+
|
|
1157
|
+
struct PartInstance {
|
|
1158
|
+
model: mat4x4<f32>,
|
|
1159
|
+
baseColor: vec4<f32>,
|
|
1160
|
+
pbr: vec4<f32>,
|
|
1161
|
+
emissive: vec4<f32>,
|
|
1162
|
+
aux: vec2<f32>,
|
|
1163
|
+
flags: u32,
|
|
1164
|
+
pickId: u32,
|
|
1165
|
+
};
|
|
1166
|
+
|
|
1167
|
+
@group(0) @binding(0) var<uniform> shd: ShadowSliceUniforms;
|
|
1168
|
+
@group(0) @binding(1) var<storage, read> parts: array<PartInstance>;
|
|
1169
|
+
|
|
1170
|
+
struct ShadowDepthOut {
|
|
1171
|
+
@builtin(position) clipPos: vec4<f32>,
|
|
1172
|
+
@location(0) worldPos: vec3<f32>,
|
|
1173
|
+
@location(1) @interpolate(flat) instIdx: u32,
|
|
1174
|
+
};
|
|
1175
|
+
|
|
1176
|
+
@vertex
|
|
1177
|
+
fn vsShadowDepth(
|
|
1178
|
+
@location(0) aPos: vec3<f32>,
|
|
1179
|
+
@location(1) aNormal: vec3<f32>,
|
|
1180
|
+
@builtin(instance_index) instIdx: u32,
|
|
1181
|
+
) -> ShadowDepthOut {
|
|
1182
|
+
let p = parts[instIdx];
|
|
1183
|
+
var out: ShadowDepthOut;
|
|
1184
|
+
if ((p.flags & 128u) != 0u || (p.flags & 1024u) == 0u) {
|
|
1185
|
+
out.clipPos = vec4<f32>(2.0, 2.0, 2.0, 1.0);
|
|
1186
|
+
out.worldPos = vec3<f32>(0.0);
|
|
1187
|
+
out.instIdx = instIdx;
|
|
1188
|
+
return out;
|
|
1189
|
+
}
|
|
1190
|
+
var m: mat4x4<f32>;
|
|
1191
|
+
if ((p.flags & 1u) != 0u) {
|
|
1192
|
+
m = p.model;
|
|
1193
|
+
} else {
|
|
1194
|
+
m = shd.modelRoot * p.model;
|
|
1195
|
+
}
|
|
1196
|
+
var wp = m * vec4<f32>(aPos, 1.0);
|
|
1197
|
+
let wn = m[0].xyz * aNormal.x + m[1].xyz * aNormal.y + m[2].xyz * aNormal.z;
|
|
1198
|
+
let nl = length(wn);
|
|
1199
|
+
if (nl > 1e-5 && shd.biasRay.w > 0.0) {
|
|
1200
|
+
let un = wn / nl;
|
|
1201
|
+
wp = vec4<f32>(
|
|
1202
|
+
wp.xyz + un * (shd.biasRay.w * max(1.0 - abs(dot(un, shd.biasRay.xyz)), 0.15)),
|
|
1203
|
+
1.0,
|
|
1204
|
+
);
|
|
1205
|
+
}
|
|
1206
|
+
out.clipPos = shd.lightVP * wp;
|
|
1207
|
+
out.worldPos = wp.xyz;
|
|
1208
|
+
out.instIdx = instIdx;
|
|
1209
|
+
return out;
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
@fragment
|
|
1213
|
+
fn fsShadowDepth(in: ShadowDepthOut) {
|
|
1214
|
+
let p = parts[in.instIdx];
|
|
1215
|
+
if (shd.flags.x != 0u && (p.flags & 64u) == 0u && dot(in.worldPos, shd.sectionPlane.xyz) > shd.sectionPlane.w) {
|
|
1216
|
+
discard;
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
`,lh=1,br=8,My=16,Ay=32,vc=64,Ty=128,_y=1,Mh=2,bc=4,Pr=16,Ey=1,Qi=1,Qn=2,Xu=4,Rr=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),qt=null,Xt=null,Zn=!1,Qt="bgra8unorm",pc=null,yc=new WeakMap;function vt(e){try{e()}catch{}}function uh(e){return Math.max(16,e+3&-4)}function gc(){let e=globalThis.navigator?.gpu;return e&&typeof e.requestAdapter=="function"?e:null}function dh(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.createBuffer=="function"&&typeof t.createTexture=="function"&&typeof t.createSampler=="function"&&typeof t.createRenderBundleEncoder=="function"&&typeof t.createRenderPipeline=="function"}function qr(){if(qt)return Promise.resolve(qt);let e=He(),t=e.webgpuDeviceProvider?.peekDevice?.();return dh(t)?(qt=t,Qt=e.webgpuDeviceProvider?.getCanvasFormat?.()||Qt,Promise.resolve(t)):Zn?Promise.resolve(null):Xt||(e.webgpuDeviceProvider&&e.webgpuDeviceProvider!==Ah?(Xt=e.webgpuDeviceProvider.acquireDevice().then(r=>(Xt=null,dh(r)?(qt=r,Qt=e.webgpuDeviceProvider?.getCanvasFormat?.()||Qt,r):qu())).catch(()=>(Xt=null,qu())),Xt):qu())}function qu(){let e=gc();if(!e)return Zn=!0,Promise.resolve(null);try{Qt=e.getPreferredCanvasFormat?.()||"bgra8unorm"}catch{Qt="bgra8unorm"}return Xt=e.requestAdapter({powerPreference:"high-performance"}).then(async t=>{if(!t)return Zn=!0,Xt=null,null;let r=t.limits,i={};for(let[a,s]of[["maxStorageBufferBindingSize",134217728],["maxBufferSize",268435456]])(r?.[a]??0)>s&&(i[a]=r[a]);let n=await(i.maxBufferSize||i.maxStorageBufferBindingSize?t.requestDevice({requiredLimits:i}).catch(()=>t.requestDevice()):t.requestDevice());return qt=n,Xt=null,n.lost?.then?.(()=>{qt===n&&(qt=null,Xt=null,Zn=!1,pc?.onDeviceLost(n))}),n}).catch(()=>(Zn=!0,Xt=null,null)),Xt}var Ah={acquireDevice:()=>qr(),peekDevice:()=>qt,getCanvasFormat:()=>Qt};function Th(e,t="bgra8unorm"){qt=e,Xt=null,Zn=e===null,Qt=t}function _h(){qt=null,Xt=null,Zn=!1,Qt="bgra8unorm"}function Ju(e){let t=String(e??"").trim().toLowerCase();return t==="webgpu"||t==="webgl2"?t:"auto"}function ky(e){let t=e.container?.getAttribute?.("renderer")??e.renderer??"auto";return Ju(t)}function Ry(e){let t=e.container,r=t?.hasAttribute?.("bloom")?t.getAttribute?.("bloom")??"":t?.getAttribute?.("bloom")??null;if(r!==null&&!e.stereoSBS){let s=r.trim().toLowerCase();if(s===""||s==="true"||s!=="false"&&s!=="0"&&s!=="none"&&Number(s)>0)return!0}let i=t?.hasAttribute?.("outline")?t.getAttribute?.("outline")??"":t?.getAttribute?.("outline")??null;if(i!==null){let s=i.trim().toLowerCase();if(s!=="false"&&s!=="0"&&s!=="none")return!0}let n=t?.hasAttribute?.("outline-selected")?t.getAttribute?.("outline-selected"):null;if(n!==null&&n!=="false"&&e.selectedMeshName||e.skyboxTexture)return!0;let a=[e.backdropMeshes??[],e.meshes??[]];for(let s of a)for(let o of s){if(o.visible===!1)continue;let l=o.extras?.xr??o.userData?.xr;if(l&&(l.bloom||l.outline||l.splatUrl||l.splat))return!0;for(let c of o.primitives??[])if(c.isTransmissive||c.customProgram&&e.renderProg&&c.customProgram!==e.renderProg&&!(He().tslWgslCompiler&&He().tslMaterialResolver?.(e,c.materialIndex))||c.pluginData?.morph||c.pluginData?.skinning||c.instanceCount!==void 0)return!0}return!1}function xc(e,t=!!(qt||gc())){let r=e;if(!r||r.xrSessionActive)return"webgl2";let i=ky(r);if(i==="webgl2"||!t)return"webgl2";let n=!1;for(let a of[r.backdropMeshes??[],r.meshes??[]]){for(let s of a){if(s.visible===!1)continue;let o=s.extras?.xr??s.userData?.xr;if(!(o?.splatUrl||o?.splat)){for(let l of s.primitives??[])if(l.positions&&l.positions.length>=3){n=!0;break}if(n)break}}if(n)break}return!n||i==="auto"&&Ry(r)?"webgl2":"webgpu"}function fh(e){let t=yc.get(e);if(t)return t;let r=e.createBindGroupLayout({entries:[{binding:0,visibility:Qi|Qn,buffer:{type:"uniform"}},{binding:1,visibility:Qi|Qn,buffer:{type:"read-only-storage"}},{binding:2,visibility:Qn,sampler:{type:"filtering"}},{binding:3,visibility:Qn,texture:{sampleType:"float"}},{binding:4,visibility:Qn,sampler:{type:"comparison"}},{binding:5,visibility:Qn,texture:{sampleType:"depth",viewDimension:"2d-array"}}]}),i=e.createBindGroupLayout({entries:[0,1,2,3,4].map(C=>({binding:C,visibility:Qn,texture:{sampleType:"float"}}))}),n=e.createBindGroupLayout({entries:[{binding:0,visibility:Qi|Qn,buffer:{type:"uniform"}}]}),a=e.createBindGroupLayout({entries:[{binding:0,visibility:Qi|Qn,buffer:{type:"uniform"}},{binding:1,visibility:Qi|Qn,buffer:{type:"read-only-storage"}}]}),s=e.createPipelineLayout({bindGroupLayouts:[r,i]}),o=e.createPipelineLayout({bindGroupLayouts:[r,i,n]}),l=e.createPipelineLayout({bindGroupLayouts:[r]}),c=e.createPipelineLayout({bindGroupLayouts:[a]}),f=e.createPipelineLayout({bindGroupLayouts:[a,n]}),m=e.createShaderModule({code:Ji}),h=e.createShaderModule({code:dc}),p=e.createShaderModule({code:Wu}),g=e.createShaderModule({code:fc}),x=e.createSampler({magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",addressModeU:"repeat",addressModeV:"repeat"}),v=e.createSampler({compare:"less-equal",magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),y=e.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"rgba8unorm",usage:bc|Mh|Pr});vt(()=>e.queue.writeTexture?.({texture:y},new Uint8Array([255,255,255,255]),{bytesPerRow:256,rowsPerImage:1},{width:1,height:1,depthOrArrayLayers:1}));let A=y.createView(),b=e.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"depth24plus",usage:bc|Pr}),w=b.createView({dimension:"2d-array",baseArrayLayer:0,arrayLayerCount:1}),S=e.createBindGroup({layout:i,entries:[0,1,2,3,4].map(C=>({binding:C,resource:A}))}),E=e.createRenderPipeline({layout:l,vertex:{module:g,entryPoint:"vsPick",buffers:[{arrayStride:32,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},fragment:{module:g,entryPoint:"fsPick",targets:[{format:"rgba8unorm"}]},primitive:{topology:"triangle-list",cullMode:"none"},depthStencil:{format:"depth24plus",depthWriteEnabled:!0,depthCompare:"less-equal"},multisample:{count:1}}),N=e.createRenderPipeline({layout:c,vertex:{module:p,entryPoint:"vsShadowDepth",buffers:[{arrayStride:32,attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x3"}]}]},fragment:{module:p,entryPoint:"fsShadowDepth",targets:[]},primitive:{topology:"triangle-list",cullMode:"none"},depthStencil:{format:"depth24plus",depthWriteEnabled:!0,depthCompare:"less-equal",depthBias:2,depthBiasSlopeScale:1.5},multisample:{count:1}});return t={sceneBgl:r,matBgl:i,tslBgl:n,shadowSliceBgl:a,scenePipeLayout:s,tslScenePipeLayout:o,auxPipeLayout:l,shadowDepthPipeLayout:c,tslShadowDepthPipeLayout:f,shaderMod:m,shadowMod:h,shadowDepthMod:p,pickMod:g,pickPipeline:E,shadowDepthPipeline:N,sampler:x,shadowSampler:v,whiteTex:y,whiteView:A,dummyShadowTex:b,dummyShadowView:w,defaultMatBg:S,byFormat:new Map,tslShaders:new Map,tslPipelinesByFormat:new Map,texCache:new WeakMap,ownedTextures:new Set([y,b])},yc.set(e,t),t}function Ly(e,t,r,i){let n=t.tslShaders.get(r);if(n)return n;let a=He().tslWgslCompiler;if(!a)return null;let s=a(i,Ji,Wu);if(!s)return null;let o=e.createShaderModule({code:s.pbrWgsl}),l=null,c=null;return s.shadowDepthWgsl&&(l=e.createShaderModule({code:s.shadowDepthWgsl}),c=e.createRenderPipeline({layout:t.tslShadowDepthPipeLayout,vertex:{module:l,entryPoint:"vsShadowDepth",buffers:[{arrayStride:32,attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x3"},{shaderLocation:2,offset:24,format:"float32x2"}]}]},fragment:{module:l,entryPoint:"fsShadowDepth",targets:[]},primitive:{topology:"triangle-list",cullMode:"none"},depthStencil:{format:"depth24plus",depthWriteEnabled:!0,depthCompare:"less-equal",depthBias:2,depthBiasSlopeScale:1.5},multisample:{count:1}})),n={pbrMod:o,shadowDepthMod:l,shadowDepthPipe:c},t.tslShaders.set(r,n),n}var Py=[{arrayStride:32,attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x3"},{shaderLocation:2,offset:24,format:"float32x2"}]}];function Eh(e,t,r,i,n){let a=s=>e.createRenderPipeline({layout:t,vertex:{module:r,entryPoint:"vsMain",buffers:Py},fragment:{module:r,entryPoint:"fsMain",targets:[s?{format:i,blend:{color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}:{format:i}]},primitive:{topology:"triangle-list",cullMode:"none"},depthStencil:{format:"depth24plus",depthWriteEnabled:!s,depthCompare:"less-equal"},multisample:{count:n}});return{opaque:a(!1),blend:a(!0)}}function Iy(e,t,r,i,n,a){let s=t.tslShaders.get(r);if(!s)return null;let o=`${r}:${i}:${n}`,l=t.tslPipelinesByFormat.get(o);return l||(l=Eh(e,t.tslScenePipeLayout,s.pbrMod,i,n),t.tslPipelinesByFormat.set(o,l)),a?l.blend:l.opaque}function kh(e,t,r,i){let n=`${r}:${i}`,a=t.byFormat.get(n);if(a)return a;let{opaque:s,blend:o}=Eh(e,t.scenePipeLayout,t.shaderMod,r,i),l=e.createRenderPipeline({layout:t.auxPipeLayout,vertex:{module:t.shadowMod,entryPoint:"vsShadow"},fragment:{module:t.shadowMod,entryPoint:"fsShadow",targets:[{format:r,blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-strip",cullMode:"none"},depthStencil:{format:"depth24plus",depthWriteEnabled:!1,depthCompare:"less-equal"},multisample:{count:i}});return a={opaque:s,blend:o,shadow:l},t.byFormat.set(n,a),a}function Rh(e){if(!e||typeof e!="object")return null;let t=e,r=Math.floor(t.naturalWidth||t.videoWidth||t.width||0),i=Math.floor(t.naturalHeight||t.videoHeight||t.height||0);return r>0&&i>0?[r,i]:null}function Lr(e){return!e||typeof e!="object"?null:e.__gpuImageSource||(Rh(e)?e:null)}function Xr(e,t,r){if(!r)return{view:t.whiteView,src:null,valid:!1};let i=Lr(r),n=t.texCache.get(r);if(n&&n.src===i)return{view:n.view,src:i,valid:i!==null};if(!i)return{view:t.whiteView,src:null,valid:!1};let a=Rh(i);if(!a)return{view:t.whiteView,src:null,valid:!1};n&&(t.ownedTextures.delete(n.tex),vt(()=>n.tex.destroy()));let[s,o]=a,l=e.createTexture({size:{width:s,height:o,depthOrArrayLayers:1},format:"rgba8unorm",usage:bc|Mh|Pr}),c=!1;if(typeof e.queue.copyExternalImageToTexture=="function"&&vt(()=>{e.queue.copyExternalImageToTexture({source:i},{texture:l},{width:s,height:o,depthOrArrayLayers:1}),c=!0}),!c&&typeof e.queue.writeTexture=="function"&&i.data){let m=i.data,h=Math.ceil(s*4/256)*256,p=new Uint8Array(h*o);for(let g=0;g<o;g++)p.set(m.subarray(g*s*4,(g+1)*s*4),g*h);vt(()=>{e.queue.writeTexture({texture:l},p,{bytesPerRow:h,rowsPerImage:o},{width:s,height:o,depthOrArrayLayers:1}),c=!0})}if(!c)return vt(()=>l.destroy()),{view:t.whiteView,src:null,valid:!1};let f=l.createView();return t.ownedTextures.add(l),t.texCache.set(r,{tex:l,view:f,src:i}),{view:f,src:i,valid:!0}}function Lh(e,t,r){let i=Xr(e,t,r.texture),n=Xr(e,t,r.metallicRoughnessTexture),a=Xr(e,t,r.normalTexture),s=Xr(e,t,r.occlusionTexture),o=Xr(e,t,r.emissiveTexture),l=0;return i.valid&&(l|=2),n.valid&&(l|=4),a.valid&&(l|=8),s.valid&&(l|=16),o.valid&&(l|=32),l===0?{bg:t.defaultMatBg,texFlags:0,src0:i.src,src1:n.src,src2:a.src,src3:s.src,src4:o.src}:{bg:e.createBindGroup({layout:t.matBgl,entries:[{binding:0,resource:i.view},{binding:1,resource:n.view},{binding:2,resource:a.view},{binding:3,resource:s.view},{binding:4,resource:o.view}]}),texFlags:l,src0:i.src,src1:n.src,src2:a.src,src3:s.src,src4:o.src}}function Cy(e,t){let r=e,i=[],n=()=>{if(!t.visible||!t.canvas)return null;try{let s=document.createElement("canvas"),o=s.width=t.canvas.width||e.width||1,l=s.height=t.canvas.height||e.height||1,c=s.getContext?.("2d");if(!c)return null;c.drawImage(e,0,0,o,l),c.drawImage(t.canvas,0,0,o,l);let f=e.parentElement?.querySelector?.("canvas.xr-live-webgpu-splat");return f&&f.style?.display!=="none"&&c.drawImage(f,0,0,o,l),s}catch{return null}},a=(s,o)=>{let l=r[s];if(typeof l!="function")return;let c=Object.prototype.hasOwnProperty.call(e,s);r[s]=o(l.bind(e)),i.push(()=>{c?r[s]=l:delete r[s]})};return a("toDataURL",s=>(o,l)=>{let c=n();return c?c.toDataURL(o,l):s(o,l)}),a("toBlob",s=>(o,l,c)=>{let f=n();f&&typeof f.toBlob=="function"?f.toBlob(o,l,c):s(o,l,c)}),()=>i.forEach(s=>s())}function mh(e){return Bu(e)}function Ny(e,t){let r=Number(e.shadowIntensity??0);if(!(r>0)||t||!e.bounds)return null;let i=e.bounds,n=Math.max(0,Math.min(1,Number(e.shadowSoftness??.5))),a=e.modelRootMatrix??Rr,s=i.center[0],o=i.center[1],l=i.center[2],c=Math.max(.02,(i.max[0]-i.min[0])*.5),f=Math.max(.02,(i.max[1]-i.min[1])*.5),m=Math.max(.02,(i.max[2]-i.min[2])*.5),h=a[0]*s+a[4]*o+a[8]*l+a[12],p=a[1]*s+a[5]*o+a[9]*l+a[13],g=a[2]*s+a[6]*o+a[10]*l+a[14],x=Math.abs(a[0])*c+Math.abs(a[4])*f+Math.abs(a[8])*m,v=Math.abs(a[1])*c+Math.abs(a[5])*f+Math.abs(a[9])*m,y=Math.abs(a[2])*c+Math.abs(a[6])*f+Math.abs(a[10])*m,A=1.35+n*.5;return{centerX:h,floorY:p-v-5e-4,centerZ:g,halfExtentX:Math.max(.05,x*A),halfExtentZ:Math.max(.05,y*A),intensity:Math.min(1,r),softness:n}}function Ph(e){return e.environmentTexture&&typeof e.environmentTexture=="object"?e.environmentTexture:e.environmentSource&&typeof e.environmentSource=="object"?e.environmentSource:null}function ko(e){if(e){vt(()=>e.vertexBuf.destroy()),vt(()=>e.indexBuf?.destroy()),vt(()=>e.partBuf.destroy()),vt(()=>e.uniformBuf.destroy()),vt(()=>e.pickUniformBuf?.destroy());for(let t of e.shadowSliceBufs)vt(()=>t?.destroy());for(let t of e.tslSlots.values())vt(()=>t.buf.destroy())}}function Ih(e,t,r,i,n){let a=He().tslMaterialResolver;if(!a||n===void 0||n<0)return{tslHash:null,tslBg:null,tslShadowPipe:null};let s=a(r,n);if(!s)return{tslHash:null,tslBg:null,tslShadowPipe:null};let o=Ly(e,t,s.hash,s.graph);if(!o)return{tslHash:null,tslBg:null,tslShadowPipe:null};let l=i.get(n);if(!l||l.hash!==s.hash){vt(()=>l?.buf.destroy());let c=e.createBuffer({size:s.buf68.byteLength,usage:vc|br});e.queue.writeBuffer(c,0,s.buf68);let f=e.createBindGroup({layout:t.tslBgl,entries:[{binding:0,resource:{buffer:c}}]});l={buf:c,bg:f,hash:s.hash,usesVertexPosition:s.usesVertexPosition,uploadedVersion:s.version},i.set(n,l)}return{tslHash:s.hash,tslBg:l.bg,tslShadowPipe:o.shadowDepthPipe}}function Yu(e){vt(()=>e.shadowTex?.destroy()),e.shadowTex=null,e.shadowArrayView=null,e.shadowLayerViews=[],e.shadowSize=0,e.shadowLayers=0,e.lastShadowDigest=0}function mc(e){vt(()=>e.msaaTex?.destroy()),vt(()=>e.depthTex?.destroy()),e.msaaTex=null,e.msaaView=null,e.depthTex=null,e.depthView=null,e.width=0,e.height=0}function hc(e){vt(()=>e.pickColorTex?.destroy()),vt(()=>e.pickDepthTex?.destroy()),vt(()=>e.pickReadBuf?.destroy()),e.pickColorTex=null,e.pickColorView=null,e.pickDepthTex=null,e.pickDepthView=null,e.pickReadBuf=null,e.pickBusy=!1}function hh(e,t,r){if(e.backdropCount!==t.length||e.meshRefs.length!==t.length+r.length)return!1;for(let i=0;i<t.length;i++)if(e.meshRefs[i]!==t[i])return!1;for(let i=0;i<r.length;i++)if(e.meshRefs[t.length+i]!==r[i])return!1;for(let i of e.groups){if(i.prim.positions!==i.posRef||(i.prim.indices??null)!==i.idxRef)return!1;let n=i.mesh.instanceMatrices;if((n&&n.length>=16?n.length>>4:i.prim.instanceCount!==void 0&&i.prim.translations?i.prim.instanceCount:1)!==i.instanceCount)return!1}return!0}function ph(e,t,r,i){let n=i?r.backdropMeshes??[]:[],a=r.meshes??[],s=[...n,...a],o=0,l=0,c=0,f=[],m=new Map;for(let N=0;N<s.length;N++){let C=s[N],_=C.extras?.xr??C.userData?.xr;if(_?.splatUrl||_?.splat)continue;let P=N<n.length,R=P||C.isPluginMesh||_?.pointerEvents==="none"?-1:N-n.length,$=C.instanceMatrices;for(let F of C.primitives??[]){let V=F.positions;if(!V||V.length<3)continue;let Y=Math.floor(V.length/3);if(Y<=0)continue;let J=F.indices??null,re=!!(J&&J.length>0),Q=re?J.length:Math.min(Y,F.indexCount??Y);if(Q<=0)continue;let ee=$&&$.length>=16?$.length>>4:F.instanceCount!==void 0&&F.translations?Math.max(1,F.instanceCount|0):1,k=Lh(e,t,F),G=Ih(e,t,r,m,F.materialIndex);f.push({mesh:C,prim:F,posRef:V,idxRef:J,meshIndex:R,isBackdrop:P,firstVertex:o,vertexCount:Y,indexed:re,firstIndex:l,indexCount:Q,firstInstance:c,instanceCount:ee,isBlend:F.alphaMode==="BLEND"||(F.baseColor?.[3]??1)<.999,matIndex:F.materialIndex,tslHash:G.tslHash,tslBg:G.tslBg,tslShadowPipe:G.tslShadowPipe,tex0:F.texture??null,tex1:F.metallicRoughnessTexture??null,tex2:F.normalTexture??null,tex3:F.occlusionTexture??null,tex4:F.emissiveTexture??null,src0:k.src0,src1:k.src1,src2:k.src2,src3:k.src3,src4:k.src4,matBg:k.bg}),o+=Y,re&&(l+=Q),c+=ee}}if(f.length===0||o===0||c===0)return null;let h=new Float32Array(o*8),p=l>0?new Uint32Array(l):null;for(let N of f){let C=N.posRef,_=N.prim.normals,P=N.prim.uvs,R=N.vertexCount,$=N.firstVertex*8;for(let F=0;F<R;F++){let V=F*3,Y=F*2;h[$]=C[V],h[$+1]=C[V+1],h[$+2]=C[V+2],_&&V+2<_.length&&(h[$+3]=_[V],h[$+4]=_[V+1],h[$+5]=_[V+2]),P&&Y+1<P.length&&(h[$+6]=P[Y],h[$+7]=P[Y+1]),$+=8}if(N.indexed&&p&&N.idxRef){let F=N.idxRef,V=N.firstIndex;for(let Y=0;Y<N.indexCount;Y++)p[V+Y]=F[Y]}}let g=e.createBuffer({size:uh(h.byteLength),usage:Ay|br});e.queue.writeBuffer(g,0,h);let x=null;p&&(x=e.createBuffer({size:uh(p.byteLength),usage:My|br}),e.queue.writeBuffer(x,0,p));let v=Math.max(128,c*128),y=e.createBuffer({size:v,usage:Ty|br}),A=e.createBuffer({size:800,usage:vc|br}),b=Ph(r),w=Xr(e,t,b),S=e.createBindGroup({layout:t.sceneBgl,entries:[{binding:0,resource:{buffer:A}},{binding:1,resource:{buffer:y}},{binding:2,resource:t.sampler},{binding:3,resource:w.view},{binding:4,resource:t.shadowSampler},{binding:5,resource:t.dummyShadowView}]}),E=new ArrayBuffer(v);return{meshRefs:s,backdropCount:n.length,groups:f,totalVertices:o,totalIndices:l,totalInstances:c,vertexBuf:g,indexBuf:x,partBuf:y,uniformBuf:A,pickUniformBuf:null,pickSceneBg:null,cpuPartBuf:E,cpuPartF32:new Float32Array(E),cpuPartU32:new Uint32Array(E),gpuPartU32:new Uint32Array(v>>>2),partsUploadedOnce:!1,envSourceRef:Lr(b),envView:w.view,shadowViewRef:t.dummyShadowView,sceneBg:S,tslSlots:m,tslVertexDirty:!1,shadowSliceBufs:[null,null,null,null],shadowSliceBgs:[null,null,null,null],shadowBundles:[null,null,null,null],opaqueBundle:null,blendBundle:null,pickBundle:null,bundleFormat:"",bundleSamples:0,bundlesDirty:!0}}function Dy(e,t,r,i,n){let a=kh(e,t,i,n),s=(o,l)=>{let c=r.groups.filter(x=>x.isBlend===o);if(c.length===0)return null;let f=o?c:[...c.filter(x=>x.isBackdrop),...c.filter(x=>!x.isBackdrop&&x.matBg===t.defaultMatBg),...c.filter(x=>!x.isBackdrop&&x.matBg!==t.defaultMatBg)],m=e.createRenderBundleEncoder({colorFormats:[i],depthStencilFormat:"depth24plus",sampleCount:n});m.setPipeline(l),m.setBindGroup(0,r.sceneBg),m.setVertexBuffer(0,r.vertexBuf),r.indexBuf&&m.setIndexBuffer(r.indexBuf,"uint32");let h=l,p=null,g=null;for(let x of f){let v=x.tslHash?Iy(e,t,x.tslHash,i,n,o)??l:l;v!==h&&(m.setPipeline(v),h=v),x.matBg!==p&&(m.setBindGroup(1,x.matBg),p=x.matBg),x.tslBg&&x.tslBg!==g&&(m.setBindGroup(2,x.tslBg),g=x.tslBg),x.indexed?m.drawIndexed(x.indexCount,x.instanceCount,x.firstIndex,x.firstVertex,x.firstInstance):m.draw(x.indexCount,x.instanceCount,x.firstVertex,x.firstInstance)}return m.finish()};r.opaqueBundle=s(!1,a.opaque),r.blendBundle=s(!0,a.blend),r.pickBundle=null,r.bundleFormat=i,r.bundleSamples=n,r.bundlesDirty=!1}function Uy(e,t,r){if(r.pickUniformBuf||(r.pickUniformBuf=e.createBuffer({size:800,usage:vc|br})),r.pickSceneBg||(r.pickSceneBg=e.createBindGroup({layout:t.sceneBgl,entries:[{binding:0,resource:{buffer:r.pickUniformBuf}},{binding:1,resource:{buffer:r.partBuf}},{binding:2,resource:t.sampler},{binding:3,resource:t.whiteView},{binding:4,resource:t.shadowSampler},{binding:5,resource:t.dummyShadowView}]})),r.pickBundle)return r.pickBundle;let i=e.createRenderBundleEncoder({colorFormats:["rgba8unorm"],depthStencilFormat:"depth24plus",sampleCount:1});i.setPipeline(t.pickPipeline),i.setBindGroup(0,r.pickSceneBg),i.setVertexBuffer(0,r.vertexBuf),r.indexBuf&&i.setIndexBuffer(r.indexBuf,"uint32");for(let n of r.groups)n.meshIndex<0||(n.indexed?i.drawIndexed(n.indexCount,n.instanceCount,n.firstIndex,n.firstVertex,n.firstInstance):i.draw(n.indexCount,n.instanceCount,n.firstVertex,n.firstInstance));return r.pickBundle=i.finish(),r.pickBundle}function By(e,t,r,i){if(i<0||i>=Ao)return null;if(r.shadowSliceBufs[i]||(r.shadowSliceBufs[i]=e.createBuffer({size:176,usage:vc|br})),r.shadowSliceBgs[i]||(r.shadowSliceBgs[i]=e.createBindGroup({layout:t.shadowSliceBgl,entries:[{binding:0,resource:{buffer:r.shadowSliceBufs[i]}},{binding:1,resource:{buffer:r.partBuf}}]})),r.shadowBundles[i])return r.shadowBundles[i];let n=e.createRenderBundleEncoder({colorFormats:[],depthStencilFormat:"depth24plus",sampleCount:1});n.setPipeline(t.shadowDepthPipeline),n.setBindGroup(0,r.shadowSliceBgs[i]),n.setVertexBuffer(0,r.vertexBuf),r.indexBuf&&n.setIndexBuffer(r.indexBuf,"uint32");let a=t.shadowDepthPipeline,s=null;for(let l of r.groups){if(l.isBackdrop||l.isBlend||l.prim.isTransmissive)continue;let c=l.tslShadowPipe??t.shadowDepthPipeline;c!==a&&(n.setPipeline(c),a=c),l.tslShadowPipe&&l.tslBg&&l.tslBg!==s&&(n.setBindGroup(1,l.tslBg),s=l.tslBg),l.indexed?n.drawIndexed(l.indexCount,l.instanceCount,l.firstIndex,l.firstVertex,l.firstInstance):n.draw(l.indexCount,l.instanceCount,l.firstVertex,l.firstInstance)}let o=n.finish();return r.shadowBundles[i]=o,o}var Ku=rt(),Wr=rt();function bh(e,t,r,i,n,a,s){let o=Ph(r),l=Lr(o),c=i.envView;if(l!==i.envSourceRef){let b=Xr(e,t,o);i.envSourceRef=b.src,c=b.view}let f=s??i.shadowViewRef;(c!==i.envView||f!==i.shadowViewRef)&&(i.envView=c,i.shadowViewRef=f,i.sceneBg=e.createBindGroup({layout:t.sceneBgl,entries:[{binding:0,resource:{buffer:i.uniformBuf}},{binding:1,resource:{buffer:i.partBuf}},{binding:2,resource:t.sampler},{binding:3,resource:c},{binding:4,resource:t.shadowSampler},{binding:5,resource:f}]}),i.bundlesDirty=!0);let m=i.cpuPartF32,h=i.cpuPartU32,p=r.selectedMeshNames,g=r.selectedMeshName||"",x=r.modelRootMatrix??Rr,v=n.eye==="none"&&!r.stereoSBS;i.tslVertexDirty=!1;let y=He().tslMaterialResolver;if(y)for(let[b,w]of i.tslSlots.entries()){let S=y(r,b);S&&S.hash===w.hash&&S.version!==w.uploadedVersion&&(e.queue.writeBuffer(w.buf,0,S.buf68),w.uploadedVersion=S.version,w.usesVertexPosition&&(i.tslVertexDirty=!0))}for(let b of i.groups){let w=b.mesh,S=b.prim;if(S.materialIndex!==b.matIndex){b.matIndex=S.materialIndex;let D=Ih(e,t,r,i.tslSlots,S.materialIndex);(D.tslHash!==b.tslHash||D.tslBg!==b.tslBg||D.tslShadowPipe!==b.tslShadowPipe)&&(D.tslShadowPipe!==b.tslShadowPipe&&(i.tslVertexDirty=!0),b.tslHash=D.tslHash,b.tslBg=D.tslBg,b.tslShadowPipe=D.tslShadowPipe,i.bundlesDirty=!0,i.shadowBundles=[null,null,null,null])}let E=S.texture??null,N=S.metallicRoughnessTexture??null,C=S.normalTexture??null,_=S.occlusionTexture??null,P=S.emissiveTexture??null;if(E!==b.tex0||N!==b.tex1||C!==b.tex2||_!==b.tex3||P!==b.tex4||Lr(E)!==b.src0||Lr(N)!==b.src1||Lr(C)!==b.src2||Lr(_)!==b.src3||Lr(P)!==b.src4){let D=Lh(e,t,S);b.tex0=E,b.tex1=N,b.tex2=C,b.tex3=_,b.tex4=P,b.src0=D.src0,b.src1=D.src1,b.src2=D.src2,b.src3=D.src3,b.src4=D.src4,b.matBg!==D.bg&&(b.matBg=D.bg,i.bundlesDirty=!0)}let R=S.baseColor??[1,1,1,1],$=R[0]??1,F=R[1]??1,V=R[2]??1,Y=R[3]??1,J=S.alphaMode==="BLEND"||Y<.999;J!==b.isBlend&&(b.isBlend=J,i.bundlesDirty=!0,i.shadowBundles=[null,null,null,null]);let re=0;b.src0&&(re|=2),b.src1&&(re|=4),b.src2&&(re|=8),b.src3&&(re|=16),b.src4&&(re|=32),(b.isBackdrop||w.isPluginMesh)&&(re|=64),w.visible===!1&&(re|=128),a&&a.slices.length>0&&!b.isBackdrop&&!J&&!S.isTransmissive&&Gr(w,a.promoteAllCasters)&&(re|=1024),a&&a.slices.length>0&&!b.isBackdrop&&$i(w,a.promoteAllReceivers)&&(re|=2048);let Q=w.extras?.xr??w.userData?.xr,ee=Q?.stereo;ee==="sbs"?re|=256:ee==="ou"&&(re|=512);let k=v?Q?.billboard:void 0;(b.isBackdrop||w.worldSpace===!0||w.name==="__xr_reticle__"||k)&&(re|=1);let G=w.transform;if(k){b.isBackdrop||w.worldSpace===!0||w.name==="__xr_reticle__"?Ku.set(w.transform):at(Ku,x,w.transform);let D=Ku,z=Math.hypot(D[0],D[1],D[2])||1,O=Math.hypot(D[4],D[5],D[6])||1,X=Math.hypot(D[8],D[9],D[10])||1,se=k==="y"||k==="cylindrical"||k==="capsule",ce=n.eyePos[0]-D[12],pe=n.eyePos[2]-D[14],xe=Math.hypot(ce,pe),he=xe>1e-5?ce/xe:0,Ne=xe>1e-5?pe/xe:1;if(se)D[0]=Ne*z,D[1]=0,D[2]=-he*z,D[3]=0,D[4]=0,D[5]=O,D[6]=0,D[7]=0,D[8]=he*X,D[9]=0,D[10]=Ne*X,D[11]=0;else{let ge=n.view;D[0]=ge[0]*z,D[1]=ge[4]*z,D[2]=ge[8]*z,D[3]=0,D[4]=ge[1]*O,D[5]=ge[5]*O,D[6]=ge[9]*O,D[7]=0,D[8]=ge[2]*X,D[9]=ge[6]*X,D[10]=ge[10]*X,D[11]=0}G=D}let q=S.metallic??0,H=S.roughness??.5,te=S.clearcoat??0,Z=S.clearcoatRoughness??.04,ae=S.emissiveFactor,ie=ae?.[0]??0,de=ae?.[1]??0,me=ae?.[2]??0,Se=(p?p.has(w.name):g!==""&&w.name===g)?1:0,Fe=S.normalScale??1,_e=S.occlusionStrength??1,Le=b.meshIndex>=0?b.meshIndex+1>>>0:0,ne=w.instanceMatrices,Re=w.instanceColors,W=S.translations;for(let D=0;D<b.instanceCount;D++){let z=(b.firstInstance+D)*32,O=G;if(ne&&ne.length>=(D+1)*16)at(Wr,G,ne.subarray(D*16,D*16+16)),O=Wr;else if(W&&W.length>=(D+1)*3){Wr.set(G);let X=W[D*3],se=W[D*3+1],ce=W[D*3+2];Wr[12]+=G[0]*X+G[4]*se+G[8]*ce,Wr[13]+=G[1]*X+G[5]*se+G[9]*ce,Wr[14]+=G[2]*X+G[6]*se+G[10]*ce,O=Wr}for(let X=0;X<16;X++)m[z+X]=O[X];Re&&Re.length>=(D+1)*3?(m[z+16]=$*Re[D*3],m[z+17]=F*Re[D*3+1],m[z+18]=V*Re[D*3+2]):(m[z+16]=$,m[z+17]=F,m[z+18]=V),m[z+19]=Y,m[z+20]=q,m[z+21]=H,m[z+22]=te,m[z+23]=Z,m[z+24]=ie,m[z+25]=de,m[z+26]=me,m[z+27]=Se,m[z+28]=Fe,m[z+29]=_e,h[z+30]=re>>>0,h[z+31]=Le}}let A=i.totalInstances*32;if(!i.partsUploadedOnce)e.queue.writeBuffer(i.partBuf,0,h,0,A),i.gpuPartU32.set(h.subarray(0,A)),i.partsUploadedOnce=!0;else{let b=i.gpuPartU32,w=-1,S=-1;for(let E=0;E<A;E++)h[E]!==b[E]&&(w<0&&(w=E),S=E,b[E]=h[E]);if(w>=0){let E=S-w+1;e.queue.writeBuffer(i.partBuf,w*4,h,w,E)}}}function Fy(e,t,r,i,n,a){let s=Math.max(1,n),o=Math.max(1,a),l=(r+.5)/s*2-1,c=1-(i+.5)/o*2;for(let f=0;f<4;f++){let m=f*4,h=t[m],p=t[m+1],g=t[m+2],x=t[m+3];e[m]=s*(h-l*x),e[m+1]=o*(p-c*x),e[m+2]=g,e[m+3]=x}return e}var Zi=class{constructor(){this.states=new WeakMap,this.trackedViewers=new Set,this.renderedFrames=0,this.bundleRecordCount=0,this.shadowPassCount=0,this.shadowCacheHits=0}getState(e){let t=this.states.get(e);return t||(t={dev:null,canvas:null,ctx:null,configuredFormat:"",visible:!1,width:0,height:0,sampleCount:Xu,msaaTex:null,msaaView:null,depthTex:null,depthView:null,shadowTex:null,shadowArrayView:null,shadowLayerViews:[],shadowSize:0,shadowLayers:0,lastShadowDigest:0,pickColorTex:null,pickColorView:null,pickDepthTex:null,pickDepthView:null,pickReadBuf:null,pickBusy:!1,scene:null,unhookSnapshot:null,gen:0,uniformScratch:new ArrayBuffer(800),shadowSliceScratch:new ArrayBuffer(176)},this.states.set(e,t),this.trackedViewers.add(e)),t}ensureCanvas(e,t,r){let i=e.canvas??e.gl?.canvas;if(!i||typeof document>"u")return null;if(!t.canvas){let o=i.parentElement;if(!o||typeof o.insertBefore!="function")return null;let l=document.createElement("canvas");l.className="three-live-webgpu-scene",l.style&&(l.style.cssText="position:absolute;inset:0;width:100%;height:100%;display:block;pointer-events:none;z-index:0"),o.insertBefore(l,i.nextSibling);let c=l.getContext?.("webgpu");if(!c||typeof c.configure!="function")return vt(()=>l.remove?.()),null;t.canvas=l,t.ctx=c,t.visible=!0,t.unhookSnapshot=Cy(i,t)}let n=Math.max(1,i.width||1),a=Math.max(1,i.height||1),s=t.canvas.width!==n||t.canvas.height!==a;if(s&&(t.canvas.width=n,t.canvas.height=a),(t.dev!==r||t.configuredFormat!==Qt||s)&&(t.ctx.configure({device:r,format:Qt,alphaMode:"premultiplied"}),t.dev=r,t.configuredFormat=Qt),t.width!==n||t.height!==a||!t.depthTex){mc(t),t.width=n,t.height=a;let o=Xu,l=null;vt(()=>{l=r.createTexture({size:{width:n,height:a,depthOrArrayLayers:1},format:Qt,sampleCount:Xu,usage:Pr})}),l||(o=1);let c=r.createTexture({size:{width:n,height:a,depthOrArrayLayers:1},format:"depth24plus",sampleCount:o,usage:Pr});t.sampleCount=o,t.msaaTex=l,t.msaaView=l?l.createView():null,t.depthTex=c,t.depthView=c.createView()}return!t.visible&&t.canvas?.style&&(t.canvas.style.display="block",t.visible=!0),t.ctx}renderScene(e,t,r,i,n,a,s,o,l,c){let f={viewer:e,vp:t,proj:r,view:i,eyePos:n,toneMappingIndex:a,viewport:s,eye:o,clear:l,isAR:c},m=f.viewer,h=this.getState(f.viewer);if(!qt){if(!Zn&&!Xt){let G=h.gen;qr().then(q=>{q&&h.gen===G&&this.trackedViewers.has(f.viewer)&&vt(()=>f.viewer.render?.())})}return this.hideLayer(f.viewer),!1}let p=qt;if(xc(m,!0)!=="webgpu")return this.hideLayer(f.viewer),!1;h.dev&&h.dev!==p&&(ko(h.scene),h.scene=null,mc(h),Yu(h),hc(h));let g=this.ensureCanvas(m,h,p);if(!g)return!1;let x=fh(p),v=!f.isAR,y=v?m.backdropMeshes??[]:[],A=m.meshes??[];if((!h.scene||!hh(h.scene,y,A))&&(ko(h.scene),h.scene=ph(p,x,m,v),h.lastShadowDigest=0,!h.scene))return this.hideLayer(f.viewer),!1;let b=h.scene,w=Gi(m),S=x.dummyShadowView,E=w.slices.length;if(E>0){if(!h.shadowTex||h.shadowSize!==w.mapSize||h.shadowLayers<E){vt(()=>h.shadowTex?.destroy());let G=Math.max(h.shadowLayers,E),q=p.createTexture({size:{width:w.mapSize,height:w.mapSize,depthOrArrayLayers:G},format:"depth24plus",usage:Pr|bc});h.shadowTex=q,h.shadowSize=w.mapSize,h.shadowLayers=G,h.shadowArrayView=q.createView({dimension:"2d-array",baseArrayLayer:0,arrayLayerCount:G}),h.shadowLayerViews=[];for(let H=0;H<G;H++)h.shadowLayerViews.push(q.createView({dimension:"2d",baseArrayLayer:H,arrayLayerCount:1}));h.lastShadowDigest=0}S=h.shadowArrayView}bh(p,x,m,b,f,w,S),(b.bundlesDirty||b.bundleFormat!==Qt||b.bundleSamples!==h.sampleCount)&&(Dy(p,x,b,Qt,h.sampleCount),this.bundleRecordCount++);let N=w.sectionPlane??mh(m),C=Ny(m,f.isAR);Ki(h.uniformScratch,{vp:f.vp,modelRoot:m.modelRootMatrix??Rr,eyePos:f.eyePos,exposure:m.exposure??1,envIntensity:m.envIntensity??1,toneMappingIndex:f.toneMappingIndex,lights:m.lights??[],hasEnvMap:b.envSourceRef!==null,isRightEye:f.eye==="right",sectionPlane:N,contactShadow:C,shadowMap:E>0?{slices:w.slices,dirSlots:w.dirSlots,ptSlots:w.ptSlots}:null}),p.queue.writeBuffer(b.uniformBuf,0,h.uniformScratch);let _=g.getCurrentTexture().createView(),P=f.isAR?[0,0,0,0]:m.clearColor??[0,0,0,0],R=P[3]??0,$={r:(P[0]??0)*R,g:(P[1]??0)*R,b:(P[2]??0)*R,a:R},F=!!m.stereoSBS,V=h.sampleCount>1&&!!h.msaaView,Y=p.createCommandEncoder();if(E>0&&h.shadowTex)if(!b.tslVertexDirty&&h.lastShadowDigest===w.digest)this.shadowCacheHits++;else{h.lastShadowDigest=w.digest;let G=m.modelRootMatrix??Rr;for(let q of w.slices){let H=By(p,x,b,q.slot),te=b.shadowSliceBufs[q.slot],Z=h.shadowLayerViews[q.slot];if(!te||!Z)continue;ah(h.shadowSliceScratch,q.viewProj,G,q.rayDir,q.normalBiasWorld,N),p.queue.writeBuffer(te,0,h.shadowSliceScratch);let ae=Y.beginRenderPass({colorAttachments:[],depthStencilAttachment:{view:Z,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});H&&ae.executeBundles([H]),ae.end(),this.shadowPassCount++}}let J=Y.beginRenderPass({colorAttachments:[V?{view:h.msaaView,resolveTarget:_,loadOp:f.clear?"clear":"load",storeOp:F?"store":"discard",clearValue:$}:{view:_,loadOp:f.clear?"clear":"load",storeOp:"store",clearValue:$}],depthStencilAttachment:{view:h.depthView,depthClearValue:1,depthLoadOp:f.clear?"clear":"load",depthStoreOp:F?"store":"discard"}}),[re,Q,ee,k]=f.viewport;if(J.setViewport&&(re!==0||Q!==0||ee!==h.width||k!==h.height)){let G=Math.max(0,Math.min(h.width-1,re)),q=Math.max(0,Math.min(h.height-1,h.height-Q-k));J.setViewport(G,q,Math.max(1,Math.min(h.width-G,ee)),Math.max(1,Math.min(h.height-q,k)),0,1)}if(b.opaqueBundle&&J.executeBundles([b.opaqueBundle]),C){let G=kh(p,x,Qt,h.sampleCount);J.setPipeline(G.shadow),J.setBindGroup(0,b.sceneBg),J.draw(4,1,0,0)}return b.blendBundle&&J.executeBundles([b.blendBundle]),J.end(),p.queue.submit([Y.finish()]),this.renderedFrames++,!0}async pickMeshGPU(e,t,r,i){let n=e,a=n.meshes??[];if(a.length===0)return-1;let s=qt??await qr();if(!s||typeof s.createCommandEncoder!="function")return-1;let o=this.getState(e),l=o.gen,c=fh(s),f=n.backdropMeshes??[];if((!o.scene||!hh(o.scene,f,a))&&(ko(o.scene),o.scene=ph(s,c,n,!0),!o.scene))return-1;let m=o.scene,h=Math.max(1,n.canvas?.width||o.width||300),p=Math.max(1,n.canvas?.height||o.height||300),g=t;if(n.stereoSBS&&!n.xrSessionActive&&h>=2){let N=Math.max(1,Math.floor(h*.5)),C=t>=N,_=C?t-N:t,P=C?Math.max(1,h-N):N,R=(_+.5)/P*2-1;g=Math.floor((R*.5+1)*.5*h)}let x=Math.max(0,Math.min(h-1,Math.floor(g))),v=Math.max(0,Math.min(p-1,Math.floor(r))),y=rt();i?y.set(i):n.projMatrix&&n.viewMatrix?at(y,n.projMatrix,n.viewMatrix):y.set(Rr),bh(s,c,n,m,{viewer:e,vp:y,proj:n.projMatrix??Rr,view:n.viewMatrix??Rr,eyePos:[0,0,3],toneMappingIndex:0,viewport:[0,0,h,p],eye:"none",clear:!0,isAR:!1}),(!o.pickColorTex||!o.pickDepthTex)&&(hc(o),o.pickColorTex=s.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"rgba8unorm",usage:Pr|_y}),o.pickColorView=o.pickColorTex.createView(),o.pickDepthTex=s.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"depth24plus",usage:Pr}),o.pickDepthView=o.pickDepthTex.createView(),o.pickReadBuf=s.createBuffer({size:256,usage:br|lh}));let A=Fy(rt(),y,x,v,h,p),b=Uy(s,c,m),w=new ArrayBuffer(800);Ki(w,{vp:A,modelRoot:n.modelRootMatrix??Rr,eyePos:[0,0,0],exposure:1,envIntensity:1,toneMappingIndex:2,lights:[],hasEnvMap:!1,sectionPlane:mh(n)}),s.queue.writeBuffer(m.pickUniformBuf,0,w);let S=!!(o.pickReadBuf&&!o.pickBusy),E=S?o.pickReadBuf:s.createBuffer({size:256,usage:br|lh});S&&(o.pickBusy=!0);try{let N=s.createCommandEncoder(),C=N.beginRenderPass({colorAttachments:[{view:o.pickColorView,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}],depthStencilAttachment:{view:o.pickDepthView,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"discard"}});if(C.executeBundles([b]),C.end(),N.copyTextureToBuffer?.({texture:o.pickColorTex},{buffer:E,bytesPerRow:256,rowsPerImage:1},{width:1,height:1,depthOrArrayLayers:1}),s.queue.submit([N.finish()]),await E.mapAsync(Ey,0,4),o.gen!==l)return vt(()=>E.unmap()),-1;let _=new Uint8Array(E.getMappedRange(0,4)),P=_[0],R=_[1],$=_[2];E.unmap();let F=P+(R<<8)+($<<16);return F>0&&F<=a.length?F-1:-1}finally{S?o.pickBusy=!1:vt(()=>E.destroy())}}willRenderScene(e){if(!qt)return!1;let t=e;if(t.xrSessionActive||xc(t,!0)!=="webgpu")return!1;if(this.states.get(e)?.ctx)return!0;let r=t.canvas??t.gl?.canvas;return!!(r&&typeof document<"u"&&typeof r.parentElement?.insertBefore=="function")}hideLayer(e){let t=this.states.get(e);t&&t.canvas&&t.visible&&(t.canvas.style&&(t.canvas.style.display="none"),t.visible=!1)}clearViewerScene(e){let t=this.states.get(e);t&&(t.gen++,ko(t.scene),t.scene=null,t.lastShadowDigest=0,this.hideLayer(e))}disposeViewer(e){let t=this.states.get(e);t&&(t.gen++,this.trackedViewers.delete(e),this.states.delete(e),t.unhookSnapshot?.(),t.unhookSnapshot=null,ko(t.scene),t.scene=null,mc(t),Yu(t),hc(t),vt(()=>t.ctx?.unconfigure?.()),vt(()=>t.canvas?.remove?.()),t.ctx=null,t.canvas=null,t.dev=null,t.visible=!1)}onDeviceLost(e){let t=yc.get(e);if(t){for(let r of t.ownedTextures)vt(()=>r.destroy());t.ownedTextures.clear(),yc.delete(e)}for(let r of this.trackedViewers){let i=this.states.get(r);i&&i.dev===e&&(i.gen++,ko(i.scene),i.scene=null,mc(i),Yu(i),hc(i),i.dev=null,i.configuredFormat="")}}};function Ro(){return pc||(pc=new Zi),pc}var wc={name:"three-live-webgpu-scene",onRegister(){let e=He();e.gpuSceneAccelerator=Ro(),e.webgpuDeviceProvider||(e.webgpuDeviceProvider=Ah),!qt&&!Zn&&!Xt&&gc()&&qr()},onElementConnected(e){let t=e;!qt&&!Zn&&!Xt&&gc()&&qr().then(r=>{r&&t?.viewer&&vt(()=>t.viewer.render?.())})},onAttributeChanged(e,t){(t==="renderer"||t==="section-plane"||t==="shadow-maps")&&e?.viewer?.render?.()},onLoadModel(e){e&&typeof e=="object"&&Ro().clearViewerScene(e)},onClearScene(e){e&&typeof e=="object"&&Ro().clearViewerScene(e)},onXRSessionEnd(e){e&&typeof e=="object"&&vt(()=>e.render?.())},onDestroy(e,t){t&&typeof t=="object"&&Ro().disposeViewer(t)}};gt(wc),kn.registerScriptRunner(so),typeof window<"u"&&(window.ThreeLiveBundle=Qu);
|